DecalSet.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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. extern const char* GEOMETRY_CATEGORY;
  46. static const unsigned MIN_VERTICES = 4;
  47. static const unsigned MIN_INDICES = 6;
  48. static const unsigned MAX_VERTICES = 65536;
  49. static const unsigned DEFAULT_MAX_VERTICES = 512;
  50. static const unsigned DEFAULT_MAX_INDICES = 1024;
  51. static const unsigned STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
  52. static const unsigned SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT | MASK_BLENDWEIGHTS |
  53. MASK_BLENDINDICES;
  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. DecalSet::DecalSet(Context* context) :
  134. Drawable(context, DRAWABLE_GEOMETRY),
  135. geometry_(new Geometry(context)),
  136. vertexBuffer_(new VertexBuffer(context_)),
  137. indexBuffer_(new IndexBuffer(context_)),
  138. numVertices_(0),
  139. numIndices_(0),
  140. maxVertices_(DEFAULT_MAX_VERTICES),
  141. maxIndices_(DEFAULT_MAX_INDICES),
  142. skinned_(false),
  143. bufferSizeDirty_(true),
  144. bufferDirty_(true),
  145. boundingBoxDirty_(true),
  146. skinningDirty_(false),
  147. assignBonesPending_(false),
  148. subscribed_(false)
  149. {
  150. geometry_->SetIndexBuffer(indexBuffer_);
  151. batches_.Resize(1);
  152. batches_[0].geometry_ = geometry_;
  153. batches_[0].geometryType_ = GEOM_STATIC_NOINSTANCING;
  154. }
  155. DecalSet::~DecalSet()
  156. {
  157. }
  158. void DecalSet::RegisterObject(Context* context)
  159. {
  160. context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
  161. ACCESSOR_ATTRIBUTE(DecalSet, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  162. ACCESSOR_ATTRIBUTE(DecalSet, VAR_RESOURCEREF, "Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  163. ACCESSOR_ATTRIBUTE(DecalSet, VAR_INT, "Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
  164. ACCESSOR_ATTRIBUTE(DecalSet, VAR_INT, "Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
  165. ACCESSOR_ATTRIBUTE(DecalSet, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  166. ACCESSOR_ATTRIBUTE(DecalSet, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  167. COPY_BASE_ATTRIBUTES(DecalSet, Drawable);
  168. ACCESSOR_ATTRIBUTE(DecalSet, VAR_BUFFER, "Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  169. }
  170. void DecalSet::ApplyAttributes()
  171. {
  172. if (assignBonesPending_)
  173. AssignBoneNodes();
  174. }
  175. void DecalSet::OnSetEnabled()
  176. {
  177. Drawable::OnSetEnabled();
  178. UpdateEventSubscription(true);
  179. }
  180. void DecalSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  181. {
  182. // Do not return raycast hits
  183. }
  184. void DecalSet::UpdateBatches(const FrameInfo& frame)
  185. {
  186. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  187. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  188. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  189. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  190. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  191. batches_[0].distance_ = distance_;
  192. if (!skinned_)
  193. batches_[0].worldTransform_ = &worldTransform;
  194. }
  195. void DecalSet::UpdateGeometry(const FrameInfo& frame)
  196. {
  197. if (bufferSizeDirty_)
  198. UpdateBufferSize();
  199. if (bufferDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost())
  200. UpdateBuffers();
  201. if (skinningDirty_)
  202. UpdateSkinning();
  203. }
  204. UpdateGeometryType DecalSet::GetUpdateGeometryType()
  205. {
  206. if (bufferDirty_ || bufferSizeDirty_ || 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 = Clamp((int)num, MIN_VERTICES, MAX_VERTICES);
  222. if (num != maxVertices_)
  223. {
  224. bufferSizeDirty_ = true;
  225. maxVertices_ = num;
  226. while (decals_.Size() && numVertices_ > maxVertices_)
  227. RemoveDecals(1);
  228. MarkNetworkUpdate();
  229. }
  230. }
  231. void DecalSet::SetMaxIndices(unsigned num)
  232. {
  233. if (num < MIN_INDICES)
  234. num = MIN_INDICES;
  235. if (num != maxIndices_)
  236. {
  237. bufferSizeDirty_ = true;
  238. maxIndices_ = num;
  239. while (decals_.Size() && numIndices_ > maxIndices_)
  240. RemoveDecals(1);
  241. MarkNetworkUpdate();
  242. }
  243. }
  244. bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size,
  245. float aspectRatio, float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive, float normalCutoff,
  246. unsigned subGeometry)
  247. {
  248. PROFILE(AddDecal);
  249. // Do not add decals in headless mode
  250. if (!node_ || !GetSubsystem<Graphics>())
  251. return false;
  252. if (!target || !target->GetNode())
  253. {
  254. LOGERROR("Null target drawable for decal");
  255. return false;
  256. }
  257. // Check for animated target and switch into skinned/static mode if necessary
  258. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  259. if ((animatedModel && !skinned_) || (!animatedModel && skinned_))
  260. {
  261. RemoveAllDecals();
  262. skinned_ = animatedModel != 0;
  263. bufferSizeDirty_ = true;
  264. }
  265. // Center the decal frustum on the world position
  266. Vector3 adjustedWorldPosition = worldPosition - 0.5f * depth * (worldRotation * Vector3::FORWARD);
  267. Matrix3x4 targetTransform = target->GetNode()->GetWorldTransform().Inverse();
  268. // For an animated model, adjust the decal position back to the bind pose
  269. // To do this, need to find the bone the decal is colliding with
  270. if (animatedModel)
  271. {
  272. Skeleton& skeleton = animatedModel->GetSkeleton();
  273. unsigned numBones = skeleton.GetNumBones();
  274. Bone* bestBone = 0;
  275. float bestSize = 0.0f;
  276. for (unsigned i = 0; i < numBones; ++i)
  277. {
  278. Bone* bone = skeleton.GetBone(i);
  279. if (!bone->node_ || !bone->collisionMask_)
  280. continue;
  281. // Represent the decal as a sphere, try to find the biggest colliding bone
  282. Sphere decalSphere(bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size /
  283. bone->node_->GetWorldScale().Length());
  284. if (bone->collisionMask_ & BONECOLLISION_BOX)
  285. {
  286. float size = bone->boundingBox_.HalfSize().Length();
  287. if (bone->boundingBox_.IsInside(decalSphere) && size > bestSize)
  288. {
  289. bestBone = bone;
  290. bestSize = size;
  291. }
  292. }
  293. else if (bone->collisionMask_ & BONECOLLISION_SPHERE)
  294. {
  295. Sphere boneSphere(Vector3::ZERO, bone->radius_);
  296. float size = bone->radius_;
  297. if (boneSphere.IsInside(decalSphere) && size > bestSize)
  298. {
  299. bestBone = bone;
  300. bestSize = size;
  301. }
  302. }
  303. }
  304. if (bestBone)
  305. targetTransform = (bestBone->node_->GetWorldTransform() * bestBone->offsetMatrix_).Inverse();
  306. }
  307. // Build the decal frustum
  308. Frustum decalFrustum;
  309. Matrix3x4 frustumTransform = targetTransform * Matrix3x4(adjustedWorldPosition, worldRotation, 1.0f);
  310. decalFrustum.DefineOrtho(size, aspectRatio, 1.0, 0.0f, depth, frustumTransform);
  311. Vector3 decalNormal = (targetTransform * Vector4(worldRotation * Vector3::BACK, 0.0f)).Normalized();
  312. decals_.Resize(decals_.Size() + 1);
  313. Decal& newDecal = decals_.Back();
  314. newDecal.timeToLive_ = timeToLive;
  315. Vector<PODVector<DecalVertex> > faces;
  316. PODVector<DecalVertex> tempFace;
  317. unsigned numBatches = target->GetBatches().Size();
  318. // Use either a specified subgeometry in the target, or all
  319. if (subGeometry < numBatches)
  320. GetFaces(faces, target, subGeometry, decalFrustum, decalNormal, normalCutoff);
  321. else
  322. {
  323. for (unsigned i = 0; i < numBatches; ++i)
  324. GetFaces(faces, target, i, decalFrustum, decalNormal, normalCutoff);
  325. }
  326. // Clip the acquired faces against all frustum planes
  327. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  328. {
  329. for (unsigned j = 0; j < faces.Size(); ++j)
  330. {
  331. PODVector<DecalVertex>& face = faces[j];
  332. if (face.Empty())
  333. continue;
  334. ClipPolygon(tempFace, face, decalFrustum.planes_[i], skinned_);
  335. face = tempFace;
  336. }
  337. }
  338. // Now triangulate the resulting faces into decal vertices
  339. for (unsigned i = 0; i < faces.Size(); ++i)
  340. {
  341. PODVector<DecalVertex>& face = faces[i];
  342. if (face.Size() < 3)
  343. continue;
  344. for (unsigned j = 2; j < face.Size(); ++j)
  345. {
  346. newDecal.AddVertex(face[0]);
  347. newDecal.AddVertex(face[j - 1]);
  348. newDecal.AddVertex(face[j]);
  349. }
  350. }
  351. // Check if resulted in no triangles
  352. if (newDecal.vertices_.Empty())
  353. {
  354. decals_.Pop();
  355. return true;
  356. }
  357. if (newDecal.vertices_.Size() > maxVertices_)
  358. {
  359. LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
  360. String(maxVertices_));
  361. decals_.Pop();
  362. return false;
  363. }
  364. if (newDecal.indices_.Size() > maxIndices_)
  365. {
  366. LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
  367. String(maxIndices_));
  368. decals_.Pop();
  369. return false;
  370. }
  371. // Calculate UVs
  372. Matrix4 projection(Matrix4::ZERO);
  373. projection.m11_ = (1.0f / (size * 0.5f));
  374. projection.m00_ = projection.m11_ / aspectRatio;
  375. projection.m22_ = 1.0f / depth;
  376. projection.m33_ = 1.0f;
  377. CalculateUVs(newDecal, frustumTransform.Inverse(), projection, topLeftUV, bottomRightUV);
  378. // Transform vertices to this node's local space and generate tangents
  379. Matrix3x4 decalTransform = node_->GetWorldTransform().Inverse() * target->GetNode()->GetWorldTransform();
  380. TransformVertices(newDecal, skinned_ ? Matrix3x4::IDENTITY : decalTransform);
  381. GenerateTangents(&newDecal.vertices_[0], sizeof(DecalVertex), &newDecal.indices_[0], sizeof(unsigned short), 0,
  382. newDecal.indices_.Size(), offsetof(DecalVertex, normal_), offsetof(DecalVertex, texCoord_), offsetof(DecalVertex,
  383. tangent_));
  384. newDecal.CalculateBoundingBox();
  385. numVertices_ += newDecal.vertices_.Size();
  386. numIndices_ += newDecal.indices_.Size();
  387. // Remove oldest decals if total vertices exceeded
  388. while (decals_.Size() && (numVertices_ > maxVertices_ || numIndices_ > maxIndices_))
  389. RemoveDecals(1);
  390. LOGDEBUG("Added decal with " + String(newDecal.vertices_.Size()) + " vertices");
  391. // If new decal is time limited, subscribe to scene post-update
  392. if (newDecal.timeToLive_ > 0.0f && !subscribed_)
  393. UpdateEventSubscription(false);
  394. MarkDecalsDirty();
  395. return true;
  396. }
  397. void DecalSet::RemoveDecals(unsigned num)
  398. {
  399. while (num-- && decals_.Size())
  400. RemoveDecal(decals_.Begin());
  401. }
  402. void DecalSet::RemoveAllDecals()
  403. {
  404. if (!decals_.Empty())
  405. {
  406. decals_.Clear();
  407. numVertices_ = 0;
  408. numIndices_ = 0;
  409. MarkDecalsDirty();
  410. }
  411. // Remove all bones and skinning matrices and stop listening to the bone nodes
  412. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  413. {
  414. if (i->node_)
  415. i->node_->RemoveListener(this);
  416. }
  417. bones_.Clear();
  418. skinMatrices_.Clear();
  419. UpdateBatch();
  420. }
  421. Material* DecalSet::GetMaterial() const
  422. {
  423. return batches_[0].material_;
  424. }
  425. void DecalSet::SetMaterialAttr(ResourceRef value)
  426. {
  427. ResourceCache* cache = GetSubsystem<ResourceCache>();
  428. SetMaterial(cache->GetResource<Material>(value.id_));
  429. }
  430. void DecalSet::SetDecalsAttr(PODVector<unsigned char> value)
  431. {
  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. /// \todo The sphere radius should be multiplied with bone scale
  566. if (i->collisionMask_ & BONECOLLISION_BOX)
  567. worldBoundingBox_.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  568. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  569. worldBoundingBox_.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  570. }
  571. }
  572. }
  573. void DecalSet::GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
  574. const Vector3& decalNormal, float normalCutoff)
  575. {
  576. // Try to use the most accurate LOD level if possible
  577. Geometry* geometry = target->GetLodGeometry(batchIndex, 0);
  578. if (!geometry || geometry->GetPrimitiveType() != TRIANGLE_LIST)
  579. return;
  580. const unsigned char* positionData = 0;
  581. const unsigned char* normalData = 0;
  582. const unsigned char* skinningData = 0;
  583. const unsigned char* indexData = 0;
  584. unsigned positionStride = 0;
  585. unsigned normalStride = 0;
  586. unsigned skinningStride = 0;
  587. unsigned indexStride = 0;
  588. IndexBuffer* ib = geometry->GetIndexBuffer();
  589. if (ib)
  590. {
  591. indexData = ib->GetShadowData();
  592. indexStride = ib->GetIndexSize();
  593. }
  594. // For morphed models positions, normals and skinning may be in different buffers
  595. for (unsigned i = 0; i < geometry->GetNumVertexBuffers(); ++i)
  596. {
  597. VertexBuffer* vb = geometry->GetVertexBuffer(i);
  598. if (!vb)
  599. continue;
  600. unsigned elementMask = geometry->GetVertexElementMask(i);
  601. unsigned char* data = vb->GetShadowData();
  602. if (!data)
  603. continue;
  604. if (elementMask & MASK_POSITION)
  605. {
  606. positionData = data;
  607. positionStride = vb->GetVertexSize();
  608. }
  609. if (elementMask & MASK_NORMAL)
  610. {
  611. normalData = data + vb->GetElementOffset(ELEMENT_NORMAL);
  612. normalStride = vb->GetVertexSize();
  613. }
  614. if (elementMask & MASK_BLENDWEIGHTS)
  615. {
  616. skinningData = data + vb->GetElementOffset(ELEMENT_BLENDWEIGHTS);
  617. skinningStride = vb->GetVertexSize();
  618. }
  619. }
  620. // Positions and indices are needed
  621. if (!positionData)
  622. {
  623. // As a fallback, try to get the geometry's raw vertex/index data
  624. unsigned elementMask;
  625. geometry->GetRawData(positionData, positionStride, indexData, indexStride, elementMask);
  626. if (!positionData)
  627. {
  628. LOGWARNING("Can not add decal, target drawable has no CPU-side geometry data");
  629. return;
  630. }
  631. }
  632. if (indexData)
  633. {
  634. unsigned indexStart = geometry->GetIndexStart();
  635. unsigned indexCount = geometry->GetIndexCount();
  636. // 16-bit indices
  637. if (indexStride == sizeof(unsigned short))
  638. {
  639. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  640. const unsigned short* indicesEnd = indices + indexCount;
  641. while (indices < indicesEnd)
  642. {
  643. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  644. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  645. indices += 3;
  646. }
  647. }
  648. else
  649. // 32-bit indices
  650. {
  651. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  652. const unsigned* 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. }
  661. else
  662. {
  663. // Non-indexed geometry
  664. unsigned indices = geometry->GetVertexStart();
  665. unsigned indicesEnd = indices + geometry->GetVertexCount();
  666. while (indices + 2 < indicesEnd)
  667. {
  668. GetFace(faces, target, batchIndex, indices, indices + 1, indices + 2, positionData, normalData, skinningData,
  669. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  670. indices += 3;
  671. }
  672. }
  673. }
  674. void DecalSet::GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1,
  675. unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
  676. unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal,
  677. float normalCutoff)
  678. {
  679. bool hasNormals = normalData != 0;
  680. bool hasSkinning = skinned_ && skinningData != 0;
  681. const Vector3& v0 = *((const Vector3*)(&positionData[i0 * positionStride]));
  682. const Vector3& v1 = *((const Vector3*)(&positionData[i1 * positionStride]));
  683. const Vector3& v2 = *((const Vector3*)(&positionData[i2 * positionStride]));
  684. // Calculate unsmoothed face normals if no normal data
  685. Vector3 faceNormal = Vector3::ZERO;
  686. if (!hasNormals)
  687. {
  688. Vector3 dist1 = v1 - v0;
  689. Vector3 dist2 = v2 - v0;
  690. faceNormal = (dist1.CrossProduct(dist2)).Normalized();
  691. }
  692. const Vector3& n0 = hasNormals ? *((const Vector3*)(&normalData[i0 * normalStride])) : faceNormal;
  693. const Vector3& n1 = hasNormals ? *((const Vector3*)(&normalData[i1 * normalStride])) : faceNormal;
  694. const Vector3& n2 = hasNormals ? *((const Vector3*)(&normalData[i2 * normalStride])) : faceNormal;
  695. const unsigned char* s0 = hasSkinning ? &skinningData[i0 * skinningStride] : (const unsigned char*)0;
  696. const unsigned char* s1 = hasSkinning ? &skinningData[i1 * skinningStride] : (const unsigned char*)0;
  697. const unsigned char* s2 = hasSkinning ? &skinningData[i2 * skinningStride] : (const unsigned char*)0;
  698. // Check if face is too much away from the decal normal
  699. if (decalNormal.DotProduct((n0 + n1 + n2) / 3.0f) < normalCutoff)
  700. return;
  701. // Check if face is culled completely by any of the planes
  702. for (unsigned i = PLANE_FAR; i < NUM_FRUSTUM_PLANES; --i)
  703. {
  704. const Plane& plane = frustum.planes_[i];
  705. if (plane.Distance(v0) < 0.0f && plane.Distance(v1) < 0.0f && plane.Distance(v2) < 0.0f)
  706. return;
  707. }
  708. faces.Resize(faces.Size() + 1);
  709. PODVector<DecalVertex>& face = faces.Back();
  710. if (!hasSkinning)
  711. {
  712. face.Reserve(3);
  713. face.Push(DecalVertex(v0, n0));
  714. face.Push(DecalVertex(v1, n1));
  715. face.Push(DecalVertex(v2, n2));
  716. }
  717. else
  718. {
  719. const float* bw0 = (const float*)s0;
  720. const float* bw1 = (const float*)s1;
  721. const float* bw2 = (const float*)s2;
  722. const unsigned char* bi0 = s0 + sizeof(float) * 4;
  723. const unsigned char* bi1 = s1 + sizeof(float) * 4;
  724. const unsigned char* bi2 = s2 + sizeof(float) * 4;
  725. unsigned char nbi0[4];
  726. unsigned char nbi1[4];
  727. unsigned char nbi2[4];
  728. // Make sure all bones are found and that there is room in the skinning matrices
  729. if (!GetBones(target, batchIndex, bw0, bi0, nbi0) || !GetBones(target, batchIndex, bw1, bi1, nbi1) ||
  730. !GetBones(target, batchIndex, bw2, bi2, nbi2))
  731. return;
  732. face.Reserve(3);
  733. face.Push(DecalVertex(v0, n0, bw0, nbi0));
  734. face.Push(DecalVertex(v1, n1, bw1, nbi1));
  735. face.Push(DecalVertex(v2, n2, bw2, nbi2));
  736. }
  737. }
  738. bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
  739. unsigned char* newBlendIndices)
  740. {
  741. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  742. if (!animatedModel)
  743. return false;
  744. // Check whether target is using global or per-geometry skinning
  745. const Vector<PODVector<Matrix3x4> >& geometrySkinMatrices = animatedModel->GetGeometrySkinMatrices();
  746. const Vector<PODVector<unsigned> >& geometryBoneMappings = animatedModel->GetGeometryBoneMappings();
  747. for (unsigned i = 0; i < 4; ++i)
  748. {
  749. if (blendWeights[i] > 0.0f)
  750. {
  751. Bone* bone = 0;
  752. if (geometrySkinMatrices.Empty())
  753. bone = animatedModel->GetSkeleton().GetBone(blendIndices[i]);
  754. else if (blendIndices[i] < geometryBoneMappings[batchIndex].Size())
  755. bone = animatedModel->GetSkeleton().GetBone(geometryBoneMappings[batchIndex][blendIndices[i]]);
  756. if (!bone)
  757. {
  758. LOGWARNING("Out of range bone index for skinned decal");
  759. return false;
  760. }
  761. bool found = false;
  762. unsigned index;
  763. for (index = 0; index < bones_.Size(); ++index)
  764. {
  765. if (bones_[index].node_ == bone->node_)
  766. {
  767. // Check also that the offset matrix matches, in case we for example have a separate attachment AnimatedModel
  768. // with a different bind pose
  769. if (bones_[index].offsetMatrix_.Equals(bone->offsetMatrix_))
  770. {
  771. found = true;
  772. break;
  773. }
  774. }
  775. }
  776. if (!found)
  777. {
  778. if (bones_.Size() >= MAX_SKIN_MATRICES)
  779. {
  780. LOGWARNING("Maximum skinned decal bone count reached");
  781. return false;
  782. }
  783. else
  784. {
  785. // Copy the bone from the model to the decal
  786. index = bones_.Size();
  787. bones_.Resize(bones_.Size() + 1);
  788. bones_[index] = *bone;
  789. skinMatrices_.Resize(skinMatrices_.Size() + 1);
  790. skinningDirty_ = true;
  791. // Start listening to bone transform changes to update skinning
  792. bone->node_->AddListener(this);
  793. }
  794. }
  795. newBlendIndices[i] = index;
  796. }
  797. else
  798. newBlendIndices[i] = 0;
  799. }
  800. // Update amount of shader data in the decal batch
  801. UpdateBatch();
  802. return true;
  803. }
  804. void DecalSet::CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV,
  805. const Vector2& bottomRightUV)
  806. {
  807. Matrix4 viewProj = projection * view;
  808. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  809. {
  810. Vector3 projected = viewProj * i->position_;
  811. i->texCoord_ = Vector2(
  812. Lerp(topLeftUV.x_, bottomRightUV.x_, projected.x_ * 0.5f + 0.5f),
  813. Lerp(bottomRightUV.y_, topLeftUV.y_, projected.y_ * 0.5f + 0.5f)
  814. );
  815. }
  816. }
  817. void DecalSet::TransformVertices(Decal& decal, const Matrix3x4& transform)
  818. {
  819. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  820. {
  821. i->position_ = transform * i->position_;
  822. i->normal_ = (transform * i->normal_).Normalized();
  823. }
  824. }
  825. List<Decal>::Iterator DecalSet::RemoveDecal(List<Decal>::Iterator i)
  826. {
  827. numVertices_ -= i->vertices_.Size();
  828. numIndices_ -= i->indices_.Size();
  829. MarkDecalsDirty();
  830. return decals_.Erase(i);
  831. }
  832. void DecalSet::MarkDecalsDirty()
  833. {
  834. if (!boundingBoxDirty_)
  835. {
  836. boundingBoxDirty_ = true;
  837. OnMarkedDirty(node_);
  838. }
  839. bufferDirty_ = true;
  840. }
  841. void DecalSet::CalculateBoundingBox()
  842. {
  843. boundingBox_.Clear();
  844. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  845. boundingBox_.Merge(i->boundingBox_);
  846. boundingBoxDirty_ = false;
  847. }
  848. void DecalSet::UpdateBufferSize()
  849. {
  850. vertexBuffer_->SetSize(maxVertices_, skinned_ ? SKINNED_ELEMENT_MASK : STATIC_ELEMENT_MASK);
  851. indexBuffer_->SetSize(maxIndices_, false);
  852. geometry_->SetVertexBuffer(0, vertexBuffer_);
  853. bufferDirty_ = true;
  854. bufferSizeDirty_ = false;
  855. }
  856. void DecalSet::UpdateBuffers()
  857. {
  858. geometry_->SetDrawRange(TRIANGLE_LIST, 0, numIndices_, 0, numVertices_);
  859. float* vertices = (float*)vertexBuffer_->Lock(0, numVertices_);
  860. unsigned short* indices = (unsigned short*)indexBuffer_->Lock(0, numIndices_);
  861. unsigned short indexStart = 0;
  862. if (vertices && indices)
  863. {
  864. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  865. {
  866. for (unsigned j = 0; j < i->vertices_.Size(); ++j)
  867. {
  868. const DecalVertex& vertex = i->vertices_[j];
  869. *vertices++ = vertex.position_.x_;
  870. *vertices++ = vertex.position_.y_;
  871. *vertices++ = vertex.position_.z_;
  872. *vertices++ = vertex.normal_.x_;
  873. *vertices++ = vertex.normal_.y_;
  874. *vertices++ = vertex.normal_.z_;
  875. *vertices++ = vertex.texCoord_.x_;
  876. *vertices++ = vertex.texCoord_.y_;
  877. *vertices++ = vertex.tangent_.x_;
  878. *vertices++ = vertex.tangent_.y_;
  879. *vertices++ = vertex.tangent_.z_;
  880. *vertices++ = vertex.tangent_.w_;
  881. if (skinned_)
  882. {
  883. *vertices++ = vertex.blendWeights_[0];
  884. *vertices++ = vertex.blendWeights_[1];
  885. *vertices++ = vertex.blendWeights_[2];
  886. *vertices++ = vertex.blendWeights_[3];
  887. *vertices++ = *((float*)vertex.blendIndices_);
  888. }
  889. }
  890. for (unsigned j = 0; j < i->indices_.Size(); ++j)
  891. *indices++ = i->indices_[j] + indexStart;
  892. indexStart += i->vertices_.Size();
  893. }
  894. }
  895. vertexBuffer_->Unlock();
  896. vertexBuffer_->ClearDataLost();
  897. indexBuffer_->Unlock();
  898. indexBuffer_->ClearDataLost();
  899. bufferDirty_ = false;
  900. }
  901. void DecalSet::UpdateSkinning()
  902. {
  903. // Use model's world transform in case a bone is missing
  904. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  905. for (unsigned i = 0; i < bones_.Size(); ++i)
  906. {
  907. const Bone& bone = bones_[i];
  908. if (bone.node_)
  909. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  910. else
  911. skinMatrices_[i] = worldTransform;
  912. }
  913. skinningDirty_ = false;
  914. }
  915. void DecalSet::UpdateBatch()
  916. {
  917. if (skinMatrices_.Size())
  918. {
  919. batches_[0].geometryType_ = GEOM_SKINNED;
  920. batches_[0].worldTransform_ = &skinMatrices_[0];
  921. batches_[0].numWorldTransforms_ = skinMatrices_.Size();
  922. }
  923. else
  924. {
  925. batches_[0].geometryType_ = GEOM_STATIC;
  926. batches_[0].worldTransform_ = &node_->GetWorldTransform();
  927. batches_[0].numWorldTransforms_ = 1;
  928. }
  929. }
  930. void DecalSet::AssignBoneNodes()
  931. {
  932. assignBonesPending_ = false;
  933. if (!node_)
  934. return;
  935. // Find the bone nodes from the node hierarchy and add listeners
  936. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  937. {
  938. Node* boneNode = node_->GetChild(i->name_, true);
  939. if (boneNode)
  940. boneNode->AddListener(this);
  941. i->node_ = boneNode;
  942. }
  943. }
  944. void DecalSet::UpdateEventSubscription(bool checkAllDecals)
  945. {
  946. Scene* scene = GetScene();
  947. if (!scene)
  948. return;
  949. bool enabled = IsEnabledEffective();
  950. if (enabled && checkAllDecals)
  951. {
  952. bool hasTimeLimitedDecals = false;
  953. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  954. {
  955. if (i->timeToLive_ > 0.0f)
  956. {
  957. hasTimeLimitedDecals = true;
  958. break;
  959. }
  960. }
  961. // If no time limited decals, no need to subscribe to scene update
  962. enabled = hasTimeLimitedDecals;
  963. }
  964. if (enabled && !subscribed_)
  965. {
  966. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(DecalSet, HandleScenePostUpdate));
  967. subscribed_ = true;
  968. }
  969. else if (!enabled && subscribed_)
  970. {
  971. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  972. subscribed_ = false;
  973. }
  974. }
  975. void DecalSet::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  976. {
  977. using namespace ScenePostUpdate;
  978. float timeStep = eventData[P_TIMESTEP].GetFloat();
  979. for (List<Decal>::Iterator i = decals_.Begin(); i != decals_.End();)
  980. {
  981. i->timer_ += timeStep;
  982. // Remove the decal if time to live expired
  983. if (i->timeToLive_ > 0.0f && i->timer_ > i->timeToLive_)
  984. i = RemoveDecal(i);
  985. else
  986. ++i;
  987. }
  988. }
  989. }