Renderer2D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Core/WorkQueue.h"
  26. #include "../Graphics/Camera.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/GraphicsEvents.h"
  29. #include "../Graphics/IndexBuffer.h"
  30. #include "../Graphics/Material.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/Technique.h"
  33. #include "../Graphics/Texture2D.h"
  34. #include "../Graphics/VertexBuffer.h"
  35. #include "../Graphics/View.h"
  36. #include "../IO/Log.h"
  37. #include "../Scene/Node.h"
  38. #include "../Scene/Scene.h"
  39. #include "../Urho2D/Drawable2D.h"
  40. #include "../Urho2D/Renderer2D.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. extern const char* blendModeNames[];
  45. static const unsigned MASK_VERTEX2D = MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1;
  46. ViewBatchInfo2D::ViewBatchInfo2D() :
  47. vertexBufferUpdateFrameNumber_(0),
  48. indexCount_(0),
  49. vertexCount_(0),
  50. batchUpdatedFrameNumber_(0),
  51. batchCount_(0)
  52. {
  53. }
  54. Renderer2D::Renderer2D(Context* context) :
  55. Drawable(context, DRAWABLE_GEOMETRY),
  56. material_(new Material(context)),
  57. indexBuffer_(new IndexBuffer(context_)),
  58. viewMask_(DEFAULT_VIEWMASK)
  59. {
  60. material_->SetName("Urho2D");
  61. auto* tech = new Technique(context_);
  62. Pass* pass = tech->CreatePass("alpha");
  63. pass->SetVertexShader("Urho2D");
  64. pass->SetPixelShader("Urho2D");
  65. pass->SetDepthWrite(false);
  66. cachedTechniques_[BLEND_REPLACE] = tech;
  67. material_->SetTechnique(0, tech);
  68. material_->SetCullMode(CULL_NONE);
  69. frame_.frameNumber_ = 0;
  70. SubscribeToEvent(E_BEGINVIEWUPDATE, URHO3D_HANDLER(Renderer2D, HandleBeginViewUpdate));
  71. }
  72. Renderer2D::~Renderer2D() = default;
  73. void Renderer2D::RegisterObject(Context* context)
  74. {
  75. context->RegisterFactory<Renderer2D>();
  76. }
  77. static inline bool CompareRayQueryResults(RayQueryResult& lr, RayQueryResult& rr)
  78. {
  79. auto* lhs = static_cast<Drawable2D*>(lr.drawable_);
  80. auto* rhs = static_cast<Drawable2D*>(rr.drawable_);
  81. if (lhs->GetLayer() != rhs->GetLayer())
  82. return lhs->GetLayer() > rhs->GetLayer();
  83. if (lhs->GetOrderInLayer() != rhs->GetOrderInLayer())
  84. return lhs->GetOrderInLayer() > rhs->GetOrderInLayer();
  85. return lhs->GetID() > rhs->GetID();
  86. }
  87. void Renderer2D::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  88. {
  89. unsigned resultSize = results.Size();
  90. for (unsigned i = 0; i < drawables_.Size(); ++i)
  91. {
  92. if (drawables_[i]->GetViewMask() & query.viewMask_)
  93. drawables_[i]->ProcessRayQuery(query, results);
  94. }
  95. if (results.Size() != resultSize)
  96. Sort(results.Begin() + resultSize, results.End(), CompareRayQueryResults);
  97. }
  98. void Renderer2D::UpdateBatches(const FrameInfo& frame)
  99. {
  100. unsigned count = batches_.Size();
  101. // Update non-thread critical parts of the source batches
  102. for (unsigned i = 0; i < count; ++i)
  103. {
  104. batches_[i].distance_ = 10.0f + (count - i) * 0.001f;
  105. batches_[i].worldTransform_ = &Matrix3x4::IDENTITY;
  106. }
  107. }
  108. void Renderer2D::UpdateGeometry(const FrameInfo& frame)
  109. {
  110. unsigned indexCount = 0;
  111. for (HashMap<Camera*, ViewBatchInfo2D>::ConstIterator i = viewBatchInfos_.Begin(); i != viewBatchInfos_.End(); ++i)
  112. {
  113. if (i->second_.batchUpdatedFrameNumber_ == frame_.frameNumber_)
  114. indexCount = Max(indexCount, i->second_.indexCount_);
  115. }
  116. // Fill index buffer
  117. if (indexBuffer_->GetIndexCount() < indexCount || indexBuffer_->IsDataLost())
  118. {
  119. bool largeIndices = (indexCount * 4 / 6) > 0xffff;
  120. indexBuffer_->SetSize(indexCount, largeIndices);
  121. void* buffer = indexBuffer_->Lock(0, indexCount, true);
  122. if (buffer)
  123. {
  124. unsigned quadCount = indexCount / 6;
  125. if (largeIndices)
  126. {
  127. auto* dest = reinterpret_cast<unsigned*>(buffer);
  128. for (unsigned i = 0; i < quadCount; ++i)
  129. {
  130. unsigned base = i * 4;
  131. dest[0] = base;
  132. dest[1] = base + 1;
  133. dest[2] = base + 2;
  134. dest[3] = base;
  135. dest[4] = base + 2;
  136. dest[5] = base + 3;
  137. dest += 6;
  138. }
  139. }
  140. else
  141. {
  142. auto* dest = reinterpret_cast<unsigned short*>(buffer);
  143. for (unsigned i = 0; i < quadCount; ++i)
  144. {
  145. unsigned base = i * 4;
  146. dest[0] = (unsigned short)(base);
  147. dest[1] = (unsigned short)(base + 1);
  148. dest[2] = (unsigned short)(base + 2);
  149. dest[3] = (unsigned short)(base);
  150. dest[4] = (unsigned short)(base + 2);
  151. dest[5] = (unsigned short)(base + 3);
  152. dest += 6;
  153. }
  154. }
  155. indexBuffer_->Unlock();
  156. }
  157. else
  158. {
  159. URHO3D_LOGERROR("Failed to lock index buffer");
  160. return;
  161. }
  162. }
  163. Camera* camera = frame.camera_;
  164. ViewBatchInfo2D& viewBatchInfo = viewBatchInfos_[camera];
  165. if (viewBatchInfo.vertexBufferUpdateFrameNumber_ != frame_.frameNumber_)
  166. {
  167. unsigned vertexCount = viewBatchInfo.vertexCount_;
  168. VertexBuffer* vertexBuffer = viewBatchInfo.vertexBuffer_;
  169. if (vertexBuffer->GetVertexCount() < vertexCount)
  170. vertexBuffer->SetSize(vertexCount, MASK_VERTEX2D, true);
  171. if (vertexCount)
  172. {
  173. auto* dest = reinterpret_cast<Vertex2D*>(vertexBuffer->Lock(0, vertexCount, true));
  174. if (dest)
  175. {
  176. const PODVector<const SourceBatch2D*>& sourceBatches = viewBatchInfo.sourceBatches_;
  177. for (unsigned b = 0; b < sourceBatches.Size(); ++b)
  178. {
  179. const Vector<Vertex2D>& vertices = sourceBatches[b]->vertices_;
  180. for (unsigned i = 0; i < vertices.Size(); ++i)
  181. dest[i] = vertices[i];
  182. dest += vertices.Size();
  183. }
  184. vertexBuffer->Unlock();
  185. }
  186. else
  187. URHO3D_LOGERROR("Failed to lock vertex buffer");
  188. }
  189. viewBatchInfo.vertexBufferUpdateFrameNumber_ = frame_.frameNumber_;
  190. }
  191. }
  192. UpdateGeometryType Renderer2D::GetUpdateGeometryType()
  193. {
  194. return UPDATE_MAIN_THREAD;
  195. }
  196. void Renderer2D::AddDrawable(Drawable2D* drawable)
  197. {
  198. if (!drawable)
  199. return;
  200. drawables_.Push(drawable);
  201. }
  202. void Renderer2D::RemoveDrawable(Drawable2D* drawable)
  203. {
  204. if (!drawable)
  205. return;
  206. drawables_.Remove(drawable);
  207. }
  208. Material* Renderer2D::GetMaterial(Texture2D* texture, BlendMode blendMode)
  209. {
  210. if (!texture)
  211. return material_;
  212. HashMap<Texture2D*, HashMap<int, SharedPtr<Material> > >::Iterator t = cachedMaterials_.Find(texture);
  213. if (t == cachedMaterials_.End())
  214. {
  215. SharedPtr<Material> newMaterial = CreateMaterial(texture, blendMode);
  216. cachedMaterials_[texture][blendMode] = newMaterial;
  217. return newMaterial;
  218. }
  219. HashMap<int, SharedPtr<Material> >& materials = t->second_;
  220. HashMap<int, SharedPtr<Material> >::Iterator b = materials.Find(blendMode);
  221. if (b != materials.End())
  222. return b->second_;
  223. SharedPtr<Material> newMaterial = CreateMaterial(texture, blendMode);
  224. materials[blendMode] = newMaterial;
  225. return newMaterial;
  226. }
  227. bool Renderer2D::CheckVisibility(Drawable2D* drawable) const
  228. {
  229. if ((viewMask_ & drawable->GetViewMask()) == 0)
  230. return false;
  231. const BoundingBox& box = drawable->GetWorldBoundingBox();
  232. return frustum_.IsInsideFast(box) != OUTSIDE;
  233. }
  234. void Renderer2D::OnWorldBoundingBoxUpdate()
  235. {
  236. // Set a large dummy bounding box to ensure the renderer is rendered
  237. boundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE);
  238. worldBoundingBox_ = boundingBox_;
  239. }
  240. SharedPtr<Material> Renderer2D::CreateMaterial(Texture2D* texture, BlendMode blendMode)
  241. {
  242. SharedPtr<Material> newMaterial = material_->Clone();
  243. HashMap<int, SharedPtr<Technique> >::Iterator techIt = cachedTechniques_.Find((int)blendMode);
  244. if (techIt == cachedTechniques_.End())
  245. {
  246. SharedPtr<Technique> tech(new Technique(context_));
  247. Pass* pass = tech->CreatePass("alpha");
  248. pass->SetVertexShader("Urho2D");
  249. pass->SetPixelShader("Urho2D");
  250. pass->SetDepthWrite(false);
  251. pass->SetBlendMode(blendMode);
  252. techIt = cachedTechniques_.Insert(MakePair((int)blendMode, tech));
  253. }
  254. newMaterial->SetTechnique(0, techIt->second_.Get());
  255. newMaterial->SetName(texture->GetName() + "_" + blendModeNames[blendMode]);
  256. newMaterial->SetTexture(TU_DIFFUSE, texture);
  257. return newMaterial;
  258. }
  259. void CheckDrawableVisibilityWork(const WorkItem* item, unsigned threadIndex)
  260. {
  261. auto* renderer = reinterpret_cast<Renderer2D*>(item->aux_);
  262. auto** start = reinterpret_cast<Drawable2D**>(item->start_);
  263. auto** end = reinterpret_cast<Drawable2D**>(item->end_);
  264. while (start != end)
  265. {
  266. Drawable2D* drawable = *start++;
  267. if (renderer->CheckVisibility(drawable))
  268. drawable->MarkInView(renderer->frame_);
  269. }
  270. }
  271. void Renderer2D::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
  272. {
  273. using namespace BeginViewUpdate;
  274. // Check that we are updating the correct scene
  275. if (GetScene() != eventData[P_SCENE].GetPtr())
  276. return;
  277. frame_ = static_cast<View*>(eventData[P_VIEW].GetPtr())->GetFrameInfo();
  278. URHO3D_PROFILE(UpdateRenderer2D);
  279. auto* camera = static_cast<Camera*>(eventData[P_CAMERA].GetPtr());
  280. frustum_ = camera->GetFrustum();
  281. viewMask_ = camera->GetViewMask();
  282. // Check visibility
  283. {
  284. URHO3D_PROFILE(CheckDrawableVisibility);
  285. auto* queue = GetSubsystem<WorkQueue>();
  286. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  287. int drawablesPerItem = drawables_.Size() / numWorkItems;
  288. PODVector<Drawable2D*>::Iterator start = drawables_.Begin();
  289. for (int i = 0; i < numWorkItems; ++i)
  290. {
  291. SharedPtr<WorkItem> item = queue->GetFreeItem();
  292. item->priority_ = M_MAX_UNSIGNED;
  293. item->workFunction_ = CheckDrawableVisibilityWork;
  294. item->aux_ = this;
  295. PODVector<Drawable2D*>::Iterator end = drawables_.End();
  296. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  297. end = start + drawablesPerItem;
  298. item->start_ = &(*start);
  299. item->end_ = &(*end);
  300. queue->AddWorkItem(item);
  301. start = end;
  302. }
  303. queue->Complete(M_MAX_UNSIGNED);
  304. }
  305. ViewBatchInfo2D& viewBatchInfo = viewBatchInfos_[camera];
  306. // Create vertex buffer
  307. if (!viewBatchInfo.vertexBuffer_)
  308. viewBatchInfo.vertexBuffer_ = new VertexBuffer(context_);
  309. UpdateViewBatchInfo(viewBatchInfo, camera);
  310. // Go through the drawables to form geometries & batches and calculate the total vertex / index count,
  311. // but upload the actual vertex data later. The idea is that the View class copies our batch vector to
  312. // its internal data structures, so we can reuse the batches for each view, provided that unique Geometry
  313. // objects are used for each view to specify the draw ranges
  314. batches_.Resize(viewBatchInfo.batchCount_);
  315. for (unsigned i = 0; i < viewBatchInfo.batchCount_; ++i)
  316. {
  317. batches_[i].distance_ = viewBatchInfo.distances_[i];
  318. batches_[i].material_ = viewBatchInfo.materials_[i];
  319. batches_[i].geometry_ = viewBatchInfo.geometries_[i];
  320. }
  321. }
  322. void Renderer2D::GetDrawables(PODVector<Drawable2D*>& drawables, Node* node)
  323. {
  324. if (!node || !node->IsEnabled())
  325. return;
  326. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  327. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  328. {
  329. auto* drawable = dynamic_cast<Drawable2D*>(i->Get());
  330. if (drawable && drawable->IsEnabled())
  331. drawables.Push(drawable);
  332. }
  333. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  334. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  335. GetDrawables(drawables, i->Get());
  336. }
  337. static inline bool CompareSourceBatch2Ds(const SourceBatch2D* lhs, const SourceBatch2D* rhs)
  338. {
  339. if (lhs->drawOrder_ != rhs->drawOrder_)
  340. return lhs->drawOrder_ < rhs->drawOrder_;
  341. if (lhs->distance_ != rhs->distance_)
  342. return lhs->distance_ > rhs->distance_;
  343. if (lhs->material_ != rhs->material_)
  344. return lhs->material_->GetNameHash() < rhs->material_->GetNameHash();
  345. return lhs < rhs;
  346. }
  347. void Renderer2D::UpdateViewBatchInfo(ViewBatchInfo2D& viewBatchInfo, Camera* camera)
  348. {
  349. // Already update in same frame
  350. if (viewBatchInfo.batchUpdatedFrameNumber_ == frame_.frameNumber_)
  351. return;
  352. PODVector<const SourceBatch2D*>& sourceBatches = viewBatchInfo.sourceBatches_;
  353. sourceBatches.Clear();
  354. for (unsigned d = 0; d < drawables_.Size(); ++d)
  355. {
  356. if (!drawables_[d]->IsInView(camera))
  357. continue;
  358. const Vector<SourceBatch2D>& batches = drawables_[d]->GetSourceBatches();
  359. for (unsigned b = 0; b < batches.Size(); ++b)
  360. {
  361. if (batches[b].material_ && !batches[b].vertices_.Empty())
  362. sourceBatches.Push(&batches[b]);
  363. }
  364. }
  365. for (unsigned i = 0; i < sourceBatches.Size(); ++i)
  366. {
  367. const SourceBatch2D* sourceBatch = sourceBatches[i];
  368. Vector3 worldPos = sourceBatch->owner_->GetNode()->GetWorldPosition();
  369. sourceBatch->distance_ = camera->GetDistance(worldPos);
  370. }
  371. Sort(sourceBatches.Begin(), sourceBatches.End(), CompareSourceBatch2Ds);
  372. viewBatchInfo.batchCount_ = 0;
  373. Material* currMaterial = nullptr;
  374. unsigned iStart = 0;
  375. unsigned iCount = 0;
  376. unsigned vStart = 0;
  377. unsigned vCount = 0;
  378. float distance = M_INFINITY;
  379. for (unsigned b = 0; b < sourceBatches.Size(); ++b)
  380. {
  381. distance = Min(distance, sourceBatches[b]->distance_);
  382. Material* material = sourceBatches[b]->material_;
  383. const Vector<Vertex2D>& vertices = sourceBatches[b]->vertices_;
  384. // When new material encountered, finish the current batch and start new
  385. if (currMaterial != material)
  386. {
  387. if (currMaterial)
  388. {
  389. AddViewBatch(viewBatchInfo, currMaterial, iStart, iCount, vStart, vCount, distance);
  390. iStart += iCount;
  391. iCount = 0;
  392. vStart += vCount;
  393. vCount = 0;
  394. distance = M_INFINITY;
  395. }
  396. currMaterial = material;
  397. }
  398. iCount += vertices.Size() * 6 / 4;
  399. vCount += vertices.Size();
  400. }
  401. // Add the final batch if necessary
  402. if (currMaterial && vCount)
  403. AddViewBatch(viewBatchInfo, currMaterial, iStart, iCount, vStart, vCount,distance);
  404. viewBatchInfo.indexCount_ = iStart + iCount;
  405. viewBatchInfo.vertexCount_ = vStart + vCount;
  406. viewBatchInfo.batchUpdatedFrameNumber_ = frame_.frameNumber_;
  407. }
  408. void Renderer2D::AddViewBatch(ViewBatchInfo2D& viewBatchInfo, Material* material,
  409. unsigned indexStart, unsigned indexCount, unsigned vertexStart, unsigned vertexCount, float distance)
  410. {
  411. if (!material || indexCount == 0 || vertexCount == 0)
  412. return;
  413. if (viewBatchInfo.distances_.Size() <= viewBatchInfo.batchCount_)
  414. viewBatchInfo.distances_.Resize(viewBatchInfo.batchCount_ + 1);
  415. viewBatchInfo.distances_[viewBatchInfo.batchCount_] = distance;
  416. if (viewBatchInfo.materials_.Size() <= viewBatchInfo.batchCount_)
  417. viewBatchInfo.materials_.Resize(viewBatchInfo.batchCount_ + 1);
  418. viewBatchInfo.materials_[viewBatchInfo.batchCount_] = material;
  419. // Allocate new geometry if necessary
  420. if (viewBatchInfo.geometries_.Size() <= viewBatchInfo.batchCount_)
  421. {
  422. SharedPtr<Geometry> geometry(new Geometry(context_));
  423. geometry->SetIndexBuffer(indexBuffer_);
  424. geometry->SetVertexBuffer(0, viewBatchInfo.vertexBuffer_);
  425. viewBatchInfo.geometries_.Push(geometry);
  426. }
  427. Geometry* geometry = viewBatchInfo.geometries_[viewBatchInfo.batchCount_];
  428. geometry->SetDrawRange(TRIANGLE_LIST, indexStart, indexCount, vertexStart, vertexCount, false);
  429. viewBatchInfo.batchCount_++;
  430. }
  431. }