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

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