Reduce Render::Renderer size
[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     if(!mRenderCallbackInput)
409     {
410       mRenderCallbackInput = std::unique_ptr<RenderCallbackInput>(new RenderCallbackInput);
411     }
412     return *mRenderCallbackInput;
413   }
414
415   /**
416    * Write the renderer's sort attributes to the passed in reference
417    *
418    * @param[out] sortAttributes
419    */
420   void SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const;
421
422   /**
423    * Sets the flag indicating whether shader changed.
424    *
425    * @param[in] value True if shader changed
426    */
427   void SetShaderChanged(bool value);
428
429   /**
430    * Check if the renderer attributes/uniforms are updated and returns the flag
431    *
432    * @param[in] bufferIndex The current update buffer index.
433    */
434   bool Updated(BufferIndex bufferIndex);
435
436   template<class T>
437   bool WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo,
438                            Render::UniformBufferView&   ubo,
439                            const T&                     data);
440
441   template<class T>
442   void WriteUniform(Render::UniformBufferView&   ubo,
443                     const Graphics::UniformInfo& uniformInfo,
444                     const T&                     data);
445
446   void WriteUniform(Render::UniformBufferView&   ubo,
447                     const Graphics::UniformInfo& uniformInfo,
448                     const void*                  data,
449                     uint32_t                     size);
450
451   [[nodiscard]] FaceCullingMode::Type GetFaceCullMode() const
452   {
453     return mFaceCullingMode;
454   }
455
456   /**
457    * @brief Gets update area after visual properties applied.
458    *
459    * @param[in] bufferIndex The index of the previous update buffer.
460    * @param[in] originalUpdateArea The original update area before apply the visual properties.
461    *
462    * @return The recalculated update area after visual properties applied.
463    */
464   Vector4 GetVisualTransformedUpdateArea(BufferIndex bufferIndex, const Vector4& originalUpdateArea) const noexcept;
465
466 private:
467   struct UniformIndexMap;
468
469   // Undefined
470   Renderer(const Renderer&);
471
472   // Undefined
473   Renderer& operator=(const Renderer& rhs);
474
475   /**
476    * Builds a uniform map based on the index of the cached location in the Program.
477    * @param[in] bufferIndex The index of the previous update buffer.
478    * @param[in] node The node using the renderer
479    * @param[in] size The size of the renderer
480    * @param[in] program The shader program on which to set the uniforms.
481    *
482    * @return the index of the node in change counters store / uniform maps store.
483    */
484   std::size_t BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program);
485
486   /**
487    * Bind the textures and setup the samplers
488    * @param[in] commandBuffer The command buffer to record binding into
489    * @param[in] boundTextures The textures bound for rendering
490    */
491   void BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures);
492
493   /**
494    * Prepare a pipeline for this renderer.
495    *
496    * As a renderer can be re-used in a single frame (e.g. being used by multiple nodes, or
497    * by non-exclusive render tasks), we store a pipeline per node/instruction.
498    * In practice, the implementation will cached pipelines, so we normally only have
499    * multiple handles.
500    */
501   Graphics::Pipeline& PrepareGraphicsPipeline(
502     Program&                                             program,
503     const Dali::Internal::SceneGraph::RenderInstruction& instruction,
504     const SceneGraph::NodeDataProvider&                  node,
505     bool                                                 blend);
506
507   /**
508    * Setup and write data to the uniform buffer
509    *
510    * @param[in] bufferIndex The current buffer index
511    * @param[in] commandBuffer The command buffer to bind the uniform buffer to
512    * @param[in] node The node using this renderer
513    * @param[in] modelViewMatrix The model-view matrix.
514    * @param[in] viewMatrix The view matrix.
515    * @param[in] projectionMatrix The projection matrix.
516    * @param[in] size Size of the render item
517    * @param[in] blend If true, blending is enabled
518    * @param[in] instruction The render instruction
519    * @param[in] The node index
520    */
521   void WriteUniformBuffer(BufferIndex                          bufferIndex,
522                           Graphics::CommandBuffer&             commandBuffer,
523                           Program*                             program,
524                           const SceneGraph::RenderInstruction& instruction,
525                           const SceneGraph::NodeDataProvider&  node,
526                           const Matrix&                        modelMatrix,
527                           const Matrix&                        modelViewMatrix,
528                           const Matrix&                        viewMatrix,
529                           const Matrix&                        projectionMatrix,
530                           const Vector3&                       size,
531                           std::size_t                          nodeIndex);
532
533   /**
534    * @brief Fill uniform buffer at index. Writes uniforms into given memory address
535    *
536    * @param[in] instruction The render instruction
537    * @param[in,out] ubo Target uniform buffer object
538    * @param[out] outBindings output bindings vector
539    * @param[out] offset output offset of the next uniform buffer memory address
540    * @param[in] updateBufferIndex update buffer index
541    */
542   void FillUniformBuffer(Program&                                      program,
543                          const SceneGraph::RenderInstruction&          instruction,
544                          Render::UniformBufferView&                    ubo,
545                          std::vector<Graphics::UniformBufferBinding>*& outBindings,
546                          uint32_t&                                     offset,
547                          BufferIndex                                   updateBufferIndex,
548                          std::size_t                                   nodeIndex);
549
550 private:
551   Graphics::Controller*           mGraphicsController;
552   SceneGraph::RenderDataProvider* mRenderDataProvider;
553
554   Render::Geometry* mGeometry;
555
556   ProgramCache*        mProgramCache{nullptr};
557   Render::ShaderCache* mShaderCache{nullptr};
558
559   Render::UniformBufferManager*               mUniformBufferManager{};
560   std::vector<Graphics::UniformBufferBinding> mUniformBufferBindings{};
561
562   Render::PipelineCache* mPipelineCache{nullptr};
563
564   using Hash = std::size_t;
565
566   typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
567
568   struct UniformIndexMap
569   {
570     ConstString              uniformName;            ///< The uniform name
571     const PropertyInputImpl* propertyValue{nullptr}; ///< The property value
572     Hash                     uniformNameHash{0u};
573     Hash                     uniformNameHashNoArray{0u};
574     int32_t                  arrayIndex{-1}; ///< The array index
575
576     int16_t    uniformLocation{0u};
577     uint16_t   uniformOffset{0u};
578     uint16_t   uniformSize{0u};
579     FuncGetter uniformFunc{0};
580   };
581
582   StencilParameters mStencilParameters; ///< Struct containing all stencil related options
583   BlendingOptions   mBlendingOptions;   ///< Blending options including blend color, blend func and blend equation
584
585   uint32_t mIndexedDrawFirstElement;  ///< Offset of first element to draw
586   uint32_t mIndexedDrawElementsCount; ///< Number of elements to draw
587
588   /** Struct to map node to index into mNodeMapCounters and mUniformIndexMaps */
589   struct RenderItemLookup
590   {
591     const SceneGraph::NodeDataProvider* node{nullptr}; ///<Node key. It can be nullptr if this NodeIndex don't need node uniform
592
593     std::size_t index{0};                       ///<Index into mUniformIndexMap
594     std::size_t nodeChangeCounter{0};           ///<The last known change counter for this node's uniform map
595     std::size_t renderItemMapChangeCounter{0u}; ///< Change counter of the renderer & shader collected uniform map for this render item (node/renderer pair)
596   };
597   std::vector<RenderItemLookup> mNodeIndexMap; ///< usually only 1 element.
598   using UniformIndexMappings = std::vector<UniformIndexMap>;
599   std::vector<UniformIndexMappings> mUniformIndexMaps; ///< Cached map per node/renderer/shader.
600
601   DepthFunction::Type   mDepthFunction : 4;             ///< The depth function
602   FaceCullingMode::Type mFaceCullingMode : 3;           ///< The mode of face culling
603   DepthWriteMode::Type  mDepthWriteMode : 3;            ///< The depth write mode
604   DepthTestMode::Type   mDepthTestMode : 3;             ///< The depth test mode
605   bool                  mPremultipliedAlphaEnabled : 1; ///< Flag indicating whether the Pre-multiplied Alpha Blending is required
606   bool                  mShaderChanged : 1;             ///< Flag indicating the shader changed and uniform maps have to be updated
607
608   std::vector<Dali::DevelRenderer::DrawCommand> mDrawCommands; // Devel stuff
609   RenderCallback*                               mRenderCallback{nullptr};
610   std::unique_ptr<RenderCallbackInput>          mRenderCallbackInput{nullptr};
611   std::vector<Graphics::Texture*>               mRenderCallbackTextureBindings{};
612 };
613
614 } // namespace Render
615
616 } // namespace Internal
617
618 } // namespace Dali
619
620 #endif // DALI_INTERNAL_RENDER_RENDERER_H