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/control-renderer-data-impl.h>
39 * @brief Loads a texture from a file
40 * @param[in] imageUrl The url of the file
41 * @param[in] generateMipmaps Indicates whether to generate mipmaps for the texture
42 * @return A texture if loading succeeds, an empty handle otherwise
44 Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
47 Dali::BitmapLoader loader = Dali::BitmapLoader::New( imageUrl );
49 PixelData pixelData = loader.GetPixelData();
52 texture = Texture::New( TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight() );
53 texture.Upload( pixelData );
57 texture.GenerateMipmaps();
74 //Defines ordering of textures for shaders.
75 //All shaders, if including certain texture types, must include them in the same order.
76 //Within the texture set for the renderer, textures are ordered in the same manner.
84 const char * const LIGHT_POSITION( "uLightPosition" ); //Shader property
85 const char * const OBJECT_MATRIX( "uObjectMatrix" ); //Shader property
87 const char * const SHADER_TYPE_TEXTURELESS( "TEXTURELESS" );
88 const char * const SHADER_TYPE_DIFFUSE_TEXTURE( "DIFFUSE_TEXTURE" );
89 const char * const SHADER_TYPE_ALL_TEXTURES( "ALL_TEXTURES" );
92 //If a shader requires certain textures, they must be listed in order,
93 //as detailed in the TextureIndex enum documentation.
95 //A basic shader that doesn't use textures at all.
96 const char* SIMPLE_VERTEX_SHADER = DALI_COMPOSE_SHADER(
97 attribute highp vec3 aPosition;\n
98 attribute highp vec3 aNormal;\n
99 varying mediump vec3 vIllumination;\n
100 uniform mediump vec3 uSize;\n
101 uniform mediump mat4 uMvpMatrix;\n
102 uniform mediump mat4 uModelView;\n
103 uniform mediump mat3 uNormalMatrix;
104 uniform mediump mat4 uObjectMatrix;\n
105 uniform mediump vec3 uLightPosition;\n
109 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
110 vertexPosition = uObjectMatrix * vertexPosition;\n
111 vertexPosition = uMvpMatrix * vertexPosition;\n
113 //Illumination in Model-View space - Transform attributes and uniforms\n
114 vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
115 vec3 normal = uNormalMatrix * mat3( uObjectMatrix ) * aNormal;\n
116 vec4 center = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
117 vec4 lightPos = vec4( center.x, center.y, uLightPosition.z, 1.0 );\n
118 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
120 float lightDiffuse = max( dot( vecToLight, normal ), 0.0 );\n
121 vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
123 gl_Position = vertexPosition;\n
127 //Fragment shader corresponding to the texture-less shader.
128 const char* SIMPLE_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
129 precision mediump float;\n
130 varying mediump vec3 vIllumination;\n
131 uniform lowp vec4 uColor;\n
135 gl_FragColor = vec4( vIllumination.rgb * uColor.rgb, uColor.a );\n
139 //Diffuse and specular illumination shader with albedo texture. Texture is index 0.
140 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
141 attribute highp vec3 aPosition;\n
142 attribute highp vec2 aTexCoord;\n
143 attribute highp vec3 aNormal;\n
144 varying mediump vec2 vTexCoord;\n
145 varying mediump vec3 vIllumination;\n
146 varying mediump float vSpecular;\n
147 uniform mediump vec3 uSize;\n
148 uniform mediump mat4 uMvpMatrix;\n
149 uniform mediump mat4 uModelView;
150 uniform mediump mat3 uNormalMatrix;
151 uniform mediump mat4 uObjectMatrix;\n
152 uniform mediump vec3 uLightPosition;\n
156 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
157 vertexPosition = uObjectMatrix * vertexPosition;\n
158 vertexPosition = uMvpMatrix * vertexPosition;\n
160 //Illumination in Model-View space - Transform attributes and uniforms\n
161 vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
162 vec4 center = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
163 vec4 lightPos = vec4( center.x, center.y, uLightPosition.z, 1.0 );\n
164 vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );\n
166 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
167 vec3 viewDir = normalize( -vertPos.xyz );
169 vec3 halfVector = normalize( viewDir + vecToLight );
171 float lightDiffuse = dot( vecToLight, normal );\n
172 lightDiffuse = max( 0.0,lightDiffuse );\n
173 vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
175 vec3 reflectDir = reflect( -vecToLight, normal );
176 vSpecular = pow( max( dot( reflectDir, viewDir ), 0.0 ), 4.0 );
178 vTexCoord = aTexCoord;\n
179 gl_Position = vertexPosition;\n
183 //Fragment shader corresponding to the diffuse and specular illumination shader with albedo texture
184 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
185 precision mediump float;\n
186 varying mediump vec2 vTexCoord;\n
187 varying mediump vec3 vIllumination;\n
188 varying mediump float vSpecular;\n
189 uniform sampler2D sDiffuse;\n
190 uniform lowp vec4 uColor;\n
194 vec4 texture = texture2D( sDiffuse, vTexCoord );\n
195 gl_FragColor = vec4( vIllumination.rgb * texture.rgb * uColor.rgb + vSpecular * 0.3, texture.a * uColor.a );\n
199 //Diffuse and specular illumination shader with albedo texture, normal map and gloss map shader.
200 //Diffuse (albedo) texture is index 0, normal is 1, gloss is 2. They must be declared in this order.
201 const char* NORMAL_MAP_VERTEX_SHADER = DALI_COMPOSE_SHADER(
202 attribute highp vec3 aPosition;\n
203 attribute highp vec2 aTexCoord;\n
204 attribute highp vec3 aNormal;\n
205 attribute highp vec3 aTangent;\n
206 attribute highp vec3 aBiNormal;\n
207 varying mediump vec2 vTexCoord;\n
208 varying mediump vec3 vLightDirection;\n
209 varying mediump vec3 vHalfVector;\n
210 uniform mediump vec3 uSize;\n
211 uniform mediump mat4 uMvpMatrix;\n
212 uniform mediump mat4 uModelView;
213 uniform mediump mat3 uNormalMatrix;
214 uniform mediump mat4 uObjectMatrix;\n
215 uniform mediump vec3 uLightPosition;\n
219 vec4 vertexPosition = vec4( aPosition * min( uSize.x, uSize.y ), 1.0 );\n
220 vertexPosition = uObjectMatrix * vertexPosition;\n
221 vertexPosition = uMvpMatrix * vertexPosition;\n
223 vec4 vertPos = uModelView * vec4( aPosition.xyz, 1.0 );\n
224 vec4 center = uModelView * vec4( 0.0, 0.0, 0.0, 1.0 );\n
225 vec4 lightPos = vec4( center.x, center.y, uLightPosition.z, 1.0 );\n
227 vec3 tangent = normalize( uNormalMatrix * aTangent );
228 vec3 binormal = normalize( uNormalMatrix * aBiNormal );
229 vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );
231 vec3 vecToLight = normalize( lightPos.xyz - vertPos.xyz );\n
232 vLightDirection.x = dot( vecToLight, tangent );
233 vLightDirection.y = dot( vecToLight, binormal );
234 vLightDirection.z = dot( vecToLight, normal );
236 vec3 viewDir = normalize( -vertPos.xyz );
237 vec3 halfVector = normalize( viewDir + vecToLight );
238 vHalfVector.x = dot( halfVector, tangent );
239 vHalfVector.y = dot( halfVector, binormal );
240 vHalfVector.z = dot( halfVector, normal );
242 vTexCoord = aTexCoord;\n
243 gl_Position = vertexPosition;\n
247 //Fragment shader corresponding to the shader that uses all textures (diffuse, normal and gloss maps)
248 const char* NORMAL_MAP_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
249 precision mediump float;\n
250 varying mediump vec2 vTexCoord;\n
251 varying mediump vec3 vLightDirection;\n
252 varying mediump vec3 vHalfVector;\n
253 uniform sampler2D sDiffuse;\n
254 uniform sampler2D sNormal;\n
255 uniform sampler2D sGloss;\n
256 uniform lowp vec4 uColor;\n
260 vec4 texture = texture2D( sDiffuse, vTexCoord );\n
261 vec3 normal = normalize( texture2D( sNormal, vTexCoord ).xyz * 2.0 - 1.0 );\n
262 vec4 glossMap = texture2D( sGloss, vTexCoord );\n
264 float lightDiffuse = max( 0.0, dot( normal, normalize( vLightDirection ) ) );\n
265 lightDiffuse = lightDiffuse * 0.5 + 0.5;\n
267 float shininess = pow ( max ( dot ( normalize( vHalfVector ), normal ), 0.0 ), 16.0 ) ;
269 gl_FragColor = vec4( texture.rgb * uColor.rgb * lightDiffuse + shininess * glossMap.rgb, texture.a * uColor.a );\n
275 MeshRenderer::MeshRenderer( RendererFactoryCache& factoryCache )
276 : ControlRenderer( factoryCache ),
277 mShaderType( ALL_TEXTURES ),
279 mUseMipmapping( true )
283 MeshRenderer::~MeshRenderer()
287 void MeshRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
289 Property::Value* objectUrl = propertyMap.Find( OBJECT_URL );
290 if( !objectUrl || !objectUrl->Get( mObjectUrl ) )
292 DALI_LOG_ERROR( "Fail to provide object URL to the MeshRenderer object.\n" );
295 Property::Value* materialUrl = propertyMap.Find( MATERIAL_URL );
297 if( !materialUrl || !materialUrl->Get( mMaterialUrl ) || mMaterialUrl.empty() )
302 Property::Value* imagesUrl = propertyMap.Find( TEXTURES_PATH );
303 if( !imagesUrl || !imagesUrl->Get( mTexturesPath ) )
305 //Default behaviour is to assume files are in the same directory,
306 // or have their locations detailed in full when supplied.
307 mTexturesPath.clear();
310 Property::Value* useMipmapping = propertyMap.Find( USE_MIPMAPPING );
313 useMipmapping->Get( mUseMipmapping );
316 Property::Value* shaderType = propertyMap.Find( SHADER_TYPE );
319 std::string shaderTypeString;
320 if( shaderType->Get( shaderTypeString ) )
322 if( shaderTypeString == SHADER_TYPE_TEXTURELESS )
324 mShaderType = TEXTURELESS;
326 else if( shaderTypeString == SHADER_TYPE_DIFFUSE_TEXTURE )
328 mShaderType = DIFFUSE_TEXTURE;
330 else if( shaderTypeString == SHADER_TYPE_ALL_TEXTURES )
332 mShaderType = ALL_TEXTURES;
336 DALI_LOG_ERROR( "Unknown shader type provided to the MeshRenderer object.\n");
342 void MeshRenderer::SetSize( const Vector2& size )
344 ControlRenderer::SetSize( size );
346 // ToDo: renderer responds to the size change
349 void MeshRenderer::SetClipRect( const Rect<int>& clipRect )
351 ControlRenderer::SetClipRect( clipRect );
353 //ToDo: renderer responds to the clipRect change
356 void MeshRenderer::SetOffset( const Vector2& offset )
358 //ToDo: renderer applies the offset
361 void MeshRenderer::DoSetOnStage( Actor& actor )
363 InitializeRenderer();
366 void MeshRenderer::DoCreatePropertyMap( Property::Map& map ) const
369 map.Insert( RENDERER_TYPE, MESH_RENDERER );
370 map.Insert( OBJECT_URL, mObjectUrl );
371 map.Insert( MATERIAL_URL, mMaterialUrl );
372 map.Insert( TEXTURES_PATH, mTexturesPath );
374 std::string shaderTypeString;
375 switch( mShaderType )
379 shaderTypeString = SHADER_TYPE_ALL_TEXTURES;
383 case DIFFUSE_TEXTURE:
385 shaderTypeString = SHADER_TYPE_DIFFUSE_TEXTURE;
391 shaderTypeString = SHADER_TYPE_TEXTURELESS;
395 map.Insert( SHADER_TYPE, shaderTypeString );
398 void MeshRenderer::InitializeRenderer()
400 //Try to load the geometry from the file.
401 if( !LoadGeometry() )
403 SupplyEmptyGeometry();
407 //If a texture is used by the obj file, load the supplied material file.
408 if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
410 if( !LoadMaterial() )
412 SupplyEmptyGeometry();
417 //Now that the required parts are loaded, create the geometry for the object.
418 if( !CreateGeometry() )
420 SupplyEmptyGeometry();
426 //Load the various texture files supplied by the material file.
427 if( !LoadTextures() )
429 SupplyEmptyGeometry();
433 mImpl->mRenderer = Renderer::New( mGeometry, mShader );
434 mImpl->mRenderer.SetTextures( mTextureSet );
435 mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
438 void MeshRenderer::SupplyEmptyGeometry()
440 mGeometry = Geometry::New();
441 mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
442 mImpl->mRenderer = Renderer::New( mGeometry, mShader );
444 DALI_LOG_ERROR( "Initialisation error in mesh renderer.\n" );
447 void MeshRenderer::UpdateShaderUniforms()
449 Stage stage = Stage::GetCurrent();
451 Vector3 lightPosition( 0, 0, stage.GetSize().width );
452 mShader.RegisterProperty( LIGHT_POSITION, lightPosition );
455 scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
456 mShader.RegisterProperty( OBJECT_MATRIX, scaleMatrix );
459 void MeshRenderer::CreateShader()
461 if( mShaderType == ALL_TEXTURES )
463 mShader = Shader::New( NORMAL_MAP_VERTEX_SHADER, NORMAL_MAP_FRAGMENT_SHADER );
465 else if( mShaderType == DIFFUSE_TEXTURE )
467 mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
471 mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
474 UpdateShaderUniforms();
477 bool MeshRenderer::CreateGeometry()
479 //Determine if we need to use a simpler shader to handle the provided data
480 if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
482 mShaderType = TEXTURELESS;
484 else if( mShaderType == ALL_TEXTURES && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
486 mShaderType = DIFFUSE_TEXTURE;
489 int objectProperties = 0;
491 if( mShaderType == DIFFUSE_TEXTURE ||
492 mShaderType == ALL_TEXTURES )
494 objectProperties |= ObjLoader::TEXTURE_COORDINATES;
497 if( mShaderType == ALL_TEXTURES )
499 objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
502 //Create geometry with attributes required by shader.
503 mGeometry = mObjLoader.CreateGeometry( objectProperties );
510 DALI_LOG_ERROR( "Failed to load geometry in mesh renderer.\n" );
514 bool MeshRenderer::LoadGeometry()
516 std::streampos fileSize;
517 Dali::Vector<char> fileContent;
519 if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
521 mObjLoader.ClearArrays();
522 mObjLoader.LoadObject( fileContent.Begin(), fileSize );
524 //Get size information from the obj loaded
525 mSceneCenter = mObjLoader.GetCenter();
526 mSceneSize = mObjLoader.GetSize();
531 DALI_LOG_ERROR( "Failed to find object to load in mesh renderer.\n" );
535 bool MeshRenderer::LoadMaterial()
537 std::streampos fileSize;
538 Dali::Vector<char> fileContent;
540 if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
542 //Load data into obj (usable) form
543 mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
547 DALI_LOG_ERROR( "Failed to find texture set to load in mesh renderer.\n" );
552 bool MeshRenderer::LoadTextures()
554 mTextureSet = TextureSet::New();
556 if( mShaderType != TEXTURELESS )
558 Sampler sampler = Sampler::New();
561 sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
564 if( !mDiffuseTextureUrl.empty() )
566 std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
569 Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
572 mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
573 mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
577 DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh renderer.\n");
582 if( !mNormalTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
584 std::string imageUrl = mTexturesPath + mNormalTextureUrl;
587 Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
590 mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
591 mTextureSet.SetSampler( NORMAL_INDEX, sampler );
595 DALI_LOG_ERROR( "Failed to load normal map texture in mesh renderer.\n");
600 if( !mGlossTextureUrl.empty() && ( mShaderType == ALL_TEXTURES ) )
602 std::string imageUrl = mTexturesPath + mGlossTextureUrl;
605 Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
608 mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
609 mTextureSet.SetSampler( GLOSS_INDEX, sampler );
613 DALI_LOG_ERROR( "Failed to load gloss map texture in mesh renderer.\n");
621 } // namespace Internal
623 } // namespace Toolkit