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

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