Modelspace - Demo 06

Objective

Learn about modelspace Modelspace.

Demo 06

Demo 06

How to Execute

Load src/modelviewprojection/demo06.py in Spyder and hit the play button.

Move the Paddles using the Keyboard

Keyboard Input

Action

w

Move Left Paddle Up

s

Move Left Paddle Down

k

Move Right Paddle Down

i

Move Right Paddle Up

Modelspace

NDC are not a natural system of numbers for use by humans. Imagine that the paddles in the previous chapters exist in real life, and are 2 meters wide and 6 meters tall. The graphics programmer should be able to use those numbers directly; they shouldn’t have to manually transform the distances into NDC.

Whatever a convenient numbering system is (i.e. coordinate system) for modeling objects is called modelspace. Since a paddle has four corners, which corner should be at the origin (0,0)? If you don’t already know what you want at the origin, then none of the corners should be; instead put the center of the object at the origin (Because by putting the center of the object at the origin, scaling and rotating the object are trivial, as shown in later chapters).

Representing a Paddle using Modelspace

Representing a Paddle using Modelspace

modelspace - the coordinate system (origin plus axes), in which some object’s vertices are defined.

WorldSpace

WorldSpace is a top-level space, independent of NDC, that we choose to use. It is arbitrary. If you were to model a racetrack for a racing game, the origin of WorldSpace may be the center of that racetrack. If you were modeling our solar system, the center of the sun could be the origin of “WorldSpace”. I personally would put the center of our flat earth at the origin, but reasonable people can disagree.

For our demo with paddles, the author arbitrarily defines the WorldSpace to be 20 units wide, 20 units tall, with the origin at the center.

Demo 06

Demo 06

Modelspace to WorldSpace

The author prefers to view transformations as changes to the graph paper, as compared to view transformations as changes to points.

As such, for placing paddle1, we can view the translation as a change to the graph paper relative to world space coordinates (only incidentally bringing the vertices along with it) and then resetting the graph paper (i.e. both origin and axes) back to its original position and orientation. Although we will think of the paddle’s vertices as relative to its own space (i.e. -1 to 1 horizontally, -3 to 3 vertically), we will not look at the numbers of what they are in world space coordinates, as doing so

  • Will not give us any insight

  • Will distract us from thinking clearly about what’s happening

  • As an example, figure out the world space coordinate of the upper rights corner of the paddle after it has been translated, and ask yourself what that means and what insight did you gain?

The animation above shows multiple steps, shown now without animation.

Modelspace of Paddle 1

Paddle 1's Modelspace

Paddle 1’s Modelspace

Vector

Coordinates

a

(1,3)

b

(-1,3)

c

(-1,-3)

d

(1,-3)

Modelspace of Paddle 1 Superimposed on Worldspace after the translation

Paddle 1’s graph paper gets translated -9 units in the x direction, and some number of units in the y direction, 0 during the first frame, based off of user input. The origin is translated, and the graph paper comes with it, onto which you can plot the vertices. Notice that the coordinate system labels below the plot and to the left of the plot is unchanged. That is world space, which has not changed.

Paddle 1's Modelspace Superimposed on World Space

Paddle 1’s Modelspace Superimposed on World Space

Vector

Coordinates (modelspace)

Coordinates (worldspace)

a

(1,3)

(1,3) + (9,3) = (-8,5)

b

(-1,3)

(-1,3) + (9,3) = (-10,5)

c

(-1,-3)

(-1,-3) + (9,3) = (-10,-1)

d

(1,-3)

(1,-3) + (9,3) = (-8,-1)

Paddle 1’s vertices in WorldSpace Coordinates

Paddle 1's Vertices in World Space

Paddle 1’s Vertices in World Space.

Vector

Coordinates (worldspace)

a

(-8,5)

b

(-10,5)

c

(-10,-1)

d

(-8,-1)

Now that the transformation has happened, the vertices are all in world space. You could calculate their values in world space, but that will not give you any insight. The only numbers that matter for insight as that the entire graph paper of modelspace, which originally was the same as world space, has changed, bringing the vertices along with it.

Same goes for Paddle 2’s modelspace, relative to its translation, which are different values.

Modelspace of Paddle 2

Paddle 1's Modelspace

Paddle 2’s Modelspace

Vector

Coordinates

a

