2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/event/effects/shader-effect-impl.h>
22 #include <dali/public-api/math/matrix.h>
23 #include <dali/public-api/math/matrix3.h>
24 #include <dali/public-api/math/vector2.h>
25 #include <dali/public-api/object/type-registry.h>
26 #include <dali/public-api/scripting/scripting.h>
27 #include <dali/public-api/shader-effects/shader-effect.h>
28 #include <dali/internal/event/common/property-helper.h>
29 #include <dali/internal/event/common/stage-impl.h>
30 #include <dali/internal/event/common/thread-local-storage.h>
31 #include <dali/internal/event/effects/shader-declarations.h>
32 #include <dali/internal/event/effects/shader-factory.h>
33 #include <dali/internal/event/images/image-impl.h>
34 #include <dali/internal/render/shaders/shader.h>
35 #include <dali/internal/render/shaders/uniform-meta.h>
36 #include <dali/internal/update/animation/scene-graph-constraint-base.h>
37 #include <dali/internal/update/common/animatable-property.h>
38 #include <dali/internal/update/manager/update-manager.h>
39 #include "dali-shaders.h"
41 using Dali::Internal::SceneGraph::UpdateManager;
42 using Dali::Internal::SceneGraph::UniformMeta;
43 using Dali::Internal::SceneGraph::Shader;
44 using Dali::Internal::SceneGraph::AnimatableProperty;
45 using Dali::Internal::SceneGraph::PropertyBase;
46 using Dali::Internal::SceneGraph::RenderQueue;
60 // Name Type writable animatable constraint-input enum for index-checking
61 DALI_PROPERTY_TABLE_BEGIN
62 DALI_PROPERTY( "grid-density", FLOAT, true, false, false, Dali::ShaderEffect::Property::GRID_DENSITY )
63 DALI_PROPERTY( "image", MAP, true, false, false, Dali::ShaderEffect::Property::IMAGE )
64 DALI_PROPERTY( "program", MAP, true, false, false, Dali::ShaderEffect::Property::PROGRAM )
65 DALI_PROPERTY( "geometry-hints", INTEGER, true, false, false, Dali::ShaderEffect::Property::GEOMETRY_HINTS )
66 DALI_PROPERTY_TABLE_END( DEFAULT_ACTOR_PROPERTY_START_INDEX )
70 Internal::ShaderEffectPtr internal = Internal::ShaderEffect::New();
72 return Dali::ShaderEffect(internal.Get());
75 TypeRegistration mType( typeid(Dali::ShaderEffect), typeid(Dali::Handle), Create );
79 const char* vertexShaderPrefix;
80 const char* fragmentShaderPrefix;
81 const char* vertexShaderPostfix;
82 const char* fragmentShaderPostfix;
85 WrapperStrings customShaderWrappers [] =
88 CustomImagePrefixVertex, CustomImagePrefixFragment,
89 CustomImagePostfixVertex, CustomImagePostfixFragment
92 CustomTextDistanceFieldPrefixVertex, CustomTextDistanceFieldPrefixFragment,
93 CustomTextDistanceFieldPostfixVertex, CustomTextDistanceFieldPostfixFragment
96 CustomUntexturedMeshPrefixVertex, CustomUntexturedMeshPrefixFragment,
97 CustomUntexturedMeshPostfixVertex, CustomUntexturedMeshPostfixFragment
100 CustomTexturedMeshPrefixVertex, CustomTexturedMeshPrefixFragment,
101 CustomTexturedMeshPostfixVertex, CustomTexturedMeshPostfixFragment
106 * Helper to wrap the program with our default pre and postfix if needed and then send it to update/render thread
107 * @param[in] effect of the shader
108 * @param[in] actualGeometryType of the shader
109 * @param[in] expectedGeometryType of the shader
110 * @param[in] vertexPrefix from application
111 * @param[in] fragmentPrefix from application
112 * @param[in] vertexBody from application
113 * @param[in] fragmentBody from application
114 * @param[in] modifiesGeometry based on flags and vertex shader
116 void WrapAndSetProgram( Internal::ShaderEffect& effect,
117 GeometryType actualGeometryType, GeometryType expectedGeometryType,
118 const std::string& vertexPrefix, const std::string& fragmentPrefix,
119 const std::string& vertexBody, const std::string& fragmentBody,
120 bool modifiesGeometry )
122 // if geometry type matches and there is some real data in the strings
123 if( ( actualGeometryType & expectedGeometryType )&&
124 ( ( vertexPrefix.length() > 0 )||
125 ( fragmentPrefix.length() > 0 )||
126 ( vertexBody.length() > 0 )||
127 ( fragmentBody.length() > 0 ) ) )
129 std::string vertexSource = vertexPrefix;
130 std::string fragmentSource = fragmentPrefix;
132 // create complete shader program strings for the given geometry type
133 unsigned int index = 0;
134 switch( expectedGeometryType )
136 case GEOMETRY_TYPE_IMAGE:
141 case GEOMETRY_TYPE_TEXT:
146 case GEOMETRY_TYPE_UNTEXTURED_MESH:
151 case GEOMETRY_TYPE_TEXTURED_MESH:
156 case GEOMETRY_TYPE_LAST:
158 DALI_ASSERT_DEBUG(0 && "Wrong geometry type");
163 vertexSource += customShaderWrappers[index].vertexShaderPrefix;
164 // Append the custom vertex shader code if supplied, otherwise append the default
165 if ( vertexBody.length() > 0 )
167 vertexSource.append( vertexBody );
171 vertexSource.append( customShaderWrappers[index].vertexShaderPostfix );
174 fragmentSource += customShaderWrappers[index].fragmentShaderPrefix;
175 // Append the custom fragment shader code if supplied, otherwise append the default
176 if ( fragmentBody.length() > 0 )
178 fragmentSource.append( fragmentBody );
182 fragmentSource.append( customShaderWrappers[index].fragmentShaderPostfix );
185 effect.SendProgramMessage( expectedGeometryType, SHADER_SUBTYPE_ALL, vertexSource, fragmentSource, modifiesGeometry );
189 std::string GetShader(const std::string& field, const Property::Value& property)
192 if( property.HasKey(field) )
194 DALI_ASSERT_ALWAYS(property.GetValue(field).GetType() == Property::STRING && "Shader property is not a string" );
196 // we could also check here for an array of strings as convenience for json not having multi line strings
197 value = property.GetValue(field).Get<std::string>();
203 } // unnamed namespace
205 ShaderEffectPtr ShaderEffect::New( Dali::ShaderEffect::GeometryHints hints )
207 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
208 UpdateManager& updateManager = tls.GetUpdateManager();
210 ShaderEffectPtr shaderEffect( new ShaderEffect( updateManager, hints ) );
211 shaderEffect->RegisterObject();
216 ShaderEffect::ShaderEffect( UpdateManager& updateManager, Dali::ShaderEffect::GeometryHints hints )
217 : mUpdateManager( updateManager ),
218 mConnectionCount (0),
219 mGeometryHints( hints )
221 mSceneObject = new Shader( hints );
222 DALI_ASSERT_DEBUG( NULL != mSceneObject );
224 // Transfer shader ownership to a scene message
225 AddShaderMessage( mUpdateManager, *mSceneObject );
228 ShaderEffect::~ShaderEffect()
230 // Guard to allow handle destruction after Core has been destroyed
231 if ( Stage::IsInstalled() )
233 // Remove scene-object using a message to the UpdateManager
236 RemoveShaderMessage( mUpdateManager, *mSceneObject );
242 void ShaderEffect::SetEffectImage( Dali::Image image )
244 // if images are the same, do nothing
250 if (mImage && mConnectionCount > 0)
252 // unset previous image
253 GetImplementation(mImage).Disconnect();
256 // in case image is empty this will reset our image handle
261 // mSceneShader can be in a separate thread; queue a setter message
262 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, 0 );
266 // tell image that we're using it
267 if (mConnectionCount > 0)
269 GetImplementation(mImage).Connect();
271 // mSceneShader can be in a separate thread; queue a setter message
272 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
276 void ShaderEffect::SetUniform( const std::string& name, Property::Value value, UniformCoordinateType uniformCoordinateType )
278 // Register the property if it does not exist
279 Property::Index index = GetPropertyIndex( name );
280 if ( Property::INVALID_INDEX == index )
282 index = RegisterProperty( name, value );
285 SetProperty( index, value );
287 // RegisterProperty guarantees a positive value as index
288 DALI_ASSERT_DEBUG( static_cast<unsigned int>(index) >= CustomPropertyStartIndex() );
289 unsigned int metaIndex = index - CustomPropertyStartIndex();
290 // check if there's space in cache
291 if( mCoordinateTypes.Count() < (metaIndex + 1) )
293 mCoordinateTypes.Resize( metaIndex + 1 );
295 // only send message if the value is different than current, initial value is COORDINATE_TYPE_DEFAULT (0)
296 if( uniformCoordinateType != mCoordinateTypes[ metaIndex ] )
298 mCoordinateTypes[ metaIndex ] = uniformCoordinateType;
299 SetCoordinateTypeMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, metaIndex, uniformCoordinateType );
303 void ShaderEffect::AttachExtension( Dali::ShaderEffect::Extension *extension )
305 DALI_ASSERT_ALWAYS( extension != NULL && "Attaching uninitialized extension" );
306 mExtension = IntrusivePtr<Dali::ShaderEffect::Extension>( extension );
309 Dali::ShaderEffect::Extension& ShaderEffect::GetExtension()
311 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
315 const Dali::ShaderEffect::Extension& ShaderEffect::GetExtension() const
317 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
321 void ShaderEffect::SetPrograms( GeometryType geometryType, const string& vertexSource, const string& fragmentSource )
323 SetPrograms( geometryType, "", "", vertexSource, fragmentSource );
326 void ShaderEffect::SetPrograms( GeometryType geometryType,
327 const std::string& vertexPrefix, const std::string& fragmentPrefix,
328 const std::string& vertexSource, const std::string& fragmentSource )
330 bool modifiesGeometry = true;
331 // check if the vertex shader is empty (means it cannot modify geometry)
332 if( (vertexPrefix.length() == 0 )&&( vertexSource.length() == 0 ) )
334 modifiesGeometry = false;
336 // check the hint second
337 if( (mGeometryHints & Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY ) != 0 )
339 modifiesGeometry = false;
342 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_IMAGE, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
343 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXT, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
344 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
345 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_UNTEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
348 void ShaderEffect::SendProgramMessage( GeometryType geometryType, ShaderSubTypes subType,
349 const string& vertexSource, const string& fragmentSource,
350 bool modifiesGeometry )
352 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
353 ShaderFactory& shaderFactory = tls.GetShaderFactory();
356 ResourceTicketPtr ticket( shaderFactory.Load(vertexSource, fragmentSource, shaderHash) );
358 DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "ShaderEffect: SetProgram(geometryType %d subType:%d ticket.id:%d)\n", geometryType, subType, ticket->GetId() );
360 // Add shader program to scene-object using a message to the UpdateManager
361 SetShaderProgramMessage( mUpdateManager, *mSceneObject, geometryType, subType, ticket->GetId(), shaderHash, modifiesGeometry );
363 mTickets.push_back(ticket); // add ticket to collection to keep it alive.
366 void ShaderEffect::Connect()
370 if (mImage && mConnectionCount == 1)
372 GetImplementation(mImage).Connect();
374 // Image may have changed resource due to load/release policy. Ensure correct texture ID is set on scene graph object
375 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
379 void ShaderEffect::Disconnect()
381 DALI_ASSERT_DEBUG(mConnectionCount > 0);
384 if (mImage && mConnectionCount == 0)
386 GetImplementation(mImage).Disconnect();
390 unsigned int ShaderEffect::GetDefaultPropertyCount() const
392 return DEFAULT_PROPERTY_COUNT;
395 void ShaderEffect::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const
397 indices.reserve( DEFAULT_PROPERTY_COUNT );
399 for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
401 indices.push_back( i );
405 const char* ShaderEffect::GetDefaultPropertyName(Property::Index index) const
407 if( index < DEFAULT_PROPERTY_COUNT )
409 return DEFAULT_PROPERTY_DETAILS[index].name;
415 Property::Index ShaderEffect::GetDefaultPropertyIndex(const std::string& name) const
417 Property::Index index = Property::INVALID_INDEX;
419 // Look for name in default properties
420 for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
422 const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[ i ];
423 if( 0 == strcmp( name.c_str(), property->name ) ) // dont want to convert rhs to string
433 bool ShaderEffect::IsDefaultPropertyWritable(Property::Index index) const
435 return DEFAULT_PROPERTY_DETAILS[ index ].writable;
438 bool ShaderEffect::IsDefaultPropertyAnimatable(Property::Index index) const
440 return DEFAULT_PROPERTY_DETAILS[ index ].animatable;
443 bool ShaderEffect::IsDefaultPropertyAConstraintInput( Property::Index index ) const
445 return DEFAULT_PROPERTY_DETAILS[ index ].constraintInput;
448 Property::Type ShaderEffect::GetDefaultPropertyType(Property::Index index) const
450 if( index < DEFAULT_PROPERTY_COUNT )
452 return DEFAULT_PROPERTY_DETAILS[index].type;
455 // index out of range...return Property::NONE
456 return Property::NONE;
459 void ShaderEffect::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
463 case Dali::ShaderEffect::Property::GRID_DENSITY:
465 SetGridDensityMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, propertyValue.Get<float>() );
469 case Dali::ShaderEffect::Property::IMAGE:
471 Dali::Image img(Scripting::NewImage( propertyValue ));
474 SetEffectImage( img );
478 DALI_LOG_WARNING("Cannot create image from property value for ShaderEffect image\n");
483 case Dali::ShaderEffect::Property::PROGRAM:
485 std::string vertexPrefix = GetShader("vertex-prefix", propertyValue);
486 std::string fragmentPrefix = GetShader("fragment-prefix", propertyValue);
487 std::string vertex = GetShader("vertex", propertyValue);
488 std::string fragment = GetShader("fragment", propertyValue);
490 GeometryType geometryType = GEOMETRY_TYPE_IMAGE;
492 if( propertyValue.HasKey("geometry-type") )
494 Property::Value geometryValue = propertyValue.GetValue("geometry-type");
495 DALI_ASSERT_ALWAYS(geometryValue.GetType() == Property::STRING && "Geometry type is not a string" );
497 std::string s = geometryValue.Get<std::string>();
498 if(s == "GEOMETRY_TYPE_IMAGE")
500 geometryType = GEOMETRY_TYPE_IMAGE;
502 else if (s == "GEOMETRY_TYPE_TEXT")
504 geometryType = GEOMETRY_TYPE_TEXT;
506 else if( s == "GEOMETRY_TYPE_UNTEXTURED_MESH")
508 geometryType = GEOMETRY_TYPE_UNTEXTURED_MESH;
510 else if( s == "GEOMETRY_TYPE_TEXTURED_MESH")
512 geometryType = GEOMETRY_TYPE_TEXTURED_MESH;
516 DALI_ASSERT_ALWAYS(!"Geometry type unknown" );
519 SetPrograms( geometryType, vertexPrefix, fragmentPrefix, vertex, fragment );
523 case Dali::ShaderEffect::Property::GEOMETRY_HINTS:
525 Dali::ShaderEffect::GeometryHints hint = Dali::ShaderEffect::HINT_NONE;
526 Property::Value geometryHintsValue = propertyValue.GetValue("geometry-hints");
528 std::string s = geometryHintsValue.Get<std::string>();
531 hint = Dali::ShaderEffect::HINT_NONE;
533 else if(s == "HINT_GRID_X")
535 hint = Dali::ShaderEffect::HINT_GRID_X;
537 else if(s == "HINT_GRID_Y")
539 hint = Dali::ShaderEffect::HINT_GRID_Y;
541 else if(s == "HINT_GRID")
543 hint = Dali::ShaderEffect::HINT_GRID;
545 else if(s == "HINT_DEPTH_BUFFER")
547 hint = Dali::ShaderEffect::HINT_DEPTH_BUFFER;
549 else if(s == "HINT_BLENDING")
551 hint = Dali::ShaderEffect::HINT_BLENDING;
553 else if(s == "HINT_DOESNT_MODIFY_GEOMETRY")
555 hint = Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY;
559 DALI_ASSERT_ALWAYS(!"Geometry hint unknown" );
562 SetHintsMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, hint );
575 Property::Value ShaderEffect::GetDefaultProperty(Property::Index /*index*/) const
577 // none of our properties are readable so return empty
578 return Property::Value();
581 void ShaderEffect::NotifyScenePropertyInstalled( const SceneGraph::PropertyBase& newProperty, const std::string& name, unsigned int index )
583 // Warning - the property is added to the Shader object in the Update thread and the meta-data is added in the Render thread (through a secondary message)
585 // mSceneObject requires metadata for each custom property (uniform)
586 UniformMeta* meta = UniformMeta::New( name, newProperty, Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT );
587 // mSceneObject is being used in a separate thread; queue a message to add the property
588 InstallUniformMetaMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, *meta ); // Message takes ownership
591 const SceneGraph::PropertyOwner* ShaderEffect::GetSceneObject() const
596 const PropertyBase* ShaderEffect::GetSceneObjectAnimatableProperty( Property::Index index ) const
598 CustomProperty* custom = FindCustomProperty( index );
599 DALI_ASSERT_ALWAYS( custom && "Property index is invalid" );
600 return custom->GetSceneGraphProperty();
603 const PropertyInputImpl* ShaderEffect::GetSceneObjectInputProperty( Property::Index index ) const
605 return GetSceneObjectAnimatableProperty( index );
608 } // namespace Internal