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