All file read operations should be done through FileLoader.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / mesh / mesh-visual.cpp
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include "mesh-visual.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/common/stage.h>
24 #include <dali/devel-api/adaptor-framework/image-loading.h>
25 #include <dali/devel-api/adaptor-framework/file-loader.h>
26 #include <dali/devel-api/scripting/enum-helper.h>
27 #include <dali/devel-api/scripting/scripting.h>
28
29 //INTERNAL INCLUDES
30 #include <dali-toolkit/public-api/visuals/visual-properties.h>
31 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
32 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
33
34 namespace Dali
35 {
36
37 namespace
38 {
39   /**
40    * @brief Loads a texture from a file
41    * @param[in] imageUrl The url of the file
42    * @param[in] generateMipmaps Indicates whether to generate mipmaps for the texture
43    * @return A texture if loading succeeds, an empty handle otherwise
44    */
45   Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
46   {
47     Texture texture;
48
49     Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl );
50     if( pixelBuffer )
51     {
52       texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
53       PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
54       texture.Upload( pixelData );
55
56       if( generateMipmaps )
57       {
58         texture.GenerateMipmaps();
59       }
60     }
61
62     return texture;
63   }
64 }// unnamed namespace
65
66 namespace Toolkit
67 {
68
69 namespace Internal
70 {
71
72 namespace
73 {
74
75 //Defines ordering of textures for shaders.
76 //All shaders, if including certain texture types, must include them in the same order.
77 //Within the texture set for the renderer, textures are ordered in the same manner.
78 enum TextureIndex
79 {
80   DIFFUSE_INDEX = 0u,
81   NORMAL_INDEX = 1u,
82   GLOSS_INDEX = 2u
83 };
84
85 //Property names
86 const char * const OBJECT_URL_NAME( "objectUrl" );
87 const char * const MATERIAL_URL_NAME( "materialUrl" );
88 const char * const TEXTURES_PATH_NAME( "texturesPath" );
89 const char * const SHADING_MODE_NAME( "shadingMode" );
90 const char * const USE_MIPMAPPING_NAME( "useMipmapping" );
91 const char * const USE_SOFT_NORMALS_NAME( "useSoftNormals" );
92 const char * const LIGHT_POSITION_NAME( "lightPosition" );
93
94 //Shading mode
95 DALI_ENUM_TO_STRING_TABLE_BEGIN( SHADING_MODE )
96 DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURELESS_WITH_DIFFUSE_LIGHTING )
97 DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_SPECULAR_LIGHTING )
98 DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
99 DALI_ENUM_TO_STRING_TABLE_END( SHADING_MODE )
100
101 //Shader properties
102 const char * const OBJECT_MATRIX_UNIFORM_NAME( "uObjectMatrix" );
103 const char * const STAGE_OFFSET_UNIFORM_NAME( "uStageOffset" );
104
105 //Shaders
106 //If a shader requires certain textures, they must be listed in order,
107 //as detailed in the TextureIndex enum documentation.
108
109 //A basic shader that doesn't use textures at all.
110 const char* SIMPLE_VERTEX_SHADER = DALI_COMPOSE_SHADER(
111   attribute highp vec3 aPosition;\n
112   attribute highp vec3 aNormal;\n
113   varying mediump vec3 vIllumination;\n
114   uniform mediump vec3 uSize;\n
115   uniform mediump mat4 uMvpMatrix;\n
116   uniform mediump mat4 uModelView;\n
117   uniform mediump mat4 uViewMatrix;\n
118   uniform mediump mat3 uNormalMatrix;
119   uniform mediump mat4 uObjectMatrix;\n
120   uniform mediump vec3 lightPosition;\n
121   uniform mediump vec2 uStageOffset;\n
122
123   //Visual size and offset
124   uniform mediump vec2 offset;\n
125   uniform mediump vec2 size;\n
126   uniform mediump vec4 offsetSizeMode;\n
127   uniform mediump vec2 origin;\n
128   uniform mediump vec2 anchorPoint;\n
129
130   vec4 ComputeVertexPosition()\n
131   {\n
132     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
133     float scaleFactor = min( visualSize.x, visualSize.y );\n
134     vec3 originFlipY =  vec3(origin.x, -origin.y, 0.0);
135     vec3 anchorPointFlipY = vec3( anchorPoint.x, -anchorPoint.y, 0.0);
136     vec3 offset = vec3( ( offset / uSize.xy ) * offsetSizeMode.xy + offset * (1.0-offsetSizeMode.xy), 0.0) * vec3(1.0,-1.0,1.0);\n
137     return vec4( (aPosition + anchorPointFlipY)*scaleFactor + (offset + originFlipY)*uSize, 1.0 );\n
138   }\n
139
140   void main()\n
141   {\n
142     vec4 normalisedVertexPosition = ComputeVertexPosition();\n
143     vec4 vertexPosition = uObjectMatrix * normalisedVertexPosition;\n
144     vertexPosition = uMvpMatrix * vertexPosition;\n
145
146     //Illumination in Model-View space - Transform attributes and uniforms\n
147     vec4 mvVertexPosition = uModelView * normalisedVertexPosition;\n
148     vec3 normal = uNormalMatrix * mat3( uObjectMatrix ) * aNormal;\n
149
150     vec4 mvLightPosition = vec4( ( lightPosition.xy - uStageOffset ), lightPosition.z, 1.0 );\n
151     mvLightPosition = uViewMatrix * mvLightPosition;\n
152     vec3 vectorToLight = normalize( mvLightPosition.xyz - mvVertexPosition.xyz );\n
153
154     float lightDiffuse = max( dot( vectorToLight, normal ), 0.0 );\n
155     vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
156
157     gl_Position = vertexPosition;\n
158   }\n
159 );
160
161 //Fragment shader corresponding to the texture-less shader.
162 const char* SIMPLE_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
163   precision mediump float;\n
164   varying mediump vec3 vIllumination;\n
165   uniform lowp vec4 uColor;\n
166   uniform lowp vec3 mixColor;\n
167   uniform lowp float preMultipliedAlpha;\n
168
169   void main()\n
170   {\n
171     gl_FragColor = vec4( vIllumination.rgb * uColor.rgb, uColor.a ) * vec4( mixColor, 1.0 );\n
172   }\n
173 );
174
175 //Diffuse and specular illumination shader with albedo texture. Texture is index 0.
176 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
177   attribute highp vec3 aPosition;\n
178   attribute highp vec2 aTexCoord;\n
179   attribute highp vec3 aNormal;\n
180   varying mediump vec2 vTexCoord;\n
181   varying mediump vec3 vIllumination;\n
182   varying mediump float vSpecular;\n
183   uniform mediump vec3 uSize;\n
184   uniform mediump mat4 uMvpMatrix;\n
185   uniform mediump mat4 uModelView;
186   uniform mediump mat4 uViewMatrix;\n
187   uniform mediump mat3 uNormalMatrix;
188   uniform mediump mat4 uObjectMatrix;\n
189   uniform mediump vec3 lightPosition;\n
190   uniform mediump vec2 uStageOffset;\n
191
192   //Visual size and offset
193   uniform mediump vec2 offset;\n
194   uniform mediump vec2 size;\n
195   uniform mediump vec4 offsetSizeMode;\n
196   uniform mediump vec2 origin;\n
197   uniform mediump vec2 anchorPoint;\n
198
199   vec4 ComputeVertexPosition()\n
200   {\n
201     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
202     float scaleFactor = min( visualSize.x, visualSize.y );\n
203     vec3 originFlipY =  vec3(origin.x, -origin.y, 0.0);
204     vec3 anchorPointFlipY = vec3( anchorPoint.x, -anchorPoint.y, 0.0);
205     vec3 offset = vec3( ( offset / uSize.xy ) * offsetSizeMode.xy + offset * (1.0-offsetSizeMode.xy), 0.0) * vec3(1.0,-1.0,1.0);\n
206     return vec4( (aPosition + anchorPointFlipY)*scaleFactor + (offset + originFlipY)*uSize, 1.0 );\n
207   }\n
208
209   void main()
210   {\n
211     vec4 normalisedVertexPosition = ComputeVertexPosition();\n
212     vec4 vertexPosition = uObjectMatrix * normalisedVertexPosition;\n
213     vertexPosition = uMvpMatrix * vertexPosition;\n
214
215     //Illumination in Model-View space - Transform attributes and uniforms\n
216     vec4 mvVertexPosition = uModelView * normalisedVertexPosition;\n
217     vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );\n
218
219     vec4 mvLightPosition = vec4( ( lightPosition.xy - uStageOffset ), lightPosition.z, 1.0 );\n
220     mvLightPosition = uViewMatrix * mvLightPosition;\n
221     vec3 vectorToLight = normalize( mvLightPosition.xyz - mvVertexPosition.xyz );\n
222
223     vec3 viewDirection = normalize( -mvVertexPosition.xyz );
224
225     float lightDiffuse = dot( vectorToLight, normal );\n
226     lightDiffuse = max( 0.0,lightDiffuse );\n
227     vIllumination = vec3( lightDiffuse * 0.5 + 0.5 );\n
228
229     vec3 reflectDirection = reflect( -vectorToLight, normal );
230     vSpecular = pow( max( dot( reflectDirection, viewDirection ), 0.0 ), 4.0 );
231
232     vTexCoord = aTexCoord;\n
233     gl_Position = vertexPosition;\n
234   }\n
235 );
236
237 //Fragment shader corresponding to the diffuse and specular illumination shader with albedo texture
238 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
239   precision mediump float;\n
240   varying mediump vec2 vTexCoord;\n
241   varying mediump vec3 vIllumination;\n
242   varying mediump float vSpecular;\n
243   uniform sampler2D sDiffuse;\n
244   uniform lowp vec4 uColor;\n
245   uniform lowp vec3 mixColor;\n
246   uniform lowp float preMultipliedAlpha;\n
247
248   void main()\n
249   {\n
250     vec4 texture = texture2D( sDiffuse, vTexCoord );\n
251     vec4 visualMixColor = vec4( mixColor, 1.0 );\n
252     gl_FragColor = vec4( vIllumination.rgb * texture.rgb * uColor.rgb * visualMixColor.rgb + vSpecular * 0.3, texture.a * uColor.a * visualMixColor.a );\n
253   }\n
254 );
255
256 //Diffuse and specular illumination shader with albedo texture, normal map and gloss map shader.
257 //Diffuse (albedo) texture is index 0, normal is 1, gloss is 2. They must be declared in this order.
258 const char* NORMAL_MAP_VERTEX_SHADER = DALI_COMPOSE_SHADER(
259   attribute highp vec3 aPosition;\n
260   attribute highp vec2 aTexCoord;\n
261   attribute highp vec3 aNormal;\n
262   attribute highp vec3 aTangent;\n
263   attribute highp vec3 aBiNormal;\n
264   varying mediump vec2 vTexCoord;\n
265   varying mediump vec3 vLightDirection;\n
266   varying mediump vec3 vHalfVector;\n
267   uniform mediump vec3 uSize;\n
268   uniform mediump mat4 uMvpMatrix;\n
269   uniform mediump mat4 uModelView;
270   uniform mediump mat4 uViewMatrix;\n
271   uniform mediump mat3 uNormalMatrix;
272   uniform mediump mat4 uObjectMatrix;\n
273   uniform mediump vec3 lightPosition;\n
274   uniform mediump vec2 uStageOffset;\n
275
276   //Visual size and offset
277   uniform mediump vec2 offset;\n
278   uniform mediump vec2 size;\n
279   uniform mediump vec4 offsetSizeMode;\n
280   uniform mediump vec2 origin;\n
281   uniform mediump vec2 anchorPoint;\n
282
283   vec4 ComputeVertexPosition()\n
284   {\n
285     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
286     float scaleFactor = min( visualSize.x, visualSize.y );\n
287     vec3 originFlipY =  vec3(origin.x, -origin.y, 0.0);
288     vec3 anchorPointFlipY = vec3( anchorPoint.x, -anchorPoint.y, 0.0);
289     vec3 offset = vec3( ( offset / uSize.xy ) * offsetSizeMode.xy + offset * (1.0-offsetSizeMode.xy), 0.0) * vec3(1.0,-1.0,1.0);\n
290     return vec4( (aPosition + anchorPointFlipY)*scaleFactor + (offset + originFlipY)*uSize, 1.0 );\n
291   }\n
292
293   void main()
294   {\n
295     vec4 normalisedVertexPosition = ComputeVertexPosition();\n
296     vec4 vertexPosition = uObjectMatrix * normalisedVertexPosition;\n
297     vertexPosition = uMvpMatrix * vertexPosition;\n
298
299     vec4 mvVertexPosition = uModelView * normalisedVertexPosition;\n
300
301     vec3 tangent = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aTangent );
302     vec3 binormal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aBiNormal );
303     vec3 normal = normalize( uNormalMatrix * mat3( uObjectMatrix ) * aNormal );
304
305     vec4 mvLightPosition = vec4( ( lightPosition.xy - uStageOffset ), lightPosition.z, 1.0 );\n
306     mvLightPosition = uViewMatrix * mvLightPosition;\n
307     vec3 vectorToLight = normalize( mvLightPosition.xyz - mvVertexPosition.xyz );\n
308     vLightDirection.x = dot( vectorToLight, tangent );
309     vLightDirection.y = dot( vectorToLight, binormal );
310     vLightDirection.z = dot( vectorToLight, normal );
311
312     vec3 viewDirection = normalize( -mvVertexPosition.xyz );
313     vec3 halfVector = normalize( viewDirection + vectorToLight );
314     vHalfVector.x = dot( halfVector, tangent );
315     vHalfVector.y = dot( halfVector, binormal );
316     vHalfVector.z = dot( halfVector, normal );
317
318     vTexCoord = aTexCoord;\n
319     gl_Position = vertexPosition;\n
320   }\n
321 );
322
323 //Fragment shader corresponding to the shader that uses all textures (diffuse, normal and gloss maps)
324 const char* NORMAL_MAP_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
325   precision mediump float;\n
326   varying mediump vec2 vTexCoord;\n
327   varying mediump vec3 vLightDirection;\n
328   varying mediump vec3 vHalfVector;\n
329   uniform sampler2D sDiffuse;\n
330   uniform sampler2D sNormal;\n
331   uniform sampler2D sGloss;\n
332   uniform lowp vec4 uColor;\n
333   uniform lowp vec3 mixColor;\n
334   uniform lowp float preMultipliedAlpha;\n
335
336   void main()\n
337   {\n
338     vec4 texture = texture2D( sDiffuse, vTexCoord );\n
339     vec3 normal = normalize( texture2D( sNormal, vTexCoord ).xyz * 2.0 - 1.0 );\n
340     vec4 glossMap = texture2D( sGloss, vTexCoord );\n
341     vec4 visualMixColor = vec4( mixColor, 1.0 );\n
342
343     float lightDiffuse = max( 0.0, dot( normal, normalize( vLightDirection ) ) );\n
344     lightDiffuse = lightDiffuse * 0.5 + 0.5;\n
345
346     float shininess = pow ( max ( dot ( normalize( vHalfVector ), normal ), 0.0 ), 16.0 )  ;
347
348     gl_FragColor = vec4( texture.rgb * uColor.rgb * visualMixColor.rgb * lightDiffuse + shininess * glossMap.rgb, texture.a * uColor.a * visualMixColor.a );\n
349   }\n
350 );
351
352 } // unnamed namespace
353
354 MeshVisualPtr MeshVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
355 {
356   MeshVisualPtr meshVisualPtr( new MeshVisual( factoryCache ) );
357   meshVisualPtr->SetProperties( properties );
358   return meshVisualPtr;
359 }
360
361 MeshVisual::MeshVisual( VisualFactoryCache& factoryCache )
362 : Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO ),
363   mShadingMode( Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ),
364   mUseTexture( true ),
365   mUseMipmapping( true ),
366   mUseSoftNormals( true )
367 {
368 }
369
370 MeshVisual::~MeshVisual()
371 {
372 }
373
374 void MeshVisual::DoSetProperties( const Property::Map& propertyMap )
375 {
376   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
377   {
378     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
379     if( keyValue.first.type == Property::Key::INDEX )
380     {
381       DoSetProperty( keyValue.first.indexKey, keyValue.second );
382     }
383     else
384     {
385       if( keyValue.first == OBJECT_URL_NAME )
386       {
387         DoSetProperty( Toolkit::MeshVisual::Property::OBJECT_URL, keyValue.second );
388       }
389       else if( keyValue.first == MATERIAL_URL_NAME )
390       {
391         DoSetProperty( Toolkit::MeshVisual::Property::MATERIAL_URL, keyValue.second );
392       }
393       else if( keyValue.first == TEXTURES_PATH_NAME )
394       {
395         DoSetProperty( Toolkit::MeshVisual::Property::TEXTURES_PATH, keyValue.second );
396       }
397       else if( keyValue.first == SHADING_MODE_NAME )
398       {
399         DoSetProperty( Toolkit::MeshVisual::Property::SHADING_MODE, keyValue.second );
400       }
401       else if( keyValue.first == USE_MIPMAPPING_NAME )
402       {
403         DoSetProperty( Toolkit::MeshVisual::Property::USE_MIPMAPPING, keyValue.second );
404       }
405       else if( keyValue.first == USE_SOFT_NORMALS_NAME )
406       {
407         DoSetProperty( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, keyValue.second );
408       }
409       else if( keyValue.first == LIGHT_POSITION_NAME )
410       {
411         DoSetProperty( Toolkit::MeshVisual::Property::LIGHT_POSITION, keyValue.second );
412       }
413     }
414   }
415
416   if( mMaterialUrl.empty() )
417   {
418     mUseTexture = false;
419   }
420
421   if( mLightPosition == Vector3::ZERO )
422   {
423     // Default behaviour is to place the light directly in front of the object,
424     // at a reasonable distance to light everything on screen.
425     Stage stage = Stage::GetCurrent();
426
427     mLightPosition = Vector3( stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5 );
428   }
429 }
430
431 void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& value )
432 {
433   switch( index )
434   {
435     case Toolkit::MeshVisual::Property::OBJECT_URL:
436     {
437       if( !value.Get( mObjectUrl ) )
438       {
439         DALI_LOG_ERROR("MeshVisual: property objectUrl is the wrong type, use STRING\n");
440       }
441       break;
442     }
443     case Toolkit::MeshVisual::Property::MATERIAL_URL:
444     {
445       if( ! value.Get( mMaterialUrl ) )
446       {
447         DALI_LOG_ERROR("MeshVisual: property materialUrl is the wrong type, use STRING\n");
448       }
449       break;
450     }
451     case Toolkit::MeshVisual::Property::TEXTURES_PATH:
452     {
453       if( ! value.Get( mTexturesPath ) )
454       {
455         mTexturesPath.clear();
456       }
457       break;
458     }
459     case Toolkit::MeshVisual::Property::SHADING_MODE:
460     {
461       Scripting::GetEnumerationProperty( value, SHADING_MODE_TABLE, SHADING_MODE_TABLE_COUNT, mShadingMode );
462       break;
463     }
464     case Toolkit::MeshVisual::Property::USE_MIPMAPPING:
465     {
466       if( !value.Get( mUseMipmapping ) )
467       {
468         DALI_LOG_ERROR("MeshVisual: property useMipmapping is the wrong type, use BOOLEAN\n");
469       }
470       break;
471     }
472     case Toolkit::MeshVisual::Property::USE_SOFT_NORMALS:
473     {
474       if( !value.Get( mUseSoftNormals ) )
475       {
476         DALI_LOG_ERROR("MeshVisual: property useSoftNormals is the wrong type, use BOOLEAN\n");
477       }
478       break;
479     }
480     case Toolkit::MeshVisual::Property::LIGHT_POSITION:
481     {
482       if( !value.Get( mLightPosition ) )
483       {
484         mLightPosition = Vector3::ZERO;
485         DALI_LOG_ERROR("MeshVisual: property lightPosition is the wrong type, use VECTOR3\n");
486       }
487       break;
488     }
489   }
490 }
491
492 void MeshVisual::OnSetTransform()
493 {
494   if( mImpl->mRenderer )
495   {
496     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
497   }
498 }
499
500 void MeshVisual::DoSetOnStage( Actor& actor )
501 {
502   InitializeRenderer();
503
504   actor.AddRenderer( mImpl->mRenderer );
505
506   // Mesh loaded and ready to display
507   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
508 }
509
510 void MeshVisual::DoCreatePropertyMap( Property::Map& map ) const
511 {
512   map.Clear();
513   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::MESH );
514   map.Insert( Toolkit::MeshVisual::Property::OBJECT_URL, mObjectUrl );
515   map.Insert( Toolkit::MeshVisual::Property::MATERIAL_URL, mMaterialUrl );
516   map.Insert( Toolkit::MeshVisual::Property::TEXTURES_PATH, mTexturesPath );
517   map.Insert( Toolkit::MeshVisual::Property::SHADING_MODE, mShadingMode );
518   map.Insert( Toolkit::MeshVisual::Property::USE_MIPMAPPING, mUseMipmapping );
519   map.Insert( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, mUseSoftNormals );
520   map.Insert( Toolkit::MeshVisual::Property::LIGHT_POSITION, mLightPosition );
521 }
522
523 void MeshVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
524 {
525   // Do nothing
526 }
527
528 void MeshVisual::InitializeRenderer()
529 {
530   //Try to load the geometry from the file.
531   if( !LoadGeometry() )
532   {
533     SupplyEmptyGeometry();
534     return;
535   }
536
537   //If a texture is used by the obj file, load the supplied material file.
538   if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
539   {
540     if( !LoadMaterial() )
541     {
542       SupplyEmptyGeometry();
543       return;
544     }
545   }
546
547   //Now that the required parts are loaded, create the geometry for the object.
548   if( !CreateGeometry() )
549   {
550     SupplyEmptyGeometry();
551     return;
552   }
553
554   CreateShader();
555
556   //Load the various texture files supplied by the material file.
557   if( !LoadTextures() )
558   {
559     SupplyEmptyGeometry();
560     return;
561   }
562
563   mImpl->mRenderer = Renderer::New( mGeometry, mShader );
564   mImpl->mRenderer.SetTextures( mTextureSet );
565   mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
566   mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
567
568   //Register transform properties
569   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
570 }
571
572 void MeshVisual::SupplyEmptyGeometry()
573 {
574   mGeometry = Geometry::New();
575   mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
576   mImpl->mRenderer = Renderer::New( mGeometry, mShader );
577
578   DALI_LOG_ERROR( "Initialisation error in mesh visual.\n" );
579 }
580
581 void MeshVisual::UpdateShaderUniforms()
582 {
583   Stage stage = Stage::GetCurrent();
584   float width = stage.GetSize().width;
585   float height = stage.GetSize().height;
586
587   Matrix scaleMatrix;
588   scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
589
590   mShader.RegisterProperty( STAGE_OFFSET_UNIFORM_NAME, Vector2( width, height ) / 2.0f );
591   mShader.RegisterProperty( LIGHT_POSITION_NAME, mLightPosition );
592   mShader.RegisterProperty( OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix );
593 }
594
595 void MeshVisual::CreateShader()
596 {
597   if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
598   {
599     mShader = Shader::New( NORMAL_MAP_VERTEX_SHADER, NORMAL_MAP_FRAGMENT_SHADER );
600   }
601   else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING )
602   {
603     mShader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
604   }
605   else //Textureless
606   {
607     mShader = Shader::New( SIMPLE_VERTEX_SHADER, SIMPLE_FRAGMENT_SHADER );
608   }
609
610   UpdateShaderUniforms();
611 }
612
613 bool MeshVisual::CreateGeometry()
614 {
615   //Determine if we need to use a simpler shader to handle the provided data
616   if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
617   {
618     mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING;
619   }
620   else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
621   {
622     mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING;
623   }
624
625   int objectProperties = 0;
626
627   if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING ||
628       mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
629   {
630     objectProperties |= ObjLoader::TEXTURE_COORDINATES;
631   }
632
633   if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
634   {
635     objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
636   }
637
638   //Create geometry with attributes required by shader.
639   mGeometry = mObjLoader.CreateGeometry( objectProperties, mUseSoftNormals );
640
641   if( mGeometry )
642   {
643     return true;
644   }
645
646   DALI_LOG_ERROR( "Failed to load geometry in mesh visual.\n" );
647   return false;
648 }
649
650 bool MeshVisual::LoadGeometry()
651 {
652   std::streampos fileSize;
653   Dali::Vector<char> fileContent;
654
655   if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
656   {
657     mObjLoader.ClearArrays();
658     mObjLoader.LoadObject( fileContent.Begin(), fileSize );
659
660     //Get size information from the obj loaded
661     mSceneCenter = mObjLoader.GetCenter();
662     mSceneSize = mObjLoader.GetSize();
663
664     return true;
665   }
666
667   DALI_LOG_ERROR( "Failed to find object to load in mesh visual.\n" );
668   return false;
669 }
670
671 bool MeshVisual::LoadMaterial()
672 {
673   std::streampos fileSize;
674   Dali::Vector<char> fileContent;
675
676   if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
677   {
678     //Load data into obj (usable) form
679     mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
680     return true;
681   }
682
683   DALI_LOG_ERROR( "Failed to find texture set to load in mesh visual.\n" );
684   mUseTexture = false;
685   return false;
686 }
687
688 bool MeshVisual::LoadTextures()
689 {
690   mTextureSet = TextureSet::New();
691
692   if( mShadingMode != Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING )
693   {
694     Sampler sampler = Sampler::New();
695     if( mUseMipmapping )
696     {
697       sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
698     }
699
700     if( !mDiffuseTextureUrl.empty() )
701     {
702       std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
703
704       //Load textures
705       Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
706       if( diffuseTexture )
707       {
708         mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
709         mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
710       }
711       else
712       {
713         DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh visual.\n");
714         return false;
715       }
716     }
717
718     if( !mNormalTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) )
719     {
720       std::string imageUrl = mTexturesPath + mNormalTextureUrl;
721
722       //Load textures
723       Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
724       if( normalTexture )
725       {
726         mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
727         mTextureSet.SetSampler( NORMAL_INDEX, sampler );
728       }
729       else
730       {
731         DALI_LOG_ERROR( "Failed to load normal map texture in mesh visual.\n");
732         return false;
733       }
734     }
735
736     if( !mGlossTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) )
737     {
738       std::string imageUrl = mTexturesPath + mGlossTextureUrl;
739
740       //Load textures
741       Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
742       if( glossTexture )
743       {
744         mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
745         mTextureSet.SetSampler( GLOSS_INDEX, sampler );
746       }
747       else
748       {
749         DALI_LOG_ERROR( "Failed to load gloss map texture in mesh visual.\n");
750         return false;
751       }
752     }
753   }
754   return true;
755 }
756
757 } // namespace Internal
758
759 } // namespace Toolkit
760
761 } // namespace Dali