Geometry Batching
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-algorithms.cpp
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/render/common/render-algorithms.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/internal/render/common/render-debug.h>
23 #include <dali/internal/render/common/render-list.h>
24 #include <dali/internal/render/common/render-instruction.h>
25 #include <dali/internal/render/gl-resources/context.h>
26 #include <dali/internal/render/renderers/render-renderer.h>
27 #include <dali/internal/update/nodes/scene-graph-layer.h>
28 #include <dali/internal/update/manager/geometry-batcher.h>
29
30 using Dali::Internal::SceneGraph::RenderItem;
31 using Dali::Internal::SceneGraph::RenderList;
32 using Dali::Internal::SceneGraph::RenderListContainer;
33 using Dali::Internal::SceneGraph::RenderInstruction;
34 using Dali::Internal::SceneGraph::GeometryBatcher;
35
36 namespace Dali
37 {
38
39 namespace Internal
40 {
41
42 namespace Render
43 {
44
45 namespace
46 {
47
48 // Table for fast look-up of Dali::DepthFunction enum to a GL depth function.
49 // Note: These MUST be in the same order as Dali::DepthFunction enum.
50 const int DaliDepthToGLDepthTable[]  = { GL_NEVER, GL_ALWAYS, GL_LESS, GL_GREATER, GL_EQUAL, GL_NOTEQUAL, GL_LEQUAL, GL_GEQUAL };
51
52 // Table for fast look-up of Dali::StencilFunction enum to a GL stencil function.
53 // Note: These MUST be in the same order as Dali::StencilFunction enum.
54 const int DaliStencilFunctionToGL[]  = { GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS };
55
56 // Table for fast look-up of Dali::StencilOperation enum to a GL stencil operation.
57 // Note: These MUST be in the same order as Dali::StencilOperation enum.
58 const int DaliStencilOperationToGL[] = { GL_ZERO, GL_KEEP, GL_REPLACE, GL_INCR, GL_DECR, GL_INVERT, GL_INCR_WRAP, GL_DECR_WRAP };
59
60 } // Unnamed namespace
61
62 /**
63  * Sets up the scissor test if required.
64  * @param[in] renderList The render list from which to get the clipping flag
65  * @param[in] context The context
66  */
67 inline void SetScissorTest( const RenderList& renderList, Context& context )
68 {
69   // Scissor testing
70   if( renderList.IsClipping() )
71   {
72     context.SetScissorTest( true );
73
74     const Dali::ClippingBox& clip = renderList.GetClippingBox();
75     context.Scissor(clip.x, clip.y, clip.width, clip.height);
76   }
77   else
78   {
79     context.SetScissorTest( false );
80   }
81 }
82
83 /**
84  * Sets the render flags for the stencil buffer and clears all required buffers (depth and stencil if required).
85  * @param[in] renderList The render list from which to get the render flags
86  * @param[in] context The context
87  * @param[in] depthTestEnabled True if depth test is enabled for the layer
88  * @param[in] isLayer3D True if the layer is a 3D layer
89  */
90 inline void SetRenderFlags( const RenderList& renderList, Context& context, bool depthTestEnabled, bool isLayer3D )
91 {
92   const unsigned int renderFlags = renderList.GetFlags();
93   GLbitfield clearMask = 0u;
94
95   // Stencil enabled, writing, and clearing...
96   const bool enableStencilBuffer( renderFlags & RenderList::STENCIL_BUFFER_ENABLED );
97   const bool enableStencilWrite( renderFlags & RenderList::STENCIL_WRITE );
98   context.EnableStencilBuffer( enableStencilBuffer );
99   if( enableStencilBuffer )
100   {
101     context.StencilFunc( ( enableStencilWrite ? GL_ALWAYS : GL_EQUAL ), 1, 0xFF );
102     context.StencilOp( GL_KEEP, GL_REPLACE, GL_REPLACE );
103
104     // Write to stencil buffer or color buffer, but not both.
105     // These should only be set if the Actor::DrawMode is managing the stencil (and color) buffer.
106     context.StencilMask( enableStencilWrite ? 0xFF : 0x00 );
107     context.ColorMask( !enableStencilWrite );
108
109     clearMask |= ( renderFlags & RenderList::STENCIL_CLEAR ) ? GL_STENCIL_BUFFER_BIT : 0u;
110   }
111
112   // Enable and Clear the depth buffer if required.
113   // DepthTest must be enabled for the layer, else testing is turned off.
114   if( !depthTestEnabled )
115   {
116     context.EnableDepthBuffer( false );
117   }
118   else if( renderList.HasColorRenderItems() || isLayer3D ) // Also, within the context of this if(), depth test is enabled.
119   {
120
121     clearMask |= GL_DEPTH_BUFFER_BIT;
122     // We need to enable the depth buffer to clear it.
123     // Subsequently it is enabled and disabled on a per-RenderItem basis.
124     // If we do not have color renderers, this is only done for 3D layers.
125     context.EnableDepthBuffer( true );
126   }
127
128   // Clear Depth and/or stencil buffers as required.
129   // Note: The buffers will only be cleared if written to since a previous clear.
130   context.Clear( clearMask, Context::CHECK_CACHED_VALUES );
131 }
132
133 /**
134  * @brief This method sets up the stencil and color buffer based on the current Renderers flags.
135  * @param[in]     item                     The current RenderItem about to be rendered
136  * @param[in]     context                  The context
137  * @param[in/out] usedStencilBuffer        True if the stencil buffer has been used so far within this RenderList
138  * @param[in]     stencilManagedByDrawMode True if the stencil and color buffer is being managed by DrawMode::STENCIL
139  */
140 inline void SetupPerRendererFlags( const RenderItem& item, Context& context, bool& usedStencilBuffer, bool stencilManagedByDrawMode )
141 {
142   // DrawMode::STENCIL is deprecated, however to support it we must not set
143   // flags based on the renderer properties if it is in use.
144   if( stencilManagedByDrawMode )
145   {
146     return;
147   }
148
149   // Setup the color buffer based on the renderers properties.
150   Renderer *renderer = item.mRenderer;
151   context.ColorMask( renderer->GetWriteToColorBuffer() );
152
153   // If the stencil buffer is disabled for this renderer, exit now to save unnecessary value setting.
154   if( renderer->GetStencilMode() != StencilMode::ON )
155   {
156     // No per-renderer stencil setup, exit.
157     context.EnableStencilBuffer( false );
158     return;
159   }
160
161   // At this point, the stencil buffer is enabled.
162   context.EnableStencilBuffer( true );
163
164   // If this is the first use of the stencil buffer within this RenderList, clear it now.
165   // This avoids unnecessary clears.
166   if( !usedStencilBuffer )
167   {
168     context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
169     usedStencilBuffer = true;
170   }
171
172   // Setup the stencil buffer based on the renderers properties.
173   context.StencilFunc( DaliStencilFunctionToGL[ renderer->GetStencilFunction() ],
174       renderer->GetStencilFunctionReference(),
175       renderer->GetStencilFunctionMask() );
176   context.StencilOp( DaliStencilOperationToGL[ renderer->GetStencilOperationOnFail() ],
177       DaliStencilOperationToGL[ renderer->GetStencilOperationOnZFail() ],
178       DaliStencilOperationToGL[ renderer->GetStencilOperationOnZPass() ] );
179   context.StencilMask( renderer->GetStencilMask() );
180 }
181
182 /**
183  * Sets up the depth buffer for reading and writing based on the current render item.
184  * The items read and write mode are used if specified.
185  * If AUTO is selected for reading, the decision will be based on the Layer Behavior.
186  * If AUTO is selected for writing, the decision will be based on the items opacity.
187  * @param item The RenderItem to set up the depth buffer for
188  * @param context The context used to execute GL commands.
189  * @param isLayer3D True if the layer behavior is set to LAYER_3D
190  */
191 inline void SetupDepthBuffer( const RenderItem& item, Context& context, bool isLayer3D )
192 {
193   // Set up whether or not to write to the depth buffer.
194   const DepthWriteMode::Type depthWriteMode = item.mRenderer->GetDepthWriteMode();
195   // Most common mode (AUTO) is tested first.
196   bool enableDepthWrite = ( ( depthWriteMode == DepthWriteMode::AUTO ) && item.mIsOpaque ) ||
197                           ( depthWriteMode == DepthWriteMode::ON );
198   context.DepthMask( enableDepthWrite );
199
200   // Set up whether or not to read from (test) the depth buffer.
201   const DepthTestMode::Type depthTestMode = item.mRenderer->GetDepthTestMode();
202   // Most common mode (AUTO) is tested first.
203   bool enableDepthTest = ( ( depthTestMode == DepthTestMode::AUTO ) && isLayer3D ) ||
204                          ( depthTestMode == DepthTestMode::ON );
205   // Look-up the GL depth function from the Dali::DepthFunction enum, and set it.
206   context.DepthFunc( DaliDepthToGLDepthTable[ item.mRenderer->GetDepthFunction() ] );
207
208   // The depth buffer must be enabled if either reading or writing.
209   context.EnableDepthBuffer( enableDepthWrite || enableDepthTest );
210 }
211
212 /**
213  * Process a render-list.
214  * @param[in] renderList The render-list to process.
215  * @param[in] context The GL context.
216  * @param[in] defaultShader The default shader to use.
217  * @param[in] buffer The current render buffer index (previous update buffer)
218  * @param[in] viewMatrix The view matrix from the appropriate camera.
219  * @param[in] projectionMatrix The projection matrix from the appropriate camera.
220  * @param[in] geometryBatcher The instance of the geometry batcher
221  */
222 inline void ProcessRenderList(
223   const RenderList& renderList,
224   Context& context,
225   SceneGraph::TextureCache& textureCache,
226   SceneGraph::Shader& defaultShader,
227   BufferIndex bufferIndex,
228   const Matrix& viewMatrix,
229   const Matrix& projectionMatrix,
230   GeometryBatcher* geometryBatcher )
231 {
232   DALI_PRINT_RENDER_LIST( renderList );
233
234   bool depthTestEnabled = !( renderList.GetSourceLayer()->IsDepthTestDisabled() );
235   bool isLayer3D = renderList.GetSourceLayer()->GetBehavior() == Dali::Layer::LAYER_3D;
236   bool usedStencilBuffer = false;
237   bool stencilManagedByDrawMode = renderList.GetFlags() & RenderList::STENCIL_BUFFER_ENABLED;
238
239   SetScissorTest( renderList, context );
240   SetRenderFlags( renderList, context, depthTestEnabled, isLayer3D );
241
242   // The Layers depth enabled flag overrides the per-renderer depth flags.
243   // So if depth test is disabled at the layer level, we ignore per-render flags.
244   // Note: Overlay renderers will not read or write from the depth buffer.
245   if( DALI_LIKELY( !renderList.HasColorRenderItems() || !depthTestEnabled ) )
246   {
247     size_t count = renderList.Count();
248     bool skip( false );
249     for ( size_t index = 0; index < count; ++index )
250     {
251       const RenderItem& item = renderList.GetItem( index );
252       DALI_PRINT_RENDER_ITEM( item );
253
254       SetupPerRendererFlags( item, context, usedStencilBuffer, stencilManagedByDrawMode );
255
256       // Check if the node has a valid batch index value ( set previously by
257       // GeometryBatcher ). If so, then it queries the geometry object for this particular batch.
258       // If not, it still checks if the batch parent is set as it is possible, batching may
259       // fail ( for example if vertex format or buffers are not set ). In that case we need
260       // to skip rendering, otherwise unwanted GPU buffers will get uploaded. This is very rare case.
261       uint32_t batchIndex = item.mNode->mBatchIndex;
262       if( batchIndex != BATCH_NULL_HANDLE )
263       {
264         item.mBatchRenderGeometry = geometryBatcher->GetGeometry( batchIndex );
265       }
266       else
267       {
268         skip = item.mNode->GetBatchParent();
269         item.mBatchRenderGeometry = NULL;
270       }
271       if( !skip )
272       {
273         item.mRenderer->Render( context, textureCache, bufferIndex, *item.mNode, defaultShader,
274                               item.mModelMatrix, item.mModelViewMatrix, viewMatrix, projectionMatrix, item.mSize, item.mBatchRenderGeometry, !item.mIsOpaque );
275       }
276     }
277   }
278   else
279   {
280     size_t count = renderList.Count();
281     for ( size_t index = 0; index < count; ++index )
282     {
283       const RenderItem& item = renderList.GetItem( index );
284       DALI_PRINT_RENDER_ITEM( item );
285
286       // Set up the depth buffer based on per-renderer flags.
287       SetupDepthBuffer( item, context, isLayer3D );
288       SetupPerRendererFlags( item, context, usedStencilBuffer, stencilManagedByDrawMode );
289
290       item.mRenderer->Render( context, textureCache, bufferIndex, *item.mNode, defaultShader,
291                               item.mModelMatrix, item.mModelViewMatrix, viewMatrix, projectionMatrix, item.mSize, item.mBatchRenderGeometry, !item.mIsOpaque );
292     }
293   }
294 }
295
296 void ProcessRenderInstruction( const RenderInstruction& instruction,
297                                Context& context,
298                                SceneGraph::TextureCache& textureCache,
299                                SceneGraph::Shader& defaultShader,
300                                GeometryBatcher& geometryBatcher,
301                                BufferIndex bufferIndex )
302 {
303   DALI_PRINT_RENDER_INSTRUCTION( instruction, bufferIndex );
304
305   const Matrix* viewMatrix       = instruction.GetViewMatrix( bufferIndex );
306   const Matrix* projectionMatrix = instruction.GetProjectionMatrix( bufferIndex );
307
308   DALI_ASSERT_DEBUG( NULL != viewMatrix );
309   DALI_ASSERT_DEBUG( NULL != projectionMatrix );
310
311   if( NULL != viewMatrix &&
312       NULL != projectionMatrix )
313   {
314     const RenderListContainer::SizeType count = instruction.RenderListCount();
315
316     // Iterate through each render list in order. If a pair of render lists
317     // are marked as interleaved, then process them together.
318     for( RenderListContainer::SizeType index = 0; index < count; ++index )
319     {
320       const RenderList* renderList = instruction.GetRenderList( index );
321
322       if(  renderList &&
323           !renderList->IsEmpty() )
324       {
325         ProcessRenderList( *renderList, context, textureCache, defaultShader, bufferIndex, *viewMatrix, *projectionMatrix, &geometryBatcher );
326       }
327     }
328   }
329 }
330
331 } // namespace Render
332
333 } // namespace Internal
334
335 } // namespace Dali