BillboardSet.cpp 17 KB

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