DecalSet.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. //
  2. // Copyright (c) 2008-2020 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/AnimatedModel.h"
  26. #include "../Graphics/Batch.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/DecalSet.h"
  29. #include "../Graphics/Geometry.h"
  30. #include "../Graphics/Graphics.h"
  31. #include "../Graphics/IndexBuffer.h"
  32. #include "../Graphics/Material.h"
  33. #include "../Graphics/Tangent.h"
  34. #include "../Graphics/VertexBuffer.h"
  35. #include "../IO/Log.h"
  36. #include "../IO/MemoryBuffer.h"
  37. #include "../Resource/ResourceCache.h"
  38. #include "../Scene/Scene.h"
  39. #include "../Scene/SceneEvents.h"
  40. #include "../DebugNew.h"
  41. #ifdef _MSC_VER
  42. #pragma warning(disable:6293)
  43. #endif
  44. namespace Urho3D
  45. {
  46. extern const char* GEOMETRY_CATEGORY;
  47. static const unsigned MIN_VERTICES = 4;
  48. static const unsigned MIN_INDICES = 6;
  49. static const unsigned MAX_VERTICES = 65536;
  50. static const unsigned DEFAULT_MAX_VERTICES = 512;
  51. static const unsigned DEFAULT_MAX_INDICES = 1024;
  52. static const VertexMaskFlags STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
  53. static const VertexMaskFlags SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT |
  54. MASK_BLENDWEIGHTS | MASK_BLENDINDICES;
  55. static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
  56. {
  57. DecalVertex ret;
  58. float t = d0 / (d0 - d1);
  59. ret.position_ = v0.position_ + t * (v1.position_ - v0.position_);
  60. ret.normal_ = v0.normal_ + t * (v1.normal_ - v0.normal_);
  61. if (skinned)
  62. {
  63. if (*((unsigned*)v0.blendIndices_) != *((unsigned*)v1.blendIndices_))
  64. {
  65. // Blend weights and indices: if indices are different, choose the vertex nearer to the split plane
  66. const DecalVertex& src = Abs(d0) < Abs(d1) ? v0 : v1;
  67. for (unsigned i = 0; i < 4; ++i)
  68. {
  69. ret.blendWeights_[i] = src.blendWeights_[i];
  70. ret.blendIndices_[i] = src.blendIndices_[i];
  71. }
  72. }
  73. else
  74. {
  75. // If indices are same, can interpolate the weights
  76. for (unsigned i = 0; i < 4; ++i)
  77. {
  78. ret.blendWeights_[i] = v0.blendWeights_[i] + t * (v1.blendWeights_[i] - v0.blendWeights_[i]);
  79. ret.blendIndices_[i] = v0.blendIndices_[i];
  80. }
  81. }
  82. }
  83. return ret;
  84. }
  85. static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
  86. {
  87. unsigned last = 0;
  88. float lastDistance = 0.0f;
  89. dest.Clear();
  90. if (src.Empty())
  91. return;
  92. for (unsigned i = 0; i < src.Size(); ++i)
  93. {
  94. float distance = plane.Distance(src[i].position_);
  95. if (distance >= 0.0f)
  96. {
  97. if (lastDistance < 0.0f)
  98. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  99. dest.Push(src[i]);
  100. }
  101. else
  102. {
  103. if (lastDistance >= 0.0f && i != 0)
  104. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  105. }
  106. last = i;
  107. lastDistance = distance;
  108. }
  109. // Recheck the distances of the last and first vertices and add the final clipped vertex if applicable
  110. float distance = plane.Distance(src[0].position_);
  111. if ((lastDistance < 0.0f && distance >= 0.0f) || (lastDistance >= 0.0f && distance < 0.0f))
  112. dest.Push(ClipEdge(src[last], src[0], lastDistance, distance, skinned));
  113. }
  114. void Decal::AddVertex(const DecalVertex& vertex)
  115. {
  116. for (unsigned i = 0; i < vertices_.Size(); ++i)
  117. {
  118. if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
  119. {
  120. indices_.Push((unsigned short)i);
  121. return;
  122. }
  123. }
  124. auto newIndex = (unsigned short)vertices_.Size();
  125. vertices_.Push(vertex);
  126. indices_.Push(newIndex);
  127. }
  128. void Decal::CalculateBoundingBox()
  129. {
  130. boundingBox_.Clear();
  131. for (unsigned i = 0; i < vertices_.Size(); ++i)
  132. boundingBox_.Merge(vertices_[i].position_);
  133. }
  134. DecalSet::DecalSet(Context* context) :
  135. Drawable(context, DRAWABLE_GEOMETRY),
  136. geometry_(new Geometry(context)),
  137. vertexBuffer_(new VertexBuffer(context_)),
  138. indexBuffer_(new IndexBuffer(context_)),
  139. numVertices_(0),
  140. numIndices_(0),
  141. maxVertices_(DEFAULT_MAX_VERTICES),
  142. maxIndices_(DEFAULT_MAX_INDICES),
  143. optimizeBufferSize_(false),
  144. skinned_(false),
  145. bufferDirty_(true),
  146. boundingBoxDirty_(true),
  147. skinningDirty_(false),
  148. assignBonesPending_(false),
  149. subscribed_(false)
  150. {
  151. geometry_->SetIndexBuffer(indexBuffer_);
  152. batches_.Resize(1);
  153. batches_[0].geometry_ = geometry_;
  154. batches_[0].geometryType_ = GEOM_STATIC_NOINSTANCING;
  155. }
  156. DecalSet::~DecalSet() = default;
  157. void DecalSet::RegisterObject(Context* context)
  158. {
  159. context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
  160. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  161. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  162. AM_DEFAULT);
  163. URHO3D_ACCESSOR_ATTRIBUTE("Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
  164. URHO3D_ACCESSOR_ATTRIBUTE("Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
  165. URHO3D_ACCESSOR_ATTRIBUTE("Optimize Buffer Size", GetOptimizeBufferSize, SetOptimizeBufferSize, bool, false, AM_DEFAULT);
  166. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  167. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  168. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  169. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
  170. AM_FILE | AM_NOEDIT);
  171. }
  172. void DecalSet::ApplyAttributes()
  173. {
  174. if (assignBonesPending_)
  175. AssignBoneNodes();
  176. }
  177. void DecalSet::OnSetEnabled()
  178. {
  179. Drawable::OnSetEnabled();
  180. UpdateEventSubscription(true);
  181. }
  182. void DecalSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  183. {
  184. // Do not return raycast hits
  185. }
  186. void DecalSet::UpdateBatches(const FrameInfo& frame)
  187. {
  188. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  189. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  190. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  191. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  192. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  193. batches_[0].distance_ = distance_;
  194. if (!skinned_)
  195. batches_[0].worldTransform_ = &worldTransform;
  196. }
  197. void DecalSet::UpdateGeometry(const FrameInfo& frame)
  198. {
  199. if (bufferDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  200. UpdateBuffers();
  201. if (skinningDirty_)
  202. UpdateSkinning();
  203. }
  204. UpdateGeometryType DecalSet::GetUpdateGeometryType()
  205. {
  206. if (bufferDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  207. return UPDATE_MAIN_THREAD;
  208. else if (skinningDirty_)
  209. return UPDATE_WORKER_THREAD;
  210. else
  211. return UPDATE_NONE;
  212. }
  213. void DecalSet::SetMaterial(Material* material)
  214. {
  215. batches_[0].material_ = material;
  216. MarkNetworkUpdate();
  217. }
  218. void DecalSet::SetMaxVertices(unsigned num)
  219. {
  220. // Never expand to 32 bit indices
  221. num = (unsigned)Clamp(num, MIN_VERTICES, MAX_VERTICES);
  222. if (num != maxVertices_)
  223. {
  224. if (!optimizeBufferSize_)
  225. bufferDirty_ = true;
  226. maxVertices_ = num;
  227. while (decals_.Size() && numVertices_ > maxVertices_)
  228. RemoveDecals(1);
  229. MarkNetworkUpdate();
  230. }
  231. }
  232. void DecalSet::SetMaxIndices(unsigned num)
  233. {
  234. if (num < MIN_INDICES)
  235. num = MIN_INDICES;
  236. if (num != maxIndices_)
  237. {
  238. if (!optimizeBufferSize_)
  239. bufferDirty_ = true;
  240. maxIndices_ = num;
  241. while (decals_.Size() && numIndices_ > maxIndices_)
  242. RemoveDecals(1);
  243. MarkNetworkUpdate();
  244. }
  245. }
  246. void DecalSet::SetOptimizeBufferSize(bool enable)
  247. {
  248. if (enable != optimizeBufferSize_)
  249. {
  250. optimizeBufferSize_ = enable;
  251. bufferDirty_ = true;
  252. MarkNetworkUpdate();
  253. }
  254. }
  255. bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size,
  256. float aspectRatio, float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive, float normalCutoff,
  257. unsigned subGeometry)
  258. {
  259. URHO3D_PROFILE(AddDecal);
  260. // Do not add decals in headless mode
  261. if (!node_ || !GetSubsystem<Graphics>())
  262. return false;
  263. if (!target || !target->GetNode())
  264. {
  265. URHO3D_LOGERROR("Null target drawable for decal");
  266. return false;
  267. }
  268. // Check for animated target and switch into skinned/static mode if necessary
  269. auto* animatedModel = dynamic_cast<AnimatedModel*>(target);
  270. if ((animatedModel && !skinned_) || (!animatedModel && skinned_))
  271. {
  272. RemoveAllDecals();
  273. skinned_ = animatedModel != nullptr;
  274. bufferDirty_ = true;
  275. }
  276. // Center the decal frustum on the world position
  277. Vector3 adjustedWorldPosition = worldPosition - 0.5f * depth * (worldRotation * Vector3::FORWARD);
  278. /// \todo target transform is not right if adding a decal to StaticModelGroup
  279. Matrix3x4 targetTransform = target->GetNode()->GetWorldTransform().Inverse();
  280. // For an animated model, adjust the decal position back to the bind pose
  281. // To do this, need to find the bone the decal is colliding with
  282. if (animatedModel)
  283. {
  284. Skeleton& skeleton = animatedModel->GetSkeleton();
  285. unsigned numBones = skeleton.GetNumBones();
  286. Bone* bestBone = nullptr;
  287. float bestSize = 0.0f;
  288. for (unsigned i = 0; i < numBones; ++i)
  289. {
  290. Bone* bone = skeleton.GetBone(i);
  291. if (!bone->node_ || !bone->collisionMask_)
  292. continue;
  293. // Represent the decal as a sphere, try to find the biggest colliding bone
  294. Sphere decalSphere
  295. (bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size / bone->node_->GetWorldScale().Length());
  296. if (bone->collisionMask_ & BONECOLLISION_BOX)
  297. {
  298. float size = bone->boundingBox_.HalfSize().Length();
  299. if (bone->boundingBox_.IsInside(decalSphere) && size > bestSize)
  300. {
  301. bestBone = bone;
  302. bestSize = size;
  303. }
  304. }
  305. else if (bone->collisionMask_ & BONECOLLISION_SPHERE)
  306. {
  307. Sphere boneSphere(Vector3::ZERO, bone->radius_);
  308. float size = bone->radius_;
  309. if (boneSphere.IsInside(decalSphere) && size > bestSize)
  310. {
  311. bestBone = bone;
  312. bestSize = size;
  313. }
  314. }
  315. }
  316. if (bestBone)
  317. targetTransform = (bestBone->node_->GetWorldTransform() * bestBone->offsetMatrix_).Inverse();
  318. }
  319. // Build the decal frustum
  320. Frustum decalFrustum;
  321. Matrix3x4 frustumTransform = targetTransform * Matrix3x4(adjustedWorldPosition, worldRotation, 1.0f);
  322. decalFrustum.DefineOrtho(size, aspectRatio, 1.0, 0.0f, depth, frustumTransform);
  323. Vector3 decalNormal = (targetTransform * Vector4(worldRotation * Vector3::BACK, 0.0f)).Normalized();
  324. decals_.Resize(decals_.Size() + 1);
  325. Decal& newDecal = decals_.Back();
  326. newDecal.timeToLive_ = timeToLive;
  327. Vector<PODVector<DecalVertex> > faces;
  328. PODVector<DecalVertex> tempFace;
  329. unsigned numBatches = target->GetBatches().Size();
  330. // Use either a specified subgeometry in the target, or all
  331. if (subGeometry < numBatches)
  332. GetFaces(faces, target, subGeometry, decalFrustum, decalNormal, normalCutoff);
  333. else
  334. {
  335. for (unsigned i = 0; i < numBatches; ++i)
  336. GetFaces(faces, target, i, decalFrustum, decalNormal, normalCutoff);
  337. }
  338. // Clip the acquired faces against all frustum planes
  339. for (const auto& plane : decalFrustum.planes_)
  340. {
  341. for (unsigned j = 0; j < faces.Size(); ++j)
  342. {
  343. PODVector<DecalVertex>& face = faces[j];
  344. if (face.Empty())
  345. continue;
  346. ClipPolygon(tempFace, face, plane, skinned_);
  347. face = tempFace;
  348. }
  349. }
  350. // Now triangulate the resulting faces into decal vertices
  351. for (unsigned i = 0; i < faces.Size(); ++i)
  352. {
  353. PODVector<DecalVertex>& face = faces[i];
  354. if (face.Size() < 3)
  355. continue;
  356. for (unsigned j = 2; j < face.Size(); ++j)
  357. {
  358. newDecal.AddVertex(face[0]);
  359. newDecal.AddVertex(face[j - 1]);
  360. newDecal.AddVertex(face[j]);
  361. }
  362. }
  363. // Check if resulted in no triangles
  364. if (newDecal.vertices_.Empty())
  365. {
  366. decals_.Pop();
  367. return true;
  368. }
  369. if (newDecal.vertices_.Size() > maxVertices_)
  370. {
  371. URHO3D_LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
  372. String(maxVertices_));
  373. decals_.Pop();
  374. return false;
  375. }
  376. if (newDecal.indices_.Size() > maxIndices_)
  377. {
  378. URHO3D_LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
  379. String(maxIndices_));
  380. decals_.Pop();
  381. return false;
  382. }
  383. // Calculate UVs
  384. Matrix4 projection(Matrix4::ZERO);
  385. projection.m11_ = (1.0f / (size * 0.5f));
  386. projection.m00_ = projection.m11_ / aspectRatio;
  387. projection.m22_ = 1.0f / depth;
  388. projection.m33_ = 1.0f;
  389. CalculateUVs(newDecal, frustumTransform.Inverse(), projection, topLeftUV, bottomRightUV);
  390. // Transform vertices to this node's local space and generate tangents
  391. Matrix3x4 decalTransform = node_->GetWorldTransform().Inverse() * target->GetNode()->GetWorldTransform();
  392. TransformVertices(newDecal, skinned_ ? Matrix3x4::IDENTITY : decalTransform);
  393. GenerateTangents(&newDecal.vertices_[0], sizeof(DecalVertex), &newDecal.indices_[0], sizeof(unsigned short), 0,
  394. newDecal.indices_.Size(), offsetof(DecalVertex, normal_), offsetof(DecalVertex, texCoord_), offsetof(DecalVertex,
  395. tangent_));
  396. newDecal.CalculateBoundingBox();
  397. numVertices_ += newDecal.vertices_.Size();
  398. numIndices_ += newDecal.indices_.Size();
  399. // Remove oldest decals if total vertices exceeded
  400. while (decals_.Size() && (numVertices_ > maxVertices_ || numIndices_ > maxIndices_))
  401. RemoveDecals(1);
  402. URHO3D_LOGDEBUG("Added decal with " + String(newDecal.vertices_.Size()) + " vertices");
  403. // If new decal is time limited, subscribe to scene post-update
  404. if (newDecal.timeToLive_ > 0.0f && !subscribed_)
  405. UpdateEventSubscription(false);
  406. MarkDecalsDirty();
  407. return true;
  408. }
  409. void DecalSet::RemoveDecals(unsigned num)
  410. {
  411. while (num-- && decals_.Size())
  412. RemoveDecal(decals_.Begin());
  413. }
  414. void DecalSet::RemoveAllDecals()
  415. {
  416. if (!decals_.Empty())
  417. {
  418. decals_.Clear();
  419. numVertices_ = 0;
  420. numIndices_ = 0;
  421. MarkDecalsDirty();
  422. }
  423. // Remove all bones and skinning matrices and stop listening to the bone nodes
  424. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  425. {
  426. if (i->node_)
  427. i->node_->RemoveListener(this);
  428. }
  429. bones_.Clear();
  430. skinMatrices_.Clear();
  431. UpdateBatch();
  432. }
  433. Material* DecalSet::GetMaterial() const
  434. {
  435. return batches_[0].material_;
  436. }
  437. void DecalSet::SetMaterialAttr(const ResourceRef& value)
  438. {
  439. auto* cache = GetSubsystem<ResourceCache>();
  440. SetMaterial(cache->GetResource<Material>(value.name_));
  441. }
  442. void DecalSet::SetDecalsAttr(const PODVector<unsigned char>& value)
  443. {
  444. RemoveAllDecals();
  445. if (value.Empty())
  446. return;
  447. MemoryBuffer buffer(value);
  448. skinned_ = buffer.ReadBool();
  449. unsigned numDecals = buffer.ReadVLE();
  450. while (numDecals--)
  451. {
  452. decals_.Resize(decals_.Size() + 1);
  453. Decal& newDecal = decals_.Back();
  454. newDecal.timer_ = buffer.ReadFloat();
  455. newDecal.timeToLive_ = buffer.ReadFloat();
  456. newDecal.vertices_.Resize(buffer.ReadVLE());
  457. newDecal.indices_.Resize(buffer.ReadVLE());
  458. for (PODVector<DecalVertex>::Iterator i = newDecal.vertices_.Begin(); i != newDecal.vertices_.End(); ++i)
  459. {
  460. i->position_ = buffer.ReadVector3();
  461. i->normal_ = buffer.ReadVector3();
  462. i->texCoord_ = buffer.ReadVector2();
  463. i->tangent_ = buffer.ReadVector4();
  464. if (skinned_)
  465. {
  466. for (float& blendWeight : i->blendWeights_)
  467. blendWeight = buffer.ReadFloat();
  468. for (unsigned char& blendIndex : i->blendIndices_)
  469. blendIndex = buffer.ReadUByte();
  470. }
  471. }
  472. for (PODVector<unsigned short>::Iterator i = newDecal.indices_.Begin(); i != newDecal.indices_.End(); ++i)
  473. *i = buffer.ReadUShort();
  474. newDecal.CalculateBoundingBox();
  475. numVertices_ += newDecal.vertices_.Size();
  476. numIndices_ += newDecal.indices_.Size();
  477. }
  478. if (skinned_)
  479. {
  480. unsigned numBones = buffer.ReadVLE();
  481. skinMatrices_.Resize(numBones);
  482. bones_.Resize(numBones);
  483. for (unsigned i = 0; i < numBones; ++i)
  484. {
  485. Bone& newBone = bones_[i];
  486. newBone.name_ = buffer.ReadString();
  487. newBone.collisionMask_ = BoneCollisionShapeFlags(buffer.ReadUByte());
  488. if (newBone.collisionMask_ & BONECOLLISION_SPHERE)
  489. newBone.radius_ = buffer.ReadFloat();
  490. if (newBone.collisionMask_ & BONECOLLISION_BOX)
  491. newBone.boundingBox_ = buffer.ReadBoundingBox();
  492. buffer.Read(&newBone.offsetMatrix_.m00_, sizeof(Matrix3x4));
  493. }
  494. assignBonesPending_ = true;
  495. skinningDirty_ = true;
  496. }
  497. UpdateEventSubscription(true);
  498. UpdateBatch();
  499. MarkDecalsDirty();
  500. }
  501. ResourceRef DecalSet::GetMaterialAttr() const
  502. {
  503. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  504. }
  505. PODVector<unsigned char> DecalSet::GetDecalsAttr() const
  506. {
  507. VectorBuffer ret;
  508. ret.WriteBool(skinned_);
  509. ret.WriteVLE(decals_.Size());
  510. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  511. {
  512. ret.WriteFloat(i->timer_);
  513. ret.WriteFloat(i->timeToLive_);
  514. ret.WriteVLE(i->vertices_.Size());
  515. ret.WriteVLE(i->indices_.Size());
  516. for (PODVector<DecalVertex>::ConstIterator j = i->vertices_.Begin(); j != i->vertices_.End(); ++j)
  517. {
  518. ret.WriteVector3(j->position_);
  519. ret.WriteVector3(j->normal_);
  520. ret.WriteVector2(j->texCoord_);
  521. ret.WriteVector4(j->tangent_);
  522. if (skinned_)
  523. {
  524. for (float blendWeight : j->blendWeights_)
  525. ret.WriteFloat(blendWeight);
  526. for (unsigned char blendIndex : j->blendIndices_)
  527. ret.WriteUByte(blendIndex);
  528. }
  529. }
  530. for (PODVector<unsigned short>::ConstIterator j = i->indices_.Begin(); j != i->indices_.End(); ++j)
  531. ret.WriteUShort(*j);
  532. }
  533. if (skinned_)
  534. {
  535. ret.WriteVLE(bones_.Size());
  536. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  537. {
  538. ret.WriteString(i->name_);
  539. ret.WriteUByte(i->collisionMask_);
  540. if (i->collisionMask_ & BONECOLLISION_SPHERE)
  541. ret.WriteFloat(i->radius_);
  542. if (i->collisionMask_ & BONECOLLISION_BOX)
  543. ret.WriteBoundingBox(i->boundingBox_);
  544. ret.Write(i->offsetMatrix_.Data(), sizeof(Matrix3x4));
  545. }
  546. }
  547. return ret.GetBuffer();
  548. }
  549. void DecalSet::OnMarkedDirty(Node* node)
  550. {
  551. Drawable::OnMarkedDirty(node);
  552. if (skinned_)
  553. {
  554. // If the scene node or any of the bone nodes move, mark skinning dirty
  555. skinningDirty_ = true;
  556. }
  557. }
  558. void DecalSet::OnWorldBoundingBoxUpdate()
  559. {
  560. if (!skinned_)
  561. {
  562. if (boundingBoxDirty_)
  563. CalculateBoundingBox();
  564. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  565. }
  566. else
  567. {
  568. // When using skinning, update world bounding box based on the bones
  569. BoundingBox worldBox;
  570. for (Vector<Bone>::ConstIterator i = bones_.Begin(); i != bones_.End(); ++i)
  571. {
  572. Node* boneNode = i->node_;
  573. if (!boneNode)
  574. continue;
  575. // Use hitbox if available. If not, use only half of the sphere radius
  576. /// \todo The sphere radius should be multiplied with bone scale
  577. if (i->collisionMask_ & BONECOLLISION_BOX)
  578. worldBox.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  579. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  580. worldBox.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  581. }
  582. worldBoundingBox_ = worldBox;
  583. }
  584. }
  585. void DecalSet::GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
  586. const Vector3& decalNormal, float normalCutoff)
  587. {
  588. // Try to use the most accurate LOD level if possible
  589. Geometry* geometry = target->GetLodGeometry(batchIndex, 0);
  590. if (!geometry || geometry->GetPrimitiveType() != TRIANGLE_LIST)
  591. return;
  592. const unsigned char* positionData = nullptr;
  593. const unsigned char* normalData = nullptr;
  594. const unsigned char* skinningData = nullptr;
  595. const unsigned char* indexData = nullptr;
  596. unsigned positionStride = 0;
  597. unsigned normalStride = 0;
  598. unsigned skinningStride = 0;
  599. unsigned indexStride = 0;
  600. IndexBuffer* ib = geometry->GetIndexBuffer();
  601. if (ib)
  602. {
  603. indexData = ib->GetShadowData();
  604. indexStride = ib->GetIndexSize();
  605. }
  606. // For morphed models positions, normals and skinning may be in different buffers
  607. for (unsigned i = 0; i < geometry->GetNumVertexBuffers(); ++i)
  608. {
  609. VertexBuffer* vb = geometry->GetVertexBuffer(i);
  610. if (!vb)
  611. continue;
  612. unsigned elementMask = vb->GetElementMask();
  613. unsigned char* data = vb->GetShadowData();
  614. if (!data)
  615. continue;
  616. if (elementMask & MASK_POSITION)
  617. {
  618. positionData = data;
  619. positionStride = vb->GetVertexSize();
  620. }
  621. if (elementMask & MASK_NORMAL)
  622. {
  623. normalData = data + vb->GetElementOffset(SEM_NORMAL);
  624. normalStride = vb->GetVertexSize();
  625. }
  626. if (elementMask & MASK_BLENDWEIGHTS)
  627. {
  628. skinningData = data + vb->GetElementOffset(SEM_BLENDWEIGHTS);
  629. skinningStride = vb->GetVertexSize();
  630. }
  631. }
  632. // Positions and indices are needed
  633. if (!positionData)
  634. {
  635. // As a fallback, try to get the geometry's raw vertex/index data
  636. const PODVector<VertexElement>* elements;
  637. geometry->GetRawData(positionData, positionStride, indexData, indexStride, elements);
  638. if (!positionData)
  639. {
  640. URHO3D_LOGWARNING("Can not add decal, target drawable has no CPU-side geometry data");
  641. return;
  642. }
  643. }
  644. if (indexData)
  645. {
  646. unsigned indexStart = geometry->GetIndexStart();
  647. unsigned indexCount = geometry->GetIndexCount();
  648. // 16-bit indices
  649. if (indexStride == sizeof(unsigned short))
  650. {
  651. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  652. const unsigned short* indicesEnd = indices + indexCount;
  653. while (indices < indicesEnd)
  654. {
  655. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  656. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  657. indices += 3;
  658. }
  659. }
  660. else
  661. // 32-bit indices
  662. {
  663. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  664. const unsigned* indicesEnd = indices + indexCount;
  665. while (indices < indicesEnd)
  666. {
  667. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  668. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  669. indices += 3;
  670. }
  671. }
  672. }
  673. else
  674. {
  675. // Non-indexed geometry
  676. unsigned indices = geometry->GetVertexStart();
  677. unsigned indicesEnd = indices + geometry->GetVertexCount();
  678. while (indices + 2 < indicesEnd)
  679. {
  680. GetFace(faces, target, batchIndex, indices, indices + 1, indices + 2, positionData, normalData, skinningData,
  681. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  682. indices += 3;
  683. }
  684. }
  685. }
  686. void DecalSet::GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1,
  687. unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
  688. unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal,
  689. float normalCutoff)
  690. {
  691. bool hasNormals = normalData != nullptr;
  692. bool hasSkinning = skinned_ && skinningData != nullptr;
  693. const Vector3& v0 = *((const Vector3*)(&positionData[i0 * positionStride]));
  694. const Vector3& v1 = *((const Vector3*)(&positionData[i1 * positionStride]));
  695. const Vector3& v2 = *((const Vector3*)(&positionData[i2 * positionStride]));
  696. // Calculate unsmoothed face normals if no normal data
  697. Vector3 faceNormal = Vector3::ZERO;
  698. if (!hasNormals)
  699. {
  700. Vector3 dist1 = v1 - v0;
  701. Vector3 dist2 = v2 - v0;
  702. faceNormal = (dist1.CrossProduct(dist2)).Normalized();
  703. }
  704. const Vector3& n0 = hasNormals ? *((const Vector3*)(&normalData[i0 * normalStride])) : faceNormal;
  705. const Vector3& n1 = hasNormals ? *((const Vector3*)(&normalData[i1 * normalStride])) : faceNormal;
  706. const Vector3& n2 = hasNormals ? *((const Vector3*)(&normalData[i2 * normalStride])) : faceNormal;
  707. const unsigned char* s0 = hasSkinning ? &skinningData[i0 * skinningStride] : nullptr;
  708. const unsigned char* s1 = hasSkinning ? &skinningData[i1 * skinningStride] : nullptr;
  709. const unsigned char* s2 = hasSkinning ? &skinningData[i2 * skinningStride] : nullptr;
  710. // Check if face is too much away from the decal normal
  711. if (decalNormal.DotProduct((n0 + n1 + n2) / 3.0f) < normalCutoff)
  712. return;
  713. // Check if face is culled completely by any of the planes
  714. for (unsigned i = PLANE_FAR; i < NUM_FRUSTUM_PLANES; --i)
  715. {
  716. const Plane& plane = frustum.planes_[i];
  717. if (plane.Distance(v0) < 0.0f && plane.Distance(v1) < 0.0f && plane.Distance(v2) < 0.0f)
  718. return;
  719. }
  720. faces.Resize(faces.Size() + 1);
  721. PODVector<DecalVertex>& face = faces.Back();
  722. if (!hasSkinning)
  723. {
  724. face.Reserve(3);
  725. face.Push(DecalVertex(v0, n0));
  726. face.Push(DecalVertex(v1, n1));
  727. face.Push(DecalVertex(v2, n2));
  728. }
  729. else
  730. {
  731. const auto* bw0 = (const float*)s0;
  732. const auto* bw1 = (const float*)s1;
  733. const auto* bw2 = (const float*)s2;
  734. const unsigned char* bi0 = s0 + sizeof(float) * 4;
  735. const unsigned char* bi1 = s1 + sizeof(float) * 4;
  736. const unsigned char* bi2 = s2 + sizeof(float) * 4;
  737. unsigned char nbi0[4];
  738. unsigned char nbi1[4];
  739. unsigned char nbi2[4];
  740. // Make sure all bones are found and that there is room in the skinning matrices
  741. if (!GetBones(target, batchIndex, bw0, bi0, nbi0) || !GetBones(target, batchIndex, bw1, bi1, nbi1) ||
  742. !GetBones(target, batchIndex, bw2, bi2, nbi2))
  743. return;
  744. face.Reserve(3);
  745. face.Push(DecalVertex(v0, n0, bw0, nbi0));
  746. face.Push(DecalVertex(v1, n1, bw1, nbi1));
  747. face.Push(DecalVertex(v2, n2, bw2, nbi2));
  748. }
  749. }
  750. bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
  751. unsigned char* newBlendIndices)
  752. {
  753. auto* animatedModel = dynamic_cast<AnimatedModel*>(target);
  754. if (!animatedModel)
  755. return false;
  756. // Check whether target is using global or per-geometry skinning
  757. const Vector<PODVector<Matrix3x4> >& geometrySkinMatrices = animatedModel->GetGeometrySkinMatrices();
  758. const Vector<PODVector<unsigned> >& geometryBoneMappings = animatedModel->GetGeometryBoneMappings();
  759. for (unsigned i = 0; i < 4; ++i)
  760. {
  761. if (blendWeights[i] > 0.0f)
  762. {
  763. Bone* bone = nullptr;
  764. if (geometrySkinMatrices.Empty())
  765. bone = animatedModel->GetSkeleton().GetBone(blendIndices[i]);
  766. else if (blendIndices[i] < geometryBoneMappings[batchIndex].Size())
  767. bone = animatedModel->GetSkeleton().GetBone(geometryBoneMappings[batchIndex][blendIndices[i]]);
  768. if (!bone)
  769. {
  770. URHO3D_LOGWARNING("Out of range bone index for skinned decal");
  771. return false;
  772. }
  773. bool found = false;
  774. unsigned index;
  775. for (index = 0; index < bones_.Size(); ++index)
  776. {
  777. if (bones_[index].node_ == bone->node_)
  778. {
  779. // Check also that the offset matrix matches, in case we for example have a separate attachment AnimatedModel
  780. // with a different bind pose
  781. if (bones_[index].offsetMatrix_.Equals(bone->offsetMatrix_))
  782. {
  783. found = true;
  784. break;
  785. }
  786. }
  787. }
  788. if (!found)
  789. {
  790. if (bones_.Size() >= Graphics::GetMaxBones())
  791. {
  792. URHO3D_LOGWARNING("Maximum skinned decal bone count reached");
  793. return false;
  794. }
  795. else
  796. {
  797. // Copy the bone from the model to the decal
  798. index = bones_.Size();
  799. bones_.Resize(bones_.Size() + 1);
  800. bones_[index] = *bone;
  801. skinMatrices_.Resize(skinMatrices_.Size() + 1);
  802. skinningDirty_ = true;
  803. // Start listening to bone transform changes to update skinning
  804. bone->node_->AddListener(this);
  805. }
  806. }
  807. newBlendIndices[i] = (unsigned char)index;
  808. }
  809. else
  810. newBlendIndices[i] = 0;
  811. }
  812. // Update amount of shader data in the decal batch
  813. UpdateBatch();
  814. return true;
  815. }
  816. void DecalSet::CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV,
  817. const Vector2& bottomRightUV)
  818. {
  819. Matrix4 viewProj = projection * view;
  820. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  821. {
  822. Vector3 projected = viewProj * i->position_;
  823. i->texCoord_ = Vector2(
  824. Lerp(topLeftUV.x_, bottomRightUV.x_, projected.x_ * 0.5f + 0.5f),
  825. Lerp(bottomRightUV.y_, topLeftUV.y_, projected.y_ * 0.5f + 0.5f)
  826. );
  827. }
  828. }
  829. void DecalSet::TransformVertices(Decal& decal, const Matrix3x4& transform)
  830. {
  831. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  832. {
  833. i->position_ = transform * i->position_;
  834. i->normal_ = (transform * Vector4(i->normal_, 0.0f)).Normalized();
  835. }
  836. }
  837. List<Decal>::Iterator DecalSet::RemoveDecal(List<Decal>::Iterator i)
  838. {
  839. numVertices_ -= i->vertices_.Size();
  840. numIndices_ -= i->indices_.Size();
  841. MarkDecalsDirty();
  842. return decals_.Erase(i);
  843. }
  844. void DecalSet::MarkDecalsDirty()
  845. {
  846. if (!boundingBoxDirty_)
  847. {
  848. boundingBoxDirty_ = true;
  849. OnMarkedDirty(node_);
  850. }
  851. bufferDirty_ = true;
  852. }
  853. void DecalSet::CalculateBoundingBox()
  854. {
  855. boundingBox_.Clear();
  856. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  857. boundingBox_.Merge(i->boundingBox_);
  858. boundingBoxDirty_ = false;
  859. }
  860. void DecalSet::UpdateBuffers()
  861. {
  862. const VertexMaskFlags newElementMask = skinned_ ? SKINNED_ELEMENT_MASK : STATIC_ELEMENT_MASK;
  863. unsigned newVBSize = optimizeBufferSize_ ? numVertices_ : maxVertices_;
  864. unsigned newIBSize = optimizeBufferSize_ ? numIndices_ : maxIndices_;
  865. if (vertexBuffer_->GetElementMask() != newElementMask || vertexBuffer_->GetVertexCount() != newVBSize)
  866. vertexBuffer_->SetSize(newVBSize, newElementMask);
  867. if (indexBuffer_->GetIndexCount() != newIBSize)
  868. indexBuffer_->SetSize(newIBSize, false);
  869. geometry_->SetVertexBuffer(0, vertexBuffer_);
  870. geometry_->SetDrawRange(TRIANGLE_LIST, 0, numIndices_, 0, numVertices_);
  871. float* vertices = numVertices_ ? (float*)vertexBuffer_->Lock(0, numVertices_) : nullptr;
  872. unsigned short* indices = numIndices_ ? (unsigned short*)indexBuffer_->Lock(0, numIndices_) : nullptr;
  873. if (vertices && indices)
  874. {
  875. unsigned short indexStart = 0;
  876. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  877. {
  878. for (unsigned j = 0; j < i->vertices_.Size(); ++j)
  879. {
  880. const DecalVertex& vertex = i->vertices_[j];
  881. *vertices++ = vertex.position_.x_;
  882. *vertices++ = vertex.position_.y_;
  883. *vertices++ = vertex.position_.z_;
  884. *vertices++ = vertex.normal_.x_;
  885. *vertices++ = vertex.normal_.y_;
  886. *vertices++ = vertex.normal_.z_;
  887. *vertices++ = vertex.texCoord_.x_;
  888. *vertices++ = vertex.texCoord_.y_;
  889. *vertices++ = vertex.tangent_.x_;
  890. *vertices++ = vertex.tangent_.y_;
  891. *vertices++ = vertex.tangent_.z_;
  892. *vertices++ = vertex.tangent_.w_;
  893. if (skinned_)
  894. {
  895. *vertices++ = vertex.blendWeights_[0];
  896. *vertices++ = vertex.blendWeights_[1];
  897. *vertices++ = vertex.blendWeights_[2];
  898. *vertices++ = vertex.blendWeights_[3];
  899. *vertices++ = *((float*)vertex.blendIndices_);
  900. }
  901. }
  902. for (unsigned j = 0; j < i->indices_.Size(); ++j)
  903. *indices++ = i->indices_[j] + indexStart;
  904. indexStart += i->vertices_.Size();
  905. }
  906. }
  907. vertexBuffer_->Unlock();
  908. vertexBuffer_->ClearDataLost();
  909. indexBuffer_->Unlock();
  910. indexBuffer_->ClearDataLost();
  911. bufferDirty_ = false;
  912. }
  913. void DecalSet::UpdateSkinning()
  914. {
  915. // Use model's world transform in case a bone is missing
  916. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  917. for (unsigned i = 0; i < bones_.Size(); ++i)
  918. {
  919. const Bone& bone = bones_[i];
  920. if (bone.node_)
  921. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  922. else
  923. skinMatrices_[i] = worldTransform;
  924. }
  925. skinningDirty_ = false;
  926. }
  927. void DecalSet::UpdateBatch()
  928. {
  929. if (skinMatrices_.Size())
  930. {
  931. batches_[0].geometryType_ = GEOM_SKINNED;
  932. batches_[0].worldTransform_ = &skinMatrices_[0];
  933. batches_[0].numWorldTransforms_ = skinMatrices_.Size();
  934. }
  935. else
  936. {
  937. batches_[0].geometryType_ = GEOM_STATIC;
  938. batches_[0].worldTransform_ = &node_->GetWorldTransform();
  939. batches_[0].numWorldTransforms_ = 1;
  940. }
  941. }
  942. void DecalSet::AssignBoneNodes()
  943. {
  944. assignBonesPending_ = false;
  945. if (!node_)
  946. return;
  947. // Find the bone nodes from the node hierarchy and add listeners
  948. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  949. {
  950. Node* boneNode = node_->GetChild(i->name_, true);
  951. if (boneNode)
  952. boneNode->AddListener(this);
  953. i->node_ = boneNode;
  954. }
  955. }
  956. void DecalSet::UpdateEventSubscription(bool checkAllDecals)
  957. {
  958. Scene* scene = GetScene();
  959. if (!scene)
  960. return;
  961. bool enabled = IsEnabledEffective();
  962. if (enabled && checkAllDecals)
  963. {
  964. bool hasTimeLimitedDecals = false;
  965. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  966. {
  967. if (i->timeToLive_ > 0.0f)
  968. {
  969. hasTimeLimitedDecals = true;
  970. break;
  971. }
  972. }
  973. // If no time limited decals, no need to subscribe to scene update
  974. enabled = hasTimeLimitedDecals;
  975. }
  976. if (enabled && !subscribed_)
  977. {
  978. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(DecalSet, HandleScenePostUpdate));
  979. subscribed_ = true;
  980. }
  981. else if (!enabled && subscribed_)
  982. {
  983. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  984. subscribed_ = false;
  985. }
  986. }
  987. void DecalSet::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  988. {
  989. using namespace ScenePostUpdate;
  990. float timeStep = eventData[P_TIMESTEP].GetFloat();
  991. for (List<Decal>::Iterator i = decals_.Begin(); i != decals_.End();)
  992. {
  993. i->timer_ += timeStep;
  994. // Remove the decal if time to live expired
  995. if (i->timeToLive_ > 0.0f && i->timer_ > i->timeToLive_)
  996. i = RemoveDecal(i);
  997. else
  998. ++i;
  999. }
  1000. }
  1001. }