DecalSet.cpp 39 KB

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