BillboardSet.cpp 15 KB

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