5 #include <fcntl.h> // for access(2)
6 #include <unistd.h> // for access(2)
8 #include "shaderprogram.h"
10 #define BASICTEX_VERT \
12 "#extension GL_ARB_shading_language_420pack : require\n"\
13 "#extension GL_ARB_explicit_attrib_location : require\n"\
15 "layout(std140, binding=0) uniform Viewport\n"\
21 "layout(location = 0) in vec2 position;\n"\
22 "layout(location = 1) in vec2 tex_coord;\n"\
24 "out vec2 fp_tex_coord;\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"\
36 #define BASICTEX_FRAG \
39 "in vec2 fp_tex_coord;\n"\
41 "out vec4 output_colour;\n"\
43 "uniform sampler2D tex;\n"\
44 "uniform vec4 colour;\n"\
48 "\toutput_colour = colour;\n"\
49 "\toutput_colour.a = texture(tex, fp_tex_coord).r;\n"\
55 static void opengl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void *data)
57 Error("OpenGL Error (%d): %s", id, msg);
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);
69 Fatal("Couldn't create window!");
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);
77 m_gl_context = SDL_GL_CreateContext(m_window);
81 // Why is this so horribly broken?
82 if (ogl_IsVersionGEQ(3,0))
84 Fatal("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
87 if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
89 Fatal("Your system does not support the ARB_shading_language_420pack extension, which is required.");
92 if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
94 Fatal("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
97 m_frame_begin_time = SDL_GetPerformanceCounter();
98 m_last_frame_time = 0;
99 m_last_frame_gpu_timer = 0;
100 glGenQueries(1, &m_frame_gpu_timer);
101 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
103 glDebugMessageCallback(opengl_debug_callback, 0);
106 glGenVertexArrays(1, &default_vao);
107 glBindVertexArray(default_vao);
109 //TODO: Error checking.
110 m_texture_prog.AttachVertexProgram(BASICTEX_VERT);
111 m_texture_prog.AttachFragmentProgram(BASICTEX_FRAG);
112 m_texture_prog.Link();
113 m_texture_prog.Use();
115 // We always want to use the texture bound to texture unit 0.
116 GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
117 glUniform1i(texture_uniform_location, 0);
119 m_colour_uniform_location = m_texture_prog.GetUniformLocation("colour");
121 m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
122 m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
124 m_debug_font_atlas = 0;
126 ResizeViewport(800, 600);
136 SDL_GL_DeleteContext(m_gl_context);
137 SDL_DestroyWindow(m_window);
141 void Screen::Clear(float r, float g, float b, float a)
143 glClearColor(r,g,b,a);
144 glClear(GL_COLOR_BUFFER_BIT);
148 void Screen::ResizeViewport(int width, int height)
150 glViewport(0, 0, width, height);
151 m_viewport_width = width;
152 m_viewport_height = height;
153 GLfloat viewportfloats[] = {(float)width, (float)height};
154 m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
157 bool Screen::PumpEvents()
160 bool no_quit_requested = true;
161 while (SDL_PollEvent(&evt))
166 no_quit_requested = false;
168 case SDL_WINDOWEVENT:
169 switch (evt.window.event)
171 case SDL_WINDOWEVENT_RESIZED:
172 case SDL_WINDOWEVENT_SIZE_CHANGED:
173 ResizeViewport(evt.window.data1, evt.window.data2);
177 case SDL_MOUSEMOTION:
178 m_last_mouse_x = evt.motion.x;
179 m_last_mouse_y = evt.motion.y;
182 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0);
185 case SDL_MOUSEBUTTONDOWN:
186 case SDL_MOUSEBUTTONUP:
187 m_last_mouse_x = evt.button.x;
188 m_last_mouse_y = evt.button.y;
191 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0);
197 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y);
202 Debug("Key %c down", (char)evt.key.keysym.sym);
203 if (isalnum((char)evt.key.keysym.sym))
205 char filename[] = "0.bmp";
206 filename[0] = (char)evt.key.keysym.sym;
207 ScreenShot(filename);
215 return no_quit_requested;
218 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
220 SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
223 case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
224 case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
225 case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
226 case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
227 case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
230 SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
231 SDL_SetCursor(system_cursor);
232 //TODO: Check if we need to free the system cursors.
235 void Screen::Present()
237 if (m_debug_font_atlas)
239 m_last_frame_time = SDL_GetPerformanceCounter() - m_frame_begin_time;
240 glEndQuery(GL_TIME_ELAPSED);
241 SDL_GL_SwapWindow(m_window);
242 m_frame_begin_time = SDL_GetPerformanceCounter();
243 if (m_last_frame_gpu_timer)
244 glDeleteQueries(1, &m_last_frame_gpu_timer);
245 m_last_frame_gpu_timer = m_frame_gpu_timer;
246 glGenQueries(1, &m_frame_gpu_timer);
247 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
250 double Screen::GetLastFrameTimeGPU() const
252 if (!m_last_frame_gpu_timer)
254 uint64_t frame_time_ns;
255 glGetQueryObjectui64v(m_last_frame_gpu_timer, GL_QUERY_RESULT, &frame_time_ns);
256 return frame_time_ns/1000000000.0;
259 void Screen::ScreenShot(const char * filename) const
261 Debug("Attempting to save BMP to file %s", filename);
263 int w = ViewportWidth();
264 int h = ViewportHeight();
265 unsigned char * pixels = new unsigned char[w*h*4];
267 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
269 for (int y = 0; y < h; ++y)
271 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
274 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
275 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
277 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
280 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
282 GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
283 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);
285 if (SDL_SaveBMP(surf, filename) != 0)
286 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
288 SDL_FreeSurface(surf);
295 * NOT PART OF THE DOCUMENT FORMAT
297 void Screen::RenderBMP(const char * filename) const
299 if (access(filename, R_OK) == -1)
301 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
304 SDL_Surface * bmp = SDL_LoadBMP(filename);
306 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
311 GLenum texture_format;
312 switch (bmp->format->BytesPerPixel)
314 case 4: //contains alpha
315 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
317 case 3: //does not contain alpha
318 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;
321 Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
325 //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);
327 m_texture_prog.Use();
328 GraphicsBuffer quad_vertex_buffer;
329 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
330 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
333 1, 0, ViewportWidth(), 0,
334 1, 1, ViewportWidth(), ViewportHeight(),
335 0, 1, 0, ViewportHeight()
337 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
338 quad_vertex_buffer.Bind();
339 m_viewport_ubo.Bind();
341 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
344 glGenTextures(1, &texID);
345 glBindTexture(GL_TEXTURE_2D, texID);
347 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
348 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
349 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
350 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
352 glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
354 glEnableVertexAttribArray(0);
355 glEnableVertexAttribArray(1);
356 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
357 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
358 glDisableVertexAttribArray(1);
359 glDisableVertexAttribArray(0);
360 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
362 SDL_FreeSurface(bmp);
365 void Screen::DebugFontInit(const char *name, float font_size)
367 unsigned char font_atlas_data[1024*1024];
368 FILE *font_file = fopen(name, "rb");
369 fseek(font_file, 0, SEEK_END);
370 size_t font_file_size = ftell(font_file);
371 fseek(font_file, 0, SEEK_SET);
372 unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
373 fread(font_file_data, 1, font_file_size, font_file);
375 stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
376 free(font_file_data);
377 glGenTextures(1, &m_debug_font_atlas);
378 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
379 glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
380 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
381 m_debug_font_size = font_size;
383 m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
384 m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
385 m_debug_font_vertices.Upload(8192, nullptr);
386 m_debug_font_vertex_head = 0;
388 m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
389 m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
390 m_debug_font_indices.Resize(500);
391 m_debug_font_index_head = 0;
394 void Screen::DebugFontClear()
396 m_debug_font_x = m_debug_font_y = 0;
397 if (!m_debug_font_atlas) return;
398 DebugFontPrint("\n");
401 void Screen::DebugFontFlush()
406 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
407 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
409 m_texture_prog.Use();
410 m_viewport_ubo.Bind();
411 m_debug_font_vertices.Bind();
412 m_debug_font_indices.Bind();
413 glUniform4f(m_colour_uniform_location, 0,0,0,1);
414 glEnableVertexAttribArray(0);
415 glEnableVertexAttribArray(1);
416 glEnable(GL_PRIMITIVE_RESTART);
417 glPrimitiveRestartIndex(65535);
418 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
419 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
420 glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
421 glDisable(GL_PRIMITIVE_RESTART);
422 glDisableVertexAttribArray(1);
423 glDisableVertexAttribArray(0);
427 m_debug_font_vertex_head = 0;
428 m_debug_font_index_head = 0;
431 void Screen::DebugFontPrint(const char* str)
433 if (!m_debug_font_atlas) return;
435 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);
436 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);
438 if ((m_debug_font_vertex_head*sizeof(float) + 16*sizeof(float) >= m_debug_font_vertices.GetSize() ) ||
439 (m_debug_font_index_head*sizeof(uint16_t) + 5*sizeof(uint16_t) >= m_debug_font_indices.GetSize()))
441 m_debug_font_indices.UnMap();
442 m_debug_font_vertices.UnMap();
447 if (*str >= 32 && *str < 128) {
448 stbtt_aligned_quad q;
449 stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
450 *vertexData = q.s0; vertexData++;
451 *vertexData = q.t0; vertexData++;
452 *vertexData = q.x0; vertexData++;
453 *vertexData = q.y0; vertexData++;
454 *vertexData = q.s1; vertexData++;
455 *vertexData = q.t0; vertexData++;
456 *vertexData = q.x1; vertexData++;
457 *vertexData = q.y0; vertexData++;
458 *vertexData = q.s1; vertexData++;
459 *vertexData = q.t1; vertexData++;
460 *vertexData = q.x1; vertexData++;
461 *vertexData = q.y1; vertexData++;
462 *vertexData = q.s0; vertexData++;
463 *vertexData = q.t1; vertexData++;
464 *vertexData = q.x0; vertexData++;
465 *vertexData = q.y1; vertexData++;
467 *indexData = m_debug_font_vertex_head/4; indexData++;
468 *indexData = m_debug_font_vertex_head/4+1; indexData++;
469 *indexData = m_debug_font_vertex_head/4+3; indexData++;
470 *indexData = m_debug_font_vertex_head/4+2; indexData++;
471 *indexData = 65535; indexData++;
473 m_debug_font_vertex_head += 16;
474 m_debug_font_index_head += 5;
477 else if (*str == '\n')
480 m_debug_font_y += m_debug_font_size;
484 m_debug_font_indices.UnMap();
485 m_debug_font_vertices.UnMap();
489 void Screen::DebugFontPrintF(const char *fmt, ...)
494 vsnprintf(buffer, BUFSIZ, fmt,va);
496 DebugFontPrint(buffer);