Refactor
This post is part of a course on geometric modeling at the Summer Liberal Arts Institute for Computer Science held at Carleton College in 2021.
Reorganizing your code to make it easier to understand and easier to update is called refactoring. Let’s refactor your code by organizing it into two separate files: one to hold your rendering code and one to hold your shape drawing code. By the end of the course, we’re going to have a lot of code for writing shapes. Our renderer won’t change nearly so much. You’ll save yourself some headache by separating them.
Follow these steps to refactor your project:
- Create a new file named
shapes.js
. - Import your
shapes.js
script so that it loads beforerender.js
by adding a newscript
tag inindex.html
. - Inside
shapes.js
create a new function that looks like this:Use your actual definitions forfunction generateSquareDonut() { const positions = [ /* ... */ ]; const triangles = [ /* ... */ ]; return {positions, triangles}; }
positions
andtriangles
that are inrender.js
. - Replace the
positions
andtriangles
definitions inrender.js
with a call to your shape generator function:const shape = generateSquareDonut();
- Update your
geometry
configuration to use theshape
object instead of the two stray arrays:let geometry = new THREE.BufferGeometry(); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(shape.positions), 3)); geometry.setIndex(shape.triangles);
When you reload the page, everything should still work. When you add new shapes from here on out, start by adding to shapes.js
a new function that is self-contained and named meaningfully, like this:
function generateLincolnSilhouette() {
const positions = [ /* ... */ ];
const triangles = [ /* ... */ ];
return {positions, triangles};
}
Then in render.js
, change only the shape generator that you call. The rest of the rendering code stays the same.