DecalSet.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. //
  2. // Copyright (c) 2008-2015 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 "../Graphics/AnimatedModel.h"
  23. #include "../Graphics/Batch.h"
  24. #include "../Graphics/Camera.h"
  25. #include "../Core/Context.h"
  26. #include "../Graphics/DecalSet.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Graphics.h"
  29. #include "../Graphics/IndexBuffer.h"
  30. #include "../IO/Log.h"
  31. #include "../Graphics/Material.h"
  32. #include "../IO/MemoryBuffer.h"
  33. #include "../Scene/Node.h"
  34. #include "../Core/Profiler.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Scene/Scene.h"
  37. #include "../Scene/SceneEvents.h"
  38. #include "../Graphics/Tangent.h"
  39. #include "../IO/VectorBuffer.h"
  40. #include "../Graphics/VertexBuffer.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. extern const char* GEOMETRY_CATEGORY;
  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. static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
  54. {
  55. DecalVertex ret;
  56. float t = d0 / (d0 - d1);
  57. ret.position_ = v0.position_ + t * (v1.position_ - v0.position_);
  58. ret.normal_ = v0.normal_ + t * (v1.normal_ - v0.normal_);
  59. if (skinned)
  60. {
  61. if (*((unsigned*)v0.blendIndices_) != *((unsigned*)v1.blendIndices_))
  62. {
  63. // Blend weights and indices: if indices are different, choose the vertex nearer to the split plane
  64. const DecalVertex& src = Abs(d0) < Abs(d1) ? v0 : v1;
  65. for (unsigned i = 0; i < 4; ++i)
  66. {
  67. ret.blendWeights_[i] = src.blendWeights_[i];
  68. ret.blendIndices_[i] = src.blendIndices_[i];
  69. }
  70. }
  71. else
  72. {
  73. // If indices are same, can interpolate the weights
  74. for (unsigned i = 0; i < 4; ++i)
  75. {
  76. ret.blendWeights_[i] = v0.blendWeights_[i] + t * (v1.blendWeights_[i] - v0.blendWeights_[i]);
  77. ret.blendIndices_[i] = v0.blendIndices_[i];
  78. }
  79. }
  80. }
  81. return ret;
  82. }
  83. static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
  84. {
  85. unsigned last;
  86. float lastDistance = 0.0f;
  87. dest.Clear();
  88. if (src.Empty())
  89. return;
  90. for (unsigned i = 0; i < src.Size(); ++i)
  91. {
  92. float distance = plane.Distance(src[i].position_);
  93. if (distance >= 0.0f)
  94. {
  95. if (lastDistance < 0.0f)
  96. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  97. dest.Push(src[i]);
  98. }
  99. else
  100. {
  101. if (lastDistance >= 0.0f && i != 0)
  102. dest.Push(ClipEdge(src[last], src[i], lastDistance, distance, skinned));
  103. }
  104. last = i;
  105. lastDistance = distance;
  106. }
  107. // Recheck the distances of the last and first vertices and add the final clipped vertex if applicable
  108. float distance = plane.Distance(src[0].position_);
  109. if ((lastDistance < 0.0f && distance >= 0.0f) || (lastDistance >= 0.0f && distance < 0.0f))
  110. dest.Push(ClipEdge(src[last], src[0], lastDistance, distance, skinned));
  111. }
  112. void Decal::AddVertex(const DecalVertex& vertex)
  113. {
  114. for (unsigned i = 0; i < vertices_.Size(); ++i)
  115. {
  116. if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
  117. {
  118. indices_.Push(i);
  119. return;
  120. }
  121. }
  122. unsigned short newIndex = vertices_.Size();
  123. vertices_.Push(vertex);
  124. indices_.Push(newIndex);
  125. }
  126. void Decal::CalculateBoundingBox()
  127. {
  128. boundingBox_.Clear();
  129. for (unsigned i = 0; i < vertices_.Size(); ++i)
  130. boundingBox_.Merge(vertices_[i].position_);
  131. }
  132. DecalSet::DecalSet(Context* context) :
  133. Drawable(context, DRAWABLE_GEOMETRY),
  134. geometry_(new Geometry(context)),
  135. vertexBuffer_(new VertexBuffer(context_)),
  136. indexBuffer_(new IndexBuffer(context_)),
  137. numVertices_(0),
  138. numIndices_(0),
  139. maxVertices_(DEFAULT_MAX_VERTICES),
  140. maxIndices_(DEFAULT_MAX_INDICES),
  141. skinned_(false),
  142. bufferSizeDirty_(true),
  143. bufferDirty_(true),
  144. boundingBoxDirty_(true),
  145. skinningDirty_(false),
  146. assignBonesPending_(false),
  147. subscribed_(false)
  148. {
  149. geometry_->SetIndexBuffer(indexBuffer_);
  150. batches_.Resize(1);
  151. batches_[0].geometry_ = geometry_;
  152. batches_[0].geometryType_ = GEOM_STATIC_NOINSTANCING;
  153. }
  154. DecalSet::~DecalSet()
  155. {
  156. }
  157. void DecalSet::RegisterObject(Context* context)
  158. {
  159. context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
  160. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  161. MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
  162. ACCESSOR_ATTRIBUTE("Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
  163. ACCESSOR_ATTRIBUTE("Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
  164. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  165. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  166. COPY_BASE_ATTRIBUTES(Drawable);
  167. MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  168. }
  169. void DecalSet::ApplyAttributes()
  170. {
  171. if (assignBonesPending_)
  172. AssignBoneNodes();
  173. }
  174. void DecalSet::OnSetEnabled()
  175. {
  176. Drawable::OnSetEnabled();
  177. UpdateEventSubscription(true);
  178. }
  179. void DecalSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  180. {
  181. // Do not return raycast hits
  182. }
  183. void DecalSet::UpdateBatches(const FrameInfo& frame)
  184. {
  185. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  186. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  187. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  188. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  189. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  190. batches_[0].distance_ = distance_;
  191. if (!skinned_)
  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. /// \todo target transform is not right if adding a decal to StaticModelGroup
  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(const ResourceRef& value)
  426. {
  427. ResourceCache* cache = GetSubsystem<ResourceCache>();
  428. SetMaterial(cache->GetResource<Material>(value.name_));
  429. }
  430. void DecalSet::SetDecalsAttr(const 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. BoundingBox worldBox;
  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. worldBox.Merge(i->boundingBox_.Transformed(boneNode->GetWorldTransform()));
  568. else if (i->collisionMask_ & BONECOLLISION_SPHERE)
  569. worldBox.Merge(Sphere(boneNode->GetWorldPosition(), i->radius_ * 0.5f));
  570. }
  571. worldBoundingBox_ = worldBox;
  572. }
  573. }
  574. void DecalSet::GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
  575. const Vector3& decalNormal, float normalCutoff)
  576. {
  577. // Try to use the most accurate LOD level if possible
  578. Geometry* geometry = target->GetLodGeometry(batchIndex, 0);
  579. if (!geometry || geometry->GetPrimitiveType() != TRIANGLE_LIST)
  580. return;
  581. const unsigned char* positionData = 0;
  582. const unsigned char* normalData = 0;
  583. const unsigned char* skinningData = 0;
  584. const unsigned char* indexData = 0;
  585. unsigned positionStride = 0;
  586. unsigned normalStride = 0;
  587. unsigned skinningStride = 0;
  588. unsigned indexStride = 0;
  589. IndexBuffer* ib = geometry->GetIndexBuffer();
  590. if (ib)
  591. {
  592. indexData = ib->GetShadowData();
  593. indexStride = ib->GetIndexSize();
  594. }
  595. // For morphed models positions, normals and skinning may be in different buffers
  596. for (unsigned i = 0; i < geometry->GetNumVertexBuffers(); ++i)
  597. {
  598. VertexBuffer* vb = geometry->GetVertexBuffer(i);
  599. if (!vb)
  600. continue;
  601. unsigned elementMask = geometry->GetVertexElementMask(i);
  602. unsigned char* data = vb->GetShadowData();
  603. if (!data)
  604. continue;
  605. if (elementMask & MASK_POSITION)
  606. {
  607. positionData = data;
  608. positionStride = vb->GetVertexSize();
  609. }
  610. if (elementMask & MASK_NORMAL)
  611. {
  612. normalData = data + vb->GetElementOffset(ELEMENT_NORMAL);
  613. normalStride = vb->GetVertexSize();
  614. }
  615. if (elementMask & MASK_BLENDWEIGHTS)
  616. {
  617. skinningData = data + vb->GetElementOffset(ELEMENT_BLENDWEIGHTS);
  618. skinningStride = vb->GetVertexSize();
  619. }
  620. }
  621. // Positions and indices are needed
  622. if (!positionData)
  623. {
  624. // As a fallback, try to get the geometry's raw vertex/index data
  625. unsigned elementMask;
  626. geometry->GetRawData(positionData, positionStride, indexData, indexStride, elementMask);
  627. if (!positionData)
  628. {
  629. LOGWARNING("Can not add decal, target drawable has no CPU-side geometry data");
  630. return;
  631. }
  632. }
  633. if (indexData)
  634. {
  635. unsigned indexStart = geometry->GetIndexStart();
  636. unsigned indexCount = geometry->GetIndexCount();
  637. // 16-bit indices
  638. if (indexStride == sizeof(unsigned short))
  639. {
  640. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  641. const unsigned short* indicesEnd = indices + indexCount;
  642. while (indices < indicesEnd)
  643. {
  644. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  645. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  646. indices += 3;
  647. }
  648. }
  649. else
  650. // 32-bit indices
  651. {
  652. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  653. const unsigned* indicesEnd = indices + indexCount;
  654. while (indices < indicesEnd)
  655. {
  656. GetFace(faces, target, batchIndex, indices[0], indices[1], indices[2], positionData, normalData, skinningData,
  657. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  658. indices += 3;
  659. }
  660. }
  661. }
  662. else
  663. {
  664. // Non-indexed geometry
  665. unsigned indices = geometry->GetVertexStart();
  666. unsigned indicesEnd = indices + geometry->GetVertexCount();
  667. while (indices + 2 < indicesEnd)
  668. {
  669. GetFace(faces, target, batchIndex, indices, indices + 1, indices + 2, positionData, normalData, skinningData,
  670. positionStride, normalStride, skinningStride, frustum, decalNormal, normalCutoff);
  671. indices += 3;
  672. }
  673. }
  674. }
  675. void DecalSet::GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1,
  676. unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
  677. unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal,
  678. float normalCutoff)
  679. {
  680. bool hasNormals = normalData != 0;
  681. bool hasSkinning = skinned_ && skinningData != 0;
  682. const Vector3& v0 = *((const Vector3*)(&positionData[i0 * positionStride]));
  683. const Vector3& v1 = *((const Vector3*)(&positionData[i1 * positionStride]));
  684. const Vector3& v2 = *((const Vector3*)(&positionData[i2 * positionStride]));
  685. // Calculate unsmoothed face normals if no normal data
  686. Vector3 faceNormal = Vector3::ZERO;
  687. if (!hasNormals)
  688. {
  689. Vector3 dist1 = v1 - v0;
  690. Vector3 dist2 = v2 - v0;
  691. faceNormal = (dist1.CrossProduct(dist2)).Normalized();
  692. }
  693. const Vector3& n0 = hasNormals ? *((const Vector3*)(&normalData[i0 * normalStride])) : faceNormal;
  694. const Vector3& n1 = hasNormals ? *((const Vector3*)(&normalData[i1 * normalStride])) : faceNormal;
  695. const Vector3& n2 = hasNormals ? *((const Vector3*)(&normalData[i2 * normalStride])) : faceNormal;
  696. const unsigned char* s0 = hasSkinning ? &skinningData[i0 * skinningStride] : (const unsigned char*)0;
  697. const unsigned char* s1 = hasSkinning ? &skinningData[i1 * skinningStride] : (const unsigned char*)0;
  698. const unsigned char* s2 = hasSkinning ? &skinningData[i2 * skinningStride] : (const unsigned char*)0;
  699. // Check if face is too much away from the decal normal
  700. if (decalNormal.DotProduct((n0 + n1 + n2) / 3.0f) < normalCutoff)
  701. return;
  702. // Check if face is culled completely by any of the planes
  703. for (unsigned i = PLANE_FAR; i < NUM_FRUSTUM_PLANES; --i)
  704. {
  705. const Plane& plane = frustum.planes_[i];
  706. if (plane.Distance(v0) < 0.0f && plane.Distance(v1) < 0.0f && plane.Distance(v2) < 0.0f)
  707. return;
  708. }
  709. faces.Resize(faces.Size() + 1);
  710. PODVector<DecalVertex>& face = faces.Back();
  711. if (!hasSkinning)
  712. {
  713. face.Reserve(3);
  714. face.Push(DecalVertex(v0, n0));
  715. face.Push(DecalVertex(v1, n1));
  716. face.Push(DecalVertex(v2, n2));
  717. }
  718. else
  719. {
  720. const float* bw0 = (const float*)s0;
  721. const float* bw1 = (const float*)s1;
  722. const float* bw2 = (const float*)s2;
  723. const unsigned char* bi0 = s0 + sizeof(float) * 4;
  724. const unsigned char* bi1 = s1 + sizeof(float) * 4;
  725. const unsigned char* bi2 = s2 + sizeof(float) * 4;
  726. unsigned char nbi0[4];
  727. unsigned char nbi1[4];
  728. unsigned char nbi2[4];
  729. // Make sure all bones are found and that there is room in the skinning matrices
  730. if (!GetBones(target, batchIndex, bw0, bi0, nbi0) || !GetBones(target, batchIndex, bw1, bi1, nbi1) ||
  731. !GetBones(target, batchIndex, bw2, bi2, nbi2))
  732. return;
  733. face.Reserve(3);
  734. face.Push(DecalVertex(v0, n0, bw0, nbi0));
  735. face.Push(DecalVertex(v1, n1, bw1, nbi1));
  736. face.Push(DecalVertex(v2, n2, bw2, nbi2));
  737. }
  738. }
  739. bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
  740. unsigned char* newBlendIndices)
  741. {
  742. AnimatedModel* animatedModel = dynamic_cast<AnimatedModel*>(target);
  743. if (!animatedModel)
  744. return false;
  745. // Check whether target is using global or per-geometry skinning
  746. const Vector<PODVector<Matrix3x4> >& geometrySkinMatrices = animatedModel->GetGeometrySkinMatrices();
  747. const Vector<PODVector<unsigned> >& geometryBoneMappings = animatedModel->GetGeometryBoneMappings();
  748. for (unsigned i = 0; i < 4; ++i)
  749. {
  750. if (blendWeights[i] > 0.0f)
  751. {
  752. Bone* bone = 0;
  753. if (geometrySkinMatrices.Empty())
  754. bone = animatedModel->GetSkeleton().GetBone(blendIndices[i]);
  755. else if (blendIndices[i] < geometryBoneMappings[batchIndex].Size())
  756. bone = animatedModel->GetSkeleton().GetBone(geometryBoneMappings[batchIndex][blendIndices[i]]);
  757. if (!bone)
  758. {
  759. LOGWARNING("Out of range bone index for skinned decal");
  760. return false;
  761. }
  762. bool found = false;
  763. unsigned index;
  764. for (index = 0; index < bones_.Size(); ++index)
  765. {
  766. if (bones_[index].node_ == bone->node_)
  767. {
  768. // Check also that the offset matrix matches, in case we for example have a separate attachment AnimatedModel
  769. // with a different bind pose
  770. if (bones_[index].offsetMatrix_.Equals(bone->offsetMatrix_))
  771. {
  772. found = true;
  773. break;
  774. }
  775. }
  776. }
  777. if (!found)
  778. {
  779. if (bones_.Size() >= Graphics::GetMaxBones())
  780. {
  781. LOGWARNING("Maximum skinned decal bone count reached");
  782. return false;
  783. }
  784. else
  785. {
  786. // Copy the bone from the model to the decal
  787. index = bones_.Size();
  788. bones_.Resize(bones_.Size() + 1);
  789. bones_[index] = *bone;
  790. skinMatrices_.Resize(skinMatrices_.Size() + 1);
  791. skinningDirty_ = true;
  792. // Start listening to bone transform changes to update skinning
  793. bone->node_->AddListener(this);
  794. }
  795. }
  796. newBlendIndices[i] = index;
  797. }
  798. else
  799. newBlendIndices[i] = 0;
  800. }
  801. // Update amount of shader data in the decal batch
  802. UpdateBatch();
  803. return true;
  804. }
  805. void DecalSet::CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV,
  806. const Vector2& bottomRightUV)
  807. {
  808. Matrix4 viewProj = projection * view;
  809. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  810. {
  811. Vector3 projected = viewProj * i->position_;
  812. i->texCoord_ = Vector2(
  813. Lerp(topLeftUV.x_, bottomRightUV.x_, projected.x_ * 0.5f + 0.5f),
  814. Lerp(bottomRightUV.y_, topLeftUV.y_, projected.y_ * 0.5f + 0.5f)
  815. );
  816. }
  817. }
  818. void DecalSet::TransformVertices(Decal& decal, const Matrix3x4& transform)
  819. {
  820. for (PODVector<DecalVertex>::Iterator i = decal.vertices_.Begin(); i != decal.vertices_.End(); ++i)
  821. {
  822. i->position_ = transform * i->position_;
  823. i->normal_ = (transform * i->normal_).Normalized();
  824. }
  825. }
  826. List<Decal>::Iterator DecalSet::RemoveDecal(List<Decal>::Iterator i)
  827. {
  828. numVertices_ -= i->vertices_.Size();
  829. numIndices_ -= i->indices_.Size();
  830. MarkDecalsDirty();
  831. return decals_.Erase(i);
  832. }
  833. void DecalSet::MarkDecalsDirty()
  834. {
  835. if (!boundingBoxDirty_)
  836. {
  837. boundingBoxDirty_ = true;
  838. OnMarkedDirty(node_);
  839. }
  840. bufferDirty_ = true;
  841. }
  842. void DecalSet::CalculateBoundingBox()
  843. {
  844. boundingBox_.Clear();
  845. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  846. boundingBox_.Merge(i->boundingBox_);
  847. boundingBoxDirty_ = false;
  848. }
  849. void DecalSet::UpdateBufferSize()
  850. {
  851. vertexBuffer_->SetSize(maxVertices_, skinned_ ? SKINNED_ELEMENT_MASK : STATIC_ELEMENT_MASK);
  852. indexBuffer_->SetSize(maxIndices_, false);
  853. geometry_->SetVertexBuffer(0, vertexBuffer_);
  854. bufferDirty_ = true;
  855. bufferSizeDirty_ = false;
  856. }
  857. void DecalSet::UpdateBuffers()
  858. {
  859. geometry_->SetDrawRange(TRIANGLE_LIST, 0, numIndices_, 0, numVertices_);
  860. float* vertices = (float*)vertexBuffer_->Lock(0, numVertices_);
  861. unsigned short* indices = (unsigned short*)indexBuffer_->Lock(0, numIndices_);
  862. if (vertices && indices)
  863. {
  864. unsigned short indexStart = 0;
  865. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  866. {
  867. for (unsigned j = 0; j < i->vertices_.Size(); ++j)
  868. {
  869. const DecalVertex& vertex = i->vertices_[j];
  870. *vertices++ = vertex.position_.x_;
  871. *vertices++ = vertex.position_.y_;
  872. *vertices++ = vertex.position_.z_;
  873. *vertices++ = vertex.normal_.x_;
  874. *vertices++ = vertex.normal_.y_;
  875. *vertices++ = vertex.normal_.z_;
  876. *vertices++ = vertex.texCoord_.x_;
  877. *vertices++ = vertex.texCoord_.y_;
  878. *vertices++ = vertex.tangent_.x_;
  879. *vertices++ = vertex.tangent_.y_;
  880. *vertices++ = vertex.tangent_.z_;
  881. *vertices++ = vertex.tangent_.w_;
  882. if (skinned_)
  883. {
  884. *vertices++ = vertex.blendWeights_[0];
  885. *vertices++ = vertex.blendWeights_[1];
  886. *vertices++ = vertex.blendWeights_[2];
  887. *vertices++ = vertex.blendWeights_[3];
  888. *vertices++ = *((float*)vertex.blendIndices_);
  889. }
  890. }
  891. for (unsigned j = 0; j < i->indices_.Size(); ++j)
  892. *indices++ = i->indices_[j] + indexStart;
  893. indexStart += i->vertices_.Size();
  894. }
  895. }
  896. vertexBuffer_->Unlock();
  897. vertexBuffer_->ClearDataLost();
  898. indexBuffer_->Unlock();
  899. indexBuffer_->ClearDataLost();
  900. bufferDirty_ = false;
  901. }
  902. void DecalSet::UpdateSkinning()
  903. {
  904. // Use model's world transform in case a bone is missing
  905. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  906. for (unsigned i = 0; i < bones_.Size(); ++i)
  907. {
  908. const Bone& bone = bones_[i];
  909. if (bone.node_)
  910. skinMatrices_[i] = bone.node_->GetWorldTransform() * bone.offsetMatrix_;
  911. else
  912. skinMatrices_[i] = worldTransform;
  913. }
  914. skinningDirty_ = false;
  915. }
  916. void DecalSet::UpdateBatch()
  917. {
  918. if (skinMatrices_.Size())
  919. {
  920. batches_[0].geometryType_ = GEOM_SKINNED;
  921. batches_[0].worldTransform_ = &skinMatrices_[0];
  922. batches_[0].numWorldTransforms_ = skinMatrices_.Size();
  923. }
  924. else
  925. {
  926. batches_[0].geometryType_ = GEOM_STATIC;
  927. batches_[0].worldTransform_ = &node_->GetWorldTransform();
  928. batches_[0].numWorldTransforms_ = 1;
  929. }
  930. }
  931. void DecalSet::AssignBoneNodes()
  932. {
  933. assignBonesPending_ = false;
  934. if (!node_)
  935. return;
  936. // Find the bone nodes from the node hierarchy and add listeners
  937. for (Vector<Bone>::Iterator i = bones_.Begin(); i != bones_.End(); ++i)
  938. {
  939. Node* boneNode = node_->GetChild(i->name_, true);
  940. if (boneNode)
  941. boneNode->AddListener(this);
  942. i->node_ = boneNode;
  943. }
  944. }
  945. void DecalSet::UpdateEventSubscription(bool checkAllDecals)
  946. {
  947. Scene* scene = GetScene();
  948. if (!scene)
  949. return;
  950. bool enabled = IsEnabledEffective();
  951. if (enabled && checkAllDecals)
  952. {
  953. bool hasTimeLimitedDecals = false;
  954. for (List<Decal>::ConstIterator i = decals_.Begin(); i != decals_.End(); ++i)
  955. {
  956. if (i->timeToLive_ > 0.0f)
  957. {
  958. hasTimeLimitedDecals = true;
  959. break;
  960. }
  961. }
  962. // If no time limited decals, no need to subscribe to scene update
  963. enabled = hasTimeLimitedDecals;
  964. }
  965. if (enabled && !subscribed_)
  966. {
  967. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(DecalSet, HandleScenePostUpdate));
  968. subscribed_ = true;
  969. }
  970. else if (!enabled && subscribed_)
  971. {
  972. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  973. subscribed_ = false;
  974. }
  975. }
  976. void DecalSet::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  977. {
  978. using namespace ScenePostUpdate;
  979. float timeStep = eventData[P_TIMESTEP].GetFloat();
  980. for (List<Decal>::Iterator i = decals_.Begin(); i != decals_.End();)
  981. {
  982. i->timer_ += timeStep;
  983. // Remove the decal if time to live expired
  984. if (i->timeToLive_ > 0.0f && i->timer_ > i->timeToLive_)
  985. i = RemoveDecal(i);
  986. else
  987. ++i;
  988. }
  989. }
  990. }