(1,3)

b

(-1,3)

c

(-1,-3)

d

(1,-3)

Modelspace of Paddle 2 Superimposed on Worldspace after the translation

Paddle 1's Modelspace Superimposed on World Space

Paddle 2’s Modelspace Superimposed on World Space

Vector

Coordinates (modelspace)

Coordinates (worldspace)

a

(1,3)

(1,3) + (9,-4) = (10,-1)

b

(-1,3)

(-1,3) + (9,-4) = (8,-1)

c

(-1,-3)

(-1,-3) + (9,-4) = (8,-7)

d

(1,-3)

(1,-3) + (9,-4) = (10,-7)

Paddle 2’s vertices in WorldSpace Coordinates

Paddle 1's Vertices in World Space

Paddle 2’s Vertices in World Space.

Vector

Coordinates (worldspace)

a

(10,-1)

b

(8,-1)

c

(8,-7)

d

(10,-7)

Scaling

Our paddles are now well outside of NDC, and as such, they would not be displayed, as they would be clipped out. Their values are outside of -1.0 to 1.0. All we will need to do to convert them from world space to NDC is divide each component, x and y, by 10.

As a demonstration of how scaling works, let’s make an object’s width twice as large, and height three times as large. (The author tried doing the actual scaling of 1/10 in an animated gif, and it looked awful, therefore a different scaling gif is showed here, but the concept is the same).

We can expand or shrink the size of an object by “scale”ing each component of the vertices by some coefficient.

Modelspace

Modelspace

Modelspace Superimposed on World Space

Modelspace Superimposed on World Space

Worldspace

Worldspace. Don’t concern yourself with what the numbers are.

Our global space is -10 to 10 in both dimensions, and to get it into NDC, we need to scale by dividing by 10

Demo 06

Demo 06

\[\begin{split}\begin{bmatrix} x_{w} \\ y_{w} \end{bmatrix} = \vec{f}_{p1}^{w}( \begin{bmatrix} x_{p1} \\ y_{p1} \end{bmatrix}) = \begin{bmatrix} x_{p1} \\ y_{p1} \end{bmatrix} + \begin{bmatrix} {p1}_{x} \\ {p1}_{y} \end{bmatrix}\end{split}\]

where x_p1, y_p1 are the modelspace coordinates of the paddle’s vertices, and where p1_center_x_worldspace, p1_center_y_worldspace, are the offset from the world space’s origin to the center of the paddle, i.e. the translation.

\[\begin{split}\begin{bmatrix} x_{w} \\ y_{w} \end{bmatrix} = \vec{f}_{p2}^{w} ( \begin{bmatrix} x_{p2} \\ y_{p2} \end{bmatrix}) = \begin{bmatrix} x_{p2} \\ y_{p2} \end{bmatrix} + \begin{bmatrix} {p2}_{x} \\ {p2}_{y} \end{bmatrix}\end{split}\]

Now, the coordinates for paddle 1 and for paddle 2 are in world space, and we need the match to take any world space coordinates and convert them to NDC.

\[\begin{split}\begin{bmatrix} x_{ndc} \\ y_{ndc} \end{bmatrix} = \vec{f}_{w}^{ndc} ( \begin{bmatrix} x_{w} \\ y_{w} \end{bmatrix}) = 1/10 * \begin{bmatrix} x_{w} \\ y_{w} \end{bmatrix}\end{split}\]

Modelviewprojection comes with a math library, the 2D version is named “mathutils2d.py”. The main class in this module is “Vector2D”, which has two components: and x value, and a y value. To add a vector2d to another one on the right hand side of the ‘+’ symbol, we just add the respective components together, and create a new Vector2D.

src/modelviewprojection/mathutils2d.py
28@dataclasses.dataclass
29class Vector2D(mu1d.Vector1D):
30    y: float  #: The y-component of the 2D Vector

In a Python class, we can overload the ‘+’ symbol, to make objects addable, by implementing the modelviewprojection.mathutils1d.Vector1D.__add__() method.

src/modelviewprojection/mathutils1d.py
32    def __add__(self, rhs: typing.Self) -> typing.Self:
src/modelviewprojection/mathutils1d.py
61        return Vector1D(x=(self.x + rhs.x))

We can also model the opposite procedure, subtraction, by implementing the modelviewprojection.mathutils.Vector.__sub__() method.

