Terrain.cpp 33 KB

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