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
58@dataclasses.dataclass
59class Vector2D(mu1d.Vector1D):
60    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
51    def __add__(self, rhs: "mu.Vector") -> "Vector1D":
src/modelviewprojection/mathutils1d.py
80        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
56    def __sub__(self, rhs: typing.Self) -> typing.Self:
src/modelviewprojection/mathutils.py
71        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
326def translate(b: Vector) -> InvertibleFunction:
327    def f(vector: Vector) -> Vector:
328        return vector + b
329
330    def f_inv(vector: Vector) -> Vector:
331        return vector - b
332
333    return InvertibleFunction(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
164def test_translate():
165    fn: mu2d.InvertibleFunction = mu2d.translate(mu2d.Vector2D(x=2.0, y=3.0))
166    fn_inv: mu2d.InvertibleFunction = mu2d.inverse(fn)
167
168    input_output_pairs = [
169        [[0.0, 0.0], [2.0, 3.0]],
170        [[1.0, 0.0], [3.0, 3.0]],
171        [[0.0, 1.0], [2.0, 4.0]],
172    ]
173
174    for input_val, output_val in input_output_pairs:
175        wrap_vec2_test(fn, input_val, output_val)
176        wrap_vec2_test(fn_inv, output_val, input_val)
177
178

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
106@dataclasses.dataclass
107class InvertibleFunction:
108    """
109    Class that wraps a function and its
110    inverse function.  The function takes
111    type T as it's argument and it's evaluation
112    results in a value of type T.
113    """
114
115    func: typing.Callable[[Vector], Vector]  #: The wrapped function
116    inverse: typing.Callable[
117        [Vector], Vector
118    ]  #: The inverse of the wrapped function
119
120    def __call__(self, x: Vector) -> Vector:
121        """
122        Execute a function with the given value.
123
124        Args:
125            func (typing.Callable[[Vector], Vector]): A function that takes a value of type Vector
126                                     and returns a value of the same type Vector.
127            value (Vector): The input value to pass to the function
128        Returns:
129            Vector: The result of calling func(value). Will be the same type as the
130                input value.
131        Raises:
132            Nothing
133        Example:
134            >>> from modelviewprojection.mathutils import InvertibleFunction
135            >>> from modelviewprojection.mathutils import inverse
136            >>> def f(x):
137            ...     return 2 + x
138            ...
139            >>> def f_inv(x):
140            ...     return x - 2
141            ...
142            >>> foo = InvertibleFunction(func=f, inverse=f_inv)
143            >>> foo # doctest: +ELLIPSIS
144            InvertibleFunction(func=<function f at 0x...>, inverse=<function f_inv at 0x...>)
145            >>> foo(5)
146            7
147            >>> inverse(foo) # doctest: +ELLIPSIS
148            InvertibleFunction(func=<function f_inv at 0x...>, inverse=<function f at 0x...>)
149            >>> inverse(foo)(foo(5))
150            5
151        """
152        return self.func(x)
153
154
155def inverse(f: InvertibleFunction) -> InvertibleFunction:
156    """
157    Get the inverse of the InvertibleFunction
158
159    Args:
160        f: InvertibleFunction: A function with it's associated inverse
161           function.
162    Returns:
163        InvertibleFunction: The Inverse of the function
164           function.
165    Raises:
166        Nothing
167    Example:
168        >>> from modelviewprojection.mathutils import InvertibleFunction
169        >>> from modelviewprojection.mathutils import inverse
170        >>> def f(x):
171        ...     return 2 + x
172        ...
173        >>> def f_inv(x):
174        ...     return x - 2
175        ...
176        >>> foo = InvertibleFunction(func=f, inverse=f_inv)
177        >>> foo # doctest: +ELLIPSIS
178        InvertibleFunction(func=<function f at 0x...>, inverse=<function f_inv at 0x...>)
179        >>> foo(5)
180        7
181        >>> inverse(foo) # doctest: +ELLIPSIS
182        InvertibleFunction(func=<function f_inv at 0x...>, inverse=<function f at 0x...>)
183        >>> inverse(foo)(foo(5))
184        5
185    """
186
187    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
 97    def __mul__(self, scalar: float) -> "Vector2D":
 98        """
 99        Multiply the Vector2D by a scalar number
100
101        Let :math:`\\vec{a} = \\begin{bmatrix} a_x \\\\ a_y \\end{bmatrix}` and constant scalar :math:`s`:
102
103        .. math::
104
105             s*\\vec{a} = \\begin{bmatrix} s*a_x \\\\ s*a_y \\end{bmatrix}
106
107        Args:
108            rhs (Vector2D): The scalar to be multiplied to the Vector's component
109                            subtraction symbol
110        Returns:
111            Vector2D: The Vector2D that represents scalar times the amount of the input Vector2D
112
113        Raises:
114            Nothing
115        Example:
116            >>> from modelviewprojection.mathutils2d import Vector2D
117            >>> a = Vector2D(x=2.0, y=3.0)
118            >>> a * 4
119            Vector2D(x=8.0, y=12.0)
120        """
121        return Vector2D(x=(self.x * scalar), y=(self.y * scalar))
122

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
338def uniform_scale(m: float) -> InvertibleFunction:
339    def f(vector: Vector) -> Vector:
340        return vector * m
341
342    def f_inv(vector: Vector) -> Vector:
343        if m == 0.0:
344            raise ValueError("Not invertible.  Scaling factor cannot be zero.")
345
346        return vector * (1.0 / m)
347
348    return InvertibleFunction(f, f_inv)
  • NEW – Add the ability to scale a vector, to stretch or to shrink

src/modelviewprojection/demo06.py
 92paddle1: Paddle = Paddle(
 93    vertices=[
 94        mu2d.Vector2D(x=-1.0, y=-3.0),
 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    ],
 99    color=colorutils.Color3(r=0.578123, g=0.0, b=1.0),
100    position=mu2d.Vector2D(-9.0, 0.0),
101)
102
103paddle2: Paddle = Paddle(
104    vertices=[
105        mu2d.Vector2D(x=-1.0, y=-3.0),
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    ],
110    color=colorutils.Color3(r=1.0, g=1.0, b=0.0),
111    position=mu2d.Vector2D(9.0, 0.0),
112)
  • paddles are using modelspace coordinates instead of NDC

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

Code

The Event Loop

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

Rendering Paddle 1

src/modelviewprojection/demo06.py
156    GL.glColor3f(*iter(paddle1.color))
157
158    GL.glBegin(GL.GL_QUADS)
159    for p1_v_ms in paddle1.vertices:
160        fn: mu2d.InvertibleFunction = mu2d.compose(
161            [mu2d.uniform_scale(1.0 / 10.0), mu2d.translate(paddle1.position)]
162        )
163        paddle1_vector_ndc: mu2d.Vector2D = fn(p1_v_ms)
164        GL.glVertex2f(paddle1_vector_ndc.x, paddle1_vector_ndc.y)
165
166    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
170    GL.glColor3f(*iter(paddle2.color))
171
172    GL.glBegin(GL.GL_QUADS)
173    for p2_v_ms in paddle2.vertices:
174        fn: mu2d.InvertibleFunction = mu2d.compose(
175            [mu2d.uniform_scale(1.0 / 10.0), mu2d.translate(paddle2.position)]
176        )
177        paddle2_vector_ndc: mu2d.Vector2D = fn(p2_v_ms)
178        GL.glVertex2f(paddle2_vector_ndc.x, paddle2_vector_ndc.y)
179    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
184    glfw.swap_buffers(window)