Terrain.cpp 34 KB

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