Outline

In this lab you will:

  1. Understand the concepts and complexity of transformations in 3D spaces
  2. Understand order of transformations
  3. Get started with 3D transformations in code

Introduction

Moving around in 3D spaces appears natural to us, until we try to describe this motion in code! As you work through the lab, it’ll be helpful to have the p5.js Transform references open in a new tab so you can refer to it easily.

Coordinate Systems

When coding in 2D, 1 unit == 1 pixel wide or 1 pixel high. How wide/tall/deep is “1” unit in a 3D scene?

As discussed last week - we have 3 dimensions. The width of the web browser window defines the maximum dimension width in the “Z zero plane”. X == 0 is in the middle of the window!

Similarly, the height of the web browser window defines the maximum dimension height in the “Z zero plane”, and Y == 0 is in the middle of the window. Note, as for 2D graphics, increasing Y values go down, decreasing Y values go up. This is counter-intuitive and runs contrary to most other 3D graphics systems.

Increasing Z values move towards to viewer, and decreasing Z values move away from the viewer. This makes the coordinate system “left-handed” with the middle finger pointing down.

When you use models imported from other systems, you need to be aware of the sizes (how big is the model in units in the original system), the handedness, and the fact that Y points down. You will need to scale and reflect or rotate your imported model to match p5.js.

Transformations

What is a transformation?

What do we mean by Transform and transformation? What are all the meanings of these word? Which words do you associate with transformation?

Choose one of the following: (A) Write down all the meanings of the word “transformation”. (B) Think of, and write as a word cloud, all the words you can that you associate with the word “transformation”. (C) Find a precise mathematical definition of “transformation” [4 minutes]

Share your findings with the class. We will have a discussion about the meanings of transformation, fitting as much as we can into a time box of 5 minutes.

Types of transformation in 3D computer graphics

Let’s take a closer look into what we mean by transformation through some concrete examples.

Think: If a Transformation is a function that maps a set X to itself: $ f \left( X \right) \rightarrow X $ then how is a rotation a transformation?

Lost in Translation

A translation is a transformation that changes the values of each point through adding a single vector to each point. The effect is that the object as a whole is moved in space without changing shape. Moving objects in space is also called translating an object.

Scale it up

A scale transformation uses a matrix multiplication to change the size of an object. This can be applied in 1 dimension (stretching/squeezing an object along an axis), 2 dimensions (stretching/squeezing along 2 axes), or in 3 dimensions (retain original shape, but increase/decrease in size).

Shearing

A shear transformation is a non-uniform translation which creates a “slant” to an object’s geometry.

Reflection

A reflection transformation creates a mirror image of the original object when reflected along an axis. This is achieved through a matrix multiplication.

Spin it around

Rotations are the most complex of the transformations. Rotations also use a matrix multiplication to transform all the points of an object such that they describe a circular motion around a point with a given axis of rotation (a vector that points in a specific direction).

Uses of Transformation

  • Translation can be used for positioning objects in a scene - setting up a static scene.
  • Scale can be used to create boxes of many different sizes: useful for fast geometry generation from a basic box(1,1,1);
  • Rotation can be used for orientating objects in a scene
  • Animation: all transforms can be changed over time to animate a scene

Order of Transformation

In Mathematics we use BODMAS, BODMAS, PEMDAS or PEDMAS to talk about the order of operations. We have learned that addition before multiplication creates a different result to addition after multiplication. Transformations use matrix addition and multiplication. So - it should be expected that the order of operations matters: and it does. We will explore order of transformation in the coding activities.

Coding Transformations

Let’s explore code for 3D transformations.

Fork, Clone and open this lab’s template repository:

Run the code. What do you see?

Note: We will also look at different types of models and materials in today’s lab. This model is standard geometry, known as Suzanne, from Blender 3D. You can see that the model is not oriented as might be expected.

debug mode: Displays standard axes to help you visualise and a ground grid plane.

orbitControl: Enables easy interaction for rotation of view, zooming and panning of camera.

Scale it right

To make the model bigger - you can scale it:

  scale(2,2,2); // scale by a factor of 2 in all dimensions

To invert the model, you can achieve this using a scale factor of -1 to flip coordinates.

  scale(1,-1,1); // mirror in the Y axis using a -1 scale factor

Think: Can you complete the 2 operations in a single function call?

