Merge branch 'devel/master' into devel/graphics
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-renderer.h
1 #ifndef DALI_INTERNAL_RENDER_RENDERER_H
2 #define DALI_INTERNAL_RENDER_RENDERER_H
3
4 /*
5  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // INTERNAL INCLUDES
22 #include <dali/public-api/math/matrix.h>
23 #include <dali/public-api/math/vector4.h>
24 #include <dali/public-api/rendering/texture-set.h>
25
26 #include <dali/graphics-api/graphics-controller.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/internal/common/blending-options.h>
29 #include <dali/internal/common/const-string.h>
30 #include <dali/internal/common/message.h>
31 #include <dali/internal/common/type-abstraction-enums.h>
32 #include <dali/internal/event/common/property-input-impl.h>
33 #include <dali/internal/render/data-providers/render-data-provider.h>
34 #include <dali/internal/render/renderers/render-geometry.h>
35 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
36 #include <dali/internal/render/shaders/program.h>
37 #include <dali/internal/update/manager/render-instruction-processor.h>
38
39 namespace Dali
40 {
41 namespace Internal
42 {
43 class Texture;
44 class ProgramCache;
45
46 namespace SceneGraph
47 {
48 class SceneController;
49 class Shader;
50 class NodeDataProvider;
51 class RenderInstruction; //for reflection effect
52 } // namespace SceneGraph
53
54 namespace Render
55 {
56 struct ShaderCache;
57 class UniformBufferManager;
58
59 /**
60  * Renderers are used to render meshes
61  * These objects are used during RenderManager::Render(), so properties modified during
62  * the Update must either be double-buffered, or set via a message added to the RenderQueue.
63  */
64 class Renderer
65 {
66 public:
67   /**
68    * @brief Struct to encapsulate stencil parameters required for control of the stencil buffer.
69    */
70   struct StencilParameters
71   {
72     StencilParameters(RenderMode::Type renderMode, StencilFunction::Type stencilFunction, int stencilFunctionMask, int stencilFunctionReference, int stencilMask, StencilOperation::Type stencilOperationOnFail, StencilOperation::Type stencilOperationOnZFail, StencilOperation::Type stencilOperationOnZPass)
73     : stencilFunctionMask(stencilFunctionMask),
74       stencilFunctionReference(stencilFunctionReference),
75       stencilMask(stencilMask),
76       renderMode(renderMode),
77       stencilFunction(stencilFunction),
78       stencilOperationOnFail(stencilOperationOnFail),
79       stencilOperationOnZFail(stencilOperationOnZFail),
80       stencilOperationOnZPass(stencilOperationOnZPass)
81     {
82     }
83
84     int                    stencilFunctionMask;         ///< The stencil function mask
85     int                    stencilFunctionReference;    ///< The stencil function reference
86     int                    stencilMask;                 ///< The stencil mask
87     RenderMode::Type       renderMode : 4;              ///< The render mode
88     StencilFunction::Type  stencilFunction : 4;         ///< The stencil function
89     StencilOperation::Type stencilOperationOnFail : 4;  ///< The stencil operation for stencil test fail
90     StencilOperation::Type stencilOperationOnZFail : 4; ///< The stencil operation for depth test fail
91     StencilOperation::Type stencilOperationOnZPass : 4; ///< The stencil operation for depth test pass
92   };
93
94   /**
95    * Create a new renderer instance
96    * @param[in] dataProviders The data providers for the renderer
97    * @param[in] geometry The geometry for the renderer
98    * @param[in] blendingBitmask A bitmask of blending options.
99    * @param[in] blendColor The blend color to pass to GL
100    * @param[in] faceCullingMode The face-culling mode.
101    * @param[in] preMultipliedAlphaEnabled whether alpha is pre-multiplied.
102    * @param[in] depthWriteMode Depth buffer write mode
103    * @param[in] depthTestMode Depth buffer test mode
104    * @param[in] depthFunction Depth function
105    * @param[in] stencilParameters Struct containing all stencil related options
106    */
107   static Renderer* New(SceneGraph::RenderDataProvider* dataProviders,
108                        Render::Geometry*               geometry,
109                        uint32_t                        blendingBitmask,
110                        const Vector4&                  blendColor,
111                        FaceCullingMode::Type           faceCullingMode,
112                        bool                            preMultipliedAlphaEnabled,
113                        DepthWriteMode::Type            depthWriteMode,
114                        DepthTestMode::Type             depthTestMode,
115                        DepthFunction::Type             depthFunction,
116                        StencilParameters&              stencilParameters);
117
118   /**
119    * Constructor.
120    * @param[in] dataProviders The data providers for the renderer
121    * @param[in] geometry The geometry for the renderer
122    * @param[in] blendingBitmask A bitmask of blending options.
123    * @param[in] blendColor The blend color to pass to GL
124    * @param[in] faceCullingMode The face-culling mode.
125    * @param[in] preMultipliedAlphaEnabled whether alpha is pre-multiplied.
126    * @param[in] depthWriteMode Depth buffer write mode
127    * @param[in] depthTestMode Depth buffer test mode
128    * @param[in] depthFunction Depth function
129    * @param[in] stencilParameters Struct containing all stencil related options
130    */
131   Renderer(SceneGraph::RenderDataProvider* dataProviders,
132            Render::Geometry*               geometry,
133            uint32_t                        blendingBitmask,
134            const Vector4&                  blendColor,
135            FaceCullingMode::Type           faceCullingMode,
136            bool                            preMultipliedAlphaEnabled,
137            DepthWriteMode::Type            depthWriteMode,
138            DepthTestMode::Type             depthTestMode,
139            DepthFunction::Type             depthFunction,
140            StencilParameters&              stencilParameters);
141
142   /**
143    * Change the geometry used by the renderer
144    * @param[in] geometry The new geometry
145    */
146   void SetGeometry(Render::Geometry* geometry);
147
148   void SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size);
149
150   /**
151    * @brief Returns a reference to an array of draw commands
152    * @return Valid array of draw commands (may be empty)
153    */
154   [[nodiscard]] const std::vector<Dali::DevelRenderer::DrawCommand>& GetDrawCommands() const
155   {
156     return mDrawCommands;
157   }
158
159   /**
160    * Second-phase construction.
161    * This is called when the renderer is inside render thread
162    * @param[in] graphicsController The graphics controller to use
163    * @param[in] programCache Cache of program objects
164    * @param[in] shaderCache Cache of shaders
165    * @param[in] uniformBufferManager Uniform buffer manager
166    */
167   void Initialize(Graphics::Controller&         graphicsController,
168                   ProgramCache&                 programCache,
169                   Render::ShaderCache&          shaderCache,
170                   Render::UniformBufferManager& uniformBufferManager);
171
172   /**
173    * Destructor
174    */
175   ~Renderer();
176
177   /**
178    * Set the face-culling mode.
179    * @param[in] mode The face-culling mode.
180    */
181   void SetFaceCullingMode(FaceCullingMode::Type mode);
182
183   /**
184    * Set the bitmask for blending options
185    * @param[in] bitmask A bitmask of blending options.
186    */
187   void SetBlendingBitMask(uint32_t bitmask);
188
189   /**
190    * Set the blend color for blending options
191    * @param[in] blendColor The blend color to pass to GL
192    */
193   void SetBlendColor(const Vector4& color);
194
195   /**
196    * Set the first element index to draw by the indexed draw
197    * @param[in] firstElement index of first element to draw
198    */
199   void SetIndexedDrawFirstElement(uint32_t firstElement);
200
201   /**
202    * Set the number of elements to draw by the indexed draw
203    * @param[in] elementsCount number of elements to draw
204    */
205   void SetIndexedDrawElementsCount(uint32_t elementsCount);
206
207   /**
208    * @brief Set whether the Pre-multiplied Alpha Blending is required
209    *
210    * @param[in] preMultipled whether alpha is pre-multiplied.
211    */
212   void EnablePreMultipliedAlpha(bool preMultipled);
213
214   /**
215    * Sets the depth write mode
216    * @param[in] depthWriteMode The depth write mode
217    */
218   void SetDepthWriteMode(DepthWriteMode::Type depthWriteMode);
219
220   /**
221    * Query the Renderer's depth write mode
222    * @return The renderer depth write mode
223    */
224   [[nodiscard]] DepthWriteMode::Type GetDepthWriteMode() const;
225
226   /**
227    * Sets the depth test mode
228    * @param[in] depthTestMode The depth test mode
229    */
230   void SetDepthTestMode(DepthTestMode::Type depthTestMode);
231
232   /**
233    * Query the Renderer's depth test mode
234    * @return The renderer depth test mode
235    */
236   [[nodiscard]] DepthTestMode::Type GetDepthTestMode() const;
237
238   /**
239    * Sets the depth function
240    * @param[in] depthFunction The depth function
241    */
242   void SetDepthFunction(DepthFunction::Type depthFunction);
243
244   /**
245    * Query the Renderer's depth function
246    * @return The renderer depth function
247    */
248   [[nodiscard]] DepthFunction::Type GetDepthFunction() const;
249
250   /**
251    * Sets the render mode
252    * @param[in] renderMode The render mode
253    */
254   void SetRenderMode(RenderMode::Type mode);
255
256   /**
257    * Gets the render mode
258    * @return The render mode
259    */
260   [[nodiscard]] RenderMode::Type GetRenderMode() const;
261
262   /**
263    * Sets the stencil function
264    * @param[in] stencilFunction The stencil function
265    */
266   void SetStencilFunction(StencilFunction::Type stencilFunction);
267
268   /**
269    * Gets the stencil function
270    * @return The stencil function
271    */
272   [[nodiscard]] StencilFunction::Type GetStencilFunction() const;
273
274   /**
275    * Sets the stencil function mask
276    * @param[in] stencilFunctionMask The stencil function mask
277    */
278   void SetStencilFunctionMask(int stencilFunctionMask);
279
280   /**
281    * Gets the stencil function mask
282    * @return The stencil function mask
283    */
284   [[nodiscard]] int GetStencilFunctionMask() const;
285
286   /**
287    * Sets the stencil function reference
288    * @param[in] stencilFunctionReference The stencil function reference
289    */
290   void SetStencilFunctionReference(int stencilFunctionReference);
291
292   /**
293    * Gets the stencil function reference
294    * @return The stencil function reference
295    */
296   [[nodiscard]] int GetStencilFunctionReference() const;
297
298   /**
299    * Sets the stencil mask
300    * @param[in] stencilMask The stencil mask
301    */
302   void SetStencilMask(int stencilMask);
303
304   /**
305    * Gets the stencil mask
306    * @return The stencil mask
307    */
308   [[nodiscard]] int GetStencilMask() const;
309
310   /**
311    * Sets the stencil operation for when the stencil test fails
312    * @param[in] stencilOperationOnFail The stencil operation
313    */
314   void SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail);
315
316   /**
317    * Gets the stencil operation for when the stencil test fails
318    * @return The stencil operation
319    */
320   [[nodiscard]] StencilOperation::Type GetStencilOperationOnFail() const;
321
322   /**
323    * Sets the stencil operation for when the depth test fails
324    * @param[in] stencilOperationOnZFail The stencil operation
325    */
326   void SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail);
327
328   /**
329    * Gets the stencil operation for when the depth test fails
330    * @return The stencil operation
331    */
332   [[nodiscard]] StencilOperation::Type GetStencilOperationOnZFail() const;
333
334   /**
335    * Sets the stencil operation for when the depth test passes
336    * @param[in] stencilOperationOnZPass The stencil operation
337    */
338   void SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass);
339
340   /**
341    * Gets the stencil operation for when the depth test passes
342    * @return The stencil operation
343    */
344   [[nodiscard]] StencilOperation::Type GetStencilOperationOnZPass() const;
345
346   /**
347    * Called to upload during RenderManager::Render().
348    */
349   void Upload();
350
351   /**
352    * Called to render during RenderManager::Render().
353    * @param[in,out] commandBuffer The command buffer to write into
354    * @param[in] bufferIndex The index of the previous update buffer.
355    * @param[in] node The node using this renderer
356    * @param[in] modelViewMatrix The model-view matrix.
357    * @param[in] viewMatrix The view matrix.
358    * @param[in] projectionMatrix The projection matrix.
359    * @param[in] size Size of the render item
360    * @param[in] blend If true, blending is enabled
361    * @param[in] boundTextures The textures bound for rendering
362    * @param[in] instruction. for use case like reflection where CullFace needs to be adjusted
363    *
364    * @return True if commands have been added to the command buffer
365    */
366   bool Render(Graphics::CommandBuffer&                             commandBuffer,
367               BufferIndex                                          bufferIndex,
368               const SceneGraph::NodeDataProvider&                  node,
369               const Matrix&                                        modelMatrix,
370               const Matrix&                                        modelViewMatrix,
371               const Matrix&                                        viewMatrix,
372               const Matrix&                                        projectionMatrix,
373               const Vector3&                                       size,
374               bool                                                 blend,
375               Vector<Graphics::Texture*>&                          boundTextures,
376               const Dali::Internal::SceneGraph::RenderInstruction& instruction,
377               uint32_t                                             queueIndex);
378
379   /**
380    * Write the renderer's sort attributes to the passed in reference
381    *
382    * @param[out] sortAttributes
383    */
384   void SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const;
385
386   /**
387    * Sets the flag indicating whether shader changed.
388    *
389    * @param[in] value True if shader changed
390    */
391   void SetShaderChanged(bool value);
392
393   /**
394    * Check if the renderer attributes/uniforms are updated and returns the flag
395    *
396    * @param[in] bufferIndex The current update buffer index.
397    * @param[in] node The node using this renderer
398    */
399   bool Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node);
400
401   template<class T>
402   bool WriteDefaultUniform(const Graphics::UniformInfo*                       uniformInfo,
403                            Render::UniformBuffer&                             ubo,
404                            const std::vector<Graphics::UniformBufferBinding>& bindings,
405                            const T&                                           data);
406
407   template<class T>
408   void WriteUniform(Render::UniformBuffer&                             ubo,
409                     const std::vector<Graphics::UniformBufferBinding>& bindings,
410                     const Graphics::UniformInfo&                       uniformInfo,
411                     const T&                                           data);
412
413   void WriteUniform(Render::UniformBuffer&                             ubo,
414                     const std::vector<Graphics::UniformBufferBinding>& bindings,
415                     const Graphics::UniformInfo&                       uniformInfo,
416                     const void*                                        data,
417                     uint32_t                                           size);
418
419 private:
420   struct UniformIndexMap;
421
422   // Undefined
423   Renderer(const Renderer&);
424
425   // Undefined
426   Renderer& operator=(const Renderer& rhs);
427
428   /**
429    * Builds a uniform map based on the index of the cached location in the Program.
430    * @param[in] bufferIndex The index of the previous update buffer.
431    * @param[in] node The node using the renderer
432    * @param[in] size The size of the renderer
433    * @param[in] program The shader program on which to set the uniforms.
434    */
435   void BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program);
436
437   /**
438    * Bind the textures and setup the samplers
439    * @param[in] commandBuffer The command buffer to record binding into
440    * @param[in] boundTextures The textures bound for rendering
441    */
442   void BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures);
443
444   /**
445    * Prepare a pipeline for this renderer.
446    *
447    * As a renderer can be re-used in a single frame (e.g. being used by multiple nodes, or
448    * by non-exclusive render tasks), we store a pipeline per node/instruction.
449    * In practice, the implementation will cached pipelines, so we normally only have
450    * multiple handles.
451    */
452   Graphics::Pipeline& PrepareGraphicsPipeline(
453     Program&                                             program,
454     const Dali::Internal::SceneGraph::RenderInstruction& instruction,
455     const SceneGraph::NodeDataProvider&                  node,
456     bool                                                 blend);
457
458   /**
459    * Setup and write data to the uniform buffer
460    *
461    * @param[in] bufferIndex The current buffer index
462    * @param[in] commandBuffer The command buffer to bind the uniform buffer to
463    * @param[in] node The node using this renderer
464    * @param[in] modelViewMatrix The model-view matrix.
465    * @param[in] viewMatrix The view matrix.
466    * @param[in] projectionMatrix The projection matrix.
467    * @param[in] size Size of the render item
468    * @param[in] blend If true, blending is enabled
469    * @param[in] instruction The render instruction
470    */
471   void WriteUniformBuffer(BufferIndex                          bufferIndex,
472                           Graphics::CommandBuffer&             commandBuffer,
473                           Program*                             program,
474                           const SceneGraph::RenderInstruction& instruction,
475                           const SceneGraph::NodeDataProvider&  node,
476                           const Matrix&                        modelMatrix,
477                           const Matrix&                        modelViewMatrix,
478                           const Matrix&                        viewMatrix,
479                           const Matrix&                        projectionMatrix,
480                           const Vector3&                       size);
481
482   /**
483    * @brief Fill uniform buffer at index. Writes uniforms into given memory address
484    *
485    * @param[in] instruction The render instruction
486    * @param[in,out] ubo Target uniform buffer object
487    * @param[out] outBindings output bindings vector
488    * @param[out] offset output offset of the next uniform buffer memory address
489    * @param[in] updateBufferIndex update buffer index
490    */
491   void FillUniformBuffer(Program&                                      program,
492                          const SceneGraph::RenderInstruction&          instruction,
493                          Render::UniformBuffer&                        ubo,
494                          std::vector<Graphics::UniformBufferBinding>*& outBindings,
495                          uint32_t&                                     offset,
496                          BufferIndex                                   updateBufferIndex);
497
498 private:
499   Graphics::Controller*                        mGraphicsController;
500   OwnerPointer<SceneGraph::RenderDataProvider> mRenderDataProvider;
501
502   Render::Geometry* mGeometry;
503
504   ProgramCache*        mProgramCache{nullptr};
505   Render::ShaderCache* mShaderCache{nullptr};
506
507   Render::UniformBufferManager*               mUniformBufferManager{};
508   std::vector<Graphics::UniformBufferBinding> mUniformBufferBindings{};
509
510   using Hash = unsigned long;
511   struct UniformIndexMap
512   {
513     ConstString              uniformName;            ///< The uniform name
514     const PropertyInputImpl* propertyValue{nullptr}; ///< The property value
515     Hash                     uniformNameHash{0u};
516     Hash                     uniformNameHashNoArray{0u};
517     int32_t                  arrayIndex{-1}; ///< The array index
518   };
519
520   using UniformIndexMappings = Dali::Vector<UniformIndexMap>;
521
522   UniformIndexMappings mUniformIndexMap;
523   Vector<int32_t>      mAttributeLocations;
524   uint64_t             mUniformsHash;
525
526   struct HashedPipeline
527   {
528     uint64_t                                mHash{0u};
529     Graphics::UniquePtr<Graphics::Pipeline> mGraphicsPipeline{nullptr};
530     inline static uint64_t                  GetHash(const void* node, const void* instruction, bool blend)
531     {
532       return (reinterpret_cast<uint64_t>(node) << 32) | ((reinterpret_cast<uint64_t>(instruction) & 0xFFFFFFF) << 1) | blend;
533     }
534   };
535   std::vector<HashedPipeline> mGraphicsPipelines{};
536
537   StencilParameters mStencilParameters; ///< Struct containing all stencil related options
538   BlendingOptions   mBlendingOptions;   ///< Blending options including blend color, blend func and blend equation
539
540   uint32_t mIndexedDrawFirstElement;  ///< Offset of first element to draw
541   uint32_t mIndexedDrawElementsCount; ///< Number of elements to draw
542
543   DepthFunction::Type   mDepthFunction : 4;             ///< The depth function
544   FaceCullingMode::Type mFaceCullingMode : 3;           ///< The mode of face culling
545   DepthWriteMode::Type  mDepthWriteMode : 3;            ///< The depth write mode
546   DepthTestMode::Type   mDepthTestMode : 3;             ///< The depth test mode
547   bool                  mUpdateAttributeLocations : 1;  ///< Indicates attribute locations have changed
548   bool                  mPremultipliedAlphaEnabled : 1; ///< Flag indicating whether the Pre-multiplied Alpha Blending is required
549   bool                  mShaderChanged : 1;             ///< Flag indicating the shader changed and uniform maps have to be updated
550   bool                  mUpdated : 1;
551
552   std::vector<Dali::DevelRenderer::DrawCommand> mDrawCommands; // Devel stuff
553
554   Graphics::UniquePtr<Render::UniformBuffer> mUniformBuffer[2]{nullptr, nullptr}; ///< The double-buffered uniform buffer
555 };
556
557 } // namespace Render
558
559 } // namespace Internal
560
561 } // namespace Dali
562
563 #endif // DALI_INTERNAL_RENDER_RENDERER_H