Renderer2D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 "Precompiled.h"
  23. #include "../Container/Sort.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/WorkQueue.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/GraphicsEvents.h"
  30. #include "../Graphics/IndexBuffer.h"
  31. #include "../Graphics/Material.h"
  32. #include "../Graphics/OctreeQuery.h"
  33. #include "../Graphics/Technique.h"
  34. #include "../Graphics/Texture2D.h"
  35. #include "../Graphics/VertexBuffer.h"
  36. #include "../Graphics/View.h"
  37. #include "../IO/Log.h"
  38. #include "../Scene/Node.h"
  39. #include "../Scene/Scene.h"
  40. #include "../Atomic2D/Drawable2D.h"
  41. #include "../Atomic2D/Renderer2D.h"
  42. #include "../DebugNew.h"
  43. namespace Atomic
  44. {
  45. extern const char* blendModeNames[];
  46. static const unsigned MASK_VERTEX2D = MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1;
  47. ViewBatchInfo2D::ViewBatchInfo2D() : 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. frustum_(0)
  59. {
  60. material_->SetName("Atomic2D");
  61. Technique* tech = new Technique(context_);
  62. Pass* pass = tech->CreatePass("alpha");
  63. pass->SetVertexShader("Atomic2D");
  64. pass->SetPixelShader("Atomic2D");
  65. pass->SetDepthWrite(false);
  66. material_->SetTechnique(0, tech);
  67. material_->SetCullMode(CULL_NONE);
  68. frame_.frameNumber_ = 0;
  69. SubscribeToEvent(E_BEGINVIEWUPDATE, HANDLER(Renderer2D, HandleBeginViewUpdate));
  70. }
  71. Renderer2D::~Renderer2D()
  72. {
  73. }
  74. void Renderer2D::RegisterObject(Context* context)
  75. {
  76. context->RegisterFactory<Renderer2D>();
  77. }
  78. static inline bool CompareRayQueryResults(RayQueryResult& lr, RayQueryResult& rr)
  79. {
  80. Drawable2D* lhs = static_cast<Drawable2D*>(lr.drawable_);
  81. Drawable2D* rhs = static_cast<Drawable2D*>(rr.drawable_);
  82. if (lhs->GetLayer() != rhs->GetLayer())
  83. return lhs->GetLayer() > rhs->GetLayer();
  84. if (lhs->GetOrderInLayer() != rhs->GetOrderInLayer())
  85. return lhs->GetOrderInLayer() > rhs->GetOrderInLayer();
  86. return lhs->GetID() > rhs->GetID();
  87. }
  88. void Renderer2D::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  89. {
  90. unsigned resultSize = results.Size();
  91. for (unsigned i = 0; i < drawables_.Size(); ++i)
  92. drawables_[i]->ProcessRayQuery(query, results);
  93. if (results.Size() != resultSize)
  94. Sort(results.Begin() + resultSize, results.End(), CompareRayQueryResults);
  95. }
  96. void Renderer2D::UpdateBatches(const FrameInfo& frame)
  97. {
  98. unsigned count = batches_.Size();
  99. // Update non-thread critical parts of the source batches
  100. for (unsigned i = 0; i < count; ++i)
  101. {
  102. batches_[i].distance_ = 10.0f + (count - i) * 0.001f;
  103. batches_[i].worldTransform_ = &Matrix3x4::IDENTITY;
  104. }
  105. }
  106. void Renderer2D::UpdateGeometry(const FrameInfo& frame)
  107. {
  108. unsigned indexCount = 0;
  109. for (HashMap<Camera*, ViewBatchInfo2D>::ConstIterator i = viewBatchInfos_.Begin(); i != viewBatchInfos_.End(); ++i)
  110. {
  111. if (i->second_.batchUpdatedFrameNumber_ == frame_.frameNumber_)
  112. indexCount = Max((int)indexCount, (int)i->second_.indexCount_);
  113. }
  114. // Fill index buffer
  115. if (indexBuffer_->GetIndexCount() < indexCount || indexBuffer_->IsDataLost())
  116. {
  117. bool largeIndices = (indexCount * 4 / 6) > 0xffff;
  118. indexBuffer_->SetSize(indexCount, largeIndices);
  119. void* buffer = indexBuffer_->Lock(0, indexCount, true);
  120. if (buffer)
  121. {
  122. unsigned quadCount = indexCount / 6;
  123. if (largeIndices)
  124. {
  125. unsigned* dest = reinterpret_cast<unsigned*>(buffer);
  126. for (unsigned i = 0; i < quadCount; ++i)
  127. {
  128. unsigned base = i * 4;
  129. dest[0] = base;
  130. dest[1] = base + 1;
  131. dest[2] = base + 2;
  132. dest[3] = base;
  133. dest[4] = base + 2;
  134. dest[5] = base + 3;
  135. dest += 6;
  136. }
  137. }
  138. else
  139. {
  140. unsigned short* dest = reinterpret_cast<unsigned short*>(buffer);
  141. for (unsigned i = 0; i < quadCount; ++i)
  142. {
  143. unsigned base = i * 4;
  144. dest[0] = (unsigned short)(base);
  145. dest[1] = (unsigned short)(base + 1);
  146. dest[2] = (unsigned short)(base + 2);
  147. dest[3] = (unsigned short)(base);
  148. dest[4] = (unsigned short)(base + 2);
  149. dest[5] = (unsigned short)(base + 3);
  150. dest += 6;
  151. }
  152. }
  153. indexBuffer_->Unlock();
  154. }
  155. else
  156. {
  157. LOGERROR("Failed to lock index buffer");
  158. return;
  159. }
  160. }
  161. Camera* camera = frame.camera_;
  162. ViewBatchInfo2D& viewBatchInfo = viewBatchInfos_[camera];
  163. if (viewBatchInfo.vertexBufferUpdateFrameNumber_ != frame_.frameNumber_)
  164. {
  165. unsigned vertexCount = viewBatchInfo.vertexCount_;
  166. VertexBuffer* vertexBuffer = viewBatchInfo.vertexBuffer_;
  167. if (vertexBuffer->GetVertexCount() < vertexCount)
  168. vertexBuffer->SetSize(vertexCount, MASK_VERTEX2D, true);
  169. if (vertexCount)
  170. {
  171. Vertex2D* dest = reinterpret_cast<Vertex2D*>(vertexBuffer->Lock(0, vertexCount, true));
  172. if (dest)
  173. {
  174. const PODVector<const SourceBatch2D*>& sourceBatches = viewBatchInfo.sourceBatches_;
  175. for (unsigned b = 0; b < sourceBatches.Size(); ++b)
  176. {
  177. const Vector<Vertex2D>& vertices = sourceBatches[b]->vertices_;
  178. for (unsigned i = 0; i < vertices.Size(); ++i)
  179. dest[i] = vertices[i];
  180. dest += vertices.Size();
  181. }
  182. vertexBuffer->Unlock();
  183. }
  184. else
  185. LOGERROR("Failed to lock vertex buffer");
  186. }
  187. viewBatchInfo.vertexBufferUpdateFrameNumber_ = frame_.frameNumber_;
  188. }
  189. }
  190. UpdateGeometryType Renderer2D::GetUpdateGeometryType()
  191. {
  192. return UPDATE_MAIN_THREAD;
  193. }
  194. void Renderer2D::AddDrawable(Drawable2D* drawable)
  195. {
  196. if (!drawable)
  197. return;
  198. drawables_.Push(drawable);
  199. }
  200. void Renderer2D::RemoveDrawable(Drawable2D* drawable)
  201. {
  202. if (!drawable)
  203. return;
  204. drawables_.Remove(drawable);
  205. }
  206. Material* Renderer2D::GetMaterial(Texture2D* texture, BlendMode blendMode)
  207. {
  208. if (!material_)
  209. return 0;
  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. const BoundingBox& box = drawable->GetWorldBoundingBox();
  230. if (frustum_)
  231. return frustum_->IsInsideFast(box) != OUTSIDE;
  232. return frustumBoundingBox_.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. newMaterial->SetName(texture->GetName() + "_" + blendModeNames[blendMode]);
  244. newMaterial->SetTexture(TU_DIFFUSE, texture);
  245. newMaterial->GetTechnique(0)->GetPass("alpha")->SetBlendMode(blendMode);
  246. return newMaterial;
  247. }
  248. void CheckDrawableVisibility(const WorkItem* item, unsigned threadIndex)
  249. {
  250. Renderer2D* renderer = reinterpret_cast<Renderer2D*>(item->aux_);
  251. Drawable2D** start = reinterpret_cast<Drawable2D**>(item->start_);
  252. Drawable2D** end = reinterpret_cast<Drawable2D**>(item->end_);
  253. while (start != end)
  254. {
  255. Drawable2D* drawable = *start++;
  256. if (renderer->CheckVisibility(drawable))
  257. drawable->MarkInView(renderer->frame_);
  258. }
  259. }
  260. void Renderer2D::HandleBeginViewUpdate(StringHash eventType, VariantMap& eventData)
  261. {
  262. using namespace BeginViewUpdate;
  263. // Check that we are updating the correct scene
  264. if (GetScene() != eventData[P_SCENE].GetPtr())
  265. return;
  266. frame_ = static_cast<View*>(eventData[P_VIEW].GetPtr())->GetFrameInfo();
  267. PROFILE(UpdateRenderer2D);
  268. Camera* camera = static_cast<Camera*>(eventData[P_CAMERA].GetPtr());
  269. frustum_ = &camera->GetFrustum();
  270. if (camera->IsOrthographic() && camera->GetNode()->GetWorldDirection() == Vector3::FORWARD)
  271. {
  272. // Define bounding box with min and max points
  273. frustumBoundingBox_.Define(frustum_->vertices_[2], frustum_->vertices_[4]);
  274. frustum_ = 0;
  275. }
  276. // Check visibility
  277. {
  278. PROFILE(CheckDrawableVisibility);
  279. WorkQueue* queue = GetSubsystem<WorkQueue>();
  280. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  281. int drawablesPerItem = drawables_.Size() / numWorkItems;
  282. PODVector<Drawable2D*>::Iterator start = drawables_.Begin();
  283. for (int i = 0; i < numWorkItems; ++i)
  284. {
  285. SharedPtr<WorkItem> item = queue->GetFreeItem();
  286. item->priority_ = M_MAX_UNSIGNED;
  287. item->workFunction_ = CheckDrawableVisibility;
  288. item->aux_ = this;
  289. PODVector<Drawable2D*>::Iterator end = drawables_.End();
  290. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  291. end = start + drawablesPerItem;
  292. item->start_ = &(*start);
  293. item->end_ = &(*end);
  294. queue->AddWorkItem(item);
  295. start = end;
  296. }
  297. queue->Complete(M_MAX_UNSIGNED);
  298. }
  299. ViewBatchInfo2D& viewBatchInfo = viewBatchInfos_[camera];
  300. // Create vertex buffer
  301. if (!viewBatchInfo.vertexBuffer_)
  302. viewBatchInfo.vertexBuffer_ = new VertexBuffer(context_);
  303. UpdateViewBatchInfo(viewBatchInfo, camera);
  304. // Go through the drawables to form geometries & batches and calculate the total vertex / index count,
  305. // but upload the actual vertex data later. The idea is that the View class copies our batch vector to
  306. // its internal data structures, so we can reuse the batches for each view, provided that unique Geometry
  307. // objects are used for each view to specify the draw ranges
  308. batches_.Resize(viewBatchInfo.batchCount_);
  309. for (unsigned i = 0; i < viewBatchInfo.batchCount_; ++i)
  310. {
  311. batches_[i].material_ = viewBatchInfo.materials_[i];
  312. batches_[i].geometry_ = viewBatchInfo.geometries_[i];
  313. }
  314. }
  315. void Renderer2D::GetDrawables(PODVector<Drawable2D*>& dest, Node* node)
  316. {
  317. if (!node || !node->IsEnabled())
  318. return;
  319. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  320. for (Vector<SharedPtr<Component> >::ConstIterator i = components.Begin(); i != components.End(); ++i)
  321. {
  322. Drawable2D* drawable = dynamic_cast<Drawable2D*>(i->Get());
  323. if (drawable && drawable->IsEnabled())
  324. dest.Push(drawable);
  325. }
  326. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  327. for (Vector<SharedPtr<Node> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  328. GetDrawables(dest, i->Get());
  329. }
  330. static inline bool CompareSourceBatch2Ds(const SourceBatch2D* lhs, const SourceBatch2D* rhs)
  331. {
  332. if (lhs->drawOrder_ != rhs->drawOrder_)
  333. return lhs->drawOrder_ < rhs->drawOrder_;
  334. if (lhs->material_ != rhs->material_)
  335. return lhs->material_->GetNameHash() < rhs->material_->GetNameHash();
  336. return lhs < rhs;
  337. }
  338. void Renderer2D::UpdateViewBatchInfo(ViewBatchInfo2D& viewBatchInfo, Camera* camera)
  339. {
  340. // Already update in same frame
  341. if (viewBatchInfo.batchUpdatedFrameNumber_ == frame_.frameNumber_)
  342. return;
  343. PODVector<const SourceBatch2D*>& soruceBatches = viewBatchInfo.sourceBatches_;
  344. soruceBatches.Clear();
  345. for (unsigned d = 0; d < drawables_.Size(); ++d)
  346. {
  347. if (!drawables_[d]->IsInView(camera))
  348. continue;
  349. const Vector<SourceBatch2D>& batches = drawables_[d]->GetSourceBatches();
  350. for (unsigned b = 0; b < batches.Size(); ++b)
  351. {
  352. if (batches[b].material_ && !batches[b].vertices_.Empty())
  353. soruceBatches.Push(&batches[b]);
  354. }
  355. }
  356. Sort(soruceBatches.Begin(), soruceBatches.End(), CompareSourceBatch2Ds);
  357. viewBatchInfo.batchCount_ = 0;
  358. Material* currMaterial = 0;
  359. unsigned iStart = 0;
  360. unsigned iCount = 0;
  361. unsigned vStart = 0;
  362. unsigned vCount = 0;
  363. for (unsigned b = 0; b < soruceBatches.Size(); ++b)
  364. {
  365. Material* material = soruceBatches[b]->material_;
  366. const Vector<Vertex2D>& vertices = soruceBatches[b]->vertices_;
  367. // When new material encountered, finish the current batch and start new
  368. if (currMaterial != material)
  369. {
  370. if (currMaterial)
  371. {
  372. AddViewBatch(viewBatchInfo, currMaterial, iStart, iCount, vStart, vCount);
  373. iStart += iCount;
  374. iCount = 0;
  375. vStart += vCount;
  376. vCount = 0;
  377. }
  378. currMaterial = material;
  379. }
  380. iCount += vertices.Size() * 6 / 4;
  381. vCount += vertices.Size();
  382. }
  383. // Add the final batch if necessary
  384. if (currMaterial && vCount)
  385. AddViewBatch(viewBatchInfo, currMaterial, iStart, iCount, vStart, vCount);
  386. viewBatchInfo.indexCount_ = iStart + iCount;
  387. viewBatchInfo.vertexCount_ = vStart + vCount;
  388. viewBatchInfo.batchUpdatedFrameNumber_ = frame_.frameNumber_;
  389. }
  390. void Renderer2D::AddViewBatch(ViewBatchInfo2D& viewBatchInfo, Material* material, unsigned indexStart, unsigned indexCount, unsigned vertexStart, unsigned vertexCount)
  391. {
  392. if (!material || indexCount == 0 || vertexCount == 0)
  393. return;
  394. if (viewBatchInfo.materials_.Size() <= viewBatchInfo.batchCount_)
  395. viewBatchInfo.materials_.Resize(viewBatchInfo.batchCount_ + 1);
  396. viewBatchInfo.materials_[viewBatchInfo.batchCount_] = material;
  397. // Allocate new geometry if necessary
  398. if (viewBatchInfo.geometries_.Size() <= viewBatchInfo.batchCount_)
  399. {
  400. SharedPtr<Geometry> geometry(new Geometry(context_));
  401. geometry->SetIndexBuffer(indexBuffer_);
  402. geometry->SetVertexBuffer(0, viewBatchInfo.vertexBuffer_, MASK_VERTEX2D);
  403. viewBatchInfo.geometries_.Push(geometry);
  404. }
  405. Geometry* geometry = viewBatchInfo.geometries_[viewBatchInfo.batchCount_];
  406. geometry->SetDrawRange(TRIANGLE_LIST, indexStart, indexCount, vertexStart, vertexCount, false);
  407. viewBatchInfo.batchCount_++;
  408. }
  409. }