Terrain.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "DrawableEvents.h"
  25. #include "Geometry.h"
  26. #include "Image.h"
  27. #include "IndexBuffer.h"
  28. #include "Log.h"
  29. #include "Material.h"
  30. #include "Node.h"
  31. #include "Octree.h"
  32. #include "Profiler.h"
  33. #include "ResourceCache.h"
  34. #include "ResourceEvents.h"
  35. #include "Scene.h"
  36. #include "StringUtils.h"
  37. #include "Terrain.h"
  38. #include "TerrainPatch.h"
  39. #include "VertexBuffer.h"
  40. #include "DebugNew.h"
  41. namespace Urho3D
  42. {
  43. extern const char* GEOMETRY_CATEGORY;
  44. static const Vector3 DEFAULT_SPACING(1.0f, 0.25f, 1.0f);
  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. Terrain::Terrain(Context* context) :
  54. Component(context),
  55. indexBuffer_(new IndexBuffer(context)),
  56. spacing_(DEFAULT_SPACING),
  57. patchWorldOrigin_(Vector2::ZERO),
  58. patchWorldSize_(Vector2::ZERO),
  59. numVertices_(IntVector2::ZERO),
  60. numPatches_(IntVector2::ZERO),
  61. patchSize_(DEFAULT_PATCH_SIZE),
  62. numLodLevels_(1),
  63. smoothing_(false),
  64. visible_(true),
  65. castShadows_(false),
  66. occluder_(false),
  67. occludee_(true),
  68. viewMask_(DEFAULT_VIEWMASK),
  69. lightMask_(DEFAULT_LIGHTMASK),
  70. shadowMask_(DEFAULT_SHADOWMASK),
  71. zoneMask_(DEFAULT_ZONEMASK),
  72. drawDistance_(0.0f),
  73. shadowDistance_(0.0f),
  74. lodBias_(1.0f),
  75. maxLights_(0),
  76. recreateTerrain_(false)
  77. {
  78. indexBuffer_->SetShadowed(true);
  79. }
  80. Terrain::~Terrain()
  81. {
  82. }
  83. void Terrain::RegisterObject(Context* context)
  84. {
  85. context->RegisterFactory<Terrain>(GEOMETRY_CATEGORY);
  86. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE(Terrain, VAR_RESOURCEREF, "Height Map", GetHeightMapAttr, SetHeightMapAttr, ResourceRef, ResourceRef(Image::GetTypeStatic()), AM_DEFAULT);
  88. ACCESSOR_ATTRIBUTE(Terrain, VAR_RESOURCEREF, "Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  89. ATTRIBUTE(Terrain, VAR_VECTOR3, "Vertex Spacing", spacing_, DEFAULT_SPACING, AM_DEFAULT);
  90. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Patch Size", GetPatchSize, SetPatchSizeAttr, int, DEFAULT_PATCH_SIZE, AM_DEFAULT);
  91. ATTRIBUTE(Terrain, VAR_BOOL, "Smooth Height Map", smoothing_, false, AM_DEFAULT);
  92. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Is Occluder", IsOccluder, SetOccluder, bool, false, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  94. ACCESSOR_ATTRIBUTE(Terrain, VAR_BOOL, "Cast Shadows", GetCastShadows, SetCastShadows, bool, false, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE(Terrain, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  96. ACCESSOR_ATTRIBUTE(Terrain, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  97. ACCESSOR_ATTRIBUTE(Terrain, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  98. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Max Lights", GetMaxLights, SetMaxLights, unsigned, 0, AM_DEFAULT);
  99. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "View Mask", GetViewMask, SetViewMask, unsigned, DEFAULT_VIEWMASK, AM_DEFAULT);
  100. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Light Mask", GetLightMask, SetLightMask, unsigned, DEFAULT_LIGHTMASK, AM_DEFAULT);
  101. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Shadow Mask", GetShadowMask, SetShadowMask, unsigned, DEFAULT_SHADOWMASK, AM_DEFAULT);
  102. ACCESSOR_ATTRIBUTE(Terrain, VAR_INT, "Zone Mask", GetZoneMask, SetZoneMask, unsigned, DEFAULT_ZONEMASK, AM_DEFAULT);
  103. }
  104. void Terrain::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  105. {
  106. Component::OnSetAttribute(attr, src);
  107. // Change of any non-accessor attribute requires recreation of the terrain
  108. if (!attr.accessor_)
  109. recreateTerrain_ = true;
  110. }
  111. void Terrain::ApplyAttributes()
  112. {
  113. if (recreateTerrain_)
  114. CreateGeometry();
  115. }
  116. void Terrain::OnSetEnabled()
  117. {
  118. bool enabled = IsEnabledEffective();
  119. for (unsigned i = 0; i < patches_.Size(); ++i)
  120. {
  121. if (patches_[i])
  122. patches_[i]->SetEnabled(enabled);
  123. }
  124. }
  125. void Terrain::SetPatchSize(int size)
  126. {
  127. if (size < MIN_PATCH_SIZE || size > MAX_PATCH_SIZE || !IsPowerOfTwo(size))
  128. return;
  129. if (size != patchSize_)
  130. {
  131. patchSize_ = size;
  132. CreateGeometry();
  133. MarkNetworkUpdate();
  134. }
  135. }
  136. void Terrain::SetSpacing(const Vector3& spacing)
  137. {
  138. if (spacing != spacing_)
  139. {
  140. spacing_ = spacing;
  141. CreateGeometry();
  142. MarkNetworkUpdate();
  143. }
  144. }
  145. void Terrain::SetSmoothing(bool enable)
  146. {
  147. if (enable != smoothing_)
  148. {
  149. smoothing_ = enable;
  150. CreateGeometry();
  151. MarkNetworkUpdate();
  152. }
  153. }
  154. bool Terrain::SetHeightMap(Image* image)
  155. {
  156. bool success = SetHeightMapInternal(image, true);
  157. MarkNetworkUpdate();
  158. return success;
  159. }
  160. void Terrain::SetMaterial(Material* material)
  161. {
  162. material_ = material;
  163. for (unsigned i = 0; i < patches_.Size(); ++i)
  164. {
  165. if (patches_[i])
  166. patches_[i]->SetMaterial(material);
  167. }
  168. MarkNetworkUpdate();
  169. }
  170. void Terrain::SetDrawDistance(float distance)
  171. {
  172. drawDistance_ = distance;
  173. for (unsigned i = 0; i < patches_.Size(); ++i)
  174. {
  175. if (patches_[i])
  176. patches_[i]->SetDrawDistance(distance);
  177. }
  178. MarkNetworkUpdate();
  179. }
  180. void Terrain::SetShadowDistance(float distance)
  181. {
  182. shadowDistance_ = distance;
  183. for (unsigned i = 0; i < patches_.Size(); ++i)
  184. {
  185. if (patches_[i])
  186. patches_[i]->SetShadowDistance(distance);
  187. }
  188. MarkNetworkUpdate();
  189. }
  190. void Terrain::SetLodBias(float bias)
  191. {
  192. lodBias_ = bias;
  193. for (unsigned i = 0; i < patches_.Size(); ++i)
  194. {
  195. if (patches_[i])
  196. patches_[i]->SetLodBias(bias);
  197. }
  198. MarkNetworkUpdate();
  199. }
  200. void Terrain::SetViewMask(unsigned mask)
  201. {
  202. viewMask_ = mask;
  203. for (unsigned i = 0; i < patches_.Size(); ++i)
  204. {
  205. if (patches_[i])
  206. patches_[i]->SetViewMask(mask);
  207. }
  208. MarkNetworkUpdate();
  209. }
  210. void Terrain::SetLightMask(unsigned mask)
  211. {
  212. lightMask_ = mask;
  213. for (unsigned i = 0; i < patches_.Size(); ++i)
  214. {
  215. if (patches_[i])
  216. patches_[i]->SetLightMask(mask);
  217. }
  218. MarkNetworkUpdate();
  219. }
  220. void Terrain::SetShadowMask(unsigned mask)
  221. {
  222. shadowMask_ = mask;
  223. for (unsigned i = 0; i < patches_.Size(); ++i)
  224. {
  225. if (patches_[i])
  226. patches_[i]->SetShadowMask(mask);
  227. }
  228. MarkNetworkUpdate();
  229. }
  230. void Terrain::SetZoneMask(unsigned mask)
  231. {
  232. zoneMask_ = mask;
  233. for (unsigned i = 0; i < patches_.Size(); ++i)
  234. {
  235. if (patches_[i])
  236. patches_[i]->SetZoneMask(mask);
  237. }
  238. MarkNetworkUpdate();
  239. }
  240. void Terrain::SetMaxLights(unsigned num)
  241. {
  242. maxLights_ = num;
  243. for (unsigned i = 0; i < patches_.Size(); ++i)
  244. {
  245. if (patches_[i])
  246. patches_[i]->SetMaxLights(num);
  247. }
  248. MarkNetworkUpdate();
  249. }
  250. void Terrain::SetCastShadows(bool enable)
  251. {
  252. castShadows_ = enable;
  253. for (unsigned i = 0; i < patches_.Size(); ++i)
  254. {
  255. if (patches_[i])
  256. patches_[i]->SetCastShadows(enable);
  257. }
  258. MarkNetworkUpdate();
  259. }
  260. void Terrain::SetOccluder(bool enable)
  261. {
  262. occluder_ = enable;
  263. for (unsigned i = 0; i < patches_.Size(); ++i)
  264. {
  265. if (patches_[i])
  266. patches_[i]->SetOccluder(enable);
  267. }
  268. MarkNetworkUpdate();
  269. }
  270. void Terrain::SetOccludee(bool enable)
  271. {
  272. occludee_ = enable;
  273. for (unsigned i = 0; i < patches_.Size(); ++i)
  274. {
  275. if (patches_[i])
  276. patches_[i]->SetOccludee(enable);
  277. }
  278. MarkNetworkUpdate();
  279. }
  280. Image* Terrain::GetHeightMap() const
  281. {
  282. return heightMap_;
  283. }
  284. Material* Terrain::GetMaterial() const
  285. {
  286. return material_;
  287. }
  288. TerrainPatch* Terrain::GetPatch(unsigned index) const
  289. {
  290. return index < patches_.Size() ? patches_[index] : (TerrainPatch*)0;
  291. }
  292. TerrainPatch* Terrain::GetPatch(int x, int z) const
  293. {
  294. if (x < 0 || x >= numPatches_.x_ || z < 0 || z >= numPatches_.y_)
  295. return 0;
  296. else
  297. return GetPatch(z * numPatches_.x_ + x);
  298. }
  299. float Terrain::GetHeight(const Vector3& worldPosition) const
  300. {
  301. if (node_)
  302. {
  303. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  304. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  305. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  306. float xFrac = xPos - floorf(xPos);
  307. float zFrac = zPos - floorf(zPos);
  308. float h1, h2, h3;
  309. if (xFrac + zFrac >= 1.0f)
  310. {
  311. h1 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos + 1);
  312. h2 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  313. h3 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  314. xFrac = 1.0f - xFrac;
  315. zFrac = 1.0f - zFrac;
  316. }
  317. else
  318. {
  319. h1 = GetRawHeight((unsigned)xPos, (unsigned)zPos);
  320. h2 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  321. h3 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  322. }
  323. float h = h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  324. /// \todo This assumes that the terrain scene node is upright
  325. return node_->GetWorldScale().y_ * h + node_->GetWorldPosition().y_;
  326. }
  327. else
  328. return 0.0f;
  329. }
  330. Vector3 Terrain::GetNormal(const Vector3& worldPosition) const
  331. {
  332. if (node_)
  333. {
  334. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  335. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  336. float zPos = (position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  337. float xFrac = xPos - floorf(xPos);
  338. float zFrac = zPos - floorf(zPos);
  339. Vector3 n1, n2, n3;
  340. if (xFrac + zFrac >= 1.0f)
  341. {
  342. n1 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos + 1);
  343. n2 = GetRawNormal((unsigned)xPos, (unsigned)zPos + 1);
  344. n3 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos);
  345. xFrac = 1.0f - xFrac;
  346. zFrac = 1.0f - zFrac;
  347. }
  348. else
  349. {
  350. n1 = GetRawNormal((unsigned)xPos, (unsigned)zPos);
  351. n2 = GetRawNormal((unsigned)xPos + 1, (unsigned)zPos);
  352. n3 = GetRawNormal((unsigned)xPos, (unsigned)zPos + 1);
  353. }
  354. Vector3 n = (n1 * (1.0f - xFrac - zFrac) + n2 * xFrac + n3 * zFrac).Normalized();
  355. return node_->GetWorldRotation() * n;
  356. }
  357. else
  358. return Vector3::UP;
  359. }
  360. void Terrain::CreatePatchGeometry(TerrainPatch* patch)
  361. {
  362. PROFILE(CreatePatchGeometry);
  363. unsigned row = patchSize_ + 1;
  364. VertexBuffer* vertexBuffer = patch->GetVertexBuffer();
  365. Geometry* geometry = patch->GetGeometry();
  366. Geometry* maxLodGeometry = patch->GetMaxLodGeometry();
  367. Geometry* minLodGeometry = patch->GetMinLodGeometry();
  368. if (vertexBuffer->GetVertexCount() != row * row)
  369. vertexBuffer->SetSize(row * row, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  370. SharedArrayPtr<unsigned char> cpuVertexData(new unsigned char[row * row * sizeof(Vector3)]);
  371. float* vertexData = (float*)vertexBuffer->Lock(0, vertexBuffer->GetVertexCount());
  372. float* positionData = (float*)cpuVertexData.Get();
  373. BoundingBox box;
  374. if (vertexData)
  375. {
  376. const IntVector2& coords = patch->GetCoordinates();
  377. for (int z1 = 0; z1 <= patchSize_; ++z1)
  378. {
  379. for (int x1 = 0; x1 <= patchSize_; ++x1)
  380. {
  381. int xPos = coords.x_ * patchSize_ + x1;
  382. int zPos = coords.y_ * patchSize_ + z1;
  383. // Position
  384. Vector3 position((float)x1 * spacing_.x_, GetRawHeight(xPos, zPos), (float)z1 * spacing_.z_);
  385. *vertexData++ = position.x_;
  386. *vertexData++ = position.y_;
  387. *vertexData++ = position.z_;
  388. *positionData++ = position.x_;
  389. *positionData++ = position.y_;
  390. *positionData++ = position.z_;
  391. box.Merge(position);
  392. // Normal
  393. Vector3 normal = GetRawNormal(xPos, zPos);
  394. *vertexData++ = normal.x_;
  395. *vertexData++ = normal.y_;
  396. *vertexData++ = normal.z_;
  397. // Texture coordinate
  398. Vector2 texCoord((float)xPos / (float)numVertices_.x_, 1.0f - (float)zPos / (float)numVertices_.y_);
  399. *vertexData++ = texCoord.x_;
  400. *vertexData++ = texCoord.y_;
  401. // Tangent
  402. Vector3 xyz = (Vector3::RIGHT - normal * normal.DotProduct(Vector3::RIGHT)).Normalized();
  403. *vertexData++ = xyz.x_;
  404. *vertexData++ = xyz.y_;
  405. *vertexData++ = xyz.z_;
  406. *vertexData++ = 1.0f;
  407. }
  408. }
  409. vertexBuffer->Unlock();
  410. vertexBuffer->ClearDataLost();
  411. }
  412. patch->SetBoundingBox(box);
  413. if (drawRanges_.Size())
  414. {
  415. unsigned lastDrawRange = drawRanges_.Size() - 1;
  416. geometry->SetIndexBuffer(indexBuffer_);
  417. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_, false);
  418. geometry->SetRawVertexData(cpuVertexData, sizeof(Vector3), MASK_POSITION);
  419. maxLodGeometry->SetIndexBuffer(indexBuffer_);
  420. maxLodGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[0].first_, drawRanges_[0].second_, false);
  421. maxLodGeometry->SetRawVertexData(cpuVertexData, sizeof(Vector3), MASK_POSITION);
  422. minLodGeometry->SetIndexBuffer(indexBuffer_);
  423. minLodGeometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[lastDrawRange].first_, drawRanges_[lastDrawRange].second_, false);
  424. minLodGeometry->SetRawVertexData(cpuVertexData, sizeof(Vector3), MASK_POSITION);
  425. }
  426. // Offset the occlusion geometry by vertex spacing to reduce possibility of over-aggressive occlusion
  427. patch->SetOcclusionOffset(-0.5f * (spacing_.x_ + spacing_.z_));
  428. patch->ResetLod();
  429. }
  430. void Terrain::UpdatePatchLod(TerrainPatch* patch)
  431. {
  432. Geometry* geometry = patch->GetGeometry();
  433. // All LOD levels except the coarsest have 16 versions for stitching
  434. unsigned lodLevel = patch->GetLodLevel();
  435. unsigned drawRangeIndex = lodLevel << 4;
  436. if (lodLevel < numLodLevels_ - 1)
  437. {
  438. TerrainPatch* north = patch->GetNorthPatch();
  439. TerrainPatch* south = patch->GetSouthPatch();
  440. TerrainPatch* west = patch->GetWestPatch();
  441. TerrainPatch* east = patch->GetEastPatch();
  442. if (north && north->GetLodLevel() > lodLevel)
  443. drawRangeIndex |= STITCH_NORTH;
  444. if (south && south->GetLodLevel() > lodLevel)
  445. drawRangeIndex |= STITCH_SOUTH;
  446. if (west && west->GetLodLevel() > lodLevel)
  447. drawRangeIndex |= STITCH_WEST;
  448. if (east && east->GetLodLevel() > lodLevel)
  449. drawRangeIndex |= STITCH_EAST;
  450. }
  451. if (drawRangeIndex < drawRanges_.Size())
  452. geometry->SetDrawRange(TRIANGLE_LIST, drawRanges_[drawRangeIndex].first_, drawRanges_[drawRangeIndex].second_, false);
  453. }
  454. void Terrain::SetMaterialAttr(ResourceRef value)
  455. {
  456. ResourceCache* cache = GetSubsystem<ResourceCache>();
  457. SetMaterial(cache->GetResource<Material>(value.name_));
  458. }
  459. void Terrain::SetHeightMapAttr(ResourceRef value)
  460. {
  461. ResourceCache* cache = GetSubsystem<ResourceCache>();
  462. Image* image = cache->GetResource<Image>(value.name_);
  463. SetHeightMapInternal(image, false);
  464. }
  465. void Terrain::SetPatchSizeAttr(int value)
  466. {
  467. if (value < MIN_PATCH_SIZE || value > MAX_PATCH_SIZE || !IsPowerOfTwo(value))
  468. return;
  469. if (value != patchSize_)
  470. {
  471. patchSize_ = value;
  472. recreateTerrain_ = true;
  473. }
  474. }
  475. ResourceRef Terrain::GetMaterialAttr() const
  476. {
  477. return GetResourceRef(material_, Material::GetTypeStatic());
  478. }
  479. ResourceRef Terrain::GetHeightMapAttr() const
  480. {
  481. return GetResourceRef(heightMap_, Image::GetTypeStatic());
  482. }
  483. void Terrain::CreateGeometry()
  484. {
  485. recreateTerrain_ = false;
  486. if (!node_)
  487. return;
  488. PROFILE(CreateTerrainGeometry);
  489. unsigned prevNumPatches = patches_.Size();
  490. // Determine number of LOD levels
  491. unsigned lodSize = patchSize_;
  492. numLodLevels_ = 1;
  493. while (lodSize > MIN_PATCH_SIZE && numLodLevels_ < MAX_LOD_LEVELS)
  494. {
  495. lodSize >>= 1;
  496. ++numLodLevels_;
  497. }
  498. // Determine total terrain size
  499. patchWorldSize_ = Vector2(spacing_.x_ * (float)patchSize_, spacing_.z_ * (float)patchSize_);
  500. if (heightMap_)
  501. {
  502. numPatches_ = IntVector2((heightMap_->GetWidth() - 1) / patchSize_, (heightMap_->GetHeight() - 1) / patchSize_);
  503. numVertices_ = IntVector2(numPatches_.x_ * patchSize_ + 1, numPatches_.y_ * patchSize_ + 1);
  504. patchWorldOrigin_ = Vector2(-0.5f * (float)numPatches_.x_ * patchWorldSize_.x_, -0.5f * (float)numPatches_.y_ *
  505. patchWorldSize_.y_);
  506. heightData_ = new float[numVertices_.x_ * numVertices_.y_];
  507. }
  508. else
  509. {
  510. numPatches_ = IntVector2::ZERO;
  511. numVertices_ = IntVector2::ZERO;
  512. patchWorldOrigin_ = Vector2::ZERO;
  513. heightData_.Reset();
  514. }
  515. // Remove old patch nodes which are not needed
  516. PODVector<Node*> oldPatchNodes;
  517. node_->GetChildrenWithComponent<TerrainPatch>(oldPatchNodes);
  518. for (PODVector<Node*>::Iterator i = oldPatchNodes.Begin(); i != oldPatchNodes.End(); ++i)
  519. {
  520. bool nodeOk = false;
  521. Vector<String> coords = (*i)->GetName().Substring(6).Split('_');
  522. if (coords.Size() == 2)
  523. {
  524. int x = ToInt(coords[0]);
  525. int z = ToInt(coords[1]);
  526. if (x < numPatches_.x_ && z < numPatches_.y_)
  527. nodeOk = true;
  528. }
  529. if (!nodeOk)
  530. node_->RemoveChild(*i);
  531. }
  532. patches_.Clear();
  533. if (heightMap_)
  534. {
  535. // Copy heightmap data
  536. const unsigned char* src = heightMap_->GetData();
  537. float* dest = heightData_;
  538. unsigned imgComps = heightMap_->GetComponents();
  539. unsigned imgRow = heightMap_->GetWidth() * imgComps;
  540. if (imgComps == 1)
  541. {
  542. for (int z = 0; z < numVertices_.y_; ++z)
  543. {
  544. for (int x = 0; x < numVertices_.x_; ++x)
  545. *dest++ = (float)src[imgRow * (numVertices_.y_ - 1 - z) + x] * spacing_.y_;
  546. }
  547. }
  548. else
  549. {
  550. // If more than 1 component, use the green channel for more accuracy
  551. for (int z = 0; z < numVertices_.y_; ++z)
  552. {
  553. for (int x = 0; x < numVertices_.x_; ++x)
  554. *dest++ = ((float)src[imgRow * (numVertices_.y_ - 1 - z) + imgComps * x] + (float)src[imgRow *
  555. (numVertices_.y_ - 1 - z) + imgComps * x + 1] / 256.0f) * spacing_.y_;
  556. }
  557. }
  558. if (smoothing_)
  559. SmoothHeightMap();
  560. patches_.Reserve(numPatches_.x_ * numPatches_.y_);
  561. bool enabled = IsEnabledEffective();
  562. // Create patches and set node transforms
  563. for (int z = 0; z < numPatches_.y_; ++z)
  564. {
  565. for (int x = 0; x < numPatches_.x_; ++x)
  566. {
  567. String nodeName = "Patch_" + String(x) + "_" + String(z);
  568. Node* patchNode = node_->GetChild(nodeName);
  569. if (!patchNode)
  570. {
  571. // Create the patch scene node as local and temporary so that it is not unnecessarily serialized to either
  572. // file or replicated over the network
  573. patchNode = node_->CreateChild(nodeName, LOCAL);
  574. patchNode->SetTemporary(true);
  575. }
  576. patchNode->SetPosition(Vector3(patchWorldOrigin_.x_ + (float)x * patchWorldSize_.x_, 0.0f, patchWorldOrigin_.y_ +
  577. (float)z * patchWorldSize_.y_));
  578. TerrainPatch* patch = patchNode->GetOrCreateComponent<TerrainPatch>();
  579. patch->SetOwner(this);
  580. patch->SetCoordinates(IntVector2(x, z));
  581. // Copy initial drawable parameters
  582. patch->SetEnabled(enabled);
  583. patch->SetMaterial(material_);
  584. patch->SetDrawDistance(drawDistance_);
  585. patch->SetShadowDistance(shadowDistance_);
  586. patch->SetLodBias(lodBias_);
  587. patch->SetViewMask(viewMask_);
  588. patch->SetLightMask(lightMask_);
  589. patch->SetShadowMask(shadowMask_);
  590. patch->SetZoneMask(zoneMask_);
  591. patch->SetMaxLights(maxLights_);
  592. patch->SetCastShadows(castShadows_);
  593. patch->SetOccluder(occluder_);
  594. patch->SetOccludee(occludee_);
  595. patches_.Push(WeakPtr<TerrainPatch>(patch));
  596. }
  597. }
  598. // Create the shared index data
  599. CreateIndexData();
  600. // Create vertex data for patches
  601. for (Vector<WeakPtr<TerrainPatch> >::Iterator i = patches_.Begin(); i != patches_.End(); ++i)
  602. {
  603. CreatePatchGeometry(*i);
  604. CalculateLodErrors(*i);
  605. SetNeighbors(*i);
  606. }
  607. }
  608. // Send event only if new geometry was generated, or the old was cleared
  609. if (patches_.Size() || prevNumPatches)
  610. {
  611. using namespace TerrainCreated;
  612. VariantMap eventData;
  613. eventData[P_NODE] = (void*)node_;
  614. node_->SendEvent(E_TERRAINCREATED, eventData);
  615. }
  616. }
  617. void Terrain::SmoothHeightMap()
  618. {
  619. PROFILE(SmoothHeightMap);
  620. SharedArrayPtr<float> newHeightData(new float[numVertices_.x_* numVertices_.y_]);
  621. for (int z = 0; z < numVertices_.y_; ++z)
  622. {
  623. for (int x = 0; x < numVertices_.x_; ++x)
  624. {
  625. float smoothedHeight = (
  626. GetRawHeight(x - 1, z - 1) + GetRawHeight(x, z - 1) * 2.0f + GetRawHeight(x + 1, z - 1) +
  627. GetRawHeight(x - 1, z) * 2.0f + GetRawHeight(x, z) * 4.0f + GetRawHeight(x + 1, z) * 2.0f +
  628. GetRawHeight(x - 1, z + 1) + GetRawHeight(x, z + 1) * 2.0f + GetRawHeight(x + 1, z + 1)
  629. ) / 16.0f;
  630. newHeightData[z * numVertices_.x_ + x] = smoothedHeight;
  631. }
  632. }
  633. heightData_ = newHeightData;
  634. }
  635. void Terrain::CreateIndexData()
  636. {
  637. PROFILE(CreateIndexData);
  638. PODVector<unsigned short> indices;
  639. drawRanges_.Clear();
  640. unsigned row = patchSize_ + 1;
  641. for (unsigned i = 0; i < numLodLevels_; ++i)
  642. {
  643. unsigned combinations = (i < numLodLevels_ - 1) ? 16 : 1;
  644. int skip = 1 << i;
  645. for (unsigned j = 0; j < combinations; ++j)
  646. {
  647. unsigned indexStart = indices.Size();
  648. int zStart = 0;
  649. int xStart = 0;
  650. int zEnd = patchSize_;
  651. int xEnd = patchSize_;
  652. if (j & STITCH_NORTH)
  653. zEnd -= skip;
  654. if (j & STITCH_SOUTH)
  655. zStart += skip;
  656. if (j & STITCH_WEST)
  657. xStart += skip;
  658. if (j & STITCH_EAST)
  659. xEnd -= skip;
  660. // Build the main grid
  661. for (int z = zStart; z < zEnd; z += skip)
  662. {
  663. for (int x = xStart; x < xEnd; x += skip)
  664. {
  665. indices.Push((z + skip) * row + x);
  666. indices.Push(z * row + x + skip);
  667. indices.Push(z * row + x);
  668. indices.Push((z + skip) * row + x);
  669. indices.Push((z + skip) * row + x + skip);
  670. indices.Push(z * row + x + skip);
  671. }
  672. }
  673. // Build the north edge
  674. if (j & STITCH_NORTH)
  675. {
  676. int z = patchSize_ - skip;
  677. for (int x = 0; x < patchSize_; x += skip * 2)
  678. {
  679. if (x > 0 || (j & STITCH_WEST) == 0)
  680. {
  681. indices.Push((z + skip) * row + x);
  682. indices.Push(z * row + x + skip);
  683. indices.Push(z * row + x);
  684. }
  685. indices.Push((z + skip) * row + x);
  686. indices.Push((z + skip) * row + x + 2 * skip);
  687. indices.Push(z * row + x + skip);
  688. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  689. {
  690. indices.Push((z + skip) * row + x + 2 * skip);
  691. indices.Push(z * row + x + 2 * skip);
  692. indices.Push(z * row + x + skip);
  693. }
  694. }
  695. }
  696. // Build the south edge
  697. if (j & STITCH_SOUTH)
  698. {
  699. int z = 0;
  700. for (int x = 0; x < patchSize_; x += skip * 2)
  701. {
  702. if (x > 0 || (j & STITCH_WEST) == 0)
  703. {
  704. indices.Push((z + skip) * row + x);
  705. indices.Push((z + skip) * row + x + skip);
  706. indices.Push(z * row + x);
  707. }
  708. indices.Push(z * row + x);
  709. indices.Push((z + skip) * row + x + skip);
  710. indices.Push(z * row + x + 2 * skip);
  711. if (x < patchSize_ - skip * 2 || (j & STITCH_EAST) == 0)
  712. {
  713. indices.Push((z + skip) * row + x + skip);
  714. indices.Push((z + skip) * row + x + 2 * skip);
  715. indices.Push(z * row + x + 2 * skip);
  716. }
  717. }
  718. }
  719. // Build the west edge
  720. if (j & STITCH_WEST)
  721. {
  722. int x = 0;
  723. for (int z = 0; z < patchSize_; z += skip * 2)
  724. {
  725. if (z > 0 || (j & STITCH_SOUTH) == 0)
  726. {
  727. indices.Push(z * row + x);
  728. indices.Push((z + skip) * row + x + skip);
  729. indices.Push(z * row + x + skip);
  730. }
  731. indices.Push((z + 2 * skip) * row + x);
  732. indices.Push((z + skip) * row + x + skip);
  733. indices.Push(z * row + x);
  734. if (x < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  735. {
  736. indices.Push((z + 2 * skip) * row + x);
  737. indices.Push((z + 2 * skip) * row + x + skip);
  738. indices.Push((z + skip) * row + x + skip);
  739. }
  740. }
  741. }
  742. // Build the east edge
  743. if (j & STITCH_EAST)
  744. {
  745. int x = patchSize_ - skip;
  746. for (int z = 0; z < patchSize_; z += skip * 2)
  747. {
  748. if (z > 0 || (j & STITCH_SOUTH) == 0)
  749. {
  750. indices.Push(z * row + x);
  751. indices.Push((z + skip) * row + x);
  752. indices.Push(z * row + x + skip);
  753. }
  754. indices.Push((z + skip) * row + x);
  755. indices.Push((z + 2 * skip) * row + x + skip);
  756. indices.Push(z * row + x + skip);
  757. if (z < patchSize_ - skip * 2 || (j & STITCH_NORTH) == 0)
  758. {
  759. indices.Push((z + skip) * row + x);
  760. indices.Push((z + 2 * skip) * row + x);
  761. indices.Push((z + 2 * skip) * row + x + skip);
  762. }
  763. }
  764. }
  765. drawRanges_.Push(MakePair(indexStart, indices.Size() - indexStart));
  766. }
  767. }
  768. indexBuffer_->SetSize(indices.Size(), false);
  769. unsigned short* indexData = (unsigned short*)indexBuffer_->Lock(0, indices.Size());
  770. if (indexData)
  771. {
  772. memcpy(indexData, &indices[0], indices.Size() * sizeof(unsigned short));
  773. indexBuffer_->Unlock();
  774. }
  775. }
  776. float Terrain::GetRawHeight(int x, int z) const
  777. {
  778. if (!heightData_)
  779. return 0.0f;
  780. x = Clamp(x, 0, numVertices_.x_ - 1);
  781. z = Clamp(z, 0, numVertices_.y_ - 1);
  782. return heightData_[z * numVertices_.x_ + x];
  783. }
  784. float Terrain::GetLodHeight(int x, int z, unsigned lodLevel) const
  785. {
  786. unsigned offset = 1 << lodLevel;
  787. float divisor = (float)offset;
  788. float xFrac = (float)(x % offset) / divisor;
  789. float zFrac = (float)(z % offset) / divisor;
  790. float h1, h2, h3;
  791. if (xFrac + zFrac >= 1.0f)
  792. {
  793. h1 = GetRawHeight(x + offset, z + offset);
  794. h2 = GetRawHeight(x, z + offset);
  795. h3 = GetRawHeight(x + offset, z);
  796. xFrac = 1.0f - xFrac;
  797. zFrac = 1.0f - zFrac;
  798. }
  799. else
  800. {
  801. h1 = GetRawHeight(x, z);
  802. h2 = GetRawHeight(x + offset, z);
  803. h3 = GetRawHeight(x, z + offset);
  804. }
  805. return h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  806. }
  807. Vector3 Terrain::GetRawNormal(int x, int z) const
  808. {
  809. float baseHeight = GetRawHeight(x, z);
  810. float nSlope = GetRawHeight(x, z - 1) - baseHeight;
  811. float neSlope = GetRawHeight(x + 1, z - 1) - baseHeight;
  812. float eSlope = GetRawHeight(x + 1, z) - baseHeight;
  813. float seSlope = GetRawHeight(x + 1, z + 1) - baseHeight;
  814. float sSlope = GetRawHeight(x, z + 1) - baseHeight;
  815. float swSlope = GetRawHeight(x - 1, z + 1) - baseHeight;
  816. float wSlope = GetRawHeight(x - 1, z) - baseHeight;
  817. float nwSlope = GetRawHeight(x - 1, z - 1) - baseHeight;
  818. float up = 0.5f * (spacing_.x_ + spacing_.z_);
  819. return (Vector3(0.0f, up, nSlope) +
  820. Vector3(-neSlope, up, neSlope) +
  821. Vector3(-eSlope, up, 0.0f) +
  822. Vector3(-seSlope, up, -seSlope) +
  823. Vector3(0.0f, up, -sSlope) +
  824. Vector3(swSlope, up, -swSlope) +
  825. Vector3(wSlope, up, 0.0f) +
  826. Vector3(nwSlope, up, nwSlope)).Normalized();
  827. }
  828. void Terrain::CalculateLodErrors(TerrainPatch* patch)
  829. {
  830. PROFILE(CalculateLodErrors);
  831. const IntVector2& coords = patch->GetCoordinates();
  832. PODVector<float>& lodErrors = patch->GetLodErrors();
  833. lodErrors.Clear();
  834. lodErrors.Reserve(numLodLevels_);
  835. int xStart = coords.x_ * patchSize_;
  836. int zStart = coords.y_ * patchSize_;
  837. int xEnd = xStart + patchSize_;
  838. int zEnd = zStart + patchSize_;
  839. for (unsigned i = 0; i < numLodLevels_; ++i)
  840. {
  841. float maxError = 0.0f;
  842. int divisor = 1 << i;
  843. if (i > 0)
  844. {
  845. for (int z = zStart; z <= zEnd; ++z)
  846. {
  847. for (int x = xStart; x <= xEnd; ++x)
  848. {
  849. if (x % divisor || z % divisor)
  850. {
  851. float error = Abs(GetLodHeight(x, z, i) - GetRawHeight(x, z));
  852. maxError = Max(error, maxError);
  853. }
  854. }
  855. }
  856. // Set error to be at least same as (half vertex spacing x LOD) to prevent horizontal stretches getting too inaccurate
  857. maxError = Max(maxError, 0.25f * (spacing_.x_ + spacing_.z_) * (float)(1 << i));
  858. }
  859. lodErrors.Push(maxError);
  860. }
  861. }
  862. void Terrain::SetNeighbors(TerrainPatch* patch)
  863. {
  864. const IntVector2& coords = patch->GetCoordinates();
  865. patch->SetNeighbors(GetPatch(coords.x_, coords.y_ + 1), GetPatch(coords.x_, coords.y_ - 1),
  866. GetPatch(coords.x_ - 1, coords.y_), GetPatch(coords.x_ + 1, coords.y_));
  867. }
  868. bool Terrain::SetHeightMapInternal(Image* image, bool recreateNow)
  869. {
  870. if (image && image->IsCompressed())
  871. {
  872. LOGERROR("Can not use a compressed image as a terrain heightmap");
  873. return false;
  874. }
  875. // Unsubscribe from the reload event of previous image (if any), then subscribe to the new
  876. if (heightMap_)
  877. UnsubscribeFromEvent(heightMap_, E_RELOADFINISHED);
  878. if (image)
  879. SubscribeToEvent(image, E_RELOADFINISHED, HANDLER(Terrain, HandleHeightMapReloadFinished));
  880. heightMap_ = image;
  881. if (recreateNow)
  882. CreateGeometry();
  883. else
  884. recreateTerrain_ = true;
  885. return true;
  886. }
  887. void Terrain::HandleHeightMapReloadFinished(StringHash eventType, VariantMap& eventData)
  888. {
  889. CreateGeometry();
  890. }
  891. }