Terrain.cpp 50 KB

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