import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
Scene, camera and renderer
A three.js application needs at least a scene, a camera and a renderer:
import * as THREE from 'three';
const camera = new THREE.PerspectiveCamera(fovCamera, window.innerWidth/window.innerHeight, frustumNear, frustumFar);
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({antialias: true})
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
Scene
A Scene inherits from Object3D and extends it with some properties of which the most interesting ones are:
.background (which is a color, a texture, or a CubeTexture or equirectangular texture for a skybox.
.fog
A scene is (typically?) rendered by a renderer (WebGLRenderer or WebGPURenderer (or CanvasRenderer? or others?))
The objects of a scene are arranged hierarchically in a scene graph.
Camera
Abstract base class for cameras.
The most frequently used derived classes are PerspectiveCamera and OrthographicCamera.
Although I have seen examples where a camera is explicitely added to a scene, it is apparently not necessary to do so. (because the influence of the camara is being taken care of with in the line renderer.render(scene, camera).
It's worth noting that a camera can be added to an object such as a car driving through a scene.
For performance reasons, a camera has a frustum (represented by a Frustum object). Objects outside the frustum are not rendered.
Constructing a perspective camera
A «full screen» camera is typically created like so:
const camera = new THREE.PerspectiveCamera(
45, // field of view (fov)
window.innerWidth / window.innerHeight, // aspect
0.1, 10000 // near, far
);
lookAt
camera.lookAt(new THREE.Vector3(x, y, z));
camera.lookAt(mesh_abc.position);
cameraHelper
An instance of a cameraHelper uses line segments to visualize the frustum of a camera.
const camHlp = new THREE.CameraHelper(camera);
scene.add(camHlp);
In the render loop:
camHlp.update();
TODO
Sprite objects are planes that always face towards the camera.
WebGLRenderer
An instance of a WebGLRenderer renders a scene using a camera.
See also the WebGPURenderer class.
WebGLRenderer inherits from no other class.
domElement
One of the parameters that the constructor of WebGLRenderer accepts is canvas.
If not provided, the canvas is created with createCanvasElement (defined in src/utils.js) which creates a HTMLCanvasElement (i. e. a <canvas>) on which the renderer draws («renders») the scene.
BufferGeometry objects store information (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes) in buffers (typed arrays).
This makes them generally faster than standard Geometries, at the cost of being somewhat harder to work with.
All geometries seem to inherit from BufferGeometry.
BufferGeometry inherits from EventDispatcher (not from Object3D, but has the member property _obj which is an Object3D).
Classes that inherit from PolyhedronGeometry include
DodecahedronGeometry
IcosahedronGeometry
OctahedronGeometry
TetrahedronGeometry
WireframeGeometry
Compare with classes that inherit from Material which seem to have an attribute wireframe that can be set to true.
Vertex normals
Vertex normals are used by the shader to
determine light reflection
assist in applying textures
provide information how pixels are lighted, shaded and colored
VertexNormalsHelpers (which inherits from LineSegments) visualizes an object's vertex normals.
See also the BufferGeometry method computeVertexNormal().
Triangles
The shape of a geometry is basically created from triangles
If a triangle is looked at its front side, its vertices appear in counterclockwise order («winding order»).
The .side property of a material specifies which side needs to be drawn and can be set to THREE.FrontSide (the default), THREE.BackSide and THREE.DoubleSide.
Material
A material describes an object's surface properties (so it directly influences how it looks like).
Material inherits from EventDispatcher.
Some materials include
MeshBasicMaterial (not affected by lights)
MeshStandardMaterial. The two important properties of this matierial are roughness and metalness.
MeshPhongMaterial (More advanced than the Lambert material (light is calculated per pixel rather than per vertex), used for shiny-looking surfaces, is affected by lights). An important property of this material is shininess (0 … 100).
ShadowMaterial (A transparent material that shows shadows cast on it)
MeshDepthMaterial
MeshDistanceMaterial (used internally for implementing shadow mapping)
MeshMatcapMaterial (defined by a MatCap or Lit Sphere texture)
MeshNormalMaterial (normal vectors mapped to (RGB) colors)
PointsMaterial (The default material used by Points)
ShaderMaterial (The material is rendered is a custom shader written in GLSL (which is run on the GPU))
SpriteMaterial (Used by Sprite objects)
TODO MeshPhysicalMaterial inherits from MeshStandardMaterial, MeshPhysicalNodeMaterial from MeshStandardNodeMaterial, MeshSSSNodeMaterial from MeshPhysicalNodeMaterial, RawShaderMaterial from ShaderMaterial
Remember to add a light if using materials that are affected by light!
Note that setting the emissive property to a color on either a MeshLambertMaterial or a MeshPhongMaterial and setting the color to black (and ishininess to 0 for MeshPhongMaterial) ends up looking just like the MeshBasicMaterial
LineBasicMaterial
LineBasicMaterial has the property linewidth but, due to limitations of the OpenGL Core Profile with the WebGL renderer, on most platforms this value will be 1 regardless of the set value.
Shader program
A material seems to be connected with a shader program (see the material's callback onBeforeCompile)
Mesh
A mesh is an object that applies a material to a geometry.
A material and/or a geometry can be used for multiple meshes.
A mesh inherits from Object3D and thus records the following attributes of an object relative to its parent in the scene:
position
orientation
scale
The mesh can then be inserted into a scene (for example scene.add()) and then be moved around
Classes that inherit from Mesh include
LineSegments2
Adds arbitrary line widths and the possibility to change widths to world unit. Line2 extends LineSegments2 and allows to create polylines.
InstancedMesh
Used for instanced rendering, i. e. if multiple objects with the same geometry and material but different world transformations (including color?) are placed into a scene. In such scenarios, using InstancedMesh reduces the number of draw calls and thus improves the rendering performance. Compare with BatchedMesh.
BatchedMesh
Used to render objects with the same material but different geometries and world coordinates. Compare with InstancedMesh.
Of which I found nothing in the docs or the examples. Apparently, it's deprecated.
MorphBlendMesh
MeshPostProcessingMaterial
VOXMesh
Refractor
Reflector
Note that objects such as MeshStandardMaterial, MeshPhongMaterial, MeshBasicMaterial etc. inherit from Material despite their names.
See also the LOD (Level of Detail) class which shows more or less details of a mesh depending on its distance from the camera.
TODO: InstancedMesh. Is this related to InstancedBufferGeometry?
Text and fonts
TextGeometry
A TextGeometry (found in /examples/jsm/geometries) creates a ExtrudeGeometry from a 3D font (which must first be loaded) and a string.
The 3D font can be loaded with an instance of a FontLoader.
A TextGeometry inherits from ExtrudeGeometry
Constructor
The constructor of a TextGeometry takes a string (the text to be rendered) and some options (of which font one seems to be the crucial one):
const txt = 'Hello world!';
const font = … // An object that is ultimately created by new Font(...)
const txtGeom = new TextGeometry(txt, {
font : font,
depth : 0.07,
// height : …
size : 0.34 , // Size of the text
curveSegments : 12 , // Number of points on the curves
bevelEnabled : false, // Indicates if bevel is enabled
bevelThickness: 0.5 , // How deep into text the bevel goes
bevelSize : 0.01 , // How far from text outline (including bevelOffset) is bevel
bevelOffset : 1 , // How far from text outline (including bevelOffset) is bevel
bevelSegments : 5 , // ???
});
Creating Font objects
A Font object can be created directly with FontLoader or indirectly with TTFLoader
FontLoader
const loader = new FontLoader();
font_path = '…';
loader.load(font_path, function (font) { // Note that the Font object is internally created by FontLoader
const geometry = new TextGeometry(text, {font: font, … });
…
});
TTFLoader
const loader = new TTFLoader();
font_path = '…';
loader.load(font_path, function (data) {
const font = new Font(data); // Note the explicit construction of a Font object
const geometry = new TextGeometry(text, {font: font, … });
…
});
The data object which is passed to the function that is given to load is a JSON object with the following top-level keys:
glyphs
familyName
ascender
descender
underlinePosition
underlineThickness
boundingBox
resolution
original_font_information
Apparently, the data object is constructed by opentype.js.
An array of connected Curve objects. Path inherits from CurvePath.
NURBSCurve
Overrides getPoint and getTangent.
TorusKnotCurve
CurvePath
A CurvePath inherits from Curve
A CurvePath is an array of connected Curve objects (stored in the member curves) which retains the API of Curve.
Path
Path is 2D path representation which provides methods for creating paths and contours of 2D shapes similar to the 2D Canvas API.
A Path inherits from CurvePath.
Shape
Shape defines an arbitrary 2d shape plane using paths with optional holes.
This object can be used with ExtrudeGeometry, ShapeGeometry, to get points, or to get triangulated faces.
An array of Shape objects is returned by a FontLoader.
A Shape inherits from Path.
Loader
Classes that inherit from Loader include
AMFLoader
AnimationLoader
AudioLoader
BufferGeometryLoader
BVHLoader
reads BVH files and outputs a single Skeleton and an AnimationClip. Compare with MDDLoader
ColladaLoader
CompressedTextureLoader
Abstract Base class to block based textures loader (dds, pvr, …). Sub classes have to implement the parse() method which will be used in load(). Such subclasses include DDSLoader, KTXLoader and PVRLoader. Compare with DataTextureLoader.
CubeTextureLoader
Internally uses the ImageLoader class.
DataTextureLoader
Abstract Base class to load generic binary textures formats. Sub classes have to implement the parse() method which will be used in load(). Such subclasses include TGALoader, EXRLoader, RGBELoader, TIFFLoader and RGBMLoader. Compare with CompressedTextureLoader.
DRACOLoader
FBXLoader
Loads an FBX file whose version must be greater or equal to 7.0 and the content in ASCII or binary format greater than or equal to 6400
FileLoader
FontLoader
Loads a font in JSON format. The loaded font is returned as an array of Shape objects. Compare with TTFLoader.
GCodeLoader
Load gcode files usually used for 3D printing or CNC applications. Gcode files are composed by commands used by machines to create objects.
Internally used by the TextureLoader, CubeTextureLoader and ObjectLoader classes.
KMZLoader
KTX2Loader
KTX is a container format for various GPU texture formats. The loader supports Basis Universal GPU textures, which can be quickly transcoded to a wide variety of GPU texture compression formats, as well as some uncompressed DataTexture and Data3DTexture formats. (See KTX, DFD and Basis HDR)
MDD is a special binary format that stores a position for every vertex in a model for every frame in an animation. Similar to BVH, it can be used to transfer animation data between different 3D applications or engines. Compare with BVHLoader
MTLLoader
Loads a Wavefront .mtl file which specifies materials
NodeLoader
NRRDLoader
ObjectLoader
Internally uses the ImageLoader class.
OBJLoader
PCDLoader
PDBLoader
PLYLoader
Loads a PLY (Polygon File Format or Standard Triangle Format) ASCII file
Rhino3dmLoader
STLLoader
Loads STL ASCII files which are created by Solidworks and other CAD programs. The loader returns a non-indexed buffer geomery.
SVGLoader
TDSLoader
TextureLoader
Loads a Texture. Uses ImageLoader internally for loading files.
ThreeMFLoader
3D Manufacturing Format of which this loader supports 3D Models, Object resources (Meshes and Components) and Material Resources (Base Materials). 3MF Materials and Properties Extension are only partially supported
TTFLoader
Loads TTF files and converts them into typeface JSON that can be used directly to create THREE.Font objects. Requires opentype.js to be included in the project. Compare with FontLoader.
scene = new THREE.Scene();
scene.background = new THREE.Color(0x2f0b03);
Fog
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x000000, 250, 1400);
BufferAttribute
Classes that inherit from BufferAttribute wrap typed arrays: the constructor of BufferAttribute expects the first parameter to be a typed parameter.
The derived classes' constructors can be given a regular JavaScript array as these constructors call the parent's constructor with new …Array (see for example the Float16BufferAttribute constructor.
Object3D is the base class for most objects in three.js. Object3D itself inherits from EventDispatcher.
Every instance of an Object3D object has an associated matrix (Matrix4) which defines the object's transformations: position, rotation and scale.
An object's matrix-transformation is relativ to the object's parent object. The transformation relative to the world can be obtained with obj.matrixWorld.
The perfect choice for first person 3D games. The implementation is based on the Pointer Lock WebAPI.
ArcballControls
Control the camera by a virtual trackball
TransformControls
Used to transform objects in 3D space by adapting a similar interaction model of DCC tools like Blender. Unlike other controls, it is not intended to transform the scene's camera.
TrackballControls
Similar to OrbitControls, but does not maintain a constant camera up vector.
FirstPersonControls
An alternative implementation of FlyControls
DragControls
Drag and drop interactions
OrbitControls
OrbitControls allows the camera to orbit around a center; performs orbiting, dollying (zooming), and panning. Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
If the observer looks at the origin from a positive z coordinate and positive x coordinates increase towards the right side, then positive y coordinates increase upwards.
The AxesHelper class draws three lines from the origin to the positive coordinates with the X-axes being red, the Y-axes being green and the Z-axes being blue.
BufferAttribute.js - The BufferAttribute class stores data for an attribute (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes ) associated with a BufferGeometry, which allows for more efficient passing of data to the GPU.
BufferGeometry.js
Clock.js - Uses performance.now to keep track of time. An alternative to Clock is Timer.
EventDispatcher.js
GLBufferAttribute.js - A buffer attribute class that does not construct a VBO (Vertex Buffer Object?), but allows to alter an already created VBO. This class does not inherit from BufferAttribute (or any other class).
InstancedBufferAttribute.js - The class InstancedBufferAttribute inherits from BufferAttribute
InstancedBufferGeometry.js
InstancedInterleavedBuffer.js - An instanced version of an InterleavedBuffer (from which it also inherits)
InterleavedBuffer.js - The adjective interleaved indicates that multiple attributes, possibly of different types, (e.g., position, normal, uv, color) are packed into a single array buffer.
InterleavedBufferAttribute.js
Layers.js - See below
Object3D.js
Raycaster.js
RenderTarget.js
Uniform.js - Global GLSL variables that are passed to shader programs
UniformsGroup.js
Layers
A Layers object assigns an Object3D to 1 or more of 32 layers numbered 0 to 31
Internally the layers are stored as a bit mask, and by default all Object3D instances are a member of layer 0.
Layers can be used to control visibility: an object must share a layer with a camera to be visible when that camera's view is rendered.
All classes that inherit from Object3D have an Object3D.layers property which is an instance of this class.
Raycaster
The Raycaster class allows to select objects (meshes, lines and/or point etc.) with the mouse.
Line3.js - A geometric line segment represented by a start and end point.
MathUtils.js
Matrix2.js
Matrix3.js
Matrix4.js
Plane.js - A two dimensional surface that extends infinitely in 3d space, represented in Hessian normal form by a unit length normal vector and a constant.
Quaternion.js - Quaternion, used in three.js to represent rotations.
Ray.js - Used by Raycaster
Sphere.js - Which is used, for example, to represent certain objects' bounding spheres
import * as THREE from 'three';
import { TrackballControls } from 'three-addons';
import { GUI } from 'three-libs/lil-gui.module.min.js';
…
console.log(THREE.REVISION);
LineLoop inherits from Line but is rendered with gl.LINE_LOOP instead of gl.LINE_STRIP.
lil-gui
lil-gui makes a floating panel for controllers on the web.
lil-gui is a drop-in replacement for dat.gui (which is no longer maintained) in most projects.
World unit
What is a world unit.
AnimationMixer
AnimationMixer is a player for animations on a particular object in the scene. When multiple objects in the scene are animated independently, one AnimationMixer may be used for each object.
Backend
The two classes WebGLBackend and WebGPUBackend, which inherit from Backend.
renderer.setClearColor() - scene.background
Compare renderer.setClearColor() with scene.background.