Order, order…

Let’s animate the model to more easily illustrate order of operations

  rotateY(frameCount * 0.01);

Now try adding the translate:

  translate(0,0,200);

Try putting it before the rotate. Before the scale.

Now add a rotation around X or Z. Add another translate.

What did you find? How does this impact your thinking?

There are other ways to create transformations: you can manipulate the transformation matrix directly through applyMatrix(). This enables you to build sophisticated transformation strategies, including using quaternions for rotations.

More Models

The lab template has included a range of models for you to investigate.

p5.js 3D models

All of the p5.js 3D models include the optional parameters of detailX and detailY which determine how many subdivisions are applied the the geometry. More divisions == smoother geometry, but higher rendering times.

  • box: a rectangular prism (width, height, depth)
  • plane: a zero thickness 2D plane (width, height)
  • sphere: (radius)
  • cylinder: (radius, height, dx, dy, topCap, bottomCap) topCap an bottomCap are booleans which define whether or not the cylinder has 2 closed ends, 1, closed end or no closed ends
  • cone: (radius, height, dx, dy, cap)
  • ellipsoid: (radiusX, radiusY, radiusZ)
  • torus: (radius, tubeRadius)

Importing Geometry

As well as the basic 3D objects provided by p5.js there is also “loadModel()” - as you have already discovered - it loads a prebuilt model constructed using a 3D graphics program.

  • loadModel(model filepath on web server): loads a geometry file of a supported type (OBJ or STL). Always load geometries in the preload() function.
  • model(modelObject): render the model

Code Generated Geometry

You can also build geometry directly from code! As an example, myGeometry has been created using code which generates a wavy plane: this could be useful for generating landscapes, etc.

NOTE: support for all aspects of geometry may depend on browser and browser version.

Material Things

To illustrate and illuminate our models we need to add colour and texture to the models.

Provided Materials

p5.js provides some basic materials for creating your virtual world.

  • normalMaterial(): a normal material is for debugging purposes despite its colourful nature. Normal materials are not affected by light. Surfaces facing the X-axis tend to blue, facing the Y-axis tend to green and facing the Z-axis tend to blue.

The other materials are impacted differently by light and can be used together to create more sophisticated materials. The standard materials use shading methods that do not cast shadows. Shadows is an advanced topic that will be left for you to explore.

  • ambientMaterial(r,g,b): a material which responds to ambient light (ambient light is non-directional)
  • emissiveMaterial(r,g,b): a material which appears to emit light of a given colour. Light is not actually emitted. Emitted light DOES NOT reflect any type of light source.
  • specularMaterial(r,g,b): a material which reflects both ambient light (where colour matches the ambient light source) and directional, point and spot lights (for the colour of those lights). The intensity and “shininess” are controlled by the shininess() function.
  • shininess(level): the amount of gloss of a specular material (level is a number between 1 and an undefined maximum)

Imported Images

You can import and image and use it to cover the outside of a model. The image must be imported in preLoad, and then the texture() function is used to apply the image as a texture over the model.

  • loadImage(image filepath): loads an image file. Always load images in the preload function.

  • textureMode(NORMAL IMAGE): determines the way the texture will be represented on the model, requiring the model to have the dimensions of the image (IMAGE) or to use normalised values (NORMAL). IMAGE is the default.
  • textureWrap(CLAMP REPEAT MIRROR): determines how the texture will repeat/wrap on a surface. CLAMP is the default. REPEAT and MIRROR are only available if your image size is a square and is a power of 2 (3232, 6464, 128128, 256256, 512*512, …)

Code Generated Materials

This is an advanced topic and will not be covered today. It involves the use of shaders. Shaders use a Shader language (in this case, GLSL - the OpenGL Shader Language). The shader requires a vertex shader (which transform geometry positions into 3D drawing coordinates) and a fragment shader (which compute the renderings of a surface’s colors and other attributes).

Remember to commit your code and push it up to Gitlab.

Summary

Congratulations! In this lab you:

  1. Explored the concepts of 3D coordinate systems and transformations
  2. Coded 3D transformations
  3. Further explored 3D geometries and standard p5.js materials

Additional Learning Resources

p5.js

coding train

bars search caret-down plus minus arrow-right times arrow-up creative-commons creative-commons-by creative-commons-nc creative-commons-sa