DecalSet.cpp 39 KB

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