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/vector2.h>
23 #include <dali/public-api/math/matrix.h>
24 #include <dali/public-api/math/matrix3.h>
25 #include <dali/public-api/shader-effects/shader-effect.h>
26 #include <dali/public-api/object/type-registry.h>
27 #include <dali/public-api/scripting/scripting.h>
28 #include <dali/internal/event/effects/shader-declarations.h>
29 #include <dali/internal/event/effects/shader-factory.h>
30 #include <dali/internal/event/images/image-impl.h>
31 #include <dali/internal/update/common/animatable-property.h>
32 #include <dali/internal/update/manager/update-manager.h>
33 #include <dali/internal/event/common/stage-impl.h>
34 #include <dali/internal/event/common/thread-local-storage.h>
35 #include <dali/internal/render/shaders/shader.h>
36 #include <dali/internal/render/shaders/uniform-meta.h>
37 #include <dali/internal/update/animation/scene-graph-constraint-base.h>
38 #include "dali-shaders.h"
40 using Dali::Internal::SceneGraph::UpdateManager;
41 using Dali::Internal::SceneGraph::UniformMeta;
42 using Dali::Internal::SceneGraph::Shader;
43 using Dali::Internal::SceneGraph::AnimatableProperty;
44 using Dali::Internal::SceneGraph::PropertyBase;
45 using Dali::Internal::SceneGraph::RenderQueue;
51 const Property::Index ShaderEffect::GRID_DENSITY = 0;
52 const Property::Index ShaderEffect::IMAGE = 1;
53 const Property::Index ShaderEffect::PROGRAM = 2;
54 const Property::Index ShaderEffect::GEOMETRY_HINTS = 3;
61 const PropertyDetails DEFAULT_PROPERTY_DETAILS[] =
63 // Name Type writable animatable constraint-input
64 { "grid-density", Property::FLOAT, true, false, false }, // GRID_DENSITY
65 { "image", Property::MAP, true, false, false }, // IMAGE
66 { "program", Property::MAP, true, false, false }, // PROGRAM
67 { "geometry-hints", Property::INTEGER, true, false, false }, // GEOMETRY_HINTS
70 const int DEFAULT_PROPERTY_COUNT = sizeof( DEFAULT_PROPERTY_DETAILS ) / sizeof( DEFAULT_PROPERTY_DETAILS[0] );
74 Internal::ShaderEffectPtr internal = Internal::ShaderEffect::New();
76 return Dali::ShaderEffect(internal.Get());
79 TypeRegistration mType( typeid(Dali::ShaderEffect), typeid(Dali::Handle), Create );
83 const char* vertexShaderPrefix;
84 const char* fragmentShaderPrefix;
85 const char* vertexShaderPostfix;
86 const char* fragmentShaderPostfix;
89 WrapperStrings customShaderWrappers [] =
92 CustomImagePrefixVertex, CustomImagePrefixFragment,
93 CustomImagePostfixVertex, CustomImagePostfixFragment
96 CustomTextDistanceFieldPrefixVertex, CustomTextDistanceFieldPrefixFragment,
97 CustomTextDistanceFieldPostfixVertex, CustomTextDistanceFieldPostfixFragment
100 CustomUntexturedMeshPrefixVertex, CustomUntexturedMeshPrefixFragment,
101 CustomUntexturedMeshPostfixVertex, CustomUntexturedMeshPostfixFragment
104 CustomTexturedMeshPrefixVertex, CustomTexturedMeshPrefixFragment,
105 CustomTexturedMeshPostfixVertex, CustomTexturedMeshPostfixFragment
110 * Helper to wrap the program with our default pre and postfix if needed and then send it to update/render thread
111 * @param[in] effect of the shader
112 * @param[in] actualGeometryType of the shader
113 * @param[in] expectedGeometryType of the shader
114 * @param[in] vertexPrefix from application
115 * @param[in] fragmentPrefix from application
116 * @param[in] vertexBody from application
117 * @param[in] fragmentBody from application
118 * @param[in] modifiesGeometry based on flags and vertex shader
120 void WrapAndSetProgram( Internal::ShaderEffect& effect,
121 GeometryType actualGeometryType, GeometryType expectedGeometryType,
122 const std::string& vertexPrefix, const std::string& fragmentPrefix,
123 const std::string& vertexBody, const std::string& fragmentBody,
124 bool modifiesGeometry )
126 // if geometry type matches and there is some real data in the strings
127 if( ( actualGeometryType & expectedGeometryType )&&
128 ( ( vertexPrefix.length() > 0 )||
129 ( fragmentPrefix.length() > 0 )||
130 ( vertexBody.length() > 0 )||
131 ( fragmentBody.length() > 0 ) ) )
133 std::string vertexSource = vertexPrefix;
134 std::string fragmentSource = fragmentPrefix;
136 // create complete shader program strings for the given geometry type
137 unsigned int index = 0;
138 switch( expectedGeometryType )
140 case GEOMETRY_TYPE_IMAGE:
145 case GEOMETRY_TYPE_TEXT:
150 case GEOMETRY_TYPE_UNTEXTURED_MESH:
155 case GEOMETRY_TYPE_TEXTURED_MESH:
160 case GEOMETRY_TYPE_LAST:
162 DALI_ASSERT_DEBUG(0 && "Wrong geometry type");
167 vertexSource += customShaderWrappers[index].vertexShaderPrefix;
168 // Append the custom vertex shader code if supplied, otherwise append the default
169 if ( vertexBody.length() > 0 )
171 vertexSource.append( vertexBody );
175 vertexSource.append( customShaderWrappers[index].vertexShaderPostfix );
178 fragmentSource += customShaderWrappers[index].fragmentShaderPrefix;
179 // Append the custom fragment shader code if supplied, otherwise append the default
180 if ( fragmentBody.length() > 0 )
182 fragmentSource.append( fragmentBody );
186 fragmentSource.append( customShaderWrappers[index].fragmentShaderPostfix );
189 effect.SendProgramMessage( expectedGeometryType, SHADER_SUBTYPE_ALL, vertexSource, fragmentSource, modifiesGeometry );
193 std::string GetShader(const std::string& field, const Property::Value& property)
196 if( property.HasKey(field) )
198 DALI_ASSERT_ALWAYS(property.GetValue(field).GetType() == Property::STRING && "Shader property is not a string" );
200 // we could also check here for an array of strings as convenience for json not having multi line strings
201 value = property.GetValue(field).Get<std::string>();
207 } // unnamed namespace
209 ShaderEffectPtr ShaderEffect::New( Dali::ShaderEffect::GeometryHints hints )
211 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
212 UpdateManager& updateManager = tls.GetUpdateManager();
214 ShaderEffectPtr shaderEffect( new ShaderEffect( updateManager, hints ) );
215 shaderEffect->RegisterObject();
220 ShaderEffect::ShaderEffect( UpdateManager& updateManager, Dali::ShaderEffect::GeometryHints hints )
221 : mUpdateManager( updateManager ),
222 mConnectionCount (0),
223 mGeometryHints( hints )
225 mSceneObject = new Shader( hints );
226 DALI_ASSERT_DEBUG( NULL != mSceneObject );
228 // Transfer shader ownership to a scene message
229 AddShaderMessage( mUpdateManager, *mSceneObject );
232 ShaderEffect::~ShaderEffect()
234 // Guard to allow handle destruction after Core has been destroyed
235 if ( Stage::IsInstalled() )
237 // Remove scene-object using a message to the UpdateManager
240 RemoveShaderMessage( mUpdateManager, *mSceneObject );
246 void ShaderEffect::SetEffectImage( Dali::Image image )
248 // if images are the same, do nothing
254 if (mImage && mConnectionCount > 0)
256 // unset previous image
257 GetImplementation(mImage).Disconnect();
260 // in case image is empty this will reset our image handle
265 // mSceneShader can be in a separate thread; queue a setter message
266 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, 0 );
270 // tell image that we're using it
271 if (mConnectionCount > 0)
273 GetImplementation(mImage).Connect();
275 // mSceneShader can be in a separate thread; queue a setter message
276 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
280 void ShaderEffect::SetUniform( const std::string& name, Property::Value value, UniformCoordinateType uniformCoordinateType )
282 // Register the property if it does not exist
283 Property::Index index = GetPropertyIndex( name );
284 if ( Property::INVALID_INDEX == index )
286 index = RegisterProperty( name, value );
289 SetProperty( index, value );
291 // RegisterProperty guarantees a positive value as index
292 DALI_ASSERT_DEBUG( static_cast<unsigned int>(index) >= CustomPropertyStartIndex() );
293 unsigned int metaIndex = index - CustomPropertyStartIndex();
294 // check if there's space in cache
295 if( mCoordinateTypes.Count() < (metaIndex + 1) )
297 mCoordinateTypes.Resize( metaIndex + 1 );
299 // only send message if the value is different than current, initial value is COORDINATE_TYPE_DEFAULT (0)
300 if( uniformCoordinateType != mCoordinateTypes[ metaIndex ] )
302 mCoordinateTypes[ metaIndex ] = uniformCoordinateType;
303 SetCoordinateTypeMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, metaIndex, uniformCoordinateType );
307 void ShaderEffect::AttachExtension( Dali::ShaderEffect::Extension *extension )
309 DALI_ASSERT_ALWAYS( extension != NULL && "Attaching uninitialized extension" );
310 mExtension = IntrusivePtr<Dali::ShaderEffect::Extension>( extension );
313 Dali::ShaderEffect::Extension& ShaderEffect::GetExtension()
315 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
319 const Dali::ShaderEffect::Extension& ShaderEffect::GetExtension() const
321 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
325 void ShaderEffect::SetPrograms( GeometryType geometryType, const string& vertexSource, const string& fragmentSource )
327 SetPrograms( geometryType, "", "", vertexSource, fragmentSource );
330 void ShaderEffect::SetPrograms( GeometryType geometryType,
331 const std::string& vertexPrefix, const std::string& fragmentPrefix,
332 const std::string& vertexSource, const std::string& fragmentSource )
334 bool modifiesGeometry = true;
335 // check if the vertex shader is empty (means it cannot modify geometry)
336 if( (vertexPrefix.length() == 0 )&&( vertexSource.length() == 0 ) )
338 modifiesGeometry = false;
340 // check the hint second
341 if( (mGeometryHints & Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY ) != 0 )
343 modifiesGeometry = false;
346 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_IMAGE, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
347 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXT, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
348 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
349 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_UNTEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
352 void ShaderEffect::SendProgramMessage( GeometryType geometryType, ShaderSubTypes subType,
353 const string& vertexSource, const string& fragmentSource,
354 bool modifiesGeometry )
356 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
357 ShaderFactory& shaderFactory = tls.GetShaderFactory();
360 ResourceTicketPtr ticket( shaderFactory.Load(vertexSource, fragmentSource, shaderHash) );
362 DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "ShaderEffect: SetProgram(geometryType %d subType:%d ticket.id:%d)\n", geometryType, subType, ticket->GetId() );
364 // Add shader program to scene-object using a message to the UpdateManager
365 SetShaderProgramMessage( mUpdateManager, *mSceneObject, geometryType, subType, ticket->GetId(), shaderHash, modifiesGeometry );
367 mTickets.push_back(ticket); // add ticket to collection to keep it alive.
370 void ShaderEffect::Connect()
374 if (mImage && mConnectionCount == 1)
376 GetImplementation(mImage).Connect();
378 // Image may have changed resource due to load/release policy. Ensure correct texture ID is set on scene graph object
379 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
383 void ShaderEffect::Disconnect()
385 DALI_ASSERT_DEBUG(mConnectionCount > 0);
388 if (mImage && mConnectionCount == 0)
390 GetImplementation(mImage).Disconnect();
394 unsigned int ShaderEffect::GetDefaultPropertyCount() const
396 return DEFAULT_PROPERTY_COUNT;
399 void ShaderEffect::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const
401 indices.reserve( DEFAULT_PROPERTY_COUNT );
403 for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
405 indices.push_back( i );
409 const char* ShaderEffect::GetDefaultPropertyName(Property::Index index) const
411 if( index < DEFAULT_PROPERTY_COUNT )
413 return DEFAULT_PROPERTY_DETAILS[index].name;
421 Property::Index ShaderEffect::GetDefaultPropertyIndex(const std::string& name) const
423 Property::Index index = Property::INVALID_INDEX;
425 // Look for name in default properties
426 for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
428 const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[ i ];
429 if( 0 == strcmp( name.c_str(), property->name ) ) // dont want to convert rhs to string
440 bool ShaderEffect::IsDefaultPropertyWritable(Property::Index index) const
442 return true; // all properties are writable
445 bool ShaderEffect::IsDefaultPropertyAnimatable(Property::Index index) const
447 return false; // all properties are non animatable
450 bool ShaderEffect::IsDefaultPropertyAConstraintInput( Property::Index index ) const
452 return false; // all properties cannot be used as constraint input
455 Property::Type ShaderEffect::GetDefaultPropertyType(Property::Index index) const
457 if( index < DEFAULT_PROPERTY_COUNT )
459 return DEFAULT_PROPERTY_DETAILS[index].type;
463 // index out of range...return Property::NONE
464 return Property::NONE;
468 void ShaderEffect::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
472 case Dali::ShaderEffect::GRID_DENSITY:
474 SetGridDensityMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, propertyValue.Get<float>() );
478 case Dali::ShaderEffect::IMAGE:
480 Dali::Image img(Scripting::NewImage( propertyValue ));
483 SetEffectImage( img );
487 DALI_LOG_WARNING("Cannot create image from property value for ShaderEffect image\n");
492 case Dali::ShaderEffect::PROGRAM:
494 std::string vertexPrefix = GetShader("vertex-prefix", propertyValue);
495 std::string fragmentPrefix = GetShader("fragment-prefix", propertyValue);
496 std::string vertex = GetShader("vertex", propertyValue);
497 std::string fragment = GetShader("fragment", propertyValue);
499 GeometryType geometryType = GEOMETRY_TYPE_IMAGE;
501 if( propertyValue.HasKey("geometry-type") )
503 Property::Value geometryValue = propertyValue.GetValue("geometry-type");
504 DALI_ASSERT_ALWAYS(geometryValue.GetType() == Property::STRING && "Geometry type is not a string" );
506 std::string s = geometryValue.Get<std::string>();
507 if(s == "GEOMETRY_TYPE_IMAGE")
509 geometryType = GEOMETRY_TYPE_IMAGE;
511 else if (s == "GEOMETRY_TYPE_TEXT")
513 geometryType = GEOMETRY_TYPE_TEXT;
515 else if( s == "GEOMETRY_TYPE_UNTEXTURED_MESH")
517 geometryType = GEOMETRY_TYPE_UNTEXTURED_MESH;
519 else if( s == "GEOMETRY_TYPE_TEXTURED_MESH")
521 geometryType = GEOMETRY_TYPE_TEXTURED_MESH;
525 DALI_ASSERT_ALWAYS(!"Geometry type unknown" );
528 SetPrograms( geometryType, vertexPrefix, fragmentPrefix, vertex, fragment );
532 case Dali::ShaderEffect::GEOMETRY_HINTS:
534 Dali::ShaderEffect::GeometryHints hint = Dali::ShaderEffect::HINT_NONE;
535 Property::Value geometryHintsValue = propertyValue.GetValue("geometry-hints");
537 std::string s = geometryHintsValue.Get<std::string>();
540 hint = Dali::ShaderEffect::HINT_NONE;
542 else if(s == "HINT_GRID_X")
544 hint = Dali::ShaderEffect::HINT_GRID_X;
546 else if(s == "HINT_GRID_Y")
548 hint = Dali::ShaderEffect::HINT_GRID_Y;
550 else if(s == "HINT_GRID")
552 hint = Dali::ShaderEffect::HINT_GRID;
554 else if(s == "HINT_DEPTH_BUFFER")
556 hint = Dali::ShaderEffect::HINT_DEPTH_BUFFER;
558 else if(s == "HINT_BLENDING")
560 hint = Dali::ShaderEffect::HINT_BLENDING;
562 else if(s == "HINT_DOESNT_MODIFY_GEOMETRY")
564 hint = Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY;
568 DALI_ASSERT_ALWAYS(!"Geometry hint unknown" );
571 SetHintsMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, hint );
584 Property::Value ShaderEffect::GetDefaultProperty(Property::Index /*index*/) const
586 // none of our properties are readable so return empty
587 return Property::Value();
590 void ShaderEffect::NotifyScenePropertyInstalled( const SceneGraph::PropertyBase& newProperty, const std::string& name, unsigned int index )
592 // 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)
594 // mSceneObject requires metadata for each custom property (uniform)
595 UniformMeta* meta = UniformMeta::New( name, newProperty, Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT );
596 // mSceneObject is being used in a separate thread; queue a message to add the property
597 InstallUniformMetaMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, *meta ); // Message takes ownership
600 const SceneGraph::PropertyOwner* ShaderEffect::GetSceneObject() const
605 const PropertyBase* ShaderEffect::GetSceneObjectAnimatableProperty( Property::Index index ) const
607 CustomProperty* custom = FindCustomProperty( index );
608 DALI_ASSERT_ALWAYS( custom && "Property index is invalid" );
609 return custom->GetSceneGraphProperty();
612 const PropertyInputImpl* ShaderEffect::GetSceneObjectInputProperty( Property::Index index ) const
614 return GetSceneObjectAnimatableProperty( index );
617 } // namespace Internal