src/modelviewprojection/mathutils.py
281    def __sub__(self, rhs):
src/modelviewprojection/mathutils.py
296        return self + -rhs

In our graphics code, instead of using “a+b”, we’ll use a more descriptive name: “translate”, which is implemented using the addition symbol. But a few things to note, modelviewprojection.mathutils.translate() is a function on the mathutils module, not a method on Vector2D class, and it’s wrapped in a class named “InvertibleFunction”

src/modelviewprojection/mathutils.py
246def translate(b: T) -> InvertibleFunction[T]:
247    def f(vector: T) -> T:
248        return vector + b
249
250    def f_inv(vector: T) -> T:
251        return vector - b
252
253    return InvertibleFunction[T](f, f_inv)

Notice in particular that the “b” parameter is passed as an argument to “translate”, but the function for translating, named “f”, and the inverse of “f” named “f_inv”, take a Vector2D. This is because we will be translating many Vector2Ds using the same amount.

Invertible functions are stored in pairs, with the “active” function being the first one passed to the constructor. So for translate above, the adding of the Vector2Ds will be the function, but InvertibleFunction holds onto the second function, for later use to be able to undo the function’s application.

tests/test_mathutils2d.py
163def test_translate():
164    fn: mu.InvertibleFunction[mu2d.Vector2D] = mu.translate(
165        mu2d.Vector2D(x=2.0, y=3.0)
166    )
167    fn_inv: mu.InvertibleFunction[mu2d.Vector2D] = mu.inverse(fn)
168
169    input_output_pairs = [
170        [[0.0, 0.0], [2.0, 3.0]],
171        [[1.0, 0.0], [3.0, 3.0]],
172        [[0.0, 1.0], [2.0, 4.0]],
173    ]
174
175    for input_val, output_val in input_output_pairs:
176        wrap_vec2_test(fn, input_val, output_val)
177        wrap_vec2_test(fn_inv, output_val, input_val)
178
179

