Skip to content

This repository contains a collection of P5 sketches that render torus knots with a shader

License

Notifications You must be signed in to change notification settings

kfahn22/torus_knots

Repository files navigation

3D Knots

This repository contains a collection of P5 sketches that render torus knots, which you can think of as a string wrapped around a donut. More formally:

A (p,q)-torus knot is obtained by looping a string through the hole of a torus p times with q revolutions before joining its ends. Wolfram MathWorld

My journey with rendering knots started with Daniel Shiffman's 3D knot coding challenge. He renders a knot using the following code, incrementing beta each time through the draw loop.

let r = 100 * (0.8 + 1.2 * sin(6.0 * beta));
let theta = 2 * beta;
let phi = 0.6 * PI * sin(12 * beta);
let x = r * cos(phi) * cos(theta);
let y = r * cos(phi) * sin(theta);
let z = r * sin(phi);

3D Knot

I have used Daniel's code, but I have replaced the code to calculate the cartesian coordinates. Equations from Lee Stemkoski at Parameterized Knots.

let phi = p * beta;
let theta = q * beta;
x = r * cos(theta) * (sc + cos(phi));
y = r * sin(theta) * (sc + cos(phi));
z = r * sin(phi);

Example: (8,9) torus knot

(8,9) torus knot

Here I have rendered three different torus knots with different radii.

Knotty and Nice Animation

In this version, I am rendering multiple tori at the same time and using Dave Pagurek's FrameBuffer library to add blur. Thanks to Daniel Shiffman for his short showing how to render a perfect GIF loop using the new p5.js saveGif() function.

2D Mathematical Rose

If z = -sin(phi) is used instead of z = r * sin(phi);, you get a 2D curve. If the parameter c = 0, you get a mathematical rose.

let k = n / d;
let r = 70 * (c + cos(k * theta));
let x = r * cos(theta);
let y = r * sin(theta);

I am not sure what the official name for this is, but I am calling it a polar donut. Rendered with
n = 7, d = 2, c = 1.25

Polar Donut

Torus Knots Rendered with a shader

I have also rendered the torus knot with a shader in P5.js. The Art of Code's YouTube tutorial Torus Knots explained! was very helpful in explaining how to render a torus knot in shadertoy, which I ported to P5.js. I have three different versions, which are sequentially loaded in the p5 sketch.

In this torus knot, we are rotating a square instead of a circle which is how we obtain a ribbon effect.

Solomon's Seal / Cinquefoil torus knot (5,2) Solomon's seal torus knot

(3,1) torus knot Braided Ring

(7,2) torus knot Torus Wreath

About

This repository contains a collection of P5 sketches that render torus knots with a shader

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published