Lab: Torus

How to 3D

Chapter 3: Meshes

Lab: Torus

In this chapter, you've been learning how to represent triangle meshes and generate algorithmic shapes like cones, cylinders, and spheres. Let's apply this knowledge by writing a renderer that generates a torus—a donut.

Form a group of no more than three people. Host, open your top-level repository directory in Visual Studio Code and run npm run dev to start up a web server. Then open the command palette via View / Command Palette and enter Live Share: Start Collaboration Session. Share the link with your group.

Torus

Your challenge is to render a spinnable torus colored by its normals. Complete these steps:

Clone the transfit renderer to make a new renderer named torus. We use transfit because it deals with the viewport distortion and has no HTML inputs.
Change the center variable in resizeCanvas to [0, 0] and size to 1.
Define a new prefab function named torus. Have it accept four parameters: the inner radius, the outer radius, the longitude count, and the latitude count. Generate the torus geometry using a similar approach to how we generated a sphere. Unlike the sphere, wrap both latitude and longitude when forming triangles. Outline an algorithm before writing code.
Render the torus as indexed triangles.
Color the torus by its normals.
Alter the vertex shader to apply only a rotation, not a scale or translate.
Use the radians to rotate the vertex around the x-axis instead of the z-axis. When you rotate a vertex around the x-axis, its x-coordinate doesn't change. It's yz-coordinates are calculated using very similar formulas to rotation around the z-axis. The only difference is that the yz-coordinates are used instead of the xy-coordinates.
Rotate the torus when the left and right keys are pressed. Add a key listener in initialize with code like this:
window.addEventListener('keydown', event => {
  if (event.key === 'ArrowLeft') {
    // ...
  }
});
window.addEventListener('keydown', event => {
  if (event.key === 'ArrowLeft') {
    // ...
  }
});

Submission

To receive credit for your lab work, follow these steps:

Non-host, download the torus folder before the host closes the session.
Share a video of your spinning torus in a post in the #lab channel in Discord. No voiceover is necessary. Tag your group members with @.
Push your code to your individual GitHub repository that your instructor made for you.

Only labs submitted on time will be granted credit. Late labs or forgot-to-submits are not accepted because Monday at noon is when your instructor has time to grade.

← Reading glTF