ba59a64bce535c3ed654f88410b4324c6d5a7be7
[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  * @brief Set up the stencil and color buffer for automatic clipping (StencilMode::AUTO).
85  * @param[in]     item                     The current RenderItem about to be rendered
86  * @param[in]     context                  The context
87  * @param[in/out] lastStencilDepth         The stencil depth of the last renderer drawn.
88  * @param[in/out] lastClippingId           The clipping ID of the last renderer drawn.
89  */
90 inline void SetupClipping( const RenderItem& item, Context& context, uint32_t& lastStencilDepth, uint32_t& lastClippingId )
91 {
92   const Dali::Internal::SceneGraph::Node* node = item.mNode;
93   const uint32_t clippingId = node->GetClippingId();
94
95   // Turn the color buffer on as we always want to render this renderer, regardless of clipping hierarchy.
96   context.ColorMask( true );
97
98   // If there is no clipping Id, then either we haven't reached a clipping Node yet, or there aren't any.
99   // Either way we can skip clipping setup for this renderer.
100   if( clippingId == 0u )
101   {
102     // Exit immediately if there are no clipping actions to perform (EG. we have not yet hit a clipping node).
103     context.EnableStencilBuffer( false );
104     return;
105   }
106
107   const ClippingMode::Type clippingMode( node->GetClippingMode() );
108   const uint32_t currentStencilDepth( node->GetClippingDepth() );
109
110   context.EnableStencilBuffer( true );
111
112   // Pre-calculate a mask which has all bits set up to and including the current clipping depth.
113   // EG. If depth is 3, the mask would be "111" in binary.
114   const uint32_t currentDepthMask = ( 1u << currentStencilDepth ) - 1u;
115
116   // If we have a clipping mode specified, we are writing to the stencil buffer.
117   if( clippingMode != ClippingMode::DISABLED )
118   {
119     // We are writing to the stencil buffer.
120     // If clipping Id is 1, this is the first clipping renderer within this render-list.
121     if( clippingId == 1u )
122     {
123       // We are enabling the stencil-buffer for the first time within this render list.
124       // Clear the buffer at this point.
125       context.StencilMask( 0xff );
126       context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
127     }
128     else if( ( currentStencilDepth < lastStencilDepth ) || ( clippingId != lastClippingId ) )
129     {
130       // The above if() statement tests if we need to clear some (not all) stencil bit-planes.
131       // We need to do this if either of the following are true:
132       //   1) We traverse up the scene-graph to a previous stencil
133       //   2) We are at the same stencil depth but the clipping Id has changed.
134       //
135       // This calculation takes the new depth to move to, and creates an inverse-mask of that number of consecutive bits.
136       // This has the effect of clearing everything except the bit-planes up to (and including) our current depth.
137       const uint32_t stencilClearMask = ( currentDepthMask >> 1u ) ^ 0xff;
138
139       context.StencilMask( stencilClearMask );
140       context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
141     }
142
143     // We keep track of the last clipping Id and depth so we can determine when we are
144     // moving back up the scene graph and require some of the stencil bit-planes to be deleted.
145     lastStencilDepth = currentStencilDepth;
146     lastClippingId = clippingId;
147
148     // We only ever write to bit-planes up to the current depth as we may need
149     // to erase individual bit-planes and revert to a previous clipping area.
150     // Our reference value for testing (in StencilFunc) is written to to the buffer, but we actually
151     // want to test a different value. IE. All the bit-planes up to but not including the current depth.
152     // So we use the Mask parameter of StencilFunc to mask off the top bit-plane when testing.
153     // Here we create our test mask to innore the top bit of the reference test value.
154     // As the mask is made up of contiguous "1" values, we can do this quickly with a bit-shift.
155     const uint32_t testMask = currentDepthMask >> 1u;
156
157     context.StencilFunc( GL_EQUAL, currentDepthMask, testMask ); // Test against existing stencil bit-planes. All must match up to (but not including) this depth.
158     context.StencilMask( currentDepthMask );                     // Write to the new stencil bit-plane (the other previous bit-planes are also written to).
159     context.StencilOp( GL_KEEP, GL_REPLACE, GL_REPLACE );
160   }
161   else
162   {
163     // We are reading from the stencil buffer. Set up the stencil accordingly
164     // This calculation sets all the bits up to the current depth bit.
165     // This has the effect of testing that the pixel being written to exists in every bit-plane up to the current depth.
166     context.StencilFunc( GL_EQUAL, currentDepthMask, 0xff );
167     context.StencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
168   }
169 }
170
171 /**
172  * @brief Set up the stencil and color buffer based on the current Renderers properties.
173  * @param[in]     item                     The current RenderItem about to be rendered
174  * @param[in]     context                  The context
175  * @param[in/out] usedStencilBuffer        True if the stencil buffer has been used so far within this RenderList. Used by StencilMode::ON.
176  * @param[in/out] lastStencilDepth         The stencil depth of the last renderer drawn. Used by the clipping feature.
177  * @param[in/out] lastClippingId           The clipping ID of the last renderer drawn.   Used by the clipping feature.
178  */
179 inline void SetupStencilBuffer( const RenderItem& item, Context& context, bool& usedStencilBuffer, uint32_t& lastStencilDepth, uint32_t& lastClippingId )
180 {
181   const Renderer *renderer = item.mRenderer;
182
183   // Setup the stencil using either the automatic clipping feature, or, the manual per-renderer stencil API.
184   // Note: This switch is in order of most likely value first.
185   RenderMode::Type renderMode = renderer->GetRenderMode();
186   switch( renderMode )
187   {
188     case RenderMode::AUTO:
189     {
190       // The automatic clipping feature will manage the stencil functions and color buffer mask.
191       SetupClipping( item, context, lastStencilDepth, lastClippingId );
192       break;
193     }
194
195     case RenderMode::NONE:
196     case RenderMode::COLOR:
197     {
198       // The stencil buffer will not be used at all.
199       context.EnableStencilBuffer( false );
200
201       // Setup the color buffer based on the RenderMode.
202       context.ColorMask( renderMode == RenderMode::COLOR );
203       return;
204       break; // Break statement for consistency (although return will be called instead).
205     }
206
207     case RenderMode::STENCIL:
208     case RenderMode::COLOR_STENCIL:
209     {
210       // We are using the low-level Renderer Stencil API.
211       // The stencil buffer must be enabled for every renderer with stencil mode on, as renderers in between can disable it.
212       // Note: As the command state is cached, it is only sent when needed.
213       context.EnableStencilBuffer( true );
214
215       // Setup the color buffer based on the RenderMode.
216       context.ColorMask( renderMode == RenderMode::COLOR_STENCIL );
217
218       // If this is the first use of the stencil buffer within this RenderList, clear it (this avoids unnecessary clears).
219       if( !usedStencilBuffer )
220       {
221         context.Clear( GL_STENCIL_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
222         usedStencilBuffer = true;
223       }
224
225       // Setup the stencil buffer based on the renderers properties.
226       context.StencilFunc( DaliStencilFunctionToGL[ renderer->GetStencilFunction() ],
227           renderer->GetStencilFunctionReference(),
228           renderer->GetStencilFunctionMask() );
229       context.StencilOp( DaliStencilOperationToGL[ renderer->GetStencilOperationOnFail() ],
230           DaliStencilOperationToGL[ renderer->GetStencilOperationOnZFail() ],
231           DaliStencilOperationToGL[ renderer->GetStencilOperationOnZPass() ] );
232       context.StencilMask( renderer->GetStencilMask() );
233       break;
234     }
235   }
236 }
237
238 /**
239  * @brief Sets up the depth buffer for reading and writing based on the current render item.
240  * The items read and write mode are used if specified.
241  *  - If AUTO is selected for reading, the decision will be based on the Layer Behavior.
242  *  - If AUTO is selected for writing, the decision will be based on the items opacity.
243  * @param[in]     item                The RenderItem to set up the depth buffer for.
244  * @param[in]     context             The context used to execute GL commands.
245  * @param[in]     depthTestEnabled    True if depth testing has been enabled.
246  * @param[in/out] firstDepthBufferUse Initialise to true on the first call, this method will set it to false afterwards.
247  */
248 inline void SetupDepthBuffer( const RenderItem& item, Context& context, bool depthTestEnabled, bool& firstDepthBufferUse )
249 {
250   // Set up whether or not to write to the depth buffer.
251   const DepthWriteMode::Type depthWriteMode = item.mRenderer->GetDepthWriteMode();
252   // Most common mode (AUTO) is tested first.
253   const bool enableDepthWrite = ( ( depthWriteMode == DepthWriteMode::AUTO ) && depthTestEnabled && item.mIsOpaque ) ||
254                                 ( depthWriteMode == DepthWriteMode::ON );
255
256   // Set up whether or not to read from (test) the depth buffer.
257   const DepthTestMode::Type depthTestMode = item.mRenderer->GetDepthTestMode();
258   // Most common mode (AUTO) is tested first.
259   const bool enableDepthTest = ( ( depthTestMode == DepthTestMode::AUTO ) && depthTestEnabled ) ||
260                                ( depthTestMode == DepthTestMode::ON );
261
262   // Is the depth buffer in use?
263   if( enableDepthWrite || enableDepthTest )
264   {
265     // The depth buffer must be enabled if either reading or writing.
266     context.EnableDepthBuffer( true );
267
268     // Set up the depth mask based on our depth write setting.
269     context.DepthMask( enableDepthWrite );
270
271     // Look-up the GL depth function from the Dali::DepthFunction enum, and set it.
272     context.DepthFunc( DaliDepthToGLDepthTable[ item.mRenderer->GetDepthFunction() ] );
273
274     // If this is the first use of the depth buffer this RenderTask, perform a clear.
275     // Note: We could do this at the beginning of the RenderTask and rely on the
276     // context cache to ignore the clear if not required, but, we would have to enable
277     // the depth buffer to do so, which could be a redundant enable.
278     if( DALI_UNLIKELY( firstDepthBufferUse ) )
279     {
280       // This is the first time the depth buffer is being written to or read.
281       firstDepthBufferUse = false;
282
283       // Note: The buffer will only be cleared if written to since a previous clear.
284       context.Clear( GL_DEPTH_BUFFER_BIT, Context::CHECK_CACHED_VALUES );
285     }
286   }
287   else
288   {
289     // The depth buffer is not being used by this renderer, so we must disable it to stop it being tested.
290     context.EnableDepthBuffer( false );
291   }
292 }
293
294 /**
295  * @brief Setup Batching and calculate if we should perform or skip the upcoming render.
296  *
297  * Check if the node has a valid batch index value ( set previously by
298  * GeometryBatcher ). If so, then it queries the geometry object for this particular batch.
299  * If not, it still checks if the batch parent is set as it is possible, batching may
300  * fail (for example if vertex format or buffers are not set). In that case we need
301  * to skip rendering, otherwise unwanted GPU buffers will get uploaded. This is very rare case.
302  * @param[in] item            The item to test / setup for batching
303  * @param[in] geometryBatcher The instance of the Geometry Batcher
304  * @return                    True if we should perform a render as normal. False if we should skip it due to batching.
305  */
306 inline bool SetupBatching( const RenderItem& item, GeometryBatcher* geometryBatcher )
307 {
308   bool performRender( true );
309   uint32_t batchIndex( item.mNode->mBatchIndex );
310
311   if( batchIndex != BATCH_NULL_HANDLE )
312   {
313     item.mBatchRenderGeometry = geometryBatcher->GetGeometry( batchIndex );
314   }
315   else
316   {
317     performRender = !( item.mNode->GetBatchParent() );
318     item.mBatchRenderGeometry = NULL;
319   }
320
321   return performRender;
322 }
323
324 /**
325  * @brief Process a render-list.
326  * @param[in] renderList       The render-list to process.
327  * @param[in] context          The GL context.
328  * @param[in] defaultShader    The default shader to use.
329  * @param[in] buffer           The current render buffer index (previous update buffer)
330  * @param[in] viewMatrix       The view matrix from the appropriate camera.
331  * @param[in] projectionMatrix The projection matrix from the appropriate camera.
332  * @param[in] geometryBatcher  The instance of the geometry batcher
333  */
334 inline void ProcessRenderList(
335   const RenderList& renderList,
336   Context& context,
337   SceneGraph::TextureCache& textureCache,
338   SceneGraph::Shader& defaultShader,
339   BufferIndex bufferIndex,
340   const Matrix& viewMatrix,
341   const Matrix& projectionMatrix,
342   GeometryBatcher* geometryBatcher )
343 {
344   DALI_PRINT_RENDER_LIST( renderList );
345
346   SetScissorTest( renderList, context );
347
348   // Note: The depth buffer is enabled or disabled on a per-renderer basis.
349   // Here we pre-calculate the value to use if these modes are set to AUTO.
350   const bool autoDepthTestMode( !( renderList.GetSourceLayer()->IsDepthTestDisabled() ) && renderList.HasColorRenderItems() );
351   const std::size_t count = renderList.Count();
352   uint32_t lastStencilDepth( 0u );
353   uint32_t lastClippingId( 0u );
354   bool usedStencilBuffer( false );
355   bool firstDepthBufferUse( true );
356
357   for( size_t index( 0u ); index < count; ++index )
358   {
359     const RenderItem& item = renderList.GetItem( index );
360     DALI_PRINT_RENDER_ITEM( item );
361
362     // Set up the depth buffer based on per-renderer flags.
363     // If the per renderer flags are set to "ON" or "OFF", they will always override any Layer depth mode or
364     // draw-mode state, such as Overlays.
365     // If the flags are set to "AUTO", the behaviour then depends on the type of renderer. Overlay Renderers will always
366     // disable depth testing and writing. Color Renderers will enable them if the Layer does.
367     SetupDepthBuffer( item, context, autoDepthTestMode, firstDepthBufferUse );
368
369     // Set up the stencil buffer based on both the Renderer and Actor APIs.
370     // The Renderer API will be used if specified. If AUTO, the Actors automatic clipping feature will be used.
371     SetupStencilBuffer( item, context, usedStencilBuffer, lastStencilDepth, lastClippingId );
372
373     // Setup Batching and calculate if we should perform or skip the upcoming render.
374     const bool performRender( SetupBatching( item, geometryBatcher ) );
375
376     // Render the item if it has not been skipped by batching.
377     if( DALI_LIKELY( performRender ) )
378     {
379       item.mRenderer->Render( context, textureCache, bufferIndex, *item.mNode, defaultShader,
380                             item.mModelMatrix, item.mModelViewMatrix, viewMatrix, projectionMatrix,
381                             item.mSize, item.mBatchRenderGeometry, !item.mIsOpaque );
382     }
383   }
384 }
385
386 void ProcessRenderInstruction( const RenderInstruction& instruction,
387                                Context& context,
388                                SceneGraph::TextureCache& textureCache,
389                                SceneGraph::Shader& defaultShader,
390                                GeometryBatcher& geometryBatcher,
391                                BufferIndex bufferIndex )
392 {
393   DALI_PRINT_RENDER_INSTRUCTION( instruction, bufferIndex );
394
395   const Matrix* viewMatrix       = instruction.GetViewMatrix( bufferIndex );
396   const Matrix* projectionMatrix = instruction.GetProjectionMatrix( bufferIndex );
397
398   DALI_ASSERT_DEBUG( viewMatrix );
399   DALI_ASSERT_DEBUG( projectionMatrix );
400
401   if( viewMatrix && projectionMatrix )
402   {
403     const RenderListContainer::SizeType count = instruction.RenderListCount();
404
405     // Iterate through each render list in order. If a pair of render lists
406     // are marked as interleaved, then process them together.
407     for( RenderListContainer::SizeType index = 0; index < count; ++index )
408     {
409       const RenderList* renderList = instruction.GetRenderList( index );
410
411       if( renderList && !renderList->IsEmpty() )
412       {
413         ProcessRenderList( *renderList, context, textureCache, defaultShader, bufferIndex, *viewMatrix, *projectionMatrix, &geometryBatcher );
414       }
415     }
416   }
417 }
418
419 } // namespace Render
420
421 } // namespace Internal
422
423 } // namespace Dali