Terrain.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  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 "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 "Scene.h"
  34. #include "Terrain.h"
  35. #include "TerrainPatch.h"
  36. #include "VertexBuffer.h"
  37. #include "DebugNew.h"
  38. OBJECTTYPESTATIC(Terrain);
  39. static const unsigned DEFAULT_PATCH_SIZE = 16;
  40. static const unsigned DEFAULT_LOD_LEVELS = 3;
  41. static const unsigned MAX_LOD_LEVELS = 4;
  42. static const unsigned MIN_PATCH_SIZE = 4;
  43. static const unsigned MAX_PATCH_SIZE = 128;
  44. static const Vector3 DEFAULT_SPACING(1.0f, 0.25f, 1.0f);
  45. Terrain::Terrain(Context* context) :
  46. Component(context),
  47. indexBuffer_(new IndexBuffer(context)),
  48. patchSize_(DEFAULT_PATCH_SIZE),
  49. spacing_(DEFAULT_SPACING),
  50. size_(IntVector2::ZERO),
  51. patchWorldSize_(Vector2::ZERO),
  52. patchWorldOrigin_(Vector2::ZERO),
  53. patchesX_(0),
  54. patchesZ_(0),
  55. numLodLevels_(DEFAULT_LOD_LEVELS),
  56. visible_(true),
  57. castShadows_(false),
  58. occluder_(false),
  59. occludee_(true),
  60. viewMask_(DEFAULT_VIEWMASK),
  61. lightMask_(DEFAULT_LIGHTMASK),
  62. shadowMask_(DEFAULT_SHADOWMASK),
  63. zoneMask_(DEFAULT_ZONEMASK),
  64. drawDistance_(0.0f),
  65. shadowDistance_(0.0f),
  66. lodBias_(1.0f),
  67. maxLights_(0),
  68. terrainDirty_(false)
  69. {
  70. indexBuffer_->SetShadowed(true);
  71. }
  72. Terrain::~Terrain()
  73. {
  74. }
  75. void Terrain::RegisterObject(Context* context)
  76. {
  77. context->RegisterFactory<Terrain>();
  78. }
  79. void Terrain::SetSpacing(const Vector3& spacing)
  80. {
  81. if (spacing != spacing_)
  82. {
  83. spacing_ = spacing;
  84. CreateGeometry();
  85. MarkNetworkUpdate();
  86. }
  87. }
  88. void Terrain::SetPatchSize(unsigned size)
  89. {
  90. size = Clamp((int)size, (int)MIN_PATCH_SIZE, (int)MAX_PATCH_SIZE);
  91. if (size != patchSize_ && IsPowerOfTwo(size))
  92. {
  93. patchSize_ = size;
  94. unsigned lodSize = size;
  95. numLodLevels_ = 1;
  96. while (lodSize > MIN_PATCH_SIZE && numLodLevels_ < MAX_LOD_LEVELS)
  97. {
  98. lodSize >>= 1;
  99. ++numLodLevels_;
  100. }
  101. CreateGeometry();
  102. MarkNetworkUpdate();
  103. }
  104. }
  105. bool Terrain::SetHeightMap(Image* image)
  106. {
  107. if (!image)
  108. return false;
  109. if (image->IsCompressed())
  110. {
  111. LOGERROR("Can not use a compressed image as a terrain heightmap");
  112. return false;
  113. }
  114. heightMap_ = image;
  115. CreateGeometry();
  116. MarkNetworkUpdate();
  117. return true;
  118. }
  119. void Terrain::SetMaterial(Material* material)
  120. {
  121. material_ = material;
  122. for (unsigned i = 0; i < patches_.Size(); ++i)
  123. patches_[i]->batches_[0].material_ = material;
  124. MarkNetworkUpdate();
  125. }
  126. void Terrain::SetDrawDistance(float distance)
  127. {
  128. drawDistance_ = distance;
  129. for (unsigned i = 0; i < patches_.Size(); ++i)
  130. patches_[i]->SetDrawDistance(distance);
  131. MarkNetworkUpdate();
  132. }
  133. void Terrain::SetShadowDistance(float distance)
  134. {
  135. shadowDistance_ = distance;
  136. for (unsigned i = 0; i < patches_.Size(); ++i)
  137. patches_[i]->SetShadowDistance(distance);
  138. MarkNetworkUpdate();
  139. }
  140. void Terrain::SetLodBias(float bias)
  141. {
  142. lodBias_ = bias;
  143. for (unsigned i = 0; i < patches_.Size(); ++i)
  144. patches_[i]->SetLodBias(bias);
  145. MarkNetworkUpdate();
  146. }
  147. void Terrain::SetViewMask(unsigned mask)
  148. {
  149. viewMask_ = mask;
  150. for (unsigned i = 0; i < patches_.Size(); ++i)
  151. patches_[i]->SetViewMask(mask);
  152. MarkNetworkUpdate();
  153. }
  154. void Terrain::SetLightMask(unsigned mask)
  155. {
  156. lightMask_ = mask;
  157. for (unsigned i = 0; i < patches_.Size(); ++i)
  158. patches_[i]->SetLightMask(mask);
  159. MarkNetworkUpdate();
  160. }
  161. void Terrain::SetShadowMask(unsigned mask)
  162. {
  163. shadowMask_ = mask;
  164. for (unsigned i = 0; i < patches_.Size(); ++i)
  165. patches_[i]->SetShadowMask(mask);
  166. MarkNetworkUpdate();
  167. }
  168. void Terrain::SetZoneMask(unsigned mask)
  169. {
  170. zoneMask_ = mask;
  171. for (unsigned i = 0; i < patches_.Size(); ++i)
  172. patches_[i]->SetZoneMask(mask);
  173. MarkNetworkUpdate();
  174. }
  175. void Terrain::SetMaxLights(unsigned num)
  176. {
  177. maxLights_ = num;
  178. for (unsigned i = 0; i < patches_.Size(); ++i)
  179. patches_[i]->SetMaxLights(num);
  180. MarkNetworkUpdate();
  181. }
  182. void Terrain::SetVisible(bool enable)
  183. {
  184. visible_ = enable;
  185. for (unsigned i = 0; i < patches_.Size(); ++i)
  186. patches_[i]->SetVisible(enable);
  187. MarkNetworkUpdate();
  188. }
  189. void Terrain::SetCastShadows(bool enable)
  190. {
  191. castShadows_ = enable;
  192. for (unsigned i = 0; i < patches_.Size(); ++i)
  193. patches_[i]->SetCastShadows(enable);
  194. MarkNetworkUpdate();
  195. }
  196. void Terrain::SetOccluder(bool enable)
  197. {
  198. occluder_ = enable;
  199. for (unsigned i = 0; i < patches_.Size(); ++i)
  200. patches_[i]->SetOccluder(enable);
  201. MarkNetworkUpdate();
  202. }
  203. void Terrain::SetOccludee(bool enable)
  204. {
  205. occluder_ = enable;
  206. for (unsigned i = 0; i < patches_.Size(); ++i)
  207. patches_[i]->SetOccludee(enable);
  208. MarkNetworkUpdate();
  209. }
  210. Image* Terrain::GetHeightMap() const
  211. {
  212. return heightMap_;
  213. }
  214. Material* Terrain::GetMaterial() const
  215. {
  216. return material_;
  217. }
  218. float Terrain::GetHeight(const Vector3& worldPosition) const
  219. {
  220. if (node_)
  221. {
  222. Vector3 position = node_->GetWorldTransform().Inverse() * worldPosition;
  223. float xPos = (position.x_ - patchWorldOrigin_.x_) / spacing_.x_;
  224. float zPos = (-position.z_ - patchWorldOrigin_.y_) / spacing_.z_;
  225. float xFrac = xPos - floorf(xPos);
  226. float zFrac = zPos - floorf(zPos);
  227. float h1, h2, h3;
  228. if (xFrac + zFrac >= 1.0f)
  229. {
  230. h1 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos + 1);
  231. h2 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  232. h3 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  233. xFrac = 1.0f - xFrac;
  234. zFrac = 1.0f - zFrac;
  235. }
  236. else
  237. {
  238. h1 = GetRawHeight((unsigned)xPos, (unsigned)zPos);
  239. h2 = GetRawHeight((unsigned)xPos + 1, (unsigned)zPos);
  240. h3 = GetRawHeight((unsigned)xPos, (unsigned)zPos + 1);
  241. }
  242. float h = h1 * (1.0f - xFrac - zFrac) + h2 * xFrac + h3 * zFrac;
  243. /// \todo This assumes that the terrain scene node is upright
  244. return node_->GetWorldScale().y_ * h + node_->GetWorldPosition().y_;
  245. }
  246. else
  247. return 0.0f;
  248. }
  249. void Terrain::UpdatePatchGeometry(TerrainPatch* patch)
  250. {
  251. BoundingBox box;
  252. unsigned vertexDataRow = patchSize_ + 1;
  253. VertexBuffer* vertexBuffer = patch->vertexBuffer_;
  254. if (vertexBuffer->GetVertexCount() != vertexDataRow * vertexDataRow)
  255. vertexBuffer->SetSize(vertexDataRow * vertexDataRow, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  256. float* vertexData = (float*)vertexBuffer->Lock(0, vertexBuffer->GetVertexCount());
  257. if (vertexData)
  258. {
  259. unsigned x = patch->x_;
  260. unsigned z = patch->z_;
  261. for (unsigned z1 = 0; z1 <= patchSize_; ++z1)
  262. {
  263. for (unsigned x1 = 0; x1 <= patchSize_; ++x1)
  264. {
  265. int xPos = x * patchSize_ + x1;
  266. int zPos = z * patchSize_ + z1;
  267. // Position
  268. Vector3 position((float)x1 * spacing_.x_, GetRawHeight(xPos, zPos), -(float)z1 * spacing_.z_);
  269. *vertexData++ = position.x_;
  270. *vertexData++ = position.y_;
  271. *vertexData++ = position.z_;
  272. box.Merge(position);
  273. // Normal
  274. Vector3 normal = GetNormal(xPos, zPos);
  275. *vertexData++ = normal.x_;
  276. *vertexData++ = normal.y_;
  277. *vertexData++ = normal.z_;
  278. // Texture coordinate
  279. Vector2 texCoord((float)xPos / (float)size_.x_, (float)zPos / (float)size_.y_);
  280. *vertexData++ = texCoord.x_;
  281. *vertexData++ = texCoord.y_;
  282. // Tangent
  283. Vector3 xyz = (Vector3::RIGHT - normal * normal.DotProduct(Vector3::RIGHT)).Normalized();
  284. *vertexData++ = xyz.x_;
  285. *vertexData++ = xyz.y_;
  286. *vertexData++ = xyz.z_;
  287. *vertexData++ = 1.0f;
  288. }
  289. }
  290. vertexBuffer->Unlock();
  291. vertexBuffer->ClearDataLost();
  292. }
  293. patch->boundingBox_ = box;
  294. patch->geometry_->SetIndexBuffer(indexBuffer_);
  295. patch->geometry_->SetDrawRange(TRIANGLE_LIST, 0, indexBuffer_->GetIndexCount());
  296. patch->OnMarkedDirty(patch->GetNode());
  297. }
  298. void Terrain::UpdatePatchLOD(TerrainPatch* patch, unsigned lod, unsigned northLod, unsigned southLod, unsigned westLod,
  299. unsigned eastLod)
  300. {
  301. }
  302. void Terrain::OnMarkedDirty(Node* node)
  303. {
  304. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  305. for (Vector<SharedPtr<TerrainPatch> >::Iterator i = patches_.Begin(); i != patches_.End(); ++i)
  306. SetPatchTransform(*i);
  307. }
  308. void Terrain::CreateGeometry()
  309. {
  310. Scene* scene = GetScene();
  311. Octree* octree = scene ? scene->GetComponent<Octree>() : 0;
  312. if (!heightMap_ || !node_ || !octree)
  313. return;
  314. PROFILE(CreateTerrainGeometry);
  315. patches_.Clear();
  316. patchNodes_.Clear();
  317. // Determine total terrain size & copy heightmap data
  318. patchesX_ = (heightMap_->GetWidth() - 1) / patchSize_;
  319. patchesZ_ = (heightMap_->GetHeight() - 1) / patchSize_;
  320. size_ = IntVector2(patchesX_ * patchSize_ + 1, patchesZ_ * patchSize_ + 1);
  321. patchWorldSize_ = Vector2(spacing_.x_ * (float)patchSize_, spacing_.z_ * (float)patchSize_);
  322. patchWorldOrigin_ = Vector2(-0.5f * (float)patchesX_ * patchWorldSize_.x_, -0.5f * (float)patchesZ_ * patchWorldSize_.y_);
  323. heightData_ = new float[size_.x_ * size_.y_];
  324. const unsigned char* src = heightMap_->GetData();
  325. float* dest = heightData_;
  326. unsigned imgComps = heightMap_->GetComponents();
  327. unsigned imgRow = heightMap_->GetWidth() * imgComps;
  328. for (int z = 0; z < size_.y_; ++z)
  329. {
  330. for (int x = 0; x < size_.x_; ++x)
  331. *dest++ = (float)src[imgRow * z + imgComps * x] * spacing_.y_;
  332. }
  333. // Create scene nodes for patches
  334. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  335. for (unsigned z = 0; z < patchesZ_; ++z)
  336. {
  337. for (unsigned x = 0; x < patchesX_; ++x)
  338. {
  339. // Note: terrain nodes are not created as part of the scene, as it's runtime generated scene hierarchy
  340. // we never want to save, serialize through network, or show in the editor
  341. Node* patchNode = new Node(context_);
  342. patchNode->SetID(FIRST_LOCAL_ID);
  343. TerrainPatch* patch = new TerrainPatch(context_);
  344. patch->owner_ = this;
  345. patch->x_ = x;
  346. patch->z_ = z;
  347. patchNode->AddComponent(patch, FIRST_LOCAL_ID, LOCAL);
  348. octree->AddManualDrawable(patch);
  349. // Copy initial drawable parameters
  350. patch->batches_[0].material_ = material_;
  351. patch->SetDrawDistance(drawDistance_);
  352. patch->SetShadowDistance(shadowDistance_);
  353. patch->SetLodBias(lodBias_);
  354. patch->SetViewMask(viewMask_);
  355. patch->SetLightMask(lightMask_);
  356. patch->SetShadowMask(shadowMask_);
  357. patch->SetZoneMask(zoneMask_);
  358. patch->SetMaxLights(maxLights_);
  359. patch->SetVisible(visible_);
  360. patch->SetCastShadows(castShadows_);
  361. patch->SetOccluder(occluder_);
  362. patch->SetOccludee(occludee_);
  363. patches_.Push(SharedPtr<TerrainPatch>(patch));
  364. patchNodes_.Push(SharedPtr<Node>(patchNode));
  365. }
  366. }
  367. // Create the shared index data
  368. /// \todo Create LOD levels
  369. indexBuffer_->SetSize(patchSize_ * patchSize_ * 6, false);
  370. unsigned vertexDataRow = patchSize_ + 1;
  371. unsigned short* indexData = (unsigned short*)indexBuffer_->Lock(0, indexBuffer_->GetIndexCount());
  372. if (indexData)
  373. {
  374. for (unsigned z = 0; z < patchSize_; ++z)
  375. {
  376. for (unsigned x = 0; x < patchSize_; ++x)
  377. {
  378. *indexData++ = x + z * vertexDataRow;
  379. *indexData++ = x + z * vertexDataRow + 1;
  380. *indexData++ = x + (z + 1) * vertexDataRow;
  381. *indexData++ = x + z * vertexDataRow + 1;
  382. *indexData++ = x + (z + 1) * vertexDataRow + 1;
  383. *indexData++ = x + (z + 1) * vertexDataRow;
  384. }
  385. }
  386. indexBuffer_->Unlock();
  387. }
  388. // Create vertex data for patches, and set transform
  389. for (Vector<SharedPtr<TerrainPatch> >::Iterator i = patches_.Begin(); i != patches_.End(); ++i)
  390. {
  391. SetPatchTransform(*i);
  392. UpdatePatchGeometry(*i);
  393. }
  394. }
  395. void Terrain::SetPatchTransform(TerrainPatch* patch)
  396. {
  397. Node* patchNode = patch->GetNode();
  398. unsigned x = patch->x_;
  399. unsigned z = patch->z_;
  400. Matrix3x4 patchTransform(Vector3(patchWorldOrigin_.x_ + (float)x * patchWorldSize_.x_, 0.0f, -patchWorldOrigin_.y_ -
  401. (float)z * patchWorldSize_.y_), Quaternion::IDENTITY, 1.0f);
  402. Matrix3x4 combinedTransform = node_->GetWorldTransform() * patchTransform;
  403. patchNode->SetTransform(combinedTransform.Translation(), combinedTransform.Rotation(), combinedTransform.Scale());
  404. }
  405. float Terrain::GetRawHeight(unsigned x, unsigned z) const
  406. {
  407. if (!heightData_)
  408. return 0.0f;
  409. x = Clamp((int)x, 0, (int)size_.x_ - 1);
  410. z = Clamp((int)z, 0, (int)size_.y_ - 1);
  411. return heightData_[z * size_.x_ + x];
  412. }
  413. Vector3 Terrain::GetNormal(unsigned x, unsigned z) const
  414. {
  415. float baseHeight = GetRawHeight(x, z);
  416. float nSlope = GetRawHeight(x, z - 1) - baseHeight;
  417. float neSlope = GetRawHeight(x + 1, z - 1) - baseHeight;
  418. float eSlope = GetRawHeight(x + 1, z) - baseHeight;
  419. float seSlope = GetRawHeight(x + 1, z + 1) - baseHeight;
  420. float sSlope = GetRawHeight(x, z + 1) - baseHeight;
  421. float swSlope = GetRawHeight(x - 1, z + 1) - baseHeight;
  422. float wSlope = GetRawHeight(x - 1, z) - baseHeight;
  423. float nwSlope = GetRawHeight(x - 1, z - 1) - baseHeight;
  424. return (Vector3(0.0f, 1.0f, -nSlope) +
  425. Vector3(-neSlope, 1.0f, -neSlope) +
  426. Vector3(-eSlope, 1.0f, 0.0f) +
  427. Vector3(-seSlope, 1.0f, seSlope) +
  428. Vector3(0.0f, 1.0f, sSlope) +
  429. Vector3(swSlope, 1.0f, swSlope) +
  430. Vector3(wSlope, 1.0f, 0.0f) +
  431. Vector3(nwSlope, 1.0f, -nwSlope)).Normalized();
  432. }