2 * Copyright (c) 2016 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 "mesh-renderer.h"
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/images/resource-image.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/devel-api/adaptor-framework/bitmap-loader.h>
26 #include <dali/devel-api/adaptor-framework/file-loader.h>
30 #include <dali-toolkit/internal/controls/renderers/renderer-string-constants.h>
31 #include <dali-toolkit/internal/controls/renderers/renderer-factory-impl.h>
32 #include <dali-toolkit/internal/controls/renderers/renderer-factory-cache.h>
33 #include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
41 * @brief Loads a texture from a file
42 * @param[in] imageUrl The url of the file
43 * @param[in] generateMipmaps Indicates whether to generate mipmaps for the texture
44 * @return A texture if loading succeeds, an empty handle otherwise
46 Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
49 Dali::BitmapLoader loader = Dali::BitmapLoader::New( imageUrl );
51 PixelData pixelData = loader.GetPixelData();
54 texture = Texture::New( TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight() );
55 texture.Upload( pixelData );
59 texture.GenerateMipmaps();
76 //Defines ordering of textures for shaders.
77 //All shaders, if including certain texture types, must include them in the same order.
78 //Within the texture set for the renderer, textures are ordered in the same manner.
86 const char * const LIGHT_POSITION( "uLightPosition" ); //Shader property
87 const char * const OBJECT_MATRIX( "uObjectMatrix" ); //Shader property
89 const char * const SHADER_TYPE_TEXTURELESS( "TEXTURELESS" );
90 const char * const SHADER_TYPE_DIFFUSE_TEXTURE( "DIFFUSE_TEXTURE" );
91 const char * const SHADER_TYPE_ALL_TEXTURES( "ALL_TEXTURES" );
94 //If a shader requires certain textures, they must be listed in order,
95 //as detailed in the TextureIndex enum documentation.
97 //A basic shader that doesn't use textures at all.
98 const char* SIMPLE_VERTEX_SHADER = DALI_COMPOSE_SHADER(
99 attribute highp vec3 aPosition;\n
100 attribute highp vec3 aNormal;\n
101 varying mediump vec3 vIllumination;\n
102 uniform mediump vec3 uSize;\n
103 uniform mediump mat4 uMvpMatrix;\n
104 uniform mediump mat4 uModelView;\n
105 uniform mediump mat3 uNormalMatrix;
106 uniform mediump mat4 uObjectMatrix;\n
107 uniform mediump vec3 uLightPosition;\n
111 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
112 vertexPosition = uObjectMatrix * vertexPosition;\n
113 vertexPosition = uMvpMatrix * vertexPosition;\n
115 //Illumination in Model-View space - Transform attributes and uniforms\n
116 vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
117 vec3 normal = uNormalMatrix * mat3( uObjectMatrix ) * aNormal;\n
118 vec4 centre = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
119 vec4 lightPos = vec4( centre.x, centre.y, uLightPosition.z, 1.0 );\n
120 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
122 float lightDiffuse = max( dot( vecToLight, normal ), 0.0 );\n
123 vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
125 gl_Position = vertexPosition;\n
129 //Fragment shader corresponding to the texture-less shader.
130 const char* SIMPLE_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
131 precision mediump float;\n
132 varying mediump vec3 vIllumination;\n
133 uniform lowp vec4 uColor;\n
137 gl_FragColor = vec4( vIllumination.rgb * uColor.rgb, uColor.a );\n
141 //Diffuse and specular illumination shader with albedo texture. Texture is index 0.
142 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
143 attribute highp vec3 aPosition;\n
144 attribute highp vec2 aTexCoord;\n
145 attribute highp vec3 aNormal;\n
146 varying mediump vec2 vTexCoord;\n
147 varying mediump vec3 vIllumination;\n
148 varying mediump float vSpecular;\n
149 uniform mediump vec3 uSize;\n
150 uniform mediump mat4 uMvpMatrix;\n
151 uniform mediump mat4 uModelView;
152 uniform mediump mat3 uNormalMatrix;
153 uniform mediump mat4 uObjectMatrix;\n
154 uniform mediump vec3 uLightPosition;\n
158 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
159 vertexPosition = uObjectMatrix * vertexPosition;\n
160 vertexPosition = uMvpMatrix * vertexPosition;\n
162 //Illumination in Model-View space - Transform attributes and uniforms\n
163 vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
164 vec4 centre = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
165 vec4 lightPos = vec4( centre.x, centre.y, uLightPosition.z, 1.0 );\n
166 vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );\n
168 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
169 vec3 viewDir = normalize( -vertPos.xyz );
171 vec3 halfVector = normalize( viewDir + vecToLight );
173 float lightDiffuse = dot( vecToLight, normal );\n
174 lightDiffuse = max( 0.0,lightDiffuse );\n
175 vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
177 vec3 reflectDir = reflect( -vecToLight, normal );
178 vSpecular = pow( max( dot( reflectDir, viewDir ), 0.0 ), 4.0 );
180 vTexCoord = aTexCoord;\n
181 gl_Position = vertexPosition;\n
185 //Fragment shader corresponding to the diffuse and specular illumination shader with albedo texture
186 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
187 precision mediump float;\n
188 varying mediump vec2 vTexCoord;\n
189 varying mediump vec3 vIllumination;\n
190 varying mediump float vSpecular;\n
191 uniform sampler2D sDiffuse;\n
192 uniform lowp vec4 uColor;\n
196 vec4 texture = texture2D( sDiffuse, vTexCoord );\n
197 gl_FragColor = vec4( vIllumination.rgb * texture.rgb * uColor.rgb + vSpecular * 0.3, texture.a * uColor.a );\n
201 //Diffuse and specular illumination shader with albedo texture, normal map and gloss map shader.
202 //Diffuse (albedo) texture is index 0, normal is 1, gloss is 2. They must be declared in this order.
203 const char* NORMAL_MAP_VERTEX_SHADER = DALI_COMPOSE_SHADER(
204 attribute highp vec3 aPosition;\n
205 attribute highp vec2 aTexCoord;\n
206 attribute highp vec3 aNormal;\n
207 attribute highp vec3 aTangent;\n
208 attribute highp vec3 aBiNormal;\n
209 varying mediump vec2 vTexCoord;\n
210 varying mediump vec3 vLightDirection;\n
211 varying mediump vec3 vHalfVector;\n
212 uniform mediump vec3 uSize;\n
213 uniform mediump mat4 uMvpMatrix;\n
214 uniform mediump mat4 uModelView;
215 uniform mediump mat3 uNormalMatrix;
216 uniform mediump mat4 uObjectMatrix;\n
217 uniform mediump vec3 uLightPosition;\n
221 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
222 vertexPosition = uObjectMatrix * vertexPosition;\n
223 vertexPosition = uMvpMatrix * vertexPosition;\n
225 vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
226 vec4 centre = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
227 vec4 lightPos = vec4( centre.x, centre.y, uLightPosition.z, 1.0 );\n
229 vec3 tangent = normalize( uNormalMatrix * aTangent );
230 vec3 binormal = normalize( uNormalMatrix * aBiNormal );
231 vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );
233 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
234 vLightDirection.x = dot( vecToLight, tangent );
235 vLightDirection.y = dot( vecToLight, binormal );
236 vLightDirection.z = dot( vecToLight, normal );
238 vec3 viewDir = normalize( -vertPos.xyz );
239 vec3 halfVector = normalize( viewDir + vecToLight );
240 vHalfVector.x = dot( halfVector, tangent );
241 vHalfVector.y = dot( halfVector, binormal );
242 vHalfVector.z = dot( halfVector, normal );
244 vTexCoord = aTexCoord;\n
245 gl_Position = vertexPosition;\n
249 //Fragment shader corresponding to the shader that uses all textures (diffuse, normal and gloss maps)
250 const char* NORMAL_MAP_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
251 precision mediump float;\n
252 varying mediump vec2 vTexCoord;\n
253 varying mediump vec3 vLightDirection;\n
254 varying mediump vec3 vHalfVector;\n
255 uniform sampler2D sDiffuse;\n
256 uniform sampler2D sNormal;\n
257 uniform sampler2D sGloss;\n
258 uniform lowp vec4 uColor;\n
262 vec4 texture = texture2D( sDiffuse, vTexCoord );\n
263 vec3 normal = normalize( texture2D( sNormal, vTexCoord ).xyz * 2.0 - 1.0 );\n
264 vec4 glossMap = texture2D( sGloss, vTexCoord );\n
266 float lightDiffuse = max( 0.0, dot( normal, normalize( vLightDirection ) ) );\n
267 lightDiffuse = lightDiffuse * 0.5 + 0.5;\n
269 float shininess = pow ( max ( dot ( normalize( vHalfVector ), normal ), 0.0 ), 16.0 ) ;
271 gl_FragColor = vec4( texture.rgb * uColor.rgb * lightDiffuse + shininess * glossMap.rgb, texture.a * uColor.a );\n
277 MeshRenderer::MeshRenderer( RendererFactoryCache& factoryCache )
278 : ControlRenderer( factoryCache ),
279 mShaderType( ALL_TEXTURES ),
281 mUseMipmapping( true )
285 MeshRenderer::~MeshRenderer()
289 void MeshRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
291 Property::Value* objectUrl = propertyMap.Find( OBJECT_URL );
292 if( !objectUrl || !objectUrl->Get( mObjectUrl ) )
294 DALI_LOG_ERROR( "Fail to provide object URL to the MeshRenderer object.\n" );
297 Property::Value* materialUrl = propertyMap.Find( MATERIAL_URL );
299 if( !materialUrl || !materialUrl->Get( mMaterialUrl ) || mMaterialUrl.empty() )
304 Property::Value* imagesUrl = propertyMap.Find( TEXTURES_PATH );
305 if( !imagesUrl || !imagesUrl->Get( mTexturesPath ) )
307 //Default behaviour is to assume files are in the same directory,
308 // or have their locations detailed in full when supplied.
309 mTexturesPath.clear();
312 Property::Value* useMipmapping = propertyMap.Find( USE_MIPMAPPING );
315 useMipmapping->Get( mUseMipmapping );
318 Property::Value* shaderType = propertyMap.Find( SHADER_TYPE );
321 std::string shaderTypeString;
322 if( shaderType->Get( shaderTypeString ) )
324 if( shaderTypeString == SHADER_TYPE_TEXTURELESS )
326 mShaderType = TEXTURELESS;
328 else if( shaderTypeString == SHADER_TYPE_DIFFUSE_TEXTURE )
330 mShaderType = DIFFUSE_TEXTURE;
332 else if( shaderTypeString == SHADER_TYPE_ALL_TEXTURES )
334 mShaderType = ALL_TEXTURES;
338 DALI_LOG_ERROR( "Unknown shader type provided to the MeshRenderer object.\n");
344 void MeshRenderer::SetSize( const Vector2& size )
346 ControlRenderer::SetSize( size );
348 // ToDo: renderer responds to the size change
351 void MeshRenderer::SetClipRect( const Rect<int>& clipRect )
353 ControlRenderer::SetClipRect( clipRect );
355 //ToDo: renderer responds to the clipRect change
358 void MeshRenderer::SetOffset( const Vector2& offset )
360 //ToDo: renderer applies the offset
363 void MeshRenderer::DoSetOnStage( Actor& actor )
365 InitializeRenderer();
368 void MeshRenderer::DoCreatePropertyMap( Property::Map& map ) const
371 map.Insert( RENDERER_TYPE, MESH_RENDERER );
372 map.Insert( OBJECT_URL, mObjectUrl );
373 map.Insert( MATERIAL_URL, mMaterialUrl );
374 map.Insert( TEXTURES_PATH, mTexturesPath );
376 std::string shaderTypeString;
377 switch( mShaderType )
381 shaderTypeString = SHADER_TYPE_ALL_TEXTURES;
385 case DIFFUSE_TEXTURE:
387 shaderTypeString = SHADER_TYPE_DIFFUSE_TEXTURE;
393 shaderTypeString = SHADER_TYPE_TEXTURELESS;
397 map.Insert( SHADER_TYPE, shaderTypeString );
400 void MeshRenderer::InitializeRenderer()
402 //Try to load the geometry from the file.
403 if( !LoadGeometry() )
405 SupplyEmptyGeometry();
409 //If a texture is used by the obj file, load the supplied material file.
410 if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
412 if( !LoadMaterial() )
414 SupplyEmptyGeometry();
419 //Now that the required parts are loaded, create the geometry for the object.
420 if( !CreateGeometry() )
422 SupplyEmptyGeometry();
428 //Load the various texture files supplied by the material file.
429 if( !LoadTextures() )
431 SupplyEmptyGeometry();
435 mImpl->mRenderer = Renderer::New( mGeometry, mShader );
436 mImpl->mRenderer.SetTextures( mTextureSet );
437 mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
440 void MeshRenderer::SupplyEmptyGeometry()
442 mGeometry = Geometry::New();
443 mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
444 mImpl->mRenderer = Renderer::New( mGeometry, mShader );
446 DALI_LOG_ERROR( "Initialisation error in mesh renderer.\n" );
449 void MeshRenderer::UpdateShaderUniforms()
451 Stage stage = Stage::GetCurrent();
453 Vector3 lightPosition( 0, 0, stage.GetSize().width );
454 mShader.RegisterProperty( LIGHT_POSITION, lightPosition );
457 scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
458 mShader.RegisterProperty( OBJECT_MATRIX, scaleMatrix );
461 void MeshRenderer::CreateShader()
463 if( mShaderType == ALL_TEXTURES )
465 mShader = Shader::New( NORMAL_MAP_VERTEX_SHADER, NORMAL_MAP_FRAGMENT_SHADER );
467 else if( mShaderType == DIFFUSE_TEXTURE )
469 mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
473 mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
476 UpdateShaderUniforms();
479 bool MeshRenderer::CreateGeometry()
481 //Determine if we need to use a simpler shader to handle the provided data
482 if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
484 mShaderType = TEXTURELESS;
486 else if( mShaderType == ALL_TEXTURES && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
488 mShaderType = DIFFUSE_TEXTURE;
491 int objectProperties = 0;
493 if( mShaderType == DIFFUSE_TEXTURE ||
494 mShaderType == ALL_TEXTURES )
496 objectProperties |= ObjLoader::TEXTURE_COORDINATES;
499 if( mShaderType == ALL_TEXTURES )
501 objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
504 //Create geometry with attributes required by shader.
505 mGeometry = mObjLoader.CreateGeometry( objectProperties );
512 DALI_LOG_ERROR( "Failed to load geometry in mesh renderer.\n" );
516 bool MeshRenderer::LoadGeometry()
518 std::streampos fileSize;
519 Dali::Vector<char> fileContent;
521 if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
523 mObjLoader.ClearArrays();
524 mObjLoader.LoadObject( fileContent.Begin(), fileSize );
526 //Get size information from the obj loaded
527 mSceneCenter = mObjLoader.GetCenter();
528 mSceneSize = mObjLoader.GetSize();
533 DALI_LOG_ERROR( "Failed to find object to load in mesh renderer.\n" );
537 bool MeshRenderer::LoadMaterial()
539 std::streampos fileSize;
540 Dali::Vector<char> fileContent;
542 if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
544 //Load data into obj (usable) form
545 mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
549 DALI_LOG_ERROR( "Failed to find texture set to load in mesh renderer.\n" );
554 bool MeshRenderer::LoadTextures()
556 mTextureSet = TextureSet::New();
558 if( mShaderType != TEXTURELESS )
560 Sampler sampler = Sampler::New();
563 sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
566 if( !mDiffuseTextureUrl.empty() )
568 std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
571 Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
574 mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
575 mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
579 DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh renderer.\n");
584 if( !mNormalTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
586 std::string imageUrl = mTexturesPath + mNormalTextureUrl;
589 Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
592 mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
593 mTextureSet.SetSampler( NORMAL_INDEX, sampler );
597 DALI_LOG_ERROR( "Failed to load normal map texture in mesh renderer.\n");
602 if( !mGlossTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
604 std::string imageUrl = mTexturesPath + mGlossTextureUrl;
607 Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
610 mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
611 mTextureSet.SetSampler( GLOSS_INDEX, sampler );
615 DALI_LOG_ERROR( "Failed to load gloss map texture in mesh renderer.\n");
623 } // namespace Internal
625 } // namespace Toolkit