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