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/scene-graph-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 CustomUntexturedMeshPrefixVertex, CustomUntexturedMeshPrefixFragment,
93 CustomUntexturedMeshPostfixVertex, CustomUntexturedMeshPostfixFragment
96 CustomTexturedMeshPrefixVertex, CustomTexturedMeshPrefixFragment,
97 CustomTexturedMeshPostfixVertex, CustomTexturedMeshPostfixFragment
102 * Helper to wrap the program with our default pre and postfix if needed and then send it to update/render thread
103 * @param[in] effect of the shader
104 * @param[in] actualGeometryType of the shader
105 * @param[in] expectedGeometryType of the shader
106 * @param[in] vertexPrefix from application
107 * @param[in] fragmentPrefix from application
108 * @param[in] vertexBody from application
109 * @param[in] fragmentBody from application
110 * @param[in] modifiesGeometry based on flags and vertex shader
112 void WrapAndSetProgram( Internal::ShaderEffect& effect,
113 GeometryType actualGeometryType, GeometryType expectedGeometryType,
114 const std::string& vertexPrefix, const std::string& fragmentPrefix,
115 const std::string& vertexBody, const std::string& fragmentBody,
116 bool modifiesGeometry )
118 // if geometry type matches and there is some real data in the strings
119 if( ( actualGeometryType & expectedGeometryType )&&
120 ( ( vertexPrefix.length() > 0 )||
121 ( fragmentPrefix.length() > 0 )||
122 ( vertexBody.length() > 0 )||
123 ( fragmentBody.length() > 0 ) ) )
125 std::string vertexSource = vertexPrefix;
126 std::string fragmentSource = fragmentPrefix;
128 // create complete shader program strings for the given geometry type
129 unsigned int index = 0;
130 switch( expectedGeometryType )
132 case GEOMETRY_TYPE_IMAGE:
137 case GEOMETRY_TYPE_UNTEXTURED_MESH:
142 case GEOMETRY_TYPE_TEXTURED_MESH:
147 case GEOMETRY_TYPE_LAST:
149 DALI_ASSERT_DEBUG(0 && "Wrong geometry type");
154 vertexSource += customShaderWrappers[index].vertexShaderPrefix;
155 // Append the custom vertex shader code if supplied, otherwise append the default
156 if ( vertexBody.length() > 0 )
158 vertexSource.append( vertexBody );
162 vertexSource.append( customShaderWrappers[index].vertexShaderPostfix );
165 fragmentSource += customShaderWrappers[index].fragmentShaderPrefix;
166 // Append the custom fragment shader code if supplied, otherwise append the default
167 if ( fragmentBody.length() > 0 )
169 fragmentSource.append( fragmentBody );
173 fragmentSource.append( customShaderWrappers[index].fragmentShaderPostfix );
176 effect.SendProgramMessage( expectedGeometryType, SHADER_SUBTYPE_ALL, vertexSource, fragmentSource, modifiesGeometry );
180 std::string GetShader(const std::string& field, const Property::Value& property)
183 if( property.HasKey(field) )
185 DALI_ASSERT_ALWAYS(property.GetValue(field).GetType() == Property::STRING && "Shader property is not a string" );
187 // we could also check here for an array of strings as convenience for json not having multi line strings
188 value = property.GetValue(field).Get<std::string>();
194 } // unnamed namespace
196 ShaderEffectPtr ShaderEffect::New( Dali::ShaderEffect::GeometryHints hints )
198 Stage* stage = Stage::GetCurrent();
200 ShaderEffectPtr shaderEffect( new ShaderEffect( *stage, hints ) );
201 shaderEffect->RegisterObject();
206 ShaderEffect::ShaderEffect( EventThreadServices& eventThreadServices, Dali::ShaderEffect::GeometryHints hints )
207 : mEventThreadServices( eventThreadServices ),
208 mConnectionCount (0),
209 mGeometryHints( hints )
211 mSceneObject = new SceneGraph::Shader( hints );
212 DALI_ASSERT_DEBUG( NULL != mSceneObject );
214 // Transfer shader ownership to a scene message
215 AddShaderMessage( eventThreadServices.GetUpdateManager(), *mSceneObject );
218 ShaderEffect::~ShaderEffect()
220 // Guard to allow handle destruction after Core has been destroyed
221 if ( Stage::IsInstalled() )
223 // Remove scene-object using a message to the UpdateManager
226 RemoveShaderMessage( mEventThreadServices.GetUpdateManager(), *mSceneObject );
232 void ShaderEffect::SetEffectImage( Dali::Image image )
234 // if images are the same, do nothing
240 if (mImage && mConnectionCount > 0)
242 // unset previous image
243 GetImplementation(mImage).Disconnect();
246 // in case image is empty this will reset our image handle
251 // mSceneShader can be in a separate thread; queue a setter message
252 SetTextureIdMessage( mEventThreadServices, *mSceneObject, 0 );
256 // tell image that we're using it
257 if (mConnectionCount > 0)
259 GetImplementation(mImage).Connect();
261 // mSceneShader can be in a separate thread; queue a setter message
262 SetTextureIdMessage( mEventThreadServices, *mSceneObject, GetImplementation(mImage).GetResourceId() );
266 void ShaderEffect::SetUniform( const std::string& name, Property::Value value, UniformCoordinateType uniformCoordinateType )
268 // Register the property if it does not exist
269 Property::Index index = GetPropertyIndex( name );
270 if ( Property::INVALID_INDEX == index )
272 index = RegisterProperty( name, value );
275 SetProperty( index, value );
277 // RegisterProperty guarantees a positive value as index
278 DALI_ASSERT_DEBUG( static_cast<unsigned int>(index) >= CustomPropertyStartIndex() );
279 unsigned int metaIndex = index - CustomPropertyStartIndex();
280 // check if there's space in cache
281 if( mCoordinateTypes.Count() < (metaIndex + 1) )
283 mCoordinateTypes.Resize( metaIndex + 1 );
285 // only send message if the value is different than current, initial value is COORDINATE_TYPE_DEFAULT (0)
286 if( uniformCoordinateType != mCoordinateTypes[ metaIndex ] )
288 mCoordinateTypes[ metaIndex ] = uniformCoordinateType;
289 SetCoordinateTypeMessage( mEventThreadServices, *mSceneObject, metaIndex, uniformCoordinateType );
293 void ShaderEffect::AttachExtension( Dali::ShaderEffect::Extension *extension )
295 DALI_ASSERT_ALWAYS( extension != NULL && "Attaching uninitialized extension" );
296 mExtension = IntrusivePtr<Dali::ShaderEffect::Extension>( extension );
299 Dali::ShaderEffect::Extension& ShaderEffect::GetExtension()
301 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
305 const Dali::ShaderEffect::Extension& ShaderEffect::GetExtension() const
307 DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
311 void ShaderEffect::SetPrograms( GeometryType geometryType, const string& vertexSource, const string& fragmentSource )
313 SetPrograms( geometryType, "", "", vertexSource, fragmentSource );
316 void ShaderEffect::SetPrograms( GeometryType geometryType,
317 const std::string& vertexPrefix, const std::string& fragmentPrefix,
318 const std::string& vertexSource, const std::string& fragmentSource )
320 bool modifiesGeometry = true;
321 // check if the vertex shader is empty (means it cannot modify geometry)
322 if( (vertexPrefix.length() == 0 )&&( vertexSource.length() == 0 ) )
324 modifiesGeometry = false;
326 // check the hint second
327 if( (mGeometryHints & Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY ) != 0 )
329 modifiesGeometry = false;
332 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_IMAGE, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
333 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
334 WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_UNTEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
337 void ShaderEffect::SendProgramMessage( GeometryType geometryType, ShaderSubTypes subType,
338 const string& vertexSource, const string& fragmentSource,
339 bool modifiesGeometry )
341 ThreadLocalStorage& tls = ThreadLocalStorage::Get();
342 ShaderFactory& shaderFactory = tls.GetShaderFactory();
345 ResourceTicketPtr ticket( shaderFactory.Load(vertexSource, fragmentSource, shaderHash) );
347 DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "ShaderEffect: SetProgram(geometryType %d subType:%d ticket.id:%d)\n", geometryType, subType, ticket->GetId() );
349 // Add shader program to scene-object using a message to the UpdateManager
350 SetShaderProgramMessage( mEventThreadServices.GetUpdateManager(), *mSceneObject, geometryType, subType, ticket->GetId(), shaderHash, modifiesGeometry );
352 mTickets.push_back(ticket); // add ticket to collection to keep it alive.
355 void ShaderEffect::Connect()
359 if (mImage && mConnectionCount == 1)
361 GetImplementation(mImage).Connect();
363 // Image may have changed resource due to load/release policy. Ensure correct texture ID is set on scene graph object
364 SetTextureIdMessage( mEventThreadServices, *mSceneObject, GetImplementation(mImage).GetResourceId() );
368 void ShaderEffect::Disconnect()
370 DALI_ASSERT_DEBUG(mConnectionCount > 0);
373 if (mImage && mConnectionCount == 0)
375 GetImplementation(mImage).Disconnect();
379 unsigned int ShaderEffect::GetDefaultPropertyCount() const
381 return DEFAULT_PROPERTY_COUNT;
384 void ShaderEffect::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const
386 indices.reserve( DEFAULT_PROPERTY_COUNT );
388 for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
390 indices.push_back( i );
394 const char* ShaderEffect::GetDefaultPropertyName(Property::Index index) const
396 if( index < DEFAULT_PROPERTY_COUNT )
398 return DEFAULT_PROPERTY_DETAILS[index].name;
404 Property::Index ShaderEffect::GetDefaultPropertyIndex(const std::string& name) const
406 Property::Index index = Property::INVALID_INDEX;
408 // Look for name in default properties
409 for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
411 const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[ i ];
412 if( 0 == strcmp( name.c_str(), property->name ) ) // dont want to convert rhs to string
422 bool ShaderEffect::IsDefaultPropertyWritable(Property::Index index) const
424 return DEFAULT_PROPERTY_DETAILS[ index ].writable;
427 bool ShaderEffect::IsDefaultPropertyAnimatable(Property::Index index) const
429 return DEFAULT_PROPERTY_DETAILS[ index ].animatable;
432 bool ShaderEffect::IsDefaultPropertyAConstraintInput( Property::Index index ) const
434 return DEFAULT_PROPERTY_DETAILS[ index ].constraintInput;
437 Property::Type ShaderEffect::GetDefaultPropertyType(Property::Index index) const
439 if( index < DEFAULT_PROPERTY_COUNT )
441 return DEFAULT_PROPERTY_DETAILS[index].type;
444 // index out of range...return Property::NONE
445 return Property::NONE;
448 void ShaderEffect::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
452 case Dali::ShaderEffect::Property::GRID_DENSITY:
454 SetGridDensityMessage( mEventThreadServices, *mSceneObject, propertyValue.Get<float>() );
458 case Dali::ShaderEffect::Property::IMAGE:
460 Dali::Image img(Scripting::NewImage( propertyValue ));
463 SetEffectImage( img );
467 DALI_LOG_WARNING("Cannot create image from property value for ShaderEffect image\n");
472 case Dali::ShaderEffect::Property::PROGRAM:
474 std::string vertexPrefix = GetShader("vertex-prefix", propertyValue);
475 std::string fragmentPrefix = GetShader("fragment-prefix", propertyValue);
476 std::string vertex = GetShader("vertex", propertyValue);
477 std::string fragment = GetShader("fragment", propertyValue);
479 GeometryType geometryType = GEOMETRY_TYPE_IMAGE;
481 if( propertyValue.HasKey("geometry-type") )
483 Property::Value geometryValue = propertyValue.GetValue("geometry-type");
484 DALI_ASSERT_ALWAYS(geometryValue.GetType() == Property::STRING && "Geometry type is not a string" );
486 std::string s = geometryValue.Get<std::string>();
487 if(s == "GEOMETRY_TYPE_IMAGE")
489 geometryType = GEOMETRY_TYPE_IMAGE;
491 else if( s == "GEOMETRY_TYPE_UNTEXTURED_MESH")
493 geometryType = GEOMETRY_TYPE_UNTEXTURED_MESH;
495 else if( s == "GEOMETRY_TYPE_TEXTURED_MESH")
497 geometryType = GEOMETRY_TYPE_TEXTURED_MESH;
501 DALI_ASSERT_ALWAYS(!"Geometry type unknown" );
504 SetPrograms( geometryType, vertexPrefix, fragmentPrefix, vertex, fragment );
508 case Dali::ShaderEffect::Property::GEOMETRY_HINTS:
510 Dali::ShaderEffect::GeometryHints hint = Dali::ShaderEffect::HINT_NONE;
511 Property::Value geometryHintsValue = propertyValue.GetValue("geometry-hints");
513 std::string s = geometryHintsValue.Get<std::string>();
516 hint = Dali::ShaderEffect::HINT_NONE;
518 else if(s == "HINT_GRID_X")
520 hint = Dali::ShaderEffect::HINT_GRID_X;
522 else if(s == "HINT_GRID_Y")
524 hint = Dali::ShaderEffect::HINT_GRID_Y;
526 else if(s == "HINT_GRID")
528 hint = Dali::ShaderEffect::HINT_GRID;
530 else if(s == "HINT_DEPTH_BUFFER")
532 hint = Dali::ShaderEffect::HINT_DEPTH_BUFFER;
534 else if(s == "HINT_BLENDING")
536 hint = Dali::ShaderEffect::HINT_BLENDING;
538 else if(s == "HINT_DOESNT_MODIFY_GEOMETRY")
540 hint = Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY;
544 DALI_ASSERT_ALWAYS(!"Geometry hint unknown" );
547 SetHintsMessage( mEventThreadServices, *mSceneObject, hint );
560 Property::Value ShaderEffect::GetDefaultProperty(Property::Index /*index*/) const
562 // none of our properties are readable so return empty
563 return Property::Value();
566 void ShaderEffect::NotifyScenePropertyInstalled( const SceneGraph::PropertyBase& newProperty, const std::string& name, unsigned int index ) const
568 // 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)
570 // mSceneObject requires metadata for each custom property (uniform)
571 UniformMeta* meta = UniformMeta::New( name, newProperty, Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT );
572 // mSceneObject is being used in a separate thread; queue a message to add the property
573 InstallUniformMetaMessage( mEventThreadServices, *mSceneObject, *meta ); // Message takes ownership
576 const SceneGraph::PropertyOwner* ShaderEffect::GetSceneObject() const
581 const PropertyBase* ShaderEffect::GetSceneObjectAnimatableProperty( Property::Index index ) const
583 PropertyMetadata* property = index >= PROPERTY_CUSTOM_START_INDEX ? static_cast<PropertyMetadata*>(FindCustomProperty( index )) : static_cast<PropertyMetadata*>(FindAnimatableProperty( index ));
584 DALI_ASSERT_ALWAYS( property && "Property index is invalid" );
585 return property->GetSceneGraphProperty();
588 const PropertyInputImpl* ShaderEffect::GetSceneObjectInputProperty( Property::Index index ) const
590 return GetSceneObjectAnimatableProperty( index );
593 } // namespace Internal