1 module components.material;
2 import core.properties;
3 import components;
4 import graphics.graphics, graphics.shaders;
5 import utility.config;
6 
7 import yaml;
8 import derelict.opengl3.gl3, derelict.freeimage.freeimage;
9 import std.variant, std.conv;
10 
11 final class Material : Component
12 {
13 public:
14 	mixin Property!( "Texture", "diffuse" );
15 	mixin Property!( "Texture", "normal" );
16 	mixin Property!( "Texture", "specular" );
17 
18 	/**
19 	* Create a Material from a Yaml node.
20 	*/
21 	static Material createFromYaml( Node yamlObj )
22 	{
23 		auto obj = new Material;
24 		Variant prop;
25 
26 		if( Config.tryGet!string( "Diffuse", prop, yamlObj ) )
27 			obj.diffuse = Assets.get!Texture( prop.get!string );
28 
29 		if( Config.tryGet!string( "Normal", prop, yamlObj ) )
30 			obj.normal = Assets.get!Texture( prop.get!string );
31 
32 		if( Config.tryGet!string( "Specular", prop, yamlObj ) )
33 			obj.specular = Assets.get!Texture( prop.get!string );
34 
35 		return obj;
36 	}
37 
38 	this()
39 	{
40 		super( null );
41 	}
42 
43 	override void update() { }
44 	override void shutdown() { }
45 }
46 
47 final class Texture
48 {
49 public:
50 	mixin Property!( "uint", "width" );
51 	mixin Property!( "uint", "height" );
52 	mixin Property!( "uint", "glID" );
53 
54 	this( string filePath )
55 	{
56 		filePath ~= "\0";
57 		auto imageData = FreeImage_ConvertTo32Bits( FreeImage_Load( FreeImage_GetFileType( filePath.ptr, 0 ), filePath.ptr, 0 ) );
58 
59 		width = FreeImage_GetWidth( imageData );
60 		height = FreeImage_GetHeight( imageData );
61 
62 		glGenTextures( 1, &_glID );
63 		glBindTexture( GL_TEXTURE_2D, glID );
64 		glTexImage2D(
65 					 GL_TEXTURE_2D,
66 					 0,
67 					 GL_RGBA,
68 					 width,
69 					 height,
70 					 0,
71 					 GL_BGRA, //FreeImage loads in BGR format because fuck you
72 					 GL_UNSIGNED_BYTE,
73 					 cast(GLvoid*)FreeImage_GetBits( imageData ) );
74 		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
75 
76 		FreeImage_Unload( imageData );
77 		glBindTexture( GL_TEXTURE_2D, 0 );
78 	}
79 
80 	void shutdown()
81 	{
82 		glBindTexture( GL_TEXTURE_2D, 0 );
83 		glDeleteBuffers( 1, &_glID );
84 	}
85 }