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/common/property-owner-messages.h>
38 #include <dali/internal/update/animation/scene-graph-constraint-base.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;
52 const Property::Index ShaderEffect::GRID_DENSITY = 0;
53 const Property::Index ShaderEffect::IMAGE = 1;
54 const Property::Index ShaderEffect::PROGRAM = 2;
55 const Property::Index ShaderEffect::GEOMETRY_HINTS = 3;
62 const PropertyDetails DEFAULT_PROPERTY_DETAILS[] =
64 // Name Type writable animatable constraint-input
65 { "grid-density", Property::FLOAT, true, false, false }, // GRID_DENSITY
66 { "image", Property::MAP, true, false, false }, // IMAGE
67 { "program", Property::MAP, true, false, false }, // PROGRAM
68 { "geometry-hints", Property::INTEGER, true, false, false }, // GEOMETRY_HINTS
71 const int DEFAULT_PROPERTY_COUNT = sizeof( DEFAULT_PROPERTY_DETAILS ) / sizeof( DEFAULT_PROPERTY_DETAILS[0] );
75 Internal::ShaderEffectPtr internal = Internal::ShaderEffect::New();
77 return Dali::ShaderEffect(internal.Get());
80 TypeRegistration mType( typeid(Dali::ShaderEffect), typeid(Dali::Handle), Create );
84 const char* vertexShaderPrefix;
85 const char* fragmentShaderPrefix;
86 const char* vertexShaderPostfix;
87 const char* fragmentShaderPostfix;
90 WrapperStrings customShaderWrappers [] =
93 CustomImagePrefixVertex, CustomImagePrefixFragment,
94 CustomImagePostfixVertex, CustomImagePostfixFragment
97 CustomTextDistanceFieldPrefixVertex, CustomTextDistanceFieldPrefixFragment,
98 CustomTextDistanceFieldPostfixVertex, CustomTextDistanceFieldPostfixFragment
101 CustomUntexturedMeshPrefixVertex, CustomUntexturedMeshPrefixFragment,
102 CustomUntexturedMeshPostfixVertex, CustomUntexturedMeshPostfixFragment
105 CustomTexturedMeshPrefixVertex, CustomTexturedMeshPrefixFragment,
106 CustomTexturedMeshPostfixVertex, CustomTexturedMeshPostfixFragment
111 * Helper to wrap the program with our default pre and postfix if needed and then send it to update/render thread
112 * @param[in] effect of the shader
113 * @param[in] actualGeometryType of the shader
114 * @param[in] expectedGeometryType of the shader
115 * @param[in] vertexPrefix from application
116 * @param[in] fragmentPrefix from application
117 * @param[in] vertexBody from application
118 * @param[in] fragmentBody from application
119 * @param[in] modifiesGeometry based on flags and vertex shader
121 void WrapAndSetProgram( Internal::ShaderEffect& effect,
122 GeometryType actualGeometryType, GeometryType expectedGeometryType,
123 const std::string& vertexPrefix, const std::string& fragmentPrefix,
124 const std::string& vertexBody, const std::string& fragmentBody,
125 bool modifiesGeometry )
127 // if geometry type matches and there is some real data in the strings
128 if( ( actualGeometryType & expectedGeometryType )&&
129 ( ( vertexPrefix.length() > 0 )||
130 ( fragmentPrefix.length() > 0 )||
131 ( vertexBody.length() > 0 )||
132 ( fragmentBody.length() > 0 ) ) )
134 std::string vertexSource = vertexPrefix;
135 std::string fragmentSource = fragmentPrefix;
137 // create complete shader program strings for the given geometry type
138 unsigned int index = 0;
139 switch( expectedGeometryType )
141 case GEOMETRY_TYPE_IMAGE:
146 case GEOMETRY_TYPE_TEXT:
151 case GEOMETRY_TYPE_UNTEXTURED_MESH:
156 case GEOMETRY_TYPE_TEXTURED_MESH:
161 case GEOMETRY_TYPE_LAST:
163 DALI_ASSERT_DEBUG(0 && "Wrong geometry type");
168 vertexSource += customShaderWrappers[index].vertexShaderPrefix;
169 // Append the custom vertex shader code if supplied, otherwise append the default
170 if ( vertexBody.length() > 0 )
172 vertexSource.append( vertexBody );
176 vertexSource.append( customShaderWrappers[index].vertexShaderPostfix );
179 fragmentSource += customShaderWrappers[index].fragmentShaderPrefix;
180 // Append the custom fragment shader code if supplied, otherwise append the default
181 if ( fragmentBody.length() > 0 )
183 fragmentSource.append( fragmentBody );
187 fragmentSource.append( customShaderWrappers[index].fragmentShaderPostfix );
190 effect.SendProgramMessage( expectedGeometryType, SHADER_SUBTYPE_ALL, vertexSource, fragmentSource, modifiesGeometry );
194 std::string GetShader(const std::string& field, const Property::Value& property)
197 if( property.HasKey(field) )
199 DALI_ASSERT_ALWAYS(property.GetValue(field).GetType() == Property::STRING && "Shader property is not a string" );
201 // we could also check here for an array of strings as convenience for json not having multi line strings
202 value = property.GetValue(field).Get<std::string>();
208 } // unnamed namespace
210 ShaderEffectPtr ShaderEffect::New( Dali::ShaderEffect::GeometryHints hints )
212 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
213 UpdateManager& updateManager = tls.GetUpdateManager();
215 ShaderEffectPtr shaderEffect( new ShaderEffect( updateManager, hints ) );
216 shaderEffect->RegisterObject();
221 ShaderEffect::ShaderEffect( UpdateManager& updateManager, Dali::ShaderEffect::GeometryHints hints )
222 : mUpdateManager( updateManager ),
223 mConnectionCount (0),
224 mGeometryHints( hints )
226 mSceneObject = new Shader( hints );
227 DALI_ASSERT_DEBUG( NULL != mSceneObject );
229 // Transfer shader ownership to a scene message
230 AddShaderMessage( mUpdateManager, *mSceneObject );
233 ShaderEffect::~ShaderEffect()
235 // Guard to allow handle destruction after Core has been destroyed
236 if ( Stage::IsInstalled() )
238 // Remove scene-object using a message to the UpdateManager
241 RemoveShaderMessage( mUpdateManager, *mSceneObject );
247 void ShaderEffect::SetEffectImage( Dali::Image image )
249 // if images are the same, do nothing
255 if (mImage && mConnectionCount > 0)
257 // unset previous image
258 GetImplementation(mImage).Disconnect();
261 // in case image is empty this will reset our image handle
266 // mSceneShader can be in a separate thread; queue a setter message
267 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, 0 );
271 // tell image that we're using it
272 if (mConnectionCount > 0)
274 GetImplementation(mImage).Connect();
276 // mSceneShader can be in a separate thread; queue a setter message
277 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
281 void ShaderEffect::SetUniform( const std::string& name, Property::Value value, UniformCoordinateType uniformCoordinateType )
283 // Register the property if it does not exist
284 Property::Index index = GetPropertyIndex( name );
285 if ( Property::INVALID_INDEX == index )
287 index = RegisterProperty( name, value );
290 SetProperty( index, value );
292 // RegisterProperty guarantees a positive value as index
293 DALI_ASSERT_DEBUG( static_cast<unsigned int>(index) >= CustomPropertyStartIndex() );
294 unsigned int metaIndex = index - CustomPropertyStartIndex();
295 // check if there's space in cache
296 if( mCoordinateTypes.Count() < (metaIndex + 1) )
298 mCoordinateTypes.Resize( metaIndex + 1 );
300 // only send message if the value is different than current, initial value is COORDINATE_TYPE_DEFAULT (0)
301 if( uniformCoordinateType != mCoordinateTypes[ metaIndex ] )
303 mCoordinateTypes[ metaIndex ] = uniformCoordinateType;
304 SetCoordinateTypeMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, metaIndex, uniformCoordinateType );
308 void ShaderEffect::AttachExtension( Dali::ShaderEffect::Extension *extension )
310 DALI_ASSERT_ALWAYS( extension != NULL && "Attaching uninitialized extension" );
311 mExtension = IntrusivePtr<Dali::ShaderEffect::Extension>( extension );
314 Dali::ShaderEffect::Extension& ShaderEffect::GetExtension()
316 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
320 const Dali::ShaderEffect::Extension& ShaderEffect::GetExtension() const
322 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
326 void ShaderEffect::SetPrograms( GeometryType geometryType, const string& vertexSource, const string& fragmentSource )
328 SetPrograms( geometryType, "", "", vertexSource, fragmentSource );
331 void ShaderEffect::SetPrograms( GeometryType geometryType,
332 const std::string& vertexPrefix, const std::string& fragmentPrefix,
333 const std::string& vertexSource, const std::string& fragmentSource )
335 bool modifiesGeometry = true;
336 // check if the vertex shader is empty (means it cannot modify geometry)
337 if( (vertexPrefix.length() == 0 )&&( vertexSource.length() == 0 ) )
339 modifiesGeometry = false;
341 // check the hint second
342 if( (mGeometryHints & Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY ) != 0 )
344 modifiesGeometry = false;
347 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_IMAGE, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
348 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXT, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
349 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
350 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_UNTEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
353 void ShaderEffect::SendProgramMessage( GeometryType geometryType, ShaderSubTypes subType,
354 const string& vertexSource, const string& fragmentSource,
355 bool modifiesGeometry )
357 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
358 ShaderFactory& shaderFactory = tls.GetShaderFactory();
361 ResourceTicketPtr ticket( shaderFactory.Load(vertexSource, fragmentSource, shaderHash) );
363 DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "ShaderEffect: SetProgram(geometryType %d subType:%d ticket.id:%d)\n", geometryType, subType, ticket->GetId() );
365 // Add shader program to scene-object using a message to the UpdateManager
366 SetShaderProgramMessage( mUpdateManager, *mSceneObject, geometryType, subType, ticket->GetId(), shaderHash, modifiesGeometry );
368 mTickets.push_back(ticket); // add ticket to collection to keep it alive.
371 void ShaderEffect::Connect()
375 if (mImage && mConnectionCount == 1)
377 GetImplementation(mImage).Connect();
379 // Image may have changed resource due to load/release policy. Ensure correct texture ID is set on scene graph object
380 SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
384 void ShaderEffect::Disconnect()
386 DALI_ASSERT_DEBUG(mConnectionCount > 0);
389 if (mImage && mConnectionCount == 0)
391 GetImplementation(mImage).Disconnect();
395 unsigned int ShaderEffect::GetDefaultPropertyCount() const
397 return DEFAULT_PROPERTY_COUNT;
400 void ShaderEffect::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const
402 indices.reserve( DEFAULT_PROPERTY_COUNT );
404 for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
406 indices.push_back( i );
410 const char* ShaderEffect::GetDefaultPropertyName(Property::Index index) const
412 if( index < DEFAULT_PROPERTY_COUNT )
414 return DEFAULT_PROPERTY_DETAILS[index].name;
422 Property::Index ShaderEffect::GetDefaultPropertyIndex(const std::string& name) const
424 Property::Index index = Property::INVALID_INDEX;
426 // Look for name in default properties
427 for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
429 const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[ i ];
430 if( 0 == strcmp( name.c_str(), property->name ) ) // dont want to convert rhs to string
441 bool ShaderEffect::IsDefaultPropertyWritable(Property::Index index) const
443 return true; // all properties are writable
446 bool ShaderEffect::IsDefaultPropertyAnimatable(Property::Index index) const
448 return false; // all properties are non animatable
451 bool ShaderEffect::IsDefaultPropertyAConstraintInput( Property::Index index ) const
453 return false; // all properties cannot be used as constraint input
456 Property::Type ShaderEffect::GetDefaultPropertyType(Property::Index index) const
458 if( index < DEFAULT_PROPERTY_COUNT )
460 return DEFAULT_PROPERTY_DETAILS[index].type;
464 // index out of range...return Property::NONE
465 return Property::NONE;
469 void ShaderEffect::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
473 case Dali::ShaderEffect::GRID_DENSITY:
475 SetGridDensityMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, propertyValue.Get<float>() );
479 case Dali::ShaderEffect::IMAGE:
481 Dali::Image img(Scripting::NewImage( propertyValue ));
484 SetEffectImage( img );
488 DALI_LOG_WARNING("Cannot create image from property value for ShaderEffect image\n");
493 case Dali::ShaderEffect::PROGRAM:
495 std::string vertexPrefix = GetShader("vertex-prefix", propertyValue);
496 std::string fragmentPrefix = GetShader("fragment-prefix", propertyValue);
497 std::string vertex = GetShader("vertex", propertyValue);
498 std::string fragment = GetShader("fragment", propertyValue);
500 GeometryType geometryType = GEOMETRY_TYPE_IMAGE;
502 if( propertyValue.HasKey("geometry-type") )
504 Property::Value geometryValue = propertyValue.GetValue("geometry-type");
505 DALI_ASSERT_ALWAYS(geometryValue.GetType() == Property::STRING && "Geometry type is not a string" );
507 std::string s = geometryValue.Get<std::string>();
508 if(s == "GEOMETRY_TYPE_IMAGE")
510 geometryType = GEOMETRY_TYPE_IMAGE;
512 else if (s == "GEOMETRY_TYPE_TEXT")
514 geometryType = GEOMETRY_TYPE_TEXT;
516 else if( s == "GEOMETRY_TYPE_UNTEXTURED_MESH")
518 geometryType = GEOMETRY_TYPE_UNTEXTURED_MESH;
520 else if( s == "GEOMETRY_TYPE_TEXTURED_MESH")
522 geometryType = GEOMETRY_TYPE_TEXTURED_MESH;
526 DALI_ASSERT_ALWAYS(!"Geometry type unknown" );
529 SetPrograms( geometryType, vertexPrefix, fragmentPrefix, vertex, fragment );
533 case Dali::ShaderEffect::GEOMETRY_HINTS:
535 Dali::ShaderEffect::GeometryHints hint = Dali::ShaderEffect::HINT_NONE;
536 Property::Value geometryHintsValue = propertyValue.GetValue("geometry-hints");
538 std::string s = geometryHintsValue.Get<std::string>();
541 hint = Dali::ShaderEffect::HINT_NONE;
543 else if(s == "HINT_GRID_X")
545 hint = Dali::ShaderEffect::HINT_GRID_X;
547 else if(s == "HINT_GRID_Y")
549 hint = Dali::ShaderEffect::HINT_GRID_Y;
551 else if(s == "HINT_GRID")
553 hint = Dali::ShaderEffect::HINT_GRID;
555 else if(s == "HINT_DEPTH_BUFFER")
557 hint = Dali::ShaderEffect::HINT_DEPTH_BUFFER;
559 else if(s == "HINT_BLENDING")
561 hint = Dali::ShaderEffect::HINT_BLENDING;
563 else if(s == "HINT_DOESNT_MODIFY_GEOMETRY")
565 hint = Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY;
569 DALI_ASSERT_ALWAYS(!"Geometry hint unknown" );
572 SetHintsMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, hint );
579 DALI_ASSERT_ALWAYS(false && "ShaderEffect property enumeration out of range"); // should not come here
585 Property::Value ShaderEffect::GetDefaultProperty(Property::Index /*index*/) const
587 // none of our properties are readable so return empty
588 return Property::Value();
591 void ShaderEffect::InstallSceneObjectProperty( PropertyBase& newProperty, const std::string& name, unsigned int index )
593 // 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)
595 // mSceneObject is being used in a separate thread; queue a message to add the property
596 InstallCustomPropertyMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, newProperty ); // Message takes ownership
598 // mSceneObject requires metadata for each custom property (uniform)
599 UniformMeta* meta = UniformMeta::New( name, newProperty, Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT );
600 // mSceneObject is being used in a separate thread; queue a message to add the property
601 InstallUniformMetaMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, *meta ); // Message takes ownership
604 const SceneGraph::PropertyOwner* ShaderEffect::GetSceneObject() const
609 const PropertyBase* ShaderEffect::GetSceneObjectAnimatableProperty( Property::Index index ) const
611 CustomProperty* custom = FindCustomProperty( index );
612 DALI_ASSERT_ALWAYS( custom && "Property index is invalid" );
613 return custom->GetSceneGraphProperty();
616 const PropertyInputImpl* ShaderEffect::GetSceneObjectInputProperty( Property::Index index ) const
618 return GetSceneObjectAnimatableProperty( index );
621 } // namespace Internal