Terrain.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DrawableEvents.h"
  26. #include "../Graphics/Geometry.h"
  27. #include "../Graphics/IndexBuffer.h"
  28. #include "../Graphics/Material.h"
  29. #include "../Graphics/Octree.h"
  30. #include "../Graphics/Terrain.h"
  31. #include "../Graphics/TerrainPatch.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/Log.h"
  34. #include "../Resource/Image.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../Scene/Node.h"
  38. #include "../Scene/Scene.h"
  39. #include "../DebugNew.h"
  40. namespace Urho3D
  41. {
  42. extern const char* GEOMETRY_CATEGORY;
  43. static const Vector3 DEFAULT_SPACING(1.0f, 0.25f, 1.0f);
  44. static const unsigned MIN_LOD_LEVELS = 1;
  45. static const unsigned MAX_LOD_LEVELS = 4;
  46. static const int DEFAULT_PATCH_SIZE = 32;
  47. static const int MIN_PATCH_SIZE = 4;
  48. static const int MAX_PATCH_SIZE = 128;
  49. static const unsigned STITCH_NORTH = 1;
  50. static const unsigned STITCH_SOUTH = 2;
  51. static const unsigned STITCH_WEST = 4;
  52. static const unsigned STITCH_EAST = 8;
  53. inline void GrowUpdateRegion(IntRect& updateRegion, int x, int y)
  54. {
  55. if (updateRegion.left_ < 0)
  56. {
  57. updateRegion.left_ = updateRegion.right_ = x;
  58. updateRegion.top_ = updateRegion.bottom_ = y;
  59. }
  60. else
  61. {
  62. if (x < updateRegion.left_)
  63. updateRegion.left_ = x;
  64. if (x > updateRegion.right_)
  65. updateRegion.right_ = x;
  66. if (y < updateRegion.top_)
  67. updateRegion.top_ = y;
  68. if (y > updateRegion.bottom_)
  69. updateRegion.bottom_ = y;
  70. }
  71. }
  72. Terrain::Terrain(Context* context) :
  73. Component(context),
  74. indexBuffer_(new IndexBuffer(context)),
  75. spacing_(DEFAULT_SPACING),
  76. lastSpacing_(Vector3::ZERO),
  77. patchWorldOrigin_(Vector2::ZERO),
  78. patchWorldSize_(Vector2::ZERO),
  79. numVertices_(IntVector2::ZERO),
  80. lastNumVertices_(IntVector2::ZERO),
  81. numPatches_(IntVector2::ZERO),
  82. patchSize_(DEFAULT_PATCH_SIZE),
  83. lastPatchSize_(0),
  84. numLodLevels_(1),
  85. maxLodLevels_(MAX_LOD_LEVELS),
  86. occlusionLodLevel_(M_MAX_UNSIGNED),
  87. smoothing_(false),
  88. visible_(true),
  89. castShadows_(false),
  90. occluder_(false),
  91. occludee_(true),
  92. viewMask_(DEFAULT_VIEWMASK),
  93. lightMask_(DEFAULT_LIGHTMASK),
  94. shadowMask_(DEFAULT_SHADOWMASK),
  95. zoneMask_(DEFAULT_ZONEMASK),
  96. drawDistance_(0.0f),
  97. shadowDistance_(0.0f),
  98. lodBias_(1.0f),
  99. maxLights_(0),
  100. northID_(0),
  101. southID_(0),
  102. westID_(0),
  103. eastID_(0),
  104. recreateTerrain_(false),
  105. neighborsDirty_(false)
  106. {
  107. indexBuffer_->SetShadowed(true);
  108. }
  109. Terrain::~Terrain()
  110. {
  111. }
  112. void Terrain::RegisterObject(Context* context)
  113. {
  114. context->RegisterFactory<Terrain>(GEOMETRY_CATEGORY);
  115. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  116. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Height Map", GetHeightMapAttr, SetHeightMapAttr, ResourceRef, ResourceRef(Image::GetTypeStatic()),
  117. AM_DEFAULT);
  118. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  119. AM_DEFAULT);
  120. URHO3D_ATTRIBUTE_EX("North Neighbor NodeID", unsigned, northID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  121. URHO3D_ATTRIBUTE_EX("South Neighbor NodeID", unsigned, southID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  122. URHO3D_ATTRIBUTE_EX("West Neighbor NodeID", unsigned, westID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  123. URHO3D_ATTRIBUTE_EX("East Neighbor NodeID", unsigned, eastID_, MarkNeighborsDirty, 0, AM_DEFAULT | AM_NODEID);
  124. URHO3D_ATTRIBUTE_EX("Vertex Spacing", Vector3, spacing_, MarkTerrainDirty, DEFAULT_SPACING, AM_DEFAULT);
  125. URHO3D_ACCESSOR_ATTRIBUTE("Patch Size", GetPatchSize, SetPatchSizeAttr, int, DEFAULT_PATCH_SIZE, AM_DEFAULT);
  126. URHO3D_ACCESSOR_ATTRIBUTE("Max LOD Levels", GetMaxLodLevels, SetMaxLodLevelsAttr, unsigned, MAX_LOD_LEVELS, AM_DEFAULT);
  127. URHO3D_ATTRIBUTE_EX("Smooth Height Map", bool, smoothing_, MarkTerrainDirty, false, AM_DEFAULT);
  128. URHO3D_ACCESSOR_ATTRIBUTE("Is Occluder", IsOccluder, SetOccluder, bool, false, AM_DEFAULT);
  129. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  130. URHO3D_ACCESSOR_ATTRIBUTE("Cast Shadows", GetCastShadows, SetCastShadows, bool, false, AM_DEFAULT);
  131. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  132. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  133. URHO3D_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  134. URHO3D_ACCESSOR_ATTRIBUTE("Max Lights", GetMaxLights, SetMaxLights, unsigned, 0, AM_DEFAULT);
  135. URHO3D_ACCESSOR_ATTRIBUTE("View Mask", GetViewMask, SetViewMask, unsigned, DEFAULT_VIEWMASK, AM_DEFAULT);
  136. URHO3D_ACCESSOR_ATTRIBUTE("Light Mask", GetLightMask, SetLightMask, unsigned, DEFAULT_LIGHTMASK, AM_DEFAULT);
  137. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Mask", GetShadowMask, SetShadowMask, unsigned, DEFAULT_SHADOWMASK, AM_DEFAULT);
  138. URHO3D_ACCESSOR_ATTRIBUTE("Zone Mask", GetZoneMask, SetZoneMask, unsigned, DEFAULT_ZONEMASK, AM_DEFAULT);
  139. URHO3D_ACCESSOR_ATTRIBUTE("Occlusion LOD level", GetOcclusionLodLevel, SetOcclusionLodLevelAttr, unsigned, M_MAX_UNSIGNED, AM_DEFAULT);
  140. }
  141. void Terrain::ApplyAttributes()
  142. {
  143. if (recreateTerrain_)
  144. CreateGeometry();
  145. if (neighborsDirty_)
  146. {
  147. Scene* scene = GetScene();
  148. Node* north = scene ? scene->GetNode(northID_) : nullptr;
  149. Node* south = scene ? scene->GetNode(southID_) : nullptr;
  150. Node* west = scene ? scene->GetNode(westID_) : nullptr;
  151. Node* east = scene ? scene->GetNode(eastID_) : nullptr;
  152. Terrain* northTerrain = north ? north->GetComponent<Terrain>() : nullptr;
  153. Terrain* southTerrain = south ? south->GetComponent<Terrain>() : nullptr;
  154. Terrain* westTerrain = west ? west->GetComponent<Terrain>() : nullptr;
  155. Terrain* eastTerrain = east ? east->GetComponent<Terrain>() : nullptr;
  156. SetNeighbors(northTerrain, southTerrain, westTerrain, eastTerrain);
  157. neighborsDirty_ = false;
  158. }
  159. }
  160. void Terrain::OnSetEnabled()
  161. {
  162. bool enabled = IsEnabledEffective();
  163. for (unsigned i = 0; i < patches_.Size(); ++i)
  164. {
  165. if (patches_[i])
  166. patches_[i]->SetEnabled(enabled);
  167. }
  168. }
  169. void Terrain::SetPatchSize(int size)
  170. {
  171. if (size < MIN_PATCH_SIZE || size > MAX_PATCH_SIZE || !IsPowerOfTwo((unsigned)size))
  172. return;
  173. if (size != patchSize_)
  174. {
  175. patchSize_ = size;
  176. CreateGeometry();
  177. MarkNetworkUpdate();
  178. }
  179. }
  180. void Terrain::SetSpacing(const Vector3& spacing)
  181. {
  182. if (spacing != spacing_)
  183. {
  184. spacing_ = spacing;
  185. CreateGeometry();
  186. MarkNetworkUpdate();
  187. }
  188. }
  189. void Terrain::SetMaxLodLevels(unsigned levels)
  190. {
  191. levels = Clamp(levels, MIN_LOD_LEVELS, MAX_LOD_LEVELS);
  192. if (levels != maxLodLevels_)
  193. {
  194. maxLodLevels_ = levels;
  195. lastPatchSize_ = 0; // Force full recreate
  196. CreateGeometry();
  197. MarkNetworkUpdate();
  198. }
  199. }
  200. void Terrain::SetOcclusionLodLevel(unsigned level)
  201. {
  202. if (level != occlusionLodLevel_)
  203. {
  204. occlusionLodLevel_ = level;
  205. lastPatchSize_ = 0; // Force full recreate
  206. CreateGeometry();
  207. MarkNetworkUpdate();
  208. }
  209. }
  210. void Terrain::SetSmoothing(bool enable)
  211. {
  212. if (enable != smoothing_)
  213. {
  214. smoothing_ = enable;
  215. CreateGeometry();
  216. MarkNetworkUpdate();
  217. }
  218. }
  219. bool Terrain::SetHeightMap(Image* image)
  220. {
  221. bool success = SetHeightMapInternal(image, true);
  222. MarkNetworkUpdate();
  223. return success;
  224. }
  225. void Terrain::SetMaterial(Material* material)
  226. {
  227. material_ = material;
  228. for (unsigned i = 0; i < patches_.Size(); ++i)
  229. {
  230. if (patches_[i])
  231. patches_[i]->SetMaterial(material);
  232. }
  233. MarkNetworkUpdate();
  234. }
  235. void Terrain::SetNorthNeighbor(Terrain* north)
  236. {
  237. if (north == north_)
  238. return;
  239. if (north_ && north_->GetNode())
  240. UnsubscribeFromEvent(north_->GetNode(), E_TERRAINCREATED);
  241. north_ = north;
  242. if (north_ && north_->GetNode())
  243. {
  244. northID_ = north_->GetNode()->GetID();
  245. SubscribeToEvent(north_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  246. }
  247. UpdateEdgePatchNeighbors();
  248. MarkNetworkUpdate();
  249. }
  250. void Terrain::SetSouthNeighbor(Terrain* south)
  251. {
  252. if (south == south_)
  253. return;
  254. if (south_ && south_->GetNode())
  255. UnsubscribeFromEvent(south_->GetNode(), E_TERRAINCREATED);
  256. south_ = south;
  257. if (south_ && south_->GetNode())
  258. {
  259. southID_ = south_->GetNode()->GetID();
  260. SubscribeToEvent(south_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  261. }
  262. UpdateEdgePatchNeighbors();
  263. MarkNetworkUpdate();
  264. }
  265. void Terrain::SetWestNeighbor(Terrain* west)
  266. {
  267. if (west == west_)
  268. return;
  269. if (west_ && west_->GetNode())
  270. UnsubscribeFromEvent(west_->GetNode(), E_TERRAINCREATED);
  271. west_ = west;
  272. if (west_ && west_->GetNode())
  273. {
  274. westID_ = west_->GetNode()->GetID();
  275. SubscribeToEvent(west_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  276. }
  277. UpdateEdgePatchNeighbors();
  278. MarkNetworkUpdate();
  279. }
  280. void Terrain::SetEastNeighbor(Terrain* east)
  281. {
  282. if (east == east_)
  283. return;
  284. if (east_ && east_->GetNode())
  285. UnsubscribeFromEvent(east_->GetNode(), E_TERRAINCREATED);
  286. east_ = east;
  287. if (east_ && east_->GetNode())
  288. {
  289. eastID_ = east_->GetNode()->GetID();
  290. SubscribeToEvent(east_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  291. }
  292. UpdateEdgePatchNeighbors();
  293. MarkNetworkUpdate();
  294. }
  295. void Terrain::SetNeighbors(Terrain* north, Terrain* south, Terrain* west, Terrain* east)
  296. {
  297. if (north_ && north_->GetNode())
  298. UnsubscribeFromEvent(north_->GetNode(), E_TERRAINCREATED);
  299. if (south_ && south_->GetNode())
  300. UnsubscribeFromEvent(south_->GetNode(), E_TERRAINCREATED);
  301. if (west_ && west_->GetNode())
  302. UnsubscribeFromEvent(west_->GetNode(), E_TERRAINCREATED);
  303. if (east_ && east_->GetNode())
  304. UnsubscribeFromEvent(east_->GetNode(), E_TERRAINCREATED);
  305. north_ = north;
  306. if (north_ && north_->GetNode())
  307. {
  308. northID_ = north_->GetNode()->GetID();
  309. SubscribeToEvent(north_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  310. }
  311. south_ = south;
  312. if (south_ && south_->GetNode())
  313. {
  314. southID_ = south_->GetNode()->GetID();
  315. SubscribeToEvent(south_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  316. }
  317. west_ = west;
  318. if (west_ && west_->GetNode())
  319. {
  320. westID_ = west_->GetNode()->GetID();
  321. SubscribeToEvent(west_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  322. }
  323. east_ = east;
  324. if (east_ && east_->GetNode())
  325. {
  326. eastID_ = east_->GetNode()->GetID();
  327. SubscribeToEvent(east_->GetNode(), E_TERRAINCREATED, URHO3D_HANDLER(Terrain, HandleNeighborTerrainCreated));
  328. }
  329. UpdateEdgePatchNeighbors();
  330. MarkNetworkUpdate();
  331. }
  332. void Terrain::SetDrawDistance(float distance)
  333. {
  334. drawDistance_ = distance;
  335. for (unsigned i = 0; i < patches_.Size(); ++i)
  336. {
  337. if (patches_[i])
  338. patches_[i]->SetDrawDistance(distance);
  339. }
  340. MarkNetworkUpdate();
  341. }
  342. void Terrain::SetShadowDistance(float distance)
  343. {
  344. shadowDistance_ = distance;
  345. for (unsigned i = 0; i < patches_.Size(); ++i)
  346. {
  347. if (patches_[i])
  348. patches_[i]->SetShadowDistance(distance);
  349. }
  350. MarkNetworkUpdate();
  351. }
  352. void Terrain::SetLodBias(float bias)
  353. {
  354. lodBias_ = bias;
  355. for (unsigned i = 0; i < patches_.Size(); ++i)
  356. {
  357. if (patches_[i])
  358. patches_[i]->SetLodBias(bias);
  359. }
  360. MarkNetworkUpdate();
  361. }
  362. void Terrain::SetViewMask(unsigned mask)
  363. {
  364. viewMask_ = mask;
  365. for (unsigned i = 0; i < patches_.Size(); ++i)
  366. {
  367. if (patches_[i])
  368. patches_[i]->SetViewMask(mask);
  369. }
  370. MarkNetworkUpdate();
  371. }
  372. void Terrain::SetLightMask(unsigned mask)
  373. {
  374. lightMask_ = mask;
  375. for (unsigned i = 0; i < patches_.Size(); ++i)
  376. {
  377. if (patches_[i])
  378. patches_[i]->SetLightMask(mask);
  379. }
  380. MarkNetworkUpdate();
  381. }
  382. void Terrain::SetShadowMask(unsigned mask)
  383. {
  384. shadowMask_ = mask;
  385. for (unsigned i = 0; i < patches_.Size(); ++i)
  386. {
  387. if (patches_[i])
  388. patches_[i]->SetShadowMask(mask);
  389. }
  390. MarkNetworkUpdate();
  391. }
  392. void Terrain::SetZoneMask(unsigned mask)
  393. {
  394. zoneMask_ = mask;
  395. for (unsigned i = 0; i < patches_.Size(); ++i)
  396. {
  397. if (patches_[i])
  398. patches_[i]->SetZoneMask(mask);
  399. }
  400. MarkNetworkUpdate();
  401. }
  402. void Terrain::SetMaxLights(unsigned num)
  403. {
  404. maxLights_ = num;
  405. for (unsigned i = 0; i < patches_.Size(); ++i)
  406. {
  407. if (patches_[i])
  408. patches_[i]->SetMaxLights(num);
  409. }
  410. MarkNetworkUpdate();
  411. }
  412. void Terrain::SetCastShadows(bool enable)
  413. {
  414. castShadows_ = enable;
  415. for (unsigned i = 0; i < patches_.Size(); ++i)
  416. {
  417. if (patches_[i])
  418. patches_[i]->SetCastShadows(enable);
  419. }
  420. MarkNetworkUpdate();
  421. }
  422. void Terrain::SetOccluder(bool enable)
  423. {
  424. occluder_ = enable;
  425. for (unsigned i = 0; i < patches_.Size(); ++i)
  426. {
  427. if (patches_[i])
  428. patches_[i]->SetOccluder(enable);
  429. }
  430. MarkNetworkUpdate();
  431. }
  432. void Terrain::SetOccludee(bool enable)
  433. {
  434. occludee_ = enable;
  435. for (unsigned i = 0; i < patches_.Size(); ++i)
  436. {
  437. if (patches_[i])
  438. patches_[i]->SetOccludee(enable);
  439. }
  440. MarkNetworkUpdate();
  441. }
  442. void Terrain::ApplyHeightMap()
  443. {
  444. if (heightMap_)
  445. CreateGeometry();
  446. }
  447. Image* Terrain::GetHeightMap() const
  448. {
  449. return heightMap_;
  450. }
  451. Material* Terrain::GetMaterial() const
  452. {
  453. return material_;
  454. }
  455. TerrainPatch* Terrain::GetPatch(unsigned index) const
  456. {
  457. return index < patches_.Size() ? patches_[index] : nullptr;
  458. }
  459. TerrainPatch* Terrain::GetPatch(int x, int z) const
  460. {
  461. if (x < 0 || x >= numPatches_.x_ || z < 0 || z >= numPatches_.y_)
  462. return nullptr;
  463. else
  464. return GetPatch((unsigned)(z * numPatches_.x_ + x));
  465. }
  466. TerrainPatch* Terrain::GetNeighborPatch(int x, int z) const
  467. {
  468. if (z >= numPatches_.y_ && north_)
  469. return north_->GetPatch(x, z - numPatches_.y_);
  470. else if (z < 0 && south_)
  471. return south_->GetPatch(x, z + south_->GetNumPatches().y_);
  472. else if (x < 0 && west_)
  473. return west_->GetPatch(x + west_->GetNumPatches().x_, z);
  474. else if (x >= numPatches_.x_ && east_)
  475. return east_->GetPatch(x - numPatches_.x_, z);
  476. else
  477. return GetPatch(x, z);
  478. }
  479. float Terrain::GetHeight(const Vector3& worldPosition) const
  480. {
  481. if (node_)
  482. {
  483. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  484. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  485. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  486. float xFrac = Fract(xPos);
  487. float zFrac = Fract(zPos);
  488. float h1, h2, h3;
  489. if (xFrac + zFrac >= 1.0f)
  490. {
  491. h1 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos + 1);
  492. h2 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  493. h3 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  494. xFrac = 1.0f - xFrac;
  495. zFrac = 1.0f - zFrac;
  496. }
  497. else
  498. {
  499. h1 = GetRawHeight((unsigned)xPos, (unsigned)zPos);
  500. h2 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  501. h3 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  502. }
  503. float h = h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  504. /// \todo This assumes that the terrain scene node is upright
  505. return node_->GetWorldScale().y_ * h + node_->GetWorldPosition().y_;
  506. }
  507. else
  508. return 0.0f;
  509. }
  510. Vector3 Terrain::GetNormal(const Vector3& worldPosition) const
  511. {
  512. if (node_)
  513. {
  514. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  515. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  516. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  517. float xFrac = Fract(xPos);
  518. float zFrac = Fract(zPos);
  519. Vector3 n1, n2, n3;
  520. if (xFrac + zFrac >= 1.0f)
  521. {
  522. n1 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos + 1);
  523. n2 = GetRawNormal((unsigned)xPos, (unsigned)zPos + 1);
  524. n3 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos);
  525. xFrac = 1.0f - xFrac;
  526. zFrac = 1.0f - zFrac;
  527. }
  528. else
  529. {
  530. n1 = GetRawNormal((unsigned)xPos, (unsigned)zPos);
  531. n2 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos);
  532. n3 = GetRawNormal((unsigned)xPos, (unsigned)zPos + 1);
  533. }
  534. Vector3 n = (n1 * (1.0f - xFrac - zFrac) + n2 * xFrac + n3 * zFrac).Normalized();
  535. return node_->GetWorldRotation() * n;
  536. }
  537. else
  538. return Vector3::UP;
  539. }
  540. IntVector2 Terrain::WorldToHeightMap(const Vector3& worldPosition) const
  541. {
  542. if (!node_)
  543. return IntVector2::ZERO;
  544. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  545. int xPos = (int)((position.x_ - patchWorldOrigin_.x_) / spacing_.x_ + 0.5f);
  546. int zPos = (int)((position.z_ - patchWorldOrigin_.y_) / spacing_.z_ + 0.5f);
  547. xPos = Clamp(xPos, 0, numVertices_.x_ - 1);
  548. zPos = Clamp(zPos, 0, numVertices_.y_ - 1);
  549. return IntVector2(xPos, numVertices_.y_ - 1 - zPos);
  550. }
  551. Vector3 Terrain::HeightMapToWorld(const IntVector2& pixelPosition) const
  552. {
  553. if (!node_)
  554. return Vector3::ZERO;
  555. IntVector2 pos(pixelPosition.x_, numVertices_.y_ - 1 - pixelPosition.y_);
  556. float xPos = (float)(pos.x_ * spacing_.x_ + patchWorldOrigin_.x_);
  557. float zPos = (float)(pos.y_ * spacing_.z_ + patchWorldOrigin_.y_);
  558. Vector3 lPos(xPos, 0.0f, zPos);
  559. Vector3 wPos = node_->GetWorldTransform() * lPos;
  560. wPos.y_ = GetHeight(wPos);
  561. return wPos;
  562. }
  563. void Terrain::CreatePatchGeometry(TerrainPatch* patch)
  564. {
  565. URHO3D_PROFILE(CreatePatchGeometry);
  566. unsigned row = (unsigned)(patchSize_ + 1);
  567. VertexBuffer* vertexBuffer = patch->GetVertexBuffer();
  568. Geometry* geometry = patch->GetGeometry();
  569. Geometry* maxLodGeometry = patch->GetMaxLodGeometry();
  570. Geometry* occlusionGeometry = patch->GetOcclusionGeometry();
  571. if (vertexBuffer->GetVertexCount() != row * row)
  572. vertexBuffer->SetSize(row * row, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  573. SharedArrayPtr<unsigned char> cpuVertexData(new unsigned char[row * row * sizeof(Vector3)]);
  574. SharedArrayPtr<unsigned char> occlusionCpuVertexData(new unsigned char[row * row * sizeof(Vector3)]);
  575. float* vertexData = (float*)vertexBuffer->Lock(0, vertexBuffer->GetVertexCount());
  576. float* positionData = (float*)cpuVertexData.Get();
  577. float* occlusionData = (float*)occlusionCpuVertexData.Get();
  578. BoundingBox box;
  579. unsigned occlusionLevel = occlusionLodLevel_;
  580. if (occlusionLevel > numLodLevels_ - 1)
  581. occlusionLevel = numLodLevels_ - 1;
  582. if (vertexData)
  583. {
  584. const IntVector2& coords = patch->GetCoordinates();
  585. int lodExpand = (1 << (occlusionLevel)) - 1;
  586. int halfLodExpand = (1 << (occlusionLevel)) / 2;
  587. for (int z = 0; z <= patchSize_; ++z)
  588. {
  589. for (int x = 0; x <= patchSize_; ++x)
  590. {
  591. int xPos = coords.x_ * patchSize_ + x;
  592. int zPos = coords.y_ * patchSize_ + z;
  593. // Position
  594. Vector3 position((float)x * spacing_.x_, GetRawHeight(xPos, zPos), (float)z * spacing_.z_);
  595. *vertexData++ = position.x_;
  596. *vertexData++ = position.y_;
  597. *vertexData++ = position.z_;
  598. *positionData++ = position.x_;
  599. *positionData++ = position.y_;
  600. *positionData++ = position.z_;
  601. box.Merge(position);
  602. // For vertices that are part of the occlusion LOD, calculate the minimum height in the neighborhood
  603. // to prevent false positive occlusion due to inaccuracy between occlusion LOD & visible LOD
  604. float minHeight = position.y_;
  605. if (halfLodExpand > 0 && (x & lodExpand) == 0 && (z & lodExpand) == 0)
  606. {
  607. int minX = Max(xPos - halfLodExpand, 0);
  608. int maxX = Min(xPos + halfLodExpand, numVertices_.x_ - 1);
  609. int minZ = Max(zPos - halfLodExpand, 0);
  610. int maxZ = Min(zPos + halfLodExpand, numVertices_.y_ - 1);
  611. for (int nZ = minZ; nZ <= maxZ; ++nZ)
  612. {
  613. for (int nX = minX; nX <= maxX; ++nX)
  614. minHeight = Min(minHeight, GetRawHeight(nX, nZ));
  615. }
  616. }
  617. *occlusionData++ = position.x_;
  618. *occlusionData++ = minHeight;
  619. *occlusionData++ = position.z_;
  620. // Normal
  621. Vector3 normal = GetRawNormal(xPos, zPos);
  622. *vertexData++ = normal.x_;
  623. *vertexData++ = normal.y_;
  624. *vertexData++ = normal.z_;
  625. // Texture coordinate
  626. Vector2 texCoord((float)xPos / (float)(numVertices_.x_ - 1), 1.0f - (float)zPos / (float)(numVertices_.y_ - 1));
  627. *vertexData++ = texCoord.x_;
  628. *vertexData++ = texCoord.y_;
  629. // Tangent
  630. Vector3 xyz = (Vector3::RIGHT - normal * normal.DotProduct(Vector3::RIGHT)).Normalized();
  631. *vertexData++ = xyz.x_;
  632. *vertexData++ = xyz.y_;
  633. *vertexData++ = xyz.z_;
  634. *vertexData++ = 1.0f;
  635. }
  636. }
  637. vertexBuffer->Unlock();
  638. vertexBuffer->ClearDataLost();
  639. }
  640. patch->SetBoundingBox(box);
  641. if (drawRanges_.Size())
  642. {
  643. unsigned occlusionDrawRange = occlusionLevel << 4;
  644. geometry->SetIndexBuffer(indexBuffer_);
  645. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_, false);
  646. geometry->SetRawVertexData(cpuVertexData, MASK_POSITION);
  647. maxLodGeometry->SetIndexBuffer(indexBuffer_);
  648. maxLodGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_, false);
  649. maxLodGeometry->SetRawVertexData(cpuVertexData, MASK_POSITION);
  650. occlusionGeometry->SetIndexBuffer(indexBuffer_);
  651. occlusionGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[occlusionDrawRange].first_, drawRanges_[occlusionDrawRange].second_, false);
  652. occlusionGeometry->SetRawVertexData(occlusionCpuVertexData, MASK_POSITION);
  653. }
  654. patch->ResetLod();
  655. }
  656. void Terrain::UpdatePatchLod(TerrainPatch* patch)
  657. {
  658. Geometry* geometry = patch->GetGeometry();
  659. // All LOD levels except the coarsest have 16 versions for stitching
  660. unsigned lodLevel = patch->GetLodLevel();
  661. unsigned drawRangeIndex = lodLevel << 4;
  662. if (lodLevel < numLodLevels_ - 1)
  663. {
  664. TerrainPatch* north = patch->GetNorthPatch();
  665. TerrainPatch* south = patch->GetSouthPatch();
  666. TerrainPatch* west = patch->GetWestPatch();
  667. TerrainPatch* east = patch->GetEastPatch();
  668. if (north && north->GetLodLevel() > lodLevel)
  669. drawRangeIndex |= STITCH_NORTH;
  670. if (south && south->GetLodLevel() > lodLevel)
  671. drawRangeIndex |= STITCH_SOUTH;
  672. if (west && west->GetLodLevel() > lodLevel)
  673. drawRangeIndex |= STITCH_WEST;
  674. if (east && east->GetLodLevel() > lodLevel)
  675. drawRangeIndex |= STITCH_EAST;
  676. }
  677. if (drawRangeIndex < drawRanges_.Size())
  678. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[drawRangeIndex].first_, drawRanges_[drawRangeIndex].second_, false);
  679. }
  680. void Terrain::SetMaterialAttr(const ResourceRef& value)
  681. {
  682. ResourceCache* cache = GetSubsystem<ResourceCache>();
  683. SetMaterial(cache->GetResource<Material>(value.name_));
  684. }
  685. void Terrain::SetHeightMapAttr(const ResourceRef& value)
  686. {
  687. ResourceCache* cache = GetSubsystem<ResourceCache>();
  688. Image* image = cache->GetResource<Image>(value.name_);
  689. SetHeightMapInternal(image, false);
  690. }
  691. void Terrain::SetPatchSizeAttr(int value)
  692. {
  693. if (value < MIN_PATCH_SIZE || value > MAX_PATCH_SIZE || !IsPowerOfTwo((unsigned)value))
  694. return;
  695. if (value != patchSize_)
  696. {
  697. patchSize_ = value;
  698. recreateTerrain_ = true;
  699. }
  700. }
  701. void Terrain::SetMaxLodLevelsAttr(unsigned value)
  702. {
  703. value = Clamp(value, MIN_LOD_LEVELS, MAX_LOD_LEVELS);
  704. if (value != maxLodLevels_)
  705. {
  706. maxLodLevels_ = value;
  707. lastPatchSize_ = 0; // Force full recreate
  708. recreateTerrain_ = true;
  709. }
  710. }
  711. void Terrain::SetOcclusionLodLevelAttr(unsigned value)
  712. {
  713. if (value != occlusionLodLevel_)
  714. {
  715. occlusionLodLevel_ = value;
  716. lastPatchSize_ = 0; // Force full recreate
  717. recreateTerrain_ = true;
  718. }
  719. }
  720. ResourceRef Terrain::GetMaterialAttr() const
  721. {
  722. return GetResourceRef(material_, Material::GetTypeStatic());
  723. }
  724. ResourceRef Terrain::GetHeightMapAttr() const
  725. {
  726. return GetResourceRef(heightMap_, Image::GetTypeStatic());
  727. }
  728. void Terrain::CreateGeometry()
  729. {
  730. recreateTerrain_ = false;
  731. if (!node_)
  732. return;
  733. URHO3D_PROFILE(CreateTerrainGeometry);
  734. unsigned prevNumPatches = patches_.Size();
  735. // Determine number of LOD levels
  736. unsigned lodSize = (unsigned)patchSize_;
  737. numLodLevels_ = 1;
  738. while (lodSize > MIN_PATCH_SIZE && numLodLevels_ < maxLodLevels_)
  739. {
  740. lodSize >>= 1;
  741. ++numLodLevels_;
  742. }
  743. // Determine total terrain size
  744. patchWorldSize_ = Vector2(spacing_.x_ * (float)patchSize_, spacing_.z_ * (float)patchSize_);
  745. bool updateAll = false;
  746. if (heightMap_)
  747. {
  748. numPatches_ = IntVector2((heightMap_->GetWidth() - 1) / patchSize_, (heightMap_->GetHeight() - 1) / patchSize_);
  749. numVertices_ = IntVector2(numPatches_.x_ * patchSize_ + 1, numPatches_.y_ * patchSize_ + 1);
  750. patchWorldOrigin_ =
  751. Vector2(-0.5f * (float)numPatches_.x_ * patchWorldSize_.x_, -0.5f * (float)numPatches_.y_ * patchWorldSize_.y_);
  752. if (numVertices_ != lastNumVertices_ || lastSpacing_ != spacing_ || patchSize_ != lastPatchSize_)
  753. updateAll = true;
  754. unsigned newDataSize = (unsigned)(numVertices_.x_ * numVertices_.y_);
  755. // Create new height data if terrain size changed
  756. if (!heightData_ || updateAll)
  757. heightData_ = new float[newDataSize];
  758. // Ensure that the source (unsmoothed) data exists if smoothing is active
  759. if (smoothing_ && (!sourceHeightData_ || updateAll))
  760. {
  761. sourceHeightData_ = new float[newDataSize];
  762. updateAll = true;
  763. }
  764. else if (!smoothing_)
  765. sourceHeightData_.Reset();
  766. }
  767. else
  768. {
  769. numPatches_ = IntVector2::ZERO;
  770. numVertices_ = IntVector2::ZERO;
  771. patchWorldOrigin_ = Vector2::ZERO;
  772. heightData_.Reset();
  773. sourceHeightData_.Reset();
  774. }
  775. lastNumVertices_ = numVertices_;
  776. lastPatchSize_ = patchSize_;
  777. lastSpacing_ = spacing_;
  778. // Remove old patch nodes which are not needed
  779. if (updateAll)
  780. {
  781. URHO3D_PROFILE(RemoveOldPatches);
  782. PODVector<Node*> oldPatchNodes;
  783. node_->GetChildrenWithComponent<TerrainPatch>(oldPatchNodes);
  784. for (PODVector<Node*>::Iterator i = oldPatchNodes.Begin(); i != oldPatchNodes.End(); ++i)
  785. {
  786. bool nodeOk = false;
  787. Vector<String> coords = (*i)->GetName().Substring(6).Split('_');
  788. if (coords.Size() == 2)
  789. {
  790. int x = ToInt(coords[0]);
  791. int z = ToInt(coords[1]);
  792. if (x < numPatches_.x_ && z < numPatches_.y_)
  793. nodeOk = true;
  794. }
  795. if (!nodeOk)
  796. node_->RemoveChild(*i);
  797. }
  798. }
  799. // Keep track of which patches actually need an update
  800. PODVector<bool> dirtyPatches((unsigned)(numPatches_.x_ * numPatches_.y_));
  801. for (unsigned i = 0; i < dirtyPatches.Size(); ++i)
  802. dirtyPatches[i] = updateAll;
  803. patches_.Clear();
  804. if (heightMap_)
  805. {
  806. // Copy heightmap data
  807. const unsigned char* src = heightMap_->GetData();
  808. float* dest = smoothing_ ? sourceHeightData_ : heightData_;
  809. unsigned imgComps = heightMap_->GetComponents();
  810. unsigned imgRow = heightMap_->GetWidth() * imgComps;
  811. IntRect updateRegion(-1, -1, -1, -1);
  812. if (imgComps == 1)
  813. {
  814. URHO3D_PROFILE(CopyHeightData);
  815. for (int z = 0; z < numVertices_.y_; ++z)
  816. {
  817. for (int x = 0; x < numVertices_.x_; ++x)
  818. {
  819. float newHeight = (float)src[imgRow * (numVertices_.y_ - 1 - z) + x] * spacing_.y_;
  820. if (updateAll)
  821. *dest = newHeight;
  822. else
  823. {
  824. if (*dest != newHeight)
  825. {
  826. *dest = newHeight;
  827. GrowUpdateRegion(updateRegion, x, z);
  828. }
  829. }
  830. ++dest;
  831. }
  832. }
  833. }
  834. else
  835. {
  836. URHO3D_PROFILE(CopyHeightData);
  837. // If more than 1 component, use the green channel for more accuracy
  838. for (int z = 0; z < numVertices_.y_; ++z)
  839. {
  840. for (int x = 0; x < numVertices_.x_; ++x)
  841. {
  842. float newHeight = ((float)src[imgRow * (numVertices_.y_ - 1 - z) + imgComps * x] +
  843. (float)src[imgRow * (numVertices_.y_ - 1 - z) + imgComps * x + 1] / 256.0f) * spacing_.y_;
  844. if (updateAll)
  845. *dest = newHeight;
  846. else
  847. {
  848. if (*dest != newHeight)
  849. {
  850. *dest = newHeight;
  851. GrowUpdateRegion(updateRegion, x, z);
  852. }
  853. }
  854. ++dest;
  855. }
  856. }
  857. }
  858. // If updating a region of the heightmap, check which patches change
  859. if (!updateAll)
  860. {
  861. int lodExpand = 1 << (numLodLevels_ - 1);
  862. // Expand the right & bottom 1 pixel more, as patches share vertices at the edge
  863. updateRegion.left_ -= lodExpand;
  864. updateRegion.right_ += lodExpand + 1;
  865. updateRegion.top_ -= lodExpand;
  866. updateRegion.bottom_ += lodExpand + 1;
  867. int sX = Max(updateRegion.left_ / patchSize_, 0);
  868. int eX = Min(updateRegion.right_ / patchSize_, numPatches_.x_ - 1);
  869. int sY = Max(updateRegion.top_ / patchSize_, 0);
  870. int eY = Min(updateRegion.bottom_ / patchSize_, numPatches_.y_ - 1);
  871. for (int y = sY; y <= eY; ++y)
  872. {
  873. for (int x = sX; x <= eX; ++x)
  874. dirtyPatches[y * numPatches_.x_ + x] = true;
  875. }
  876. }
  877. patches_.Reserve((unsigned)(numPatches_.x_ * numPatches_.y_));
  878. bool enabled = IsEnabledEffective();
  879. {
  880. URHO3D_PROFILE(CreatePatches);
  881. // Create patches and set node transforms
  882. for (int z = 0; z < numPatches_.y_; ++z)
  883. {
  884. for (int x = 0; x < numPatches_.x_; ++x)
  885. {
  886. String nodeName = "Patch_" + String(x) + "_" + String(z);
  887. Node* patchNode = node_->GetChild(nodeName);
  888. if (!patchNode)
  889. {
  890. // Create the patch scene node as local and temporary so that it is not unnecessarily serialized to either
  891. // file or replicated over the network
  892. patchNode = node_->CreateTemporaryChild(nodeName, LOCAL);
  893. }
  894. patchNode->SetPosition(Vector3(patchWorldOrigin_.x_ + (float)x * patchWorldSize_.x_, 0.0f,
  895. patchWorldOrigin_.y_ + (float)z * patchWorldSize_.y_));
  896. TerrainPatch* patch = patchNode->GetComponent<TerrainPatch>();
  897. if (!patch)
  898. {
  899. patch = patchNode->CreateComponent<TerrainPatch>();
  900. patch->SetOwner(this);
  901. patch->SetCoordinates(IntVector2(x, z));
  902. // Copy initial drawable parameters
  903. patch->SetEnabled(enabled);
  904. patch->SetMaterial(material_);
  905. patch->SetDrawDistance(drawDistance_);
  906. patch->SetShadowDistance(shadowDistance_);
  907. patch->SetLodBias(lodBias_);
  908. patch->SetViewMask(viewMask_);
  909. patch->SetLightMask(lightMask_);
  910. patch->SetShadowMask(shadowMask_);
  911. patch->SetZoneMask(zoneMask_);
  912. patch->SetMaxLights(maxLights_);
  913. patch->SetCastShadows(castShadows_);
  914. patch->SetOccluder(occluder_);
  915. patch->SetOccludee(occludee_);
  916. }
  917. patches_.Push(WeakPtr<TerrainPatch>(patch));
  918. }
  919. }
  920. }
  921. // Create the shared index data
  922. if (updateAll)
  923. CreateIndexData();
  924. // Create vertex data for patches. First update smoothing to ensure normals are calculated correctly across patch borders
  925. if (smoothing_)
  926. {
  927. URHO3D_PROFILE(UpdateSmoothing);
  928. for (unsigned i = 0; i < patches_.Size(); ++i)
  929. {
  930. if (dirtyPatches[i])
  931. {
  932. TerrainPatch* patch = patches_[i];
  933. const IntVector2& coords = patch->GetCoordinates();
  934. int startX = coords.x_ * patchSize_;
  935. int endX = startX + patchSize_;
  936. int startZ = coords.y_ * patchSize_;
  937. int endZ = startZ + patchSize_;
  938. for (int z = startZ; z <= endZ; ++z)
  939. {
  940. for (int x = startX; x <= endX; ++x)
  941. {
  942. float smoothedHeight = (
  943. GetSourceHeight(x - 1, z - 1) + GetSourceHeight(x, z - 1) * 2.0f + GetSourceHeight(x + 1, z - 1) +
  944. GetSourceHeight(x - 1, z) * 2.0f + GetSourceHeight(x, z) * 4.0f + GetSourceHeight(x + 1, z) * 2.0f +
  945. GetSourceHeight(x - 1, z + 1) + GetSourceHeight(x, z + 1) * 2.0f + GetSourceHeight(x + 1, z + 1)
  946. ) / 16.0f;
  947. heightData_[z * numVertices_.x_ + x] = smoothedHeight;
  948. }
  949. }
  950. }
  951. }
  952. }
  953. for (unsigned i = 0; i < patches_.Size(); ++i)
  954. {
  955. TerrainPatch* patch = patches_[i];
  956. if (dirtyPatches[i])
  957. {
  958. CreatePatchGeometry(patch);
  959. CalculateLodErrors(patch);
  960. }
  961. SetPatchNeighbors(patch);
  962. }
  963. }
  964. // Send event only if new geometry was generated, or the old was cleared
  965. if (patches_.Size() || prevNumPatches)
  966. {
  967. using namespace TerrainCreated;
  968. VariantMap& eventData = GetEventDataMap();
  969. eventData[P_NODE] = node_;
  970. node_->SendEvent(E_TERRAINCREATED, eventData);
  971. }
  972. }
  973. void Terrain::CreateIndexData()
  974. {
  975. URHO3D_PROFILE(CreateIndexData);
  976. PODVector<unsigned short> indices;
  977. drawRanges_.Clear();
  978. unsigned row = (unsigned)(patchSize_ + 1);
  979. /* Build index data for each LOD level. Each LOD level except the lowest can stitch to the next lower LOD from the edges:
  980. north, south, west, east, or any combination of them, requiring 16 different versions of each LOD level's index data
  981. Normal edge: Stitched edge:
  982. +----+----+ +---------+
  983. |\ |\ | |\ /|
  984. | \ | \ | | \ / |
  985. | \ | \ | | \ / |
  986. | \| \| | \ / |
  987. +----+----+ +----+----+
  988. */
  989. for (unsigned i = 0; i < numLodLevels_; ++i)
  990. {
  991. unsigned combinations = (i < numLodLevels_ - 1) ? 16 : 1;
  992. int skip = 1 << i;
  993. for (unsigned j = 0; j < combinations; ++j)
  994. {
  995. unsigned indexStart = indices.Size();
  996. int zStart = 0;
  997. int xStart = 0;
  998. int zEnd = patchSize_;
  999. int xEnd = patchSize_;
  1000. if (j & STITCH_NORTH)
  1001. zEnd -= skip;
  1002. if (j & STITCH_SOUTH)
  1003. zStart += skip;
  1004. if (j & STITCH_WEST)
  1005. xStart += skip;
  1006. if (j & STITCH_EAST)
  1007. xEnd -= skip;
  1008. // Build the main grid
  1009. for (int z = zStart; z < zEnd; z += skip)
  1010. {
  1011. for (int x = xStart; x < xEnd; x += skip)
  1012. {
  1013. indices.Push((unsigned short)((z + skip) * row + x));
  1014. indices.Push((unsigned short)(z * row + x + skip));
  1015. indices.Push((unsigned short)(z * row + x));
  1016. indices.Push((unsigned short)((z + skip) * row + x));
  1017. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1018. indices.Push((unsigned short)(z * row + x + skip));
  1019. }
  1020. }
  1021. // Build the north edge
  1022. if (j & STITCH_NORTH)
  1023. {
  1024. int z = patchSize_ - skip;
  1025. for (int x = 0; x < patchSize_; x += skip * 2)
  1026. {
  1027. if (x > 0 || (j & STITCH_WEST) == 0)
  1028. {
  1029. indices.Push((unsigned short)((z + skip) * row + x));
  1030. indices.Push((unsigned short)(z * row + x + skip));
  1031. indices.Push((unsigned short)(z * row + x));
  1032. }
  1033. indices.Push((unsigned short)((z + skip) * row + x));
  1034. indices.Push((unsigned short)((z + skip) * row + x + 2 * skip));
  1035. indices.Push((unsigned short)(z * row + x + skip));
  1036. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  1037. {
  1038. indices.Push((unsigned short)((z + skip) * row + x + 2 * skip));
  1039. indices.Push((unsigned short)(z * row + x + 2 * skip));
  1040. indices.Push((unsigned short)(z * row + x + skip));
  1041. }
  1042. }
  1043. }
  1044. // Build the south edge
  1045. if (j & STITCH_SOUTH)
  1046. {
  1047. int z = 0;
  1048. for (int x = 0; x < patchSize_; x += skip * 2)
  1049. {
  1050. if (x > 0 || (j & STITCH_WEST) == 0)
  1051. {
  1052. indices.Push((unsigned short)((z + skip) * row + x));
  1053. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1054. indices.Push((unsigned short)(z * row + x));
  1055. }
  1056. indices.Push((unsigned short)(z * row + x));
  1057. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1058. indices.Push((unsigned short)(z * row + x + 2 * skip));
  1059. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  1060. {
  1061. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1062. indices.Push((unsigned short)((z + skip) * row + x + 2 * skip));
  1063. indices.Push((unsigned short)(z * row + x + 2 * skip));
  1064. }
  1065. }
  1066. }
  1067. // Build the west edge
  1068. if (j & STITCH_WEST)
  1069. {
  1070. int x = 0;
  1071. for (int z = 0; z < patchSize_; z += skip * 2)
  1072. {
  1073. if (z > 0 || (j & STITCH_SOUTH) == 0)
  1074. {
  1075. indices.Push((unsigned short)(z * row + x));
  1076. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1077. indices.Push((unsigned short)(z * row + x + skip));
  1078. }
  1079. indices.Push((unsigned short)((z + 2 * skip) * row + x));
  1080. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1081. indices.Push((unsigned short)(z * row + x));
  1082. if (z < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  1083. {
  1084. indices.Push((unsigned short)((z + 2 * skip) * row + x));
  1085. indices.Push((unsigned short)((z + 2 * skip) * row + x + skip));
  1086. indices.Push((unsigned short)((z + skip) * row + x + skip));
  1087. }
  1088. }
  1089. }
  1090. // Build the east edge
  1091. if (j & STITCH_EAST)
  1092. {
  1093. int x = patchSize_ - skip;
  1094. for (int z = 0; z < patchSize_; z += skip * 2)
  1095. {
  1096. if (z > 0 || (j & STITCH_SOUTH) == 0)
  1097. {
  1098. indices.Push((unsigned short)(z * row + x));
  1099. indices.Push((unsigned short)((z + skip) * row + x));
  1100. indices.Push((unsigned short)(z * row + x + skip));
  1101. }
  1102. indices.Push((unsigned short)((z + skip) * row + x));
  1103. indices.Push((unsigned short)((z + 2 * skip) * row + x + skip));
  1104. indices.Push((unsigned short)(z * row + x + skip));
  1105. if (z < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  1106. {
  1107. indices.Push((unsigned short)((z + skip) * row + x));
  1108. indices.Push((unsigned short)((z + 2 * skip) * row + x));
  1109. indices.Push((unsigned short)((z + 2 * skip) * row + x + skip));
  1110. }
  1111. }
  1112. }
  1113. drawRanges_.Push(MakePair(indexStart, indices.Size() - indexStart));
  1114. }
  1115. }
  1116. indexBuffer_->SetSize(indices.Size(), false);
  1117. indexBuffer_->SetData(&indices[0]);
  1118. }
  1119. float Terrain::GetRawHeight(int x, int z) const
  1120. {
  1121. if (!heightData_)
  1122. return 0.0f;
  1123. x = Clamp(x, 0, numVertices_.x_ - 1);
  1124. z = Clamp(z, 0, numVertices_.y_ - 1);
  1125. return heightData_[z * numVertices_.x_ + x];
  1126. }
  1127. float Terrain::GetSourceHeight(int x, int z) const
  1128. {
  1129. if (!sourceHeightData_)
  1130. return 0.0f;
  1131. x = Clamp(x, 0, numVertices_.x_ - 1);
  1132. z = Clamp(z, 0, numVertices_.y_ - 1);
  1133. return sourceHeightData_[z * numVertices_.x_ + x];
  1134. }
  1135. float Terrain::GetLodHeight(int x, int z, unsigned lodLevel) const
  1136. {
  1137. unsigned offset = (unsigned)(1 << lodLevel);
  1138. float divisor = (float)offset;
  1139. float xFrac = (float)(x % offset) / divisor;
  1140. float zFrac = (float)(z % offset) / divisor;
  1141. float h1, h2, h3;
  1142. if (xFrac + zFrac >= 1.0f)
  1143. {
  1144. h1 = GetRawHeight(x + offset, z + offset);
  1145. h2 = GetRawHeight(x, z + offset);
  1146. h3 = GetRawHeight(x + offset, z);
  1147. xFrac = 1.0f - xFrac;
  1148. zFrac = 1.0f - zFrac;
  1149. }
  1150. else
  1151. {
  1152. h1 = GetRawHeight(x, z);
  1153. h2 = GetRawHeight(x + offset, z);
  1154. h3 = GetRawHeight(x, z + offset);
  1155. }
  1156. return h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  1157. }
  1158. Vector3 Terrain::GetRawNormal(int x, int z) const
  1159. {
  1160. float baseHeight = GetRawHeight(x, z);
  1161. float nSlope = GetRawHeight(x, z - 1) - baseHeight;
  1162. float neSlope = GetRawHeight(x + 1, z - 1) - baseHeight;
  1163. float eSlope = GetRawHeight(x + 1, z) - baseHeight;
  1164. float seSlope = GetRawHeight(x + 1, z + 1) - baseHeight;
  1165. float sSlope = GetRawHeight(x, z + 1) - baseHeight;
  1166. float swSlope = GetRawHeight(x - 1, z + 1) - baseHeight;
  1167. float wSlope = GetRawHeight(x - 1, z) - baseHeight;
  1168. float nwSlope = GetRawHeight(x - 1, z - 1) - baseHeight;
  1169. float up = 0.5f * (spacing_.x_ + spacing_.z_);
  1170. return (Vector3(0.0f, up, nSlope) +
  1171. Vector3(-neSlope, up, neSlope) +
  1172. Vector3(-eSlope, up, 0.0f) +
  1173. Vector3(-seSlope, up, -seSlope) +
  1174. Vector3(0.0f, up, -sSlope) +
  1175. Vector3(swSlope, up, -swSlope) +
  1176. Vector3(wSlope, up, 0.0f) +
  1177. Vector3(nwSlope, up, nwSlope)).Normalized();
  1178. }
  1179. void Terrain::CalculateLodErrors(TerrainPatch* patch)
  1180. {
  1181. URHO3D_PROFILE(CalculateLodErrors);
  1182. const IntVector2& coords = patch->GetCoordinates();
  1183. PODVector<float>& lodErrors = patch->GetLodErrors();
  1184. lodErrors.Clear();
  1185. lodErrors.Reserve(numLodLevels_);
  1186. int xStart = coords.x_ * patchSize_;
  1187. int zStart = coords.y_ * patchSize_;
  1188. int xEnd = xStart + patchSize_;
  1189. int zEnd = zStart + patchSize_;
  1190. for (unsigned i = 0; i < numLodLevels_; ++i)
  1191. {
  1192. float maxError = 0.0f;
  1193. int divisor = 1 << i;
  1194. if (i > 0)
  1195. {
  1196. for (int z = zStart; z <= zEnd; ++z)
  1197. {
  1198. for (int x = xStart; x <= xEnd; ++x)
  1199. {
  1200. if (x % divisor || z % divisor)
  1201. {
  1202. float error = Abs(GetLodHeight(x, z, i) - GetRawHeight(x, z));
  1203. maxError = Max(error, maxError);
  1204. }
  1205. }
  1206. }
  1207. // Set error to be at least same as (half vertex spacing x LOD) to prevent horizontal stretches getting too inaccurate
  1208. maxError = Max(maxError, 0.25f * (spacing_.x_ + spacing_.z_) * (float)(1 << i));
  1209. }
  1210. lodErrors.Push(maxError);
  1211. }
  1212. }
  1213. void Terrain::SetPatchNeighbors(TerrainPatch* patch)
  1214. {
  1215. if (!patch)
  1216. return;
  1217. const IntVector2& coords = patch->GetCoordinates();
  1218. patch->SetNeighbors(GetNeighborPatch(coords.x_, coords.y_ + 1), GetNeighborPatch(coords.x_, coords.y_ - 1),
  1219. GetNeighborPatch(coords.x_ - 1, coords.y_), GetNeighborPatch(coords.x_ + 1, coords.y_));
  1220. }
  1221. bool Terrain::SetHeightMapInternal(Image* image, bool recreateNow)
  1222. {
  1223. if (image && image->IsCompressed())
  1224. {
  1225. URHO3D_LOGERROR("Can not use a compressed image as a terrain heightmap");
  1226. return false;
  1227. }
  1228. // Unsubscribe from the reload event of previous image (if any), then subscribe to the new
  1229. if (heightMap_)
  1230. UnsubscribeFromEvent(heightMap_, E_RELOADFINISHED);
  1231. if (image)
  1232. SubscribeToEvent(image, E_RELOADFINISHED, URHO3D_HANDLER(Terrain, HandleHeightMapReloadFinished));
  1233. heightMap_ = image;
  1234. if (recreateNow)
  1235. CreateGeometry();
  1236. else
  1237. recreateTerrain_ = true;
  1238. return true;
  1239. }
  1240. void Terrain::HandleHeightMapReloadFinished(StringHash eventType, VariantMap& eventData)
  1241. {
  1242. CreateGeometry();
  1243. }
  1244. void Terrain::HandleNeighborTerrainCreated(StringHash eventType, VariantMap& eventData)
  1245. {
  1246. UpdateEdgePatchNeighbors();
  1247. }
  1248. void Terrain::UpdateEdgePatchNeighbors()
  1249. {
  1250. for (int x = 1; x < numPatches_.x_ - 1; ++x)
  1251. {
  1252. SetPatchNeighbors(GetPatch(x, 0));
  1253. SetPatchNeighbors(GetPatch(x, numPatches_.y_ - 1));
  1254. }
  1255. for (int z = 1; z < numPatches_.y_ - 1; ++z)
  1256. {
  1257. SetPatchNeighbors(GetPatch(0, z));
  1258. SetPatchNeighbors(GetPatch(numPatches_.x_ - 1, z));
  1259. }
  1260. SetPatchNeighbors(GetPatch(0, 0));
  1261. SetPatchNeighbors(GetPatch(numPatches_.x_ - 1, 0));
  1262. SetPatchNeighbors(GetPatch(0, numPatches_.y_ - 1));
  1263. SetPatchNeighbors(GetPatch(numPatches_.x_ - 1, numPatches_.y_ - 1));
  1264. }
  1265. }