Terrain.cpp 47 KB

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