Normal Mapping

Screen shot of normal mapping
normal_mapping_simple.py
  1"""
  2Simple normal mapping example.
  3
  4We load a diffuse and normal map and render them using a simple shader.
  5The normal texture stores a direction vector in the RGB channels
  6pointing up from the surface.
  7
  8For simplicity we use the texture coordinates to determine the
  9screen position but this can be done in other ways.
 10
 11Controls:
 12    Mouse: Move light source
 13    Mouse wheel: Move light source in and out
 14
 15Run this example from the command line with:
 16python -m arcade.examples.gl.normal_mapping_simple
 17"""
 18import arcade
 19from arcade.gl import geometry
 20
 21
 22class NormalMapping(arcade.Window):
 23
 24    def __init__(self):
 25        super().__init__(512, 512, "Normal Mapping")
 26
 27        # Load the color (diffuse) and normal texture
 28        # These should ideally be the same size
 29        self.texture_diffuse = self.ctx.load_texture(":resources:images/test_textures/normal_mapping/diffuse.jpg")
 30        self.texture_normal = self.ctx.load_texture(":resources:images/test_textures/normal_mapping/normal.jpg")
 31
 32        # Shader program doing basic normal mapping
 33        self.program = self.ctx.program(
 34            vertex_shader="""
 35                #version 330
 36
 37                // Inputs from the quad_fs geometry
 38                in vec2 in_vert;
 39                in vec2 in_uv;
 40
 41                // Output to the fragment shader
 42                out vec2 uv;
 43
 44                void main() {
 45                    uv = in_uv;
 46                    gl_Position = vec4(in_vert, 0.0, 1.0);
 47                }
 48
 49            """,
 50            fragment_shader="""
 51                #version 330
 52
 53                // Samplers for reading from textures
 54                uniform sampler2D texture_diffuse;
 55                uniform sampler2D texture_normal;
 56                // Global light position we can set from python
 57                uniform vec3 light_pos;
 58
 59                // Input from vertex shader
 60                in vec2 uv;
 61
 62                // Output to the framebuffer
 63                out vec4 f_color;
 64
 65                void main() {
 66                    // Read RGBA color from the diffuse texture
 67                    vec4 diffuse = texture(texture_diffuse, uv);
 68                    // Read normal from RGB channels and convert to a direction vector.
 69                    // These vectors are like a needle per pixel pointing up from the surface.
 70                    // Since RGB is 0-1 we need to convert to -1 to 1.
 71                    vec3 normal = normalize(texture(texture_normal, uv).rgb * 2.0 - 1.0);
 72
 73                    // Calculate the light direction.
 74                    // This is the direction between the light position and the pixel position.
 75                    vec3 light_dir = normalize(light_pos - vec3(uv, 0.0));
 76
 77                    // Calculate the diffuse factor.
 78                    // This is the dot product between the light direction and the normal.
 79                    // It's basically calculating the angle between the two vectors.
 80                    // The result is a value between 0 and 1.
 81                    float diffuse_factor = max(dot(normal, light_dir), 0.0);
 82
 83                    // Write the final color to the framebuffer.
 84                    // We multiply the diffuse color with the diffuse factor.
 85                    f_color = vec4(diffuse.rgb * diffuse_factor, 1.0);
 86                }
 87            """,
 88        )
 89        # Configure what texture channel the samplers should read from
 90        self.program["texture_diffuse"] = 0
 91        self.program["texture_normal"] = 1
 92
 93        # Shortcut for a full screen quad
 94        # It has two buffers with positions and texture coordinates
 95        # named "in_vert" and "in_uv" so we need to use that in the vertex shader
 96        self.quad_fs = geometry.quad_2d_fs()
 97
 98        # Keep track of mouse coordinates for light position
 99        self.mouse_x = 0.0
100        self.mouse_y = 0.0
101        self.mouse_z = 0.25
102
103        self.text = arcade.Text("0, 0, 0", 20, 20, arcade.color.WHITE)
104
105    def on_draw(self):
106        self.clear()
107
108        # Bind the textures to the channels we configured in the shader
109        self.texture_diffuse.use(0)
110        self.texture_normal.use(1)
111
112        # Update the light position uniform variable
113        self.program["light_pos"] = self.mouse_x, self.mouse_y, self.mouse_z
114
115        # Run the normal mapping shader (fills a full screen quad)
116        self.quad_fs.render(self.program)
117
118        # Draw the mouse coordinates
119        self.text.text = f"{self.mouse_x:.2f}, {self.mouse_y:.2f}, {self.mouse_z:.2f}"
120        self.text.draw()
121
122    def on_mouse_motion(self, x: int, y: int, dx: int, dy: int):
123        """Move the light source with the mouse."""
124        # Convert to normalized coordinates
125        # (0.0, 0.0) is bottom left, (1.0, 1.0) is top right
126        self.mouse_x, self.mouse_y = x / self.width, y / self.height
127
128    def on_mouse_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int):
129        """Zoom in/out with the mouse wheel."""
130        self.mouse_z += scroll_y * 0.05
131
132
133NormalMapping().run()