Renderer2D.cpp 16 KB

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