The above is a unit test that shows how the translate function can be used. We call “translate”, a function which takes a translate amount, both in the x direction and the y direction, but we have not yet specified what needs to be translated by that amount. “translate” returns an InvertibleFunction, which is Callable[Vector2D, Vector2D]. Callable[Vector2D, Vector2D] is a type which is a function that takes a Vector2D as input, and returns a Vector2D (in this case, the output is the input, translated by Vector2D(x=2.0, y=3.0).

On the next 3 lines, we call the function t, passing in a Vector2D to be translated, and we test if the result is equal to the specified amount. (“approx”, is a function from the pytest module, which when tested for equality, returns true if the two floating point numbers under comparison are “close enough”).

We then define a function t_inv, by calling “inverse” on function “t”. We then see that composing t_inv and t results in no transformation.

Here’s how InvertibleFunction is implemented:

src/modelviewprojection/mathutils.py
 24# Define a generic type variable
 25T = typing.TypeVar("T")
 26
 27
 28@dataclasses.dataclass
 29class InvertibleFunction(typing.Generic[T]):
 30    """
 31    Class that wraps a function and its
 32    inverse function.  The function takes
 33    type T as it's argument and it's evaluation
 34    results in a value of type T.
 35    """
 36
 37    func: typing.Callable[[T], T]  #: The wrapped function
 38    inverse: typing.Callable[[T], T]  #: The inverse of the wrapped function
 39
 40    def __call__(self, x: T) -> T:
 41        """
 42        Execute a function with the given value.
 43
 44        Args:
 45            func (typing.Callable[[T], T]): A function that takes a value of type T
 46                                     and returns a value of the same type T.
 47            value (T): The input value to pass to the function
 48        Returns:
 49            T: The result of calling func(value). Will be the same type as the
 50                input value.
 51        Raises:
 52            Nothing
 53        Example:
 54            >>> from modelviewprojection.mathutils import InvertibleFunction
 55            >>> from modelviewprojection.mathutils import inverse
 56            >>> def f(x):
 57            ...     return 2 + x
 58            ...
 59            >>> def f_inv(x):
 60            ...     return x - 2
 61            ...
 62            >>> foo = InvertibleFunction(func=f, inverse=f_inv)
 63            >>> foo # doctest: +ELLIPSIS
 64            InvertibleFunction(func=<function f at 0x...>, inverse=<function f_inv at 0x...>)
 65            >>> foo(5)
 66            7
 67            >>> inverse(foo) # doctest: +ELLIPSIS
 68            InvertibleFunction(func=<function f_inv at 0x...>, inverse=<function f at 0x...>)
 69            >>> inverse(foo)(foo(5))
 70            5
 71        """
 72        return self.func(x)
 73
 74
 75def inverse(f: InvertibleFunction[T]) -> InvertibleFunction[T]:
 76    """
 77    Get the inverse of the InvertibleFunction
 78
 79    Args:
 80        f: InvertibleFunction[T]: A function with it's associated inverse
 81           function.
 82    Returns:
 83        InvertibleFunction[T]: The Inverse of the function
 84           function.
 85    Raises:
 86        Nothing
 87    Example:
 88        >>> from modelviewprojection.mathutils import InvertibleFunction
 89        >>> from modelviewprojection.mathutils import inverse
 90        >>> def f(x):
 91        ...     return 2 + x
 92        ...
 93        >>> def f_inv(x):
 94        ...     return x - 2
 95        ...
 96        >>> foo = InvertibleFunction(func=f, inverse=f_inv)
 97        >>> foo # doctest: +ELLIPSIS
 98        InvertibleFunction(func=<function f at 0x...>, inverse=<function f_inv at 0x...>)
 99        >>> foo(5)
100        7
101        >>> inverse(foo) # doctest: +ELLIPSIS
102        InvertibleFunction(func=<function f_inv at 0x...>, inverse=<function f at 0x...>)
103        >>> inverse(foo)(foo(5))
104        5
105    """
106
107    return InvertibleFunction(f.inverse, f.func)

Just as Python allows an object to override the ‘+’ and ‘-’ syntax, in Python, any object can be treated as a function, by implementing the “__call__” method

Back to method’s on the Vector2D class. We can also define scaling of a Vector2D, by implementing multiplication of Vector2D’s by a scalar, meaning a real number that scaled the Vector2D by the same amount in all directions. We do this by implementing the ‘__mul__’ and ‘__rmul__’ methods, where __rmul__ just means that this object is on the right hand side of the multiplication.

src/modelviewprojection/mathutils2d.py
66    def __mul__(self, scalar: float) -> typing.Self:
67        """
68        Multiply the Vector2D by a scalar number
69
70        Let :math:`\\vec{a} = \\begin{pmatrix} a_x \\\\ a_y \\end{pmatrix}` and constant scalar :math:`s`:
71
72        .. math::
73
74             s*\\vec{a} = \\begin{pmatrix} s*a_x \\\\ s*a_y \\end{pmatrix}
75
76        Args:
77            rhs (Vector2D): The scalar to be multiplied to the Vector's component
78                            subtraction symbol
79        Returns:
80            Vector2D: The Vector2D that represents scalar times the amount of the input Vector2D
81
82        Raises:
83            Nothing
84        Example:
85            >>> from modelviewprojection.mathutils2d import Vector2D
86            >>> a = Vector2D(x=2.0, y=3.0)
87            >>> a * 4
88            Vector2D(x=8.0, y=12.0)
89        """
90        return Vector2D(x=(self.x * scalar), y=(self.y * scalar))
91

Just like we made a top level invertible function called “translate” for addition, we are going to do the same for multiplication, and call it “uniform_scale”. Notice in particular that the scalar is passed as an argument to modelviewprojection.mathutils.uniform_scale(), but the function for scaling “f”, and the inverse of “f” named “f_inv”, take a Vector2D. This is because we will be scaling many Vector2Ds using the same scaling factor.

src/modelviewprojection/mathutils.py
258def uniform_scale(m: float) -> InvertibleFunction[T]:
259    def f(vector: T) -> T:
260        return vector * m
261
262    def f_inv(vector: T) -> T:
263        if m == 0.0:
264            raise ValueError("Not invertible.  Scaling factor cannot be zero.")
265
266        return vector * (1.0 / m)
267
268    return InvertibleFunction[T](f, f_inv)
  • NEW – Add the ability to scale a vector, to stretch or to shrink

src/modelviewprojection/demo06.py
 93paddle1: Paddle = Paddle(
 94    vertices=[
 95        mu2d.Vector2D(x=-1.0, y=-3.0),
 96        mu2d.Vector2D(x=1.0, y=-3.0),
 97        mu2d.Vector2D(x=1.0, y=3.0),
 98        mu2d.Vector2D(x=-1.0, y=3.0),
 99    ],
100    color=colorutils.Color3(r=0.578123, g=0.0, b=1.0),
101    position=mu2d.Vector2D(-9.0, 0.0),
102)
103
104paddle2: Paddle = Paddle(
105    vertices=[
106        mu2d.Vector2D(x=-1.0, y=-3.0),
107        mu2d.Vector2D(x=1.0, y=-3.0),
108        mu2d.Vector2D(x=1.0, y=3.0),
109        mu2d.Vector2D(x=-1.0, y=3.0),
110    ],
111    color=colorutils.Color3(r=1.0, g=1.0, b=0.0),
112    position=mu2d.Vector2D(9.0, 0.0),
113)
  • paddles are using modelspace coordinates instead of NDC

src/modelviewprojection/demo06.py
118def handle_movement_of_paddles() -> None:
119    global paddle1, paddle2
120
121    if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS:
122        paddle1.position.y -= 1.0
123    if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS:
124        paddle1.position.y += 1.0
125    if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS:
126        paddle2.position.y -= 1.0
127    if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS:
128        paddle2.position.y += 1.0
129
130
  • Movement code needs to happen in modelspace’s units.

Code

The Event Loop

src/modelviewprojection/demo06.py
138while not glfw.window_should_close(window):
139    while (
140        glfw.get_time()
141        < time_at_beginning_of_previous_frame + 1.0 / TARGET_FRAMERATE
142    ):
143        pass
144    time_at_beginning_of_previous_frame = glfw.get_time()
145
146    glfw.poll_events()
147
148    width, height = glfw.get_framebuffer_size(window)
149    GL.glViewport(0, 0, width, height)
150    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
151
152    draw_in_square_viewport()
153    handle_movement_of_paddles()

Rendering Paddle 1

src/modelviewprojection/demo06.py
157    GL.glColor3f(*iter(paddle1.color))
158
159    GL.glBegin(GL.GL_QUADS)
160    for p1_v_ms in paddle1.vertices:
161        fn: mu.InvertibleFunction[mu2d.Vector2D] = mu.compose(
162            [mu.uniform_scale(1.0 / 10.0), mu.translate(paddle1.position)]
163        )
164        paddle1_vector_ndc: mu2d.Vector2D = fn(p1_v_ms)
165        GL.glVertex2f(paddle1_vector_ndc.x, paddle1_vector_ndc.y)
166
167    GL.glEnd()
Paddle 1's Modelspace

Paddle 1’s Modelspace

Paddle 1's Modelspace Superimposed on World Space

Paddle 1’s Modelspace Superimposed on World Space

Paddle 1's Modelspace Superimposed on World Space

Reset coordinate system.

The coordinate system now resets back to the coordinate system specified on the left and below. Now, we must scale everything by 1/10. I have not included a picture of that here. Scaling happens relative to the origin, so the picture would be the same, just with different labels on the bottom and on the left.

Rendering Paddle 2

src/modelviewprojection/demo06.py
171    GL.glColor3f(*iter(paddle2.color))
172
173    GL.glBegin(GL.GL_QUADS)
174    for p2_v_ms in paddle2.vertices:
175        fn: mu.InvertibleFunction[mu2d.Vector2D] = mu.compose(
176            [mu.uniform_scale(1.0 / 10.0), mu.translate(paddle2.position)]
177        )
178        paddle2_vector_ndc: mu2d.Vector2D = fn(p2_v_ms)
179        GL.glVertex2f(paddle2_vector_ndc.x, paddle2_vector_ndc.y)
180    GL.glEnd()
Paddle 2's Modelspace

Paddle 2’s Modelspace

Paddle 2's Modelspace Superimposed on World Space

Paddle 2’s Modelspace Superimposed on World Space

Paddle 2's Modelspace Superimposed on World Space

Reset coordinate system.

The coordinate system is reset. Now scale everything by 1/10. I have not included a picture of that here. Scaling happens relative to the origin, so the picture would be the same, just with different labels on the bottom and on the left.

src/modelviewprojection/demo06.py
185    glfw.swap_buffers(window)