BillboardSet.cpp 15 KB

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