1 module meatbox.imagebox;
2 
3 import meatbox.box;
4 
5 import derelict.opengl3.gl;
6 import derelict.opengl3.gl3;
7 import derelict.sdl2.sdl;
8 import derelict.sdl2.image;
9 
10 static this()
11 { 
12 	DerelictSDL2Image.load();
13 	IMG_Init( IMG_INIT_PNG );
14 }
15 static ~this()
16 	{ IMG_Quit(); }
17 
18 class Imagebox: Box
19 {
20 public:
21 	override void width( int width ) @property
22 	{
23 		super.width =width;
24 		this._verts[4] =width;
25 		this._verts[6] =width;
26 	}
27 	override void height( int height ) @property
28 	{
29 		super.height =height;
30 		this._verts[3] =height;
31 		this._verts[5] =height;
32 	}
33 	this()
34 	{ 
35 		glGenTextures( 1, &_buffer );
36 	}
37 	this( string path )
38 	{
39 		this();
40 		load( path );
41 	}
42 	~this()
43 		{ glDeleteTextures( 1, &_buffer );}
44 	/+ Returns if it loaded properly because why not+/
45 	bool load( string path )
46 	{
47 		SDL_Surface* img =IMG_Load( cast(const(char)*)(path) );
48 		if( img is null )
49 		{ 
50 			return false; 
51 		}
52 			
53 		glBindTexture( GL_TEXTURE_2D, _buffer );
54 		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
55 		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
56 		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
57 		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
58 		
59 		this.width =img.w; this.height =img.h;
60 		glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, img.w, img.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, cast(const(void)*)img.pixels );
61 		glBindTexture( GL_TEXTURE_2D, 0 );
62 		return true;
63 	}
64 	void render()
65 	{
66 		glVertexPointer( 2, GL_FLOAT, 0, _verts.ptr );	
67 		glBindTexture( GL_TEXTURE_2D, _buffer );
68 		
69 		glPushMatrix();
70 		glTranslatef( x, y, 0);
71 		glDrawArrays( GL_QUADS, 0, 4);
72 		glPopMatrix();
73 		
74 	}
75 	static this()
76 	{
77 		//Preload box vectors into GPU memory.
78 		//Stick into base Box class?
79 	}
80 	static void startRender()
81 	{
82 		glEnableClientState( GL_VERTEX_ARRAY );
83 		glEnableClientState( GL_TEXTURE_COORD_ARRAY );
84 		glEnable( GL_TEXTURE_2D );
85 		glEnable( GL_BLEND );
86 		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );	
87 		glColor4f( 1f, 1f, 1f, 1f );
88 		glTexCoordPointer( 2, GL_FLOAT, 0, Imagebox.texbox.ptr );	
89 	}
90 	static void endRender()
91 	{
92 		glDisable( GL_BLEND);
93 		glDisable( GL_TEXTURE_2D);
94 		glDisableClientState( GL_TEXTURE_COORD_ARRAY);
95 		glDisableClientState( GL_VERTEX_ARRAY);
96 	}
97 private:
98 	static immutable float[8] texbox =
99 	[ 
100 		0f, 0f,
101 		0f, 1f,
102 		1f, 1f,
103 		1f, 0f
104 	];
105 	uint _buffer;
106 	float[8] _verts =
107 	[ 
108 		0f, 0f,
109 		0f, 1f,
110 		1f, 1f,
111 		1f, 0f
112 	];
113 }