40754b3e6e3efcc37bb88d22962c82eb5e3b072a
[ipdf/code.git] / src / screen.cpp
1 #include "common.h"
2 #include "screen.h"
3
4 #include "gl_core44.h"
5 #include <fcntl.h> // for access(2)
6 #include <unistd.h> // for access(2)
7
8 #include "shaderprogram.h"
9
10 #define BASICTEX_VERT \
11         "#version 140\n"\
12         "#extension GL_ARB_shading_language_420pack : require\n"\
13         "#extension GL_ARB_explicit_attrib_location : require\n"\
14         "\n"\
15         "layout(std140, binding=0) uniform Viewport\n"\
16         "{\n"\
17         "\tfloat width;\n"\
18         "\tfloat height;\n"\
19         "};\n"\
20         "\n"\
21         "layout(location = 0) in vec2 position;\n"\
22         "layout(location = 1) in vec2 tex_coord;\n"\
23         "\n"\
24         "out vec2 fp_tex_coord;\n"\
25         "\n"\
26         "void main()\n"\
27         "{\n"\
28         "\t// Transform to clip coordinates (-1,1, -1,1).\n"\
29         "\tgl_Position.x = (position.x*2/width) - 1;\n"\
30         "\tgl_Position.y = 1 - (position.y*2/height);\n"\
31         "\tgl_Position.z = 0.0;\n"\
32         "\tgl_Position.w = 1.0;\n"\
33         "\tfp_tex_coord = tex_coord;\n"\
34         "}\n"
35
36 #define BASICTEX_FRAG \
37         "#version 140\n"\
38         "\n"\
39         "in vec2 fp_tex_coord;\n"\
40         "\n"\
41         "out vec4 output_colour;\n"\
42         "\n"\
43         "uniform sampler2D tex;\n"\
44         "uniform vec4 colour;\n"\
45         "\n"\
46         "void main()\n"\
47         "{\n"\
48         "\toutput_colour = colour;\n"\
49         "\toutput_colour.a = texture(tex, fp_tex_coord).r;\n"\
50         "}\n"
51
52 using namespace IPDF;
53 using namespace std;
54
55 static void opengl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void *data)
56 {
57         Error("OpenGL Error (%d): %s", id, msg);
58 }
59
60
61 Screen::Screen()
62 {
63         SDL_Init(SDL_INIT_VIDEO);
64         m_window = SDL_CreateWindow("IPDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
65                         800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
66
67         if (!m_window)
68         {
69                 Fatal("Couldn't create window!");
70         }
71
72         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
73         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
74         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
75         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
76
77         m_gl_context = SDL_GL_CreateContext(m_window);
78
79         ogl_LoadFunctions();
80
81         // Why is this so horribly broken?
82         if (ogl_IsVersionGEQ(3,0))
83         {
84                 Fatal("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
85         }
86
87         if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
88         {
89                 Fatal("Your system does not support the ARB_shading_language_420pack extension, which is required.");
90         }
91
92         if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
93         {
94                 Fatal("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
95         }
96
97         glDebugMessageCallback(opengl_debug_callback, 0);
98
99         GLuint default_vao;
100         glGenVertexArrays(1, &default_vao);
101         glBindVertexArray(default_vao);
102
103         //TODO: Error checking.
104         m_texture_prog.AttachVertexProgram(BASICTEX_VERT);
105         m_texture_prog.AttachFragmentProgram(BASICTEX_FRAG);
106         m_texture_prog.Link();
107         m_texture_prog.Use();
108
109         // We always want to use the texture bound to texture unit 0.
110         GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
111         glUniform1i(texture_uniform_location, 0);
112
113         m_colour_uniform_location = m_texture_prog.GetUniformLocation("colour");
114
115         m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
116         m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
117
118         m_debug_font_atlas = 0;
119
120         ResizeViewport(800, 600);
121
122         Clear();
123         Present();
124         
125
126 }
127
128 Screen::~Screen()
129 {
130         SDL_GL_DeleteContext(m_gl_context);
131         SDL_DestroyWindow(m_window);
132         SDL_Quit();
133 }
134
135 void Screen::Clear(float r, float g, float b, float a)
136 {
137         glClearColor(r,g,b,a);
138         glClear(GL_COLOR_BUFFER_BIT);
139         DebugFontClear();
140 }
141
142 void Screen::ResizeViewport(int width, int height)
143 {
144         glViewport(0, 0, width, height);
145         m_viewport_width = width;
146         m_viewport_height = height;
147         GLfloat viewportfloats[] = {(float)width, (float)height};
148         m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
149 }
150
151 bool Screen::PumpEvents()
152 {
153         SDL_Event evt;
154         bool no_quit_requested = true;
155         while (SDL_PollEvent(&evt))
156         {
157                 switch (evt.type)
158                 {
159                 case SDL_QUIT:
160                         no_quit_requested = false;
161                         break;
162                 case SDL_WINDOWEVENT:
163                         switch (evt.window.event)
164                         {
165                         case SDL_WINDOWEVENT_RESIZED:
166                         case SDL_WINDOWEVENT_SIZE_CHANGED:
167                                 ResizeViewport(evt.window.data1, evt.window.data2);
168                                 break;
169                         }
170                         break;
171                 case SDL_MOUSEMOTION:
172                         m_last_mouse_x = evt.motion.x;
173                         m_last_mouse_y = evt.motion.y;
174                         if (m_mouse_handler)
175                         {
176                                 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0);
177                         }
178                         break;
179                 case SDL_MOUSEBUTTONDOWN:
180                 case SDL_MOUSEBUTTONUP:
181                         m_last_mouse_x = evt.button.x;
182                         m_last_mouse_y = evt.button.y;
183                         if (m_mouse_handler)
184                         {
185                                 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0);
186                         }
187                         break;
188                 case SDL_MOUSEWHEEL:
189                         if (m_mouse_handler)
190                         {
191                                 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y);
192                         }
193                         break;
194                 case SDL_KEYDOWN:
195                 {
196                         Debug("Key %c down", (char)evt.key.keysym.sym);
197                         if (isalnum((char)evt.key.keysym.sym))
198                         {
199                                 char filename[] = "0.bmp";
200                                 filename[0] = (char)evt.key.keysym.sym;
201                                 ScreenShot(filename);
202                         }
203                         break;
204                 }
205                 default:
206                         break;
207                 }
208         }
209         return no_quit_requested;
210 }
211
212 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
213 {
214         SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
215         switch (cursor)
216         {
217         case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
218         case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
219         case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
220         case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
221         case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
222         default: break;
223         }
224         SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
225         SDL_SetCursor(system_cursor);
226         //TODO: Check if we need to free the system cursors.
227 }
228
229 void Screen::Present()
230 {
231         if (m_debug_font_atlas)
232                 DebugFontFlush();
233         SDL_GL_SwapWindow(m_window);
234 }
235
236 void Screen::ScreenShot(const char * filename) const
237 {
238         Debug("Attempting to save BMP to file %s", filename);
239
240         int w = ViewportWidth();
241         int h = ViewportHeight();
242         unsigned char * pixels = new unsigned char[w*h*4];
243         if (pixels == NULL)
244                 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
245
246         for (int y = 0; y < h; ++y)
247         {
248                 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
249         }
250
251 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
252         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
253 #else
254         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
255 #endif
256         if (surf == NULL)
257                 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
258
259         GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
260         Debug("SDL_Surface %d BytesPerPixel, format %d (RGB = %d, BGR = %d, RGBA = %d, BGRA = %d)", surf->format->BytesPerPixel, texture_format, GL_RGB, GL_BGR, GL_RGBA, GL_BGRA);
261
262         if (SDL_SaveBMP(surf, filename) != 0)
263                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
264         
265         SDL_FreeSurface(surf);
266         delete [] pixels;
267         Debug("Succeeded!");
268 }
269
270 /**
271  * Render a BMP
272  * NOT PART OF THE DOCUMENT FORMAT
273  */
274 void Screen::RenderBMP(const char * filename) const
275 {
276         if (access(filename, R_OK) == -1)
277         {
278                 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
279                 return;
280         }
281         SDL_Surface * bmp = SDL_LoadBMP(filename);
282         if (bmp == NULL)
283                 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
284
285         int w = bmp->w;
286         int h = bmp->h;
287
288         GLenum texture_format; 
289         switch (bmp->format->BytesPerPixel)
290         {
291                 case 4: //contains alpha
292                         texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
293                         break;
294                 case 3: //does not contain alpha
295                         texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;  
296                         break;
297                 default:
298                         Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
299                         break;  
300         }
301
302         //Debug("SDL_Surface %d BytesPerPixel, format %d (RGB = %d, BGR = %d, RGBA = %d, BGRA = %d)", bmp->format->BytesPerPixel, texture_format, GL_RGB, GL_BGR, GL_RGBA, GL_BGRA);
303
304         m_texture_prog.Use();
305         GraphicsBuffer quad_vertex_buffer;
306         quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
307         quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
308         GLfloat quad[] = { 
309                 0, 0, 0, 0,
310                 1, 0, ViewportWidth(), 0,
311                 1, 1, ViewportWidth(), ViewportHeight(),
312                 0, 1, 0, ViewportHeight()
313         };
314         quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
315         quad_vertex_buffer.Bind();
316         m_viewport_ubo.Bind();
317
318         glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
319
320         GLuint texID;
321         glGenTextures(1, &texID);
322         glBindTexture(GL_TEXTURE_2D, texID);
323
324         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
325         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
326         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
327         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
328
329         glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
330
331         glEnableVertexAttribArray(0);
332         glEnableVertexAttribArray(1);
333         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
334         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
335         glDisableVertexAttribArray(1);
336         glDisableVertexAttribArray(0);
337         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
338
339         SDL_FreeSurface(bmp);   
340 }
341
342 void Screen::DebugFontInit(const char *name, float font_size)
343 {
344         unsigned char font_atlas_data[1024*1024];
345         FILE *font_file = fopen(name, "rb");
346         fseek(font_file, 0, SEEK_END);
347         size_t font_file_size = ftell(font_file);
348         fseek(font_file, 0, SEEK_SET);
349         unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
350         fread(font_file_data, 1, font_file_size, font_file);
351         fclose(font_file);
352         stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
353         free(font_file_data);
354         glGenTextures(1, &m_debug_font_atlas);
355         glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
356         glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
357         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
358         m_debug_font_size = font_size;
359
360         m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
361         m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
362         m_debug_font_vertices.Upload(8192, nullptr);
363         m_debug_font_vertex_head = 0;
364
365         m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
366         m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
367         m_debug_font_indices.Resize(500);
368         m_debug_font_index_head = 0;
369 }
370
371 void Screen::DebugFontClear()
372 {
373         m_debug_font_x = m_debug_font_y = 0;
374         if (!m_debug_font_atlas) return;
375         DebugFontPrint("\n");
376 }
377
378 void Screen::DebugFontFlush()
379 {
380         
381                 
382         glEnable(GL_BLEND);
383         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
384         glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
385
386         m_texture_prog.Use();
387         m_viewport_ubo.Bind();
388         m_debug_font_vertices.Bind();
389         m_debug_font_indices.Bind();
390         glUniform4f(m_colour_uniform_location, 0,0,0,1);
391         glEnableVertexAttribArray(0);
392         glEnableVertexAttribArray(1);
393         glEnable(GL_PRIMITIVE_RESTART);
394         glPrimitiveRestartIndex(65535);
395         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
396         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
397         glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
398         glDisable(GL_PRIMITIVE_RESTART);
399         glDisableVertexAttribArray(1);
400         glDisableVertexAttribArray(0);
401
402         glDisable(GL_BLEND);
403
404         m_debug_font_vertex_head = 0;
405         m_debug_font_index_head = 0;
406 }
407
408 void Screen::DebugFontPrint(const char* str)
409 {
410         if (!m_debug_font_atlas) return;
411
412         float *vertexData = (float*)m_debug_font_vertices.MapRange(m_debug_font_vertex_head*sizeof(float), m_debug_font_vertices.GetSize() - m_debug_font_vertex_head*sizeof(float), false, true, true);
413         uint16_t *indexData = (uint16_t*)m_debug_font_indices.MapRange(m_debug_font_index_head*sizeof(uint16_t), m_debug_font_indices.GetSize() - m_debug_font_index_head*sizeof(uint16_t), false, true, true);
414         while (*str) {
415                 if ((m_debug_font_vertex_head*sizeof(float) + 16*sizeof(float) >= m_debug_font_vertices.GetSize() ) ||
416                         (m_debug_font_index_head*sizeof(uint16_t) + 5*sizeof(uint16_t) >= m_debug_font_indices.GetSize()))
417                 {
418                         m_debug_font_indices.UnMap();
419                         m_debug_font_vertices.UnMap();
420                         DebugFontFlush();
421                         DebugFontPrint(str);
422                         return;
423                 }
424                 if (*str >= 32 && *str < 128) {
425                         stbtt_aligned_quad q;
426                         stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
427                         *vertexData = q.s0; vertexData++;
428                         *vertexData = q.t0; vertexData++;
429                         *vertexData = q.x0; vertexData++;
430                         *vertexData = q.y0; vertexData++;
431                         *vertexData = q.s1; vertexData++;
432                         *vertexData = q.t0; vertexData++;
433                         *vertexData = q.x1; vertexData++;
434                         *vertexData = q.y0; vertexData++;
435                         *vertexData = q.s1; vertexData++;
436                         *vertexData = q.t1; vertexData++;
437                         *vertexData = q.x1; vertexData++;
438                         *vertexData = q.y1; vertexData++;
439                         *vertexData = q.s0; vertexData++;
440                         *vertexData = q.t1; vertexData++;
441                         *vertexData = q.x0; vertexData++;
442                         *vertexData = q.y1; vertexData++;
443
444                         *indexData = m_debug_font_vertex_head/4; indexData++;
445                         *indexData = m_debug_font_vertex_head/4+1; indexData++;
446                         *indexData = m_debug_font_vertex_head/4+3; indexData++;
447                         *indexData = m_debug_font_vertex_head/4+2; indexData++;
448                         *indexData = 65535; indexData++;
449
450                         m_debug_font_vertex_head += 16;
451                         m_debug_font_index_head += 5;
452
453                 }
454                 else if (*str == '\n')
455                 {
456                         m_debug_font_x = 0;
457                         m_debug_font_y += m_debug_font_size;
458                 }
459                 ++str;
460         }
461         m_debug_font_indices.UnMap();
462         m_debug_font_vertices.UnMap();
463         //DebugFontFlush();
464 }
465
466 void Screen::DebugFontPrintF(const char *fmt, ...)
467 {
468         char buffer[BUFSIZ];
469         va_list va;
470         va_start(va, fmt);
471         vsnprintf(buffer, BUFSIZ, fmt,va);
472         va_end(va);
473         DebugFontPrint(buffer);
474 }

UCC git Repository :: git.ucc.asn.au