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