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