BillboardSet.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 "Batch.h"
  25. #include "BillboardSet.h"
  26. #include "Camera.h"
  27. #include "Context.h"
  28. #include "Geometry.h"
  29. #include "Graphics.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Material.h"
  33. #include "MemoryBuffer.h"
  34. #include "Profiler.h"
  35. #include "ResourceCache.h"
  36. #include "Sort.h"
  37. #include "VertexBuffer.h"
  38. #include "XMLElement.h"
  39. #include "DebugNew.h"
  40. static const Vector3 DOT_SCALE(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  41. static const float INV_SQRT_TWO = 1.0f / sqrtf(2.0f);
  42. inline bool CompareBillboards(Billboard* lhs, Billboard* rhs)
  43. {
  44. return lhs->sortDistance_ > rhs->sortDistance_;
  45. }
  46. OBJECTTYPESTATIC(BillboardSet);
  47. BillboardSet::BillboardSet(Context* context) :
  48. Drawable(context),
  49. geometry_(new Geometry(context_)),
  50. animationLodBias_(1.0f),
  51. animationLodTimer_(0.0f),
  52. relative_(true),
  53. scaled_(true),
  54. sorted_(false),
  55. bufferSizeDirty_(true),
  56. bufferDirty_(true),
  57. forceUpdate_(false),
  58. previousOffset_(Vector3::ZERO),
  59. sortFrameNumber_(0)
  60. {
  61. drawableFlags_ = DRAWABLE_GEOMETRY;
  62. }
  63. BillboardSet::~BillboardSet()
  64. {
  65. }
  66. void BillboardSet::RegisterObject(Context* context)
  67. {
  68. context->RegisterFactory<BillboardSet>();
  69. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_RESOURCEREF, "Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  70. ATTRIBUTE(BillboardSet, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  71. ATTRIBUTE(BillboardSet, VAR_BOOL, "Can Be Occluded", occludee_, true, AM_DEFAULT);
  72. ATTRIBUTE(BillboardSet, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  73. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_BOOL, "Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
  74. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_BOOL, "Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
  75. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_BOOL, "Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
  76. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  77. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  78. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_FLOAT, "Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  79. COPY_BASE_ATTRIBUTES(BillboardSet, Drawable);
  80. ACCESSOR_ATTRIBUTE(BillboardSet, VAR_VARIANTVECTOR, "Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, VariantVector(), AM_FILE);
  81. REF_ACCESSOR_ATTRIBUTE(BillboardSet, VAR_BUFFER, "Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>, PODVector<unsigned char>(), AM_NET | AM_NOEDIT);
  82. }
  83. void BillboardSet::UpdateDistance(const FrameInfo& frame)
  84. {
  85. // Check if position relative to camera has changed, and re-sort in that case
  86. const Vector3& worldPos = GetWorldPosition();
  87. Vector3 offset = (worldPos - frame.camera_->GetWorldPosition());
  88. if (offset != previousOffset_)
  89. {
  90. previousOffset_ = offset;
  91. if (sorted_)
  92. {
  93. // Sort billboards only once per frame. This means that secondary views will get
  94. // the same sorting as the main view
  95. if (frame.frameNumber_ != sortFrameNumber_)
  96. {
  97. sortFrameNumber_ = frame.frameNumber_;
  98. bufferDirty_ = true;
  99. }
  100. }
  101. }
  102. distance_ = frame.camera_->GetDistance(worldPos);
  103. // Calculate scaled distance for animation LOD
  104. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  105. // If there are no billboards, the size becomes zero, and LOD'ed updates no longer happen. Disable LOD in that case
  106. if (scale > M_EPSILON)
  107. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  108. else
  109. lodDistance_ = 0.0f;
  110. }
  111. void BillboardSet::UpdateGeometry(const FrameInfo& frame)
  112. {
  113. if (bufferSizeDirty_)
  114. {
  115. UpdateBufferSize();
  116. forceUpdate_ = true;
  117. }
  118. if (vertexBuffer_->IsDataLost())
  119. {
  120. vertexBuffer_->ClearDataLost();
  121. bufferDirty_ = true;
  122. forceUpdate_ = true;
  123. }
  124. if (bufferDirty_)
  125. UpdateVertexBuffer(frame);
  126. }
  127. UpdateGeometryType BillboardSet::GetUpdateGeometryType()
  128. {
  129. if (bufferDirty_ || bufferSizeDirty_ || (vertexBuffer_ && vertexBuffer_->IsDataLost()))
  130. return UPDATE_MAIN_THREAD;
  131. else
  132. return UPDATE_NONE;
  133. }
  134. unsigned BillboardSet::GetNumBatches()
  135. {
  136. return 1;
  137. }
  138. void BillboardSet::GetBatch(Batch& batch, const FrameInfo& frame, unsigned batchIndex)
  139. {
  140. batch.distance_ = distance_;
  141. batch.geometry_ = geometry_;
  142. batch.geometryType_ = GEOM_BILLBOARD;
  143. batch.worldTransform_ = &GetWorldTransform();
  144. batch.material_ = material_;
  145. }
  146. void BillboardSet::SetMaterial(Material* material)
  147. {
  148. material_ = material;
  149. }
  150. void BillboardSet::SetNumBillboards(unsigned num)
  151. {
  152. unsigned oldNum = billboards_.Size();
  153. billboards_.Resize(num);
  154. // Set default values to new billboards
  155. for (unsigned i = oldNum; i < num; ++i)
  156. {
  157. billboards_[i].position_ = Vector3::ZERO;
  158. billboards_[i].size_ = Vector2::ONE;
  159. billboards_[i].uv_ = Rect::POSITIVE;
  160. billboards_[i].color_ = Color(1.0f, 1.0f, 1.0f);
  161. billboards_[i].rotation_ = 0.0f;
  162. billboards_[i].enabled_ = false;
  163. }
  164. bufferSizeDirty_ = true;
  165. MarkPositionsDirty();
  166. }
  167. void BillboardSet::SetRelative(bool enable)
  168. {
  169. relative_ = enable;
  170. MarkPositionsDirty();
  171. }
  172. void BillboardSet::SetScaled(bool enable)
  173. {
  174. scaled_ = enable;
  175. MarkPositionsDirty();
  176. }
  177. void BillboardSet::SetSorted(bool enable)
  178. {
  179. sorted_ = enable;
  180. MarkPositionsDirty();
  181. }
  182. void BillboardSet::SetAnimationLodBias(float bias)
  183. {
  184. animationLodBias_ = Max(bias, 0.0f);
  185. }
  186. void BillboardSet::Updated()
  187. {
  188. MarkPositionsDirty();
  189. }
  190. Billboard* BillboardSet::GetBillboard(unsigned index)
  191. {
  192. return index < billboards_.Size() ? &billboards_[index] : (Billboard*)0;
  193. }
  194. void BillboardSet::SetMaterialAttr(ResourceRef value)
  195. {
  196. ResourceCache* cache = GetSubsystem<ResourceCache>();
  197. SetMaterial(cache->GetResource<Material>(value.id_));
  198. }
  199. void BillboardSet::SetBillboardsAttr(VariantVector value)
  200. {
  201. unsigned index = 0;
  202. SetNumBillboards(value[index++].GetInt());
  203. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  204. {
  205. i->position_ = value[index++].GetVector3();
  206. i->size_ = value[index++].GetVector2();
  207. Vector4 uv = value[index++].GetVector4();
  208. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  209. i->color_ = value[index++].GetColor();
  210. i->rotation_ = value[index++].GetFloat();
  211. i->enabled_ = value[index++].GetBool();
  212. }
  213. Updated();
  214. }
  215. void BillboardSet::SetNetBillboardsAttr(const PODVector<unsigned char>& value)
  216. {
  217. MemoryBuffer buf(value);
  218. unsigned numBillboards = buf.ReadVLE();
  219. SetNumBillboards(numBillboards);
  220. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  221. {
  222. i->position_ = buf.ReadVector3();
  223. i->size_ = buf.ReadVector2();
  224. i->uv_ = buf.ReadRect();
  225. i->color_ = buf.ReadColor();
  226. i->rotation_ = buf.ReadFloat();
  227. i->enabled_ = buf.ReadBool();
  228. }
  229. Updated();
  230. }
  231. ResourceRef BillboardSet::GetMaterialAttr() const
  232. {
  233. return GetResourceRef(material_, Material::GetTypeStatic());
  234. }
  235. VariantVector BillboardSet::GetBillboardsAttr() const
  236. {
  237. VariantVector ret;
  238. ret.Push(billboards_.Size());
  239. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  240. {
  241. ret.Push(i->position_);
  242. ret.Push(i->size_);
  243. ret.Push(Vector4(i->uv_.min_.x_, i->uv_.min_.y_, i->uv_.max_.x_, i->uv_.max_.y_));
  244. ret.Push(i->color_);
  245. ret.Push(i->rotation_);
  246. ret.Push(i->enabled_);
  247. }
  248. return ret;
  249. }
  250. const PODVector<unsigned char>& BillboardSet::GetNetBillboardsAttr() const
  251. {
  252. attrBuffer_.Clear();
  253. attrBuffer_.WriteVLE(billboards_.Size());
  254. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  255. {
  256. attrBuffer_.WriteVector3(i->position_);
  257. attrBuffer_.WriteVector2(i->size_);
  258. attrBuffer_.WriteRect(i->uv_);
  259. attrBuffer_.WriteColor(i->color_);
  260. attrBuffer_.WriteFloat(i->rotation_);
  261. attrBuffer_.WriteBool(i->enabled_);
  262. }
  263. return attrBuffer_.GetBuffer();
  264. }
  265. void BillboardSet::OnMarkedDirty(Node* node)
  266. {
  267. Drawable::OnMarkedDirty(node);
  268. if (node == node_ && relative_)
  269. bufferDirty_ = true;
  270. }
  271. void BillboardSet::OnWorldBoundingBoxUpdate()
  272. {
  273. worldBoundingBox_.defined_ = false;
  274. unsigned enabledBillboards = 0;
  275. const Matrix3x4& worldTransform = GetWorldTransform();
  276. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  277. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  278. for (unsigned i = 0; i < billboards_.Size(); ++i)
  279. {
  280. if (!billboards_[i].enabled_)
  281. continue;
  282. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  283. Vector3 center = billboardTransform * billboards_[i].position_;
  284. Vector3 edge = Vector3::ONE * size;
  285. worldBoundingBox_.Merge(BoundingBox(center - edge, center + edge));
  286. ++enabledBillboards;
  287. }
  288. // If no billboards enabled, the bounding box is just the node's world position
  289. if (!enabledBillboards)
  290. worldBoundingBox_.Merge(GetWorldPosition());
  291. }
  292. void BillboardSet::UpdateBufferSize()
  293. {
  294. if (!vertexBuffer_ || !indexBuffer_)
  295. {
  296. vertexBuffer_ = new VertexBuffer(context_);
  297. indexBuffer_ = new IndexBuffer(context_);
  298. geometry_->SetVertexBuffer(0, vertexBuffer_, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2);
  299. geometry_->SetIndexBuffer(indexBuffer_);
  300. }
  301. unsigned numBillboards = billboards_.Size();
  302. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  303. indexBuffer_->SetSize(numBillboards * 6, false);
  304. bufferSizeDirty_ = false;
  305. bufferDirty_ = true;
  306. if (!numBillboards)
  307. return;
  308. // Indices do not change for a given billboard capacity
  309. unsigned short* dest = (unsigned short*)indexBuffer_->Lock(0, numBillboards * 6, LOCK_DISCARD);
  310. if (!dest)
  311. return;
  312. unsigned vertexIndex = 0;
  313. while (numBillboards--)
  314. {
  315. *dest++ = vertexIndex; *dest++ = vertexIndex + 1; *dest++ = vertexIndex + 2;
  316. *dest++ = vertexIndex + 2; *dest++ = vertexIndex + 3; *dest++ = vertexIndex;
  317. vertexIndex += 4;
  318. }
  319. indexBuffer_->Unlock();
  320. }
  321. void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
  322. {
  323. // If using animation LOD, accumulate time and see if it is time to update
  324. if (animationLodBias_ > 0.0f && lodDistance_ > 0.0f)
  325. {
  326. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * frame.viewSize_.y_ * ANIMATION_LOD_BASESCALE;
  327. if (animationLodTimer_ >= lodDistance_)
  328. animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_);
  329. else
  330. {
  331. // No LOD if immediate update forced
  332. if (!forceUpdate_)
  333. return;
  334. }
  335. }
  336. unsigned numBillboards = billboards_.Size();
  337. unsigned enabledBillboards = 0;
  338. const Matrix3x4& worldTransform = GetWorldTransform();
  339. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  340. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  341. // First check number of enabled billboards
  342. for (unsigned i = 0; i < numBillboards; ++i)
  343. {
  344. if (billboards_[i].enabled_)
  345. ++enabledBillboards;
  346. }
  347. sortedBillboards_.Resize(enabledBillboards);
  348. unsigned index = 0;
  349. // Then set initial sort order and distances
  350. for (unsigned i = 0; i < numBillboards; ++i)
  351. {
  352. Billboard& billboard = billboards_[i];
  353. if (billboard.enabled_)
  354. {
  355. sortedBillboards_[index++] = &billboard;
  356. if (sorted_)
  357. billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboardTransform * billboards_[i].position_);
  358. }
  359. }
  360. geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false);
  361. bufferDirty_ = false;
  362. forceUpdate_ = false;
  363. if (!enabledBillboards)
  364. return;
  365. if (sorted_)
  366. Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards);
  367. float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, LOCK_DISCARD);
  368. if (!dest)
  369. return;
  370. const Vector3& worldScale = GetWorldTransform().Scale();
  371. for (unsigned i = 0; i < enabledBillboards; ++i)
  372. {
  373. Billboard& billboard = *sortedBillboards_[i];
  374. Vector3 position(billboardTransform * billboard.position_);
  375. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  376. unsigned color = billboard.color_.ToUInt();
  377. float angleRad = billboard.rotation_ * M_DEGTORAD;
  378. float rotationMatrix[2][2];
  379. rotationMatrix[0][0] = cosf(angleRad);
  380. rotationMatrix[0][1] = sinf(angleRad);
  381. rotationMatrix[1][0] = -rotationMatrix[0][1];
  382. rotationMatrix[1][1] = rotationMatrix[0][0];
  383. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  384. *((unsigned*)dest) = color; dest++;
  385. *dest++ = billboard.uv_.min_.x_; *dest++ = billboard.uv_.max_.y_;
  386. *dest++ = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  387. *dest++ = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  388. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  389. *((unsigned*)dest) = color; dest++;
  390. *dest++ = billboard.uv_.max_.x_; *dest++ = billboard.uv_.max_.y_;
  391. *dest++ = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  392. *dest++ = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  393. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  394. *((unsigned*)dest) = color; dest++;
  395. *dest++ = billboard.uv_.max_.x_; *dest++ = billboard.uv_.min_.y_;
  396. *dest++ = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  397. *dest++ = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  398. *dest++ = position.x_; *dest++ = position.y_; *dest++ = position.z_;
  399. *((unsigned*)dest) = color; dest++;
  400. *dest++ = billboard.uv_.min_.x_; *dest++ = billboard.uv_.min_.y_;
  401. *dest++ = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  402. *dest++ = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  403. }
  404. vertexBuffer_->Unlock();
  405. }
  406. void BillboardSet::MarkPositionsDirty()
  407. {
  408. Drawable::OnMarkedDirty(node_);
  409. bufferDirty_ = true;
  410. }