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