Terrain.cpp 34 KB

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