BillboardSet.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Batch.h"
  26. #include "../Graphics/BillboardSet.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/IndexBuffer.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/MemoryBuffer.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Node.h"
  36. #include "../DebugNew.h"
  37. namespace Urho3D
  38. {
  39. extern const char* GEOMETRY_CATEGORY;
  40. static const float INV_SQRT_TWO = 1.0f / sqrtf(2.0f);
  41. const char* faceCameraModeNames[] =
  42. {
  43. "None",
  44. "Rotate XYZ",
  45. "Rotate Y",
  46. "LookAt XYZ",
  47. "LookAt Y",
  48. "LookAt Mixed",
  49. "Direction",
  50. 0
  51. };
  52. const char* billboardsStructureElementNames[] =
  53. {
  54. "Billboard Count",
  55. " Position",
  56. " Size",
  57. " UV Coordinates",
  58. " Color",
  59. " Rotation",
  60. " Direction",
  61. " Is Enabled",
  62. 0
  63. };
  64. inline bool CompareBillboards(Billboard* lhs, Billboard* rhs)
  65. {
  66. return lhs->sortDistance_ > rhs->sortDistance_;
  67. }
  68. BillboardSet::BillboardSet(Context* context) :
  69. Drawable(context, DRAWABLE_GEOMETRY),
  70. animationLodBias_(1.0f),
  71. animationLodTimer_(0.0f),
  72. relative_(true),
  73. scaled_(true),
  74. sorted_(false),
  75. fixedScreenSize_(false),
  76. faceCameraMode_(FC_ROTATE_XYZ),
  77. minAngle_(0.0f),
  78. geometry_(new Geometry(context)),
  79. vertexBuffer_(new VertexBuffer(context_)),
  80. indexBuffer_(new IndexBuffer(context_)),
  81. bufferSizeDirty_(true),
  82. bufferDirty_(true),
  83. forceUpdate_(false),
  84. geometryTypeUpdate_(false),
  85. sortThisFrame_(false),
  86. hasOrthoCamera_(false),
  87. sortFrameNumber_(0),
  88. previousOffset_(Vector3::ZERO)
  89. {
  90. geometry_->SetVertexBuffer(0, vertexBuffer_);
  91. geometry_->SetIndexBuffer(indexBuffer_);
  92. batches_.Resize(1);
  93. batches_[0].geometry_ = geometry_;
  94. batches_[0].geometryType_ = GEOM_BILLBOARD;
  95. batches_[0].worldTransform_ = &transforms_[0];
  96. }
  97. BillboardSet::~BillboardSet()
  98. {
  99. }
  100. void BillboardSet::RegisterObject(Context* context)
  101. {
  102. context->RegisterFactory<BillboardSet>(GEOMETRY_CATEGORY);
  103. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  104. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  105. AM_DEFAULT);
  106. URHO3D_ACCESSOR_ATTRIBUTE("Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
  107. URHO3D_ACCESSOR_ATTRIBUTE("Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
  108. URHO3D_ACCESSOR_ATTRIBUTE("Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
  109. URHO3D_ACCESSOR_ATTRIBUTE("Fixed Screen Size", IsFixedScreenSize, SetFixedScreenSize, bool, false, AM_DEFAULT);
  110. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  111. URHO3D_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  112. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Face Camera Mode", GetFaceCameraMode, SetFaceCameraMode, FaceCameraMode, faceCameraModeNames, FC_ROTATE_XYZ, AM_DEFAULT);
  113. URHO3D_ACCESSOR_ATTRIBUTE("Min Angle", GetMinAngle, SetMinAngle, float, 0.0f, AM_DEFAULT);
  114. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  115. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  116. URHO3D_ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  117. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  118. URHO3D_MIXED_ACCESSOR_VARIANT_VECTOR_STRUCTURE_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr,
  119. VariantVector, Variant::emptyVariantVector,
  120. billboardsStructureElementNames, AM_FILE);
  121. URHO3D_ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>,
  122. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  123. }
  124. void BillboardSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  125. {
  126. // If no billboard-level testing, use the Drawable test
  127. if (query.level_ < RAY_TRIANGLE)
  128. {
  129. Drawable::ProcessRayQuery(query, results);
  130. return;
  131. }
  132. // Check ray hit distance to AABB before proceeding with billboard-level tests
  133. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  134. return;
  135. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  136. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  137. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  138. for (unsigned i = 0; i < billboards_.Size(); ++i)
  139. {
  140. if (!billboards_[i].enabled_)
  141. continue;
  142. // Approximate the billboards as spheres for raycasting
  143. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  144. if (fixedScreenSize_)
  145. size *= billboards_[i].screenScaleFactor_;
  146. Vector3 center = billboardTransform * billboards_[i].position_;
  147. Sphere billboardSphere(center, size);
  148. float distance = query.ray_.HitDistance(billboardSphere);
  149. if (distance < query.maxDistance_)
  150. {
  151. // If the code reaches here then we have a hit
  152. RayQueryResult result;
  153. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  154. result.normal_ = -query.ray_.direction_;
  155. result.distance_ = distance;
  156. result.drawable_ = this;
  157. result.node_ = node_;
  158. result.subObject_ = i;
  159. results.Push(result);
  160. }
  161. }
  162. }
  163. void BillboardSet::UpdateBatches(const FrameInfo& frame)
  164. {
  165. // If beginning a new frame, assume no sorting first
  166. if (frame.frameNumber_ != sortFrameNumber_)
  167. {
  168. sortThisFrame_ = false;
  169. sortFrameNumber_ = frame.frameNumber_;
  170. }
  171. Vector3 worldPos = node_->GetWorldPosition();
  172. Vector3 offset = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
  173. // Sort if position relative to camera has changed
  174. if (offset != previousOffset_ || frame.camera_->IsOrthographic() != hasOrthoCamera_)
  175. {
  176. if (sorted_)
  177. sortThisFrame_ = true;
  178. if (faceCameraMode_ == FC_DIRECTION)
  179. bufferDirty_ = true;
  180. hasOrthoCamera_ = frame.camera_->IsOrthographic();
  181. }
  182. // Calculate fixed screen size scale factor for billboards. Will not dirty the buffer unless actually changed
  183. if (fixedScreenSize_)
  184. CalculateFixedScreenSize(frame);
  185. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  186. // Calculate scaled distance for animation LOD
  187. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  188. // If there are no billboards, the size becomes zero, and LOD'ed updates no longer happen. Disable LOD in that case
  189. if (scale > M_EPSILON)
  190. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  191. else
  192. lodDistance_ = 0.0f;
  193. batches_[0].distance_ = distance_;
  194. batches_[0].numWorldTransforms_ = 2;
  195. // Billboard positioning
  196. transforms_[0] = relative_ ? node_->GetWorldTransform() : Matrix3x4::IDENTITY;
  197. // Billboard rotation
  198. transforms_[1] = Matrix3x4(Vector3::ZERO, faceCameraMode_ != FC_NONE ? frame.camera_->GetFaceCameraRotation(
  199. node_->GetWorldPosition(), node_->GetWorldRotation(), faceCameraMode_, minAngle_) : node_->GetWorldRotation(), Vector3::ONE);
  200. }
  201. void BillboardSet::UpdateGeometry(const FrameInfo& frame)
  202. {
  203. // If rendering from multiple views and fixed screen size is in use, re-update scale factors before each render
  204. if (fixedScreenSize_ && viewCameras_.Size() > 1)
  205. CalculateFixedScreenSize(frame);
  206. // If using camera facing, re-update the rotation for the current view now
  207. if (faceCameraMode_ != FC_NONE)
  208. {
  209. transforms_[1] = Matrix3x4(Vector3::ZERO, frame.camera_->GetFaceCameraRotation(node_->GetWorldPosition(),
  210. node_->GetWorldRotation(), faceCameraMode_, minAngle_), Vector3::ONE);
  211. }
  212. if (bufferSizeDirty_ || indexBuffer_->IsDataLost())
  213. UpdateBufferSize();
  214. if (bufferDirty_ || sortThisFrame_ || vertexBuffer_->IsDataLost())
  215. UpdateVertexBuffer(frame);
  216. }
  217. UpdateGeometryType BillboardSet::GetUpdateGeometryType()
  218. {
  219. // If using camera facing, always need some kind of geometry update, in case the billboard set is rendered from several views
  220. if (bufferDirty_ || bufferSizeDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost() || sortThisFrame_ ||
  221. faceCameraMode_ != FC_NONE || fixedScreenSize_)
  222. return UPDATE_MAIN_THREAD;
  223. else
  224. return UPDATE_NONE;
  225. }
  226. void BillboardSet::SetMaterial(Material* material)
  227. {
  228. batches_[0].material_ = material;
  229. MarkNetworkUpdate();
  230. }
  231. void BillboardSet::SetNumBillboards(unsigned num)
  232. {
  233. // Prevent negative value being assigned from the editor
  234. if (num > M_MAX_INT)
  235. num = 0;
  236. unsigned oldNum = billboards_.Size();
  237. if (num == oldNum)
  238. return;
  239. billboards_.Resize(num);
  240. // Set default values to new billboards
  241. for (unsigned i = oldNum; i < num; ++i)
  242. {
  243. billboards_[i].position_ = Vector3::ZERO;
  244. billboards_[i].size_ = Vector2::ONE;
  245. billboards_[i].uv_ = Rect::POSITIVE;
  246. billboards_[i].color_ = Color(1.0f, 1.0f, 1.0f);
  247. billboards_[i].rotation_ = 0.0f;
  248. billboards_[i].direction_ = Vector3::UP;
  249. billboards_[i].enabled_ = false;
  250. billboards_[i].screenScaleFactor_ = 1.0f;
  251. }
  252. bufferSizeDirty_ = true;
  253. Commit();
  254. }
  255. void BillboardSet::SetRelative(bool enable)
  256. {
  257. relative_ = enable;
  258. Commit();
  259. }
  260. void BillboardSet::SetScaled(bool enable)
  261. {
  262. scaled_ = enable;
  263. Commit();
  264. }
  265. void BillboardSet::SetSorted(bool enable)
  266. {
  267. sorted_ = enable;
  268. Commit();
  269. }
  270. void BillboardSet::SetFixedScreenSize(bool enable)
  271. {
  272. fixedScreenSize_ = enable;
  273. Commit();
  274. }
  275. void BillboardSet::SetFaceCameraMode(FaceCameraMode mode)
  276. {
  277. if ((faceCameraMode_ != FC_DIRECTION && mode == FC_DIRECTION) || (faceCameraMode_ == FC_DIRECTION && mode != FC_DIRECTION))
  278. {
  279. faceCameraMode_ = mode;
  280. if (faceCameraMode_ == FC_DIRECTION)
  281. batches_[0].geometryType_ = GEOM_DIRBILLBOARD;
  282. else
  283. batches_[0].geometryType_ = GEOM_BILLBOARD;
  284. geometryTypeUpdate_ = true;
  285. bufferSizeDirty_ = true;
  286. Commit();
  287. }
  288. else
  289. {
  290. faceCameraMode_ = mode;
  291. MarkNetworkUpdate();
  292. }
  293. }
  294. void BillboardSet::SetMinAngle(float angle)
  295. {
  296. minAngle_ = angle;
  297. MarkNetworkUpdate();
  298. }
  299. void BillboardSet::SetAnimationLodBias(float bias)
  300. {
  301. animationLodBias_ = Max(bias, 0.0f);
  302. MarkNetworkUpdate();
  303. }
  304. void BillboardSet::Commit()
  305. {
  306. MarkPositionsDirty();
  307. MarkNetworkUpdate();
  308. }
  309. Material* BillboardSet::GetMaterial() const
  310. {
  311. return batches_[0].material_;
  312. }
  313. Billboard* BillboardSet::GetBillboard(unsigned index)
  314. {
  315. return index < billboards_.Size() ? &billboards_[index] : (Billboard*)0;
  316. }
  317. void BillboardSet::SetMaterialAttr(const ResourceRef& value)
  318. {
  319. ResourceCache* cache = GetSubsystem<ResourceCache>();
  320. SetMaterial(cache->GetResource<Material>(value.name_));
  321. }
  322. void BillboardSet::SetBillboardsAttr(const VariantVector& value)
  323. {
  324. unsigned index = 0;
  325. unsigned numBillboards = index < value.Size() ? value[index++].GetUInt() : 0;
  326. SetNumBillboards(numBillboards);
  327. // Dealing with old billboard format
  328. if (value.Size() == billboards_.Size() * 6 + 1)
  329. {
  330. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  331. {
  332. i->position_ = value[index++].GetVector3();
  333. i->size_ = value[index++].GetVector2();
  334. Vector4 uv = value[index++].GetVector4();
  335. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  336. i->color_ = value[index++].GetColor();
  337. i->rotation_ = value[index++].GetFloat();
  338. i->enabled_ = value[index++].GetBool();
  339. }
  340. }
  341. // New billboard format
  342. else
  343. {
  344. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  345. {
  346. i->position_ = value[index++].GetVector3();
  347. i->size_ = value[index++].GetVector2();
  348. Vector4 uv = value[index++].GetVector4();
  349. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  350. i->color_ = value[index++].GetColor();
  351. i->rotation_ = value[index++].GetFloat();
  352. i->direction_ = value[index++].GetVector3();
  353. i->enabled_ = value[index++].GetBool();
  354. }
  355. }
  356. Commit();
  357. }
  358. void BillboardSet::SetNetBillboardsAttr(const PODVector<unsigned char>& value)
  359. {
  360. MemoryBuffer buf(value);
  361. unsigned numBillboards = buf.ReadVLE();
  362. SetNumBillboards(numBillboards);
  363. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  364. {
  365. i->position_ = buf.ReadVector3();
  366. i->size_ = buf.ReadVector2();
  367. i->uv_ = buf.ReadRect();
  368. i->color_ = buf.ReadColor();
  369. i->rotation_ = buf.ReadFloat();
  370. i->direction_ = buf.ReadVector3();
  371. i->enabled_ = buf.ReadBool();
  372. }
  373. Commit();
  374. }
  375. ResourceRef BillboardSet::GetMaterialAttr() const
  376. {
  377. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  378. }
  379. VariantVector BillboardSet::GetBillboardsAttr() const
  380. {
  381. VariantVector ret;
  382. ret.Reserve(billboards_.Size() * 7 + 1);
  383. ret.Push(billboards_.Size());
  384. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  385. {
  386. ret.Push(i->position_);
  387. ret.Push(i->size_);
  388. ret.Push(Vector4(i->uv_.min_.x_, i->uv_.min_.y_, i->uv_.max_.x_, i->uv_.max_.y_));
  389. ret.Push(i->color_);
  390. ret.Push(i->rotation_);
  391. ret.Push(i->direction_);
  392. ret.Push(i->enabled_);
  393. }
  394. return ret;
  395. }
  396. const PODVector<unsigned char>& BillboardSet::GetNetBillboardsAttr() const
  397. {
  398. attrBuffer_.Clear();
  399. attrBuffer_.WriteVLE(billboards_.Size());
  400. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  401. {
  402. attrBuffer_.WriteVector3(i->position_);
  403. attrBuffer_.WriteVector2(i->size_);
  404. attrBuffer_.WriteRect(i->uv_);
  405. attrBuffer_.WriteColor(i->color_);
  406. attrBuffer_.WriteFloat(i->rotation_);
  407. attrBuffer_.WriteVector3(i->direction_);
  408. attrBuffer_.WriteBool(i->enabled_);
  409. }
  410. return attrBuffer_.GetBuffer();
  411. }
  412. void BillboardSet::OnWorldBoundingBoxUpdate()
  413. {
  414. unsigned enabledBillboards = 0;
  415. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  416. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  417. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  418. BoundingBox worldBox;
  419. for (unsigned i = 0; i < billboards_.Size(); ++i)
  420. {
  421. if (!billboards_[i].enabled_)
  422. continue;
  423. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  424. if (fixedScreenSize_)
  425. size *= billboards_[i].screenScaleFactor_;
  426. Vector3 center = billboardTransform * billboards_[i].position_;
  427. Vector3 edge = Vector3::ONE * size;
  428. worldBox.Merge(BoundingBox(center - edge, center + edge));
  429. ++enabledBillboards;
  430. }
  431. // Always merge the node's own position to ensure particle emitter updates continue when the relative mode is switched
  432. worldBox.Merge(node_->GetWorldPosition());
  433. worldBoundingBox_ = worldBox;
  434. }
  435. void BillboardSet::UpdateBufferSize()
  436. {
  437. unsigned numBillboards = billboards_.Size();
  438. if (vertexBuffer_->GetVertexCount() != numBillboards * 4 || geometryTypeUpdate_)
  439. {
  440. if (faceCameraMode_ == FC_DIRECTION)
  441. {
  442. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_NORMAL | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  443. geometry_->SetVertexBuffer(0, vertexBuffer_);
  444. }
  445. else
  446. {
  447. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  448. geometry_->SetVertexBuffer(0, vertexBuffer_);
  449. }
  450. geometryTypeUpdate_ = false;
  451. }
  452. bool largeIndices = (numBillboards * 4) >= 65536;
  453. if (indexBuffer_->GetIndexCount() != numBillboards * 6)
  454. indexBuffer_->SetSize(numBillboards * 6, largeIndices);
  455. bufferSizeDirty_ = false;
  456. bufferDirty_ = true;
  457. forceUpdate_ = true;
  458. if (!numBillboards)
  459. return;
  460. // Indices do not change for a given billboard capacity
  461. void* destPtr = indexBuffer_->Lock(0, numBillboards * 6, true);
  462. if (!destPtr)
  463. return;
  464. if (!largeIndices)
  465. {
  466. unsigned short* dest = (unsigned short*)destPtr;
  467. unsigned short vertexIndex = 0;
  468. while (numBillboards--)
  469. {
  470. dest[0] = vertexIndex;
  471. dest[1] = vertexIndex + 1;
  472. dest[2] = vertexIndex + 2;
  473. dest[3] = vertexIndex + 2;
  474. dest[4] = vertexIndex + 3;
  475. dest[5] = vertexIndex;
  476. dest += 6;
  477. vertexIndex += 4;
  478. }
  479. }
  480. else
  481. {
  482. unsigned* dest = (unsigned*)destPtr;
  483. unsigned vertexIndex = 0;
  484. while (numBillboards--)
  485. {
  486. dest[0] = vertexIndex;
  487. dest[1] = vertexIndex + 1;
  488. dest[2] = vertexIndex + 2;
  489. dest[3] = vertexIndex + 2;
  490. dest[4] = vertexIndex + 3;
  491. dest[5] = vertexIndex;
  492. dest += 6;
  493. vertexIndex += 4;
  494. }
  495. }
  496. indexBuffer_->Unlock();
  497. indexBuffer_->ClearDataLost();
  498. }
  499. void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
  500. {
  501. // If using animation LOD, accumulate time and see if it is time to update
  502. if (animationLodBias_ > 0.0f && lodDistance_ > 0.0f)
  503. {
  504. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  505. if (animationLodTimer_ >= lodDistance_)
  506. animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_);
  507. else
  508. {
  509. // No LOD if immediate update forced
  510. if (!forceUpdate_)
  511. return;
  512. }
  513. }
  514. unsigned numBillboards = billboards_.Size();
  515. unsigned enabledBillboards = 0;
  516. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  517. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  518. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  519. // First check number of enabled billboards
  520. for (unsigned i = 0; i < numBillboards; ++i)
  521. {
  522. if (billboards_[i].enabled_)
  523. ++enabledBillboards;
  524. }
  525. sortedBillboards_.Resize(enabledBillboards);
  526. unsigned index = 0;
  527. // Then set initial sort order and distances
  528. for (unsigned i = 0; i < numBillboards; ++i)
  529. {
  530. Billboard& billboard = billboards_[i];
  531. if (billboard.enabled_)
  532. {
  533. sortedBillboards_[index++] = &billboard;
  534. if (sorted_)
  535. billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboardTransform * billboards_[i].position_);
  536. }
  537. }
  538. batches_[0].geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false);
  539. bufferDirty_ = false;
  540. forceUpdate_ = false;
  541. if (!enabledBillboards)
  542. return;
  543. if (sorted_)
  544. {
  545. Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards);
  546. Vector3 worldPos = node_->GetWorldPosition();
  547. // Store the "last sorted position" now
  548. previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
  549. }
  550. float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true);
  551. if (!dest)
  552. return;
  553. if (faceCameraMode_ != FC_DIRECTION)
  554. {
  555. for (unsigned i = 0; i < enabledBillboards; ++i)
  556. {
  557. Billboard& billboard = *sortedBillboards_[i];
  558. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  559. unsigned color = billboard.color_.ToUInt();
  560. if (fixedScreenSize_)
  561. size *= billboard.screenScaleFactor_;
  562. float rotationMatrix[2][2];
  563. SinCos(billboard.rotation_, rotationMatrix[0][1], rotationMatrix[0][0]);
  564. rotationMatrix[1][0] = -rotationMatrix[0][1];
  565. rotationMatrix[1][1] = rotationMatrix[0][0];
  566. dest[0] = billboard.position_.x_;
  567. dest[1] = billboard.position_.y_;
  568. dest[2] = billboard.position_.z_;
  569. ((unsigned&)dest[3]) = color;
  570. dest[4] = billboard.uv_.min_.x_;
  571. dest[5] = billboard.uv_.min_.y_;
  572. dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  573. dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  574. dest[8] = billboard.position_.x_;
  575. dest[9] = billboard.position_.y_;
  576. dest[10] = billboard.position_.z_;
  577. ((unsigned&)dest[11]) = color;
  578. dest[12] = billboard.uv_.max_.x_;
  579. dest[13] = billboard.uv_.min_.y_;
  580. dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  581. dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  582. dest[16] = billboard.position_.x_;
  583. dest[17] = billboard.position_.y_;
  584. dest[18] = billboard.position_.z_;
  585. ((unsigned&)dest[19]) = color;
  586. dest[20] = billboard.uv_.max_.x_;
  587. dest[21] = billboard.uv_.max_.y_;
  588. dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  589. dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  590. dest[24] = billboard.position_.x_;
  591. dest[25] = billboard.position_.y_;
  592. dest[26] = billboard.position_.z_;
  593. ((unsigned&)dest[27]) = color;
  594. dest[28] = billboard.uv_.min_.x_;
  595. dest[29] = billboard.uv_.max_.y_;
  596. dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  597. dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  598. dest += 32;
  599. }
  600. }
  601. else
  602. {
  603. for (unsigned i = 0; i < enabledBillboards; ++i)
  604. {
  605. Billboard& billboard = *sortedBillboards_[i];
  606. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  607. unsigned color = billboard.color_.ToUInt();
  608. if (fixedScreenSize_)
  609. size *= billboard.screenScaleFactor_;
  610. float rot2D[2][2];
  611. SinCos(billboard.rotation_, rot2D[0][1], rot2D[0][0]);
  612. rot2D[1][0] = -rot2D[0][1];
  613. rot2D[1][1] = rot2D[0][0];
  614. dest[0] = billboard.position_.x_;
  615. dest[1] = billboard.position_.y_;
  616. dest[2] = billboard.position_.z_;
  617. dest[3] = billboard.direction_.x_;
  618. dest[4] = billboard.direction_.y_;
  619. dest[5] = billboard.direction_.z_;
  620. ((unsigned&)dest[6]) = color;
  621. dest[7] = billboard.uv_.min_.x_;
  622. dest[8] = billboard.uv_.min_.y_;
  623. dest[9] = -size.x_ * rot2D[0][0] + size.y_ * rot2D[0][1];
  624. dest[10] = -size.x_ * rot2D[1][0] + size.y_ * rot2D[1][1];
  625. dest[11] = billboard.position_.x_;
  626. dest[12] = billboard.position_.y_;
  627. dest[13] = billboard.position_.z_;
  628. dest[14] = billboard.direction_.x_;
  629. dest[15] = billboard.direction_.y_;
  630. dest[16] = billboard.direction_.z_;
  631. ((unsigned&)dest[17]) = color;
  632. dest[18] = billboard.uv_.max_.x_;
  633. dest[19] = billboard.uv_.min_.y_;
  634. dest[20] = size.x_ * rot2D[0][0] + size.y_ * rot2D[0][1];
  635. dest[21] = size.x_ * rot2D[1][0] + size.y_ * rot2D[1][1];
  636. dest[22] = billboard.position_.x_;
  637. dest[23] = billboard.position_.y_;
  638. dest[24] = billboard.position_.z_;
  639. dest[25] = billboard.direction_.x_;
  640. dest[26] = billboard.direction_.y_;
  641. dest[27] = billboard.direction_.z_;
  642. ((unsigned&)dest[28]) = color;
  643. dest[29] = billboard.uv_.max_.x_;
  644. dest[30] = billboard.uv_.max_.y_;
  645. dest[31] = size.x_ * rot2D[0][0] - size.y_ * rot2D[0][1];
  646. dest[32] = size.x_ * rot2D[1][0] - size.y_ * rot2D[1][1];
  647. dest[33] = billboard.position_.x_;
  648. dest[34] = billboard.position_.y_;
  649. dest[35] = billboard.position_.z_;
  650. dest[36] = billboard.direction_.x_;
  651. dest[37] = billboard.direction_.y_;
  652. dest[38] = billboard.direction_.z_;
  653. ((unsigned&)dest[39]) = color;
  654. dest[40] = billboard.uv_.min_.x_;
  655. dest[41] = billboard.uv_.max_.y_;
  656. dest[42] = -size.x_ * rot2D[0][0] - size.y_ * rot2D[0][1];
  657. dest[43] = -size.x_ * rot2D[1][0] - size.y_ * rot2D[1][1];
  658. dest += 44;
  659. }
  660. }
  661. vertexBuffer_->Unlock();
  662. vertexBuffer_->ClearDataLost();
  663. }
  664. void BillboardSet::MarkPositionsDirty()
  665. {
  666. Drawable::OnMarkedDirty(node_);
  667. bufferDirty_ = true;
  668. }
  669. void BillboardSet::CalculateFixedScreenSize(const FrameInfo& frame)
  670. {
  671. float invViewHeight = 1.0f / frame.viewSize_.y_;
  672. float halfViewWorldSize = frame.camera_->GetHalfViewSize();
  673. bool scaleFactorChanged = false;
  674. if (!frame.camera_->IsOrthographic())
  675. {
  676. Matrix4 viewProj(frame.camera_->GetProjection() * frame.camera_->GetView());
  677. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  678. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  679. for (unsigned i = 0; i < billboards_.Size(); ++i)
  680. {
  681. Vector4 projPos(viewProj * Vector4(billboardTransform * billboards_[i].position_, 1.0f));
  682. float newScaleFactor = invViewHeight * halfViewWorldSize * projPos.w_;
  683. if (newScaleFactor != billboards_[i].screenScaleFactor_)
  684. {
  685. billboards_[i].screenScaleFactor_ = newScaleFactor;
  686. scaleFactorChanged = true;
  687. }
  688. }
  689. }
  690. else
  691. {
  692. for (unsigned i = 0; i < billboards_.Size(); ++i)
  693. {
  694. float newScaleFactor = invViewHeight * halfViewWorldSize;
  695. if (newScaleFactor != billboards_[i].screenScaleFactor_)
  696. {
  697. billboards_[i].screenScaleFactor_ = newScaleFactor;
  698. scaleFactorChanged = true;
  699. }
  700. }
  701. }
  702. if (scaleFactorChanged)
  703. {
  704. bufferDirty_ = true;
  705. forceUpdate_ = true;
  706. worldBoundingBoxDirty_ = true;
  707. }
  708. }
  709. }