Merge branch 'devel/master' into devel/graphics
[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         auto& bindings = cmd.data.bindUniformBuffers;
604         auto  buffer   = bindings.standaloneUniformsBufferBinding;
605
606         // based on reflection, issue gl calls
607         buffer.buffer->BindAsUniformBuffer(static_cast<const TestGraphicsProgram*>(currentPipeline->programState.program), bindings.standaloneUniformsBufferBinding);
608         break;
609       }
610       case CommandType::BIND_SAMPLERS:
611       {
612         break;
613       }
614       case CommandType::BIND_PIPELINE:
615       {
616         currentPipeline = Uncast<TestGraphicsPipeline>(cmd.data.bindPipeline.pipeline);
617         BindPipeline(currentPipeline);
618         break;
619       }
620       case CommandType::DRAW:
621       {
622         mGl.DrawArrays(GetTopology(currentPipeline->inputAssemblyState.topology),
623                        0,
624                        cmd.data.draw.draw.vertexCount);
625         break;
626       }
627       case CommandType::DRAW_INDEXED:
628       {
629         mGl.DrawElements(GetTopology(currentPipeline->inputAssemblyState.topology),
630                          static_cast<GLsizei>(cmd.data.draw.drawIndexed.indexCount),
631                          GL_UNSIGNED_SHORT,
632                          reinterpret_cast<void*>(cmd.data.draw.drawIndexed.firstIndex));
633         break;
634       }
635       case CommandType::DRAW_INDEXED_INDIRECT:
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         break;
642       }
643       case CommandType::SET_SCISSOR:
644       {
645         if(scissorEnabled)
646         {
647           auto& rect = cmd.data.scissor.region;
648           mGl.Scissor(rect.x, rect.y, rect.width, rect.height);
649         }
650         break;
651       }
652       case CommandType::SET_SCISSOR_TEST:
653       {
654         if(cmd.data.scissorTest.enable)
655         {
656           mGl.Enable(GL_SCISSOR_TEST);
657           scissorEnabled = true;
658         }
659         else
660         {
661           mGl.Disable(GL_SCISSOR_TEST);
662           scissorEnabled = false;
663         }
664         break;
665       }
666       case CommandType::SET_VIEWPORT_TEST:
667       {
668         break;
669       }
670       case CommandType::SET_VIEWPORT: // @todo Consider correcting for orientation here?
671       {
672         auto& rect = cmd.data.viewport.region;
673         mGl.Viewport(rect.x, rect.y, rect.width, rect.height);
674         break;
675       }
676
677       case CommandType::SET_COLOR_MASK:
678       {
679         // Set all channels to the same mask
680         const bool mask = cmd.data.colorMask.enabled;
681         mGl.ColorMask(mask, mask, mask, mask);
682         break;
683       }
684       case CommandType::CLEAR_STENCIL_BUFFER:
685       {
686         mGl.Clear(GL_STENCIL_BUFFER_BIT);
687         break;
688       }
689       case CommandType::CLEAR_DEPTH_BUFFER:
690       {
691         mGl.Clear(GL_DEPTH_BUFFER_BIT);
692         break;
693       }
694
695       case CommandType::SET_STENCIL_TEST_ENABLE:
696       {
697         if(cmd.data.stencilTest.enabled)
698         {
699           mGl.Enable(GL_STENCIL_TEST);
700         }
701         else
702         {
703           mGl.Disable(GL_STENCIL_TEST);
704         }
705         break;
706       }
707
708       case CommandType::SET_STENCIL_FUNC:
709       {
710         mGl.StencilFunc(GLCompareOp(cmd.data.stencilFunc.compareOp).op,
711                         cmd.data.stencilFunc.reference,
712                         cmd.data.stencilFunc.compareMask);
713         break;
714       }
715
716       case CommandType::SET_STENCIL_WRITE_MASK:
717       {
718         mGl.StencilMask(cmd.data.stencilWriteMask.mask);
719         break;
720       }
721       case CommandType::SET_STENCIL_OP:
722       {
723         mGl.StencilOp(GLStencilOp(cmd.data.stencilOp.failOp).op,
724                       GLStencilOp(cmd.data.stencilOp.depthFailOp).op,
725                       GLStencilOp(cmd.data.stencilOp.passOp).op);
726         break;
727       }
728
729       case CommandType::SET_DEPTH_COMPARE_OP:
730       {
731         mGl.DepthFunc(GLCompareOp(cmd.data.depth.compareOp).op);
732         break;
733       }
734       case CommandType::SET_DEPTH_TEST_ENABLE:
735       {
736         if(cmd.data.depth.testEnabled)
737         {
738           mGl.Enable(GL_DEPTH_TEST);
739         }
740         else
741         {
742           mGl.Disable(GL_DEPTH_TEST);
743         }
744         break;
745       }
746       case CommandType::SET_DEPTH_WRITE_ENABLE:
747       {
748         mGl.DepthMask(cmd.data.depth.writeEnabled);
749         break;
750       }
751
752       case CommandType::EXECUTE_COMMAND_BUFFERS:
753       {
754         // Process secondary command buffers
755         for(auto& buf : cmd.data.executeCommandBuffers.buffers)
756         {
757           ProcessCommandBuffer(*Uncast<TestGraphicsCommandBuffer>(buf));
758         }
759         break;
760       }
761       case CommandType::BEGIN_RENDER_PASS:
762       {
763         auto renderTarget = Uncast<TestGraphicsRenderTarget>(cmd.data.beginRenderPass.renderTarget);
764
765         if(renderTarget)
766         {
767           auto fb = renderTarget->mCreateInfo.framebuffer;
768           if(fb)
769           {
770             if(currentFramebuffer != fb)
771             {
772               currentFramebuffer = Uncast<TestGraphicsFramebuffer>(fb);
773               currentFramebuffer->Bind();
774             }
775           }
776           else
777           {
778             mGl.BindFramebuffer(GL_FRAMEBUFFER, 0);
779           }
780         }
781         else
782         {
783           mGl.BindFramebuffer(GL_FRAMEBUFFER, 0);
784         }
785
786         auto& clearValues = cmd.data.beginRenderPass.clearValues;
787         if(clearValues.size() > 0)
788         {
789           const auto renderPass = static_cast<TestGraphicsRenderPass*>(cmd.data.beginRenderPass.renderPass);
790           if(renderPass)
791           {
792             const auto& color0 = renderPass->attachments[0];
793             GLuint      mask   = 0;
794             if(color0.loadOp == Graphics::AttachmentLoadOp::CLEAR)
795             {
796               mask |= GL_COLOR_BUFFER_BIT;
797
798               // Set clear color (todo: cache it!)
799               // Something goes wrong here if Alpha mask is GL_TRUE
800               mGl.ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
801               mGl.ClearColor(clearValues[0].color.r,
802                              clearValues[0].color.g,
803                              clearValues[0].color.b,
804                              clearValues[0].color.a);
805             }
806
807             // check for depth stencil
808             if(renderPass->attachments.size() > 1)
809             {
810               const auto& depthStencil = renderPass->attachments.back();
811               if(depthStencil.loadOp == Graphics::AttachmentLoadOp::CLEAR)
812               {
813                 mGl.DepthMask(true);
814                 uint32_t depthClearColor = 0u;
815                 if(clearValues.size() == renderPass->attachments.size())
816                 {
817                   depthClearColor = clearValues.back().depthStencil.depth;
818                 }
819                 mGl.ClearDepthf(depthClearColor);
820                 mask |= GL_DEPTH_BUFFER_BIT;
821               }
822               if(depthStencil.stencilLoadOp == Graphics::AttachmentLoadOp::CLEAR)
823               {
824                 uint32_t stencilClearColor = 0u;
825                 if(clearValues.size() == renderPass->attachments.size())
826                 {
827                   stencilClearColor = clearValues.back().depthStencil.stencil;
828                 }
829                 mGl.ClearStencil(stencilClearColor);
830                 mGl.StencilMask(0xFF); // Clear all the bitplanes (assume 8)
831                 mask |= GL_STENCIL_BUFFER_BIT;
832               }
833             }
834
835             if(mask != 0)
836             {
837               // Test scissor area and RT size
838               const auto& area = cmd.data.beginRenderPass.renderArea;
839               if(area.x == 0 &&
840                  area.y == 0 &&
841                  area.width == renderTarget->mCreateInfo.extent.width &&
842                  area.height == renderTarget->mCreateInfo.extent.height)
843               {
844                 mGl.Disable(GL_SCISSOR_TEST);
845                 mGl.Clear(mask);
846               }
847               else
848               {
849                 mGl.Enable(GL_SCISSOR_TEST);
850                 mGl.Scissor(cmd.data.beginRenderPass.renderArea.x, cmd.data.beginRenderPass.renderArea.y, cmd.data.beginRenderPass.renderArea.width, cmd.data.beginRenderPass.renderArea.height);
851                 mGl.Clear(mask);
852                 mGl.Disable(GL_SCISSOR_TEST);
853               }
854             }
855           }
856           else
857           {
858             DALI_ASSERT_DEBUG(0 && "BeginRenderPass has no render pass");
859           }
860         }
861         break;
862       }
863       case CommandType::END_RENDER_PASS:
864       {
865         if(cmd.data.endRenderPass.syncObject != nullptr)
866         {
867           auto syncObject = Uncast<TestGraphicsSyncObject>(cmd.data.endRenderPass.syncObject);
868           syncObject->InitializeResource(); // create the sync object.
869         }
870         break;
871       }
872     }
873   }
874 }
875
876 void TestGraphicsController::BindPipeline(TestGraphicsPipeline* pipeline)
877 {
878   auto& vi = pipeline->vertexInputState;
879   for(auto& attribute : vi.attributes)
880   {
881     mGl.EnableVertexAttribArray(attribute.location);
882     uint32_t attributeOffset = attribute.offset;
883     GLsizei  stride          = vi.bufferBindings[attribute.binding].stride;
884
885     mGl.VertexAttribPointer(attribute.location,
886                             GetNumComponents(attribute.format),
887                             GetGlType(attribute.format),
888                             GL_FALSE, // Not normalized
889                             stride,
890                             reinterpret_cast<void*>(attributeOffset));
891   }
892
893   // Cull face setup
894   auto& rasterizationState = pipeline->rasterizationState;
895   if(rasterizationState.cullMode == Graphics::CullMode::NONE)
896   {
897     mGl.Disable(GL_CULL_FACE);
898   }
899   else
900   {
901     mGl.Enable(GL_CULL_FACE);
902     mGl.CullFace(GetCullFace(rasterizationState.cullMode));
903   }
904
905   mGl.FrontFace(GetFrontFace(rasterizationState.frontFace));
906
907   // Blending setup
908   auto& colorBlendState = pipeline->colorBlendState;
909   if(colorBlendState.blendEnable)
910   {
911     mGl.Enable(GL_BLEND);
912
913     mGl.BlendFuncSeparate(GetBlendFactor(colorBlendState.srcColorBlendFactor),
914                           GetBlendFactor(colorBlendState.dstColorBlendFactor),
915                           GetBlendFactor(colorBlendState.srcAlphaBlendFactor),
916                           GetBlendFactor(colorBlendState.dstAlphaBlendFactor));
917     if(colorBlendState.colorBlendOp != colorBlendState.alphaBlendOp)
918     {
919       mGl.BlendEquationSeparate(GetBlendOp(colorBlendState.colorBlendOp), GetBlendOp(colorBlendState.alphaBlendOp));
920     }
921     else
922     {
923       mGl.BlendEquation(GetBlendOp(colorBlendState.colorBlendOp));
924     }
925     mGl.BlendColor(colorBlendState.blendConstants[0],
926                    colorBlendState.blendConstants[1],
927                    colorBlendState.blendConstants[2],
928                    colorBlendState.blendConstants[3]);
929   }
930   else
931   {
932     mGl.Disable(GL_BLEND);
933   }
934
935   auto* program = static_cast<const TestGraphicsProgram*>(pipeline->programState.program);
936   mGl.UseProgram(program->mImpl->mId);
937 }
938
939 /**
940  * @brief Presents render target
941  * @param renderTarget render target to present
942  */
943 void TestGraphicsController::PresentRenderTarget(Graphics::RenderTarget* renderTarget)
944 {
945   TraceCallStack::NamedParams namedParams;
946   namedParams["renderTarget"] << std::hex << renderTarget;
947   mCallStack.PushCall("PresentRenderTarget", "", namedParams);
948 }
949
950 /**
951  * @brief Waits until the GPU is idle
952  */
953 void TestGraphicsController::WaitIdle()
954 {
955   mCallStack.PushCall("WaitIdle", "");
956 }
957
958 /**
959  * @brief Lifecycle pause event
960  */
961 void TestGraphicsController::Pause()
962 {
963   mCallStack.PushCall("Pause", "");
964 }
965
966 /**
967  * @brief Lifecycle resume event
968  */
969 void TestGraphicsController::Resume()
970 {
971   mCallStack.PushCall("Resume", "");
972 }
973
974 void TestGraphicsController::Shutdown()
975 {
976   mCallStack.PushCall("Shutdown", "");
977 }
978
979 void TestGraphicsController::Destroy()
980 {
981   mCallStack.PushCall("Destroy", "");
982 }
983
984 void TestGraphicsController::UpdateTextures(const std::vector<Graphics::TextureUpdateInfo>&       updateInfoList,
985                                             const std::vector<Graphics::TextureUpdateSourceInfo>& sourceList)
986 {
987   TraceCallStack::NamedParams namedParams;
988   namedParams["updateInfoList"] << "[" << updateInfoList.size() << "]:";
989   namedParams["sourceList"] << "[" << sourceList.size() << "]:";
990
991   mCallStack.PushCall("UpdateTextures", "", namedParams);
992
993   // Call either TexImage2D or TexSubImage2D
994   for(unsigned int i = 0; i < updateInfoList.size(); ++i)
995   {
996     auto& updateInfo = updateInfoList[i];
997     auto& source     = sourceList[i];
998
999     auto texture = static_cast<TestGraphicsTexture*>(updateInfo.dstTexture);
1000     texture->Bind(0); // Use first texture unit during resource update
1001     texture->Update(updateInfo, source);
1002   }
1003 }
1004
1005 void TestGraphicsController::GenerateTextureMipmaps(const Graphics::Texture& texture)
1006 {
1007   mCallStack.PushCall("GenerateTextureMipmaps", "");
1008
1009   auto gfxTexture = Uncast<TestGraphicsTexture>(&texture);
1010   mGl.BindTexture(gfxTexture->GetTarget(), 0);
1011   mGl.GenerateMipmap(gfxTexture->GetTarget());
1012 }
1013
1014 bool TestGraphicsController::EnableDepthStencilBuffer(bool enableDepth, bool enableStencil)
1015 {
1016   TraceCallStack::NamedParams namedParams;
1017   namedParams["enableDepth"] << (enableDepth ? "T" : "F");
1018   namedParams["enableStencil"] << (enableStencil ? "T" : "F");
1019   mCallStack.PushCall("EnableDepthStencilBuffer", "", namedParams);
1020   return false;
1021 }
1022
1023 void TestGraphicsController::RunGarbageCollector(size_t numberOfDiscardedRenderers)
1024 {
1025   TraceCallStack::NamedParams namedParams;
1026   namedParams["numberOfDiscardedRenderers"] << numberOfDiscardedRenderers;
1027   mCallStack.PushCall("RunGarbageCollector", "", namedParams);
1028 }
1029
1030 void TestGraphicsController::DiscardUnusedResources()
1031 {
1032   mCallStack.PushCall("DiscardUnusedResources", "");
1033 }
1034
1035 bool TestGraphicsController::IsDiscardQueueEmpty()
1036 {
1037   mCallStack.PushCall("IsDiscardQueueEmpty", "");
1038   return isDiscardQueueEmptyResult;
1039 }
1040
1041 /**
1042  * @brief Test if the graphics subsystem has resumed & should force a draw
1043  *
1044  * @return true if the graphics subsystem requires a re-draw
1045  */
1046 bool TestGraphicsController::IsDrawOnResumeRequired()
1047 {
1048   mCallStack.PushCall("IsDrawOnResumeRequired", "");
1049   return isDrawOnResumeRequiredResult;
1050 }
1051
1052 Graphics::UniquePtr<Graphics::Buffer> TestGraphicsController::CreateBuffer(const Graphics::BufferCreateInfo& createInfo, Graphics::UniquePtr<Graphics::Buffer>&& oldBuffer)
1053 {
1054   std::ostringstream oss;
1055   oss << "bufferCreateInfo:" << createInfo;
1056   mCallStack.PushCall("CreateBuffer", oss.str());
1057   return Graphics::MakeUnique<TestGraphicsBuffer>(mCallStack, mGl, createInfo.size, createInfo.usage);
1058 }
1059
1060 Graphics::UniquePtr<Graphics::CommandBuffer> TestGraphicsController::CreateCommandBuffer(const Graphics::CommandBufferCreateInfo& commandBufferCreateInfo, Graphics::UniquePtr<Graphics::CommandBuffer>&& oldCommandBuffer)
1061 {
1062   std::ostringstream oss;
1063   oss << "commandBufferCreateInfo:" << commandBufferCreateInfo;
1064   mCallStack.PushCall("CreateCommandBuffer", oss.str());
1065   return Graphics::MakeUnique<TestGraphicsCommandBuffer>(mCommandBufferCallStack, mGl);
1066 }
1067
1068 Graphics::UniquePtr<Graphics::RenderPass> TestGraphicsController::CreateRenderPass(const Graphics::RenderPassCreateInfo& renderPassCreateInfo, Graphics::UniquePtr<Graphics::RenderPass>&& oldRenderPass)
1069 {
1070   mCallStack.PushCall("CreateRenderPass", "");
1071   return Graphics::MakeUnique<TestGraphicsRenderPass>(mGl, renderPassCreateInfo);
1072 }
1073
1074 Graphics::UniquePtr<Graphics::Texture> TestGraphicsController::CreateTexture(const Graphics::TextureCreateInfo& textureCreateInfo, Graphics::UniquePtr<Graphics::Texture>&& oldTexture)
1075 {
1076   TraceCallStack::NamedParams namedParams;
1077   namedParams["textureCreateInfo"] << textureCreateInfo;
1078   mCallStack.PushCall("CreateTexture", namedParams.str(), namedParams);
1079
1080   return Graphics::MakeUnique<TestGraphicsTexture>(mGl, textureCreateInfo);
1081 }
1082
1083 Graphics::UniquePtr<Graphics::Framebuffer> TestGraphicsController::CreateFramebuffer(
1084   const Graphics::FramebufferCreateInfo&       createInfo,
1085   Graphics::UniquePtr<Graphics::Framebuffer>&& oldFramebuffer)
1086 {
1087   TraceCallStack::NamedParams namedParams;
1088   namedParams["framebufferCreateInfo"] << createInfo;
1089   mCallStack.PushCall("Controller::CreateFramebuffer", namedParams.str(), namedParams);
1090
1091   return Graphics::MakeUnique<TestGraphicsFramebuffer>(mFrameBufferCallStack, mGl, createInfo);
1092 }
1093
1094 Graphics::UniquePtr<Graphics::Pipeline> TestGraphicsController::CreatePipeline(const Graphics::PipelineCreateInfo& pipelineCreateInfo, Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
1095 {
1096   mCallStack.PushCall("CreatePipeline", "");
1097   return std::make_unique<TestGraphicsPipeline>(mGl, pipelineCreateInfo);
1098 }
1099
1100 Graphics::UniquePtr<Graphics::Program> TestGraphicsController::CreateProgram(const Graphics::ProgramCreateInfo& programCreateInfo, Graphics::UniquePtr<Graphics::Program>&& oldProgram)
1101 {
1102   mCallStack.PushCall("CreateProgram", "");
1103
1104   for(auto cacheEntry : mProgramCache)
1105   {
1106     bool found = true;
1107     for(auto& shader : *(programCreateInfo.shaderState))
1108     {
1109       auto                 graphicsShader = Uncast<TestGraphicsShader>(shader.shader);
1110       std::vector<uint8_t> source;
1111       source.resize(graphicsShader->mCreateInfo.sourceSize);
1112       memcpy(&source[0], graphicsShader->mCreateInfo.sourceData, graphicsShader->mCreateInfo.sourceSize);
1113
1114       if(!std::equal(source.begin(), source.end(), cacheEntry.shaders[shader.pipelineStage].begin()))
1115       {
1116         found = false;
1117         break;
1118       }
1119     }
1120     if(found)
1121     {
1122       return Graphics::MakeUnique<TestGraphicsProgram>(cacheEntry.programImpl);
1123     }
1124   }
1125
1126   mProgramCache.emplace_back();
1127   mProgramCache.back().programImpl = new TestGraphicsProgramImpl(mGl, programCreateInfo, mVertexFormats, mCustomUniforms);
1128   for(auto& shader : *(programCreateInfo.shaderState))
1129   {
1130     auto graphicsShader = Uncast<TestGraphicsShader>(shader.shader);
1131     mProgramCache.back().shaders[shader.pipelineStage].resize(graphicsShader->mCreateInfo.sourceSize);
1132     memcpy(&mProgramCache.back().shaders[shader.pipelineStage][0], graphicsShader->mCreateInfo.sourceData, graphicsShader->mCreateInfo.sourceSize);
1133   }
1134   return Graphics::MakeUnique<TestGraphicsProgram>(mProgramCache.back().programImpl);
1135 }
1136
1137 Graphics::UniquePtr<Graphics::Shader> TestGraphicsController::CreateShader(const Graphics::ShaderCreateInfo& shaderCreateInfo, Graphics::UniquePtr<Graphics::Shader>&& oldShader)
1138 {
1139   mCallStack.PushCall("CreateShader", "");
1140   return Graphics::MakeUnique<TestGraphicsShader>(mGl, shaderCreateInfo);
1141 }
1142
1143 Graphics::UniquePtr<Graphics::Sampler> TestGraphicsController::CreateSampler(const Graphics::SamplerCreateInfo& samplerCreateInfo, Graphics::UniquePtr<Graphics::Sampler>&& oldSampler)
1144 {
1145   TraceCallStack::NamedParams namedParams;
1146   namedParams["samplerCreateInfo"] << samplerCreateInfo;
1147   mCallStack.PushCall("CreateSampler", namedParams.str(), namedParams);
1148
1149   return Graphics::MakeUnique<TestGraphicsSampler>(mGl, samplerCreateInfo);
1150 }
1151
1152 Graphics::UniquePtr<Graphics::RenderTarget> TestGraphicsController::CreateRenderTarget(const Graphics::RenderTargetCreateInfo& renderTargetCreateInfo, Graphics::UniquePtr<Graphics::RenderTarget>&& oldRenderTarget)
1153 {
1154   mCallStack.PushCall("CreateRenderTarget", "");
1155   return Graphics::MakeUnique<TestGraphicsRenderTarget>(mGl, renderTargetCreateInfo);
1156 }
1157
1158 Graphics::UniquePtr<Graphics::SyncObject> TestGraphicsController::CreateSyncObject(
1159   const Graphics::SyncObjectCreateInfo&       syncObjectCreateInfo,
1160   Graphics::UniquePtr<Graphics::SyncObject>&& oldSyncObject)
1161 {
1162   mCallStack.PushCall("CreateSyncObject", "");
1163   return Graphics::MakeUnique<TestGraphicsSyncObject>(mGraphicsSyncImpl, syncObjectCreateInfo);
1164 }
1165
1166 Graphics::UniquePtr<Graphics::Memory> TestGraphicsController::MapBufferRange(const Graphics::MapBufferInfo& mapInfo)
1167 {
1168   mCallStack.PushCall("MapBufferRange", "");
1169
1170   auto buffer = static_cast<TestGraphicsBuffer*>(mapInfo.buffer);
1171   buffer->memory.resize(mapInfo.offset + mapInfo.size); // For initial testing, allow writes past capacity
1172
1173   return std::make_unique<TestGraphicsMemory>(mCallStack, *buffer, mapInfo.offset, mapInfo.size);
1174 }
1175
1176 Graphics::UniquePtr<Graphics::Memory> TestGraphicsController::MapTextureRange(const Graphics::MapTextureInfo& mapInfo)
1177 {
1178   mCallStack.PushCall("MapTextureRange", "");
1179   return nullptr;
1180 }
1181
1182 void TestGraphicsController::UnmapMemory(Graphics::UniquePtr<Graphics::Memory> memory)
1183 {
1184   mCallStack.PushCall("UnmapMemory", "");
1185 }
1186
1187 Graphics::MemoryRequirements TestGraphicsController::GetTextureMemoryRequirements(Graphics::Texture& texture) const
1188 {
1189   mCallStack.PushCall("GetTextureMemoryRequirements", "");
1190   return Graphics::MemoryRequirements{};
1191 }
1192
1193 Graphics::MemoryRequirements TestGraphicsController::GetBufferMemoryRequirements(Graphics::Buffer& buffer) const
1194 {
1195   mCallStack.PushCall("GetBufferMemoryRequirements", "");
1196   return Graphics::MemoryRequirements{};
1197 }
1198
1199 const Graphics::TextureProperties& TestGraphicsController::GetTextureProperties(const Graphics::Texture& texture)
1200 {
1201   static Graphics::TextureProperties textureProperties{};
1202   mCallStack.PushCall("GetTextureProperties", "");
1203
1204   return textureProperties;
1205 }
1206
1207 const Graphics::Reflection& TestGraphicsController::GetProgramReflection(const Graphics::Program& program)
1208 {
1209   mCallStack.PushCall("GetProgramReflection", "");
1210
1211   return static_cast<const TestGraphicsProgram*>(&program)->GetReflection();
1212 }
1213
1214 bool TestGraphicsController::PipelineEquals(const Graphics::Pipeline& pipeline0, const Graphics::Pipeline& pipeline1) const
1215 {
1216   mCallStack.PushCall("PipelineEquals", "");
1217   return false;
1218 }
1219
1220 bool TestGraphicsController::GetProgramParameter(Graphics::Program& program, uint32_t parameterId, void* outData)
1221 {
1222   mCallStack.PushCall("GetProgramParameter", "");
1223   auto graphicsProgram = Uncast<TestGraphicsProgram>(&program);
1224   return graphicsProgram->GetParameter(parameterId, outData);
1225 }
1226
1227 } // namespace Dali