Terrain.cpp 50 KB

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