[retro-gtk/wip/aplazas/gl-display] draw the texture with scanlines



commit f3388ea60c5e325a27222e10413e56ccbb20959b
Author: Adrien Plazas <kekun plazas laposte net>
Date:   Tue Nov 14 14:03:17 2017 +0100

    draw the texture with scanlines

 retro-gtk/retro-gl-display-fragment.glsl |   16 ++--
 retro-gtk/retro-gl-display-vertex.glsl   |    6 +-
 retro-gtk/retro-gl-display.c             |   82 +++++++++++++++-----
 retro-gtk/retro-gtk.gresource.xml        |    3 +
 retro-gtk/shaders/crt-simple.fs          |  127 ++++++++++++++++++++++++++++++
 retro-gtk/shaders/crt-simple.vs          |   27 ++++++
 retro-gtk/shaders/scanline.fs            |   20 +++++
 7 files changed, 253 insertions(+), 28 deletions(-)
---
diff --git a/retro-gtk/retro-gl-display-fragment.glsl b/retro-gtk/retro-gl-display-fragment.glsl
index aa70c52..93f7013 100644
--- a/retro-gtk/retro-gl-display-fragment.glsl
+++ b/retro-gtk/retro-gl-display-fragment.glsl
@@ -1,11 +1,13 @@
-#version 150 core
+#version 150
 
-in vec2 texture_coordinates_frag;
-out vec4 out_color;
+uniform sampler2D source[];
 
-uniform sampler2D video;
+in Vertex {
+  vec2 texCoord;
+};
 
