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

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