DALi Version 2.0.47
[platform/core/uifw/dali-toolkit.git] / automated-tests / src / dali-toolkit / dali-toolkit-test-utils / test-graphics-controller.cpp
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "test-graphics-controller.h"
18
19 #include "test-graphics-buffer.h"
20 #include "test-graphics-command-buffer.h"
21 #include "test-graphics-framebuffer.h"
22 #include "test-graphics-reflection.h"
23 #include "test-graphics-render-pass.h"
24 #include "test-graphics-render-target.h"
25 #include "test-graphics-sampler.h"
26 #include "test-graphics-shader.h"
27 #include "test-graphics-sync-object.h"
28 #include "test-graphics-texture.h"
29
30 #include <dali/integration-api/gl-defines.h>
31 #include <cstdio>
32 #include <iostream>
33 #include <sstream>
34
35 namespace Dali
36 {
37 std::ostream& operator<<(std::ostream& o, const Graphics::BufferCreateInfo& bufferCreateInfo)
38 {
39   return o << "usage:" << std::hex << bufferCreateInfo.usage << ", size:" << std::dec << bufferCreateInfo.size;
40 }
41
42 std::ostream& operator<<(std::ostream& o, const Graphics::CommandBufferCreateInfo& commandBufferCreateInfo)
43 {
44   return o << "level:" << (commandBufferCreateInfo.level == Graphics::CommandBufferLevel::PRIMARY ? "PRIMARY" : "SECONDARY")
45            << ", fixedCapacity:" << std::dec << commandBufferCreateInfo.fixedCapacity;
46 }
47
48 std::ostream& operator<<(std::ostream& o, const Graphics::TextureType& textureType)
49 {
50   switch(textureType)
51   {
52     case Graphics::TextureType::TEXTURE_2D:
53       o << "TEXTURE_2D";
54       break;
55     case Graphics::TextureType::TEXTURE_3D:
56       o << "TEXTURE_3D";
57       break;
58     case Graphics::TextureType::TEXTURE_CUBEMAP:
59       o << "TEXTURE_CUBEMAP";
60       break;
61   }
62   return o;
63 }
64
65 std::ostream& operator<<(std::ostream& o, const Graphics::Extent2D extent)
66 {
67   o << "width:" << extent.width << ", height:" << extent.height;
68   return o;
69 }
70
71 std::ostream& operator<<(std::ostream& o, const Graphics::TextureCreateInfo& createInfo)
72 {
73   o << "textureType:" << createInfo.textureType
74     << " size:" << createInfo.size
75     << " format:" << static_cast<uint32_t>(createInfo.format)
76     << " mipMapFlag:" << createInfo.mipMapFlag
77     << " layout:" << (createInfo.layout == Graphics::TextureLayout::LINEAR ? "LINEAR" : "OPTIMAL")
78     << " usageFlags:" << std::hex << createInfo.usageFlags
79     << " data:" << std::hex << createInfo.data
80     << " dataSize:" << std::dec << createInfo.dataSize
81     << " nativeImagePtr:" << std::hex << createInfo.nativeImagePtr;
82   return o;
83 }
84
85 std::ostream& operator<<(std::ostream& o, Graphics::SamplerAddressMode addressMode)
86 {
87   switch(addressMode)
88   {
89     case Graphics::SamplerAddressMode::REPEAT:
90       o << "REPEAT";
91       break;
92     case Graphics::SamplerAddressMode::MIRRORED_REPEAT:
93       o << "MIRRORED_REPEAT";
94       break;
95     case Graphics::SamplerAddressMode::CLAMP_TO_EDGE:
96       o << "CLAMP_TO_EDGE";
97       break;
98     case Graphics::SamplerAddressMode::CLAMP_TO_BORDER:
99       o << "CLAMP_TO_BORDER";
100       break;
101     case Graphics::SamplerAddressMode::MIRROR_CLAMP_TO_EDGE:
102       o << "MIRROR_CLAMP_TO_EDGE";
103       break;
104   }
105   return o;
106 }
107
108 std::ostream& operator<<(std::ostream& o, Graphics::SamplerFilter filterMode)
109 {
110   switch(filterMode)
111   {
112     case Graphics::SamplerFilter::LINEAR:
113       o << "LINEAR";
114       break;
115     case Graphics::SamplerFilter::NEAREST:
116       o << "NEAREST";
117       break;
118   }
119   return o;
120 }
121
122 std::ostream& operator<<(std::ostream& o, Graphics::SamplerMipmapMode mipmapMode)
123 {
124   switch(mipmapMode)
125   {
126     case Graphics::SamplerMipmapMode::NONE:
127       o << "NONE";
128       break;
129     case Graphics::SamplerMipmapMode::LINEAR:
130       o << "LINEAR";
131       break;
132     case Graphics::SamplerMipmapMode::NEAREST:
133       o << "NEAREST";
134       break;
135   }
136   return o;
137 }
138
139 std::ostream& operator<<(std::ostream& o, const Graphics::SamplerCreateInfo& createInfo)
140 {
141   o << "minFilter:" << createInfo.minFilter
142     << " magFilter:" << createInfo.magFilter
143     << " wrapModeU:" << createInfo.addressModeU
144     << " wrapModeV:" << createInfo.addressModeV
145     << " wrapModeW:" << createInfo.addressModeW
146     << " mipMapMode:" << createInfo.mipMapMode;
147   return o;
148 }
149
150 std::ostream& operator<<(std::ostream& o, const Graphics::ColorAttachment& colorAttachment)
151 {
152   o << "attachmentId:" << colorAttachment.attachmentId
153     << " layerId:" << colorAttachment.layerId
154     << " levelId:" << colorAttachment.levelId
155     << " texture:" << colorAttachment.texture;
156   return o;
157 }
158
159 std::ostream& operator<<(std::ostream& o, const Graphics::DepthStencilAttachment& depthStencilAttachment)
160 {
161   o << "depthTexture:" << depthStencilAttachment.depthTexture
162     << "depthLevel:" << depthStencilAttachment.depthLevel
163     << "stencilTexture:" << depthStencilAttachment.stencilTexture
164     << "stencilLevel:" << depthStencilAttachment.stencilLevel;
165   return o;
166 }
167
168 std::ostream& operator<<(std::ostream& o, const Graphics::FramebufferCreateInfo& createInfo)
169 {
170   o << "colorAttachments:";
171   for(auto i = 0u; i < createInfo.colorAttachments.size(); ++i)
172   {
173     o << "[" << i << "]=" << createInfo.colorAttachments[i] << "  ";
174   }
175   o << "depthStencilAttachment:" << createInfo.depthStencilAttachment;
176   o << "size: " << createInfo.size;
177   return o;
178 }
179
180 int GetNumComponents(Graphics::VertexInputFormat vertexFormat)
181 {
182   switch(vertexFormat)
183   {
184     case Graphics::VertexInputFormat::UNDEFINED:
185     case Graphics::VertexInputFormat::FLOAT:
186     case Graphics::VertexInputFormat::INTEGER:
187       return 1;
188     case Graphics::VertexInputFormat::IVECTOR2:
189     case Graphics::VertexInputFormat::FVECTOR2:
190       return 2;
191     case Graphics::VertexInputFormat::IVECTOR3:
192     case Graphics::VertexInputFormat::FVECTOR3:
193       return 3;
194     case Graphics::VertexInputFormat::FVECTOR4:
195     case Graphics::VertexInputFormat::IVECTOR4:
196       return 4;
197   }
198   return 1;
199 }
200
201 GLint GetSize(Graphics::VertexInputFormat vertexFormat)
202 {
203   switch(vertexFormat)
204   {
205     case Graphics::VertexInputFormat::UNDEFINED:
206       return 1u;
207     case Graphics::VertexInputFormat::INTEGER:
208     case Graphics::VertexInputFormat::IVECTOR2:
209     case Graphics::VertexInputFormat::IVECTOR3:
210     case Graphics::VertexInputFormat::IVECTOR4:
211       return 2u;
212     case Graphics::VertexInputFormat::FLOAT:
213     case Graphics::VertexInputFormat::FVECTOR2:
214     case Graphics::VertexInputFormat::FVECTOR3:
215     case Graphics::VertexInputFormat::FVECTOR4:
216       return 4u;
217   }
218   return 1u;
219 }
220
221 GLint GetGlType(Graphics::VertexInputFormat vertexFormat)
222 {
223   switch(vertexFormat)
224   {
225     case Graphics::VertexInputFormat::UNDEFINED:
226       return GL_BYTE;
227     case Graphics::VertexInputFormat::INTEGER:
228     case Graphics::VertexInputFormat::IVECTOR2:
229     case Graphics::VertexInputFormat::IVECTOR3:
230     case Graphics::VertexInputFormat::IVECTOR4:
231       return GL_SHORT;
232     case Graphics::VertexInputFormat::FLOAT:
233     case Graphics::VertexInputFormat::FVECTOR2:
234     case Graphics::VertexInputFormat::FVECTOR3:
235     case Graphics::VertexInputFormat::FVECTOR4:
236       return GL_FLOAT;
237   }
238   return GL_BYTE;
239 }
240
241 GLenum GetTopology(Graphics::PrimitiveTopology topology)
242 {
243   switch(topology)
244   {
245     case Graphics::PrimitiveTopology::POINT_LIST:
246       return GL_POINTS;
247
248     case Graphics::PrimitiveTopology::LINE_LIST:
249       return GL_LINES;
250
251     case Graphics::PrimitiveTopology::LINE_LOOP:
252       return GL_LINE_LOOP;
253
254     case Graphics::PrimitiveTopology::LINE_STRIP:
255       return GL_LINE_STRIP;
256
257     case Graphics::PrimitiveTopology::TRIANGLE_LIST:
258       return GL_TRIANGLES;
259
260     case Graphics::PrimitiveTopology::TRIANGLE_STRIP:
261       return GL_TRIANGLE_STRIP;
262
263     case Graphics::PrimitiveTopology::TRIANGLE_FAN:
264       return GL_TRIANGLE_FAN;
265   }
266   return GL_TRIANGLES;
267 }
268
269 GLenum GetCullFace(Graphics::CullMode cullMode)
270 {
271   switch(cullMode)
272   {
273     case Graphics::CullMode::NONE:
274       return GL_NONE;
275     case Graphics::CullMode::FRONT:
276       return GL_FRONT;
277     case Graphics::CullMode::BACK:
278       return GL_BACK;
279     case Graphics::CullMode::FRONT_AND_BACK:
280       return GL_FRONT_AND_BACK;
281   }
282   return GL_NONE;
283 }
284
285 GLenum GetFrontFace(Graphics::FrontFace frontFace)
286 {
287   if(frontFace == Graphics::FrontFace::CLOCKWISE)
288   {
289     return GL_CW;
290   }
291   return GL_CCW;
292 }
293
294 GLenum GetBlendFactor(Graphics::BlendFactor blendFactor)
295 {
296   GLenum glFactor = GL_ZERO;
297
298   switch(blendFactor)
299   {
300     case Graphics::BlendFactor::ZERO:
301       glFactor = GL_ZERO;
302       break;
303     case Graphics::BlendFactor::ONE:
304       glFactor = GL_ONE;
305       break;
306     case Graphics::BlendFactor::SRC_COLOR:
307       glFactor = GL_SRC_COLOR;
308       break;
309     case Graphics::BlendFactor::ONE_MINUS_SRC_COLOR:
310       glFactor = GL_ONE_MINUS_SRC_COLOR;
311       break;
312     case Graphics::BlendFactor::DST_COLOR:
313       glFactor = GL_DST_COLOR;
314       break;
315     case Graphics::BlendFactor::ONE_MINUS_DST_COLOR:
316       glFactor = GL_ONE_MINUS_DST_COLOR;
317       break;
318     case Graphics::BlendFactor::SRC_ALPHA:
319       glFactor = GL_SRC_ALPHA;
320       break;
321     case Graphics::BlendFactor::ONE_MINUS_SRC_ALPHA:
322       glFactor = GL_ONE_MINUS_SRC_ALPHA;
323       break;
324     case Graphics::BlendFactor::DST_ALPHA:
325       glFactor = GL_DST_ALPHA;
326       break;
327     case Graphics::BlendFactor::ONE_MINUS_DST_ALPHA:
328       glFactor = GL_ONE_MINUS_DST_ALPHA;
329       break;
330     case Graphics::BlendFactor::CONSTANT_COLOR:
331       glFactor = GL_CONSTANT_COLOR;
332       break;
333     case Graphics::BlendFactor::ONE_MINUS_CONSTANT_COLOR:
334       glFactor = GL_ONE_MINUS_CONSTANT_COLOR;
335       break;
336     case Graphics::BlendFactor::CONSTANT_ALPHA:
337       glFactor = GL_CONSTANT_ALPHA;
338       break;
339     case Graphics::BlendFactor::ONE_MINUS_CONSTANT_ALPHA:
340       glFactor = GL_ONE_MINUS_CONSTANT_ALPHA;
341       break;
342     case Graphics::BlendFactor::SRC_ALPHA_SATURATE:
343       glFactor = GL_SRC_ALPHA_SATURATE;
344       break;
345       // GLES doesn't appear to have dual source blending.
346     case Graphics::BlendFactor::SRC1_COLOR:
347       glFactor = GL_SRC_COLOR;
348       break;
349     case Graphics::BlendFactor::ONE_MINUS_SRC1_COLOR:
350       glFactor = GL_ONE_MINUS_SRC_COLOR;
351       break;
352     case Graphics::BlendFactor::SRC1_ALPHA:
353       glFactor = GL_SRC_ALPHA;
354       break;
355     case Graphics::BlendFactor::ONE_MINUS_SRC1_ALPHA:
356       glFactor = GL_ONE_MINUS_SRC_ALPHA;
357       break;
358   }
359   return glFactor;
360 }
361
362 GLenum GetBlendOp(Graphics::BlendOp blendOp)
363 {
364   GLenum op = GL_FUNC_ADD;
365   switch(blendOp)
366   {
367     case Graphics::BlendOp::ADD:
368       op = GL_FUNC_ADD;
369       break;
370     case Graphics::BlendOp::SUBTRACT:
371       op = GL_FUNC_SUBTRACT;
372       break;
373     case Graphics::BlendOp::REVERSE_SUBTRACT:
374       op = GL_FUNC_REVERSE_SUBTRACT;
375       break;
376     case Graphics::BlendOp::MIN:
377       op = GL_MIN;
378       break;
379     case Graphics::BlendOp::MAX:
380       op = GL_MAX;
381       break;
382
383       // @todo Add advanced blend equations
384   }
385   return op;
386 }
387
388 struct GLCompareOp
389 {
390   constexpr explicit GLCompareOp(Graphics::CompareOp compareOp)
391   {
392     switch(compareOp)
393     {
394       case Graphics::CompareOp::NEVER:
395         op = GL_NEVER;
396         break;
397       case Graphics::CompareOp::LESS:
398         op = GL_LESS;
399         break;
400       case Graphics::CompareOp::EQUAL:
401         op = GL_EQUAL;
402         break;
403       case Graphics::CompareOp::LESS_OR_EQUAL:
404         op = GL_LEQUAL;
405         break;
406       case Graphics::CompareOp::GREATER:
407         op = GL_GREATER;
408         break;
409       case Graphics::CompareOp::NOT_EQUAL:
410         op = GL_NOTEQUAL;
411         break;
412       case Graphics::CompareOp::GREATER_OR_EQUAL:
413         op = GL_GEQUAL;
414         break;
415       case Graphics::CompareOp::ALWAYS:
416         op = GL_ALWAYS;
417         break;
418     }
419   }
420   GLenum op{GL_LESS};
421 };
422
423 struct GLStencilOp
424 {
425   constexpr explicit GLStencilOp(Graphics::StencilOp stencilOp)
426   {
427     switch(stencilOp)
428     {
429       case Graphics::StencilOp::KEEP:
430         op = GL_KEEP;
431         break;
432       case Graphics::StencilOp::ZERO:
433         op = GL_ZERO;
434         break;
435       case Graphics::StencilOp::REPLACE:
436         op = GL_REPLACE;
437         break;
438       case Graphics::StencilOp::INCREMENT_AND_CLAMP:
439         op = GL_INCR;
440         break;
441       case Graphics::StencilOp::DECREMENT_AND_CLAMP:
442         op = GL_DECR;
443         break;
444       case Graphics::StencilOp::INVERT:
445         op = GL_INVERT;
446         break;
447       case Graphics::StencilOp::INCREMENT_AND_WRAP:
448         op = GL_INCR_WRAP;
449         break;
450       case Graphics::StencilOp::DECREMENT_AND_WRAP:
451         op = GL_DECR_WRAP;
452         break;
453     }
454   }
455   GLenum op{GL_KEEP};
456 };
457
458 class TestGraphicsMemory : public Graphics::Memory
459 {
460 public:
461   TestGraphicsMemory(TraceCallStack& callStack, TestGraphicsBuffer& buffer, uint32_t mappedOffset, uint32_t mappedSize)
462   : mCallStack(callStack),
463     mBuffer(buffer),
464     mMappedOffset(mappedOffset),
465     mMappedSize(mappedSize),
466     mLockedOffset(0u),
467     mLockedSize(0u)
468   {
469   }
470
471   void* LockRegion(uint32_t offset, uint32_t size) override
472   {
473     std::ostringstream o;
474     o << offset << ", " << size;
475     mCallStack.PushCall("Memory::LockRegion", o.str());
476
477     if(offset > mMappedOffset + mMappedSize ||
478        size + offset > mMappedOffset + mMappedSize)
479     {
480       fprintf(stderr, "TestGraphics.Memory::LockRegion() Out of bounds");
481       mBuffer.memory.resize(mMappedOffset + offset + size); // Grow to prevent memcpy from crashing
482     }
483     mLockedOffset = offset;
484     mLockedSize   = size;
485     return &mBuffer.memory[mMappedOffset + offset];
486   }
487
488   void Unlock(bool flush) override
489   {
490     mCallStack.PushCall("Memory::Unlock", (flush ? "Flush" : "NoFlush"));
491     if(flush)
492     {
493       Flush();
494     }
495   }
496
497   void Flush() override
498   {
499     mCallStack.PushCall("Memory::Flush", "");
500     mBuffer.Bind();
501     mBuffer.Upload(mMappedOffset + mLockedOffset, mLockedSize);
502     mBuffer.Unbind();
503   }
504
505   TraceCallStack&     mCallStack;
506   TestGraphicsBuffer& mBuffer;
507   uint32_t            mMappedOffset;
508   uint32_t            mMappedSize;
509   uint32_t            mLockedOffset;
510   uint32_t            mLockedSize;
511 };
512
513 TestGraphicsController::TestGraphicsController()
514 : mCallStack(true, "TestGraphicsController."),
515   mCommandBufferCallStack(true, "TestCommandBuffer."),
516   mFrameBufferCallStack(true, "TestFrameBuffer.")
517 {
518   mCallStack.Enable(true);
519   mCommandBufferCallStack.Enable(true);
520   auto& trace = mGl.GetTextureTrace();
521   trace.Enable(true);
522   trace.EnableLogging(true);
523 }
524
525 void TestGraphicsController::SubmitCommandBuffers(const Graphics::SubmitInfo& submitInfo)
526 {
527   TraceCallStack::NamedParams namedParams;
528   namedParams["submitInfo"] << "cmdBuffer[" << submitInfo.cmdBuffer.size()
529                             << "], flags:" << std::hex << submitInfo.flags;
530
531   mCallStack.PushCall("SubmitCommandBuffers", "", namedParams);
532
533   mSubmitStack.emplace_back(submitInfo);
534
535   for(auto& graphicsCommandBuffer : submitInfo.cmdBuffer)
536   {
537     auto commandBuffer = Uncast<TestGraphicsCommandBuffer>(graphicsCommandBuffer);
538     ProcessCommandBuffer(*commandBuffer);
539   }
540 }
541
542 void TestGraphicsController::ProcessCommandBuffer(TestGraphicsCommandBuffer& commandBuffer)
543 {
544   bool                     scissorEnabled = false;
545   TestGraphicsFramebuffer* currentFramebuffer{nullptr};
546   TestGraphicsPipeline*    currentPipeline{nullptr};
547
548   for(auto& cmd : commandBuffer.GetCommands())
549   {
550     // process command
551     switch(cmd.type)
552     {
553       case CommandType::FLUSH:
554       {
555         // Nothing to do here
556         break;
557       }
558       case CommandType::BIND_TEXTURES:
559       {
560         for(auto& binding : cmd.data.bindTextures.textureBindings)
561         {
562           if(binding.texture)
563           {
564             auto texture = Uncast<TestGraphicsTexture>(binding.texture);
565             texture->Bind(binding.binding);
566
567             if(binding.sampler)
568             {
569               auto sampler = Uncast<TestGraphicsSampler>(binding.sampler);
570               if(sampler)
571               {
572                 sampler->Apply(texture->GetTarget());
573               }
574             }
575
576             texture->Prepare(); // Ensure native texture is ready
577           }
578         }
579         break;
580       }
581       case CommandType::BIND_VERTEX_BUFFERS:
582       {
583         for(auto& binding : cmd.data.bindVertexBuffers.vertexBufferBindings)
584         {
585           auto graphicsBuffer = binding.buffer;
586           auto vertexBuffer   = Uncast<TestGraphicsBuffer>(graphicsBuffer);
587           vertexBuffer->Bind();
588         }
589         break;
590       }
591       case CommandType::BIND_INDEX_BUFFER:
592       {
593         auto& indexBufferBinding = cmd.data.bindIndexBuffer;
594         if(indexBufferBinding.buffer)
595         {
596           auto buffer = Uncast<TestGraphicsBuffer>(indexBufferBinding.buffer);
597           buffer->Bind();
598         }
599         break;
600       }
601       case CommandType::BIND_UNIFORM_BUFFER:
602       {
603         if(currentPipeline)
604         {
605           auto& bindings = cmd.data.bindUniformBuffers;
606           auto  buffer   = bindings.standaloneUniformsBufferBinding;
607
608           // based on reflection, issue gl calls
609           buffer.buffer->BindAsUniformBuffer(static_cast<const TestGraphicsProgram*>(currentPipeline->programState.program), bindings.standaloneUniformsBufferBinding);
610         }
611         break;
612       }
613       case CommandType::BIND_SAMPLERS:
614       {
615         break;
616       }
617       case CommandType::BIND_PIPELINE:
618       {
619         currentPipeline = Uncast<TestGraphicsPipeline>(cmd.data.bindPipeline.pipeline);
620         BindPipeline(currentPipeline);
621         break;
622       }
623       case CommandType::DRAW:
624       {
625         if(currentPipeline)
626         {
627           mGl.DrawArrays(GetTopology(currentPipeline->inputAssemblyState.topology),
628                          0,
629                          cmd.data.draw.draw.vertexCount);
630         }
631         break;
632       }
633       case CommandType::DRAW_INDEXED:
634       {
635         if(currentPipeline)
636         {
637           mGl.DrawElements(GetTopology(currentPipeline->inputAssemblyState.topology),
638                            static_cast<GLsizei>(cmd.data.draw.drawIndexed.indexCount),
639                            GL_UNSIGNED_SHORT,
640                            reinterpret_cast<void*>(cmd.data.draw.drawIndexed.firstIndex));
641         }
642         break;
643       }
644       case CommandType::DRAW_INDEXED_INDIRECT:
645       {
646         if(currentPipeline)
647         {
648           mGl.DrawElements(GetTopology(currentPipeline->inputAssemblyState.topology),
649                            static_cast<GLsizei>(cmd.data.draw.drawIndexed.indexCount),
650                            GL_UNSIGNED_SHORT,
651                            reinterpret_cast<void*>(cmd.data.draw.drawIndexed.firstIndex));
652         }
653         break;
654       }
655       case CommandType::SET_SCISSOR:
656       {
657         if(scissorEnabled)
658         {
659           auto& rect = cmd.data.scissor.region;
660           mGl.Scissor(rect.x, rect.y, rect.width, rect.height);
661         }
662         break;
663       }
664       case CommandType::SET_SCISSOR_TEST:
665       {
666         if(cmd.data.scissorTest.enable)
667         {
668           mGl.Enable(GL_SCISSOR_TEST);
669           scissorEnabled = true;
670         }
671         else
672         {
673           mGl.Disable(GL_SCISSOR_TEST);
674           scissorEnabled = false;
675         }
676         break;
677       }
678       case CommandType::SET_VIEWPORT_TEST:
679       {
680         break;
681       }
682       case CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
683       {
684         auto& rect = cmd.data.viewport.region;
685         mGl.Viewport(rect.x, rect.y, rect.width, rect.height);
686         break;
687       }
688
689       case CommandType::SET_COLOR_MASK:
690       {
691         // Set all channels to the same mask
692         const bool mask = cmd.data.colorMask.enabled;
693         mGl.ColorMask(mask, mask, mask, mask);
694         break;
695       }
696       case CommandType::CLEAR_STENCIL_BUFFER:
697       {
698         mGl.Clear(GL_STENCIL_BUFFER_BIT);
699         break;
700       }
701       case CommandType::CLEAR_DEPTH_BUFFER:
702       {
703         mGl.Clear(GL_DEPTH_BUFFER_BIT);
704         break;
705       }
706
707       case CommandType::SET_STENCIL_TEST_ENABLE:
708       {
709         if(cmd.data.stencilTest.enabled)
710         {
711           mGl.Enable(GL_STENCIL_TEST);
712         }
713         else
714         {
715           mGl.Disable(GL_STENCIL_TEST);
716         }
717         break;
718       }
719
720       case CommandType::SET_STENCIL_FUNC:
721       {
722         mGl.StencilFunc(GLCompareOp(cmd.data.stencilFunc.compareOp).op,
723                         cmd.data.stencilFunc.reference,
724                         cmd.data.stencilFunc.compareMask);
725         break;
726       }
727
728       case CommandType::SET_STENCIL_WRITE_MASK:
729       {
730         mGl.StencilMask(cmd.data.stencilWriteMask.mask);
731         break;
732       }
733       case CommandType::SET_STENCIL_OP:
734       {
735         mGl.StencilOp(GLStencilOp(cmd.data.stencilOp.failOp).op,
736                       GLStencilOp(cmd.data.stencilOp.depthFailOp).op,
737                       GLStencilOp(cmd.data.stencilOp.passOp).op);
738         break;
739       }
740
741       case CommandType::SET_DEPTH_COMPARE_OP:
742       {
743         mGl.DepthFunc(GLCompareOp(cmd.data.depth.compareOp).op);
744         break;
745       }
746       case CommandType::SET_DEPTH_TEST_ENABLE:
747       {
748         if(cmd.data.depth.testEnabled)
749         {
750           mGl.Enable(GL_DEPTH_TEST);
751         }
752         else
753         {
754           mGl.Disable(GL_DEPTH_TEST);
755         }
756         break;
757       }
758       case CommandType::SET_DEPTH_WRITE_ENABLE:
759       {
760         mGl.DepthMask(cmd.data.depth.writeEnabled);
761         break;
762       }
763
764       case CommandType::EXECUTE_COMMAND_BUFFERS:
765       {
766         // Process secondary command buffers
767         for(auto& buf : cmd.data.executeCommandBuffers.buffers)
768         {
769           ProcessCommandBuffer(*Uncast<TestGraphicsCommandBuffer>(buf));
770         }
771         break;
772       }
773       case CommandType::BEGIN_RENDER_PASS:
774       {
775         auto renderTarget = Uncast<TestGraphicsRenderTarget>(cmd.data.beginRenderPass.renderTarget);
776
777         if(renderTarget)
778         {
779           auto fb = renderTarget->mCreateInfo.framebuffer;
780           if(fb)
781           {
782             if(currentFramebuffer != fb)
783             {
784               currentFramebuffer = Uncast<TestGraphicsFramebuffer>(fb);
785               currentFramebuffer->Bind();
786             }
787           }
788           else
789           {
790             mGl.BindFramebuffer(GL_FRAMEBUFFER, 0);
791           }
792         }
793         else
794         {
795           mGl.BindFramebuffer(GL_FRAMEBUFFER, 0);
796         }
797
798         auto& clearValues = cmd.data.beginRenderPass.clearValues;
799         if(clearValues.size() > 0)
800         {
801           const auto renderPass = static_cast<TestGraphicsRenderPass*>(cmd.data.beginRenderPass.renderPass);
802           if(renderPass)
803           {
804             const auto& color0 = renderPass->attachments[0];
805             GLuint      mask   = 0;
806             if(color0.loadOp == Graphics::AttachmentLoadOp::CLEAR)
807             {
808               mask |= GL_COLOR_BUFFER_BIT;
809
810               // Set clear color (todo: cache it!)
811               // Something goes wrong here if Alpha mask is GL_TRUE
812               mGl.ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
813               mGl.ClearColor(clearValues[0].color.r,
814                              clearValues[0].color.g,
815                              clearValues[0].color.b,
816                              clearValues[0].color.a);
817             }
818
819             // check for depth stencil
820             if(renderPass->attachments.size() > 1)
821             {
822               const auto& depthStencil = renderPass->attachments.back();
823               if(depthStencil.loadOp == Graphics::AttachmentLoadOp::CLEAR)
824               {
825                 mGl.DepthMask(true);
826                 uint32_t depthClearColor = 0u;
827                 if(clearValues.size() == renderPass->attachments.size())
828                 {
829                   depthClearColor = clearValues.back().depthStencil.depth;
830                 }
831                 mGl.ClearDepthf(depthClearColor);
832                 mask |= GL_DEPTH_BUFFER_BIT;
833               }
834               if(depthStencil.stencilLoadOp == Graphics::AttachmentLoadOp::CLEAR)
835               {
836                 uint32_t stencilClearColor = 0u;
837                 if(clearValues.size() == renderPass->attachments.size())
838                 {
839                   stencilClearColor = clearValues.back().depthStencil.stencil;
840                 }
841                 mGl.ClearStencil(stencilClearColor);
842                 mGl.StencilMask(0xFF); // Clear all the bitplanes (assume 8)
843                 mask |= GL_STENCIL_BUFFER_BIT;
844               }
845             }
846
847             if(mask != 0)
848             {
849               // Test scissor area and RT size
850               const auto& area = cmd.data.beginRenderPass.renderArea;
851               if(area.x == 0 &&
852                  area.y == 0 &&
853                  renderTarget &&
854                  area.width == renderTarget->mCreateInfo.extent.width &&
855                  area.height == renderTarget->mCreateInfo.extent.height)
856               {
857                 mGl.Disable(GL_SCISSOR_TEST);
858                 mGl.Clear(mask);
859               }
860               else
861               {
862                 mGl.Enable(GL_SCISSOR_TEST);
863                 mGl.Scissor(cmd.data.beginRenderPass.renderArea.x, cmd.data.beginRenderPass.renderArea.y, cmd.data.beginRenderPass.renderArea.width, cmd.data.beginRenderPass.renderArea.height);
864                 mGl.Clear(mask);
865                 mGl.Disable(GL_SCISSOR_TEST);
866               }
867             }
868           }
869           else
870           {
871             DALI_ASSERT_DEBUG(0 && "BeginRenderPass has no render pass");
872           }
873         }
874         break;
875       }
876       case CommandType::END_RENDER_PASS:
877       {
878         if(cmd.data.endRenderPass.syncObject != nullptr)
879         {
880           auto syncObject = Uncast<TestGraphicsSyncObject>(cmd.data.endRenderPass.syncObject);
881           syncObject->InitializeResource(); // create the sync object.
882         }
883         break;
884       }
885     }
886   }
887 }
888
889 void TestGraphicsController::BindPipeline(TestGraphicsPipeline* pipeline)
890 {
891   auto& vi = pipeline->vertexInputState;
892   for(auto& attribute : vi.attributes)
893   {
894     mGl.EnableVertexAttribArray(attribute.location);
895     uint32_t attributeOffset = attribute.offset;
896     GLsizei  stride          = vi.bufferBindings[attribute.binding].stride;
897
898     mGl.VertexAttribPointer(attribute.location,
899                             GetNumComponents(attribute.format),
900                             GetGlType(attribute.format),
901                             GL_FALSE, // Not normalized
902                             stride,
903                             reinterpret_cast<void*>(attributeOffset));
904   }
905
906   // Cull face setup
907   auto& rasterizationState = pipeline->rasterizationState;
908   if(rasterizationState.cullMode == Graphics::CullMode::NONE)
909   {
910     mGl.Disable(GL_CULL_FACE);
911   }
912   else
913   {
914     mGl.Enable(GL_CULL_FACE);
915     mGl.CullFace(GetCullFace(rasterizationState.cullMode));
916   }
917
918   mGl.FrontFace(GetFrontFace(rasterizationState.frontFace));
919
920   // Blending setup
921   auto& colorBlendState = pipeline->colorBlendState;
922   if(colorBlendState.blendEnable)
923   {
924     mGl.Enable(GL_BLEND);
925
926     mGl.BlendFuncSeparate(GetBlendFactor(colorBlendState.srcColorBlendFactor),
927                           GetBlendFactor(colorBlendState.dstColorBlendFactor),
928                           GetBlendFactor(colorBlendState.srcAlphaBlendFactor),
929                           GetBlendFactor(colorBlendState.dstAlphaBlendFactor));
930     if(colorBlendState.colorBlendOp != colorBlendState.alphaBlendOp)
931     {
932       mGl.BlendEquationSeparate(GetBlendOp(colorBlendState.colorBlendOp), GetBlendOp(colorBlendState.alphaBlendOp));
933     }
934     else
935     {
936       mGl.BlendEquation(GetBlendOp(colorBlendState.colorBlendOp));
937     }
938     mGl.BlendColor(colorBlendState.blendConstants[0],
939                    colorBlendState.blendConstants[1],
940                    colorBlendState.blendConstants[2],
941                    colorBlendState.blendConstants[3]);
942   }
943   else
944   {
945     mGl.Disable(GL_BLEND);
946   }
947
948   auto* program = static_cast<const TestGraphicsProgram*>(pipeline->programState.program);
949   mGl.UseProgram(program->mImpl->mId);
950 }
951
952 /**
953  * @brief Presents render target
954  * @param renderTarget render target to present
955  */
956 void TestGraphicsController::PresentRenderTarget(Graphics::RenderTarget* renderTarget)
957 {
958   TraceCallStack::NamedParams namedParams;
959   namedParams["renderTarget"] << std::hex << renderTarget;
960   mCallStack.PushCall("PresentRenderTarget", "", namedParams);
961 }
962
963 /**
964  * @brief Waits until the GPU is idle
965  */
966 void TestGraphicsController::WaitIdle()
967 {
968   mCallStack.PushCall("WaitIdle", "");
969 }
970
971 /**
972  * @brief Lifecycle pause event
973  */
974 void TestGraphicsController::Pause()
975 {
976   mCallStack.PushCall("Pause", "");
977 }
978
979 /**
980  * @brief Lifecycle resume event
981  */
982 void TestGraphicsController::Resume()
983 {
984   mCallStack.PushCall("Resume", "");
985 }
986
987 void TestGraphicsController::Shutdown()
988 {
989   mCallStack.PushCall("Shutdown", "");
990 }
991
992 void TestGraphicsController::Destroy()
993 {
994   mCallStack.PushCall("Destroy", "");
995 }
996
997 void TestGraphicsController::UpdateTextures(const std::vector<Graphics::TextureUpdateInfo>&       updateInfoList,
998                                             const std::vector<Graphics::TextureUpdateSourceInfo>& sourceList)
999 {
1000   TraceCallStack::NamedParams namedParams;
1001   namedParams["updateInfoList"] << "[" << updateInfoList.size() << "]:";
1002   namedParams["sourceList"] << "[" << sourceList.size() << "]:";
1003
1004   mCallStack.PushCall("UpdateTextures", "", namedParams);
1005
1006   // Call either TexImage2D or TexSubImage2D
1007   for(unsigned int i = 0; i < updateInfoList.size(); ++i)
1008   {
1009     auto& updateInfo = updateInfoList[i];
1010     auto& source     = sourceList[i];
1011
1012     auto texture = static_cast<TestGraphicsTexture*>(updateInfo.dstTexture);
1013     texture->Bind(0); // Use first texture unit during resource update
1014     texture->Update(updateInfo, source);
1015   }
1016 }
1017
1018 void TestGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
1019 {
1020   mCallStack.PushCall("GenerateTextureMipmaps", "");
1021
1022   auto gfxTexture = Uncast<TestGraphicsTexture>(&texture);
1023   mGl.BindTexture(gfxTexture->GetTarget(), 0);
1024   mGl.GenerateMipmap(gfxTexture->GetTarget());
1025 }
1026
1027 bool TestGraphicsController::EnableDepthStencilBuffer(bool enableDepth, bool enableStencil)
1028 {
1029   TraceCallStack::NamedParams namedParams;
1030   namedParams["enableDepth"] << (enableDepth ? "T" : "F");
1031   namedParams["enableStencil"] << (enableStencil ? "T" : "F");
1032   mCallStack.PushCall("EnableDepthStencilBuffer", "", namedParams);
1033   return false;
1034 }
1035
1036 void TestGraphicsController::RunGarbageCollector(size_t numberOfDiscardedRenderers)
1037 {
1038   TraceCallStack::NamedParams namedParams;
1039   namedParams["numberOfDiscardedRenderers"] << numberOfDiscardedRenderers;
1040   mCallStack.PushCall("RunGarbageCollector", "", namedParams);
1041 }
1042
1043 void TestGraphicsController::DiscardUnusedResources()
1044 {
1045   mCallStack.PushCall("DiscardUnusedResources", "");
1046 }
1047
1048 bool TestGraphicsController::IsDiscardQueueEmpty()
1049 {
1050   mCallStack.PushCall("IsDiscardQueueEmpty", "");
1051   return isDiscardQueueEmptyResult;
1052 }
1053
1054 /**
1055  * @brief Test if the graphics subsystem has resumed & should force a draw
1056  *
1057  * @return true if the graphics subsystem requires a re-draw
1058  */
1059 bool TestGraphicsController::IsDrawOnResumeRequired()
1060 {
1061   mCallStack.PushCall("IsDrawOnResumeRequired", "");
1062   return isDrawOnResumeRequiredResult;
1063 }
1064
1065 Graphics::UniquePtr<Graphics::Buffer> TestGraphicsController::CreateBuffer(const Graphics::BufferCreateInfo& createInfo, Graphics::UniquePtr<Graphics::Buffer>&& oldBuffer)
1066 {
1067   std::ostringstream oss;
1068   oss << "bufferCreateInfo:" << createInfo;
1069   mCallStack.PushCall("CreateBuffer", oss.str());
1070   return Graphics::MakeUnique<TestGraphicsBuffer>(mCallStack, mGl, createInfo.size, createInfo.usage);
1071 }
1072
1073 Graphics::UniquePtr<Graphics::CommandBuffer> TestGraphicsController::CreateCommandBuffer(const Graphics::CommandBufferCreateInfo& commandBufferCreateInfo, Graphics::UniquePtr<Graphics::CommandBuffer>&& oldCommandBuffer)
1074 {
1075   std::ostringstream oss;
1076   oss << "commandBufferCreateInfo:" << commandBufferCreateInfo;
1077   mCallStack.PushCall("CreateCommandBuffer", oss.str());
1078   return Graphics::MakeUnique<TestGraphicsCommandBuffer>(mCommandBufferCallStack, mGl);
1079 }
1080
1081 Graphics::UniquePtr<Graphics::RenderPass> TestGraphicsController::CreateRenderPass(const Graphics::RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<Graphics::RenderPass>&& oldRenderPass)
1082 {
1083   mCallStack.PushCall("CreateRenderPass", "");
1084   return Graphics::MakeUnique<TestGraphicsRenderPass>(mGl, renderPassCreateInfo);
1085 }
1086
1087 Graphics::UniquePtr<Graphics::Texture> TestGraphicsController::CreateTexture(const Graphics::TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Graphics::Texture>&& oldTexture)
1088 {
1089   TraceCallStack::NamedParams namedParams;
1090   namedParams["textureCreateInfo"] << textureCreateInfo;
1091   mCallStack.PushCall("CreateTexture", namedParams.str(), namedParams);
1092
1093   return Graphics::MakeUnique<TestGraphicsTexture>(mGl, textureCreateInfo);
1094 }
1095
1096 Graphics::UniquePtr<Graphics::Framebuffer> TestGraphicsController::CreateFramebuffer(
1097   const Graphics::FramebufferCreateInfo&       createInfo,
1098   Graphics::UniquePtr<Graphics::Framebuffer>&& oldFramebuffer)
1099 {
1100   TraceCallStack::NamedParams namedParams;
1101   namedParams["framebufferCreateInfo"] << createInfo;
1102   mCallStack.PushCall("Controller::CreateFramebuffer", namedParams.str(), namedParams);
1103
1104   return Graphics::MakeUnique<TestGraphicsFramebuffer>(mFrameBufferCallStack, mGl, createInfo);
1105 }
1106
1107 Graphics::UniquePtr<Graphics::Pipeline> TestGraphicsController::CreatePipeline(const Graphics::PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
1108 {
1109   mCallStack.PushCall("CreatePipeline", "");
1110   return std::make_unique<TestGraphicsPipeline>(mGl, pipelineCreateInfo);
1111 }
1112
1113 Graphics::UniquePtr<Graphics::Program> TestGraphicsController::CreateProgram(const Graphics::ProgramCreateInfo& programCreateInfo, Graphics::UniquePtr<Graphics::Program>&& oldProgram)
1114 {
1115   mCallStack.PushCall("CreateProgram", "");
1116
1117   for(auto cacheEntry : mProgramCache)
1118   {
1119     bool found = true;
1120     for(auto& shader : *(programCreateInfo.shaderState))
1121     {
1122       auto                 graphicsShader = Uncast<TestGraphicsShader>(shader.shader);
1123       std::vector<uint8_t> source;
1124       source.resize(graphicsShader->mCreateInfo.sourceSize);
1125       memcpy(&source[0], graphicsShader->mCreateInfo.sourceData, graphicsShader->mCreateInfo.sourceSize);
1126
1127       if(!std::equal(source.begin(), source.end(), cacheEntry.shaders[shader.pipelineStage].begin()))
1128       {
1129         found = false;
1130         break;
1131       }
1132     }
1133     if(found)
1134     {
1135       return Graphics::MakeUnique<TestGraphicsProgram>(cacheEntry.programImpl);
1136     }
1137   }
1138
1139   mProgramCache.emplace_back();
1140   mProgramCache.back().programImpl = new TestGraphicsProgramImpl(mGl, programCreateInfo, mVertexFormats, mCustomUniforms);
1141   for(auto& shader : *(programCreateInfo.shaderState))
1142   {
1143     auto graphicsShader = Uncast<TestGraphicsShader>(shader.shader);
1144     mProgramCache.back().shaders[shader.pipelineStage].resize(graphicsShader->mCreateInfo.sourceSize);
1145     memcpy(&mProgramCache.back().shaders[shader.pipelineStage][0], graphicsShader->mCreateInfo.sourceData, graphicsShader->mCreateInfo.sourceSize);
1146   }
1147   return Graphics::MakeUnique<TestGraphicsProgram>(mProgramCache.back().programImpl);
1148 }
1149
1150 Graphics::UniquePtr<Graphics::Shader> TestGraphicsController::CreateShader(const Graphics::ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Graphics::Shader>&& oldShader)
1151 {
1152   mCallStack.PushCall("CreateShader", "");
1153   return Graphics::MakeUnique<TestGraphicsShader>(mGl, shaderCreateInfo);
1154 }
1155
1156 Graphics::UniquePtr<Graphics::Sampler> TestGraphicsController::CreateSampler(const Graphics::SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Graphics::Sampler>&& oldSampler)
1157 {
1158   TraceCallStack::NamedParams namedParams;
1159   namedParams["samplerCreateInfo"] << samplerCreateInfo;
1160   mCallStack.PushCall("CreateSampler", namedParams.str(), namedParams);
1161
1162   return Graphics::MakeUnique<TestGraphicsSampler>(mGl, samplerCreateInfo);
1163 }
1164
1165 Graphics::UniquePtr<Graphics::RenderTarget> TestGraphicsController::CreateRenderTarget(const Graphics::RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<Graphics::RenderTarget>&& oldRenderTarget)
1166 {
1167   mCallStack.PushCall("CreateRenderTarget", "");
1168   return Graphics::MakeUnique<TestGraphicsRenderTarget>(mGl, renderTargetCreateInfo);
1169 }
1170
1171 Graphics::UniquePtr<Graphics::SyncObject> TestGraphicsController::CreateSyncObject(
1172   const Graphics::SyncObjectCreateInfo&       syncObjectCreateInfo,
1173   Graphics::UniquePtr<Graphics::SyncObject>&& oldSyncObject)
1174 {
1175   mCallStack.PushCall("CreateSyncObject", "");
1176   return Graphics::MakeUnique<TestGraphicsSyncObject>(mGraphicsSyncImpl, syncObjectCreateInfo);
1177 }
1178
1179 Graphics::UniquePtr<Graphics::Memory> TestGraphicsController::MapBufferRange(const Graphics::MapBufferInfo& mapInfo)
1180 {
1181   mCallStack.PushCall("MapBufferRange", "");
1182
1183   auto buffer = static_cast<TestGraphicsBuffer*>(mapInfo.buffer);
1184   buffer->memory.resize(mapInfo.offset + mapInfo.size); // For initial testing, allow writes past capacity
1185
1186   return std::make_unique<TestGraphicsMemory>(mCallStack, *buffer, mapInfo.offset, mapInfo.size);
1187 }
1188
1189 Graphics::UniquePtr<Graphics::Memory> TestGraphicsController::MapTextureRange(const Graphics::MapTextureInfo& mapInfo)
1190 {
1191   mCallStack.PushCall("MapTextureRange", "");
1192   return nullptr;
1193 }
1194
1195 void TestGraphicsController::UnmapMemory(Graphics::UniquePtr<Graphics::Memory> memory)
1196 {
1197   mCallStack.PushCall("UnmapMemory", "");
1198 }
1199
1200 Graphics::MemoryRequirements TestGraphicsController::GetTextureMemoryRequirements(Graphics::Texture& texture) const
1201 {
1202   mCallStack.PushCall("GetTextureMemoryRequirements", "");
1203   return Graphics::MemoryRequirements{};
1204 }
1205
1206 Graphics::MemoryRequirements TestGraphicsController::GetBufferMemoryRequirements(Graphics::Buffer& buffer) const
1207 {
1208   mCallStack.PushCall("GetBufferMemoryRequirements", "");
1209   return Graphics::MemoryRequirements{};
1210 }
1211
1212 const Graphics::TextureProperties& TestGraphicsController::GetTextureProperties(const Graphics::Texture& texture)
1213 {
1214   static Graphics::TextureProperties textureProperties{};
1215   mCallStack.PushCall("GetTextureProperties", "");
1216
1217   return textureProperties;
1218 }
1219
1220 const Graphics::Reflection& TestGraphicsController::GetProgramReflection(const Graphics::Program& program)
1221 {
1222   mCallStack.PushCall("GetProgramReflection", "");
1223
1224   return static_cast<const TestGraphicsProgram*>(&program)->GetReflection();
1225 }
1226
1227 bool TestGraphicsController::PipelineEquals(const Graphics::Pipeline& pipeline0, const Graphics::Pipeline& pipeline1) const
1228 {
1229   mCallStack.PushCall("PipelineEquals", "");
1230   return false;
1231 }
1232
1233 bool TestGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
1234 {
1235   mCallStack.PushCall("GetProgramParameter", "");
1236   auto graphicsProgram = Uncast<TestGraphicsProgram>(&program);
1237   return graphicsProgram->GetParameter(parameterId, outData);
1238 }
1239
1240 } // namespace Dali