-void main ()
-{
-  out_color = texture (video, texture_coordinates_frag);
+out vec4 fragColor;
+
+void main() {
+  fragColor = texture(source[0], texCoord);
 }
diff --git a/retro-gtk/retro-gl-display-vertex.glsl b/retro-gtk/retro-gl-display-vertex.glsl
index 529d345..52caf7c 100644
--- a/retro-gtk/retro-gl-display-vertex.glsl
+++ b/retro-gtk/retro-gl-display-vertex.glsl
@@ -3,13 +3,15 @@
 in vec2 position;
 in vec2 texture_coordinates;
 
-out vec2 texture_coordinates_frag;
+out Vertex {
+  vec2 texCoord;
+} vertexOut;
 
 uniform float relative_aspect_ratio;
 
 void main ()
 {
-  texture_coordinates_frag = texture_coordinates;
+  vertexOut.texCoord = texture_coordinates;
   if (relative_aspect_ratio > 1.0f)
     gl_Position = vec4 (position.x / relative_aspect_ratio,
                         position.y,
diff --git a/retro-gtk/retro-gl-display.c b/retro-gtk/retro-gl-display.c
index 13b693c..fb637e1 100644
--- a/retro-gtk/retro-gl-display.c
+++ b/retro-gtk/retro-gl-display.c
@@ -78,18 +78,39 @@ typedef struct {
   } texture_coordinates;
 } RetroVertex;
 
-float vertices[] = {
+static float vertices[] = {
   -1.0f,  1.0f, 0.0f, 0.0f, // Top-left
    1.0f,  1.0f, 1.0f, 0.0f, // Top-right
    1.0f, -1.0f, 1.0f, 1.0f, // Bottom-right
   -1.0f, -1.0f, 0.0f, 1.0f, // Bottom-left
 };
 
-GLuint elements[] = {
+static GLuint elements[] = {
     0, 1, 2,
     2, 3, 0,
 };
 
+static GLuint
+create_shader_from_resource (GLenum                 shader_type,
+                             const char            *path,
+                             GResourceLookupFlags   lookup_flags,
+                             GError               **error)
+{
+  GBytes *source_bytes;
+  const gchar *source;
+  GLuint shader;
+
+  // TODO Handle the error properly.
+  source_bytes = g_resources_lookup_data (path, lookup_flags, error);
+  source = g_bytes_get_data (source_bytes, NULL);
+  shader = glCreateShader (shader_type);
+  glShaderSource (shader, 1, &source, NULL);
+  glCompileShader (shader);
+  g_bytes_unref (source_bytes);
+
+  return shader;
+}
+
 static void
 retro_gl_display_realize (RetroGLDisplay *self)
 {
@@ -99,8 +120,6 @@ retro_gl_display_realize (RetroGLDisplay *self)
   GLuint vertex_shader;
   GLuint fragment_shader;
   GLuint shader_program;
-  GBytes *shader_source_bytes;
-  const gchar *shader_source;
 
   gtk_gl_area_make_current (GTK_GL_AREA (self));
 
@@ -115,21 +134,17 @@ retro_gl_display_realize (RetroGLDisplay *self)
   glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, element_buffer_object);
   glBufferData (GL_ELEMENT_ARRAY_BUFFER, sizeof (elements), elements, GL_STATIC_DRAW);
 
-  // Prepare the vertex shader
-  shader_source_bytes = g_resources_lookup_data ("/org/gnome/Retro/retro-gl-display-vertex.glsl", 0, NULL);
-  shader_source = g_bytes_get_data (shader_source_bytes, NULL);
-  vertex_shader = glCreateShader (GL_VERTEX_SHADER);
-  glShaderSource (vertex_shader, 1, &shader_source, NULL);
-  glCompileShader (vertex_shader);
-  g_bytes_unref (shader_source_bytes);
-
-  // Prepare the fragment shader
-  shader_source_bytes = g_resources_lookup_data ("/org/gnome/Retro/retro-gl-display-fragment.glsl", 0, NULL);
-  shader_source = g_bytes_get_data (shader_source_bytes, NULL);
-  fragment_shader = glCreateShader (GL_FRAGMENT_SHADER);
-  glShaderSource (fragment_shader, 1, &shader_source, NULL);
-  glCompileShader (fragment_shader);
-  g_bytes_unref (shader_source_bytes);
+  vertex_shader =
+    create_shader_from_resource (GL_VERTEX_SHADER,
+                                 "/org/gnome/Retro/retro-gl-display-vertex.glsl",
+                                 0,
+                                 NULL);
+
+  fragment_shader =
+    create_shader_from_resource (GL_FRAGMENT_SHADER,
+                                 "/org/gnome/Retro/shaders/scanline.fs",
+                                 0,
+                                 NULL);
 
   // Prepare the shader program
   shader_program = glCreateProgram();
@@ -165,6 +180,21 @@ retro_gl_display_unrealize (RetroGLDisplay *self)
   self->shader_program = 0;
 }
 
+static void
+set_gl_uniform_4f (GLuint        program,
+                   const GLchar *name,
+                   GLfloat       v0,
+                   GLfloat       v1,
+                   GLfloat       v2,
+                   GLfloat       v3)
+{
+
+  GLint location;
+
+  location = glGetUniformLocation (program, name);
+  glUniform4f (location, v0, v1, v2, v3);
+}
+
 static gboolean
 retro_gl_display_render (RetroGLDisplay *self)
 {
@@ -174,6 +204,7 @@ retro_gl_display_render (RetroGLDisplay *self)
   gdouble y = 0.0;
   GLenum filter;
   GLint relative_aspect_ratio;
+  GLfloat target_width, target_height, output_width, output_height;
 
   g_return_val_if_fail (self != NULL, FALSE);
 
@@ -216,6 +247,19 @@ retro_gl_display_render (RetroGLDisplay *self)
                (gfloat) gtk_widget_get_allocated_height (GTK_WIDGET (self)) /
                self->aspect_ratio);
 
+  target_width = (GLfloat) gdk_pixbuf_get_width (self->pixbuf);
+  target_height = (GLfloat) gdk_pixbuf_get_height (self->pixbuf);
+  output_width = (GLfloat) gtk_widget_get_allocated_width (GTK_WIDGET (self));
+  output_height = (GLfloat) gtk_widget_get_allocated_height (GTK_WIDGET (self));
+
+  set_gl_uniform_4f (self->shader_program, "targetSize",
+                     target_width, target_height,
+                     1.0f / target_width, 1.0f / target_height);
+
+  set_gl_uniform_4f (self->shader_program, "outputSize",
+                     output_width, output_height,
+                     1.0f / output_width, 1.0f / output_height);
+
   glDrawElements (GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
 
   return FALSE;
diff --git a/retro-gtk/retro-gtk.gresource.xml b/retro-gtk/retro-gtk.gresource.xml
index e9a9c5f..5133261 100644
--- a/retro-gtk/retro-gtk.gresource.xml
+++ b/retro-gtk/retro-gtk.gresource.xml
@@ -3,5 +3,8 @@
   <gresource prefix="/org/gnome/Retro">
     <file>retro-gl-display-fragment.glsl</file>
     <file>retro-gl-display-vertex.glsl</file>
+    <file>shaders/crt-simple.fs</file>
+    <file>shaders/crt-simple.vs</file>
+    <file>shaders/scanline.fs</file>
   </gresource>
 </gresources>
diff --git a/retro-gtk/shaders/crt-simple.fs b/retro-gtk/shaders/crt-simple.fs
new file mode 100644
index 0000000..5fdccaa
--- /dev/null
+++ b/retro-gtk/shaders/crt-simple.fs
@@ -0,0 +1,127 @@
+#version 150
+
+uniform sampler2D source[];
+uniform vec4 sourceSize[];
+
+in Vertex {
+  vec2 texCoord;
+  vec2 one;
+  float mod_factor;
+};
+
+out vec4 fragColor;
+
+        uniform vec4 targetSize;
+        uniform vec2 outputSize;
+
+        // Enable screen curvature.
+        #define CURVATURE
+
+        // Controls the intensity of the barrel distortion used to emulate the
+        // curvature of a CRT. 0.0 is perfectly flat, 1.0 is annoyingly
+        // distorted, higher values are increasingly ridiculous.
+        #define distortion 0.08
+
+        // Simulate a CRT gamma of 2.4.
+        #define inputGamma  2.4
+
+        // Compensate for the standard sRGB gamma of 2.2.
+        #define outputGamma 2.2
+
+        // Macros.
+        #define TEX2D(c) pow(texture2D(source[0], (c)), vec4(inputGamma))
+        #define PI 3.141592653589
+
+        // Apply radial distortion to the given coordinate.
+        vec2 radialDistortion(vec2 coord)
+        {
+                vec2 cc = coord - 0.5;
+                float dist = dot(cc, cc) * distortion;
+                return (coord + cc * (1.0 + dist) * dist);
+        }
+
+        // Calculate the influence of a scanline on the current pixel.
+        //
+        // 'distance' is the distance in texture coordinates from the current
+        // pixel to the scanline in question.
+        // 'color' is the colour of the scanline at the horizontal location of
+        // the current pixel.
+        vec4 scanlineWeights(float distance, vec4 color)
+        {
+                // The "width" of the scanline beam is set as 2*(1 + x^4) for
+                // each RGB channel.
+                vec4 wid = 2.0 + 2.0 * pow(color, vec4(4.0));
+
+                // The "weights" lines basically specify the formula that gives
+                // you the profile of the beam, i.e. the intensity as
+                // a function of distance from the vertical center of the
+                // scanline. In this case, it is gaussian if width=2, and
+                // becomes nongaussian for larger widths. Ideally this should
+                // be normalized so that the integral across the beam is
+                // independent of its width. That is, for a narrower beam
+                // "weights" should have a higher peak at the center of the
+                // scanline than for a wider beam.
+                vec4 weights = vec4(distance / 0.3);
+                return 1.4 * exp(-pow(weights * inversesqrt(0.5 * wid), wid)) / (0.6 + 0.2 * wid);
+        }
+
+void main() {
+                 // Here's a helpful diagram to keep in mind while trying to
+                // understand the code:
+                //
+                //  |      |      |      |      |
+                // -------------------------------
+                //  |      |      |      |      |
+                //  |  01  |  11  |  21  |  31  | <-- current scanline
+                //  |      | @    |      |      |
+                // -------------------------------
+                //  |      |      |      |      |
+                //  |  02  |  12  |  22  |  32  | <-- next scanline
+                //  |      |      |      |      |
+                // -------------------------------
+                //  |      |      |      |      |
+                //
+                // Each character-cell represents a pixel on the output
+                // surface, "@" represents the current pixel (always somewhere
+                // in the bottom half of the current scan-line, or the top-half
+                // of the next scanline). The grid of lines represents the
+                // edges of the texels of the underlying texture.
+
+                // Texture coordinates of the texel containing the active pixel.
+        #ifdef CURVATURE
+                vec2 xy = radialDistortion(texCoord);
+        #else
+                vec2 xy = texCoord;
+        #endif
+
+                // Of all the pixels that are mapped onto the texel we are
+                // currently rendering, which pixel are we currently rendering?
+                vec2 ratio_scale = xy * sourceSize[0].xy - vec2(0.5);
+                vec2 uv_ratio = fract(ratio_scale);
+
+                // Snap to the center of the underlying texel.
+                xy.y = (floor(ratio_scale.y) + 0.5) / sourceSize[0].y;
+
+                // Calculate the effective colour of the current and next
+                // scanlines at the horizontal location of the current pixel.
+                vec4 col  = TEX2D(xy);
+                vec4 col2 = TEX2D(xy + vec2(0.0, one.y));
+
+                // Calculate the influence of the current and next scanlines on
+                // the current pixel.
+                vec4 weights  = scanlineWeights(uv_ratio.y, col);
+                vec4 weights2 = scanlineWeights(1.0 - uv_ratio.y, col2);
+                vec3 mul_res  = (col * weights + col2 * weights2).rgb;
+
+                // dot-mask emulation:
+                // Output pixels are alternately tinted green and magenta.
+                vec3 dotMaskWeights = mix(
+                        vec3(1.0, 0.7, 1.0),
+                        vec3(0.7, 1.0, 0.7),
+                        floor(mod(mod_factor, 2.0))
+                    );
+
+                mul_res *= dotMaskWeights;
+
+                fragColor = vec4(pow(mul_res, vec3(1.0 / outputGamma)), 1.0);
+}
diff --git a/retro-gtk/shaders/crt-simple.vs b/retro-gtk/shaders/crt-simple.vs
new file mode 100644
index 0000000..e1f50d5
--- /dev/null
+++ b/retro-gtk/shaders/crt-simple.vs
@@ -0,0 +1,27 @@
+#version 150
+
+in vec2 position;
+in vec2 texCoord;
+
+out Vertex {
+  vec2 texCoord;
+  // Define some calculations that will be used in fragment shader.
+  vec2 one;
+  float mod_factor;
+} vertexOut;
+
+        uniform vec4 targetSize;
+        uniform vec2 outputSize;
+        uniform vec4 sourceSize[];
+
+void main() {
+  gl_Position = vec4 (position, 0.0, 1.0);
+  vertexOut.texCoord = texCoord;
+
+
+   // The size of one texel, in texture-coordinates.
+   vertexOut.one = 1.0 / sourceSize[0].xy;
+
+   // Resulting X pixel-coordinate of the pixel we're drawing.
+   vertexOut.mod_factor = texCoord.x * targetSize.x;
+}
diff --git a/retro-gtk/shaders/scanline.fs b/retro-gtk/shaders/scanline.fs
new file mode 100644
index 0000000..42a9603
--- /dev/null
+++ b/retro-gtk/shaders/scanline.fs
@@ -0,0 +1,20 @@
+#version 150
+
+uniform sampler2D source[];
+
+in Vertex {
+  vec2 texCoord;
+};
+
+out vec4 fragColor;
+
+void main() {
+  vec4 rgba = texture(source[0], texCoord);
+  vec4 intensity;
+  if(fract(gl_FragCoord.y * (0.5 * 4.0 / 3.0)) > 0.5) {
+    intensity = vec4(0);
+  } else {
+    intensity = smoothstep(0.2, 0.8, rgba) + normalize(rgba);
+  }
+  fragColor = intensity * -0.25 + rgba * 1.1;
+}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]