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

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