Manual

Next Steps

Reference

Animation / Tracks

Audio

Cameras

Constants

Core

Core / BufferAttributes

Extras

Extras / Core

Extras / Curves

Geometries

Helpers

Lights

Lights / Shadows

Loaders

Loaders / Managers

Materials

Math

Math / Interpolants

Objects

Renderers

Renderers / Shaders

Renderers / WebXR

Scenes

Textures

Addons

Controls

Lines

Post-Processing

Exporters

Misc

Modifiers

ConvexHull

Utils

WebXR

Developer Reference

Installation

Project structure

Every three.js project needs at least one HTML file to define the webpage, and a JavaScript file to run your three.js code. The structure and naming choices below aren't required, but will be used throughout this guide for consistency.

Now that we've set up the basic project structure, we need a way to run the project locally and access it through a web browser. Installation and local development can be accomplished with npm and a build tool, or by importing three.js from a CDN. Both options are explained in the sections below.

Option 1: Install with NPM and a build tool

Development

Installing from the npm package registry and using a build tool is the recommended approach for most users — the more dependencies your project needs, the more likely you are to run into problems that the static hosting cannot easily resolve. With a build tool, importing local JavaScript files and npm packages should work out of the box, without import maps.

  1. Install Node.js. We'll need it to load manage dependencies and to run our build tool.
  2. Install three.js and a build tool, Vite, using a terminal in your project folder. Vite will be used during development, but it isn't part of the final webpage. If you prefer to use another build tool, that's fine — we support modern build tools that can import ES Modules.

    # three.js npm install --save three # vite npm install --save-dev vite
  3. From your terminal, run: npx vite
  4. If everything went well, you'll see a URL like http://localhost:5173 appear in your terminal, and can open that URL to see your web application.

The page will be blank — you're ready to create a scene.

If you want to learn more about these tools before you continue, see:

Production

Later, when you're ready to deploy your web application, you'll just need to tell Vite to run a production build — npx vite build. Everything used by the application will be compiled, optimized, and copied into the dist/ folder. The contents of that folder are ready to be hosted on your website.

Option 2: Import from a CDN

Development

Installing without build tools will require some changes to the project structure given above.

  1. We imported code from 'three' (an npm package) in main.js, and web browsers don't know what that means. In index.html we'll need to add an import map defining where to get the package. Put the code below inside the <head></head> tag, after the styles.

    <script type="importmap"> { "imports": { "three": "https://cdn.jsdelivr.net/npm/three@<version>/build/three.module.js", "three/addons/": "https://cdn.jsdelivr.net/npm/three@<version>/examples/jsm/" } } </script>

    Don't forget to replace <version> with an actual version of three.js, like "v0.149.0". The most recent version can be found on the npm version list.

  2. We'll also need to run a local server to host these files at URL where the web browser can access them. While it's technically possible to double-click an HTML file and open it in your browser, important features that we'll later implement, do not work when the page is opened this way, for security reasons.

    Install Node.js, then run serve to start a local server in the project's directory:

    npx serve .
  3. If everything went well, you'll see a URL like http://localhost:3000 appear in your terminal, and can open that URL to see your web application.

The page will be blank — you're ready to create a scene.

Many other local static servers are available — some use different languages instead of Node.js, and others are desktop applications. They all work basically the same way, and we've provided a few alternatives below.

More local servers

Command Line

Command line local servers run from a terminal window. The associated programming language may need to be installed first.

  • npx http-server (Node.js)
  • npx five-server (Node.js)
  • python -m SimpleHTTPServer (Python 2.x)
  • python -m http.server (Python 3.x)
  • php -S localhost:8000 (PHP 5.4+)

GUI

GUI local servers run as an application window on your computer, and may have a user interface.

Code Editor Plugins

Some code editors have plugins that spawn a simple server on demand.

Production

When you're ready to deploy your web application, push the source files to your web hosting provider — no need to build or compile anything. The downside of that tradeoff is that you'll need to be careful to keep the import map updated with any dependencies (and dependencies of dependencies!) that your application requires. If the CDN hosting your dependencies goes down temporarily, your website will stop working too.

IMPORTANT: Import all dependencies from the same version of three.js, and from the same CDN. Mixing files from different sources may cause duplicate code to be included, or even break the application in unexpected ways.

Addons

Out of the box, three.js includes the fundamentals of a 3D engine. Other three.js components — such as controls, loaders, and post-processing effects — are part of the addons/ directory. Addons do not need to be installed separately, but do need to be imported separately.

The example below shows how to import three.js with the OrbitControls and GLTFLoader addons. Where necessary, this will also be mentioned in each addon's documentation or examples.

import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; const controls = new OrbitControls( camera, renderer.domElement ); const loader = new GLTFLoader();

Some excellent third-party projects are available for three.js, too. These need to be installed separately — see Libraries and Plugins.

Next Steps

You're now ready to create a scene.

Creating a scene

The goal of this section is to give a brief introduction to three.js. We will start by setting up a scene, with a spinning cube. A working example is provided at the bottom of the page in case you get stuck and need help.

Before we start

If you haven't yet, go through the Installation guide. We'll assume you've already set up the same project structure (including index.html and main.js), have installed three.js, and are either running a build tool, or using a local server with a CDN and import maps.

Creating the scene

To actually be able to display anything with three.js, we need three things: scene, camera and renderer, so that we can render the scene with camera.

main.js —

import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement );

Let's take a moment to explain what's going on here. We have now set up the scene, our camera and the renderer.

There are a few different cameras in three.js. For now, let's use a PerspectiveCamera.

The first attribute is the field of view. FOV is the extent of the scene that is seen on the display at any given moment. The value is in degrees.

The second one is the aspect ratio. You almost always want to use the width of the element divided by the height, or you'll get the same result as when you play old movies on a widescreen TV - the image looks squished.

The next two attributes are the near and far clipping plane. What that means, is that objects further away from the camera than the value of far or closer than near won't be rendered. You don't have to worry about this now, but you may want to use other values in your apps to get better performance.

Next up is the renderer. In addition to creating the renderer instance, we also need to set the size at which we want it to render our app. It's a good idea to use the width and height of the area we want to fill with our app - in this case, the width and height of the browser window. For performance intensive apps, you can also give setSize smaller values, like window.innerWidth/2 and window.innerHeight/2, which will make the app render at quarter size.

If you wish to keep the size of your app but render it at a lower resolution, you can do so by calling setSize with false as updateStyle (the third argument). For example, setSize(window.innerWidth/2, window.innerHeight/2, false) will render your app at half resolution, given that your <canvas> has 100% width and height.

Last but not least, we add the renderer element to our HTML document. This is a <canvas> element the renderer uses to display the scene to us.

"That's all good, but where's that cube you promised?" Let's add it now.

const geometry = new THREE.BoxGeometry( 1, 1, 1 ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const cube = new THREE.Mesh( geometry, material ); scene.add( cube ); camera.position.z = 5;

To create a cube, we need a BoxGeometry. This is an object that contains all the points (vertices) and fill (faces) of the cube. We'll explore this more in the future.

In addition to the geometry, we need a material to color it. Three.js comes with several materials, but we'll stick to the MeshBasicMaterial for now. All materials take an object of properties which will be applied to them. To keep things very simple, we only supply a color attribute of 0x00ff00, which is green. This works the same way that colors work in CSS or Photoshop (hex colors).

The third thing we need is a Mesh. A mesh is an object that takes a geometry, and applies a material to it, which we then can insert to our scene, and move freely around.

By default, when we call scene.add(), the thing we add will be added to the coordinates (0,0,0). This would cause both the camera and the cube to be inside each other. To avoid this, we simply move the camera out a bit.

Rendering the scene

If you copied the code from above into the main.js file we created earlier, you wouldn't be able to see anything. This is because we're not actually rendering anything yet. For that, we need what's called a render or animation loop.

function animate() { renderer.render( scene, camera ); } renderer.setAnimationLoop( animate );

This will create a loop that causes the renderer to draw the scene every time the screen is refreshed (on a typical screen this means 60 times per second). If you're new to writing games in the browser, you might say "why don't we just create a setInterval ?" The thing is - we could, but requestAnimationFrame which is internally used in WebGLRenderer has a number of advantages. Perhaps the most important one is that it pauses when the user navigates to another browser tab, hence not wasting their precious processing power and battery life.

Animating the cube

If you insert all the code above into the file you created before we began, you should see a green box. Let's make it all a little more interesting by rotating it.

Add the following code right above the renderer.render call in your animate function:

cube.rotation.x += 0.01; cube.rotation.y += 0.01;

This will be run every frame (normally 60 times per second), and give the cube a nice rotation animation. Basically, anything you want to move or change while the app is running has to go through the animation loop. You can of course call other functions from there, so that you don't end up with an animate function that's hundreds of lines.

The result

Congratulations! You have now completed your first three.js application. It's simple, but you have to start somewhere.

The full code is available below and as an editable live example. Play around with it to get a better understanding of how it works.

index.html —

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>My first three.js app</title> <style> body { margin: 0; } </style> </head> <body> <script type="module" src="/main.js"></script> </body> </html>

main.js —

import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setAnimationLoop( animate ); document.body.appendChild( renderer.domElement ); const geometry = new THREE.BoxGeometry( 1, 1, 1 ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const cube = new THREE.Mesh( geometry, material ); scene.add( cube ); camera.position.z = 5; function animate() { cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render( scene, camera ); }

WebGL compatibility check

Even though this is becoming less and less of a problem, some devices or browsers may still not support WebGL 2. The following method allows you to check if it is supported and display a message to the user if it is not. Import the WebGL support detection module, and run the following before attempting to render anything.

import WebGL from 'three/addons/capabilities/WebGL.js'; if ( WebGL.isWebGL2Available() ) { // Initiate function or other initializations here animate(); } else { const warning = WebGL.getWebGL2ErrorMessage(); document.getElementById( 'container' ).appendChild( warning ); }

Drawing lines

Let's say you want to draw a line or a circle, not a wireframe Mesh. First we need to set up the renderer, scene and camera (see the Creating a scene page).

Here is the code that we will use:

const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 500 ); camera.position.set( 0, 0, 100 ); camera.lookAt( 0, 0, 0 ); const scene = new THREE.Scene();

Next thing we will do is define a material. For lines we have to use LineBasicMaterial or LineDashedMaterial.

//create a blue LineBasicMaterial const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );

After material we will need a geometry with some vertices:

const points = []; points.push( new THREE.Vector3( - 10, 0, 0 ) ); points.push( new THREE.Vector3( 0, 10, 0 ) ); points.push( new THREE.Vector3( 10, 0, 0 ) ); const geometry = new THREE.BufferGeometry().setFromPoints( points );

Note that lines are drawn between each consecutive pair of vertices, but not between the first and last (the line is not closed.)

Now that we have points for two lines and a material, we can put them together to form a line.

const line = new THREE.Line( geometry, material );

All that's left is to add it to the scene and call render.

scene.add( line ); renderer.render( scene, camera );

You should now be seeing an arrow pointing upwards, made from two blue lines.

Creating text

There are often times when you might need to use text in your three.js application - here are a couple of ways that you can do so.

1. DOM + CSS

Using HTML is generally the easiest and fastest manner to add text. This is the method used for descriptive overlays in most three.js examples.

You can add content to a

<div id="info">Description</div>

and use CSS markup to position absolutely at a position above all others with a z-index especially if you are running three.js full screen.

#info { position: absolute; top: 10px; width: 100%; text-align: center; z-index: 100; display:block; }

2. Use CSS2DRenderer or CSS3DRenderer

Use these renderers to draw high-quality text contained in DOM elements to your three.js scene. This is similar to 1. except that with these renderers elements can be integrated more tightly and dynamically into the scene.

3. Draw text to canvas and use as a Texture

Use this method if you wish to draw text easily on a plane in your three.js scene.

4. Create a model in your favourite 3D application and export to three.js

Use this method if you prefer working with your 3d applications and importing the models to three.js.

5. Procedural Text Geometry

If you prefer to work purely in THREE.js or to create procedural and dynamic 3D text geometries, you can create a mesh whose geometry is an instance of THREE.TextGeometry:

new THREE.TextGeometry( text, parameters );

In order for this to work, however, your TextGeometry will need an instance of THREE.Font to be set on its "font" parameter. See the TextGeometry page for more info on how this can be done, descriptions of each accepted parameter, and a list of the JSON fonts that come with the THREE.js distribution itself.

Examples

WebGL / geometry / text
WebGL / shadowmap

If Typeface is down, or you want to use a font that is not there, there's a tutorial with a python script for blender that allows you to export text to Three.js's JSON format: http://www.jaanga.com/2012/03/blender-to-threejs-create-3d-text-with.html

6. Bitmap Fonts

BMFonts (bitmap fonts) allow batching glyphs into a single BufferGeometry. BMFont rendering supports word-wrapping, letter spacing, kerning, signed distance fields with standard derivatives, multi-channel signed distance fields, multi-texture fonts, and more. See three-mesh-ui or three-bmfont-text.

Stock fonts are available in projects like A-Frame Fonts, or you can create your own from any .TTF font, optimizing to include only characters required for a project.

Some helpful tools:

7. Troika Text

The troika-three-text package renders quality antialiased text using a similar technique as BMFonts, but works directly with any .TTF or .WOFF font file so you don't have to pregenerate a glyph texture offline. It also adds capabilities including:

  • Effects like strokes, drop shadows, and curvature
  • The ability to apply any three.js Material, even a custom ShaderMaterial
  • Support for font ligatures, scripts with joined letters, and right-to-left/bidirectional layout
  • Optimization for large amounts of dynamic text, performing most work off the main thread in a web worker

Loading 3D models

3D models are available in hundreds of file formats, each with different purposes, assorted features, and varying complexity. Although three.js provides many loaders, choosing the right format and workflow will save time and frustration later on. Some formats are difficult to work with, inefficient for realtime experiences, or simply not fully supported at this time.

This guide provides a workflow recommended for most users, and suggestions for what to try if things don't go as expected.

Before we start

If you're new to running a local server, begin with installation first. Many common errors viewing 3D models can be avoided by hosting files correctly.

Recommended workflow

Where possible, we recommend using glTF (GL Transmission Format). Both .GLB and .GLTF versions of the format are well supported. Because glTF is focused on runtime asset delivery, it is compact to transmit and fast to load. Features include meshes, materials, textures, skins, skeletons, morph targets, animations, lights, and cameras.

Public-domain glTF files are available on sites like Sketchfab, or various tools include glTF export:

If your preferred tools do not support glTF, consider requesting glTF export from the authors, or posting on the glTF roadmap thread.

When glTF is not an option, popular formats such as FBX, OBJ, or COLLADA are also available and regularly maintained.

Loading

Only a few loaders (e.g. ObjectLoader) are included by default with three.js — others should be added to your app individually.

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

Once you've imported a loader, you're ready to add a model to your scene. Syntax varies among different loaders — when using another format, check the examples and documentation for that loader. For glTF, usage with global scripts would be:

const loader = new GLTFLoader(); loader.load( 'path/to/model.glb', function ( gltf ) { scene.add( gltf.scene ); }, undefined, function ( error ) { console.error( error ); } );

See GLTFLoader documentation for further details.

Troubleshooting

You've spent hours modeling an artisanal masterpiece, you load it into the webpage, and — oh no! 😭 It's distorted, miscolored, or missing entirely. Start with these troubleshooting steps:

  1. Check the JavaScript console for errors, and make sure you've used an onError callback when calling .load() to log the result.
  2. View the model in another application. For glTF, drag-and-drop viewers are available for three.js and babylon.js. If the model appears correctly in one or more applications, file a bug against three.js. If the model cannot be shown in any application, we strongly encourage filing a bug with the application used to create the model.
  3. Try scaling the model up or down by a factor of 1000. Many models are scaled differently, and large models may not appear if the camera is inside the model.
  4. Try to add and position a light source. The model may be hidden in the dark.
  5. Look for failed texture requests in the network tab, like "C:\\Path\To\Model\texture.jpg". Use paths relative to your model instead, such as images/texture.jpg — this may require editing the model file in a text editor.

Asking for help

If you've gone through the troubleshooting process above and your model still isn't working, the right approach to asking for help will get you to a solution faster. Post a question on the three.js forum and, whenever possible, include your model (or a simpler model with the same problem) in any formats you have available. Include enough information for someone else to reproduce the issue quickly — ideally, a live demo.

Libraries and Plugins

Listed here are externally developed compatible libraries and plugins for three.js. This list and the associated packages are maintained by the community and not guaranteed to be up to date. If you'd like to update this list make a PR!

Physics

Postprocessing

In addition to the official three.js postprocessing effects, support for some additional effects and frameworks are available through external libraries.

Intersection and Raycast Performance

Path Tracing

File Formats

In addition to the official three.js loaders, support for some additional formats is available through external libraries.

Geometry

3D Text and Layout

Particle Systems

Inverse Kinematics

Game AI

Wrappers and Frameworks

FAQ

Which 3D model format is best supported?

The recommended format for importing and exporting assets is glTF (GL Transmission Format). Because glTF is focused on runtime asset delivery, it is compact to transmit and fast to load.

three.js provides loaders for many other popular formats like FBX, Collada or OBJ as well. Nevertheless, you should always try to establish a glTF based workflow in your projects first. For more information, see loading 3D models.

Why are there meta viewport tags in examples?

<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

These tags control viewport size and scale for mobile browsers (where page content may be rendered at different size than visible viewport).

Safari: Using the Viewport

MDN: Using the viewport meta tag

How can scene scale be preserved on resize?

We want all objects, regardless of their distance from the camera, to appear the same size, even as the window is resized. The key equation to solving this is this formula for the visible height at a given distance: visible_height = 2 * Math.tan( ( Math.PI / 180 ) * camera.fov / 2 ) * distance_from_camera; If we increase the window height by a certain percentage, then what we want is the visible height at all distances to increase by the same percentage. This can not be done by changing the camera position. Instead you have to change the camera field-of-view. Example.

Why is part of my object invisible?

This could be because of face culling. Faces have an orientation that decides which side is which. And the culling removes the backside in normal circumstances. To see if this is your problem, change the material side to THREE.DoubleSide. material.side = THREE.DoubleSide

Why does three.js sometimes return strange results for invalid inputs?

For performance reasons, three.js doesn't validate inputs in most cases. It's your app's responsibility to make sure that all inputs are valid.

Can I use three.js in Node.js?

Because three.js is built for the web, it depends on browser and DOM APIs that don't always exist in Node.js. Some of these issues can be avoided by using shims like headless-gl and jsdom-global, or by replacing components like TextureLoader with custom alternatives. Other DOM APIs may be deeply intertwined with the code that uses them, and will be harder to work around. We welcome simple and maintainable pull requests to improve Node.js support, but recommend opening an issue to discuss your improvements first.

How to update things

All objects by default automatically update their matrices if they have been added to the scene with

const object = new THREE.Object3D(); scene.add( object ); or if they are the child of another object that has been added to the scene: const object1 = new THREE.Object3D(); const object2 = new THREE.Object3D(); object1.add( object2 ); scene.add( object1 ); //object1 and object2 will automatically update their matrices

However, if you know the object will be static, you can disable this and update the transform matrix manually just when needed.

object.matrixAutoUpdate = false; object.updateMatrix();

BufferGeometry

BufferGeometries store information (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes) in buffers - that is, typed arrays. This makes them generally faster than standard Geometries, at the cost of being somewhat harder to work with.

With regards to updating BufferGeometries, the most important thing to understand is that you cannot resize buffers (this is very costly, basically the equivalent to creating a new geometry). You can however update the content of buffers.

This means that if you know an attribute of your BufferGeometry will grow, say the number of vertices, you must pre-allocate a buffer large enough to hold any new vertices that may be created. Of course, this also means that there will be a maximum size for your BufferGeometry - there is no way to create a BufferGeometry that can efficiently be extended indefinitely.

We'll use the example of a line that gets extended at render time. We'll allocate space in the buffer for 500 vertices but draw only two at first, using BufferGeometry.drawRange.

const MAX_POINTS = 500; // geometry const geometry = new THREE.BufferGeometry(); // attributes const positions = new Float32Array( MAX_POINTS * 3 ); // 3 floats (x, y and z) per point geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) ); // draw range const drawCount = 2; // draw the first 2 points, only geometry.setDrawRange( 0, drawCount ); // material const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // line const line = new THREE.Line( geometry, material ); scene.add( line );

Next we'll randomly add points to the line using a pattern like:

const positionAttribute = line.geometry.getAttribute( 'position' ); let x = 0, y = 0, z = 0; for ( let i = 0; i < positionAttribute.count; i ++ ) { positionAttribute.setXYZ( i, x, y, z ); x += ( Math.random() - 0.5 ) * 30; y += ( Math.random() - 0.5 ) * 30; z += ( Math.random() - 0.5 ) * 30; }

If you want to change the number of points rendered after the first render, do this:

line.geometry.setDrawRange( 0, newValue );

If you want to change the position data values after the first render, you need to set the needsUpdate flag like so:

positionAttribute.needsUpdate = true; // required after the first render

If you change the position data values after the initial render, you may need to recompute bounding volumes so other features of the engine like view frustum culling or helpers properly work.

line.geometry.computeBoundingBox(); line.geometry.computeBoundingSphere();

Here is a fiddle showing an animated line which you can adapt to your use case.

Examples

WebGL / custom / attributes
WebGL / buffergeometry / custom / attributes / particles

Materials

All uniforms values can be changed freely (e.g. colors, textures, opacity, etc), values are sent to the shader every frame.

Also GLstate related parameters can change any time (depthTest, blending, polygonOffset, etc).

The following properties can't be easily changed at runtime (once the material is rendered at least once):

  • numbers and types of uniforms
  • presence or not of
    • texture
    • fog
    • vertex colors
    • morphing
    • shadow map
    • alpha test
    • transparent

Changes in these require building of new shader program. You'll need to set

material.needsUpdate = true

Bear in mind this might be quite slow and induce jerkiness in framerate (especially on Windows, as shader compilation is slower in DirectX than OpenGL).

For smoother experience you can emulate changes in these features to some degree by having "dummy" values like zero intensity lights, white textures, or zero density fog.

You can freely change the material used for geometry chunks, however you cannot change how an object is divided into chunks (according to face materials).

If you need to have different configurations of materials during runtime:

If the number of materials / chunks is small, you could pre-divide the object beforehand (e.g. hair / face / body / upper clothes / trousers for a human, front / sides / top / glass / tire / interior for a car).

If the number is large (e.g. each face could be potentially different), consider a different solution, such as using attributes / textures to drive different per-face look.

Examples

WebGL / materials / car
WebGL / webgl_postprocessing / dof

Textures

Image, canvas, video and data textures need to have the following flag set if they are changed:

texture.needsUpdate = true;

Render targets update automatically.

Examples

WebGL / materials / video
WebGL / rtt

Cameras

A camera's position and target is updated automatically. If you need to change

  • fov
  • aspect
  • near
  • far

then you'll need to recompute the projection matrix:

camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();

InstancedMesh

InstancedMesh is a class for conveniently access instanced rendering in three.js. Certain library features like view frustum culling or ray casting rely on up-to-date bounding volumes (bounding sphere and bounding box). Because of the way how InstancedMesh works, the class has its own boundingBox and boundingSphere properties that supersede the bounding volumes on geometry level.

Similar to geometries you have to recompute the bounding box and sphere whenever you change the underlying data. In context of InstancedMesh, that happens when you transform instances via setMatrixAt(). You can use the same pattern like with geometries.

instancedMesh.computeBoundingBox(); instancedMesh.computeBoundingSphere();

SkinnedMesh

SkinnedMesh follows the same principles like InstancedMesh in context of bounding volumes. Meaning the class has its own version of boundingBox and boundingSphere to correctly enclose animated meshes. When calling computeBoundingBox() and computeBoundingSphere(), the class computes the respective bounding volumes based on the current bone transformation (or in other words the current animation state).

How to dispose of objects

One important aspect in order to improve performance and avoid memory leaks in your application is the disposal of unused library entities. Whenever you create an instance of a three.js type, you allocate a certain amount of memory. However, three.js creates for specific objects like geometries or materials WebGL related entities like buffers or shader programs which are necessary for rendering. It's important to highlight that these objects are not released automatically. Instead, the application has to use a special API in order to free such resources. This guide provides a brief overview about how this API is used and what objects are relevant in this context.

Geometries

A geometry usually represents vertex information defined as a collection of attributes. three.js internally creates an object of type WebGLBuffer for each attribute. These entities are only deleted if you call BufferGeometry.dispose(). If a geometry becomes obsolete in your application, execute the method to free all related resources.

Materials

A material defines how objects are rendered. three.js uses the information of a material definition in order to construct a shader program for rendering. Shader programs can only be deleted if the respective material is disposed. For performance reasons, three.js tries to reuse existing shader programs if possible. So a shader program is only deleted if all related materials are disposed. You can indicate the disposal of a material by executing Material.dispose().

Textures

The disposal of a material has no effect on textures. They are handled separately since a single texture can be used by multiple materials at the same time. Whenever you create an instance of Texture, three.js internally creates an instance of WebGLTexture. Similar to buffers, this object can only be deleted by calling Texture.dispose().

If you use an ImageBitmap as the texture's data source, you have to call ImageBitmap.close() at the application level to dispose of all CPU-side resources. An automated call of ImageBitmap.close() in Texture.dispose() is not possible, since the image bitmap becomes unusable, and the engine has no way of knowing if the image bitmap is used elsewhere.

Render Targets

Objects of type WebGLRenderTarget not only allocate an instance of WebGLTexture but also WebGLFramebuffers and WebGLRenderbuffers for realizing custom rendering destinations. These objects are only deallocated by executing WebGLRenderTarget.dispose().

Miscellaneous

There are other classes from the examples directory like controls or post processing passes which provide dispose() methods in order to remove internal event listeners or render targets. In general, it's recommended to check the API or documentation of a class and watch for dispose(). If present, you should use it when cleaning things up.

FAQ

Why can't three.js dispose objects automatically?

This question was asked many times by the community so it's important to clarify this matter. Fact is that three.js does not know the lifetime or scope of user-created entities like geometries or materials. This is the responsibility of the application. For example even if a material is currently not used for rendering, it might be necessary for the next frame. So if the application decides that a certain object can be deleted, it has to notify the engine via calling the respective dispose() method.

Does removing a mesh from the scene also dispose its geometry and material?

No, you have to explicitly dispose the geometry and material via dispose(). Keep in mind that geometries and materials can be shared among 3D objects like meshes.

Does three.js provide information about the amount of cached objects?

Yes. It's possible to evaluate WebGLRenderer.info, a special property of the renderer with a series of statistical information about the graphics board memory and the rendering process. Among other things, it tells you how many textures, geometries and shader programs are internally stored. If you notice performance problems in your application, it's a good idea to debug this property in order to easily identify a memory leak.

What happens when you call dispose() on a texture but the image is not loaded yet?

Internal resources for a texture are only allocated if the image has fully loaded. If you dispose a texture before the image was loaded, nothing happens. No resources were allocated so there is also no need for clean up.

What happens when I call dispose() and then use the respective object at a later point?

That depends. For geometries, materials, textures, render targets and post processing passes the deleted internal resources can be created again by the engine. So no runtime error will occur but you might notice a negative performance impact for the current frame, especially when shader programs have to be compiled. Controls and renderers are an exception. Instances of these classes can not be used after dispose() has been called. You have to create new instances in this case.

How should I manage three.js objects in my app? When do I know how to dispose things?

In general, there is no definite recommendation for this. It highly depends on the specific use case when calling dispose() is appropriate. It's important to highlight that it's not always necessary to dispose objects all the time. A good example for this is a game which consists of multiple levels. A good place for object disposal is when switching the level. The app could traverse through the old scene and dispose all obsolete materials, geometries and textures. As mentioned in the previous section, it does not produce a runtime error if you dispose an object that is actually still in use. The worst thing that can happen is performance drop for a single frame.

Examples that demonstrate the usage of dispose()

WebGL / test / memory
WebGL / test / memory2

How to create VR content

This guide provides a brief overview of the basic components of a web-based VR application made with three.js.

Workflow

First, you have to include VRButton.js into your project.

import { VRButton } from 'three/addons/webxr/VRButton.js';

VRButton.createButton() does two important things: It creates a button which indicates VR compatibility. Besides, it initiates a VR session if the user activates the button. The only thing you have to do is to add the following line of code to your app.

document.body.appendChild( VRButton.createButton( renderer ) );

Next, you have to tell your instance of WebGLRenderer to enable XR rendering.

renderer.xr.enabled = true;

Finally, you have to adjust your animation loop since we can't use our well known window.requestAnimationFrame() function. For VR projects we use setAnimationLoop. The minimal code looks like this:

renderer.setAnimationLoop( function () { renderer.render( scene, camera ); } );

Next Steps

Have a look at one of the official WebVR examples to see this workflow in action.

WebXR / XR / ballshooter
WebXR / XR / cubes
WebXR / XR / dragging
WebXR / XR / paint
WebXR / XR / sculpt
WebXR / VR / panorama_depth
WebXR / VR / panorama
WebXR / VR / rollercoaster
WebXR / VR / sandbox
WebXR / VR / video

How to use post-processing

Many three.js applications render their 3D objects directly to the screen. Sometimes, however, you want to apply one or more graphical effects like Depth-Of-Field, Bloom, Film Grain or various types of Anti-aliasing. Post-processing is a widely used approach to implement such effects. First, the scene is rendered to a render target which represents a buffer in the video card's memory. In the next step one or more post-processing passes apply filters and effects to the image buffer before it is eventually rendered to the screen.

three.js provides a complete post-processing solution via EffectComposer to implement such a workflow.

Workflow

The first step in the process is to import all necessary files from the examples directory. The guide assumes you are using the official npm package of three.js. For our basic demo in this guide we need the following files.

import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; import { GlitchPass } from 'three/addons/postprocessing/GlitchPass.js'; import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

After all files are successfully imported, we can create our composer by passing in an instance of WebGLRenderer.

const composer = new EffectComposer( renderer );

When using a composer, it's necessary to change the application's animation loop. Instead of calling the render method of WebGLRenderer, we now use the respective counterpart of EffectComposer.

function animate() { requestAnimationFrame( animate ); composer.render(); }

Our composer is now ready so it's possible to configure the chain of post-processing passes. These passes are responsible for creating the final visual output of the application. They are processed in order of their addition/insertion. In our example, the instance of RenderPass is executed first, then the instance of GlitchPass and finally OutputPass. The last enabled pass in the chain is automatically rendered to the screen. The setup of the passes looks like so:

const renderPass = new RenderPass( scene, camera ); composer.addPass( renderPass ); const glitchPass = new GlitchPass(); composer.addPass( glitchPass ); const outputPass = new OutputPass(); composer.addPass( outputPass );

RenderPass is normally placed at the beginning of the chain in order to provide the rendered scene as an input for the next post-processing step. In our case, GlitchPass is going to use these image data to apply a wild glitch effect. OutputPass is usually the last pass in the chain which performs sRGB color space conversion and tone mapping. Check out this live example to see it in action.

Built-in Passes

You can use a wide range of pre-defined post-processing passes provided by the engine. They are located in the postprocessing directory.

Custom Passes

Sometimes you want to write a custom post-processing shader and include it into the chain of post-processing passes. For this scenario, you can utilize ShaderPass. After importing the file and your custom shader, you can use the following code to setup the pass.

import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js'; import { LuminosityShader } from 'three/addons/shaders/LuminosityShader.js'; // later in your init routine const luminosityPass = new ShaderPass( LuminosityShader ); composer.addPass( luminosityPass );

The repository provides a file called CopyShader which is a good starting code for your own custom shader. CopyShader just copies the image contents of the EffectComposer's read buffer to its write buffer without applying any effects.

Matrix transformations

Three.js uses matrices to encode 3D transformations---translations (position), rotations, and scaling. Every instance of Object3D has a matrix which stores that object's position, rotation, and scale. This page describes how to update an object's transformation.

Convenience properties and matrixAutoUpdate

There are two ways to update an object's transformation:

  1. Modify the object's position, quaternion, and scale properties, and let three.js recompute the object's matrix from these properties: object.position.copy( start_position ); object.quaternion.copy( quaternion ); By default, the matrixAutoUpdate property is set true, and the matrix will be automatically recalculated. If the object is static, or you wish to manually control when recalculation occurs, better performance can be obtained by setting the property false: object.matrixAutoUpdate = false; And after changing any properties, manually update the matrix: object.updateMatrix();
  2. Modify the object's matrix directly. The Matrix4 class has various methods for modifying the matrix: object.matrix.setRotationFromQuaternion( quaternion ); object.matrix.setPosition( start_position ); object.matrixAutoUpdate = false; Note that matrixAutoUpdate must be set to false in this case, and you should make sure not to call updateMatrix. Calling updateMatrix will clobber the manual changes made to the matrix, recalculating the matrix from position, scale, and so on.

Object and world matrices

An object's matrix stores the object's transformation relative to the object's parent; to get the object's transformation in world coordinates, you must access the object's Object3D.matrixWorld.

When either the parent or the child object's transformation changes, you can request that the child object's matrixWorld be updated by calling updateMatrixWorld().

An object can be transformed via Object3D.applyMatrix4. Note: Under-the-hood, this method relies on Matrix4.decompose, and not all matrices are decomposable in this way. For example, if an object has a non-uniformly scaled parent, then the object's world matrix may not be decomposable, and this method may not be appropriate.

Rotation and Quaternion

Three.js provides two ways of representing 3D rotations: Euler angles and Quaternions, as well as methods for converting between the two. Euler angles are subject to a problem called "gimbal lock," where certain configurations can lose a degree of freedom (preventing the object from being rotated about one axis). For this reason, object rotations are always stored in the object's quaternion.

Previous versions of the library included a useQuaternion property which, when set to false, would cause the object's matrix to be calculated from an Euler angle. This practice is deprecated---instead, you should use the setRotationFromEuler method, which will update the quaternion.

Animation system

Overview

Within the three.js animation system you can animate various properties of your models: the bones of a skinned and rigged model, morph targets, different material properties (colors, opacity, booleans), visibility and transforms. The animated properties can be faded in, faded out, crossfaded and warped. The weight and time scales of different simultaneous animations on the same object as well as on different objects can be changed independently. Various animations on the same and on different objects can be synchronized.

To achieve all this in one homogeneous system, the three.js animation system has completely changed in 2015 (beware of outdated information!), and it has now an architecture similar to Unity/Unreal Engine 4. This page gives a short overview of the main components of the system and how they work together.

Animation Clips

If you have successfully imported an animated 3D object (it doesn't matter if it has bones or morph targets or both) — for example exporting it from Blender with the glTF Blender exporter and loading it into a three.js scene using GLTFLoader — one of the response fields should be an array named "animations", containing the AnimationClips for this model (see a list of possible loaders below).

Each AnimationClip usually holds the data for a certain activity of the object. If the mesh is a character, for example, there may be one AnimationClip for a walkcycle, a second for a jump, a third for sidestepping and so on.

Keyframe Tracks

Inside of such an AnimationClip the data for each animated property are stored in a separate KeyframeTrack. Assuming a character object has a skeleton, one keyframe track could store the data for the position changes of the lower arm bone over time, a different track the data for the rotation changes of the same bone, a third the track position, rotation or scaling of another bone, and so on. It should be clear, that an AnimationClip can be composed of lots of such tracks.

Assuming the model has morph targets (for example one morph target showing a friendly face and another showing an angry face), each track holds the information as to how the influence of a certain morph target changes during the performance of the clip.

Animation Mixer

The stored data forms only the basis for the animations - actual playback is controlled by the AnimationMixer. You can imagine this not only as a player for animations, but as a simulation of a hardware like a real mixer console, which can control several animations simultaneously, blending and merging them.

Animation Actions

The AnimationMixer itself has only very few (general) properties and methods, because it can be controlled by the AnimationActions. By configuring an AnimationAction you can determine when a certain AnimationClip shall be played, paused or stopped on one of the mixers, if and how often the clip has to be repeated, whether it shall be performed with a fade or a time scaling, and some additional things, such crossfading or synchronizing.

Animation Object Groups

If you want a group of objects to receive a shared animation state, you can use an AnimationObjectGroup.

Supported Formats and Loaders

Note that not all model formats include animation (OBJ notably does not), and that only some three.js loaders support AnimationClip sequences. Several that do support this animation type:

Note that 3ds max and Maya currently can't export multiple animations (meaning animations which are not on the same timeline) directly to a single file.

Example

let mesh; // Create an AnimationMixer, and get the list of AnimationClip instances const mixer = new THREE.AnimationMixer( mesh ); const clips = mesh.animations; // Update the mixer on each frame function update () { mixer.update( deltaSeconds ); } // Play a specific animation const clip = THREE.AnimationClip.findByName( clips, 'dance' ); const action = mixer.clipAction( clip ); action.play(); // Play all animations clips.forEach( function ( clip ) { mixer.clipAction( clip ).play(); } );

Color management

What is a color space?

Every color space is a collection of several design decisions, chosen together to support a large range of colors while satisfying technical constraints related to precision and display technologies. When creating a 3D asset, or assembling 3D assets together into a scene, it is important to know what these properties are, and how the properties of one color space relate to other color spaces in the scene.

sRGB colors and white point (D65) displayed in the reference CIE 1931 chromaticity diagram. Colored region represents a 2D projection of the sRGB gamut, which is a 3D volume. Source: Wikipedia

Consider two very common color spaces: SRGBColorSpace ("sRGB") and LinearSRGBColorSpace ("Linear-sRGB"). Both use the same primaries and white point, and therefore have the same color gamut. Both use the RGB color model. They differ only in the transfer functions — Linear-sRGB is linear with respect to physical light intensity. sRGB uses the nonlinear sRGB transfer functions, and more closely resembles the way that the human eye perceives light and the responsiveness of common display devices.

That difference is important. Lighting calculations and other rendering operations must generally occur in a linear color space. However, a linear colors are less efficient to store in an image or framebuffer, and do not look correct when viewed by a human observer. As a result, input textures and the final rendered image will generally use the nonlinear sRGB color space.

ℹ️ NOTICE: While some modern displays support wider gamuts like Display-P3, the web platform's graphics APIs largely rely on sRGB. Applications using three.js today will typically use only the sRGB and Linear-sRGB color spaces.

Roles of color spaces

Linear workflows — required for modern rendering methods — generally involve more than one color space, each assigned to a particular role. Linear and nonlinear color spaces are appropriate for different roles, explained below.

Input color space

Colors supplied to three.js — from color pickers, textures, 3D models, and other sources — each have an associated color space. Those not already in the Linear-sRGB working color space must be converted, and textures be given the correct texture.colorSpace assignment. Certain conversions (for hexadecimal and CSS colors in sRGB) can be made automatically if the THREE.ColorManagement API is enabled before initializing colors:

THREE.ColorManagement.enabled = true;

THREE.ColorManagement is enabled by default.

⚠️ WARNING: Many formats for 3D models do not correctly or consistently define color space information. While three.js attempts to handle most cases, problems are common with older file formats. For best results, use glTF 2.0 (GLTFLoader) and test 3D models in online viewers early to confirm the asset itself is correct.

Working color space

Rendering, interpolation, and many other operations must be performed in an open domain linear working color space, in which RGB components are proportional to physical illumination. In three.js, the working color space is Linear-sRGB.

Output color space

Output to a display device, image, or video may involve conversion from the open domain Linear-sRGB working color space to another color space. This conversion may be performed in the main render pass (WebGLRenderer.outputColorSpace), or during post-processing.

renderer.outputColorSpace = THREE.SRGBColorSpace; // optional with post-processing

⚠️ WARNING: Render targets may use either sRGB or Linear-sRGB. sRGB makes better use of limited precision. In the closed domain, 8 bits often suffice for sRGB whereas ≥12 bits (half float) may be required for Linear-sRGB. If later pipeline stages require Linear-sRGB input, the additional conversions may have a small performance cost.

Custom materials based on ShaderMaterial and RawShaderMaterial have to implement their own output color space conversion. For instances of ShaderMaterial, adding the colorspace_fragment shader chunk to the fragment shader's main() function should be sufficient.

Working with THREE.Color instances

Methods reading or modifying Color instances assume data is already in the three.js working color space, Linear-sRGB. RGB and HSL components are direct representations of data stored by the Color instance, and are never converted implicitly. Color data may be explicitly converted with .convertLinearToSRGB() or .convertSRGBToLinear().

// RGB components (no change). color.r = color.g = color.b = 0.5; console.log( color.r ); // → 0.5 // Manual conversion. color.r = 0.5; color.convertSRGBToLinear(); console.log( color.r ); // → 0.214041140

With ColorManagement.enabled = true set (recommended), certain conversions are made automatically. Because hexadecimal and CSS colors are generally sRGB, Color methods will automatically convert these inputs from sRGB to Linear-sRGB in setters, or convert from Linear-sRGB to sRGB when returning hexadecimal or CSS output from getters.

// Hexadecimal conversion. color.setHex( 0x808080 ); console.log( color.r ); // → 0.214041140 console.log( color.getHex() ); // → 0x808080 // CSS conversion. color.setStyle( 'rgb( 0.5, 0.5, 0.5 )' ); console.log( color.r ); // → 0.214041140 // Override conversion with 'colorSpace' argument. color.setHex( 0x808080, LinearSRGBColorSpace ); console.log( color.r ); // → 0.5 console.log( color.getHex( LinearSRGBColorSpace ) ); // → 0x808080 console.log( color.getHex( SRGBColorSpace ) ); // → 0xBCBCBC

Common mistakes

When an individual color or texture is misconfigured, it will appear darker or lighter than expected. When the renderer's output color space is misconfigured, the entire scene may appear darker (e.g. missing conversion to sRGB) or lighter (e.g. a double conversion to sRGB with post-processing). In each case the problem may not be uniform, and simply increasing/decreasing lighting does not solve it.

A more subtle issue appears when both the input color spaces and the output color spaces are incorrect — the overall brightness levels may be fine, but colors may change unexpectedly under different lighting, or shading may appear more blown-out and less soft than intended. These two wrongs do not make a right, and it's important that the working color space be linear ("scene referred") and the output color space be nonlinear ("display referred").

Further reading

AnimationAction

AnimationActions schedule the performance of the animations which are stored in AnimationClips.

Note: Most of AnimationAction's methods can be chained.

For an overview of the different elements of the three.js animation system see the "Animation System" article in the "Next Steps" section of the manual.

Constructor

AnimationAction( mixer : AnimationMixer, clip : AnimationClip, localRoot : Object3D )

mixer - the AnimationMixer that is controlled by this action.
clip - the AnimationClip that holds the animation data for this action.
localRoot - the root object on which this action is performed.
blendMode - defines how the animation is blended/combined when two or more animations are simultaneously played.

Note: Instead of calling this constructor directly you should instantiate an AnimationAction with AnimationMixer.clipAction since this method provides caching for better performance.

Properties

.blendMode : Number

Defines how the animation is blended/combined when two or more animations are simultaneously played. Valid values are NormalAnimationBlendMode (default) and AdditiveAnimationBlendMode.

.clampWhenFinished : Boolean

If clampWhenFinished is set to true the animation will automatically be paused on its last frame.

If clampWhenFinished is set to false, enabled will automatically be switched to false when the last loop of the action has finished, so that this action has no further impact.

Default is false.

Note: clampWhenFinished has no impact if the action is interrupted (it has only an effect if its last loop has really finished).

.enabled : Boolean

Setting enabled to false disables this action, so that it has no impact. Default is true.

When the action is re-enabled, the animation continues from its current time (setting enabled to false doesn't reset the action).

Note: Setting enabled to true doesn’t automatically restart the animation. Setting enabled to true will only restart the animation immediately if the following condition is fulfilled: paused is false, this action has not been deactivated in the meantime (by executing a stop or reset command), and neither weight nor timeScale is 0.

.loop : Number

The looping mode (can be changed with setLoop). Default is THREE.LoopRepeat (with an infinite number of repetitions)

Must be one of these constants:

THREE.LoopOnce - playing the clip once,
THREE.LoopRepeat - playing the clip with the chosen number of repetitions, each time jumping from the end of the clip directly to its beginning,
THREE.LoopPingPong - playing the clip with the chosen number of repetitions, alternately playing forward and backward.

.paused : Boolean

Setting paused to true pauses the execution of the action by setting the effective time scale to 0. Default is false.

.repetitions : Number

The number of repetitions of the performed AnimationClip over the course of this action. Can be set via setLoop. Default is Infinity.

Setting this number has no effect, if the loop mode is set to THREE.LoopOnce.

.time : Number

The local time of this action (in seconds, starting with 0).

The value gets clamped or wrapped to 0...clip.duration (according to the loop state). It can be scaled relatively to the global mixer time by changing timeScale (using setEffectiveTimeScale or setDuration).

.timeScale : Number

Scaling factor for the time. A value of 0 causes the animation to pause. Negative values cause the animation to play backwards. Default is 1.

Properties/methods concerning timeScale (respectively time) are: getEffectiveTimeScale, halt, paused, setDuration, setEffectiveTimeScale, stopWarping, syncWith, warp.

.weight : Number

The degree of influence of this action (in the interval [0, 1]). Values between 0 (no impact) and 1 (full impact) can be used to blend between several actions. Default is 1.

Properties/methods concerning weight are: crossFadeFrom, crossFadeTo, enabled, fadeIn, fadeOut, getEffectiveWeight, setEffectiveWeight, stopFading.

.zeroSlopeAtEnd : Boolean

Enables smooth interpolation without separate clips for start, loop and end. Default is true.

.zeroSlopeAtStart : Boolean

Enables smooth interpolation without separate clips for start, loop and end. Default is true.

Methods

.crossFadeFrom ( fadeOutAction : AnimationAction, durationInSeconds : Number, warpBoolean : Boolean ) : this

Causes this action to fade in, fading out another action simultaneously, within the passed time interval. This method can be chained.

If warpBoolean is true, additional warping (gradually changes of the time scales) will be applied.

Note: Like with fadeIn/fadeOut, the fading starts/ends with a weight of 1.

.crossFadeTo ( fadeInAction : AnimationAction, durationInSeconds : Number, warpBoolean : Boolean ) : this

Causes this action to fade out, fading in another action simultaneously, within the passed time interval. This method can be chained.

If warpBoolean is true, additional warping (gradually changes of the time scales) will be applied.

Note: Like with fadeIn/fadeOut, the fading starts/ends with a weight of 1.

.fadeIn ( durationInSeconds : Number ) : this

Increases the weight of this action gradually from 0 to 1, within the passed time interval. This method can be chained.

.fadeOut ( durationInSeconds : Number ) : this

Decreases the weight of this action gradually from 1 to 0, within the passed time interval. This method can be chained.

.getEffectiveTimeScale () : Number

Returns the effective time scale (considering the current states of warping and paused).

.getEffectiveWeight () : Number

Returns the effective weight (considering the current states of fading and enabled).

.getClip () : AnimationClip

Returns the clip which holds the animation data for this action.

.getMixer () : AnimationMixer

Returns the mixer which is responsible for playing this action.

.getRoot () : Object3D

Returns the root object on which this action is performed.

.halt ( durationInSeconds : Number ) : this

Decelerates this animation's speed to 0 by decreasing timeScale gradually (starting from its current value), within the passed time interval. This method can be chained.

.isRunning () : Boolean

Returns true if the action’s time is currently running.

In addition to being activated in the mixer (see isScheduled) the following conditions must be fulfilled: paused is equal to false, enabled is equal to true, timeScale is different from 0, and there is no scheduling for a delayed start (startAt).

Note: isRunning being true doesn’t necessarily mean that the animation can actually be seen. This is only the case, if weight is additionally set to a non-zero value.

.isScheduled () : Boolean

Returns true, if this action is activated in the mixer.

Note: This doesn’t necessarily mean that the animation is actually running (compare the additional conditions for isRunning).

.play () : this

Tells the mixer to activate the action. This method can be chained.

Note: Activating this action doesn’t necessarily mean that the animation starts immediately: If the action had already finished before (by reaching the end of its last loop), or if a time for a delayed start has been set (via startAt), a reset must be executed first. Some other settings (paused=true, enabled=false, weight=0, timeScale=0) can prevent the animation from playing, too.

.reset () : this

Resets the action. This method can be chained.

This method sets paused to false, enabled to true, time to 0, interrupts any scheduled fading and warping, and removes the internal loop count and scheduling for delayed starting.

Note: .reset is always called by stop, but .reset doesn’t call .stop itself. This means: If you want both, resetting and stopping, don’t call .reset; call .stop instead.

.setDuration ( durationInSeconds : Number ) : this

Sets the duration for a single loop of this action (by adjusting timeScale and stopping any scheduled warping). This method can be chained.

.setEffectiveTimeScale ( timeScale : Number ) : this

Sets the timeScale and stops any scheduled warping. This method can be chained.

If paused is false, the effective time scale (an internal property) will also be set to this value; otherwise the effective time scale (directly affecting the animation at this moment) will be set to 0.

Note: .paused will not be switched to true automatically, if .timeScale is set to 0 by this method.

.setEffectiveWeight ( weight : Number ) : this

Sets the weight and stops any scheduled fading. This method can be chained.

If enabled is true, the effective weight (an internal property) will also be set to this value; otherwise the effective weight (directly affecting the animation at this moment) will be set to 0.

Note: .enabled will not be switched to false automatically, if .weight is set to 0 by this method.

.setLoop ( loopMode : Number, repetitions : Number) : this

Sets the loop mode and the number of repetitions. This method can be chained.

.startAt ( startTimeInSeconds : Number ) : this

Defines the time for a delayed start (usually passed as AnimationMixer.time + deltaTimeInSeconds). This method can be chained.

Note: The animation will only start at the given time, if .startAt is chained with play, or if the action has already been activated in the mixer (by a previous call of .play, without stopping or resetting it in the meantime).

.stop () : this

Tells the mixer to deactivate this action. This method can be chained.

The action will be immediately stopped and completely reset.

Note: You can stop all active actions on the same mixer in one go via mixer.stopAllAction.

.stopFading () : this

Stops any scheduled fading which is applied to this action. This method can be chained.

.stopWarping () : this

Stops any scheduled warping which is applied to this action. This method can be chained.

.syncWith ( otherAction : AnimationAction ) : this

Synchronizes this action with the passed other action. This method can be chained.

Synchronizing is done by setting this action’s time and timeScale values to the corresponding values of the other action (stopping any scheduled warping).

Note: Future changes of the other action's time and timeScale will not be detected.

.warp ( startTimeScale : Number, endTimeScale : Number, durationInSeconds : Number ) : this

Changes the playback speed, within the passed time interval, by modifying timeScale gradually from startTimeScale to endTimeScale. This method can be chained.

Events

There are two events indicating when a single loop of the action respectively the entire action has finished. You can react to them with:

mixer.addEventListener( 'loop', function( e ) { …} ); // properties of e: type, action and loopDelta mixer.addEventListener( 'finished', function( e ) { …} ); // properties of e: type, action and direction

Source

src/animation/AnimationAction.js

AnimationClip

An AnimationClip is a reusable set of keyframe tracks which represent an animation.

For an overview of the different elements of the three.js animation system see the "Animation System" article in the "Next Steps" section of the manual.

Constructor

AnimationClip( name : String, duration : Number, tracks : Array )

name - a name for this clip.
duration - the duration of this clip (in seconds). If a negative value is passed, the duration will be calculated from the passed tracks array.
tracks - an array of KeyframeTracks.
blendMode - defines how the animation is blended/combined when two or more animations are simultaneously played.

Note: Instead of instantiating an AnimationClip directly with the constructor, you can use one of its static methods to create AnimationClips: from JSON (parse), from morph target sequences (CreateFromMorphTargetSequence, CreateClipsFromMorphTargetSequences) or from animation hierarchies (parseAnimation) - if your model doesn't already hold AnimationClips in its geometry's animations array.

Properties

.blendMode : Number

Defines how the animation is blended/combined when two or more animations are simultaneously played. Valid values are NormalAnimationBlendMode (default) and AdditiveAnimationBlendMode.

.duration : Number

The duration of this clip (in seconds). This can be calculated from the tracks array via resetDuration.

.name : String

A name for this clip. A certain clip can be searched via findByName.

.tracks : Array

An array containing a KeyframeTrack for each property that are animated by this clip.

.uuid : String

The UUID of this clip instance. It gets automatically assigned and shouldn't be edited.

Methods

.clone () : AnimationClip

Returns a copy of this clip.

.optimize () : this

Optimizes each track by removing equivalent sequential keys (which are common in morph target sequences).

.resetDuration () : this

Sets the duration of the clip to the duration of its longest KeyframeTrack.

.toJSON () : Object

Returns a JSON object representing the serialized animation clip.

.trim () : this

Trims all tracks to the clip's duration.

.validate () : Boolean

Performs minimal validation on each track in the clip. Returns true if all tracks are valid.

Static Methods

.CreateClipsFromMorphTargetSequences ( name : String, morphTargetSequence : Array, fps : Number, noLoop : Boolean ) : Array

Returns an array of new AnimationClips created from the morph target sequences of a geometry, trying to sort morph target names into animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".

.CreateFromMorphTargetSequence ( name : String, morphTargetSequence : Array, fps : Number, noLoop : Boolean ) : AnimationClip

Returns a new AnimationClip from the passed morph targets array of a geometry, taking a name and the number of frames per second.

Note: The fps parameter is required, but the animation speed can be overridden in an AnimationAction via animationAction.setDuration.

.findByName ( objectOrClipArray : Object, name : String ) : AnimationClip

Searches for an AnimationClip by name, taking as its first parameter either an array of AnimationClips, or a mesh or geometry that contains an array named "animations".

.parse ( json : Object ) : AnimationClip

Parses a JSON representation of a clip and returns an AnimationClip.

.parseAnimation ( animation : Object, bones : Array ) : AnimationClip

Parses the animation.hierarchy format and returns an AnimationClip.

.toJSON ( clip : AnimationClip ) : Object

Takes an AnimationClip and returns a JSON object.

Source

src/animation/AnimationClip.js

AnimationMixer

The 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.

For an overview of the different elements of the three.js animation system see the "Animation System" article in the "Next Steps" section of the manual.

Constructor

AnimationMixer( rootObject : Object3D )

rootObject - the object whose animations shall be played by this mixer.

Properties

.time : Number

The global mixer time (in seconds; starting with 0 on the mixer's creation).

.timeScale : Number

A scaling factor for the global mixer time.

Note: Setting the mixer's timeScale to 0 and later back to 1 is a possibility to pause/unpause all actions that are controlled by this mixer.

Methods

.clipAction (clip : AnimationClip, optionalRoot : Object3D) : AnimationAction

Returns an AnimationAction for the passed clip, optionally using a root object different from the mixer's default root. The first parameter can be either an AnimationClip object or the name of an AnimationClip.

If an action fitting the clip and root parameters doesn't yet exist, it will be created by this method. Calling this method several times with the same clip and root parameters always returns the same clip instance.

.existingAction (clip : AnimationClip, optionalRoot : Object3D) : AnimationAction

Returns an existing AnimationAction for the passed clip, optionally using a root object different from the mixer's default root.

The first parameter can be either an AnimationClip object or the name of an AnimationClip.

.getRoot () : Object3D

Returns this mixer's root object.

.stopAllAction () : this

Deactivates all previously scheduled actions on this mixer.

.update (deltaTimeInSeconds : Number) : this

Advances the global mixer time and updates the animation.

This is usually done in the render loop, passing clock.getDelta scaled by the mixer's timeScale.

.setTime (timeInSeconds : Number) : this

Sets the global mixer to a specific time and updates the animation accordingly.

This is useful when you need to jump to an exact time in an animation. The input parameter will be scaled by the mixer's timeScale.

.uncacheClip (clip : AnimationClip) : undefined

Deallocates all memory resources for a clip. Before using this method make sure to call AnimationAction.stop() for all related actions.

.uncacheRoot (root : Object3D) : undefined

Deallocates all memory resources for a root object. Before using this method make sure to call AnimationAction.stop() for all related actions or alternatively .stopAllAction() when the mixer operates on a single root.

.uncacheAction (clip : AnimationClip, optionalRoot : Object3D) : undefined

Deallocates all memory resources for an action. Before using this method make sure to call AnimationAction.stop() to deactivate the action.

Source

src/animation/AnimationMixer.js

AnimationObjectGroup

A group of objects that receives a shared animation state.

For an overview of the different elements of the three.js animation system see the "Animation System" article in the "Next Steps" section of the manual.

Usage:

Add objects you would otherwise pass as 'root' to the constructor or the clipAction method of AnimationMixer and instead pass this object as 'root'.

Note that objects of this class appear as one object to the mixer, so cache control of the individual objects must be done on the group.

Limitations

The animated properties must be compatible among all objects in the group.

A single property can either be controlled through a target group or directly, but not both.

Constructor

AnimationObjectGroup( obj1 : Object, obj2 : Object, obj3 : Object, ...)

obj - an arbitrary number of meshes that share the same animation state.

Properties

.isAnimationObjectGroup : Boolean

Read-only flag to check if a given object is of type AnimationObjectGroup.

.stats : Object

An object that contains some informations of this AnimationObjectGroup (total number, number in use, number of bindings per object)

.uuid : String

The UUID of this AnimationObjectGroup. It gets automatically assigned and shouldn't be edited.

Methods

.add ( obj1 : Object, obj2 : Object, obj3 : Object, ... ) : undefined

Adds an arbitrary number of objects to this AnimationObjectGroup.

.remove ( obj1 : Object, obj2 : Object, obj3 : Object, ... ) : undefined

Removes an arbitrary number of objects from this AnimationObjectGroup.

.uncache ( obj1 : Object, obj2 : Object, obj3 : Object, ... ) : undefined

Deallocates all memory resources for the passed objects of this AnimationObjectGroup.

Source

src/animation/AnimationObjectGroup.js

AnimationUtils

An object with various functions to assist with animations, used internally.

Methods

.convertArray ( array, type, forceClone ) : Array

Converts an array to a specific type.

.flattenJSON ( jsonKeys, times, values, valuePropertyName ) : Array

Used for parsing AOS keyframe formats.

.getKeyframeOrder ( times ) : Array

Returns an array by which times and values can be sorted.

.isTypedArray ( object ) : Boolean

Returns true if the object is a typed array.

.makeClipAdditive ( targetClip : AnimationClip, referenceFrame : Number, referenceClip : AnimationClip, fps : Number ) : AnimationClip

Converts the keyframes of the given animation clip to an additive format.

.sortedArray ( values, stride, order ) : Array

Sorts the array previously returned by getKeyframeOrder.

.subclip ( clip : AnimationClip, name : String, startFrame : Number, endFrame : Number, fps : Number ) : AnimationClip

Creates a new clip, containing only the segment of the original clip between the given frames.

Source

src/animation/AnimationUtils.js

KeyframeTrack

A KeyframeTrack is a timed sequence of keyframes, which are composed of lists of times and related values, and which are used to animate a specific property of an object.

For an overview of the different elements of the three.js animation system see the "Animation System" article in the "Next Steps" section of the manual.

In contrast to the animation hierarchy of the JSON model format a KeyframeTrack doesn't store its single keyframes as objects in a "keys" array (holding the times and the values for each frame together in one place).

Instead of this there are always two arrays in a KeyframeTrack: the times array stores the time values for all keyframes of this track in sequential order, and the values array contains the corresponding changing values of the animated property.

A single value, belonging to a certain point of time, can not only be a simple number, but (for example) a vector (if a position is animated) or a quaternion (if a rotation is animated). For this reason the values array (which is a flat array, too) might be three or four times as long as the times array.

Corresponding to the different possible types of animated values there are several subclasses of KeyframeTrack, inheriting the most properties and methods:

Some examples of how to manually create AnimationClips with different sorts of KeyframeTracks can be found in the AnimationClipCreator file.

Since explicit values are only specified for the discrete points of time stored in the times array, all values in between have to be interpolated.

The track's name is important for the connection of this track with a specific property of the animated node (done by PropertyBinding).

Constructor

KeyframeTrack( name : String, times : Array, values : Array, interpolation : Constant )

name - the identifier for the KeyframeTrack.
times - an array of keyframe times, converted internally to a Float32Array.
values - an array with the values related to the times array, converted internally to a Float32Array.
interpolation - the type of interpolation to use. See Animation Constants for possible values. Default is InterpolateLinear.

Properties

.name : String

The track's name can refer to morph targets or bones or possibly other values within an animated object. See PropertyBinding.parseTrackName for the forms of strings that can be parsed for property binding:

The name can specify the node either using its name or its uuid (although it needs to be in the subtree of the scene graph node passed into the mixer). Or, if the track name starts with a dot, the track applies to the root node that was passed into the mixer.

Usually after the node a property will be specified directly. But you can also specify a subproperty, such as .rotation[x], if you just want to drive the X component of the rotation via a float track.

You can also specify bones or multimaterials by using an object name, for example: .bones[R_hand].scale; the red channel of the diffuse color of the fourth material in a materials array - as a further example - can be accessed with .materials[3].diffuse[r].

PropertyBinding will also resolve morph target names, for example: .morphTargetInfluences[run].

Note: The track's name does not necessarily have to be unique. Multiple tracks can drive the same property. The result should be based on a weighted blend between the multiple tracks according to the weights of their respective actions.

.times : Float32Array

A Float32Array, converted from the times array which is passed in the constructor.

.values : Float32Array

A Float32Array, converted from the values array which is passed in the constructor.

.DefaultInterpolation : Constant

The default interpolation type: InterpolateLinear.

.TimeBufferType : Constant

Float32Array, the type of the buffer internally used for the times.

.ValueBufferType : Constant

Float32Array, the type of the buffer internally used for the values.

Methods

.clone () : KeyframeTrack

Returns a copy of this track.

.createInterpolant () : Interpolant

Creates a LinearInterpolant, CubicInterpolant or DiscreteInterpolant, depending on the value of the interpolation parameter passed in the constructor.

.getInterpolation () : Interpolant

Returns the interpolation type.

.getValueSize () : Number

Returns the size of each value (that is the length of the values array divided by the length of the times array).

.InterpolantFactoryMethodDiscrete ( result ) : DiscreteInterpolant

Creates a new DiscreteInterpolant from the times and values. A Float32Array can be passed which will receive the results. Otherwise a new array with the appropriate size will be created automatically.

.InterpolantFactoryMethodLinear ( result ) : LinearInterpolant

Creates a new LinearInterpolant from the times and values. A Float32Array can be passed which will receive the results. Otherwise a new array with the appropriate size will be created automatically.

.InterpolantFactoryMethodSmooth ( result ) : CubicInterpolant

Create a new CubicInterpolant from the times and values. A Float32Array can be passed which will receive the results. Otherwise a new array with the appropriate size will be created automatically.

.optimize () : this

Removes equivalent sequential keys, which are common in morph target sequences.

.scale () : this

Scales all keyframe times by a factor.

Note: This is useful, for example, for conversions to a certain rate of frames per seconds (as it is done internally by animationClip.CreateFromMorphTargetSequence).

.setInterpolation ( interpolationType : Constant ) : this

Sets the interpolation type. See Animation Constants for choices.

.shift ( timeOffsetInSeconds : Number ) : this

Moves all keyframes either forward or backward in time.

.trim ( startTimeInSeconds : Number, endTimeInSeconds : Number ) : this

Removes keyframes before startTime and after endTime, without changing any values within the range [startTime, endTime].

.validate () : Boolean

Performs minimal validation on the tracks. Returns true if valid.

This method logs errors to the console, if a track is empty, if the value size is not valid, if an item in the times or values array is not a valid number or if the items in the times array are out of order.

Static Methods

.toJSON ( track : KeyframeTrack ) : JSON

Converts the track to JSON.

Source

src/animation/KeyframeTrack.js

PropertyBinding

This holds a reference to a real property in the scene graph; used internally.

Constructor

PropertyBinding( rootNode : Object3D, path, parsedPath )

-- rootNode: -- path -- parsedPath (optional)

Properties

.path : Number

.parsedPath : Number

.node : Number

.rootNode : Number

.BindingType : Object

.Versioning : Object

.GetterByBindingType : Array

.SetterByBindingTypeAndVersioning : Array

Methods

.getValue ( targetArray : Array, offset : Number ) : undefined

.setValue ( sourceArray : Array, offset : Number ) : undefined

.bind ( ) : undefined

Create getter / setter pair for a property in the scene graph. Used internally by getValue and setValue.

.unbind ( ) : undefined

Unbind getter / setter pair for a property in the scene graph.

.Composite ( targetGroup, path, optionalParsedPath ) : Constructor

Create a new Composite PropertyBinding.

.create ( root, path, parsedPath ) : Constructor

Create a new Composite PropertyBinding (if root is an AnimationObjectGroup) or PropertyBinding.

.parseTrackName ( trackName ) : Constructor

Matches strings in the following forms:
-- nodeName.property
-- nodeName.property[accessor]
-- nodeName.material.property[accessor]
-- uuid.property[accessor]
-- uuid.objectName[objectIndex].propertyName[propertyIndex]
-- parentName/nodeName.property
-- parentName/parentName/nodeName.property[index]
-- .bone[Armature.DEF_cog].position
-- scene:helium_balloon_model:helium_balloon_model.position

.findNode ( root, nodeName ) : Constructor

Find a node in a node tree or Skeleton.

Source

src/animation/PropertyBinding.js

PropertyMixer

Buffered scene graph property that allows weighted accumulation; used internally.

Constructor

PropertyMixer( binding : PropertyBinding, typeName : String, valueSize : Number )

-- binding
-- typeName
-- valueSize

Properties

.binding : PropertyBinding

.buffer : TypedArray

Buffer with size valueSize * 4.

This has the layout: [ incoming | accu0 | accu1 | orig ]

Interpolators can use .buffer as their .result and the data then goes to 'incoming'. 'accu0' and 'accu1' are used frame-interleaved for the cumulative result and are compared to detect changes. 'orig' stores the original state of the property.

.cumulativeWeight : Number

Default is 0.

.cumulativeWeightAdditive : Number

Default is 0.

.valueSize : Number

.referenceCount : Number

Default is 0.

.useCount : Number

Default is 0.

Methods

.accumulate ( accuIndex : Number, weight : Number ) : undefined

Accumulate data in buffer[accuIndex] 'incoming' region into 'accu[i]'.
If weight is 0 this does nothing.

.accumulateAdditive ( weight : Number ) : undefined

Accumulate data in the 'incoming' region into 'add'.
If weight is 0 this does nothing.

.apply ( accuIndex : Number ) : undefined

Apply the state of buffer 'accu[i]' to the binding when accus differ.

.saveOriginalState ( ) : undefined

Remember the state of the bound property and copy it to both accus.

.restoreOriginalState ( ) : undefined

Apply the state previously taken via 'saveOriginalState' to the binding.

Source

src/animation/PropertyMixer.js

KeyframeTrack

BooleanKeyframeTrack

A Track of boolean keyframe values.

Constructor

BooleanKeyframeTrack( name : String, times : Array, values : Array )

name - (required) identifier for the KeyframeTrack.
times - (required) array of keyframe times.
values - values for the keyframes at the times specified.

This keyframe track type has no interpolation parameter because the interpolation is always InterpolateDiscrete.

Properties

See KeyframeTrack for inherited properties.

.DefaultInterpolation : Constant

The default interpolation type to use. Only InterpolateDiscrete is valid for this track type.

.ValueBufferType : Array

A normal Array (no Float32Array in this case, unlike ValueBufferType of KeyframeTrack).

.ValueTypeName : String

String 'bool'.

Methods

See KeyframeTrack for inherited methods.

.InterpolantFactoryMethodLinear () : undefined

The value of this method here is 'undefined', as it does not make sense for discrete properties.

.InterpolantFactoryMethodSmooth () : undefined

The value of this method here is 'undefined', as it does not make sense for discrete properties.

Source

src/animation/tracks/BooleanKeyframeTrack.js

KeyframeTrack

ColorKeyframeTrack

A Track of keyframe values that represent color changes.

The very basic implementation of this subclass has nothing special yet. However, this is the place for color space parameterization.

Constructor

ColorKeyframeTrack( name : String, times : Array, values : Array, interpolation : Constant )

name - (required) identifier for the KeyframeTrack.
times - (required) array of keyframe times.
values - values for the keyframes at the times specified, a flat array of color components between 0 and 1.
interpolation - the type of interpolation to use. See Animation Constants for possible values. Default is InterpolateLinear.

Properties

See KeyframeTrack for inherited properties.

.ValueTypeName : String

String 'color'.

Methods

See KeyframeTrack for inherited methods.

Source

src/animation/tracks/ColorKeyframeTrack.js

KeyframeTrack

NumberKeyframeTrack

A Track of numeric keyframe values.

Constructor

NumberKeyframeTrack( name : String, times : Array, values : Array, interpolation : Constant )

name - (required) identifier for the KeyframeTrack.
times - (required) array of keyframe times.
values - values for the keyframes at the times specified.
interpolation - the type of interpolation to use. See Animation Constants for possible values. Default is InterpolateLinear.

Properties

See KeyframeTrack for inherited properties.

.ValueTypeName : String

String 'number'.

Methods

See KeyframeTrack for inherited methods.

Source

src/animation/tracks/NumberKeyframeTrack.js

KeyframeTrack

QuaternionKeyframeTrack

A Track of quaternion keyframe values.

Constructor

QuaternionKeyframeTrack( name : String, times : Array, values : Array, interpolation : Constant )

name - (required) identifier for the KeyframeTrack.
times - (required) array of keyframe times.
values - values for the keyframes at the times specified, a flat array of quaternion components.
interpolation - the type of interpolation to use. See Animation Constants for possible values. Default is InterpolateLinear.

Properties

See KeyframeTrack for inherited properties.

.DefaultInterpolation : Constant

The default interpolation type to use, InterpolateLinear.

.ValueTypeName : String

String 'quaternion'.

Methods

See KeyframeTrack for inherited methods.

.InterpolantFactoryMethodLinear () : QuaternionLinearInterpolant

Returns a new QuaternionLinearInterpolant based on the values, times and valueSize of the keyframes.

Source

src/animation/tracks/QuaternionKeyframeTrack.js

KeyframeTrack

StringKeyframeTrack

A Track of string keyframe values.

Constructor

StringKeyframeTrack( name : String, times : Array, values : Array )

name - (required) identifier for the KeyframeTrack.
times - (required) array of keyframe times.
values - values for the keyframes at the times specified.

This keyframe track type has no interpolation parameter because the interpolation is always InterpolateDiscrete.

Properties

See KeyframeTrack for inherited properties.

.DefaultInterpolation : Constant

The default interpolation type to use. Only InterpolateDiscrete is valid for this track type.

.ValueBufferType : Array

A normal Array (no Float32Array in this case, unlike ValueBufferType of KeyframeTrack).

.ValueTypeName : String

String 'string'.

Methods

See KeyframeTrack for inherited methods.

.InterpolantFactoryMethodLinear () : undefined

The value of this method here is 'undefined', as it does not make sense for discrete properties.

.InterpolantFactoryMethodSmooth () : undefined

The value of this method here is 'undefined', as it does not make sense for discrete properties.

Source

src/animation/tracks/StringKeyframeTrack.js

KeyframeTrack

VectorKeyframeTrack

A Track of vector keyframe values.

Constructor

VectorKeyframeTrack( name : String, times : Array, values : Array, interpolation : Constant )

name - (required) identifier for the KeyframeTrack.
times - (required) array of keyframe times.
values - values for the keyframes at the times specified, a flat array of vector components.
interpolation - the type of interpolation to use. See Animation Constants for possible values. Default is InterpolateLinear.

Properties

See KeyframeTrack for inherited properties.

.ValueTypeName : String

String 'vector'.

Methods

See KeyframeTrack for inherited methods.

Source

src/animation/tracks/VectorKeyframeTrack.js

Object3D

Audio

Create a non-positional ( global ) audio object.

This uses the Web Audio API.

Code Example

// create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create a global audio source const sound = new THREE.Audio( listener ); // load a sound and set it as the Audio object's buffer const audioLoader = new THREE.AudioLoader(); audioLoader.load( 'sounds/ambient.ogg', function( buffer ) { sound.setBuffer( buffer ); sound.setLoop( true ); sound.setVolume( 0.5 ); sound.play(); });

Examples

webaudio / sandbox
webaudio / visualizer

Constructor

Audio( listener : AudioListener )

listener — (required) AudioListener instance.

Properties

.autoplay : Boolean

Whether to start playback automatically. Default is false.

.context : AudioContext

The AudioContext of the listener given in the constructor.

.detune : Number

Modify pitch, measured in cents. +/- 100 is a semitone. +/- 1200 is an octave. Default is 0.

.filters : Array

Represents an array of AudioNodes. Can be used to apply a variety of low-order filters to create more complex sound effects. In most cases, the array contains instances of BiquadFilterNodes. Filters are set via Audio.setFilter or Audio.setFilters.

.gain : GainNode

A GainNode created using AudioContext.createGain().

.hasPlaybackControl : Boolean

Whether playback can be controlled using the play(), pause() etc. methods. Default is true.

.isPlaying : Boolean

Whether the audio is currently playing.

.listener : AudioListener

A reference to the listener object of this audio.

.playbackRate : Number

Speed of playback. Default is 1.

.offset : Number

An offset to the time within the audio buffer that playback should begin. Same as the offset parameter of AudioBufferSourceNode.start(). Default is 0.

.duration : Number

Overrides the duration of the audio. Same as the duration parameter of AudioBufferSourceNode.start(). Default is undefined to play the whole buffer.

.source : AudioNode

An AudioBufferSourceNode created using AudioContext.createBufferSource().

.sourceType : String

Type of the audio source. Default is string 'empty'.

.type : String

String denoting the type, set to 'Audio'.

Methods

.connect () : this

Connect to the Audio.source. This is used internally on initialisation and when setting / removing filters.

.disconnect () : this

Disconnect from the Audio.source. This is used internally when setting / removing filters.

.getDetune () : Float

Returns the detuning of oscillation in cents.

.getFilter () : BiquadFilterNode

Returns the first element of the filters array.

.getFilters () : Array

Returns the filters array.

.getLoop () : Boolean

Return the value of source.loop (whether playback should loop).

.getOutput () : GainNode

Return the gainNode.

.getPlaybackRate () : Float

Return the value of playbackRate.

.getVolume () : Float

Return the current volume.

.play ( delay ) : this

delay (optional) - The delay, in seconds, at which the audio should start playing.
If hasPlaybackControl is true, starts playback.

.pause () : this

If hasPlaybackControl is true, pauses playback.

.onEnded () : undefined

Called automatically when playback finished.

.setBuffer ( audioBuffer ) : this

Setup the source to the audioBuffer, and sets sourceType to 'buffer'.
If autoplay, also starts playback.

.setDetune ( value : Float ) : this

Defines the detuning of oscillation in cents.

.setFilter ( filter ) : this

Applies a single filter node to the audio.

.setFilters ( value : Array ) : this

value - arrays of filters.
Applies an array of filter nodes to the audio.

.setLoop ( value : Boolean ) : this

Set source.loop to value (whether playback should loop).

.setLoopStart ( value : Float ) : this

Set source.loopStart to value.

.setLoopEnd ( value : Float ) : this

Set source.loopEnd to value.

.setMediaElementSource ( mediaElement ) : this

Applies the given object of type HTMLMediaElement as the source of this audio.
Also sets hasPlaybackControl to false.

.setMediaStreamSource ( mediaStream ) : this

Applies the given object of type MediaStream as the source of this audio.
Also sets hasPlaybackControl to false.

.setNodeSource ( audioNode ) : this

Setup the source to the audioBuffer, and sets sourceType to 'audioNode'.
Also sets hasPlaybackControl to false.

.setPlaybackRate ( value : Float ) : this

If hasPlaybackControl is enabled, set the playbackRate to value.

.setVolume ( value : Float ) : this

Set the volume.

.stop ( delay ) : this

delay (optional) - The delay, in seconds, at which the audio should stop playing.
If hasPlaybackControl is enabled, stops playback.

Source

src/audio/Audio.js

AudioAnalyser

Create a AudioAnalyser object, which uses an AnalyserNode to analyse audio data.

This uses the Web Audio API.

Code Example

// create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create an Audio source const sound = new THREE.Audio( listener ); // load a sound and set it as the Audio object's buffer const audioLoader = new THREE.AudioLoader(); audioLoader.load( 'sounds/ambient.ogg', function( buffer ) { sound.setBuffer( buffer ); sound.setLoop(true); sound.setVolume(0.5); sound.play(); }); // create an AudioAnalyser, passing in the sound and desired fftSize const analyser = new THREE.AudioAnalyser( sound, 32 ); // get the average frequency of the sound const data = analyser.getAverageFrequency();

Examples

webaudio / sandbox
webaudio / visualizer

Constructor

AudioAnalyser( audio, fftSize )

Create a new AudioAnalyser.

Properties

.analyser : AnalyserNode

An AnalyserNode used to analyze audio.

.fftSize : Integer

A non-zero power of two up to 2048, representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain. See this page for details.

.data : Uint8Array

A Uint8Array with size determined by analyser.frequencyBinCount used to hold analysis data.

Methods

.getFrequencyData () : Uint8Array

Uses the Web Audio's getByteFrequencyData method. See that page.

.getAverageFrequency () : Number

Get the average of the frequencies returned by the getFrequencyData method.

Source

src/audio/AudioAnalyser.js

AudioContext

This contains methods for setting up an AudioContext.

Used internally by the AudioListener and AudioLoader classes.

This uses the Web Audio API.

Methods

.getContext () : AudioContext

Return the value of the variable context in the outer scope, if defined, otherwise set it to a new AudioContext.

.setContext ( value : AudioContext ) : AudioContext

Set the variable context in the outer scope to value.

Source

src/audio/AudioContext.js

Object3D

AudioListener

The AudioListener represents a virtual listener of the all positional and non-positional audio effects in the scene.
A three.js application usually creates a single instance of AudioListener. It is a mandatory constructor parameter for audios entities like Audio and PositionalAudio.
In most cases, the listener object is a child of the camera. So the 3D transformation of the camera represents the 3D transformation of the listener.

Code Example

// create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create a global audio source const sound = new THREE.Audio( listener ); // load a sound and set it as the Audio object's buffer const audioLoader = new THREE.AudioLoader(); audioLoader.load( 'sounds/ambient.ogg', function( buffer ) { sound.setBuffer( buffer ); sound.setLoop(true); sound.setVolume(0.5); sound.play(); });

Examples

webaudio / sandbox
webaudio / timing
webaudio / visualizer

Constructor

AudioListener( )

Create a new AudioListener.

Properties

.context : AudioContext

The AudioContext of the listener given in the constructor.

.gain : GainNode

A GainNode created using AudioContext.createGain().

.filter : AudioNode

Default is null.

.timeDelta : Number

Time delta value for audio entities. Use in context of AudioParam.linearRampToValueAtTimeDefault(). Default is .

Methods

.getInput () : GainNode

Return the gainNode.

.removeFilter () : this

Set the filter property to null.

.getFilter () : AudioNode

Returns the value of the filter property.

.setFilter ( value : AudioNode ) : this

Set the filter property to value.

.getMasterVolume () : Float

Return the volume.

.setMasterVolume ( value : Number ) : this

Set the volume.

Source

src/audio/AudioListener.js

Object3DAudio

PositionalAudio

Create a positional audio object.

This uses the Web Audio API.

Code Example

// create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create the PositionalAudio object (passing in the listener) const sound = new THREE.PositionalAudio( listener ); // load a sound and set it as the PositionalAudio object's buffer const audioLoader = new THREE.AudioLoader(); audioLoader.load( 'sounds/song.ogg', function( buffer ) { sound.setBuffer( buffer ); sound.setRefDistance( 20 ); sound.play(); }); // create an object for the sound to play from const sphere = new THREE.SphereGeometry( 20, 32, 16 ); const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } ); const mesh = new THREE.Mesh( sphere, material ); scene.add( mesh ); // finally add the sound to the mesh mesh.add( sound );

Examples

webaudio / orientation
webaudio / sandbox
webaudio / timing

Constructor

PositionalAudio( listener : AudioListener )

listener — (required) AudioListener instance.

Properties

See the Audio class for inherited properties.

.panner : PannerNode

The PositionalAudio's PannerNode.

Methods

See the Audio class for inherited methods.

.getOutput () : PannerNode

Returns the panner.

.getRefDistance () : Float

Returns the value of panner.refDistance.

.setRefDistance ( value : Float ) : this

Sets the value of panner.refDistance.

.getRolloffFactor () : Float

Returns the value of panner.rolloffFactor.

.setRolloffFactor ( value : Float ) : this

Sets the value of panner.rolloffFactor.

.getDistanceModel () : String

Returns the value of panner.distanceModel.

.setDistanceModel ( value : String ) : this

Sets the value of panner.distanceModel.

.getMaxDistance () : Float

Returns the value of panner.maxDistance.

.setMaxDistance ( value : Float ) : this

Sets the value of panner.maxDistance.

.setDirectionalCone ( coneInnerAngle : Float, coneOuterAngle : Float, coneOuterGain : Float ) : this

This method can be used in order to transform an omnidirectional sound into a directional sound.

Source

src/audio/PositionalAudio.js

Object3DCameraPerspectiveCamera

ArrayCamera

ArrayCamera can be used in order to efficiently render a scene with a predefined set of cameras. This is an important performance aspect for rendering VR scenes.
An instance of ArrayCamera always has an array of sub cameras. It's mandatory to define for each sub camera the viewport property which determines the part of the viewport that is rendered with this camera.

Examples

camera / array

Constructor

ArrayCamera( array : Array )

An array of cameras.

Properties

See the base PerspectiveCamera class for common properties.

.cameras : Array

An array of cameras.

.isArrayCamera : Boolean

Read-only flag to check if a given object is of type ArrayCamera.

Methods

See the base PerspectiveCamera class for common methods.

Source

src/cameras/ArrayCamera.js

Object3D

Camera

Abstract base class for cameras. This class should always be inherited when you build a new camera.

Constructor

Camera()

Creates a new Camera. Note that this class is not intended to be called directly; you probably want a PerspectiveCamera or OrthographicCamera instead.

Properties

See the base Object3D class for common properties.

.isCamera : Boolean

Read-only flag to check if a given object is of type Camera.

.layers : Layers

The layers that the camera is a member of. This is an inherited property from Object3D.

Objects must share at least one layer with the camera to be seen when the camera's viewpoint is rendered.

.matrixWorldInverse : Matrix4

This is the inverse of matrixWorld. MatrixWorld contains the Matrix which has the world transform of the Camera.

.projectionMatrix : Matrix4

This is the matrix which contains the projection.

.projectionMatrixInverse : Matrix4

The inverse of projectionMatrix.

Methods

See the base Object3D class for common methods.

.clone ( ) : Camera

Return a new camera with the same properties as this one.

.copy ( source : Camera, recursive : Boolean ) : this

Copy the properties from the source camera into this one.

.getWorldDirection ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns a Vector3 representing the world space direction in which the camera is looking. (Note: A camera looks down its local, negative z-axis).

Source

src/cameras/Camera.js

Object3D

CubeCamera

Creates 6 cameras that render to a WebGLCubeRenderTarget.

Code Example

// Create cube render target const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 128, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } ); // Create cube camera const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget ); scene.add( cubeCamera ); // Create car const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } ); const car = new THREE.Mesh( carGeometry, chromeMaterial ); scene.add( car ); // Update the render target cube car.visible = false; cubeCamera.position.copy( car.position ); cubeCamera.update( renderer, scene ); // Render the scene car.visible = true; renderer.render( scene, camera );

Examples

materials / cubemap / dynamic

Constructor

CubeCamera( near : Number, far : Number, renderTarget : WebGLCubeRenderTarget )

near -- The near clipping distance.
far -- The far clipping distance.
renderTarget -- The destination cube render target.

Constructs a CubeCamera that contains 6 PerspectiveCameras that render to a WebGLCubeRenderTarget.

Properties

See the base Object3D class for common properties.

.renderTarget : WebGLCubeRenderTarget

The destination cube render target.

Methods

See the base Object3D class for common methods.

.update ( renderer : WebGLRenderer, scene : Scene ) : undefined

renderer -- The current WebGL renderer
scene -- The current scene

Call this to update the renderTarget.

Source

src/cameras/CubeCamera.js

Object3DCamera

OrthographicCamera

Camera that uses orthographic projection.

In this projection mode, an object's size in the rendered image stays constant regardless of its distance from the camera.

This can be useful for rendering 2D scenes and UI elements, amongst other things.

Code Example

const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); scene.add( camera );

Examples

camera
interactive / cubes / ortho
materials / cubemap / dynamic
postprocessing / advanced
postprocessing / dof2
postprocessing / godrays
rtt
shadowmap

Constructor

OrthographicCamera( left : Number, right : Number, top : Number, bottom : Number, near : Number, far : Number )

left — Camera frustum left plane.
right — Camera frustum right plane.
top — Camera frustum top plane.
bottom — Camera frustum bottom plane.
near — Camera frustum near plane.
far — Camera frustum far plane.

Together these define the camera's viewing frustum.

Properties

See the base Camera class for common properties.
Note that after making changes to most of these properties you will have to call .updateProjectionMatrix for the changes to take effect.

.bottom : Float

Camera frustum bottom plane.

.far : Float

Camera frustum far plane. Default is 2000.

Must be greater than the current value of near plane.

.isOrthographicCamera : Boolean

Read-only flag to check if a given object is of type OrthographicCamera.

.left : Float

Camera frustum left plane.

.near : Float

Camera frustum near plane. Default is 0.1.

The valid range is between 0 and the current value of the far plane. Note that, unlike for the PerspectiveCamera, 0 is a valid value for an OrthographicCamera's near plane.

.right : Float

Camera frustum right plane.

.top : Float

Camera frustum top plane.

.view : Object

Set by setViewOffset. Default is null.

.zoom : number

Gets or sets the zoom factor of the camera. Default is 1.

Methods

See the base Camera class for common methods.

.setViewOffset ( fullWidth : Float, fullHeight : Float, x : Float, y : Float, width : Float, height : Float ) : undefined

fullWidth — full width of multiview setup
fullHeight — full height of multiview setup
x — horizontal offset of subcamera
y — vertical offset of subcamera
width — width of subcamera
height — height of subcamera

Sets an offset in a larger viewing frustum. This is useful for multi-window or multi-monitor/multi-machine setups. For an example on how to use it see PerspectiveCamera.

.clearViewOffset () : undefined

Removes any offset set by the .setViewOffset method.

.updateProjectionMatrix () : undefined

Updates the camera projection matrix. Must be called after any change of parameters.

.toJSON (meta : Object) : Object

meta -- object containing metadata such as textures or images in objects' descendants.
Convert the camera to three.js JSON Object/Scene format.

Source

src/cameras/OrthographicCamera.js

Object3DCamera

PerspectiveCamera

Camera that uses perspective projection.

This projection mode is designed to mimic the way the human eye sees. It is the most common projection mode used for rendering a 3D scene.

Code Example

const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); scene.add( camera );

Examples

animation / skinning / blending
animation / skinning / morph
effects / stereo
interactive / cubes
loader / collada / skinning

Constructor

PerspectiveCamera( fov : Number, aspect : Number, near : Number, far : Number )

fov — Camera frustum vertical field of view.
aspect — Camera frustum aspect ratio.
near — Camera frustum near plane.
far — Camera frustum far plane.

Together these define the camera's viewing frustum.

Properties

See the base Camera class for common properties.
Note that after making changes to most of these properties you will have to call .updateProjectionMatrix for the changes to take effect.

.aspect : Float

Camera frustum aspect ratio, usually the canvas width / canvas height. Default is 1 (square canvas).

.far : Float

Camera frustum far plane. Default is 2000.

Must be greater than the current value of near plane.

.filmGauge : Float

Film size used for the larger axis. Default is 35 (millimeters). This parameter does not influence the projection matrix unless .filmOffset is set to a nonzero value.

.filmOffset : Float

Horizontal off-center offset in the same unit as .filmGauge. Default is 0.

.focus : Float

Object distance used for stereoscopy and depth-of-field effects. This parameter does not influence the projection matrix unless a StereoCamera is being used. Default is 10.

.fov : Float

Camera frustum vertical field of view, from bottom to top of view, in degrees. Default is 50.

.isPerspectiveCamera : Boolean

Read-only flag to check if a given object is of type PerspectiveCamera.

.near : Float

Camera frustum near plane. Default is 0.1.

The valid range is greater than 0 and less than the current value of the far plane. Note that, unlike for the OrthographicCamera, 0 is not a valid value for a PerspectiveCamera's near plane.

.view : Object

Frustum window specification or null. This is set using the .setViewOffset method and cleared using .clearViewOffset.

.zoom : number

Gets or sets the zoom factor of the camera. Default is 1.

Methods

See the base Camera class for common methods.

.clearViewOffset () : undefined

Removes any offset set by the .setViewOffset method.

.getEffectiveFOV () : Float

Returns the current vertical field of view angle in degrees considering .zoom.

.getFilmHeight () : Float

Returns the height of the image on the film. If .aspect is less than or equal to one (portrait format), the result equals .filmGauge.

.getFilmWidth () : Float

Returns the width of the image on the film. If .aspect is greater than or equal to one (landscape format), the result equals .filmGauge.

.getFocalLength () : Float

Returns the focal length of the current .fov in respect to .filmGauge.

.setFocalLength ( focalLength : Float ) : undefined

Sets the FOV by focal length in respect to the current .filmGauge.

By default, the focal length is specified for a 35mm (full frame) camera.

.getViewBounds ( distance : Float, minTarget : Vector2, maxTarget : Vector2 ) : undefined

Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.

.getViewSize ( distance : Float, target : Vector2 ) : Vector2

Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. Copies the result into the target Vector2, where x is width and y is height.

.setViewOffset ( fullWidth : Float, fullHeight : Float, x : Float, y : Float, width : Float, height : Float ) : undefined

fullWidth — full width of multiview setup
fullHeight — full height of multiview setup
x — horizontal offset of subcamera
y — vertical offset of subcamera
width — width of subcamera
height — height of subcamera

Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups.

For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this:

+---+---+---+
| A | B | C |
+---+---+---+
| D | E | F |
+---+---+---+
		

const w = 1920; const h = 1080; const fullWidth = w * 3; const fullHeight = h * 2; // A camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); // B camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); // C camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); // D camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); // E camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); // F camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );

Note there is no reason monitors have to be the same size or in a grid.

.updateProjectionMatrix () : undefined

Updates the camera projection matrix. Must be called after any change of parameters.

.toJSON (meta : Object) : Object

meta -- object containing metadata such as textures or images in objects' descendants.
Convert the camera to three.js JSON Object/Scene format.

Source

src/cameras/PerspectiveCamera.js

StereoCamera

Dual PerspectiveCameras used for effects such as 3D Anaglyph or Parallax Barrier.

Examples

effects / anaglyph
effects / parallaxbarrier
effects / stereo

Constructor

StereoCamera( )

Properties

.aspect : Float

Default is 1.

.eyeSep : Float

Default is 0.064.

.cameraL : PerspectiveCamera

Left camera. This is added to layer 1 - objects to be rendered by the left camera must also be added to this layer.

.cameraR : PerspectiveCamera

Right camera.This is added to layer 2 - objects to be rendered by the right camera must also be added to this layer.

Methods

.update ( camera : PerspectiveCamera ) : undefined

Update the stereo cameras based on the camera passed in.

Source

src/cameras/StereoCamera.js

Animation Constants

Loop Modes

THREE.LoopOnce THREE.LoopRepeat THREE.LoopPingPong

Interpolation Modes

THREE.InterpolateDiscrete THREE.InterpolateLinear THREE.InterpolateSmooth

Ending Modes

THREE.ZeroCurvatureEnding THREE.ZeroSlopeEnding THREE.WrapAroundEnding

Animation Blend Modes

THREE.NormalAnimationBlendMode THREE.AdditiveAnimationBlendMode

Source

src/constants.js

Core Constants

Revision Number

THREE.REVISION
The current three.js revision number.

Color Spaces

THREE.NoColorSpace = "" THREE.SRGBColorSpace = "srgb" THREE.LinearSRGBColorSpace = "srgb-linear"

NoColorSpace defines no specific color space. It is commonly used for textures including normal maps, roughness maps, metalness maps, ambient occlusion maps, and other non-color data.

SRGBColorSpace (“srgb”) refers to the color space defined by the Rec. 709 primaries, D65 white point, and nonlinear sRGB transfer functions. sRGB is the default color space in CSS, and is often found in color palettes and color pickers. Colors expressed in hexadecimal or CSS notation are typically in the sRGB color space.

LinearSRGBColorSpace (“srgb-linear”) refers to the sRGB color space (above) with linear transfer functions. Linear-sRGB is the working color space in three.js, used throughout most of the rendering process. RGB components found in three.js materials and shaders are in the Linear-sRGB color space.

For further background and usage, see Color management.

Mouse Buttons

THREE.MOUSE.LEFT THREE.MOUSE.MIDDLE THREE.MOUSE.RIGHT THREE.MOUSE.ROTATE THREE.MOUSE.DOLLY THREE.MOUSE.PAN

The constants LEFT and ROTATE have the same underlying value. The constants MIDDLE and DOLLY have the same underlying value. The constants RIGHT and PAN have the same underlying value.

Touch Actions

THREE.TOUCH.ROTATE THREE.TOUCH.PAN THREE.TOUCH.DOLLY_PAN THREE.TOUCH.DOLLY_ROTATE

Source

src/constants.js

Custom Blending Equation Constants

These work with all material types. First set the material's blending mode to THREE.CustomBlending, then set the desired Blending Equation, Source Factor and Destination Factor.

Code Example

const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} ); material.blending = THREE.CustomBlending; material.blendEquation = THREE.AddEquation; //default material.blendSrc = THREE.SrcAlphaFactor; //default material.blendDst = THREE.OneMinusSrcAlphaFactor; //default

Examples

materials / blending / custom

Blending Equations

THREE.AddEquation THREE.SubtractEquation THREE.ReverseSubtractEquation THREE.MinEquation THREE.MaxEquation

Source Factors

THREE.ZeroFactor THREE.OneFactor THREE.SrcColorFactor THREE.OneMinusSrcColorFactor THREE.SrcAlphaFactor THREE.OneMinusSrcAlphaFactor THREE.DstAlphaFactor THREE.OneMinusDstAlphaFactor THREE.DstColorFactor THREE.OneMinusDstColorFactor THREE.SrcAlphaSaturateFactor THREE.ConstantColorFactor THREE.OneMinusConstantColorFactor THREE.ConstantAlphaFactor THREE.OneMinusConstantAlphaFactor

Destination Factors

All of the Source Factors are valid as Destination Factors, except for THREE.SrcAlphaSaturateFactor

Source

src/constants.js

Buffer Attribute Usage Constants

The usage constants can be used to provide a hint to the API regarding how the geometry buffer attribute will be used in order to optimize performance.

Code Example

const geometry = new THREE.BufferGeometry(); const positionAttribute = new THREE.BufferAttribute( array, 3 , false ); positionAttribute.setUsage( THREE.DynamicDrawUsage ); geometry.setAttribute( 'position', positionAttribute );

Examples

materials / buffergeometry / drawrange

Geometry Usage

THREE.StaticDrawUsage THREE.DynamicDrawUsage THREE.StreamDrawUsage THREE.StaticReadUsage THREE.DynamicReadUsage THREE.StreamReadUsage THREE.StaticCopyUsage THREE.DynamicCopyUsage THREE.StreamCopyUsagethis OpenGL documentation

Source

src/constants.js

Material Constants

These constants define properties common to all material types, with the exception of Texture Combine Operations which only apply to MeshBasicMaterial, MeshLambertMaterial and MeshPhongMaterial.

Side

THREE.FrontSide THREE.BackSide THREE.DoubleSide

Defines which side of faces will be rendered - front, back or both. Default is FrontSide.

Blending Mode

THREE.NoBlending THREE.NormalBlending THREE.AdditiveBlending THREE.SubtractiveBlending THREE.MultiplyBlending THREE.CustomBlending

These control the source and destination blending equations for the material's RGB and Alpha sent to the WebGLRenderer for use by WebGL.
NormalBlending is the default.
Note that CustomBlending must be set to use Custom Blending Equations.
See the materials / blending example.

Depth Mode

THREE.NeverDepth THREE.AlwaysDepth THREE.EqualDepth THREE.LessDepth THREE.LessEqualDepth THREE.GreaterEqualDepth THREE.GreaterDepth THREE.NotEqualDepth

Which depth function the material uses to compare incoming pixels Z-depth against the current Z-depth buffer value. If the result of the comparison is true, the pixel will be drawn.
NeverDepth will never return true.
AlwaysDepth will always return true.
EqualDepth will return true if the incoming pixel Z-depth is equal to the current buffer Z-depth.
LessDepth will return true if the incoming pixel Z-depth is less than the current buffer Z-depth.
LessEqualDepth is the default and will return true if the incoming pixel Z-depth is less than or equal to the current buffer Z-depth.
GreaterEqualDepth will return true if the incoming pixel Z-depth is greater than or equal to the current buffer Z-depth.
GreaterDepth will return true if the incoming pixel Z-depth is greater than the current buffer Z-depth.
NotEqualDepth will return true if the incoming pixel Z-depth is not equal to the current buffer Z-depth.

Texture Combine Operations

THREE.MultiplyOperation THREE.MixOperation THREE.AddOperation

These define how the result of the surface's color is combined with the environment map (if present), for MeshBasicMaterial, MeshLambertMaterial and MeshPhongMaterial.
MultiplyOperation is the default and multiplies the environment map color with the surface color.
MixOperation uses reflectivity to blend between the two colors.
AddOperation adds the two colors.

Stencil Functions

THREE.NeverStencilFunc THREE.LessStencilFunc THREE.EqualStencilFunc THREE.LessEqualStencilFunc THREE.GreaterStencilFunc THREE.NotEqualStencilFunc THREE.GreaterEqualStencilFunc THREE.AlwaysStencilFunc

Which stencil function the material uses to determine whether or not to perform a stencil operation.
NeverStencilFunc will never return true.
LessStencilFunc will return true if the stencil reference value is less than the current stencil value.
EqualStencilFunc will return true if the stencil reference value is equal to the current stencil value.
LessEqualStencilFunc will return true if the stencil reference value is less than or equal to the current stencil value.
GreaterStencilFunc will return true if the stencil reference value is greater than the current stencil value.
NotEqualStencilFunc will return true if the stencil reference value is not equal to the current stencil value.
GreaterEqualStencilFunc will return true if the stencil reference value is greater than or equal to the current stencil value.
AlwaysStencilFunc will always return true.

Stencil Operations

THREE.ZeroStencilOp THREE.KeepStencilOp THREE.ReplaceStencilOp THREE.IncrementStencilOp THREE.DecrementStencilOp THREE.IncrementWrapStencilOp THREE.DecrementWrapStencilOp THREE.InvertStencilOp

Which stencil operation the material will perform on the stencil buffer pixel if the provided stencil function passes.
ZeroStencilOp will set the stencil value to 0.
KeepStencilOp will not change the current stencil value.
ReplaceStencilOp will replace the stencil value with the specified stencil reference value.
IncrementStencilOp will increment the current stencil value by 1.
DecrementStencilOp will decrement the current stencil value by 1.
IncrementWrapStencilOp will increment the current stencil value by 1. If the value increments past 255 it will be set to 0.
DecrementWrapStencilOp will increment the current stencil value by 1. If the value decrements below 0 it will be set to 255.
InvertStencilOp will perform a bitwise inversion of the current stencil value.

Normal map type

THREE.TangentSpaceNormalMap THREE.ObjectSpaceNormalMap

Defines the type of the normal map. For TangentSpaceNormalMap, the information is relative to the underlying surface. For ObjectSpaceNormalMap, the information is relative to the object orientation. Default is TangentSpaceNormalMap.

GLSL Version

THREE.GLSL1 THREE.GLSL3

Source

src/constants.js

WebGLRenderer Constants

Cull Face Modes

THREE.CullFaceNone THREE.CullFaceBack THREE.CullFaceFront THREE.CullFaceFrontBack

CullFaceNone disables face culling.
CullFaceBack culls back faces (default).
CullFaceFront culls front faces.
CullFaceFrontBack culls both front and back faces.

Shadow Types

THREE.BasicShadowMap THREE.PCFShadowMap THREE.PCFSoftShadowMap THREE.VSMShadowMap

These define the WebGLRenderer's shadowMap.type property.

BasicShadowMap gives unfiltered shadow maps - fastest, but lowest quality.
PCFShadowMap filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm (default).
PCFSoftShadowMap filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with better soft shadows especially when using low-resolution shadow maps.
VSMShadowMap filters shadow maps using the Variance Shadow Map (VSM) algorithm. When using VSMShadowMap all shadow receivers will also cast shadows.

Tone Mapping

THREE.NoToneMapping THREE.LinearToneMapping THREE.ReinhardToneMapping THREE.CineonToneMapping THREE.ACESFilmicToneMapping THREE.AgXToneMapping THREE.NeutralToneMapping THREE.CustomToneMapping

These define the WebGLRenderer's toneMapping property. This is used to approximate the appearance of high dynamic range (HDR) on the low dynamic range medium of a standard computer monitor or mobile device's screen.

THREE.LinearToneMapping, THREE.ReinhardToneMapping, THREE.CineonToneMapping, THREE.ACESFilmicToneMapping, THREE.AgXToneMapping and THREE.NeutralToneMapping are built-in implementations of tone mapping. THREE.CustomToneMapping expects a custom implementation by modifying GLSL code of the material's fragment shader. See the WebGL / tonemapping example.

THREE.NeutralToneMapping is an implementation based on the Khronos 3D Commerce Group standard tone mapping.

Source

src/constants.js

Texture Constants

Mapping Modes

THREE.UVMapping THREE.CubeReflectionMapping THREE.CubeRefractionMapping THREE.EquirectangularReflectionMapping THREE.EquirectangularRefractionMapping THREE.CubeUVReflectionMapping

These define the texture's mapping mode.
UVMapping is the default, and maps the texture using the mesh's UV coordinates.

The rest define environment mapping types.

CubeReflectionMapping and CubeRefractionMapping are for use with a CubeTexture, which is made up of six textures, one for each face of the cube. CubeReflectionMapping is the default for a CubeTexture.

EquirectangularReflectionMapping and EquirectangularRefractionMapping are for use with an equirectangular environment map. Also called a lat-long map, an equirectangular texture represents a 360-degree view along the horizontal centerline, and a 180-degree view along the vertical axis, with the top and bottom edges of the image corresponding to the north and south poles of a mapped sphere.

See the materials / envmaps example.

Wrapping Modes

THREE.RepeatWrapping THREE.ClampToEdgeWrapping THREE.MirroredRepeatWrapping

These define the texture's wrapS and wrapT properties, which define horizontal and vertical texture wrapping.

With RepeatWrapping the texture will simply repeat to infinity.

ClampToEdgeWrapping is the default. The last pixel of the texture stretches to the edge of the mesh.

With MirroredRepeatWrapping the texture will repeats to infinity, mirroring on each repeat.

Magnification Filters

THREE.NearestFilter THREE.LinearFilter

For use with a texture's magFilter property, these define the texture magnification function to be used when the pixel being textured maps to an area less than or equal to one texture element (texel).

NearestFilter returns the value of the texture element that is nearest (in Manhattan distance) to the specified texture coordinates.

LinearFilter is the default and returns the weighted average of the four texture elements that are closest to the specified texture coordinates, and can include items wrapped or repeated from other parts of a texture, depending on the values of wrapS and wrapT, and on the exact mapping.

Minification Filters

THREE.NearestFilter THREE.NearestMipmapNearestFilter THREE.NearestMipmapLinearFilter THREE.LinearFilter THREE.LinearMipmapNearestFilter THREE.LinearMipmapLinearFilter

For use with a texture's minFilter property, these define the texture minifying function that is used whenever the pixel being textured maps to an area greater than one texture element (texel).

In addition to NearestFilter and LinearFilter, the following four functions can be used for minification:

NearestMipmapNearestFilter chooses the mipmap that most closely matches the size of the pixel being textured and uses the NearestFilter criterion (the texel nearest to the center of the pixel) to produce a texture value.

NearestMipmapLinearFilter chooses the two mipmaps that most closely match the size of the pixel being textured and uses the NearestFilter criterion to produce a texture value from each mipmap. The final texture value is a weighted average of those two values.

LinearMipmapNearestFilter chooses the mipmap that most closely matches the size of the pixel being textured and uses the LinearFilter criterion (a weighted average of the four texels that are closest to the center of the pixel) to produce a texture value.

LinearMipmapLinearFilter is the default and chooses the two mipmaps that most closely match the size of the pixel being textured and uses the LinearFilter criterion to produce a texture value from each mipmap. The final texture value is a weighted average of those two values.

See the materials / texture / filters example.

Types

THREE.UnsignedByteType THREE.ByteType THREE.ShortType THREE.UnsignedShortType THREE.IntType THREE.UnsignedIntType THREE.FloatType THREE.HalfFloatType THREE.UnsignedShort4444Type THREE.UnsignedShort5551Type THREE.UnsignedInt248Type THREE.UnsignedInt5999Type

For use with a texture's type property, which must correspond to the correct format. See below for details.

UnsignedByteType is the default.

Formats

THREE.AlphaFormat THREE.RedFormat THREE.RedIntegerFormat THREE.RGFormat THREE.RGIntegerFormat THREE.RGBFormat THREE.RGBAFormat THREE.RGBAIntegerFormat THREE.LuminanceFormat THREE.LuminanceAlphaFormat THREE.DepthFormat THREE.DepthStencilFormat

For use with a texture's format property, these define how elements of a 2d texture, or texels, are read by shaders.

AlphaFormat discards the red, green and blue components and reads just the alpha component.

RedFormat discards the green and blue components and reads just the red component.

RedIntegerFormat discards the green and blue components and reads just the red component. The texels are read as integers instead of floating point.

RGFormat discards the alpha, and blue components and reads the red, and green components.

RGIntegerFormat discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.

RGBAFormat is the default and reads the red, green, blue and alpha components.

RGBAIntegerFormat is the default and reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.

LuminanceFormat reads each element as a single luminance component. This is then converted to a floating point, clamped to the range [0,1], and then assembled into an RGBA element by placing the luminance value in the red, green and blue channels, and attaching 1.0 to the alpha channel.

LuminanceAlphaFormat reads each element as a luminance/alpha double. The same process occurs as for the LuminanceFormat, except that the alpha channel may have values other than 1.0.

DepthFormat reads each element as a single depth value, converts it to floating point, and clamps to the range [0,1]. This is the default for DepthTexture.

DepthStencilFormat reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as in DepthFormat. The stencil component is interpreted based on the depth + stencil internal format.

Note that the texture must have the correct type set, as described above. See WebGLRenderingContext.texImage2D for details.

DDS / ST3C Compressed Texture Formats

THREE.RGB_S3TC_DXT1_Format THREE.RGBA_S3TC_DXT1_Format THREE.RGBA_S3TC_DXT3_Format THREE.RGBA_S3TC_DXT5_Format

For use with a CompressedTexture's format property, these require support for the WEBGL_compressed_texture_s3tc extension.

There are four S3TC formats available via this extension. These are:
RGB_S3TC_DXT1_Format: A DXT1-compressed image in an RGB image format.
RGBA_S3TC_DXT1_Format: A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
RGBA_S3TC_DXT3_Format: A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
RGBA_S3TC_DXT5_Format: A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.

PVRTC Compressed Texture Formats

THREE.RGB_PVRTC_4BPPV1_Format THREE.RGB_PVRTC_2BPPV1_Format THREE.RGBA_PVRTC_4BPPV1_Format THREE.RGBA_PVRTC_2BPPV1_Format

For use with a CompressedTexture's format property, these require support for the [link:https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/ WEBGL_compressed_texture_pvrtc] extension.
PVRTC is typically only available on mobile devices with PowerVR chipsets, which are mainly Apple devices.

There are four PVRTC formats available via this extension. These are:
RGB_PVRTC_4BPPV1_Format: RGB compression in 4-bit mode. One block for each 4×4 pixels.
RGB_PVRTC_2BPPV1_Format: RGB compression in 2-bit mode. One block for each 8×4 pixels.
RGBA_PVRTC_4BPPV1_Format: RGBA compression in 4-bit mode. One block for each 4×4 pixels.
RGBA_PVRTC_2BPPV1_Format: RGBA compression in 2-bit mode. One block for each 8×4 pixels.

ETC Compressed Texture Format

THREE.RGB_ETC1_Format THREE.RGB_ETC2_Format THREE.RGBA_ETC2_EAC_Format

For use with a CompressedTexture's format property, these require support for the WEBGL_compressed_texture_etc1 (ETC1) or WEBGL_compressed_texture_etc (ETC2) extensions.

ASTC Compressed Texture Format

THREE.RGBA_ASTC_4x4_Format THREE.RGBA_ASTC_5x4_Format THREE.RGBA_ASTC_5x5_Format THREE.RGBA_ASTC_6x5_Format THREE.RGBA_ASTC_6x6_Format THREE.RGBA_ASTC_8x5_Format THREE.RGBA_ASTC_8x6_Format THREE.RGBA_ASTC_8x8_Format THREE.RGBA_ASTC_10x5_Format THREE.RGBA_ASTC_10x6_Format THREE.RGBA_ASTC_10x8_Format THREE.RGBA_ASTC_10x10_Format THREE.RGBA_ASTC_12x10_Format THREE.RGBA_ASTC_12x12_Format

For use with a CompressedTexture's format property, these require support for the WEBGL_compressed_texture_astc extension.

BPTC Compressed Texture Format

THREE.RGBA_BPTC_Format

For use with a CompressedTexture's format property, these require support for the EXT_texture_compression_bptc extension.

Texture Comparison functions

THREE.NeverCompare THREE.LessCompare THREE.EqualCompare THREE.LessEqualCompare THREE.GreaterCompare THREE.NotEqualCompare THREE.GreaterEqualCompare THREE.AlwaysCompare

Internal Formats

'ALPHA' 'RGB' 'RGBA' 'LUMINANCE' 'LUMINANCE_ALPHA' 'RED_INTEGER' 'R8' 'R8_SNORM' 'R8I' 'R8UI' 'R16I' 'R16UI' 'R16F' 'R32I' 'R32UI' 'R32F' 'RG8' 'RG8_SNORM' 'RG8I' 'RG8UI' 'RG16I' 'RG16UI' 'RG16F' 'RG32I' 'RG32UI' 'RG32F' 'RGB565' 'RGB8' 'RGB8_SNORM' 'RGB8I' 'RGB8UI' 'RGB16I' 'RGB16UI' 'RGB16F' 'RGB32I' 'RGB32UI' 'RGB32F' 'RGB9_E5' 'SRGB8' 'R11F_G11F_B10F' 'RGBA4' 'RGBA8' 'RGBA8_SNORM' 'RGBA8I' 'RGBA8UI' 'RGBA16I' 'RGBA16UI' 'RGBA16F' 'RGBA32I' 'RGBA32UI' 'RGBA32F' 'RGB5_A1' 'RGB10_A2' 'RGB10_A2UI' 'SRGB8_ALPHA8' 'DEPTH_COMPONENT16' 'DEPTH_COMPONENT24' 'DEPTH_COMPONENT32F' 'DEPTH24_STENCIL8' 'DEPTH32F_STENCIL8'

For use with a texture's internalFormat property, these define how elements of a texture, or texels, are stored on the GPU.

R8 stores the red component on 8 bits.

R8_SNORM stores the red component on 8 bits. The component is stored as normalized.

R8I stores the red component on 8 bits. The component is stored as an integer.

R8UI stores the red component on 8 bits. The component is stored as an unsigned integer.

R16I stores the red component on 16 bits. The component is stored as an integer.

R16UI stores the red component on 16 bits. The component is stored as an unsigned integer.

R16F stores the red component on 16 bits. The component is stored as floating point.

R32I stores the red component on 32 bits. The component is stored as an integer.

R32UI stores the red component on 32 bits. The component is stored as an unsigned integer.

R32F stores the red component on 32 bits. The component is stored as floating point.

RG8 stores the red and green components on 8 bits each.

RG8_SNORM stores the red and green components on 8 bits each. Every component is stored as normalized.

RG8I stores the red and green components on 8 bits each. Every component is stored as an integer.

RG8UI stores the red and green components on 8 bits each. Every component is stored as an unsigned integer.

RG16I stores the red and green components on 16 bits each. Every component is stored as an integer.

RG16UI stores the red and green components on 16 bits each. Every component is stored as an unsigned integer.

RG16F stores the red and green components on 16 bits each. Every component is stored as floating point.

RG32I stores the red and green components on 32 bits each. Every component is stored as an integer.

RG32UI stores the red and green components on 32 bits. Every component is stored as an unsigned integer.

RG32F stores the red and green components on 32 bits. Every component is stored as floating point.

RGB8 stores the red, green, and blue components on 8 bits each. RGB8_SNORM stores the red, green, and blue components on 8 bits each. Every component is stored as normalized.

RGB8I stores the red, green, and blue components on 8 bits each. Every component is stored as an integer.

RGB8UI stores the red, green, and blue components on 8 bits each. Every component is stored as an unsigned integer.

RGB16I stores the red, green, and blue components on 16 bits each. Every component is stored as an integer.

RGB16UI stores the red, green, and blue components on 16 bits each. Every component is stored as an unsigned integer.

RGB16F stores the red, green, and blue components on 16 bits each. Every component is stored as floating point

RGB32I stores the red, green, and blue components on 32 bits each. Every component is stored as an integer.

RGB32UI stores the red, green, and blue components on 32 bits each. Every component is stored as an unsigned integer.

RGB32F stores the red, green, and blue components on 32 bits each. Every component is stored as floating point

R11F_G11F_B10F stores the red, green, and blue components respectively on 11 bits, 11 bits, and 10bits. Every component is stored as floating point.

RGB565 stores the red, green, and blue components respectively on 5 bits, 6 bits, and 5 bits.

RGB9_E5 stores the red, green, and blue components on 9 bits each.

RGBA8 stores the red, green, blue, and alpha components on 8 bits each.

RGBA8_SNORM stores the red, green, blue, and alpha components on 8 bits. Every component is stored as normalized.

RGBA8I stores the red, green, blue, and alpha components on 8 bits each. Every component is stored as an integer.

RGBA8UI stores the red, green, blue, and alpha components on 8 bits. Every component is stored as an unsigned integer.

RGBA16I stores the red, green, blue, and alpha components on 16 bits. Every component is stored as an integer.

RGBA16UI stores the red, green, blue, and alpha components on 16 bits. Every component is stored as an unsigned integer.

RGBA16F stores the red, green, blue, and alpha components on 16 bits. Every component is stored as floating point.

RGBA32I stores the red, green, blue, and alpha components on 32 bits. Every component is stored as an integer.

RGBA32UI stores the red, green, blue, and alpha components on 32 bits. Every component is stored as an unsigned integer.

RGBA32F stores the red, green, blue, and alpha components on 32 bits. Every component is stored as floating point.

RGB5_A1 stores the red, green, blue, and alpha components respectively on 5 bits, 5 bits, 5 bits, and 1 bit.

RGB10_A2 stores the red, green, blue, and alpha components respectively on 10 bits, 10 bits, 10 bits and 2 bits.

RGB10_A2UI stores the red, green, blue, and alpha components respectively on 10 bits, 10 bits, 10 bits and 2 bits. Every component is stored as an unsigned integer.

SRGB8 stores the red, green, and blue components on 8 bits each.

SRGB8_ALPHA8 stores the red, green, blue, and alpha components on 8 bits each.

DEPTH_COMPONENT16 stores the depth component on 16bits.

DEPTH_COMPONENT24 stores the depth component on 24bits.

DEPTH_COMPONENT32F stores the depth component on 32bits. The component is stored as floating point.

DEPTH24_STENCIL8 stores the depth, and stencil components respectively on 24 bits and 8 bits. The stencil component is stored as an unsigned integer.

DEPTH32F_STENCIL8 stores the depth, and stencil components respectively on 32 bits and 8 bits. The depth component is stored as floating point, and the stencil component as an unsigned integer.

Note that the texture must have the correct type set, as well as the correct format. See WebGLRenderingContext.texImage2D, and WebGL2RenderingContext.texImage3D, for more details regarding the possible combination of format, internalFormat, and type.

For more in-depth information regarding internal formats, you can also refer directly to the WebGL2 Specification and to the OpenGL ES 3.0 Specification.

Depth Packing

THREE.BasicDepthPacking THREE.RGBADepthPacking

For use with the depthPacking property of MeshDepthMaterial.

Color Space

THREE.NoColorSpace = "" THREE.SRGBColorSpace = "srgb" THREE.LinearSRGBColorSpace = "srgb-linear"

Used to define the color space of textures (and the output color space of the renderer).

If the color space type is changed after the texture has already been used by a material, you will need to set Material.needsUpdate to true to make the material recompile.

Source

src/constants.js

BufferAttribute

This 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. See that page for details and a usage example. When working with vector-like data, the .fromBufferAttribute( attribute, index ) helper methods on Vector2, Vector3, Vector4, and Color classes may be helpful.

Constructor

BufferAttribute( array : TypedArray, itemSize : Integer, normalized : Boolean )

array -- Must be a TypedArray. Used to instantiate the buffer.
This array should have itemSize * numVertices elements, where numVertices is the number of vertices in the associated BufferGeometry.

itemSize -- the number of values of the array that should be associated with a particular vertex. For instance, if this attribute is storing a 3-component vector (such as a position, normal, or color), then itemSize should be 3.

normalized -- (optional) Applies to integer data only. Indicates how the underlying data in the buffer maps to the values in the GLSL code. For instance, if array is an instance of UInt16Array, and normalized is true, the values 0 - +65535 in the array data will be mapped to 0.0f - +1.0f in the GLSL attribute. An Int16Array (signed) would map from -32768 - +32767 to -1.0f - +1.0f. If normalized is false, the values will be converted to floats unmodified, i.e. 32767 becomes 32767.0f.

Properties

.array : TypedArray

The array holding data stored in the buffer.

.count : Integer

Represents the number of items this buffer attribute stores. It is internally computed by dividing the array's length by the itemSize. Read-only property.

.gpuType : Number

Configures the bound GPU type for use in shaders. Either THREE.FloatType or THREE.IntType, default is THREE.FloatType. Note: this only has an effect for integer arrays and is not configurable for float arrays. For lower precision float types, see THREE.Float16BufferAttribute.

.isBufferAttribute : Boolean

Read-only flag to check if a given object is of type BufferAttribute.

.itemSize : Integer

The length of vectors that are being stored in the array.

.name : String

Optional name for this attribute instance. Default is an empty string.

.needsUpdate : Boolean

Flag to indicate that this attribute has changed and should be re-sent to the GPU. Set this to true when you modify the value of the array.

Setting this to true also increments the version.

.normalized : Boolean

Indicates how the underlying data in the buffer maps to the values in the GLSL shader code. See the constructor above for details.

.onUploadCallback : Function

A callback function that is executed after the Renderer has transferred the attribute array data to the GPU.

.updateRanges : Object

Array of objects containing:
start: Position at which to start update.
count: The number of components to update.

This can be used to only update some components of stored vectors (for example, just the component related to color). Use the addUpdateRange function to add ranges to this array.

.usage : Usage

Defines the intended usage pattern of the data store for optimization purposes. Corresponds to the usage parameter of WebGLRenderingContext.bufferData(). Default is StaticDrawUsage. See usage constants for all possible values.

Note: After the initial use of a buffer, its usage cannot be changed. Instead, instantiate a new one and set the desired usage before the next render.

.version : Integer

A version number, incremented every time the needsUpdate property is set to true.

Methods

.applyMatrix3 ( m : Matrix3 ) : this

Applies matrix m to every Vector3 element of this BufferAttribute.

.applyMatrix4 ( m : Matrix4 ) : this

Applies matrix m to every Vector3 element of this BufferAttribute.

.applyNormalMatrix ( m : Matrix3 ) : this

Applies normal matrix m to every Vector3 element of this BufferAttribute.

.transformDirection ( m : Matrix4 ) : this

Applies matrix m to every Vector3 element of this BufferAttribute, interpreting the elements as a direction vectors.

.addUpdateRange ( start : Integer, count : Integer ) : this

Adds a range of data in the data array to be updated on the GPU. Adds an object describing the range to the updateRanges array.

.clearUpdateRanges () : this

Clears the updateRanges array.

.clone () : BufferAttribute

Return a copy of this bufferAttribute.

.copy ( bufferAttribute : BufferAttribute ) : this

Copies another BufferAttribute to this BufferAttribute.

.copyArray ( array ) : this

Copy the array given here (which can be a normal array or TypedArray) into array.

See TypedArray.set for notes on requirements if copying a TypedArray.

.copyAt ( index1 : Integer, bufferAttribute : BufferAttribute, index2 : Integer ) : this

Copy a vector from bufferAttribute[index2] to array[index1].

.getComponent ( index : Integer, component : Integer ) : Number

Returns the given component of the vector at the given index.

.getX ( index : Integer ) : Number

Returns the x component of the vector at the given index.

.getY ( index : Integer ) : Number

Returns the y component of the vector at the given index.

.getZ ( index : Integer ) : Number

Returns the z component of the vector at the given index.

.getW ( index : Integer ) : Number

Returns the w component of the vector at the given index.

.onUpload ( callback : Function ) : this

Sets the value of the onUploadCallback property.

In the WebGL / Buffergeometry this is used to free memory after the buffer has been transferred to the GPU.

.set ( value : Array, offset : Integer ) : this

value -- an Array or TypedArray from which to copy values.
offset -- (optional) index of the array at which to start copying.

Calls TypedArray.set( value, offset ) on the array.

In particular, see that page for requirements on value being a TypedArray.

.setUsage ( value : Usage ) : this

Set usage to value. See usage constants for all possible input values.

Note: After the initial use of a buffer, its usage cannot be changed. Instead, instantiate a new one and set the desired usage before the next render.

.setComponent ( index : Integer, component : Integer, value : Float ) : Number

Sets the given component of the vector at the given index.

.setX ( index : Integer, x : Float ) : this

Sets the x component of the vector at the given index.

.setY ( index : Integer, y : Float ) : this

Sets the y component of the vector at the given index.

.setZ ( index : Integer, z : Float ) : this

Sets the z component of the vector at the given index.

.setW ( index : Integer, w : Float ) : this

Sets the w component of the vector at the given index.

.setXY ( index : Integer, x : Float, y : Float ) : this

Sets the x and y components of the vector at the given index.

.setXYZ ( index : Integer, x : Float, y : Float, z : Float ) : this

Sets the x, y and z components of the vector at the given index.

.setXYZW ( index : Integer, x : Float, y : Float, z : Float, w : Float ) : this

Sets the x, y, z and w components of the vector at the given index.

Source

src/core/BufferAttribute.js

BufferGeometry

A representation of mesh, line, or point geometry. Includes vertex positions, face indices, normals, colors, UVs, and custom attributes within buffers, reducing the cost of passing all this data to the GPU.

To read and edit data in BufferGeometry attributes, see BufferAttribute documentation.

Code Example

const geometry = new THREE.BufferGeometry(); // create a simple square shape. We duplicate the top left and bottom right // vertices because each vertex needs to appear once per triangle. const vertices = new Float32Array( [ -1.0, -1.0, 1.0, // v0 1.0, -1.0, 1.0, // v1 1.0, 1.0, 1.0, // v2 1.0, 1.0, 1.0, // v3 -1.0, 1.0, 1.0, // v4 -1.0, -1.0, 1.0 // v5 ] ); // itemSize = 3 because there are 3 values (components) per vertex geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); const mesh = new THREE.Mesh( geometry, material );

Code Example (Index)

const geometry = new THREE.BufferGeometry(); const vertices = new Float32Array( [ -1.0, -1.0, 1.0, // v0 1.0, -1.0, 1.0, // v1 1.0, 1.0, 1.0, // v2 -1.0, 1.0, 1.0, // v3 ] ); const indices = [ 0, 1, 2, 2, 3, 0, ]; geometry.setIndex( indices ); geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } ); const mesh = new THREE.Mesh( geometry, material );

Examples

Mesh with non-indexed faces
Mesh with indexed faces
Lines
Indexed Lines
Particles
Raw Shaders

Constructor

BufferGeometry()

This creates a new BufferGeometry. It also sets several properties to a default value.

Properties

.attributes : Object

This hashmap has as id the name of the attribute to be set and as value the buffer to set it to. Rather than accessing this property directly, use .setAttribute and .getAttribute to access attributes of this geometry.

.boundingBox : Box3

Bounding box for the bufferGeometry, which can be calculated with .computeBoundingBox(). Default is null.

.boundingSphere : Sphere

Bounding sphere for the bufferGeometry, which can be calculated with .computeBoundingSphere(). Default is null.

.drawRange : Object

Determines the part of the geometry to render. This should not be set directly, instead use .setDrawRange. Default is { start: 0, count: Infinity } For non-indexed BufferGeometry, count is the number of vertices to render. For indexed BufferGeometry, count is the number of indices to render.

.groups : Array

Split the geometry into groups, each of which will be rendered in a separate WebGL draw call. This allows an array of materials to be used with the geometry.

Each group is an object of the form: { start: Integer, count: Integer, materialIndex: Integer } where start specifies the first element in this draw call – the first vertex for non-indexed geometry, otherwise the first triangle index. Count specifies how many vertices (or indices) are included, and materialIndex specifies the material array index to use.

Use .addGroup to add groups, rather than modifying this array directly.

Every vertex and index must belong to exactly one group — groups must not share vertices or indices, and must not leave vertices or indices unused.

.id : Integer

Unique number for this bufferGeometry instance.

.index : BufferAttribute

Allows for vertices to be re-used across multiple triangles; this is called using "indexed triangles". Each triangle is associated with the indices of three vertices. This attribute therefore stores the index of each vertex for each triangular face. If this attribute is not set, the renderer assumes that each three contiguous positions represent a single triangle. Default is null.

.isBufferGeometry : Boolean

Read-only flag to check if a given object is of type BufferGeometry.

.morphAttributes : Object

Hashmap of BufferAttributes holding details of the geometry's morph targets.
Note: Once the geometry has been rendered, the morph attribute data cannot be changed. You will have to call .dispose(), and create a new instance of BufferGeometry.

.morphTargetsRelative : Boolean

Used to control the morph target behavior; when set to true, the morph target data is treated as relative offsets, rather than as absolute positions/normals. Default is false.

.name : String

Optional name for this bufferGeometry instance. Default is an empty string.

.userData : Object

An object that can be used to store custom data about the BufferGeometry. It should not hold references to functions as these will not be cloned. Default is an empty object {}.

.uuid : String

UUID of this object instance. This gets automatically assigned and shouldn't be edited.

Methods

EventDispatcher methods are available on this class.

.addGroup ( start : Integer, count : Integer, materialIndex : Integer ) : undefined

Adds a group to this geometry; see the groups property for details.

.applyMatrix4 ( matrix : Matrix4 ) : this

Applies the matrix transform to the geometry.

.applyQuaternion ( quaternion : Quaternion ) : this

Applies the rotation represented by the quaternion to the geometry.

.center () : this

Center the geometry based on the bounding box.

.clearGroups ( ) : undefined

Clears all groups.

.clone () : BufferGeometry

Creates a clone of this BufferGeometry.

.computeBoundingBox () : undefined

Computes the bounding box of the geometry, and updates the .boundingBox attribute. The bounding box is not computed by the engine; it must be computed by your app. You may need to recompute the bounding box if the geometry vertices are modified.

.computeBoundingSphere () : undefined

Computes the bounding sphere of the geometry, and updates the .boundingSphere attribute. The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. You may need to recompute the bounding sphere if the geometry vertices are modified.

.computeTangents () : undefined

Calculates and adds a tangent attribute to this geometry.
The computation is only supported for indexed geometries and if position, normal, and uv attributes are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by BufferGeometryUtils.computeMikkTSpaceTangents instead.

.computeVertexNormals () : undefined

Computes vertex normals for the given vertex data. For indexed geometries, the method sets each vertex normal to be the average of the face normals of the faces that share that vertex. For non-indexed geometries, vertices are not shared, and the method sets each vertex normal to be the same as the face normal.

.copy ( bufferGeometry : BufferGeometry ) : this

Copies another BufferGeometry to this BufferGeometry.

.deleteAttribute ( name : String ) : BufferAttribute

Deletes the attribute with the specified name.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.getAttribute ( name : String ) : BufferAttribute

Returns the attribute with the specified name.

.getIndex () : BufferAttribute

Return the .index buffer.

.hasAttribute ( name : String ) : Boolean

Returns true if the attribute with the specified name exists.

.lookAt ( vector : Vector3 ) : this

vector - A world vector to look at.

Rotates the geometry to face a point in space. This is typically done as a one time operation, and not during a loop. Use Object3D.lookAt for typical real-time mesh usage.

.normalizeNormals () : undefined

Every normal vector in a geometry will have a magnitude of 1. This will correct lighting on the geometry surfaces.

.rotateX ( radians : Float ) : this

Rotate the geometry about the X axis. This is typically done as a one time operation, and not during a loop. Use Object3D.rotation for typical real-time mesh rotation.

.rotateY ( radians : Float ) : this

Rotate the geometry about the Y axis. This is typically done as a one time operation, and not during a loop. Use Object3D.rotation for typical real-time mesh rotation.

.rotateZ ( radians : Float ) : this

Rotate the geometry about the Z axis. This is typically done as a one time operation, and not during a loop. Use Object3D.rotation for typical real-time mesh rotation.

.scale ( x : Float, y : Float, z : Float ) : this

Scale the geometry data. This is typically done as a one time operation, and not during a loop. Use Object3D.scale for typical real-time mesh scaling.

.setAttribute ( name : String, attribute : BufferAttribute ) : this

Sets an attribute to this geometry. Use this rather than the attributes property, because an internal hashmap of .attributes is maintained to speed up iterating over attributes.

.setDrawRange ( start : Integer, count : Integer ) : undefined

Set the .drawRange property. For non-indexed BufferGeometry, count is the number of vertices to render. For indexed BufferGeometry, count is the number of indices to render.

.setFromPoints ( points : Array ) : this

Defines a geometry by creating a position attribute based on the given array of points. The array can hold instances of Vector2 or Vector3. When using two-dimensional data, the z coordinate for all vertices is set to 0.
If the method is used with an existing position attribute, the vertex data are overwritten with the data from the array. The length of the array must match the vertex count.

.setIndex ( index : BufferAttribute ) : this

Set the .index buffer.

.toJSON () : Object

Convert the buffer geometry to three.js JSON Object/Scene format.

.toNonIndexed () : BufferGeometry

Return a non-index version of an indexed BufferGeometry.

.translate ( x : Float, y : Float, z : Float ) : this

Translate the geometry. This is typically done as a one time operation, and not during a loop. Use Object3D.position for typical real-time mesh translation.

Source

src/core/BufferGeometry.js

Clock

Object for keeping track of time. This uses performance.now.

Constructor

Clock( autoStart : Boolean )

autoStart — (optional) whether to automatically start the clock when .getDelta() is called for the first time. Default is true.

Properties

.autoStart : Boolean

If set, starts the clock automatically when .getDelta() is called for the first time. Default is true.

.startTime : Float

Holds the time at which the clock's start method was last called. Default is 0.

.oldTime : Float

Holds the time at which the clock's start, .getElapsedTime() or .getDelta() methods were last called. Default is 0.

.elapsedTime : Float

Keeps track of the total time that the clock has been running. Default is 0.

.running : Boolean

Whether the clock is running or not. Default is false.

Methods

.start () : undefined

Starts clock. Also sets the .startTime and .oldTime to the current time, sets .elapsedTime to 0 and .running to true.

.stop () : undefined

Stops clock and sets oldTime to the current time.

.getElapsedTime () : Float

Get the seconds passed since the clock started and sets .oldTime to the current time.
If .autoStart is true and the clock is not running, also starts the clock.

.getDelta () : Float

Get the seconds passed since the time .oldTime was set and sets .oldTime to the current time.
If .autoStart is true and the clock is not running, also starts the clock.

Source

src/core/Clock.js

EventDispatcher

JavaScript events for custom objects.
EventDispatcher on GitHub

Code Example

// Adding events to a custom object class Car extends EventDispatcher { start() { this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } ); } }; // Using events with the custom object const car = new Car(); car.addEventListener( 'start', function ( event ) { alert( event.message ); } ); car.start();

Constructor

EventDispatcher()

Creates EventDispatcher object.

Methods

.addEventListener ( type : String, listener : Function ) : undefined

type - The type of event to listen to.
listener - The function that gets called when the event is fired.

Adds a listener to an event type.

.hasEventListener ( type : String, listener : Function ) : Boolean

type - The type of event to listen to.
listener - The function that gets called when the event is fired.

Checks if listener is added to an event type.

.removeEventListener ( type : String, listener : Function ) : undefined

type - The type of the listener that gets removed.
listener - The listener function that gets removed.

Removes a listener from an event type.

.dispatchEvent ( event : Object ) : undefined

event - The event that gets fired.

Fire an event type.

Source

src/core/EventDispatcher.js

GLBufferAttribute

This buffer attribute class does not construct a VBO. Instead, it uses whatever VBO is passed in constructor and can later be altered via the buffer property.

It is required to pass additional params alongside the VBO. Those are: the GL context, the GL data type, the number of components per vertex, the number of bytes per component, and the number of vertices.

The most common use case for this class is when some kind of GPGPU calculation interferes or even produces the VBOs in question.

Constructor

GLBufferAttribute( buffer : WebGLBuffer, type : GLenum, itemSize : Integer, elementSize : Integer, count : Integer )

buffer — Must be a WebGLBuffer.
type — One of WebGL Data Types.
itemSize — The number of values of the array that should be associated with a particular vertex. For instance, if this attribute is storing a 3-component vector (such as a position, normal, or color), then itemSize should be 3.
elementSize — 1, 2 or 4. The corresponding size (in bytes) for the given "type" param.

count

Properties

.buffer : WebGLBuffer

The current WebGLBuffer instance.

.count : Integer

The expected number of vertices in VBO.

.isGLBufferAttribute : Boolean

Read-only. Always true.

.itemSize : Integer

How many values make up each item (vertex).

.elementSize : Integer

Stores the corresponding size in bytes for the current type property value.

See above (constructor) for a list of known type sizes.

.name : String

Optional name for this attribute instance. Default is an empty string.

.type : GLenum

A WebGL Data Type describing the underlying VBO contents.

Set this property together with elementSize. The recommended way is using the setType method.

Methods

.setBuffer ( buffer ) : this

Sets the buffer property.

.setType ( type, elementSize ) : this

Sets the both type and elementSize properties.

.setItemSize ( itemSize ) : this

Sets the itemSize property.

.setCount ( count ) : this

Sets the count property.

.version : Integer

A version number, incremented every time the needsUpdate property is set to true.

.needsUpdate : Boolean

Default is false. Setting this to true increments version.

Source

src/core/GLBufferAttribute.js

BufferAttribute

InstancedBufferAttribute

An instanced version of BufferAttribute.

Constructor

InstancedBufferAttribute( array : TypedArray, itemSize : Integer, normalized : Boolean, meshPerAttribute : Number )

Properties

See BufferAttribute for inherited properties.

.meshPerAttribute : Number

Defines how often a value of this buffer attribute should be repeated. A value of one means that each value of the instanced attribute is used for a single instance. A value of two means that each value is used for two consecutive instances (and so on). Default is 1.

Methods

See BufferAttribute for inherited methods.

Source

src/core/InstancedBufferAttribute.js

BufferGeometry

InstancedBufferGeometry

An instanced version of BufferGeometry.

Constructor

InstancedBufferGeometry( )

Properties

See BufferGeometry for inherited properties.

.instanceCount : Number

Default is Infinity.

.isInstancedBufferGeometry : Boolean

Read-only flag to check if a given object is of type InstancedBufferGeometry.

Methods

See BufferGeometry for inherited methods.

.copy ( source : InstancedBufferGeometry ) : this

Copies the given InstancedBufferGeometry to this instance.

Source

src/core/InstancedBufferGeometry.js

InterleavedBuffer

InstancedInterleavedBuffer

An instanced version of InterleavedBuffer.

Constructor

InstancedInterleavedBuffer( array : TypedArray, itemSize : Integer, meshPerAttribute : Number )

Properties

See InterleavedBuffer for inherited properties.

.meshPerAttribute : Number

Default is 1.

Methods

See InterleavedBuffer for inherited methods.

Source

src/core/InstancedInterleavedBuffer.js

InterleavedBuffer

"Interleaved" means that multiple attributes, possibly of different types, (e.g., position, normal, uv, color) are packed into a single array buffer.

An introduction into interleaved arrays can be found here: Interleaved array basics

Examples

webgl / buffergeometry / points / interleaved

Constructor

InterleavedBuffer( array : TypedArray, stride : Integer )

array -- A typed array with a shared buffer. Stores the geometry data.
stride -- The number of typed-array elements per vertex.

Properties

.array : Array

A typed array with a shared buffer. Stores the geometry data.

.stride : Integer

The number of typed-array elements per vertex.

.count : Integer

Gives the total number of elements in the array.

.updateRanges : Object

Array of objects containing:
start: Position at which to start update.
count: The number of components to update.

This can be used to only update some components of stored data. Use the addUpdateRange function to add ranges to this array.

.uuid : String

UUID of this instance. This gets automatically assigned, so this shouldn't be edited.

.version : Integer

A version number, incremented every time the needsUpdate property is set to true.

.needsUpdate : Boolean

Default is false. Setting this to true increments version.

.usage : Usage

Defines the intended usage pattern of the data store for optimization purposes. Corresponds to the usage parameter of WebGLRenderingContext.bufferData().

Methods

.addUpdateRange ( start : Integer, count : Integer ) : this

Adds a range of data in the data array to be updated on the GPU. Adds an object describing the range to the updateRanges array.

.clearUpdateRanges () : this

Clears the updateRanges array.

.copy ( source : InterleavedBuffer ) : this

Copies another InterleavedBuffer to this InterleavedBuffer.

.copyAt ( index1 : Integer, attribute : InterleavedBuffer, index2 : Integer ) : this

Copies data from attribute[index2] to array[index1].

.set ( value : TypedArray, offset : Integer ) : this

value - The source (typed) array.
offset - The offset into the target array at which to begin writing values from the source array. Default is 0.

Stores multiple values in the buffer, reading input values from a specified array.

.clone ( data : Object ) : InterleavedBuffer

data - This object holds shared array buffers required for properly cloning geometries with interleaved attributes.

Creates a clone of this InterleavedBuffer.

.setUsage ( value : Usage ) : this

Set usage to value.

.toJSON ( data : Object ) : Object

data - This object holds shared array buffers required for properly serializing geometries with interleaved attributes.

Serializes this InterleavedBuffer.

Source

src/core/InterleavedBuffer.js

InterleavedBufferAttribute

Constructor

InterleavedBufferAttribute( interleavedBuffer : InterleavedBuffer, itemSize : Integer, offset : Integer, normalized : Boolean )

Properties

.data : InterleavedBuffer

The InterleavedBuffer instance passed in the constructor.

.array : TypedArray

The value of data.array.

.count : Integer

The value of data.count. If the buffer is storing a 3-component item (such as a position, normal, or color), then this will count the number of such items stored.

.isInterleavedBufferAttribute : Boolean

Read-only flag to check if a given object is of type InterleavedBufferAttribute.

.itemSize : Integer

How many values make up each item.

.name : String

Optional name for this attribute instance. Default is an empty string.

.needsUpdate : Boolean

Default is false. Setting this to true will send the entire interleaved buffer (not just the specific attribute data) to the GPU again.

.normalized : Boolean

Default is false.

.offset : Integer

The offset in the underlying array buffer where an item starts.

Methods

.applyMatrix4 ( m : Matrix4 ) : this

Applies matrix m to every Vector3 element of this InterleavedBufferAttribute.

.applyNormalMatrix ( m : Matrix3 ) : this

Applies normal matrix m to every Vector3 element of this InterleavedBufferAttribute.

.transformDirection ( m : Matrix4 ) : this

Applies matrix m to every Vector3 element of this InterleavedBufferAttribute, interpreting the elements as a direction vectors.

.getComponent ( index : Integer, component : Integer ) : Number

Returns the given component of the vector at the given index.

.getX ( index : Integer ) : Number

Returns the x component of the item at the given index.

.getY ( index : Integer ) : Number

Returns the y component of the item at the given index.

.getZ ( index : Integer ) : Number

Returns the z component of the item at the given index.

.getW ( index : Integer ) : Number

Returns the w component of the item at the given index.

.setComponent ( index : Integer, component : Integer, value : Float ) : Number

Sets the given component of the vector at the given index.

.setX ( index : Integer, x : Float ) : this

Sets the x component of the item at the given index.

.setY ( index : Integer, y : Float ) : this

Sets the y component of the item at the given index.

.setZ ( index : Integer, z : Float ) : this

Sets the z component of the item at the given index.

.setW ( index : Integer, w : Float ) : this

Sets the w component of the item at the given index.

.setXY ( index : Integer, x : Float, y : Float ) : this

Sets the x and y components of the item at the given index.

.setXYZ ( index : Integer, x : Float, y : Float, z : Float ) : this

Sets the x, y and z components of the item at the given index.

.setXYZW ( index : Integer, x : Float, y : Float, z : Float, w : Float ) : this

Sets the x, y, z and w components of the item at the given index.

Source

src/core/InterleavedBufferAttribute.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 Object3Ds are a member of layer 0.

This 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.

Examples

WebGL / layers

Constructor

Layers()

Create a new Layers object, with membership initially set to layer 0.

Properties

.mask : Integer

A bit mask storing which of the 32 layers this layers object is currently a member of.

Methods

.disable ( layer : Integer ) : undefined

layer - an integer from 0 to 31.

Remove membership of this layer.

.enable ( layer : Integer ) : undefined

layer - an integer from 0 to 31.

Add membership of this layer.

.set ( layer : Integer ) : undefined

layer - an integer from 0 to 31.

Set membership to layer, and remove membership all other layers.

.test ( layers : Layers ) : Boolean

layers - a Layers object

Returns true if this and the passed layers object have at least one layer in common.

.isEnabled ( layer : Integer ) : Boolean

layer - an integer from 0 to 31.

Returns true if the given layer is enabled.

.toggle ( layer : Integer ) : undefined

layer - an integer from 0 to 31.

Toggle membership of layer.

.enableAll () : undefined

Add membership to all layers.

.disableAll () : undefined

Remove membership from all layers.

Source

src/core/Layers.js

Object3D

This is the base class for most objects in three.js and provides a set of properties and methods for manipulating objects in 3D space.

Note that this can be used for grouping objects via the .add( object ) method which adds the object as a child, however it is better to use Group for this.

Constructor

Object3D()

The constructor takes no arguments.

Properties

.animations : AnimationClip

Array with object's animation clips.

.castShadow : Boolean

Whether the object gets rendered into shadow map. Default is false.

.children : Array

Array with object's children. See Group for info on manually grouping objects.

.customDepthMaterial : Material

Custom depth material to be used when rendering to the depth map. Can only be used in context of meshes. When shadow-casting with a DirectionalLight or SpotLight, if you are modifying vertex positions in the vertex shader you must specify a customDepthMaterial for proper shadows. Default is undefined.

.customDistanceMaterial : Material

Same as customDepthMaterial, but used with PointLight. Default is undefined.

.frustumCulled : Boolean

When this is set, it checks every frame if the object is in the frustum of the camera before rendering the object. If set to false the object gets rendered every frame even if it is not in the frustum of the camera. Default is true.

.id : Integer

readonly – Unique number for this object instance.

.isObject3D : Boolean

Read-only flag to check if a given object is of type Object3D.

.layers : Layers

The layer membership of the object. The object is only visible if it has at least one layer in common with the Camera in use. This property can also be used to filter out unwanted objects in ray-intersection tests when using Raycaster.

.matrix : Matrix4

The local transform matrix.

.matrixAutoUpdate : Boolean

When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. Default is Object3D.DEFAULT_MATRIX_AUTO_UPDATE (true).

.matrixWorld : Matrix4

The global transform of the object. If the Object3D has no parent, then it's identical to the local transform .matrix.

.matrixWorldAutoUpdate : Boolean

If set, then the renderer checks every frame if the object and its children need matrix updates. When it isn't, then you have to maintain all matrices in the object and its children yourself. Default is Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE (true).

.matrixWorldNeedsUpdate : Boolean

When this is set, it calculates the matrixWorld in that frame and resets this property to false. Default is false.

.modelViewMatrix : Matrix4

This is passed to the shader and used to calculate the position of the object.

.name : String

Optional name of the object (doesn't need to be unique). Default is an empty string.

.normalMatrix : Matrix3

This is passed to the shader and used to calculate lighting for the object. It is the transpose of the inverse of the upper left 3x3 sub-matrix of this object's modelViewMatrix.

The reason for this special matrix is that simply using the modelViewMatrix could result in a non-unit length of normals (on scaling) or in a non-perpendicular direction (on non-uniform scaling).

On the other hand the translation part of the modelViewMatrix is not relevant for the calculation of normals. Thus a Matrix3 is sufficient.

.onAfterRender : Function

An optional callback that is executed immediately after a 3D object is rendered. This function is called with the following parameters: renderer, scene, camera, geometry, material, group.

Please notice that this callback is only executed for renderable 3D objects. Meaning 3D objects which define their visual appearance with geometries and materials like instances of Mesh, Line, Points or Sprite. Instances of Object3D, Group or Bone are not renderable and thus this callback is not executed for such objects.

.onAfterShadow : Function

An optional callback that is executed immediately after a 3D object is rendered to a shadow map. This function is called with the following parameters: renderer, scene, camera, shadowCamera, geometry, depthMaterial, group.

Please notice that this callback is only executed for renderable 3D objects. Meaning 3D objects which define their visual appearance with geometries and materials like instances of Mesh, Line, Points or Sprite. Instances of Object3D, Group or Bone are not renderable and thus this callback is not executed for such objects.

.onBeforeRender : Function

An optional callback that is executed immediately before a 3D object is rendered. This function is called with the following parameters: renderer, scene, camera, geometry, material, group.

Please notice that this callback is only executed for renderable 3D objects. Meaning 3D objects which define their visual appearance with geometries and materials like instances of Mesh, Line, Points or Sprite. Instances of Object3D, Group or Bone are not renderable and thus this callback is not executed for such objects.

.onBeforeShadow : Function

An optional callback that is executed immediately before a 3D object is rendered to a shadow map. This function is called with the following parameters: renderer, scene, camera, shadowCamera, geometry, depthMaterial, group.

Please notice that this callback is only executed for renderable 3D objects. Meaning 3D objects which define their visual appearance with geometries and materials like instances of Mesh, Line, Points or Sprite. Instances of Object3D, Group or Bone are not renderable and thus this callback is not executed for such objects.

.parent : Object3D

Object's parent in the scene graph. An object can have at most one parent.

.position : Vector3

A Vector3 representing the object's local position. Default is (0, 0, 0).

.quaternion : Quaternion

Object's local rotation as a Quaternion.

.receiveShadow : Boolean

Whether the material receives shadows. Default is false.

.renderOrder : Number

This value allows the default rendering order of scene graph objects to be overridden although opaque and transparent objects remain sorted independently. When this property is set for an instance of Group, all descendants objects will be sorted and rendered together. Sorting is from lowest to highest renderOrder. Default value is 0.

.rotation : Euler

Object's local rotation (see Euler angles), in radians.

.scale : Vector3

The object's local scale. Default is Vector3( 1, 1, 1 ).

.up : Vector3

This is used by the lookAt method, for example, to determine the orientation of the result.
Default is Object3D.DEFAULT_UP - that is, ( 0, 1, 0 ).

.userData : Object

An object that can be used to store custom data about the Object3D. It should not hold references to functions as these will not be cloned. Default is an empty object {}.

.uuid : String

UUID of this object instance. This gets automatically assigned, so this shouldn't be edited.

.visible : Boolean

Object gets rendered if true. Default is true.

Static Properties

Static properties and methods are defined per class rather than per instance of that class. This means that changing Object3D.DEFAULT_UP or Object3D.DEFAULT_MATRIX_AUTO_UPDATE will change the values of up and matrixAutoUpdate for every instance of Object3D (or derived classes) created after the change has been made (already created Object3Ds will not be affected).

.DEFAULT_UP : Vector3

The default up direction for objects, also used as the default position for DirectionalLight, HemisphereLight and Spotlight (which creates lights shining from the top down).
Set to ( 0, 1, 0 ) by default.

.DEFAULT_MATRIX_AUTO_UPDATE : Boolean

The default setting for matrixAutoUpdate for newly created Object3Ds.

.DEFAULT_MATRIX_WORLD_AUTO_UPDATE : Boolean

The default setting for matrixWorldAutoUpdate for newly created Object3Ds.

Methods

EventDispatcher methods are available on this class.

.add ( object : Object3D, ... ) : this

Adds object as child of this object. An arbitrary number of objects may be added. Any current parent on an object passed in here will be removed, since an object can have at most one parent.

See Group for info on manually grouping objects.

.applyMatrix4 ( matrix : Matrix4 ) : undefined

Applies the matrix transform to the object and updates the object's position, rotation and scale.

.applyQuaternion ( quaternion : Quaternion ) : this

Applies the rotation represented by the quaternion to the object.

.attach ( object : Object3D ) : this

Adds object as a child of this, while maintaining the object's world transform.

Note: This method does not support scene graphs having non-uniformly-scaled nodes(s).

.clear () : this

Removes all child objects.

.clone ( recursive : Boolean ) : Object3D

recursive -- if true, descendants of the object are also cloned. Default is true.

Returns a clone of this object and optionally all descendants.

.copy ( object : Object3D, recursive : Boolean ) : this

recursive -- If set to true, descendants of the object are copied next to the existing ones. If set to false, descendants are left unchanged. Default is true.

Copies the given object into this object. Note: Event listeners and user-defined callbacks (.onAfterRender and .onBeforeRender) are not copied.

.getObjectById ( id : Integer ) : Object3D

id -- Unique number of the object instance

Searches through an object and its children, starting with the object itself, and returns the first with a matching id.
Note that ids are assigned in chronological order: 1, 2, 3, ..., incrementing by one for each new object.

.getObjectByName ( name : String ) : Object3D

name -- String to match to the children's Object3D.name property.

Searches through an object and its children, starting with the object itself, and returns the first with a matching name.
Note that for most objects the name is an empty string by default. You will have to set it manually to make use of this method.

.getObjectByProperty ( name : String, value : Any ) : Object3D

name -- the property name to search for.
value -- value of the given property.

Searches through an object and its children, starting with the object itself, and returns the first with a property that matches the value given.

.getObjectsByProperty ( name : String, value : Any, optionalTarget : Array ) : Object3D

name -- the property name to search for.
value -- value of the given property.
optionalTarget -- (optional) target to set the result. Otherwise a new Array is instantiated. If set, you must clear this array prior to each call (i.e., array.length = 0;).

Searches through an object and its children, starting with the object itself, and returns all the objects with a property that matches the value given.

.getWorldPosition ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns a vector representing the position of the object in world space.

.getWorldQuaternion ( target : Quaternion ) : Quaternion

target — the result will be copied into this Quaternion.

Returns a quaternion representing the rotation of the object in world space.

.getWorldScale ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns a vector of the scaling factors applied to the object for each axis in world space.

.getWorldDirection ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns a vector representing the direction of object's positive z-axis in world space.

.localToWorld ( vector : Vector3 ) : Vector3

vector - A vector representing a position in this object's local space.

Converts the vector from this object's local space to world space.

.lookAt ( vector : Vector3 ) : undefined
.lookAt ( x : Float, y : Float, z : Float ) : undefined

vector - A vector representing a position in world space.

Optionally, the x, y and z components of the world space position.

Rotates the object to face a point in world space.

This method does not support objects having non-uniformly-scaled parent(s).

.raycast ( raycaster : Raycaster, intersects : Array ) : undefined

Abstract (empty) method to get intersections between a casted ray and this object. Subclasses such as Mesh, Line, and Points implement this method in order to use raycasting.

.remove ( object : Object3D, ... ) : this

Removes object as child of this object. An arbitrary number of objects may be removed.

.removeFromParent () : this

Removes this object from its current parent.

.rotateOnAxis ( axis : Vector3, angle : Float ) : this

axis -- A normalized vector in object space.
angle -- The angle in radians.

Rotate an object along an axis in object space. The axis is assumed to be normalized.

.rotateOnWorldAxis ( axis : Vector3, angle : Float) : this

axis -- A normalized vector in world space.
angle -- The angle in radians.

Rotate an object along an axis in world space. The axis is assumed to be normalized. Method Assumes no rotated parent.

.rotateX ( rad : Float ) : this

rad - the angle to rotate in radians.

Rotates the object around x axis in local space.

.rotateY ( rad : Float ) : this

rad - the angle to rotate in radians.

Rotates the object around y axis in local space.

.rotateZ ( rad : Float ) : this

rad - the angle to rotate in radians.

Rotates the object around z axis in local space.

.setRotationFromAxisAngle ( axis : Vector3, angle : Float ) : undefined

axis -- A normalized vector in object space.
angle -- angle in radians

Calls setFromAxisAngle( axis, angle ) on the .quaternion.

.setRotationFromEuler ( euler : Euler ) : undefined

euler -- Euler angle specifying rotation amount.
Calls setRotationFromEuler( euler) on the .quaternion.

.setRotationFromMatrix ( m : Matrix4 ) : undefined

m -- rotate the quaternion by the rotation component of the matrix.
Calls setFromRotationMatrix( m) on the .quaternion.

Note that this assumes that the upper 3x3 of m is a pure rotation matrix (i.e, unscaled).

.setRotationFromQuaternion ( q : Quaternion ) : undefined

q -- normalized Quaternion.

Copy the given quaternion into .quaternion.

.toJSON ( meta : Object ) : Object

meta -- object containing metadata such as materials, textures or images for the object.
Convert the object to three.js JSON Object/Scene format.

.translateOnAxis ( axis : Vector3, distance : Float ) : this

axis -- A normalized vector in object space.
distance -- The distance to translate.

Translate an object by distance along an axis in object space. The axis is assumed to be normalized.

.translateX ( distance : Float ) : this

Translates object along x axis in object space by distance units.

.translateY ( distance : Float ) : this

Translates object along y axis in object space by distance units.

.translateZ ( distance : Float ) : this

Translates object along z axis in object space by distance units.

.traverse ( callback : Function ) : undefined

callback - A function with as first argument an object3D object.

Executes the callback on this object and all descendants.
Note: Modifying the scene graph inside the callback is discouraged.

.traverseVisible ( callback : Function ) : undefined

callback - A function with as first argument an object3D object.

Like traverse, but the callback will only be executed for visible objects. Descendants of invisible objects are not traversed.
Note: Modifying the scene graph inside the callback is discouraged.

.traverseAncestors ( callback : Function ) : undefined

callback - A function with as first argument an object3D object.

Executes the callback on all ancestors.
Note: Modifying the scene graph inside the callback is discouraged.

.updateMatrix () : undefined

Updates the local transform.

.updateMatrixWorld ( force : Boolean ) : undefined

force - A boolean that can be used to bypass .matrixWorldAutoUpdate, to recalculate the world matrix of the object and descendants on the current frame. Useful if you cannot wait for the renderer to update it on the next frame (assuming .matrixWorldAutoUpdate set to true).

Updates the global transform of the object and its descendants if the world matrix needs update (.matrixWorldNeedsUpdate set to true) or if the force parameter is set to true.

.updateWorldMatrix ( updateParents : Boolean, updateChildren : Boolean ) : undefined

updateParents - recursively updates global transform of ancestors.
updateChildren - recursively updates global transform of descendants.

Updates the global transform of the object.

.worldToLocal ( vector : Vector3 ) : Vector3

vector - A vector representing a position in world space.

Converts the vector from world space to this object's local space.

Events

added

Fires when the object has been added to its parent object.

removed

Fires when the object has been removed from its parent object.

childadded

Fires when a new child object has been added.

childremoved

Fires when a new child object has been removed.

Source

src/core/Object3D.js

Raycaster

This class is designed to assist with raycasting. Raycasting is used for mouse picking (working out what objects in the 3d space the mouse is over) amongst other things.

Code Example

const raycaster = new THREE.Raycaster(); const pointer = new THREE.Vector2(); function onPointerMove( event ) { // calculate pointer position in normalized device coordinates // (-1 to +1) for both components pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1; pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1; } function render() { // update the picking ray with the camera and pointer position raycaster.setFromCamera( pointer, camera ); // calculate objects intersecting the picking ray const intersects = raycaster.intersectObjects( scene.children ); for ( let i = 0; i < intersects.length; i ++ ) { intersects[ i ].object.material.color.set( 0xff0000 ); } renderer.render( scene, camera ); } window.addEventListener( 'pointermove', onPointerMove ); window.requestAnimationFrame(render);

Examples

Raycasting to a Mesh
Raycasting to a Mesh in using an OrthographicCamera
Raycasting to a Mesh with BufferGeometry
Raycasting to a InstancedMesh
Raycasting to a Line
Raycasting to Points
Terrain raycasting
Raycasting to paint voxels
Raycast to a Texture

Constructor

Raycaster( origin : Vector3, direction : Vector3, near : Float, far : Float )

origin — The origin vector where the ray casts from.
direction — The direction vector that gives direction to the ray. Should be normalized.
near — All results returned are further away than near. Near can't be negative. Default value is 0.
far — All results returned are closer than far. Far can't be lower than near. Default value is Infinity.

This creates a new raycaster object.

Properties

.far : Float

The far factor of the raycaster. This value indicates which objects can be discarded based on the distance. This value shouldn't be negative and should be larger than the near property.

.near : Float

The near factor of the raycaster. This value indicates which objects can be discarded based on the distance. This value shouldn't be negative and should be smaller than the far property.

.camera : Camera

The camera to use when raycasting against view-dependent objects such as billboarded objects like Sprites. This field can be set manually or is set when calling "setFromCamera". Defaults to null.

.layers : Layers

Used by Raycaster to selectively ignore 3D objects when performing intersection tests. The following code example ensures that only 3D objects on layer 1 will be honored by the instance of Raycaster. raycaster.layers.set( 1 ); object.layers.enable( 1 );

.params : Object

An object with the following properties: { Mesh: {}, Line: { threshold: 1 }, LOD: {}, Points: { threshold: 1 }, Sprite: {} } Where threshold is the precision of the raycaster when intersecting objects, in world units.

.ray : Ray

The Ray used for the raycasting.

Methods

.set ( origin : Vector3, direction : Vector3) : undefined

origin — The origin vector where the ray casts from.
direction — The normalized direction vector that gives direction to the ray.

Updates the ray with a new origin and direction. Please note that this method only copies the values from the arguments.

.setFromCamera ( coords : Vector2, camera : Camera ) : undefined

coords — 2D coordinates of the mouse, in normalized device coordinates (NDC)---X and Y components should be between -1 and 1.
camera — camera from which the ray should originate

Updates the ray with a new origin and direction.

.setFromXRController ( controller : WebXRController ) : this

controller — The controller to copy the position and direction from.

Updates the ray with a new origin and direction.

.intersectObject ( object : Object3D, recursive : Boolean, optionalTarget : Array ) : Array

object — The object to check for intersection with the ray.
recursive — If true, it also checks all descendants. Otherwise it only checks intersection with the object. Default is true.
optionalTarget — (optional) target to set the result. Otherwise a new Array is instantiated. If set, you must clear this array prior to each call (i.e., array.length = 0;).

Checks all intersection between the ray and the object with or without the descendants. Intersections are returned sorted by distance, closest first. An array of intersections is returned...

[ { distance, point, face, faceIndex, object }, ... ]

distance – distance between the origin of the ray and the intersection
point – point of intersection, in world coordinates
face – intersected face
faceIndex – index of the intersected face
object – the intersected object
uv - U,V coordinates at point of intersection
uv1 - Second set of U,V coordinates at point of intersection
normal - interpolated normal vector at point of intersection
instanceId – The index number of the instance where the ray intersects the InstancedMesh

Raycaster delegates to the raycast method of the passed object, when evaluating whether the ray intersects the object or not. This allows meshes to respond differently to ray casting than lines and pointclouds.

Note that for meshes, faces must be pointed towards the origin of the ray in order to be detected; intersections of the ray passing through the back of a face will not be detected. To raycast against both faces of an object, you'll want to set the material's side property to THREE.DoubleSide.

.intersectObjects ( objects : Array, recursive : Boolean, optionalTarget : Array ) : Array

objects — The objects to check for intersection with the ray.
recursive — If true, it also checks all descendants of the objects. Otherwise it only checks intersection with the objects. Default is true.
optionalTarget — (optional) target to set the result. Otherwise a new Array is instantiated. If set, you must clear this array prior to each call (i.e., array.length = 0;).

Checks all intersection between the ray and the objects with or without the descendants. Intersections are returned sorted by distance, closest first. Intersections are of the same form as those returned by .intersectObject.

Source

src/core/Raycaster.js

Uniform

Uniforms are global GLSL variables. They are passed to shader programs.

Code Example

When declaring a uniform of a ShaderMaterial, it is declared by value or by object.

uniforms: { time: { value: 1.0 }, resolution: new Uniform( new Vector2() ) };

Uniform types

Each uniform must have a value property. The type of the value must correspond to the type of the uniform variable in the GLSL code as specified for the primitive GLSL types in the table below. Uniform structures and arrays are also supported. GLSL arrays of primitive type must either be specified as an array of the corresponding THREE objects or as a flat array containing the data of all the objects. In other words; GLSL primitives in arrays must not be represented by arrays. This rule does not apply transitively. An array of vec2 arrays, each with a length of five vectors, must be an array of arrays, of either five Vector2 objects or ten numbers.

Uniform types
GLSL type JavaScript type
int Number
uint Number
float Number
bool Boolean
bool Number
vec2 THREE.Vector2
vec2 Float32Array (*)
vec2 Array (*)
vec3 THREE.Vector3
vec3 THREE.Color
vec3 Float32Array (*)
vec3 Array (*)
vec4 THREE.Vector4
vec4 THREE.Quaternion
vec4 Float32Array (*)
vec4 Array (*)
mat2 Float32Array (*)
mat2 Array (*)
mat3 THREE.Matrix3
mat3 Float32Array (*)
mat3 Array (*)
mat4 THREE.Matrix4
mat4 Float32Array (*)
mat4 Array (*)
ivec2, bvec2 Float32Array (*)
ivec2, bvec2 Array (*)
ivec3, bvec3 Int32Array (*)
ivec3, bvec3 Array (*)
ivec4, bvec4 Int32Array (*)
ivec4, bvec4 Array (*)
sampler2D THREE.Texture
samplerCube THREE.CubeTexture

(*) Same for an (innermost) array (dimension) of the same GLSL type, containing the components of all vectors or matrices in the array.

Structured Uniforms

Sometimes you want to organize uniforms as structs in your shader code. The following style must be used so three.js is able to process structured uniform data.

uniforms = { data: { value: { position: new Vector3(), direction: new Vector3( 0, 0, 1 ) } } };struct Data { vec3 position; vec3 direction; }; uniform Data data;

Structured Uniforms with Arrays

It's also possible to manage structs in arrays. The syntax for this use case looks like so:

const entry1 = { position: new Vector3(), direction: new Vector3( 0, 0, 1 ) }; const entry2 = { position: new Vector3( 1, 1, 1 ), direction: new Vector3( 0, 1, 0 ) }; uniforms = { data: { value: [ entry1, entry2 ] } };struct Data { vec3 position; vec3 direction; }; uniform Data data[ 2 ];

Constructor

Uniform( value : Object )

value -- An object containing the value to set up the uniform. It's type must be one of the Uniform Types described above.

Properties

.value : Object

Current value of the uniform.

Methods

.clone () : Uniform

Returns a clone of this uniform.
If the uniform's value property is an Object with a clone() method, this is used, otherwise the value is copied by assignment. Array values are shared between cloned Uniforms.

Source

src/core/Uniform.js

BufferAttribute

BufferAttribute Types

There are nine types of BufferAttribute available in three.js. These correspond to the JavaScript Typed Arrays.

THREE.Float32BufferAttribute THREE.Float16BufferAttribute THREE.Uint32BufferAttribute THREE.Int32BufferAttribute THREE.Uint16BufferAttribute THREE.Int16BufferAttribute THREE.Uint8ClampedBufferAttribute THREE.Uint8BufferAttribute THREE.Int8BufferAttribute

Constructor

All of the above are called in the same way.

TypedBufferAttribute( array : Array_or_Integer, itemSize : Integer, normalized : Boolean )

array -- this can be a typed or untyped (normal) array or an integer length. An array value will be converted to the Type specified. If a length is given a new TypedArray will created, initialized with all elements set to zero.

itemSize -- the number of values of the array that should be associated with a particular vertex.

normalized -- (optional) indicates how the underlying data in the buffer maps to the values in the GLSL code.

Properties

See the BufferAttribute page for inherited properties.

Methods

See the BufferAttribute page for inherited methods.

Source

src/core/BufferAttribute.js

EventDispatcher

Controls

Abstract base class for controls.

Constructor

Controls( object : Object3D, domElement : HTMLDOMElement )

object - The object the controls should manage (usually the camera).

domElement: The HTML element used for event listeners. (optional)

Creates a new instance of Controls.

Properties

.domElement : HTMLDOMElement

The HTML element used for event listeners. If not provided via the constructor, .connect() must be called after domElement has been set.

.enabled : Boolean

When set to false, the controls will not respond to user input. Default is true.

.keys : Object

This object defines the keyboard input of the controls. Default is {}.

.mouseButtons : Object

This object defines what type of actions are assigned to the available mouse buttons. It depends on the control implementation what kind of mouse buttons and actions are supported. Default is { LEFT: null, MIDDLE: null, RIGHT: null }.

Possible buttons are: LEFT, MIDDLE, RIGHT.

Possible actions are defined in the Constants page.

.object : Object3D

The 3D object that is managed by the controls.

.state : Integer

The internal state of the controls. Default is -1 (NONE).

.touches : Object

This object defines what type of actions are assigned to what kind of touch interaction. It depends on the control implementation what kind of touch interaction and actions are supported. Default is { ONE: null, TWO: null }.

Possible buttons are: ONE, TWO.

Possible actions are defined in the Constants page.

Methods

See the base EventDispatcher class for common methods.

.connect () : undefined

Connects the controls to the DOM. This method has so called "side effects" since it adds the module's event listeners to the DOM.

.disconnect () : undefined

Disconnects the controls from the DOM.

.dispose () : undefined

Call this method if you no longer want use to the controls. It frees all internal resources and removes all event listeners.

.update ( delta : Number ) : undefined

Controls should implement this method if they have to update their internal state per simulation step.

Source

src/extras/Controls.js

DataUtils

A class containing utility functions for data.

Methods

.toHalfFloat ( val : Number ) : Number

val -- A single precision floating point value.

Returns a half precision floating point value from the given single precision floating point value.

.fromHalfFloat ( val : Number ) : Number

val -- A half precision floating point value.

Returns a single precision floating point value from the given half precision floating point value.

Source

src/extras/DataUtils.js

Earcut

An implementation of the earcut polygon triangulation algorithm. The code is a port of mapbox/earcut.

Methods

.triangulate ( data, holeIndices, dim ) : Array

data -- A flat array of vertex coordinates.
holeIndices -- An array of hole indices if any.
dim -- The number of coordinates per vertex in the input array.

Triangulates the given shape definition by returning an array of triangles. A triangle is defined by three consecutive integers representing vertex indices.

Source

src/extras/Earcut.js

ImageUtils

A class containing utility functions for images.

Methods

.getDataURL ( image : HTMLCanvasElement | image : HTMLImageElement | image : ImageBitmap ) : String

image -- The image object.

Returns a data URI containing a representation of the given image.

.sRGBToLinear ( image : HTMLCanvasElement | image : HTMLImageElement | image : ImageBitmap ) : Object

image -- The image object.

Converts the given sRGB image data to linear color space.

Source

src/extras/ImageUtils.js

PMREMGenerator

This class generates a Prefiltered, Mipmapped Radiance Environment Map (PMREM) from a cubeMap environment texture. This allows different levels of blur to be quickly accessed based on material roughness. Unlike a traditional mipmap chain, it only goes down to the LOD_MIN level (above), and then creates extra even more filtered 'mips' at the same LOD_MIN resolution, associated with higher roughness levels. In this way we maintain resolution to smoothly interpolate diffuse lighting while limiting sampling computation.

Note: The minimum MeshStandardMaterial's roughness depends on the size of the provided texture. If your render has small dimensions or the shiny parts have a lot of curvature, you may still be able to get away with a smaller texture size.

texture size minimum roughness
16 0.21
32 0.15
64 0.11
128 0.076
256 0.054
512 0.038
1024 0.027

Constructor

PMREMGenerator( renderer : WebGLRenderer )

This constructor creates a new PMREMGenerator.

Methods

.fromScene ( scene : Scene, sigma : Number, near : Number, far : Number ) : WebGLRenderTarget

scene - The given scene.
sigma - (optional) Specifies a blur radius in radians to be applied to the scene before PMREM generation. Default is 0.
near - (optional) The near plane value. Default is 0.1.
far - (optional) The far plane value. Default is 100.

Generates a PMREM from a supplied Scene, which can be faster than using an image if networking bandwidth is low. Optional near and far planes ensure the scene is rendered in its entirety (the cubeCamera is placed at the origin).

.fromEquirectangular ( equirectangular : Texture ) : WebGLRenderTarget

equirectangular - The equirectangular texture.

Generates a PMREM from an equirectangular texture.

.fromCubemap ( cubemap : CubeTexture ) : WebGLRenderTarget

cubemap - The cubemap texture.

Generates a PMREM from an cubemap texture.

.compileCubemapShader () : undefined

Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during your texture's network fetch for increased concurrency.

.compileEquirectangularShader () : undefined

Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during your texture's network fetch for increased concurrency.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/extras/PMREMGenerator.js

ShapeUtils

A class containing utility functions for shapes.

Note that these are all linear functions so it is necessary to calculate separately for x, y (and z, w if present) components of a vector.

Methods

.area ( contour ) : Number

contour -- 2D polygon. An array of THREE.Vector2()

Calculate area of a ( 2D ) contour polygon.

.isClockWise ( pts ) : Boolean

pts -- points defining a 2D polygon

Note that this is a linear function so it is necessary to calculate separately for x, y components of a polygon.

Used internally by Path, ExtrudeGeometry and ShapeGeometry.

.triangulateShape ( contour, holes ) : Array

contour -- 2D polygon. An array of Vector2.
holes -- An array that holds arrays of Vector2s. Each array represents a single hole definition.

Used internally by ExtrudeGeometry and ShapeGeometry to calculate faces in shapes with holes.

Source

src/extras/ShapeUtils.js

TextureUtils

A class containing utility functions for textures.

Methods

.contain ( texture : Texture, aspect : Number ) : Texture

Scales the texture as large as possible within its surface without cropping or stretching the texture. The method preserves the original aspect ratio of the texture. Akin to CSS object-fit: contain.

.cover ( texture : Texture, aspect : Number ) : Texture

Scales the texture to the smallest possible size to fill the surface, leaving no empty space. The method preserves the original aspect ratio of the texture. Akin to CSS object-fit: cover.

.fill ( texture : Texture ) : Texture

Configures the texture to the default transformation. Akin to CSS object-fit: fill.

.getByteLength ( width : Number, height : Number, format : Number, type : Number ) : Number

Given the width, height, format, and type of a texture. Determines how many bytes must be used to represent the texture.

Source

src/extras/TextureUtils.js

Curve

An abstract base class for creating a Curve object that contains methods for interpolation. For an array of Curves see CurvePath.

Constructor

Curve()

This constructor creates a new Curve.

Properties

.arcLengthDivisions : Integer

This value determines the amount of divisions when calculating the cumulative segment lengths of a curve via .getLengths. To ensure precision when using methods like .getSpacedPoints, it is recommended to increase .arcLengthDivisions if the curve is very large. Default is 200.

Methods

.getPoint ( t : Float, optionalTarget : Vector ) : Vector

t - A position on the curve. Must be in the range [ 0, 1 ].
optionalTarget — (optional) If specified, the result will be copied into this Vector, otherwise a new Vector will be created.

Returns a vector for a given position on the curve.

.getPointAt ( u : Float, optionalTarget : Vector ) : Vector

u - A position on the curve according to the arc length. Must be in the range [ 0, 1 ].
optionalTarget — (optional) If specified, the result will be copied into this Vector, otherwise a new Vector will be created.

Returns a vector for a given position on the curve according to the arc length.

.getPoints ( divisions : Integer ) : Array

divisions -- number of pieces to divide the curve into. Default is 5.

Returns a set of divisions + 1 points using getPoint( t ).

.getSpacedPoints ( divisions : Integer ) : Array

divisions -- number of pieces to divide the curve into. Default is 5.

Returns a set of divisions + 1 equi-spaced points using getPointAt( u ).

.getLength () : Float

Get total curve arc length.

.getLengths ( divisions : Integer ) : Array

Get list of cumulative segment lengths.

.updateArcLengths () : undefined

Update the cumulative segment distance cache. The method must be called every time curve parameters are changed. If an updated curve is part of a composed curve like CurvePath, .updateArcLengths() must be called on the composed curve, too.

.getUtoTmapping ( u : Float, distance : Float ) : Float

Given u in the range ( 0 .. 1 ), returns t also in the range ( 0 .. 1 ). u and t can then be used to give you points which are equidistant from the ends of the curve, using .getPoint.

.getTangent ( t : Float, optionalTarget : Vector ) : Vector

t - A position on the curve. Must be in the range [ 0, 1 ].
optionalTarget — (optional) If specified, the result will be copied into this Vector, otherwise a new Vector will be created.

Returns a unit vector tangent at t. If the derived curve does not implement its tangent derivation, two points a small delta apart will be used to find its gradient which seems to give a reasonable approximation.

.getTangentAt ( u : Float, optionalTarget : Vector ) : Vector

u - A position on the curve according to the arc length. Must be in the range [ 0, 1 ].
optionalTarget — (optional) If specified, the result will be copied into this Vector, otherwise a new Vector will be created.

Returns tangent at a point which is equidistant to the ends of the curve from the point given in .getTangent.

.computeFrenetFrames ( segments : Integer, closed : Boolean ) : Object

Generates the Frenet Frames. Requires a curve definition in 3D space. Used in geometries like TubeGeometry or ExtrudeGeometry.

.clone () : Curve

Creates a clone of this instance.

.copy ( source : Curve ) : this

Copies another Curve object to this instance.

.toJSON () : Object

Returns a JSON object representation of this instance.

.fromJSON ( json : Object ) : this

Copies the data from the given JSON object to this instance.

Source

src/extras/core/Curve.js

Curve

CurvePath

An abstract base class extending Curve. A CurvePath is simply an array of connected curves, but retains the api of a curve.

Constructor

CurvePath()

The constructor take no parameters.

Properties

See the base Curve class for common properties.

.curves : Array

The array of Curves.

.autoClose : Boolean

Whether or not to automatically close the path.

Methods

See the base Curve class for common methods.

.add ( curve : Curve ) : undefined

Add a curve to the .curves array.

.closePath () : this

Adds a lineCurve to close the path.

.getCurveLengths () : Array

Get list of cumulative curve lengths of the curves in the .curves array.

.getPoints ( divisions : Integer ) : Array

divisions -- number of pieces to divide the curve into. Default is 12.

Returns an array of points representing a sequence of curves. The division parameter defines the number of pieces each curve is divided into. However, for optimization and quality purposes, the actual sampling resolution for each curve depends on its type. For example, for a LineCurve, the returned number of points is always just 2.

.getSpacedPoints ( divisions : Integer ) : Array

divisions -- number of pieces to divide the curve into. Default is 40.

Returns a set of divisions + 1 equi-spaced points using getPointAt( u ).

Source

src/extras/core/CurvePath.js

Interpolations

Interpolations contains spline and Bézier functions internally used by concrete curve classes.

Methods

.CatmullRom ( t : Float, p0 : Float, p1 : Float, p2 : Float, p3 : Float ) : Float

t -- interpolation weight.
p0, p1, p2, p3 -- the points defining the spline curve.

Used internally by SplineCurve.

.QuadraticBezier ( t : Float, p0 : Float, p1 : Float, p2 : Float ) : Float

t -- interpolation weight.
p0, p1, p2 -- the starting, control and end points defining the curve.

Used internally by QuadraticBezierCurve3 and QuadraticBezierCurve.

.CubicBezier ( t : Float, p0 : Float, p1 : Float, p2 : Float, p3 : Float ) : Float

t -- interpolation weight.
p0, p1, p2, p3 -- the starting, control(twice) and end points defining the curve.

Used internally by CubicBezierCurve3 and CubicBezierCurve.

Source

src/extras/core/Interpolations.js

CurveCurvePath

Path

A 2D path representation. The class provides methods for creating paths and contours of 2D shapes similar to the 2D Canvas API.

Code Example

const path = new THREE.Path(); path.lineTo( 0, 0.8 ); path.quadraticCurveTo( 0, 1, 0.2, 1 ); path.lineTo( 1, 1 ); const points = path.getPoints(); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xffffff } ); const line = new THREE.Line( geometry, material ); scene.add( line );

Constructor

Path( points : Array )

points -- (optional) array of Vector2s.

Creates a Path from the points. The first point defines the offset, then successive points are added to the curves array as LineCurves.

If no points are specified, an empty path is created and the .currentPoint is set to the origin.

Properties

See the base CurvePath class for common properties.

.currentPoint : Vector2

The current offset of the path. Any new Curve added will start here.

Methods

See the base CurvePath class for common methods.

.absarc ( x : Float, y : Float, radius : Float, startAngle : Float, endAngle : Float, clockwise : Boolean ) : this

x, y -- The absolute center of the arc.
radius -- The radius of the arc.
startAngle -- The start angle in radians.
endAngle -- The end angle in radians.
clockwise -- Sweep the arc clockwise. Defaults to false.

Adds an absolutely positioned EllipseCurve to the path.

.absellipse ( x : Float, y : Float, xRadius : Float, yRadius : Float, startAngle : Float, endAngle : Float, clockwise : Boolean, rotation : Float ) : this

x, y -- The absolute center of the ellipse.
xRadius -- The radius of the ellipse in the x axis.
yRadius -- The radius of the ellipse in the y axis.
startAngle -- The start angle in radians.
endAngle -- The end angle in radians.
clockwise -- Sweep the ellipse clockwise. Defaults to false.
rotation -- The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. Optional, defaults to 0.

Adds an absolutely positioned EllipseCurve to the path.

.arc ( x : Float, y : Float, radius : Float, startAngle : Float, endAngle : Float, clockwise : Boolean ) : this

x, y -- The center of the arc offset from the last call.
radius -- The radius of the arc.
startAngle -- The start angle in radians.
endAngle -- The end angle in radians.
clockwise -- Sweep the arc clockwise. Defaults to false.

Adds an EllipseCurve to the path, positioned relative to .currentPoint.

.bezierCurveTo ( cp1X : Float, cp1Y : Float, cp2X : Float, cp2Y : Float, x : Float, y : Float ) : this

This creates a bezier curve from .currentPoint with (cp1X, cp1Y) and (cp2X, cp2Y) as control points and updates .currentPoint to x and y.

.ellipse ( x : Float, y : Float, xRadius : Float, yRadius : Float, startAngle : Float, endAngle : Float, clockwise : Boolean, rotation : Float ) : this

x, y -- The center of the ellipse offset from the last call.
xRadius -- The radius of the ellipse in the x axis.
yRadius -- The radius of the ellipse in the y axis.
startAngle -- The start angle in radians.
endAngle -- The end angle in radians.
clockwise -- Sweep the ellipse clockwise. Defaults to false.
rotation -- The rotation angle of the ellipse in radians, counterclockwise from the positive X axis. Optional, defaults to 0.

Adds an EllipseCurve to the path, positioned relative to .currentPoint.

.lineTo ( x : Float, y : Float ) : this

Connects a LineCurve from .currentPoint to x, y onto the path.

.moveTo ( x : Float, y : Float ) : this

Move the .currentPoint to x, y.

.quadraticCurveTo ( cpX : Float, cpY : Float, x : Float, y : Float ) : this

Creates a quadratic curve from .currentPoint with cpX and cpY as control point and updates .currentPoint to x and y.

.setFromPoints ( vector2s : Array ) : this

points -- array of Vector2s.

Points are added to the curves array as LineCurves.

.splineThru ( points : Array ) : this

points - An array of Vector2s

Connects a new SplineCurve onto the path.

Source

src/extras/core/Path.js

CurveCurvePathPath

Shape

Defines an arbitrary 2d shape plane using paths with optional holes. It can be used with ExtrudeGeometry, ShapeGeometry, to get points, or to get triangulated faces.

Code Example

const heartShape = new THREE.Shape(); heartShape.moveTo( 25, 25 ); heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 ); heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 ); heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 ); heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 ); heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 ); heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 ); const extrudeSettings = { depth: 8, bevelEnabled: true, bevelSegments: 2, steps: 2, bevelSize: 1, bevelThickness: 1 }; const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings ); const mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial() );

Examples

geometry / shapes
geometry / extrude / shapes

Constructor

Shape( points : Array )

points -- (optional) array of Vector2s.

Creates a Shape from the points. The first point defines the offset, then successive points are added to the curves array as LineCurves.

If no points are specified, an empty shape is created and the .currentPoint is set to the origin.

Properties

See the base Path class for common properties.

.uuid : String

UUID of this instance. This gets automatically assigned, so this shouldn't be edited.

.holes : Array

An array of paths that define the holes in the shape.

Methods

See the base Path class for common methods.

.extractPoints ( divisions : Integer ) : Array

divisions -- The fineness of the result.

Call getPoints on the shape and the .holes array, and return an object of the form: { shape holes } where shape and holes are arrays of Vector2s.

.getPointsHoles ( divisions : Integer ) : Array

divisions -- The fineness of the result.

Get an array of Vector2s that represent the holes in the shape.

Source

src/extras/core/Shape.js

ShapePath

This class is used to convert a series of shapes to an array of Paths, for example an SVG shape to a path.

Constructor

ShapePath( )

Creates a new ShapePath. Unlike a Path, no points are passed in as the ShapePath is designed to be generated after creation.

Properties

.subPaths : Array

Array of Paths.

.currentPath : Array

The current Path that is being generated.

.color : Color

Color of the shape, by default set to white (0xffffff).

Methods

.moveTo ( x : Float, y : Float ) : this

Starts a new Path and calls Path.moveTo( x, y ) on that Path. Also points currentPath to that Path.

.lineTo ( x : Float, y : Float ) : this

This creates a line from the currentPath's offset to X and Y and updates the offset to X and Y.

.quadraticCurveTo ( cpX : Float, cpY : Float, x : Float, y : Float ) : this

This creates a quadratic curve from the currentPath's offset to x and y with cpX and cpY as control point and updates the currentPath's offset to x and y.

.bezierCurveTo ( cp1X : Float, cp1Y : Float, cp2X : Float, cp2Y : Float, x : Float, y : Float ) : this

This creates a bezier curve from the currentPath's offset to x and y with cp1X, cp1Y and cp2X, cp2Y as control points and updates the currentPath's offset to x and y.

.splineThru ( points : Array ) : this

points - An array of Vector2s

Connects a new SplineCurve onto the currentPath.

.toShapes ( isCCW : Boolean ) : Array

isCCW -- Changes how solids and holes are generated

Converts the subPaths array into an array of Shapes. By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW). If isCCW is set to true, then those are flipped.

Source

src/extras/core/ShapePath.js

CurveEllipseCurve

ArcCurve

Alias for EllipseCurve.

Properties

See the EllipseCurve class for common properties.

Source

src/extras/curves/ArcCurve.js

Curve

CatmullRomCurve3

Create a smooth 3d spline curve from a series of points using the Catmull-Rom algorithm.

Code Example

//Create a closed wavey loop const curve = new THREE.CatmullRomCurve3( [ new THREE.Vector3( -10, 0, 10 ), new THREE.Vector3( -5, 5, 5 ), new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 5, -5, 5 ), new THREE.Vector3( 10, 0, 10 ) ] ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const curveObject = new THREE.Line( geometry, material );

Examples

WebGL / geometry / extrude / splines

Constructor

CatmullRomCurve3( points : Array, closed : Boolean, curveType : String, tension : Float )

points – An array of Vector3 points
closed – Whether the curve is closed. Default is false.
curveType – Type of the curve. Default is centripetal.
tension – Tension of the curve. Default is 0.5.

Properties

See the base Curve class for common properties.

.points : Array

The array of Vector3 points that define the curve. It needs at least two entries.

.closed : Boolean

The curve will loop back onto itself when this is true.

.curveType : String

Possible values are centripetal, chordal and catmullrom.

.tension : Float

When .curveType is catmullrom, defines catmullrom's tension.

Methods

See the base Curve class for common methods.

Source

src/extras/curves/CatmullRomCurve3.js

Curve

CubicBezierCurve

Create a smooth 2d cubic bezier curve, defined by a start point, endpoint and two control points.

Code Example

const curve = new THREE.CubicBezierCurve( new THREE.Vector2( -10, 0 ), new THREE.Vector2( -5, 15 ), new THREE.Vector2( 20, 15 ), new THREE.Vector2( 10, 0 ) ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const curveObject = new THREE.Line( geometry, material );

Constructor

CubicBezierCurve ( v0 : Vector2, v1 : Vector2, v2 : Vector2, v3 : Vector2 )

v0 – The starting point.
v1 – The first control point.
v2 – The second control point.
v3 – The ending point.

Properties

See the base Curve class for common properties.

.v0 : Vector2

The starting point.

.v1 : Vector2

The first control point.

.v2 : Vector2

The second control point.

.v3 : Vector2

The ending point.

Methods

See the base Curve class for common Methods.

Source

src/extras/curves/CubicBezierCurve.js

Curve

CubicBezierCurve3

Create a smooth 3d cubic bezier curve, defined by a start point, endpoint and two control points.

Code Example

const curve = new THREE.CubicBezierCurve3( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( -5, 15, 0 ), new THREE.Vector3( 20, 15, 0 ), new THREE.Vector3( 10, 0, 0 ) ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const curveObject = new THREE.Line( geometry, material );

Constructor

CubicBezierCurve3( v0 : Vector3, v1 : Vector3, v2 : Vector3, v3 : Vector3 )

v0 – The starting point.
v1 – The first control point.
v2 – The second control point.
v3 – The ending point.

Properties

See the base Curve class for common properties.

.v0 : Vector3

The starting point.

.v1 : Vector3

The first control point.

.v2 : Vector3

The second control point.

.v3 : Vector3

The ending point.

Methods

See the base Curve class for common Methods.

Source

src/extras/curves/CubicBezierCurve3.js

Curve

EllipseCurve

Creates a 2d curve in the shape of an ellipse. Setting the xRadius equal to the yRadius will result in a circle.

Code Example

const curve = new THREE.EllipseCurve( 0, 0, // ax, aY 10, 10, // xRadius, yRadius 0, 2 * Math.PI, // aStartAngle, aEndAngle false, // aClockwise 0 // aRotation ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const ellipse = new THREE.Line( geometry, material );

Constructor

EllipseCurve( aX : Float, aY : Float, xRadius : Float, yRadius : Float, aStartAngle : Radians, aEndAngle : Radians, aClockwise : Boolean, aRotation : Radians )

aX – The X center of the ellipse. Default is 0.
aY – The Y center of the ellipse. Default is 0.
xRadius – The radius of the ellipse in the x direction. Default is 1.
yRadius – The radius of the ellipse in the y direction. Default is 1.
aStartAngle – The start angle of the curve in radians starting from the positive X axis. Default is 0.
aEndAngle – The end angle of the curve in radians starting from the positive X axis. Default is 2 x Math.PI.
aClockwise – Whether the ellipse is drawn clockwise. Default is false.
aRotation – The rotation angle of the ellipse in radians, counterclockwise from the positive X axis (optional). Default is 0.

Properties

See the base Curve class for common properties.

.aX : Float

The X center of the ellipse.

.aY : Float

The Y center of the ellipse.

.xRadius : Radians

The radius of the ellipse in the x direction.

.yRadius : Radians

The radius of the ellipse in the y direction.

.aStartAngle : Float

The start angle of the curve in radians starting from the middle right side.

.aEndAngle : Float

The end angle of the curve in radians starting from the middle right side.

.aClockwise : Boolean

Whether the ellipse is drawn clockwise.

.aRotation : Float

The rotation angle of the ellipse in radians, counterclockwise from the positive X axis (optional). Default is 0.

Methods

See the base Curve class for common methods.

Source

src/extras/curves/EllipseCurve.js

Curve

LineCurve

A curve representing a 2d line segment.

Constructor

LineCurve( v1 : Vector2, v2 : Vector2 )

v1 – The start point.
v2 - The end point.

Properties

See the base Curve class for common properties.

.v1 : Vector2

The start point.

.v2 : Vector2

The end point

Methods

See the base Curve class for common methods.

Source

src/extras/curves/LineCurve.js

Curve

LineCurve3

A curve representing a 3d line segment.

Constructor

LineCurve3( v1 : Vector3, v2 : Vector3 )

v1 – The start point.
v2 - The end point.

Properties

See the base Curve class for common properties.

.v1 : Vector3

The start point.

.v2 : Vector3

The end point.

Methods

See the base Curve class for common methods.

Source

src/extras/curves/LineCurve3.js

Curve

QuadraticBezierCurve

Create a smooth 2d quadratic bezier curve, defined by a startpoint, endpoint and a single control point.

Code Example

const curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( -10, 0 ), new THREE.Vector2( 20, 15 ), new THREE.Vector2( 10, 0 ) ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const curveObject = new THREE.Line( geometry, material );

Constructor

QuadraticBezierCurve( v0 : Vector2, v1 : Vector2, v2 : Vector2 )

v0 – The startpoint.
v1 – The control point.
v2 – The endpoint.

Properties

See the base Curve class for common properties.

.v0 : Vector2

The startpoint.

.v1 : Vector2

The control point.

.v2 : Vector2

The endpoint.

Methods

See the base Curve class for common methods.

Source

src/extras/curves/QuadraticBezierCurve.js

Curve

QuadraticBezierCurve3

Create a smooth 3d quadratic bezier curve, defined by a startpoint, endpoint and a single control point.

Code Example

const curve = new THREE.QuadraticBezierCurve3( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 20, 15, 0 ), new THREE.Vector3( 10, 0, 0 ) ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const curveObject = new THREE.Line( geometry, material );

Constructor

QuadraticBezierCurve3( v0 : Vector3, v1 : Vector3, v2 : Vector3 )

v0 – The starting point
v1 – The middle control point
v2 – The ending point

Properties

See the base Curve class for common properties.

.v0 : Vector3

The startpoint.

.v1 : Vector3

The control point.

.v2 : Vector3

The endpoint.

Methods

See the base Curve class for common methods.

Source

src/extras/curves/QuadraticBezierCurve3.js

Curve

SplineCurve

Create a smooth 2d spline curve from a series of points. Internally this uses Interpolations.CatmullRom to create the curve.

Code Example

// Create a sine-like wave const curve = new THREE.SplineCurve( [ new THREE.Vector2( -10, 0 ), new THREE.Vector2( -5, 5 ), new THREE.Vector2( 0, 0 ), new THREE.Vector2( 5, -5 ), new THREE.Vector2( 10, 0 ) ] ); const points = curve.getPoints( 50 ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); // Create the final object to add to the scene const splineObject = new THREE.Line( geometry, material );

Constructor

SplineCurve( points : Array )

points – An array of Vector2 points that define the curve.

Properties

See the base Curve class for common properties.

.points : Array

The array of Vector2 points that define the curve.

Methods

See the base Curve class for common methods.

Source

src/extras/curves/SplineCurve.js

BufferGeometry

BoxGeometry

BoxGeometry is a geometry class for a rectangular cuboid with a given 'width', 'height', and 'depth'. On creation, the cuboid is centred on the origin, with each edge parallel to one of the axes.

Code Example

const geometry = new THREE.BoxGeometry( 1, 1, 1 ); const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} ); const cube = new THREE.Mesh( geometry, material ); scene.add( cube );

Constructor

BoxGeometry(width : Float, height : Float, depth : Float, widthSegments : Integer, heightSegments : Integer, depthSegments : Integer)

width — Width; that is, the length of the edges parallel to the X axis. Optional; defaults to 1.
height — Height; that is, the length of the edges parallel to the Y axis. Optional; defaults to 1.
depth — Depth; that is, the length of the edges parallel to the Z axis. Optional; defaults to 1.
widthSegments — Number of segmented rectangular faces along the width of the sides. Optional; defaults to 1.
heightSegments — Number of segmented rectangular faces along the height of the sides. Optional; defaults to 1.
depthSegments — Number of segmented rectangular faces along the depth of the sides. Optional; defaults to 1.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/BoxGeometry.js

BufferGeometryLatheGeometry

CapsuleGeometry

CapsuleGeometry is a geometry class for a capsule with given radii and height. It is constructed using a lathe.

Code Example

const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8 ); const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} ); const capsule = new THREE.Mesh( geometry, material ); scene.add( capsule );

Constructor

CapsuleGeometry(radius : Float, length : Float, capSegments : Integer, radialSegments : Integer)

radius — Radius of the capsule. Optional; defaults to 1.
length — Length of the middle section. Optional; defaults to 1.
capSegments — Number of curve segments used to build the caps. Optional; defaults to 4.
radialSegments — Number of segmented faces around the circumference of the capsule. Optional; defaults to 8.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/CapsuleGeometry.js

BufferGeometry

CircleGeometry

CircleGeometry is a simple shape of Euclidean geometry. It is constructed from a number of triangular segments that are oriented around a central point and extend as far out as a given radius. It is built counter-clockwise from a start angle and a given central angle. It can also be used to create regular polygons, where the number of segments determines the number of sides.

Code Example

const geometry = new THREE.CircleGeometry( 5, 32 ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); const circle = new THREE.Mesh( geometry, material ); scene.add( circle );

Constructor

CircleGeometry(radius : Float, segments : Integer, thetaStart : Float, thetaLength : Float)

radius — Radius of the circle, default = 1.
segments — Number of segments (triangles), minimum = 3, default = 32.
thetaStart — Start angle for first segment, default = 0 (three o'clock position).
thetaLength — The central angle, often called theta, of the circular sector. The default is 2*Pi, which makes for a complete circle.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/CircleGeometry.js

BufferGeometryCylinderGeometry

ConeGeometry

A class for generating cone geometries.

Code Example

const geometry = new THREE.ConeGeometry( 5, 20, 32 ); const material = new THREE.MeshBasicMaterial( {color: 0xffff00} ); const cone = new THREE.Mesh(geometry, material ); scene.add( cone );

Constructor

ConeGeometry(radius : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)

radius — Radius of the cone base. Default is 1.
height — Height of the cone. Default is 1.
radialSegments — Number of segmented faces around the circumference of the cone. Default is 32
heightSegments — Number of rows of faces along the height of the cone. Default is 1.
openEnded — A Boolean indicating whether the base of the cone is open or capped. Default is false, meaning capped.
thetaStart — Start angle for first segment, default = 0 (three o'clock position).
thetaLength — The central angle, often called theta, of the circular sector. The default is 2*Pi, which makes for a complete cone.

Properties

See the base CylinderGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base CylinderGeometry class for common methods.

Source

src/geometries/ConeGeometry.js

BufferGeometry

CylinderGeometry

A class for generating cylinder geometries.

Code Example

const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 ); const material = new THREE.MeshBasicMaterial( {color: 0xffff00} ); const cylinder = new THREE.Mesh( geometry, material ); scene.add( cylinder );

Constructor

CylinderGeometry(radiusTop : Float, radiusBottom : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)

radiusTop — Radius of the cylinder at the top. Default is 1.
radiusBottom — Radius of the cylinder at the bottom. Default is 1.
height — Height of the cylinder. Default is 1.
radialSegments — Number of segmented faces around the circumference of the cylinder. Default is 32
heightSegments — Number of rows of faces along the height of the cylinder. Default is 1.
openEnded — A Boolean indicating whether the ends of the cylinder are open or capped. Default is false, meaning capped.
thetaStart — Start angle for first segment, default = 0 (three o'clock position).
thetaLength — The central angle, often called theta, of the circular sector. The default is 2*Pi, which makes for a complete cylinder.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/CylinderGeometry.js

BufferGeometryPolyhedronGeometry

DodecahedronGeometry

A class for generating a dodecahedron geometries.

Constructor

DodecahedronGeometry(radius : Float, detail : Integer)

radius — Radius of the dodecahedron. Default is 1.
detail — Default is 0. Setting this to a value greater than 0 adds vertices making it no longer a dodecahedron.

Properties

See the base PolyhedronGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base PolyhedronGeometry class for common methods.

Source

src/geometries/DodecahedronGeometry.js

BufferGeometry

EdgesGeometry

This can be used as a helper object to view the edges of a geometry.

Code Example

const geometry = new THREE.BoxGeometry( 100, 100, 100 ); const edges = new THREE.EdgesGeometry( geometry ); const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial( { color: 0xffffff } ) ); scene.add( line );

Examples

helpers

Constructor

EdgesGeometry( geometry : BufferGeometry, thresholdAngle : Integer )

geometry — Any geometry object.
thresholdAngle — An edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/EdgesGeometry.js

BufferGeometry

ExtrudeGeometry

Creates extruded geometry from a path shape.

Code Example

const length = 12, width = 8; const shape = new THREE.Shape(); shape.moveTo( 0,0 ); shape.lineTo( 0, width ); shape.lineTo( length, width ); shape.lineTo( length, 0 ); shape.lineTo( 0, 0 ); const extrudeSettings = { steps: 2, depth: 16, bevelEnabled: true, bevelThickness: 1, bevelSize: 1, bevelOffset: 0, bevelSegments: 1 }; const geometry = new THREE.ExtrudeGeometry( shape, extrudeSettings ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const mesh = new THREE.Mesh( geometry, material ) ; scene.add( mesh );

Constructor

ExtrudeGeometry(shapes : Array, options : Object)

shapes — Shape or an array of shapes.
options — Object that can contain the following parameters.

This object extrudes a 2D shape to a 3D geometry.

When creating a Mesh with this geometry, if you'd like to have a separate material used for its face and its extruded sides, you can use an array of materials. The first material will be applied to the face; the second material will be applied to the sides.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/ExtrudeGeometry.js

BufferGeometryPolyhedronGeometry

IcosahedronGeometry

A class for generating an icosahedron geometry.

Constructor

IcosahedronGeometry(radius : Float, detail : Integer)

radius — Default is 1.
detail — Default is 0. Setting this to a value greater than 0 adds more vertices making it no longer an icosahedron. When detail is greater than 1, it's effectively a sphere.

Properties

See the base PolyhedronGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base PolyhedronGeometry class for common methods.

Source

src/geometries/IcosahedronGeometry.js

BufferGeometry

LatheGeometry

Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.

Code Example

const points = []; for ( let i = 0; i < 10; i ++ ) { points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) ); } const geometry = new THREE.LatheGeometry( points ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); const lathe = new THREE.Mesh( geometry, material ); scene.add( lathe );

Constructor

LatheGeometry(points : Array, segments : Integer, [param:Float phiStart], phiLength : Float)

points — Array of Vector2s. The x-coordinate of each point must be greater than zero. Default is an array with (0,-0.5), (0.5,0) and (0,0.5) which creates a simple diamond shape.
segments — the number of circumference segments to generate. Default is 12.
phiStart — the starting angle in radians. Default is 0.
phiLength — the radian (0 to 2PI) range of the lathed section 2PI is a closed lathe, less than 2PI is a portion. Default is 2PI.

This creates a LatheGeometry based on the parameters.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/LatheGeometry.js

BufferGeometryPolyhedronGeometry

OctahedronGeometry

A class for generating an octahedron geometry.

Constructor

OctahedronGeometry(radius : Float, detail : Integer)

radius — Radius of the octahedron. Default is 1.
detail — Default is 0. Setting this to a value greater than zero add vertices making it no longer an octahedron.

Properties

See the base PolyhedronGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base PolyhedronGeometry class for common methods.

Source

src/geometries/OctahedronGeometry.js

BufferGeometry

PlaneGeometry

A class for generating plane geometries.

Code Example

const geometry = new THREE.PlaneGeometry( 1, 1 ); const material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} ); const plane = new THREE.Mesh( geometry, material ); scene.add( plane );

Constructor

PlaneGeometry(width : Float, height : Float, widthSegments : Integer, heightSegments : Integer)

width — Width along the X axis. Default is 1.
height — Height along the Y axis. Default is 1.
widthSegments — Optional. Default is 1.
heightSegments — Optional. Default is 1.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/PlaneGeometry.js

BufferGeometry

PolyhedronGeometry

A polyhedron is a solid in three dimensions with flat faces. This class will take an array of vertices, project them onto a sphere, and then divide them up to the desired level of detail. This class is used by DodecahedronGeometry, IcosahedronGeometry, OctahedronGeometry, and TetrahedronGeometry to generate their respective geometries.

Code Example

const verticesOfCube = [ -1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1, -1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1, ]; const indicesOfFaces = [ 2,1,0, 0,3,2, 0,4,7, 7,3,0, 0,1,5, 5,4,0, 1,2,6, 6,5,1, 2,3,7, 7,6,2, 4,5,6, 6,7,4 ]; const geometry = new THREE.PolyhedronGeometry( verticesOfCube, indicesOfFaces, 6, 2 );

Constructor

PolyhedronGeometry(vertices : Array, indices : Array, radius : Float, detail : Integer)

vertices — Array of points of the form [1,1,1, -1,-1,-1, ... ]
indices — Array of indices that make up the faces of the form [0,1,2, 2,3,0, ... ]
radius — Float - The radius of the final shape
detail — Integer - How many levels to subdivide the geometry. The more detail, the smoother the shape.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/PolyhedronGeometry.js

BufferGeometry

RingGeometry

A class for generating a two-dimensional ring geometry.

Code Example

const geometry = new THREE.RingGeometry( 1, 5, 32 ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } ); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh );

Constructor

RingGeometry(innerRadius : Float, outerRadius : Float, thetaSegments : Integer, phiSegments : Integer, thetaStart : Float, thetaLength : Float)

innerRadius — Default is 0.5.
outerRadius — Default is 1.
thetaSegments — Number of segments. A higher number means the ring will be more round. Minimum is 3. Default is 32.
phiSegments — Number of segments per ring segment. Minimum is 1. Default is 1.
thetaStart — Starting angle. Default is 0.
thetaLength — Central angle. Default is Math.PI * 2.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/RingGeometry.js

BufferGeometry

ShapeGeometry

Creates an one-sided polygonal geometry from one or more path shapes.

Code Example

const x = 0, y = 0; const heartShape = new THREE.Shape(); heartShape.moveTo( x + 5, y + 5 ); heartShape.bezierCurveTo( x + 5, y + 5, x + 4, y, x, y ); heartShape.bezierCurveTo( x - 6, y, x - 6, y + 7,x - 6, y + 7 ); heartShape.bezierCurveTo( x - 6, y + 11, x - 3, y + 15.4, x + 5, y + 19 ); heartShape.bezierCurveTo( x + 12, y + 15.4, x + 16, y + 11, x + 16, y + 7 ); heartShape.bezierCurveTo( x + 16, y + 7, x + 16, y, x + 10, y ); heartShape.bezierCurveTo( x + 7, y, x + 5, y + 5, x + 5, y + 5 ); const geometry = new THREE.ShapeGeometry( heartShape ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const mesh = new THREE.Mesh( geometry, material ) ; scene.add( mesh );

Constructor

ShapeGeometry(shapes : Array, curveSegments : Integer)

shapes — Array of shapes or a single shape. Default is a single triangle shape.
curveSegments - Integer - Number of segments per shape. Default is 12.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/ShapeGeometry.js

BufferGeometry

SphereGeometry

A class for generating sphere geometries.

Code Example

const geometry = new THREE.SphereGeometry( 15, 32, 16 ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); const sphere = new THREE.Mesh( geometry, material ); scene.add( sphere );

Constructor

SphereGeometry(radius : Float, widthSegments : Integer, heightSegments : Integer, phiStart : Float, phiLength : Float, thetaStart : Float, thetaLength : Float)

radius — sphere radius. Default is 1.
widthSegments — number of horizontal segments. Minimum value is 3, and the default is 32.
heightSegments — number of vertical segments. Minimum value is 2, and the default is 16.
phiStart — specify horizontal starting angle. Default is 0.
phiLength — specify horizontal sweep angle size. Default is Math.PI * 2.
thetaStart — specify vertical starting angle. Default is 0.
thetaLength — specify vertical sweep angle size. Default is Math.PI.

The geometry is created by sweeping and calculating vertexes around the Y axis (horizontal sweep) and the Z axis (vertical sweep). Thus, incomplete spheres (akin to 'sphere slices') can be created through the use of different values of phiStart, phiLength, thetaStart and thetaLength, in order to define the points in which we start (or end) calculating those vertices.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/SphereGeometry.js

BufferGeometryPolyhedronGeometry

TetrahedronGeometry

A class for generating a tetrahedron geometries.

Constructor

TetrahedronGeometry(radius : Float, detail : Integer)

radius — Radius of the tetrahedron. Default is 1.
detail — Default is 0. Setting this to a value greater than 0 adds vertices making it no longer a tetrahedron.

Properties

See the base PolyhedronGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base PolyhedronGeometry class for common methods.

Source

src/geometries/TetrahedronGeometry.js

BufferGeometry

TorusGeometry

A class for generating torus geometries.

Code Example

const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); const torus = new THREE.Mesh( geometry, material ); scene.add( torus );

Constructor

TorusGeometry(radius : Float, tube : Float, radialSegments : Integer, tubularSegments : Integer, arc : Float)

radius - Radius of the torus, from the center of the torus to the center of the tube. Default is 1.
tube — Radius of the tube. Default is 0.4.
radialSegments — Default is 12
tubularSegments — Default is 48.
arc — Central angle. Default is Math.PI * 2.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/TorusGeometry.js

BufferGeometry

TorusKnotGeometry

Creates a torus knot, the particular shape of which is defined by a pair of coprime integers, p and q. If p and q are not coprime, the result will be a torus link.

Code Example

const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); const torusKnot = new THREE.Mesh( geometry, material ); scene.add( torusKnot );

Constructor

TorusKnotGeometry(radius : Float, tube : Float, tubularSegments : Integer, radialSegments : Integer, p : Integer, q : Integer)

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/TorusKnotGeometry.js

BufferGeometry

TubeGeometry

Creates a tube that extrudes along a 3d curve.

Code Example

class CustomSinCurve extends THREE.Curve { constructor( scale = 1 ) { super(); this.scale = scale; } getPoint( t, optionalTarget = new THREE.Vector3() ) { const tx = t * 3 - 1.5; const ty = Math.sin( 2 * Math.PI * t ); const tz = 0; return optionalTarget.set( tx, ty, tz ).multiplyScalar( this.scale ); } } const path = new CustomSinCurve( 10 ); const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh );

Constructor

TubeGeometry(path : Curve, tubularSegments : Integer, radius : Float, radialSegments : Integer, closed : Boolean)

path — Curve - A 3D path that inherits from the Curve base class. Default is a quadratic bezier curve.
tubularSegments — Integer - The number of segments that make up the tube. Default is 64.
radius — Float - The radius of the tube. Default is 1.
radialSegments — Integer - The number of segments that make up the cross-section. Default is 8.
closed — Boolean Is the tube open or closed. Default is false.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

.tangents : Array

An array of Vector3 tangents

.normals : Array

An array of Vector3 normals

.binormals : Array

An array of Vector3 binormals

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/TubeGeometry.js

BufferGeometry

WireframeGeometry

This can be used as a helper object to view a geometry as a wireframe.

Code Example

const geometry = new THREE.SphereGeometry( 100, 100, 100 ); const wireframe = new THREE.WireframeGeometry( geometry ); const line = new THREE.LineSegments( wireframe ); line.material.depthTest = false; line.material.opacity = 0.25; line.material.transparent = true; scene.add( line );

Examples

helpers

Constructor

WireframeGeometry( geometry : BufferGeometry )

geometry — any geometry object.

Properties

See the base BufferGeometry class for common properties.

Methods

See the base BufferGeometry class for common methods.

Source

src/geometries/WireframeGeometry.js

Object3D

ArrowHelper

An 3D arrow object for visualizing directions.

Code Example

const dir = new THREE.Vector3( 1, 2, 0 ); //normalize the direction vector (convert to vector of length 1) dir.normalize(); const origin = new THREE.Vector3( 0, 0, 0 ); const length = 1; const hex = 0xffff00; const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex ); scene.add( arrowHelper );

Examples

WebGL / shadowmesh

Constructor

ArrowHelper(dir : Vector3, origin : Vector3, length : Number, hex : Number, headLength : Number, headWidth : Number )

dir -- direction from origin. Must be a unit vector.
origin -- Point at which the arrow starts.
length -- length of the arrow. Default is 1.
hex -- hexadecimal value to define color. Default is 0xffff00.
headLength -- The length of the head of the arrow. Default is 0.2 * length.
headWidth -- The width of the head of the arrow. Default is 0.2 * headLength.

Properties

See the base Object3D class for common properties.

.line : Line

Contains the line part of the arrowHelper.

.cone : Mesh

Contains the cone part of the arrowHelper.

Methods

See the base Object3D class for common methods.

.setColor (color : Color) : undefined

color -- The desired color.

Sets the color of the arrowHelper.

.setLength (length : Number, headLength : Number, headWidth : Number) : undefined

length -- The desired length.
headLength -- The length of the head of the arrow.
headWidth -- The width of the head of the arrow.

Sets the length of the arrowhelper.

.setDirection (dir : Vector3) : undefined

dir -- The desired direction. Must be a unit vector.

Sets the direction of the arrowhelper.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/ArrowHelper.js

Object3DLineLineSegments

AxesHelper

An axis object to visualize the 3 axes in a simple way.
The X axis is red. The Y axis is green. The Z axis is blue.

Code Example

const axesHelper = new THREE.AxesHelper( 5 ); scene.add( axesHelper );

Examples

WebGL / buffergeometry / compression
WebGL / geometry / convex
WebGL / loader / nrrd

Constructor

AxesHelper( size : Number )

size -- (optional) size of the lines representing the axes. Default is 1.

Properties

See the base LineSegments class for common properties.

Methods

See the base LineSegments class for common methods.

.setColors ( xAxisColor : Color, yAxisColor : Color, zAxisColor : Color ) : this

Sets the axes colors to xAxisColor, yAxisColor, zAxisColor.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/AxesHelper.js

Object3DLineLineSegments

BoxHelper

Helper object to graphically show the world-axis-aligned bounding box around an object. The actual bounding box is handled with Box3, this is just a visual helper for debugging. It can be automatically resized with the BoxHelper.update method when the object it's created from is transformed. Note that the object must have a BufferGeometry for this to work, so it won't work with Sprites.

Code Example

const sphere = new THREE.SphereGeometry(); const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) ); const box = new THREE.BoxHelper( object, 0xffff00 ); scene.add( box );

Examples

WebGL / helpers
WebGL / loader / nrrd
WebGL / buffergeometry / drawrange

Constructor

BoxHelper( object : Object3D, color : Color )

object -- (optional) the object3D to show the world-axis-aligned boundingbox.
color -- (optional) hexadecimal value that defines the box's color. Default is 0xffff00.

Creates a new wireframe box that bounds the passed object. Internally this uses Box3.setFromObject to calculate the dimensions. Note that this includes any children.

Properties

See the base LineSegments class for common properties.

Methods

See the base LineSegments class for common methods.

.update () : undefined

Updates the helper's geometry to match the dimensions of the object, including any children. See Box3.setFromObject.

.setFromObject ( object : Object3D ) : this

object - Object3D to create the helper of.

Updates the wireframe box for the passed object.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/BoxHelper.js

Object3DLineLineSegments

Box3Helper

Helper object to visualize a Box3.

Code Example

const box = new THREE.Box3(); box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) ); const helper = new THREE.Box3Helper( box, 0xffff00 ); scene.add( helper );

Constructor

Box3Helper( box : Box3, color : Color )

box -- the Box3 to show.
color -- (optional) the box's color. Default is 0xffff00.

Creates a new wireframe box that represents the passed Box3.

Properties

See the base LineSegments class for common properties.

.box : Box3

The Box3 being visualized.

Methods

See the base LineSegments class for common methods.

.updateMatrixWorld ( force : Boolean ) : undefined

This overrides the method in the base Object3D class so that it also updates the wireframe box to the extent of the .box property.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/Box3Helper.js

Object3DLineLineSegments

CameraHelper

This helps with visualizing what a camera contains in its frustum. It visualizes the frustum of a camera using a LineSegments.

CameraHelper must be a child of the scene.

Code Example

const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); const helper = new THREE.CameraHelper( camera ); scene.add( helper );

Examples

WebGL / camera
WebGL / extrude / splines

Constructor

CameraHelper( camera : Camera )

camera -- The camera to visualize.

This create a new CameraHelper for the specified camera.

Properties

See the base LineSegments class for common properties.

.camera : Camera

The camera being visualized.

.pointMap : Object

This contains the points used to visualize the camera.

.matrix : Object

Reference to the camera.matrixWorld.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the camera's matrixWorld.

Methods

See the base LineSegments class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.setColors ( frustum : Color, cone : Color, up : Color, target : Color, cross : Color ) : this

Defines the colors of the helper.

.update () : undefined

Updates the helper based on the projectionMatrix of the camera.

Source

src/helpers/CameraHelper.js

Object3D

DirectionalLightHelper

Helper object to assist with visualizing a DirectionalLight's effect on the scene. This consists of plane and a line representing the light's position and direction.

Code Example

const light = new THREE.DirectionalLight( 0xFFFFFF ); scene.add( light ); const helper = new THREE.DirectionalLightHelper( light, 5 ); scene.add( helper );

Constructor

DirectionalLightHelper( light : DirectionalLight, size : Number, color : Hex )

light-- The light to be visualized.

size -- (optional) dimensions of the plane. Default is 1.

color -- (optional) if this is not the set the helper will take the color of the light.

Properties

See the base Object3D class for common properties.

.lightPlane : Line

Contains the line mesh showing the location of the directional light.

.light : DirectionalLight

Reference to the directionalLight being visualized.

.matrix : Object

Reference to the light's matrixWorld.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the light's matrixWorld.

.color : hex

The color parameter passed in the constructor. Default is undefined. If this is changed, the helper's color will update the next time update is called.

Methods

See the base Object3D class for common properties.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.update () : undefined

Updates the helper to match the position and direction of the directionalLight being visualized.

Source

src/helpers/DirectionalLightHelper.js

Object3DLineLineSegments

GridHelper

The GridHelper is an object to define grids. Grids are two-dimensional arrays of lines.

Code Example

const size = 10; const divisions = 10; const gridHelper = new THREE.GridHelper( size, divisions ); scene.add( gridHelper );

Examples

WebGL / helpers

Constructor

GridHelper( size : number, divisions : Number, colorCenterLine : Color, colorGrid : Color )

size -- The size of the grid. Default is 10.
divisions -- The number of divisions across the grid. Default is 10.
colorCenterLine -- The color of the centerline. This can be a Color, a hexadecimal value and an CSS-Color name. Default is 0x444444
colorGrid -- The color of the lines of the grid. This can be a Color, a hexadecimal value and an CSS-Color name. Default is 0x888888

Creates a new GridHelper of size 'size' and divided into 'divisions' segments per side. Colors are optional.

Methods

See the base LineSegments class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/GridHelper.js

Object3DLineLineSegments

PolarGridHelper

The PolarGridHelper is an object to define polar grids. Grids are two-dimensional arrays of lines.

Code Example

const radius = 10; const sectors = 16; const rings = 8; const divisions = 64; const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions ); scene.add( helper );

Examples

WebGL / helpers

Constructor

PolarGridHelper( radius : Number, sectors : Number, rings : Number, divisions : Number, color1 : Color, color2 : Color )

radius -- The radius of the polar grid. This can be any positive number. Default is 10.
sectors -- The number of sectors the grid will be divided into. This can be any positive integer. Default is 16.
rings -- The number of rings. This can be any positive integer. Default is 8.
divisions -- The number of line segments used for each circle. This can be any positive integer that is 3 or greater. Default is 64.
color1 -- The first color used for grid elements. This can be a Color, a hexadecimal value and an CSS-Color name. Default is 0x444444
color2 -- The second color used for grid elements. This can be a Color, a hexadecimal value and an CSS-Color name. Default is 0x888888

Creates a new PolarGridHelper of radius 'radius' with 'sectors' number of sectors and 'rings' number of rings, where each circle is smoothed into 'divisions' number of line segments. Colors are optional.

Methods

See the base LineSegments class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/PolarGridHelper.js

Object3D

HemisphereLightHelper

Creates a visual aid consisting of a spherical Mesh for a HemisphereLight.

Code Example

const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); const helper = new THREE.HemisphereLightHelper( light, 5 ); scene.add( helper );

Constructor

HemisphereLightHelper( light : HemisphereLight, sphereSize : Number, color : Hex )

light -- The light being visualized.

size -- The size of the mesh used to visualize the light.

color -- (optional) if this is not the set the helper will take the color of the light.

Properties

See the base Object3D class for common properties.

.light : HemisphereLight

Reference to the HemisphereLight being visualized.

.matrix : Object

Reference to the hemisphereLight's matrixWorld.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the hemisphereLight's matrixWorld.

.color : hex

The color parameter passed in the constructor. Default is undefined. If this is changed, the helper's color will update the next time update is called.

Methods

See the base Object3D class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.update () : undefined

Updates the helper to match the position and direction of the .light.

Source

src/helpers/HemisphereLightHelper.js

Object3DLineLineSegments

PlaneHelper

Helper object to visualize a Plane.

Code Example

const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 ); const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 ); scene.add( helper );

Constructor

PlaneHelper( plane : Plane, size : Float, hex : Color )

plane -- the plane to visualize.
size -- (optional) side length of plane helper. Default is 1.
color -- (optional) the color of the helper. Default is 0xffff00.

Creates a new wireframe representation of the passed plane.

Properties

See the base Line class for common properties.

.plane : Plane

The plane being visualized.

.size : Float

The side lengths of plane helper.

Methods

See the base LineSegments class for common methods.

.updateMatrixWorld ( force : Boolean ) : undefined

This overrides the method in the base Object3D class so that it also updates the helper object according to the .plane and .size properties.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/PlaneHelper.js

Object3DMesh

PointLightHelper

This displays a helper object consisting of a spherical Mesh for visualizing a PointLight.

Code Example

const pointLight = new THREE.PointLight( 0xff0000, 1, 100 ); pointLight.position.set( 10, 10, 10 ); scene.add( pointLight ); const sphereSize = 1; const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize ); scene.add( pointLightHelper );

Examples

WebGL / helpers

Constructor

PointLightHelper( light : PointLight, sphereSize : Float, color : Hex )

light -- The light to be visualized.

sphereSize -- (optional) The size of the sphere helper. Default is 1.

color -- (optional) if this is not the set the helper will take the color of the light.

Properties

See the base Mesh class for common properties.

.light : PointLight

The PointLight that is being visualized.

.matrix : Object

Reference to the pointLight's matrixWorld.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the pointLight's matrixWorld.

.color : hex

The color parameter passed in the constructor. Default is undefined. If this is changed, the helper's color will update the next time update is called.

Methods

See the base Mesh class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.update () : undefined

Updates the helper to match the position of the .light.

Source

src/helpers/PointLightHelper.js

Object3DLineLineSegments

SkeletonHelper

A helper object to assist with visualizing a Skeleton. The helper is rendered using a LineBasicMaterial.

Code Example

const helper = new THREE.SkeletonHelper( skinnedMesh ); scene.add( helper );

Examples

WebGL / animation / skinning / blending
WebGL / animation / skinning / morph
WebGL / loader / bvh

Constructor

SkeletonHelper( object : Object3D )

object -- Usually an instance of SkinnedMesh. However, any instance of Object3D can be used if it represents a hierarchy of Bones (via Object3D.children).

Properties

.bones : Array

The list of bones that the helper renders as Lines.

.isSkeletonHelper : Boolean

Read-only flag to check if a given object is of type SkeletonHelper.

.root : Object3D

The object passed in the constructor.

Methods

See the base LineSegments class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/helpers/SkeletonHelper.js

Object3D

SpotLightHelper

This displays a cone shaped helper object for a SpotLight.

Code Example

const spotLight = new THREE.SpotLight( 0xffffff ); spotLight.position.set( 10, 10, 10 ); scene.add( spotLight ); const spotLightHelper = new THREE.SpotLightHelper( spotLight ); scene.add( spotLightHelper );

Examples

WebGL/ lights / spotlights

Constructor

SpotLightHelper( light : SpotLight, color : Hex )

light -- The SpotLight to be visualized.

color -- (optional) if this is not the set the helper will take the color of the light.

Properties

See the base Object3D class for common properties.

.cone : LineSegments

LineSegments used to visualize the light.

.light : SpotLight

Reference to the SpotLight being visualized.

.matrix : Object

Reference to the spotLight's matrixWorld.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the spotLight's matrixWorld.

.color : hex

The color parameter passed in the constructor. Default is undefined. If this is changed, the helper's color will update the next time update is called.

Methods

See the base Object3D class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.update () : undefined

Updates the light helper.

Source

src/helpers/SpotLightHelper.js

Object3DLight

AmbientLight

This light globally illuminates all objects in the scene equally.

This light cannot be used to cast shadows as it does not have a direction.

Code Example

const light = new THREE.AmbientLight( 0x404040 ); // soft white light scene.add( light );

Constructor

AmbientLight( color : Integer, intensity : Float )

color - (optional) Numeric value of the RGB component of the color. Default is 0xffffff.
intensity - (optional) Numeric value of the light's strength/intensity. Default is 1.

Creates a new AmbientLight.

Properties

See the base Light class for common properties.

.isAmbientLight : Boolean

Read-only flag to check if a given object is of type AmbientLight.

Methods

See the base Light class for common methods.

Source

src/lights/AmbientLight.js

Object3DLight

DirectionalLight

A light that gets emitted in a specific direction. This light will behave as though it is infinitely far away and the rays produced from it are all parallel. The common use case for this is to simulate daylight; the sun is far enough away that its position can be considered to be infinite, and all light rays coming from it are parallel.

This light can cast shadows - see the DirectionalLightShadow page for details.

A Note about Position, Target and rotation

A common point of confusion for directional lights is that setting the rotation has no effect. This is because three.js's DirectionalLight is the equivalent to what is often called a 'Target Direct Light' in other applications.

This means that its direction is calculated as pointing from the light's position to the target's position (as opposed to a 'Free Direct Light' that just has a rotation component).

The reason for this is to allow the light to cast shadows - the shadow camera needs a position to calculate shadows from.

See the target property below for details on updating the target.

Code Example

// White directional light at half intensity shining from the top. const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); scene.add( directionalLight );

Examples

controls / fly
effects / parallaxbarrier
effects / stereo
geometry / extrude / splines
materials / bumpmap

Constructor

DirectionalLight( color : Integer, intensity : Float )

color - (optional) hexadecimal color of the light. Default is 0xffffff (white).
intensity - (optional) numeric value of the light's strength/intensity. Default is 1.

Creates a new DirectionalLight.

Properties

See the base Light class for common properties.

.castShadow : Boolean

If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. See the DirectionalLightShadow for details. The default is false.

.isDirectionalLight : Boolean

Read-only flag to check if a given object is of type DirectionalLight.

.position : Vector3

This is set equal to Object3D.DEFAULT_UP (0, 1, 0), so that the light shines from the top down.

.shadow : DirectionalLightShadow

A DirectionalLightShadow used to calculate shadows for this light.

.target : Object3D

The DirectionalLight points from its position to target.position. The default position of the target is (0, 0, 0).
Note: For the target's position to be changed to anything other than the default, it must be added to the scene using

scene.add( light.target );

This is so that the target's matrixWorld gets automatically updated each frame.

It is also possible to set the target to be another object in the scene (anything with a position property), like so:

const targetObject = new THREE.Object3D(); scene.add(targetObject); light.target = targetObject;

The directionalLight will now track the target object.

Methods

See the base Light class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.copy ( source : DirectionalLight ) : this

Copies value of all the properties from the source to this DirectionalLight.

Source

src/lights/DirectionalLight.js

Object3DLight

HemisphereLight

A light source positioned directly above the scene, with color fading from the sky color to the ground color.

This light cannot be used to cast shadows.

Code Example

const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); scene.add( light );

Examples

animation / skinning / blending
lights / hemisphere
controls / pointerlock
loader / collada / kinematics
loader / stl

Constructor

HemisphereLight( skyColor : Integer, groundColor : Integer, intensity : Float )

skyColor - (optional) hexadecimal color of the sky. Default is 0xffffff.
groundColor - (optional) hexadecimal color of the ground. Default is 0xffffff.
intensity - (optional) numeric value of the light's strength/intensity. Default is 1.

Creates a new HemisphereLight.

Properties

See the base Light class for common properties.

.color : Float

The light's sky color, as passed in the constructor. Default is a new Color set to white (0xffffff).

.groundColor : Float

The light's ground color, as passed in the constructor. Default is a new Color set to white (0xffffff).

.isHemisphereLight : Boolean

Read-only flag to check if a given object is of type HemisphereLight.

.position : Vector3

This is set equal to Object3D.DEFAULT_UP (0, 1, 0), so that the light shines from the top down.

Methods

See the base Light class for common methods.

.copy ( source : HemisphereLight ) : this

Copies the value of color, intensity and groundColor from the source light into this one.

Source

src/lights/HemisphereLight.js

Object3D

Light

Abstract base class for lights - all other light types inherit the properties and methods described here.

Constructor

Light( color : Integer, intensity : Float )

color - (optional) hexadecimal color of the light. Default is 0xffffff (white).
intensity - (optional) numeric value of the light's strength/intensity. Default is 1.

Creates a new Light. Note that this is not intended to be called directly (use one of derived classes instead).

Properties

See the base Object3D class for common properties.

.color : Color

Color of the light. Defaults to a new Color set to white, if not passed in the constructor.

.intensity : Float

The light's intensity, or strength.
The units of intensity depend on the type of light.
Default - 1.0.

.isLight : Boolean

Read-only flag to check if a given object is of type Light.

Methods

See the base Object3D class for common methods.

.dispose () : undefined

Abstract dispose method for classes that extend this class; implemented by subclasses that have disposable GPU-related resources.

.copy ( source : Light ) : this

Copies the value of color and intensity from the source light into this one.

.toJSON ( meta : Object ) : Object

meta -- object containing metadata such as materials, textures for objects.
Convert the light to three.js JSON Object/Scene format.

Source

src/lights/Light.js

Object3DLight

LightProbe

Light probes are an alternative way of adding light to a 3D scene. Unlike classical light sources (e.g. directional, point or spot lights), light probes do not emit light. Instead they store information about light passing through 3D space. During rendering, the light that hits a 3D object is approximated by using the data from the light probe.

Light probes are usually created from (radiance) environment maps. The class LightProbeGenerator can be used to create light probes from instances of CubeTexture or WebGLCubeRenderTarget. However, light estimation data could also be provided in other forms e.g. by WebXR. This enables the rendering of augmented reality content that reacts to real world lighting.

The current probe implementation in three.js supports so-called diffuse light probes. This type of light probe is functionally equivalent to an irradiance environment map.

Examples

WebGL / light probe
WebGL / light probe / cube camera

Constructor

LightProbe( sh : SphericalHarmonics3, intensity : Float )

sh - (optional) An instance of SphericalHarmonics3.
intensity - (optional) Numeric value of the light probe's intensity. Default is 1.

Creates a new LightProbe.

Properties

See the base Light class for common properties. The color property is currently not evaluated and thus has no effect.

.isLightProbe : Boolean

Read-only flag to check if a given object is of type LightProbe.

.sh : SphericalHarmonics3

A light probe uses spherical harmonics to encode lighting information.

Methods

See the base Light class for common methods.

Source

src/lights/LightProbe.js

Object3DLight

PointLight

A light that gets emitted from a single point in all directions. A common use case for this is to replicate the light emitted from a bare lightbulb.

This light can cast shadows - see PointLightShadow page for details.

Code Example

const light = new THREE.PointLight( 0xff0000, 1, 100 ); light.position.set( 50, 50, 50 ); scene.add( light );

Examples

lights / pointlights
effects / anaglyph
geometry / text
lensflares

Constructor

PointLight( color : Integer, intensity : Float, distance : Number, decay : Float )

color - (optional) hexadecimal color of the light. Default is 0xffffff (white).
intensity - (optional) numeric value of the light's strength/intensity. Default is 1.
distance - Maximum range of the light. Default is 0 (no limit).
decay - The amount the light dims along the distance of the light. Default is 2.

Creates a new PointLight.

Properties

See the base Light class for common properties.

.castShadow : Boolean

If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. See the PointLightShadow for details. The default is false.

.decay : Float

The amount the light dims along the distance of the light. Default is 2.
In context of physically-correct rendering the default value should not be changed.

.distance : Float

When distance is zero, light will attenuate according to inverse-square law to infinite distance. When distance is non-zero, light will attenuate according to inverse-square law until near the distance cutoff, where it will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not physically correct.

Default is 0.0.

.intensity : Float

The light's luminous intensity measured in candela (cd). Default is 1.

Changing the intensity will also change the light's power.

.power : Float

The light's power.
Power is the luminous power of the light measured in lumens (lm).

Changing the power will also change the light's intensity.

.shadow : PointLightShadow

A PointLightShadow used to calculate shadows for this light.

The lightShadow's camera is set to a PerspectiveCamera with fov of 90, aspect of 1, near clipping plane at 0.5 and far clipping plane at 500.

Methods

See the base Light class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.copy ( source : PointLight ) : this

Copies value of all the properties from the source to this PointLight.

Source

src/lights/PointLight.js

Object3DLight

RectAreaLight

RectAreaLight emits light uniformly across the face a rectangular plane. This light type can be used to simulate light sources such as bright windows or strip lighting.

Important Notes:

Code Example

const width = 10; const height = 10; const intensity = 1; const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height ); rectLight.position.set( 5, 5, 0 ); rectLight.lookAt( 0, 0, 0 ); scene.add( rectLight ) const rectLightHelper = new RectAreaLightHelper( rectLight ); rectLight.add( rectLightHelper );

Examples

WebGL / rectarealight

Constructor

RectAreaLight( color : Integer, intensity : Float, width : Float, height : Float )

color - (optional) hexadecimal color of the light. Default is 0xffffff (white).
intensity - (optional) the light's intensity, or brightness. Default is 1.
width - (optional) width of the light. Default is 10.
height - (optional) height of the light. Default is 10.

Creates a new RectAreaLight.

Properties

See the base Light class for common properties.

.height : Float

The height of the light.

.intensity : Float

The light's intensity. It is the luminance (brightness) of the light measured in nits (cd/m^2). Default is 1.

Changing the intensity will also change the light's power.

.isRectAreaLight : Boolean

Read-only flag to check if a given object is of type RectAreaLight.

.power : Float

The light's power.
Power is the luminous power of the light measured in lumens (lm).

Changing the power will also change the light's intensity.

.width : Float

The width of the light.

Methods

See the base Light class for common methods.

.copy ( source : RectAreaLight ) : this

Copies value of all the properties from the source to this RectAreaLight.

src/lights/RectAreaLight.js

Object3DLight

SpotLight

This light gets emitted from a single point in one direction, along a cone that increases in size the further from the light it gets.

This light can cast shadows - see the SpotLightShadow page for details.

Code Example

// white spotlight shining from the side, modulated by a texture, casting a shadow const spotLight = new THREE.SpotLight( 0xffffff ); spotLight.position.set( 100, 1000, 100 ); spotLight.map = new THREE.TextureLoader().load( url ); spotLight.castShadow = true; spotLight.shadow.mapSize.width = 1024; spotLight.shadow.mapSize.height = 1024; spotLight.shadow.camera.near = 500; spotLight.shadow.camera.far = 4000; spotLight.shadow.camera.fov = 30; scene.add( spotLight );

Examples

lights / spotlight
lights / spotlights

Constructor

SpotLight( color : Integer, intensity : Float, distance : Float, angle : Radians, penumbra : Float, decay : Float )

color - (optional) hexadecimal color of the light. Default is 0xffffff (white).
intensity - (optional) numeric value of the light's strength/intensity. Default is 1.
distance - Maximum range of the light. Default is 0 (no limit).
angle - Maximum angle of light dispersion from its direction whose upper bound is Math.PI/2.
penumbra - Percent of the spotlight cone that is attenuated due to penumbra. Takes values between zero and 1. Default is zero.
decay - The amount the light dims along the distance of the light.

Creates a new SpotLight.

Properties

See the base Light class for common properties.

.angle : Float

Maximum extent of the spotlight, in radians, from its direction. Should be no more than Math.PI/2. The default is Math.PI/3.

.castShadow : Boolean

If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. See the SpotLightShadow for details. The default is false.

.decay : Float

The amount the light dims along the distance of the light. Default is 2.
In context of physically-correct rendering the default value should not be changed.

.distance : Float

When distance is zero, light will attenuate according to inverse-square law to infinite distance. When distance is non-zero, light will attenuate according to inverse-square law until near the distance cutoff, where it will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not physically correct.

Default is 0.0.

.intensity : Float

The light's luminous intensity measured in candela (cd). Default is 1.

Changing the intensity will also change the light's power.

.isSpotLight : Boolean

Read-only flag to check if a given object is of type SpotLight.

.penumbra : Float

Percent of the spotlight cone that is attenuated due to penumbra. Takes values between zero and 1. The default is 0.0.

.position : Vector3

This is set equal to Object3D.DEFAULT_UP (0, 1, 0), so that the light shines from the top down.

.power : Float

The light's power.
Power is the luminous power of the light measured in lumens (lm).

Changing the power will also change the light's intensity.

.shadow : SpotLightShadow

A SpotLightShadow used to calculate shadows for this light.

.target : Object3D

The Spotlight points from its position to target.position. The default position of the target is (0, 0, 0).
Note: For the target's position to be changed to anything other than the default, it must be added to the scene using scene.add( light.target ); This is so that the target's matrixWorld gets automatically updated each frame.

It is also possible to set the target to be another object in the scene (anything with a position property), like so: const targetObject = new THREE.Object3D(); scene.add(targetObject); light.target = targetObject; The spotlight will now track the target object.

.map : Texture

A Texture used to modulate the color of the light. The spot light color is mixed with the RGB value of this texture, with a ratio corresponding to its alpha value. The cookie-like masking effect is reproduced using pixel values (0, 0, 0, 1-cookie_value). Warning: .map is disabled if .castShadow is false.

Methods

See the base Light class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.copy ( source : SpotLight ) : this

Copies value of all the properties from the source to this SpotLight.

src/lights/SpotLight.js

LightShadow

Serves as a base class for the other shadow classes.

Constructor

LightShadow( camera : Camera )

camera - the light's view of the world.

Create a new LightShadow. This is not intended to be called directly - it is used as a base class by other light shadows.

Properties

.autoUpdate : Boolean

Enables automatic updates of the light's shadow. Default is true. If you do not require dynamic lighting / shadows, you may set this to false.

.camera : Camera

The light's view of the world. This is used to generate a depth map of the scene; objects behind other objects from the light's perspective will be in shadow.

.bias : Float

Shadow map bias, how much to add or subtract from the normalized depth when deciding whether a surface is in shadow.
The default is 0. Very tiny adjustments here (in the order of 0.0001) may help reduce artifacts in shadows

.blurSamples : Integer

The amount of samples to use when blurring a VSM shadow map.

.intensity : Float

The intensity of the shadow. The default is 1. Valid values are in the range [0, 1].

.map : WebGLRenderTarget

The depth map generated using the internal camera; a location beyond a pixel's depth is in shadow. Computed internally during rendering.

.mapPass : WebGLRenderTarget

The distribution map generated using the internal camera; an occlusion is calculated based on the distribution of depths. Computed internally during rendering.

.mapSize : Vector2

A Vector2 defining the width and height of the shadow map.

Higher values give better quality shadows at the cost of computation time. Values must be powers of 2, up to the WebGLRenderer.capabilities.maxTextureSize for a given device, although the width and height don't have to be the same (so, for example, (512, 1024) is valid). The default is ( 512, 512 ).

.matrix : Matrix4

Model to shadow camera space, to compute location and depth in shadow map. Stored in a Matrix4. This is computed internally during rendering.

.needsUpdate : Boolean

When set to true, shadow maps will be updated in the next render call. Default is false. If you have set .autoUpdate to false, you will need to set this property to true and then make a render call to update the light's shadow.

.normalBias : Float

Defines how much the position used to query the shadow map is offset along the object normal. The default is 0. Increasing this value can be used to reduce shadow acne especially in large scenes where light shines onto geometry at a shallow angle. The cost is that shadows may appear distorted.

.radius : Float

Setting this to values greater than 1 will blur the edges of the shadow.
High values will cause unwanted banding effects in the shadows - a greater mapSize will allow for a higher value to be used here before these effects become visible.
If WebGLRenderer.shadowMap.type is set to PCFSoftShadowMap, radius has no effect and it is recommended to increase softness by decreasing mapSize instead.

Note that this has no effect if the WebGLRenderer.shadowMap.type is set to BasicShadowMap.

Methods

.getFrameExtents () : Vector2

Used internally by the renderer to extend the shadow map to contain all viewports

.updateMatrices ( light : Light ) : undefined

Update the matrices for the camera and shadow, used internally by the renderer.

light -- the light for which the shadow is being rendered.

.getFrustum () : Frustum

Gets the shadow cameras frustum. Used internally by the renderer to cull objects.

.getViewportCount () : number

Used internally by the renderer to get the number of viewports that need to be rendered for this shadow.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.copy ( source : LightShadow ) : this

Copies value of all the properties from the source to this Light.

.clone () : LightShadow

Creates a new LightShadow with the same properties as this one.

.toJSON () : Object

Serialize this LightShadow.

Source

src/lights/LightShadow.js

LightShadow

PointLightShadow

This is used internally by PointLights for calculating shadows.

Code Example

//Create a WebGLRenderer and turn on shadows in the renderer const renderer = new THREE.WebGLRenderer(); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; // default THREE.PCFShadowMap //Create a PointLight and turn on shadows for the light const light = new THREE.PointLight( 0xffffff, 1, 100 ); light.position.set( 0, 10, 4 ); light.castShadow = true; // default false scene.add( light ); //Set up shadow properties for the light light.shadow.mapSize.width = 512; // default light.shadow.mapSize.height = 512; // default light.shadow.camera.near = 0.5; // default light.shadow.camera.far = 500; // default //Create a sphere that cast shadows (but does not receive them) const sphereGeometry = new THREE.SphereGeometry( 5, 32, 32 ); const sphereMaterial = new THREE.MeshStandardMaterial( { color: 0xff0000 } ); const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); sphere.castShadow = true; //default is false sphere.receiveShadow = false; //default scene.add( sphere ); //Create a plane that receives shadows (but does not cast them) const planeGeometry = new THREE.PlaneGeometry( 20, 20, 32, 32 ); const planeMaterial = new THREE.MeshStandardMaterial( { color: 0x00ff00 } ) const plane = new THREE.Mesh( planeGeometry, planeMaterial ); plane.receiveShadow = true; scene.add( plane ); //Create a helper for the shadow camera (optional) const helper = new THREE.CameraHelper( light.shadow.camera ); scene.add( helper );

Constructor

PointLightShadow( )

Creates a new PointLightShadow. This is not intended to be called directly - it is called internally by PointLight.

Properties

See the base LightShadow class for common properties.

.isPointLightShadow : Boolean

Read-only flag to check if a given object is of type PointLightShadow.

Methods

See the base LightShadow class for common methods.

.updateMatrices ( light : Light, viewportIndex : number) : undefined

Update the matrices for the camera and shadow, used internally by the renderer.

light -- the light for which the shadow is being rendered.
viewportIndex -- calculates the matrix for this viewport

Source

src/lights/PointLightShadow.js

LightShadow

DirectionalLightShadow

This is used internally by DirectionalLights for calculating shadows.

Unlike the other shadow classes, this uses an OrthographicCamera to calculate the shadows, rather than a PerspectiveCamera. This is because light rays from a DirectionalLight are parallel.

Code Example

//Create a WebGLRenderer and turn on shadows in the renderer const renderer = new THREE.WebGLRenderer(); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; // default THREE.PCFShadowMap //Create a DirectionalLight and turn on shadows for the light const light = new THREE.DirectionalLight( 0xffffff, 1 ); light.position.set( 0, 1, 0 ); //default; light shining from top light.castShadow = true; // default false scene.add( light ); //Set up shadow properties for the light light.shadow.mapSize.width = 512; // default light.shadow.mapSize.height = 512; // default light.shadow.camera.near = 0.5; // default light.shadow.camera.far = 500; // default //Create a sphere that cast shadows (but does not receive them) const sphereGeometry = new THREE.SphereGeometry( 5, 32, 32 ); const sphereMaterial = new THREE.MeshStandardMaterial( { color: 0xff0000 } ); const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); sphere.castShadow = true; //default is false sphere.receiveShadow = false; //default scene.add( sphere ); //Create a plane that receives shadows (but does not cast them) const planeGeometry = new THREE.PlaneGeometry( 20, 20, 32, 32 ); const planeMaterial = new THREE.MeshStandardMaterial( { color: 0x00ff00 } ) const plane = new THREE.Mesh( planeGeometry, planeMaterial ); plane.receiveShadow = true; scene.add( plane ); //Create a helper for the shadow camera (optional) const helper = new THREE.CameraHelper( light.shadow.camera ); scene.add( helper );

Constructor

DirectionalLightShadow( )

Creates a new DirectionalLightShadow. This is not intended to be called directly - it is called internally by DirectionalLight.

Properties

See the base LightShadow class for common properties.

.camera : Camera

The light's view of the world. This is used to generate a depth map of the scene; objects behind other objects from the light's perspective will be in shadow.

The default is an OrthographicCamera with left and bottom set to -5, right and top set to 5, the near clipping plane at 0.5 and the far clipping plane at 500.

.isDirectionalLightShadow : Boolean

Read-only flag to check if a given object is of type DirectionalLightShadow.

Methods

See the base LightShadow class for common methods.

Source

src/lights/DirectionalLightShadow.js

LightShadow

SpotLightShadow

This is used internally by SpotLights for calculating shadows.

Code Example

//Create a WebGLRenderer and turn on shadows in the renderer const renderer = new THREE.WebGLRenderer(); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; // default THREE.PCFShadowMap //Create a SpotLight and turn on shadows for the light const light = new THREE.SpotLight( 0xffffff ); light.castShadow = true; // default false scene.add( light ); //Set up shadow properties for the light light.shadow.mapSize.width = 512; // default light.shadow.mapSize.height = 512; // default light.shadow.camera.near = 0.5; // default light.shadow.camera.far = 500; // default light.shadow.focus = 1; // default //Create a sphere that cast shadows (but does not receive them) const sphereGeometry = new THREE.SphereGeometry( 5, 32, 32 ); const sphereMaterial = new THREE.MeshStandardMaterial( { color: 0xff0000 } ); const sphere = new THREE.Mesh( sphereGeometry, sphereMaterial ); sphere.castShadow = true; //default is false sphere.receiveShadow = false; //default scene.add( sphere ); //Create a plane that receives shadows (but does not cast them) const planeGeometry = new THREE.PlaneGeometry( 20, 20, 32, 32 ); const planeMaterial = new THREE.MeshStandardMaterial( { color: 0x00ff00 } ) const plane = new THREE.Mesh( planeGeometry, planeMaterial ); plane.receiveShadow = true; scene.add( plane ); //Create a helper for the shadow camera (optional) const helper = new THREE.CameraHelper( light.shadow.camera ); scene.add( helper );

Constructor

The constructor creates a PerspectiveCamera : PerspectiveCamera to manage the shadow's view of the world.

Properties

See the base LightShadow class for common properties.

.camera : Camera

The light's view of the world. This is used to generate a depth map of the scene; objects behind other objects from the light's perspective will be in shadow.

The default is a PerspectiveCamera with near clipping plane at 0.5. The fov will track the angle property of the owning SpotLight via the update method. Similarly, the aspect property will track the aspect of the mapSize. If the distance property of the light is set, the far clipping plane will track that, otherwise it defaults to 500.

.focus : Number

Used to focus the shadow camera. The camera's field of view is set as a percentage of the spotlight's field-of-view. Range is [0, 1]. Default is 1.0.

.isSpotLightShadow : Boolean

Read-only flag to check if a given object is of type SpotLightShadow.

Methods

See the base LightShadow class for common methods.

Source

src/lights/SpotLightShadow.js

Loader

AnimationLoader

Class for loading AnimationClips in JSON format. This uses the FileLoader internally for loading files.

Code Example

// instantiate a loader const loader = new THREE.AnimationLoader(); // load a resource loader.load( // resource URL 'animations/animation.js', // onLoad callback function ( animations ) { // animations is an array of AnimationClips }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.log( 'An error happened' ); } );

Constructor

AnimationLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new AnimationLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded animation clips.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called if load errors.

Begin loading from url and pass the loaded animation to onLoad.

.parse ( json : JSON ) : Array

json — required

Parse the JSON object and return an array of animation clips. Individual clips in the object will be parsed with AnimationClip.parse.

Source

src/loaders/AnimationLoader.js

Loader

AudioLoader

Class for loading an AudioBuffer. This uses the FileLoader internally for loading files.

Code Example

// instantiate a listener const audioListener = new THREE.AudioListener(); // add the listener to the camera camera.add( audioListener ); // instantiate audio object const oceanAmbientSound = new THREE.Audio( audioListener ); // add the audio object to the scene scene.add( oceanAmbientSound ); // instantiate a loader const loader = new THREE.AudioLoader(); // load a resource loader.load( // resource URL 'audio/ambient_ocean.ogg', // onLoad callback function ( audioBuffer ) { // set the audio object buffer to the loaded object oceanAmbientSound.setBuffer( audioBuffer ); // play the audio oceanAmbientSound.play(); }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.log( 'An error happened' ); } );

Constructor

AudioLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new AudioLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded text response.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called when load errors.

Begin loading from url and pass the loaded AudioBuffer to onLoad.

Source

src/loaders/AudioLoader.js

Loader

BufferGeometryLoader

A loader for loading a BufferGeometry. This uses the FileLoader internally for loading files.

Code Example

// instantiate a loader const loader = new THREE.BufferGeometryLoader(); // load a resource loader.load( // resource URL 'models/json/pressure.json', // onLoad callback function ( geometry ) { const material = new THREE.MeshLambertMaterial( { color: 0xF5F5F5 } ); const object = new THREE.Mesh( geometry, material ); scene.add( object ); }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.log( 'An error happened' ); } );

Constructor

BufferGeometryLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new BufferGeometryLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.d
onLoad — Will be called when load completes. The argument will be the loaded BufferGeometry.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called when load errors.

Begin loading from url and call onLoad with the parsed response content.

.parse ( json : Object ) : BufferGeometry

json — The JSON structure to parse.

Parse a JSON structure and return a BufferGeometry.

Source

src/loaders/BufferGeometryLoader.js

Cache

A simple caching system, used internally by FileLoader.

Code Example

To enable caching across all loaders that use FileLoader, set

THREE.Cache.enabled = true.

Examples

WebGL / geometry / text
WebGL / interactive / instances / gpu
WebGL / loader / ttf

Properties

.enabled : Boolean

Whether caching is enabled. Default is false.

.files : Object

An object that holds cached files.

Methods

.add ( key : String, file : Object ) : undefined

key — the key to reference the cached file by.
file — The file to be cached.

Adds a cache entry with a key to reference the file. If this key already holds a file, it is overwritten.

.get ( key : String ) : Any

key — A string key

Get the value of key. If the key does not exist undefined is returned.

.remove ( key : String ) : undefined

key — A string key that references a cached file.

Remove the cached file associated with the key.

.clear () : undefined

Remove all values from the cache.

Source

src/loaders/Cache.js

Loader

CompressedTextureLoader

Abstract base class for block based textures loader (dds, pvr, ...). This uses the FileLoader internally for loading files.

Examples

See the DDSLoader and PVRLoader for examples of derived classes.

Constructor

CompressedTextureLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new CompressedTextureLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : CompressedTexture

url — the path or URL to the file. This can also be a Data URI.
onLoad (optional) — Will be called when load completes. The argument will be the loaded texture.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called when load errors.

Begin loading from url and pass the loaded texture to onLoad. The method also returns a new texture object which can directly be used for material creation.

Source

src/loaders/CompressedTextureLoader.js

Loader

CubeTextureLoader

CubeTextureLoader can be used to load cube maps. The loader returns an instance of CubeTexture and expects the cube map to be defined as six separate images representing the sides of a cube. Other cube map definitions like vertical and horizontal cross, column and row layouts are not supported.

The loaded CubeTexture is in sRGB color space. Meaning the colorSpace property is set to THREE.SRGBColorSpace by default.

Code Example

const scene = new THREE.Scene(); scene.background = new THREE.CubeTextureLoader() .setPath( 'textures/cubeMaps/' ) .load( [ 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png' ] );

Examples

materials / cubemap
materials / cubemap / dynamic
materials / cubemap / refraction

Constructor

CubeTextureLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new CubeTextureLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( urls : String, onLoad : Function, onProgress : Function, onError : Function ) : CubeTexture

urls — array of 6 urls to images, one for each side of the CubeTexture. The urls should be specified in the following order: pos-x, neg-x, pos-y, neg-y, pos-z, neg-z. They can also be Data URIs.
Note that, by convention, cube maps are specified in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words, using a left-handed coordinate system. Since three.js uses a right-handed coordinate system, environment maps used in three.js will have pos-x and neg-x swapped.
onLoad (optional) — Will be called when load completes. The argument will be the loaded texture.
onProgress (optional) — This callback function is currently not supported.
onError (optional) — Will be called when load errors.

Begin loading from url and pass the loaded texture to onLoad. The method also returns a new texture object which can directly be used for material creation.

Source

src/loaders/CubeTextureLoader.js

Loader

DataTextureLoader

Abstract base class to load generic binary textures formats (rgbe, hdr, ...). This uses the FileLoader internally for loading files, and creates a new DataTexture.

Examples

See the RGBELoader for an example of a derived class.

Constructor

DataTextureLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new DataTextureLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : DataTexture

url — the path or URL to the file. This can also be a Data URI.
onLoad (optional) — Will be called when load completes. The argument will be the loaded texture.
onProgress (optional) — Will be called while load progresses.The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .[page:Integer loaded]. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called when load errors.

Begin loading from url and pass the loaded texture to onLoad. The method also returns a new texture object which can directly be used for material creation.

Source

src/loaders/DataTextureLoader.js

Loader

FileLoader

A low level class for loading resources with Fetch, used internally by most loaders. It can also be used directly to load any file type that does not have a loader.

Code Example

const loader = new THREE.FileLoader(); //load a text file and output the result to the console loader.load( // resource URL 'example.txt', // onLoad callback function ( data ) { // output the text to the console console.log( data ) }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.error( 'An error happened' ); } );

*Note:* The cache must be enabled using THREE.Cache.enabled = true; This is a global property and only needs to be set once to be used by all loaders that use FileLoader internally. Cache is a cache module that holds the response from each request made through this loader, so each file is requested once.

Constructor

FileLoader ( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is DefaultLoadingManager.

Properties

See the base Loader class for common properties.

.mimeType : String

The expected mimeType. See .setMimeType. Default is undefined.

.responseType : String

The expected response type. See .setResponseType. Default is undefined.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad (optional) — Will be called when loading completes. The argument will be the loaded response.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called if an error occurs.

Load the URL and pass the response to the onLoad function.

.setMimeType ( mimeType : String ) : this

Set the expected mimeType of the file being loaded. Note that in many cases this will be determined automatically, so by default it is undefined.

.setResponseType ( responseType : String ) : this

Change the response type. Valid values are:
text or empty string (default) - returns the data as String.
arraybuffer - loads the data into a ArrayBuffer and returns that.
blob - returns the data as a Blob.
document - parses the file using the DOMParser.
json - parses the file using JSON.parse.

Source

src/loaders/FileLoader.js

Loader

ImageBitmapLoader

A loader for loading an Image as an ImageBitmap. An ImageBitmap provides an asynchronous and resource efficient pathway to prepare textures for rendering in WebGL.
Unlike FileLoader, ImageBitmapLoader does not avoid multiple concurrent requests to the same URL.

Note that Texture.flipY and Texture.premultiplyAlpha with ImageBitmap are ignored. ImageBitmap needs these configuration on bitmap creation unlike regular images need them on uploading to GPU. You need to set the equivalent options via ImageBitmapLoader.setOptions instead. Refer to WebGL specification for the detail.

Code Example

// instantiate a loader const loader = new THREE.ImageBitmapLoader(); // set options if needed loader.setOptions( { imageOrientation: 'flipY' } ); // load a image resource loader.load( // resource URL 'image.png', // onLoad callback function ( imageBitmap ) { const texture = new THREE.CanvasTexture( imageBitmap ); const material = new THREE.MeshBasicMaterial( { map: texture } ); }, // onProgress callback currently not supported undefined, // onError callback function ( err ) { console.log( 'An error happened' ); } );

Examples

WebGL / loader / ImageBitmap

Constructor

ImageBitmapLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new ImageBitmapLoader.

Properties

See the base Loader class for common properties.

.isImageBitmapLoader : Boolean

Read-only flag to check if a given object is of type ImageBitmapLoader.

.options : String

An optional object that sets options for the internally used createImageBitmap factory method. Default is undefined.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded image.
onProgress (optional) — This callback function is currently not supported.
onError (optional) — Will be called when load errors.

Begin loading from url and return the image object that will contain the data.

.setOptions ( options : Object ) : this

Sets the options object for createImageBitmap.

Source

src/loaders/ImageBitmapLoader.js

Loader

ImageLoader

A loader for loading an Image. This is used internally by the CubeTextureLoader, ObjectLoader and TextureLoader.

Code Example

// instantiate a loader const loader = new THREE.ImageLoader(); // load a image resource loader.load( // resource URL 'image.png', // onLoad callback function ( image ) { // use the image, e.g. draw part of it on a canvas const canvas = document.createElement( 'canvas' ); const context = canvas.getContext( '2d' ); context.drawImage( image, 100, 100 ); }, // onProgress callback currently not supported undefined, // onError callback function () { console.error( 'An error happened.' ); } );

Please note three.js r84 dropped support for ImageLoader progress events. For an ImageLoader that supports progress events, see this thread.

Examples

WebGL / loader / obj
WebGL / shaders / ocean

Constructor

ImageLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new ImageLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : HTMLImageElement

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded image.
onProgress (optional) — This callback function is currently not supported.
onError (optional) — Will be called when load errors.

Begin loading from url and return the image object that will contain the data.

Source

src/loaders/ImageLoader.js

Loader

Base class for implementing loaders.

Constructor

Loader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new Loader.

Properties

.crossOrigin : String

The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS. Default is anonymous.

.withCredentials : Boolean

Whether the XMLHttpRequest uses credentials. See .setWithCredentials. Default is false.

.manager : LoadingManager

The loadingManager the loader is using. Default is DefaultLoadingManager.

.path : String

The base path from which the asset will be loaded. Default is the empty string.

.resourcePath : String

The base path from which additional resources like textures will be loaded. Default is the empty string.

.requestHeader : Object

The request header used in HTTP request. See .setRequestHeader. Default is empty object.

Methods

.load () : undefined

This method needs to be implement by all concrete loaders. It holds the logic for loading the asset from the backend.

.loadAsync ( url : String, onProgress : Function ) : Promise

url — A string containing the path/URL of the file to be loaded.
onProgress (optional) — A function to be called while the loading is in progress. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.

This method is equivalent to .load, but returns a Promise.

onLoad is handled by Promise.resolve and onError is handled by Promise.reject.

.parse () : undefined

This method needs to be implement by all concrete loaders. It holds the logic for parsing the asset into three.js entities.

.setCrossOrigin ( crossOrigin : String ) : this

crossOrigin — The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.

.setWithCredentials ( value : Boolean ) : this

Whether the XMLHttpRequest uses credentials such as cookies, authorization headers or TLS client certificates. See XMLHttpRequest.withCredentials.
Note that this has no effect if you are loading files locally or from the same domain.

.setPath ( path : String ) : this

path — Set the base path for the asset.

.setResourcePath ( resourcePath : String ) : this

resourcePath — Set the base path for dependent resources like textures.

.setRequestHeader ( requestHeader : Object ) : this

requestHeader - key: The name of the header whose value is to be set. value: The value to set as the body of the header.

Set the request header used in HTTP request.

Source

src/loaders/Loader.js

LoaderUtils

An object with several loader utility functions.

Functions

.decodeText ( array : TypedArray ) : String

array — A stream of bytes as a typed array.

The function takes a stream of bytes as input and returns a string representation.

.extractUrlBase ( url : String ) : String

url — The url to extract the base url from.

Extract the base from the URL.

.resolveURL ( url : String, path : String ) : String

url — The absolute or relative url resolve. path — The base path for relative urls to be resolved against.

Resolves relative urls against the given path. Absolute paths, data urls, and blob urls will be returned as is. Invalid urls will return an empty string.

Source

src/loaders/LoaderUtils.js

Loader

MaterialLoader

A loader for loading a Material in JSON format. This uses the FileLoader internally for loading files.

Code Example

// instantiate a loader const loader = new THREE.MaterialLoader(); // load a resource loader.load( // resource URL 'path/to/material.json', // onLoad callback function ( material ) { object.material = material; }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.log( 'An error happened' ); } );

Constructor

MaterialLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new MaterialLoader.

Properties

See the base Loader class for common properties.

.textures : Object

Object holding any textures used by the material. See .setTextures.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded Material.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called when load errors.

Begin loading from url.

.parse ( json : Object ) : Material

json — The json object containing the parameters of the Material.

Parse a JSON structure and create a new Material of the type json.type with parameters defined in the json object.

.setTextures ( textures : Object ) : this

textures — object containing any textures used by the material.

Source

src/loaders/MaterialLoader.js

Loader

ObjectLoader

A loader for loading a JSON resource in the JSON Object/Scene format.

This uses the FileLoader internally for loading files.

Code Example

const loader = new THREE.ObjectLoader(); loader.load( // resource URL "models/json/example.json", // onLoad callback // Here the loaded data is assumed to be an object function ( obj ) { // Add the loaded object to the scene scene.add( obj ); }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.error( 'An error happened' ); } ); // Alternatively, to parse a previously loaded JSON structure const object = loader.parse( a_json_object ); scene.add( object );

Examples

WebGL / materials / lightmap

Constructor

ObjectLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new ObjectLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded object.
onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.
onError (optional) — Will be called when load errors.

Begin loading from url and call onLoad with the parsed response content.

.parse ( json : Object, onLoad : Function ) : Object3D

json — required. The JSON source to parse.

onLoad — Will be called when parsed completes. The argument will be the parsed object.

Parse a JSON structure and return a three.js object. This is used internally by .load() but can also be used directly to parse a previously loaded JSON structure.

.parseGeometries ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any geometries in the JSON structure.

.parseMaterials ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any materials in the JSON structure using MaterialLoader.

.parseAnimations ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any animations in the JSON structure, using AnimationClip.parse().

.parseImages ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any images in the JSON structure, using ImageLoader.

.parseTextures ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any textures in the JSON structure.

.parseObject ( json : Object, geometries : BufferGeometry, materials : Material, animations : AnimationClip ) : Object3D

json — required. The JSON source to parse.
geometries — required. The geometries of the JSON.
materials — required. The materials of the JSON.
animations — required. The animations of the JSON.

This is used by .parse() to parse any 3D objects in the JSON structure.

Source

src/loaders/ObjectLoader.js

Loader

TextureLoader

Class for loading a texture. This uses the ImageLoader internally for loading files.

Code Example

const texture = new THREE.TextureLoader().load('textures/land_ocean_ice_cloud_2048.jpg' ); // immediately use the texture for material creation const material = new THREE.MeshBasicMaterial( { map:texture } );

Code Example with Callbacks

// instantiate a loader const loader = new THREE.TextureLoader(); // load a resource loader.load( // resource URL 'textures/land_ocean_ice_cloud_2048.jpg', // onLoad callback function ( texture ) { // in this example we create the material when the texture is loaded const material = new THREE.MeshBasicMaterial( { map: texture } ); }, // onProgress callback currently not supported undefined, // onError callback function ( err ) { console.error( 'An error happened.' ); } );

Please note three.js r84 dropped support for TextureLoader progress events. For a TextureLoader that supports progress events, see this thread.

Examples

geometry / cube

Constructor

TextureLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new TextureLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : Texture

url — the path or URL to the file. This can also be a Data URI.
onLoad (optional) — Will be called when load completes. The argument will be the loaded texture.
onProgress (optional) — This callback function is currently not supported.
onError (optional) — Will be called when load errors.

Begin loading from the given URL and pass the fully loaded texture to onLoad. The method also returns a new texture object which can directly be used for material creation. If you do it this way, the texture may pop up in your scene once the respective loading process is finished.

Source

src/loaders/TextureLoader.js

DefaultLoadingManager

A global instance of the LoadingManager, used by most loaders when no custom manager has been specified.

This will be sufficient for most purposes, however there may be times when you desire separate loading managers for say, textures and models.

Code Example

You can optionally set the onStart, onLoad, onProgress, onError functions for the manager. These will then apply to any loaders using the DefaultLoadingManager.

Note that these shouldn't be confused with the similarly named functions of individual loaders, as they are intended for displaying information about the overall status of loading, rather than dealing with the data that has been loaded.

THREE.DefaultLoadingManager.onStart = function ( url, itemsLoaded, itemsTotal ) { console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' ); }; THREE.DefaultLoadingManager.onLoad = function ( ) { console.log( 'Loading Complete!'); }; THREE.DefaultLoadingManager.onProgress = function ( url, itemsLoaded, itemsTotal ) { console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' ); }; THREE.DefaultLoadingManager.onError = function ( url ) { console.log( 'There was an error loading ' + url ); };

Properties

See the LoadingManager page for details of properties.

Methods

See the LoadingManager page for details of methods.

Source

src/loaders/LoadingManager.js

LoadingManager

Handles and keeps track of loaded and pending data. A default global instance of this class is created and used by loaders if not supplied manually - see DefaultLoadingManager.

In general that should be sufficient, however there are times when it can be useful to have separate loaders - for example if you want to show separate loading bars for objects and textures.

Code Example

This example shows how to use LoadingManager to track the progress of OBJLoader.

const manager = new THREE.LoadingManager(); manager.onStart = function ( url, itemsLoaded, itemsTotal ) { console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' ); }; manager.onLoad = function ( ) { console.log( 'Loading complete!'); }; manager.onProgress = function ( url, itemsLoaded, itemsTotal ) { console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' ); }; manager.onError = function ( url ) { console.log( 'There was an error loading ' + url ); }; const loader = new OBJLoader( manager ); loader.load( 'file.obj', function ( object ) { // } );

In addition to observing progress, a LoadingManager can be used to override resource URLs during loading. This may be helpful for assets coming from drag-and-drop events, WebSockets, WebRTC, or other APIs. An example showing how to load an in-memory model using Blob URLs is below.

// Blob or File objects created when dragging files into the webpage. const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3}; const manager = new THREE.LoadingManager(); // Initialize loading manager with URL callback. const objectURLs = []; manager.setURLModifier( ( url ) => { url = URL.createObjectURL( blobs[ url ] ); objectURLs.push( url ); return url; } ); // Load as usual, then revoke the blob URLs. const loader = new GLTFLoader( manager ); loader.load( 'fish.gltf', (gltf) => { scene.add( gltf.scene ); objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) ); });

Examples

WebGL / loader / obj
WebGL / postprocessing / outline

Constructor

LoadingManager( onLoad : Function, onProgress : Function, onError : Function )

onLoad — (optional) this function will be called when all loaders are done.
onProgress — (optional) this function will be called when an item is complete.
onError — (optional) this function will be called a loader encounters errors.
Creates a new LoadingManager.

Properties

.onStart : Function

This function will be called when loading starts. The arguments are:
url — The url of the item just loaded.
itemsLoaded — the number of items already loaded so far.
itemsTotal — the total amount of items to be loaded.

By default this is undefined.

.onLoad : Function

This function will be called when all loading is completed. By default this is undefined, unless passed in the constructor.

.onProgress : Function

This function will be called when an item is complete. The arguments are:
url — The url of the item just loaded.
itemsLoaded — the number of items already loaded so far.
itemsTotal — the total amount of items to be loaded.

By default this is undefined, unless passed in the constructor.

.onError : Function

This function will be called when any item errors, with the argument:
url — The url of the item that errored.

By default this is undefined, unless passed in the constructor.

Methods

.addHandler ( regex : Object, loader : Loader ) : this

regex — A regular expression.
loader — The loader.

Registers a loader with the given regular expression. Can be used to define what loader should be used in order to load specific files. A typical use case is to overwrite the default loader for textures.

// add handler for TGA textures manager.addHandler( /\.tga$/i, new TGALoader() );

.getHandler ( file : String ) : Loader

file — The file path.

Can be used to retrieve the registered loader for the given file path.

.removeHandler ( regex : Object ) : this

regex — A regular expression.

Removes the loader for the given regular expression.

.resolveURL ( url : String ) : String

url — the url to load

Given a URL, uses the URL modifier callback (if any) and returns a resolved URL. If no URL modifier is set, returns the original URL.

.setURLModifier ( callback : Function ) : this

callback — URL modifier callback. Called with url argument, and must return resolvedURL.

If provided, the callback will be passed each resource URL before a request is sent. The callback may return the original URL, or a new URL to override loading behavior. This behavior can be used to load assets from .ZIP files, drag-and-drop APIs, and Data URIs.


Note: The following methods are designed to be called internally by loaders. You shouldn't call them directly.

.itemStart ( url : String ) : undefined

url — the url to load

This should be called by any loader using the manager when the loader starts loading an url.

.itemEnd ( url : String ) : undefined

url — the loaded url

This should be called by any loader using the manager when the loader ended loading an url.

.itemError ( url : String ) : undefined

url — the loaded url

This should be called by any loader using the manager when the loader errors loading an url.

Source

src/loaders/LoadingManager.js

Material

LineBasicMaterial

A material for drawing wireframe-style geometries.

Code Example

const material = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 1, linecap: 'round', //ignored by WebGLRenderer linejoin: 'round' //ignored by WebGLRenderer } );

Examples

WebGL / buffergeometry / drawrange
WebGL / buffergeometry / lines
WebGL / buffergeometry / lines / indexed
WebGL / decals
WebGL / geometry / nurbs
WebGL / geometry / shapes
WebGL / geometry / spline / editor
WebGL / interactive / buffergeometry
WebGL / interactive / voxelpainter
WebGL / lines / colors
WebGL / lines / dashed
physics / ammo / rope

Constructor

LineBasicMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.color : Color

Color of the material, by default set to white (0xffffff).

.fog : Boolean

Whether the material is affected by fog. Default is true.

.linewidth : Float

Controls line thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

If you need wider lines, consider using Line2 or LineSegments2 with LineMaterial.

.linecap : String

Define appearance of line ends. Possible values are 'butt', 'round' and 'square'. Default is 'round'.

This corresponds to the 2D Canvas lineCap property and it is ignored by the WebGL renderer.

.linejoin : String

Define appearance of line joints. Possible values are 'round', 'bevel' and 'miter'. Default is 'round'.

This corresponds to the 2D Canvas lineJoin property and it is ignored by the WebGL renderer.

.map : Texture

Sets the color of the lines using data from a Texture.

Methods

See the base Material class for common methods.

Source

src/materials/LineBasicMaterial.js

MaterialLineBasicMaterial

LineDashedMaterial

A material for drawing wireframe-style geometries with dashed lines.
Note: You must call Line.computeLineDistances() when using LineDashedMaterial.

Code Example

const material = new THREE.LineDashedMaterial( { color: 0xffffff, linewidth: 1, scale: 1, dashSize: 3, gapSize: 1, } );

Examples

WebGL / lines / dashed

Constructor

LineDashedMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from LineBasicMaterial) can be passed in here.

Properties

See the base LineBasicMaterial class for common properties.

.dashSize : number

The size of the dash. This is both the gap with the stroke. Default is 3.

.gapSize : number

The size of the gap. Default is 1.

.isLineDashedMaterial : Boolean

Read-only flag to check if a given object is of type LineDashedMaterial.

.scale : number

The scale of the dashed part of a line. Default is 1.

Methods

See the base LineBasicMaterial class for common methods.

Source

src/materials/LineDashedMaterial.js

Material

Abstract base class for materials.

Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer.

The following properties and methods are inherited by all other material types (although they may have different defaults).

Constructor

Material()

This creates a generic material.

Properties

.alphaHash : Boolean

Enables alpha hashed transparency, an alternative to .transparent or .alphaTest. The material will not be rendered if opacity is lower than a random threshold. Randomization introduces some grain or noise, but approximates alpha blending without the associated problems of sorting. Using TAARenderPass can reduce the resulting noise.

.alphaTest : Float

Sets the alpha value to be used when running an alpha test. The material will not be rendered if the opacity is lower than this value. Default is 0.

.alphaToCoverage : Boolean

Enables alpha to coverage. Can only be used with MSAA-enabled contexts (meaning when the renderer was created with antialias parameter set to true). Enabling this will smooth aliasing on clip plane edges and alphaTest-clipped edges. Default is false.

.blendAlpha : Float

Represents the alpha value of the constant blend color. Default is 0. This property has only an effect when using custom blending with ConstantAlpha or OneMinusConstantAlpha.

.blendColor : Color

Represent the RGB values of the constant blend color. Default is 0x000000.
This property has only an effect when using custom blending with ConstantColor or OneMinusConstantColor.

.blendDst : Integer

Blending destination. Default is OneMinusSrcAlphaFactor. See the destination factors constants for all possible values.
The material's blending must be set to CustomBlending for this to have any effect.

.blendDstAlpha : Integer

The transparency of the .blendDst. Uses .blendDst value if null. Default is null.

.blendEquation : Integer

Blending equation to use when applying blending. Default is AddEquation. See the blending equation constants for all possible values.
The material's blending must be set to CustomBlending for this to have any effect.

.blendEquationAlpha : Integer

The transparency of the .blendEquation. Uses .blendEquation value if null. Default is null.

.blending : Blending

Which blending to use when displaying objects with this material.
This must be set to CustomBlending to use custom blendSrc, blendDst or blendEquation.
See the blending mode constants for all possible values. Default is NormalBlending.

.blendSrc : Integer

Blending source. Default is SrcAlphaFactor. See the source factors constants for all possible values.
The material's blending must be set to CustomBlending for this to have any effect.

.blendSrcAlpha : Integer

The transparency of the .blendSrc. Uses .blendSrc value if null. Default is null.

.clipIntersection : Boolean

Changes the behavior of clipping planes so that only their intersection is clipped, rather than their union. Default is false.

.clippingPlanes : Array

User-defined clipping planes specified as THREE.Plane objects in world space. These planes apply to the objects this material is attached to. Points in space whose signed distance to the plane is negative are clipped (not rendered). This requires WebGLRenderer.localClippingEnabled to be true. See the WebGL / clipping /intersection example. Default is null.

.clipShadows : Boolean

Defines whether to clip shadows according to the clipping planes specified on this material. Default is false.

.colorWrite : Boolean

Whether to render the material's color. This can be used in conjunction with a mesh's renderOrder property to create invisible objects that occlude other objects. Default is true.

.defines : Object

Custom defines to be injected into the shader. These are passed in form of an object literal, with key/value pairs. { MY_CUSTOM_DEFINE: '' , PI2: Math.PI * 2 }. The pairs are defined in both vertex and fragment shaders. Default is undefined.

.depthFunc : Integer

Which depth function to use. Default is LessEqualDepth. See the depth mode constants for all possible values.

.depthTest : Boolean

Whether to have depth test enabled when rendering this material. Default is true. When the depth test is disabled, the depth write will also be implicitly disabled.

.depthWrite : Boolean

Whether rendering this material has any effect on the depth buffer. Default is true.

When drawing 2D overlays it can be useful to disable the depth writing in order to layer several things together without creating z-index artifacts.

.forceSinglePass : Boolean

Whether double-sided, transparent objects should be rendered with a single pass or not. Default is false.

The engine renders double-sided, transparent objects with two draw calls (back faces first, then front faces) to mitigate transparency artifacts. There are scenarios however where this approach produces no quality gains but still doubles draw calls e.g. when rendering flat vegetation like grass sprites. In these cases, set the forceSinglePass flag to true to disable the two pass rendering to avoid performance issues.

.isMaterial : Boolean

Read-only flag to check if a given object is of type Material.

.stencilWrite : Boolean

Whether stencil operations are performed against the stencil buffer. In order to perform writes or comparisons against the stencil buffer this value must be true. Default is false.

.stencilWriteMask : Integer

The bit mask to use when writing to the stencil buffer. Default is 0xFF.

.stencilFunc : Integer

The stencil comparison function to use. Default is AlwaysStencilFunc. See stencil function constants for all possible values.

.stencilRef : Integer

The value to use when performing stencil comparisons or stencil operations. Default is 0.

.stencilFuncMask : Integer

The bit mask to use when comparing against the stencil buffer. Default is 0xFF.

.stencilFail : Integer

Which stencil operation to perform when the comparison function returns false. Default is KeepStencilOp. See the stencil operations constants for all possible values.

.stencilZFail : Integer

Which stencil operation to perform when the comparison function returns true but the depth test fails. Default is KeepStencilOp. See the stencil operations constants for all possible values.

.stencilZPass : Integer

Which stencil operation to perform when the comparison function returns true and the depth test passes. Default is KeepStencilOp. See the stencil operations constants for all possible values.

.id : Integer

Unique number for this material instance.

.name : String

Optional name of the object (doesn't need to be unique). Default is an empty string.

.needsUpdate : Boolean

Specifies that the material needs to be recompiled.

.opacity : Float

Float in the range of 0.0 - 1.0 indicating how transparent the material is. A value of 0.0 indicates fully transparent, 1.0 is fully opaque.
If the material's transparent property is not set to true, the material will remain fully opaque and this value will only affect its color.
Default is 1.0.

.polygonOffset : Boolean

Whether to use polygon offset. Default is false. This corresponds to the GL_POLYGON_OFFSET_FILL WebGL feature.

.polygonOffsetFactor : Integer

Sets the polygon offset factor. Default is 0.

.polygonOffsetUnits : Integer

Sets the polygon offset units. Default is 0.

.precision : String

Override the renderer's default precision for this material. Can be "highp", "mediump" or "lowp". Default is null.

.premultipliedAlpha : Boolean

Whether to premultiply the alpha (transparency) value. See WebGL / Materials / Physical / Transmission for an example of the difference. Default is false.

.dithering : Boolean

Whether to apply dithering to the color to remove the appearance of banding. Default is false.

.shadowSide : Integer

Defines which side of faces cast shadows. When set, can be THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide. Default is null.
If null, the side casting shadows is determined as follows:

Material.side Side casting shadows
THREE.FrontSide back side
THREE.BackSide front side
THREE.DoubleSide both sides

.side : Integer

Defines which side of faces will be rendered - front, back or both. Default is THREE.FrontSide. Other options are THREE.BackSide or THREE.DoubleSide.

.toneMapped : Boolean

Defines whether this material is tone mapped according to the renderer's toneMapping setting. It is ignored when rendering to a render target or using post processing. Default is true.

.transparent : Boolean

Defines whether this material is transparent. This has an effect on rendering as transparent objects need special treatment and are rendered after non-transparent objects.
When set to true, the extent to which the material is transparent is controlled by setting its opacity property. Default is false.

.type : String

Value is the string 'Material'. This shouldn't be changed, and can be used to find all objects of this type in a scene.

.uuid : String

UUID of this material instance. This gets automatically assigned, so this shouldn't be edited.

.version : Integer

This starts at 0 and counts how many times .needsUpdate is set to true.

.vertexColors : Boolean

Defines whether vertex coloring is used. Default is false. The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or four (RGBA) component color buffer attribute is used.

.visible : Boolean

Defines whether this material is visible. Default is true.

.userData : Object

An object that can be used to store custom data about the Material. It should not hold references to functions as these will not be cloned. Default is an empty object {}.

Methods

EventDispatcher methods are available on this class.

.clone ( ) : Material

Return a new material with the same parameters as this material.

.copy ( material : material ) : this

Copy the parameters from the passed material into this material.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Material textures must be disposed of by the dispose() method of Texture.

.onBeforeCompile ( shader : Shader, renderer : WebGLRenderer ) : undefined

An optional callback that is executed immediately before the shader program is compiled. This function is called with the shader source code as a parameter. Useful for the modification of built-in materials.

Unlike properties, the callback is not supported by .clone(), .copy() and .toJSON().

This callback is only supported in WebGLRenderer (not WebGPURenderer).

.onBeforeRender ( renderer : WebGLRenderer, scene : Scene, camera : Camera, geometry : BufferGeometry, object : Object3D, group : Group ) : undefined

An optional callback that is executed immediately before the material is used to render a 3D object.

Unlike properties, the callback is not supported by .clone(), .copy() and .toJSON().

This callback is only supported in WebGLRenderer (not WebGPURenderer).

.customProgramCacheKey () : String

In case onBeforeCompile is used, this callback can be used to identify values of settings used in onBeforeCompile, so three.js can reuse a cached shader or recompile the shader for this material as needed.

For example, if onBeforeCompile contains a conditional statement like:
if ( black ) { shader.fragmentShader = shader.fragmentShader.replace('gl_FragColor = vec4(1)', 'gl_FragColor = vec4(0)') } then customProgramCacheKey should be set like this:
material.customProgramCacheKey = function() { return black ? '1' : '0'; }

Unlike properties, the callback is not supported by .clone(), .copy() and .toJSON().

.setValues ( values : Object ) : undefined

values -- a container with parameters.
Sets the properties based on the values.

.toJSON ( meta : Object ) : Object

meta -- object containing metadata such as textures or images for the material.
Convert the material to three.js JSON Object/Scene format.

Source

src/materials/Material.js

Material

MeshBasicMaterial

A material for drawing geometries in a simple shaded (flat or wireframe) way.

This material is not affected by lights.

Constructor

MeshBasicMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.aoMap : Texture

The red channel of this texture is used as the ambient occlusion map. Default is null. The aoMap requires a second set of UVs.

.aoMapIntensity : Float

Intensity of the ambient occlusion effect. Range is 0-1, where 0 disables ambient occlusion. Where intensity is 1 and the .aoMap red channel is also 1, ambient light is fully occluded on a surface. Default is 1.

.color : Color

Color of the material, by default set to white (0xffffff).

.combine : Integer

How to combine the result of the surface's color with the environment map, if any.

Options are THREE.MultiplyOperation (default), THREE.MixOperation, THREE.AddOperation. If mix is chosen, the .reflectivity is used to blend between the two colors.

.envMap : Texture

The environment map. Default is null.

.envMapRotation : Euler

The rotation of the environment map in radians. Default is (0,0,0).

.fog : Boolean

Whether the material is affected by fog. Default is true.

.lightMap : Texture

The light map. Default is null. The lightMap requires a second set of UVs.

.lightMapIntensity : Float

Intensity of the baked light. Default is 1.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null.

.reflectivity : Float

How much the environment map affects the surface; also see .combine. The default value is 1 and the valid range is between 0 (no reflections) and 1 (full reflections).

.refractionRatio : Float

The index of refraction (IOR) of air (approximately 1) divided by the index of refraction of the material. It is used with environment mapping modes THREE.CubeRefractionMapping and THREE.EquirectangularRefractionMapping. The refraction ratio should not exceed 1. Default is 0.98.

.specularMap : Texture

Specular map used by the material. Default is null.

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as flat polygons).

.wireframeLinecap : String

Define appearance of line ends. Possible values are "butt", "round" and "square". Default is 'round'.

This corresponds to the 2D Canvas lineCap property and it is ignored by the WebGL renderer.

.wireframeLinejoin : String

Define appearance of line joints. Possible values are "round", "bevel" and "miter". Default is 'round'.

This corresponds to the 2D Canvas lineJoin property and it is ignored by the WebGL renderer.

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshBasicMaterial.js

Material

MeshDepthMaterial

A material for drawing geometry by depth. Depth is based off of the camera near and far plane. White is nearest, black is farthest.

Constructor

MeshDepthMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.depthPacking : Constant

Type for depth packing. Default is BasicDepthPacking.

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.fog : Boolean

Whether the material is affected by fog. Default is false.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null.

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as smooth shaded).

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshDepthMaterial.js

Material

MeshDistanceMaterial

MeshDistanceMaterial is internally used for implementing shadow mapping with PointLights.

Can also be used to customize the shadow casting of an object by assigning an instance of MeshDistanceMaterial to Object3D.customDistanceMaterial. The following examples demonstrates this approach in order to ensure transparent parts of objects do no cast shadows.

Examples

WebGL / shadowmap / pointlight

Constructor

MeshDistanceMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.fog : Boolean

Whether the material is affected by fog. Default is false.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null.

Methods

See the base Material class for common methods.

Source

src/materials/MeshDistanceMaterial.js

Material

MeshLambertMaterial

A material for non-shiny surfaces, without specular highlights.

The material uses a non-physically based Lambertian model for calculating reflectance. This can simulate some surfaces (such as untreated wood or stone) well, but cannot simulate shiny surfaces with specular highlights (such as varnished wood). MeshLambertMaterial uses per-fragment shading.

Due to the simplicity of the reflectance and illumination models, performance will be greater when using this material over the MeshPhongMaterial, MeshStandardMaterial or MeshPhysicalMaterial, at the cost of some graphical accuracy.

Constructor

MeshLambertMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.aoMap : Texture

The red channel of this texture is used as the ambient occlusion map. Default is null. The aoMap requires a second set of UVs.

.aoMapIntensity : Float

Intensity of the ambient occlusion effect. Range is 0-1, where 0 disables ambient occlusion. Where intensity is 1 and the .aoMap red channel is also 1, ambient light is fully occluded on a surface. Default is 1.

.bumpMap : Texture

The texture to create a bump map. The black and white values map to the perceived depth in relation to the lights. Bump doesn't actually affect the geometry of the object, only the lighting. If a normal map is defined this will be ignored.

.bumpScale : Float

How much the bump map affects the material. Typical ranges are 0-1. Default is 1.

.color : Color

Color of the material, by default set to white (0xffffff).

.combine : Integer

How to combine the result of the surface's color with the environment map, if any.

Options are THREE.MultiplyOperation (default), THREE.MixOperation, THREE.AddOperation. If mix is chosen, the .reflectivity is used to blend between the two colors.

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.emissive : Color

Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.

.emissiveMap : Texture

Set emissive (glow) map. Default is null. The emissive map color is modulated by the emissive color and the emissive intensity. If you have an emissive map, be sure to set the emissive color to something other than black.

.emissiveIntensity : Float

Intensity of the emissive light. Modulates the emissive color. Default is 1.

.envMap : Texture

The environment map. Default is null.

.envMapRotation : Euler

The rotation of the environment map in radians. Default is (0,0,0).

.flatShading : Boolean

Define whether the material is rendered with flat shading. Default is false.

.fog : Boolean

Whether the material is affected by fog. Default is true.

.lightMap : Texture

The light map. Default is null. The lightMap requires a second set of UVs.

.lightMapIntensity : Float

Intensity of the baked light. Default is 1.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null.

.normalMap : Texture

The texture to create a normal map. The RGB values affect the surface normal for each pixel fragment and change the way the color is lit. Normal maps do not change the actual shape of the surface, only the lighting. In case the material has a normal map authored using the left handed convention, the y component of normalScale should be negated to compensate for the different handedness.

.normalMapType : Integer

The type of normal map.

Options are THREE.TangentSpaceNormalMap (default), and THREE.ObjectSpaceNormalMap.

.normalScale : Vector2

How much the normal map affects the material. Typical ranges are 0-1. Default is a Vector2 set to (1,1).

.reflectivity : Float

How much the environment map affects the surface; also see .combine.

.refractionRatio : Float

The index of refraction (IOR) of air (approximately 1) divided by the index of refraction of the material. It is used with environment mapping modes THREE.CubeRefractionMapping and THREE.EquirectangularRefractionMapping. The refraction ratio should not exceed 1. Default is 0.98.

.specularMap : Texture

Specular map used by the material. Default is null.

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as flat polygons).

.wireframeLinecap : String

Define appearance of line ends. Possible values are "butt", "round" and "square". Default is 'round'.

This corresponds to the 2D Canvas lineCap property and it is ignored by the WebGL renderer.

.wireframeLinejoin : String

Define appearance of line joints. Possible values are "round", "bevel" and "miter". Default is 'round'.

This corresponds to the 2D Canvas lineJoin property and it is ignored by the WebGL renderer.

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshLambertMaterial.js

Material

MeshMatcapMaterial

MeshMatcapMaterial is defined by a MatCap (or Lit Sphere) texture, which encodes the material color and shading.

MeshMatcapMaterial does not respond to lights since the matcap image file encodes baked lighting. It will cast a shadow onto an object that receives shadows (and shadow clipping works), but it will not self-shadow or receive shadows.

Constructor

MeshMatcapMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.bumpMap : Texture

The texture to create a bump map. The black and white values map to the perceived depth in relation to the lights. Bump doesn't actually affect the geometry of the object, only the lighting. If a normal map is defined this will be ignored.

.bumpScale : Float

How much the bump map affects the material. Typical ranges are 0-1. Default is 1.

.color : Color

Color of the material, by default set to white (0xffffff).

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.flatShading : Boolean

Define whether the material is rendered with flat shading. Default is false.

.fog : Boolean

Whether the material is affected by fog. Default is true.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null. The texture map color is modulated by the diffuse .color.

.matcap : Texture

The matcap map. Default is null.

.normalMap : Texture

The texture to create a normal map. The RGB values affect the surface normal for each pixel fragment and change the way the color is lit. Normal maps do not change the actual shape of the surface, only the lighting. In case the material has a normal map authored using the left handed convention, the y component of normalScale should be negated to compensate for the different handedness.

.normalMapType : Integer

The type of normal map.

Options are THREE.TangentSpaceNormalMap (default), and THREE.ObjectSpaceNormalMap.

.normalScale : Vector2

How much the normal map affects the material. Typical ranges are 0-1. Default is a Vector2 set to (1,1).

Methods

See the base Material class for common methods.

Source

src/materials/MeshMatcapMaterial.js

Material

MeshNormalMaterial

A material that maps the normal vectors to RGB colors.

Constructor

MeshNormalMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

Properties

See the base Material class for common properties.

.bumpMap : Texture

The texture to create a bump map. The black and white values map to the perceived depth in relation to the lights. Bump doesn't actually affect the geometry of the object, only the lighting. If a normal map is defined this will be ignored.

.bumpScale : Float

How much the bump map affects the material. Typical ranges are 0-1. Default is 1.

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.flatShading : Boolean

Define whether the material is rendered with flat shading. Default is false.

.fog : Boolean

Whether the material is affected by fog. Default is false.

.normalMap : Texture

The texture to create a normal map. The RGB values affect the surface normal for each pixel fragment and change the way the color is lit. Normal maps do not change the actual shape of the surface, only the lighting. In case the material has a normal map authored using the left handed convention, the y component of normalScale should be negated to compensate for the different handedness.

.normalMapType : Integer

The type of normal map.

Options are THREE.TangentSpaceNormalMap (default), and THREE.ObjectSpaceNormalMap.

.normalScale : Vector2

How much the normal map affects the material. Typical ranges are 0-1. Default is a Vector2 set to (1,1).

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as smooth shaded).

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshNormalMaterial.js

Material

MeshPhongMaterial

A material for shiny surfaces with specular highlights.

The material uses a non-physically based Blinn-Phong model for calculating reflectance. Unlike the Lambertian model used in the MeshLambertMaterial this can simulate shiny surfaces with specular highlights (such as varnished wood). MeshPhongMaterial uses per-fragment shading.

Performance will generally be greater when using this material over the MeshStandardMaterial or MeshPhysicalMaterial, at the cost of some graphical accuracy.

Constructor

MeshPhongMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.aoMap : Texture

The red channel of this texture is used as the ambient occlusion map. Default is null. The aoMap requires a second set of UVs.

.aoMapIntensity : Float

Intensity of the ambient occlusion effect. Range is 0-1, where 0 disables ambient occlusion. Where intensity is 1 and the .aoMap red channel is also 1, ambient light is fully occluded on a surface. Default is 1.

.bumpMap : Texture

The texture to create a bump map. The black and white values map to the perceived depth in relation to the lights. Bump doesn't actually affect the geometry of the object, only the lighting. If a normal map is defined this will be ignored.

.bumpScale : Float

How much the bump map affects the material. Typical ranges are 0-1. Default is 1.

.color : Color

Color of the material, by default set to white (0xffffff).

.combine : Integer

How to combine the result of the surface's color with the environment map, if any.

Options are THREE.MultiplyOperation (default), THREE.MixOperation, THREE.AddOperation. If mix is chosen, the .reflectivity is used to blend between the two colors.

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.emissive : Color

Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.

.emissiveMap : Texture

Set emissive (glow) map. Default is null. The emissive map color is modulated by the emissive color and the emissive intensity. If you have an emissive map, be sure to set the emissive color to something other than black.

.emissiveIntensity : Float

Intensity of the emissive light. Modulates the emissive color. Default is 1.

.envMap : Texture

The environment map. Default is null.

.envMapRotation : Euler

The rotation of the environment map in radians. Default is (0,0,0).

.flatShading : Boolean

Define whether the material is rendered with flat shading. Default is false.

.fog : Boolean

Whether the material is affected by fog. Default is true.

.lightMap : Texture

The light map. Default is null. The lightMap requires a second set of UVs.

.lightMapIntensity : Float

Intensity of the baked light. Default is 1.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null. The texture map color is modulated by the diffuse .color.

.normalMap : Texture

The texture to create a normal map. The RGB values affect the surface normal for each pixel fragment and change the way the color is lit. Normal maps do not change the actual shape of the surface, only the lighting. In case the material has a normal map authored using the left handed convention, the y component of normalScale should be negated to compensate for the different handedness.

.normalMapType : Integer

The type of normal map.

Options are THREE.TangentSpaceNormalMap (default), and THREE.ObjectSpaceNormalMap.

.normalScale : Vector2

How much the normal map affects the material. Typical ranges are 0-1. Default is a Vector2 set to (1,1).

.reflectivity : Float

How much the environment map affects the surface; also see .combine. The default value is 1 and the valid range is between 0 (no reflections) and 1 (full reflections).

.refractionRatio : Float

The index of refraction (IOR) of air (approximately 1) divided by the index of refraction of the material. It is used with environment mapping modes THREE.CubeRefractionMapping and THREE.EquirectangularRefractionMapping. The refraction ratio should not exceed 1. Default is 0.98.

.shininess : Float

How shiny the .specular highlight is; a higher value gives a sharper highlight. Default is 30.

.specular : Color

Specular color of the material. Default is a Color set to 0x111111 (very dark grey).

This defines how shiny the material is and the color of its shine.

.specularMap : Texture

The specular map value affects both how much the specular surface highlight contributes and how much of the environment map affects the surface. Default is null.

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as flat polygons).

.wireframeLinecap : String

Define appearance of line ends. Possible values are "butt", "round" and "square". Default is 'round'.

This corresponds to the 2D Canvas lineCap property and it is ignored by the WebGL renderer.

.wireframeLinejoin : String

Define appearance of line joints. Possible values are "round", "bevel" and "miter". Default is 'round'.

This corresponds to the 2D Canvas lineJoin property and it is ignored by the WebGL renderer.

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshPhongMaterial.js

MaterialMeshStandardMaterial

MeshPhysicalMaterial

An extension of the MeshStandardMaterial, providing more advanced physically-based rendering properties:

As a result of these complex shading features, MeshPhysicalMaterial has a higher performance cost, per pixel, than other three.js materials. Most effects are disabled by default, and add cost as they are enabled. For best results, always specify an environment map when using this material.

Examples

loader / gltf / anisotropy
materials / physical / clearcoat
loader / gltf / iridescence
loader / gltf / sheen
materials / physical / transmission

Constructor

MeshPhysicalMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material and MeshStandardMaterial) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material and MeshStandardMaterial classes for common properties.

.anisotropy : Float

The anisotropy strength. Default is 0.0.

.anisotropyMap : Texture

Red and green channels represent the anisotropy direction in [-1, 1] tangent, bitangent space, to be rotated by .anisotropyRotation. The blue channel contains strength as [0, 1] to be multiplied by .anisotropy. Default is null.

.anisotropyRotation : Float

The rotation of the anisotropy in tangent, bitangent space, measured in radians counter-clockwise from the tangent. When .anisotropyMap is present, this property provides additional rotation to the vectors in the texture. Default is 0.0.

.attenuationColor : Color

The color that white light turns into due to absorption when reaching the attenuation distance. Default is white (0xffffff).

.attenuationDistance : Float

Density of the medium given as the average distance that light travels in the medium before interacting with a particle. The value is given in world space units, and must be greater than zero. Default is Infinity.

.clearcoat : Float

Represents the intensity of the clear coat layer, from 0.0 to 1.0. Use clear coat related properties to enable multilayer materials that have a thin translucent layer over the base layer. Default is 0.0.

.clearcoatMap : Texture

The red channel of this texture is multiplied against .clearcoat, for per-pixel control over a coating's intensity. Default is null.

.clearcoatNormalMap : Texture

Can be used to enable independent normals for the clear coat layer. Default is null.

.clearcoatNormalScale : Vector2

How much .clearcoatNormalMap affects the clear coat layer, from (0,0) to (1,1). Default is (1,1).

.clearcoatRoughness : Float

Roughness of the clear coat layer, from 0.0 to 1.0. Default is 0.0.

.clearcoatRoughnessMap : Texture

The green channel of this texture is multiplied against .clearcoatRoughness, for per-pixel control over a coating's roughness. Default is null.

.defines : Object

An object of the form: { 'STANDARD': '', 'PHYSICAL': '', }; This is used by the WebGLRenderer for selecting shaders.

.dispersion : Float

Defines the strength of the angular separation of colors (chromatic aberration) transmitting through a relatively clear volume. Any value zero or larger is valid, the typical range of realistic values is [0, 1]. Default is 0 (no dispersion). This property can be only be used with transmissive objects, see .transmission.

.ior : Float

Index-of-refraction for non-metallic materials, from 1.0 to 2.333. Default is 1.5.

.reflectivity : Float

Degree of reflectivity, from 0.0 to 1.0. Default is 0.5, which corresponds to an index-of-refraction of 1.5.
This models the reflectivity of non-metallic materials. It has no effect when metalness is 1.0

.iridescence : Float

The intensity of the iridescence layer, simulating RGB color shift based on the angle between the surface and the viewer, from 0.0 to 1.0. Default is 0.0.

.iridescenceMap : Texture

The red channel of this texture is multiplied against .iridescence, for per-pixel control over iridescence. Default is null.

.iridescenceIOR : Float

Strength of the iridescence RGB color shift effect, represented by an index-of-refraction. Between 1.0 to 2.333. Default is 1.3.

.iridescenceThicknessRange : Array

Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer. Thickness of iridescence layer has an equivalent effect of the one .thickness has on .ior. Default is [100, 400].
If .iridescenceThicknessMap is not defined, iridescence thickness will use only the second element of the given array.

.iridescenceThicknessMap : Texture

A texture that defines the thickness of the iridescence layer, stored in the green channel. Minimum and maximum values of thickness are defined by .iridescenceThicknessRange array:

null

.sheen : Float

The intensity of the sheen layer, from 0.0 to 1.0. Default is 0.0.

.sheenRoughness : Float

Roughness of the sheen layer, from 0.0 to 1.0. Default is 1.0.

.sheenRoughnessMap : Texture

The alpha channel of this texture is multiplied against .sheenRoughness, for per-pixel control over sheen roughness. Default is null.

.sheenColor : Color

The sheen tint. Default is 0x000000, black.

.sheenColorMap : Texture

The RGB channels of this texture are multiplied against .sheenColor, for per-pixel control over sheen tint. Default is null.

.specularIntensity : Float

A float that scales the amount of specular reflection for non-metals only. When set to zero, the model is effectively Lambertian. From 0.0 to 1.0. Default is 1.0.

.specularIntensityMap : Texture

The alpha channel of this texture is multiplied against .specularIntensity, for per-pixel control over specular intensity. Default is null.

.specularColor : Color

A Color that tints the specular reflection at normal incidence for non-metals only. Default is 0xffffff, white.

.specularColorMap : Texture

The RGB channels of this texture are multiplied against .specularColor, for per-pixel control over specular color. Default is null.

.thickness : Float

The thickness of the volume beneath the surface. The value is given in the coordinate space of the mesh. If the value is 0 the material is thin-walled. Otherwise the material is a volume boundary. Default is 0.

.thicknessMap : Texture

A texture that defines the thickness, stored in the green channel. This will be multiplied by .thickness. Default is null.

.transmission : Float

Degree of transmission (or optical transparency), from 0.0 to 1.0. Default is 0.0.
Thin, transparent or semitransparent, plastic or glass materials remain largely reflective even if they are fully transmissive. The transmission property can be used to model these materials.
When transmission is non-zero, opacity should be set to 1.

.transmissionMap : Texture

The red channel of this texture is multiplied against .transmission, for per-pixel control over optical transparency. Default is null.

Methods

See the base Material and MeshStandardMaterial classes for common methods.

Source

src/materials/MeshPhysicalMaterial.js

Material

MeshStandardMaterial

A standard physically based material, using Metallic-Roughness workflow.

Physically based rendering (PBR) has recently become the standard in many 3D applications, such as Unity, Unreal and 3D Studio Max.

This approach differs from older approaches in that instead of using approximations for the way in which light interacts with a surface, a physically correct model is used. The idea is that, instead of tweaking materials to look good under specific lighting, a material can be created that will react 'correctly' under all lighting scenarios.

In practice this gives a more accurate and realistic looking result than the MeshLambertMaterial or MeshPhongMaterial, at the cost of being somewhat more computationally expensive. MeshStandardMaterial uses per-fragment shading.

Note that for best results you should always specify an environment map when using this material.

For a non-technical introduction to the concept of PBR and how to set up a PBR material, check out these articles by the people at marmoset:

Technical details of the approach used in three.js (and most other PBR systems) can be found is this paper from Disney (pdf), by Brent Burley.

Constructor

MeshStandardMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.aoMap : Texture

The red channel of this texture is used as the ambient occlusion map. Default is null. The aoMap requires a second set of UVs.

.aoMapIntensity : Float

Intensity of the ambient occlusion effect. Range is 0-1, where 0 disables ambient occlusion. Where intensity is 1 and the .aoMap red channel is also 1, ambient light is fully occluded on a surface. Default is 1.

.bumpMap : Texture

The texture to create a bump map. The black and white values map to the perceived depth in relation to the lights. Bump doesn't actually affect the geometry of the object, only the lighting. If a normal map is defined this will be ignored.

.bumpScale : Float

How much the bump map affects the material. Typical ranges are 0-1. Default is 1.

.color : Color

Color of the material, by default set to white (0xffffff).

.defines : Object

An object of the form: { 'STANDARD': '' }; This is used by the WebGLRenderer for selecting shaders.

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.emissive : Color

Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.

.emissiveMap : Texture

Set emissive (glow) map. Default is null. The emissive map color is modulated by the emissive color and the emissive intensity. If you have an emissive map, be sure to set the emissive color to something other than black.

.emissiveIntensity : Float

Intensity of the emissive light. Modulates the emissive color. Default is 1.

.envMap : Texture

The environment map. To ensure a physically correct rendering, you should only add environment maps which were preprocessed by PMREMGenerator. Default is null.

.envMapRotation : Euler

The rotation of the environment map in radians. Default is (0,0,0).

.envMapIntensity : Float

Scales the effect of the environment map by multiplying its color.

.flatShading : Boolean

Define whether the material is rendered with flat shading. Default is false.

.fog : Boolean

Whether the material is affected by fog. Default is true.

.isMeshStandardMaterial : Boolean

Read-only flag to check if a given object is of type MeshStandardMaterial.

.lightMap : Texture

The light map. Default is null. The lightMap requires a second set of UVs.

.lightMapIntensity : Float

Intensity of the baked light. Default is 1.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null. The texture map color is modulated by the diffuse .color.

.metalness : Float

How much the material is like a metal. Non-metallic materials such as wood or stone use 0.0, metallic use 1.0, with nothing (usually) in between. Default is 0.0. A value between 0.0 and 1.0 could be used for a rusty metal look. If metalnessMap is also provided, both values are multiplied.

.metalnessMap : Texture

The blue channel of this texture is used to alter the metalness of the material.

.normalMap : Texture

The texture to create a normal map. The RGB values affect the surface normal for each pixel fragment and change the way the color is lit. Normal maps do not change the actual shape of the surface, only the lighting. In case the material has a normal map authored using the left handed convention, the y component of normalScale should be negated to compensate for the different handedness.

.normalMapType : Integer

The type of normal map.

Options are THREE.TangentSpaceNormalMap (default), and THREE.ObjectSpaceNormalMap.

.normalScale : Vector2

How much the normal map affects the material. Typical ranges are 0-1. Default is a Vector2 set to (1,1).

.roughness : Float

How rough the material appears. 0.0 means a smooth mirror reflection, 1.0 means fully diffuse. Default is 1.0. If roughnessMap is also provided, both values are multiplied.

.roughnessMap : Texture

The green channel of this texture is used to alter the roughness of the material.

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as flat polygons).

.wireframeLinecap : String

Define appearance of line ends. Possible values are "butt", "round" and "square". Default is 'round'.

This corresponds to the 2D Canvas lineCap property and it is ignored by the WebGL renderer.

.wireframeLinejoin : String

Define appearance of line joints. Possible values are "round", "bevel" and "miter". Default is 'round'.

This corresponds to the 2D Canvas lineJoin property and it is ignored by the WebGL renderer.

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshStandardMaterial.js

Material

MeshToonMaterial

A material implementing toon shading.

Examples

materials / toon

Constructor

MeshToonMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.aoMap : Texture

The red channel of this texture is used as the ambient occlusion map. Default is null. The aoMap requires a second set of UVs.

.aoMapIntensity : Float

Intensity of the ambient occlusion effect. Range is 0-1, where 0 disables ambient occlusion. Where intensity is 1 and the .aoMap red channel is also 1, ambient light is fully occluded on a surface. Default is 1.

.bumpMap : Texture

The texture to create a bump map. The black and white values map to the perceived depth in relation to the lights. Bump doesn't actually affect the geometry of the object, only the lighting. If a normal map is defined this will be ignored.

.bumpScale : Float

How much the bump map affects the material. Typical ranges are 0-1. Default is 1.

.color : Color

Color of the material, by default set to white (0xffffff).

.displacementMap : Texture

The displacement map affects the position of the mesh's vertices. Unlike other maps which only affect the light and shade of the material the displaced vertices can cast shadows, block other objects, and otherwise act as real geometry. The displacement texture is an image where the value of each pixel (white being the highest) is mapped against, and repositions, the vertices of the mesh.

.displacementScale : Float

How much the displacement map affects the mesh (where black is no displacement, and white is maximum displacement). Without a displacement map set, this value is not applied. Default is 1.

.displacementBias : Float

The offset of the displacement map's values on the mesh's vertices. Without a displacement map set, this value is not applied. Default is 0.

.emissive : Color

Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.

.emissiveMap : Texture

Set emissive (glow) map. Default is null. The emissive map color is modulated by the emissive color and the emissive intensity. If you have an emissive map, be sure to set the emissive color to something other than black.

.emissiveIntensity : Float

Intensity of the emissive light. Modulates the emissive color. Default is 1.

.fog : Boolean

Whether the material is affected by fog. Default is true.

.gradientMap : Texture

Gradient map for toon shading. It's required to set Texture.minFilter and Texture.magFilter to THREE.NearestFilter when using this type of texture. Default is null.

.lightMap : Texture

The light map. Default is null. The lightMap requires a second set of UVs.

.lightMapIntensity : Float

Intensity of the baked light. Default is 1.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null. The texture map color is modulated by the diffuse .color.

.normalMap : Texture

The texture to create a normal map. The RGB values affect the surface normal for each pixel fragment and change the way the color is lit. Normal maps do not change the actual shape of the surface, only the lighting. In case the material has a normal map authored using the left handed convention, the y component of normalScale should be negated to compensate for the different handedness.

.normalMapType : Integer

The type of normal map.

Options are THREE.TangentSpaceNormalMap (default), and THREE.ObjectSpaceNormalMap.

.normalScale : Vector2

How much the normal map affects the material. Typical ranges are 0-1. Default is a Vector2 set to (1,1).

.wireframe : Boolean

Render geometry as wireframe. Default is false (i.e. render as flat polygons).

.wireframeLinecap : String

Define appearance of line ends. Possible values are "butt", "round" and "square". Default is 'round'.

This corresponds to the 2D Canvas lineCap property and it is ignored by the WebGL renderer.

.wireframeLinejoin : String

Define appearance of line joints. Possible values are "round", "bevel" and "miter". Default is 'round'.

This corresponds to the 2D Canvas lineJoin property and it is ignored by the WebGL renderer.

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

Source

src/materials/MeshToonMaterial.js

Material

PointsMaterial

The default material used by Points.

Code Example

const vertices = []; for ( let i = 0; i < 10000; i ++ ) { const x = THREE.MathUtils.randFloatSpread( 2000 ); const y = THREE.MathUtils.randFloatSpread( 2000 ); const z = THREE.MathUtils.randFloatSpread( 2000 ); vertices.push( x, y, z ); } const geometry = new THREE.BufferGeometry(); geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) ); const material = new THREE.PointsMaterial( { color: 0x888888 } ); const points = new THREE.Points( geometry, material ); scene.add( points );

Examples

misc / controls / fly
WebGL / BufferGeometry / drawrange
WebGL / BufferGeometry / points
WebGL / BufferGeometry / points / interleaved
WebGL / camera
WebGL / geometry / convex
WebGL / geometry / shapes
WebGL / interactive / raycasting / points
WebGL / multiple / elements / text
WebGL / points / billboards
WebGL / points / dynamic
WebGL / points / sprites

Constructor

PointsMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.color : Color

Color of the material, by default set to white (0xffffff).

.fog : Boolean

Whether the material is affected by fog. Default is true.

.map : Texture

Sets the color of the points using data from a Texture. May optionally include an alpha channel, typically combined with .transparent or .alphaTest.

.size : Number

Defines the size of the points in pixels. Default is 1.0.
Will be capped if it exceeds the hardware dependent parameter gl.ALIASED_POINT_SIZE_RANGE.

.sizeAttenuation : Boolean

Specify whether points' size is attenuated by the camera depth. (Perspective camera only.) Default is true.

Methods

See the base Material class for common methods.

Source

src/materials/PointsMaterial.js

MaterialShaderMaterial

RawShaderMaterial

This class works just like ShaderMaterial, except that definitions of built-in uniforms and attributes are not automatically prepended to the GLSL shader code.

Code Example

const material = new THREE.RawShaderMaterial( { uniforms: { time: { value: 1.0 } }, vertexShader: document.getElementById( 'vertexShader' ).textContent, fragmentShader: document.getElementById( 'fragmentShader' ).textContent, } );

Examples

WebGL / buffergeometry / rawshader
WebGL / buffergeometry / instancing / billboards
WebGL / buffergeometry / instancing
WebGL / raymarching / reflect
WebGL / volume / cloud
WebGL / volume / instancing
WebGL / volume / perlin

Constructor

RawShaderMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material and ShaderMaterial) can be passed in here.

Properties

See the base Material and ShaderMaterial classes for common properties.

Methods

See the base Material and ShaderMaterial classes for common methods.

Source

src/materials/RawShaderMaterial.js

Material

ShaderMaterial

A material rendered with custom shaders. A shader is a small program written in GLSL that runs on the GPU. You may want to use a custom shader if you need to:

ShaderMaterial

Code Example

const material = new THREE.ShaderMaterial( { uniforms: { time: { value: 1.0 }, resolution: { value: new THREE.Vector2() } }, vertexShader: document.getElementById( 'vertexShader' ).textContent, fragmentShader: document.getElementById( 'fragmentShader' ).textContent } );

Examples

webgl / buffergeometry / custom / attributes / particles
webgl / buffergeometry / selective / draw
webgl / custom / attributes
webgl / custom / attributes / lines
webgl / custom / attributes / points
webgl / custom / attributes / points2
webgl / custom / attributes / points3
webgl / depth / texture
webgl / gpgpu / birds
webgl / gpgpu / protoplanet
webgl / gpgpu / water
webgl / interactive / points
webgl / video / kinect
webgl / lights / hemisphere
webgl / marchingcubes
webgl / materials / envmaps
webgl / materials / wireframe
webgl / modifier / tessellation
webgl / postprocessing / dof2
webgl / postprocessing / godrays

Vertex shaders and fragment shaders

You can specify two different types of shaders for each material:

  • The vertex shader runs first; it receives attributes, calculates / manipulates the position of each individual vertex, and passes additional data (varyings) to the fragment shader.
  • The fragment ( or pixel ) shader runs second; it sets the color of each individual "fragment" (pixel) rendered to the screen.

There are three types of variables in shaders: uniforms, attributes, and varyings:

  • Uniforms are variables that have the same value for all vertices - lighting, fog, and shadow maps are examples of data that would be stored in uniforms. Uniforms can be accessed by both the vertex shader and the fragment shader.
  • Attributes are variables associated with each vertex---for instance, the vertex position, face normal, and vertex color are all examples of data that would be stored in attributes. Attributes can only be accessed within the vertex shader.
  • Varyings are variables that are passed from the vertex shader to the fragment shader. For each fragment, the value of each varying will be smoothly interpolated from the values of adjacent vertices.

Note that within the shader itself, uniforms and attributes act like constants; you can only modify their values by passing different values to the buffers from your JavaScript code.

Built-in attributes and uniforms

The WebGLRenderer provides many attributes and uniforms to shaders by default; definitions of these variables are prepended to your fragmentShader and vertexShader code by the WebGLProgram when the shader is compiled; you don't need to declare them yourself. See WebGLProgram for details of these variables.

Some of these uniforms or attributes (e.g. those pertaining lighting, fog, etc.) require properties to be set on the material in order for WebGLRenderer to copy the appropriate values to the GPU - make sure to set these flags if you want to use these features in your own shader.

If you don't want WebGLProgram to add anything to your shader code, you can use RawShaderMaterial instead of this class.

Custom attributes and uniforms

Both custom attributes and uniforms must be declared in your GLSL shader code (within vertexShader and/or fragmentShader). Custom uniforms must be defined in both the uniforms property of your ShaderMaterial, whereas any custom attributes must be defined via BufferAttribute instances. Note that varyings only need to be declared within the shader code (not within the material).

To declare a custom attribute, please reference the BufferGeometry page for an overview, and the BufferAttribute page for a detailed look at the BufferAttribute API.

When creating your attributes, each typed array that you create to hold your attribute's data must be a multiple of your data type's size. For example, if your attribute is a THREE.Vector3 type, and you have 3000 vertices in your BufferGeometry, your typed array value must be created with a length of 3000 * 3, or 9000 (one value per-component). A table of each data type's size is shown below for reference:

Attribute sizes
GLSL type JavaScript type Size
float Number 1
vec2 THREE.Vector2 2
vec3 THREE.Vector3 3
vec3 THREE.Color 3
vec4 THREE.Vector4 4

Note that attribute buffers are not refreshed automatically when their values change. To update custom attributes, set the needsUpdate flag to true on the BufferAttribute of the geometry (see BufferGeometry for further details).

To declare a custom Uniform, use the uniforms property: uniforms: { time: { value: 1.0 }, resolution: { value: new THREE.Vector2() } }

You're recommended to update custom Uniform values depending on object and camera in Object3D.onBeforeRender because Material can be shared among meshes, matrixWorld of Scene and Camera are updated in WebGLRenderer.render, and some effects render a scene with their own private cameras.

Constructor

ShaderMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

Properties

See the base Material class for common properties.

.clipping : Boolean

Defines whether this material supports clipping; true to let the renderer pass the clippingPlanes uniform. Default is false.

.defaultAttributeValues : Object

When the rendered geometry doesn't include these attributes but the material does, these default values will be passed to the shaders. This avoids errors when buffer data is missing. this.defaultAttributeValues = { 'color': [ 1, 1, 1 ], 'uv': [ 0, 0 ], 'uv1': [ 0, 0 ] };

.defines : Object

Defines custom constants using #define directives within the GLSL code for both the vertex shader and the fragment shader; each key/value pair yields another directive: defines: { FOO: 15, BAR: true } yields the lines #define FOO 15 #define BAR true in the GLSL code.

.extensions : Object

An object with the following properties: this.extensions = { clipCullDistance: false, // set to use vertex shader clipping multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID };

.fog : Boolean

Define whether the material color is affected by global fog settings; true to pass fog uniforms to the shader. Default is false.

.fragmentShader : String

Fragment shader GLSL code. This is the actual code for the shader. In the example above, the vertexShader and fragmentShader code is extracted from the DOM; it could be passed as a string directly or loaded via AJAX instead.

.glslVersion : String

Defines the GLSL version of custom shader code. Valid values are THREE.GLSL1 or THREE.GLSL3. Default is null.

.index0AttributeName : String

If set, this calls gl.bindAttribLocation to bind a generic vertex index to an attribute variable. Default is undefined.

.isShaderMaterial : Boolean

Read-only flag to check if a given object is of type ShaderMaterial.

.lights : Boolean

Defines whether this material uses lighting; true to pass uniform data related to lighting to this shader. Default is false.

.linewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

.flatShading : Boolean

Define whether the material is rendered with flat shading. Default is false.

.uniforms : Object

An object of the form: { "uniform1": { value: 1.0 }, "uniform2": { value: 2 } } specifying the uniforms to be passed to the shader code; keys are uniform names, values are definitions of the form { value: 1.0 } where value is the value of the uniform. Names must match the name of the uniform, as defined in the GLSL code. Note that uniforms are refreshed on every frame, so updating the value of the uniform will immediately update the value available to the GLSL code.

.uniformsNeedUpdate : Boolean

Can be used to force a uniform update while changing uniforms in Object3D.onBeforeRender(). Default is false.

.vertexColors : Boolean

Defines whether vertex coloring is used. Default is false.

.vertexShader : String

Vertex shader GLSL code. This is the actual code for the shader. In the example above, the vertexShader and fragmentShader code is extracted from the DOM; it could be passed as a string directly or loaded via AJAX instead.

.wireframe : Boolean

Render geometry as wireframe (using GL_LINES instead of GL_TRIANGLES). Default is false (i.e. render as flat polygons).

.wireframeLinewidth : Float

Controls wireframe thickness. Default is 1.

Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.

Methods

See the base Material class for common methods.

.clone () : ShaderMaterial

Generates a shallow copy of this material. Note that the vertexShader and fragmentShader are copied by reference, as are the definitions of the attributes; this means that clones of the material will share the same compiled WebGLProgram. However, the uniforms are copied by value, which allows you to have different sets of uniforms for different copies of the material.

Source

src/materials/ShaderMaterial.js

Material

ShadowMaterial

This material can receive shadows, but otherwise is completely transparent.

Code Example

const geometry = new THREE.PlaneGeometry( 2000, 2000 ); geometry.rotateX( - Math.PI / 2 ); const material = new THREE.ShadowMaterial(); material.opacity = 0.2; const plane = new THREE.Mesh( geometry, material ); plane.position.y = -200; plane.receiveShadow = true; scene.add( plane );

Examples

geometry / spline / editor

Constructor

ShadowMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

Properties

See the base Material classes for common properties.

.color : Color

Color of the material, by default set to black (0x000000).

.fog : Boolean

Whether the material is affected by fog. Default is true.

.transparent : Boolean

Defines whether this material is transparent. Default is true.

Methods

See the base Material classes for common methods.

Source

src/materials/ShadowMaterial.js

Material

SpriteMaterial

A material for a use with a Sprite.

Code Example

const map = new THREE.TextureLoader().load( 'textures/sprite.png' ); const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } ); const sprite = new THREE.Sprite( material ); sprite.scale.set(200, 200, 1) scene.add( sprite );

Examples

WebGL / raycast / sprite
WebGL / sprites
SVG / sandbox

Constructor

SpriteMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from Material) can be passed in here.

The exception is the property color, which can be passed in as a hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally. SpriteMaterials are not clipped by using Material.clippingPlanes.

Properties

See the base Material class for common properties.

.alphaMap : Texture

The alpha map is a grayscale texture that controls the opacity across the surface (black: fully transparent; white: fully opaque). Default is null.

Only the color of the texture is used, ignoring the alpha channel if one exists. For RGB and RGBA textures, the WebGL renderer will use the green channel when sampling this texture due to the extra bit of precision provided for green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and luminance/alpha textures will also still work as expected.

.color : Color

Color of the material, by default set to white (0xffffff). The .map is multiplied by the color.

.fog : Boolean

Whether the material is affected by fog. Default is true.

.isSpriteMaterial : Boolean

Read-only flag to check if a given object is of type SpriteMaterial.

.map : Texture

The color map. May optionally include an alpha channel, typically combined with .transparent or .alphaTest. Default is null.

.rotation : Radians

The rotation of the sprite in radians. Default is 0.

.sizeAttenuation : Boolean

Whether the size of the sprite is attenuated by the camera depth. (Perspective camera only.) Default is true.

.transparent : Boolean

Defines whether this material is transparent. Default is true.

Methods

See the base Material class for common methods.

Source

src/materials/SpriteMaterial.js

Box2

Represents an axis-aligned bounding box (AABB) in 2D space.

Constructor

Box2( min : Vector2, max : Vector2 )

min - (optional) Vector2 representing the lower (x, y) boundary of the box. Default is ( + Infinity, + Infinity ).
max - (optional) Vector2 representing the upper (x, y) boundary of the box. Default is ( - Infinity, - Infinity ).

Creates a Box2 bounded by min and max.

Properties

.min : Vector2

Vector2 representing the lower (x, y) boundary of the box.
Default is ( + Infinity, + Infinity ).

.max : Vector2

Vector2 representing the lower upper (x, y) boundary of the box.
Default is ( - Infinity, - Infinity ).

Methods

.clampPoint ( point : Vector2, target : Vector2 ) : Vector2

point - Vector2 to clamp.
target — the result will be copied into this Vector2.

Clamps the point within the bounds of this box.

.clone () : Box2

Returns a new Box2 with the same min and max as this one.

.containsBox ( box : Box2 ) : Boolean

box - Box2 to test for inclusion.

Returns true if this box includes the entirety of box. If this and box are identical,
this function also returns true.

.containsPoint ( point : Vector2 ) : Boolean

point - Vector2 to check for inclusion.

Returns true if the specified point lies within or on the boundaries of this box.

.copy ( box : Box2 ) : this

Copies the min and max from box to this box.

.distanceToPoint ( point : Vector2 ) : Float

point - Vector2 to measure distance to.

Returns the distance from any edge of this box to the specified point. If the point lies inside of this box, the distance will be 0.

.equals ( box : Box2 ) : Boolean

box - Box to compare with this one.

Returns true if this box and box share the same lower and upper bounds.

.expandByPoint ( point : Vector2 ) : this

point - Vector2 that should be included in the box.

Expands the boundaries of this box to include point.

.expandByScalar ( scalar : Float ) : this

scalar - Distance to expand the box by.

Expands each dimension of the box by scalar. If negative, the dimensions of the box will be contracted.

.expandByVector ( vector : Vector2 ) : this

vector - Vector2 to expand the box by.

Expands this box equilaterally by vector. The width of this box will be expanded by the x component of vector in both directions. The height of this box will be expanded by the y component of vector in both directions.

.getCenter ( target : Vector2 ) : Vector2

target — the result will be copied into this Vector2.

Returns the center point of the box as a Vector2.

.getParameter ( point : Vector2, target : Vector2 ) : Vector2

point - Vector2.
target — the result will be copied into this Vector2.

Returns a point as a proportion of this box's width and height.

.getSize ( target : Vector2 ) : Vector2

target — the result will be copied into this Vector2.

Returns the width and height of this box.

.intersect ( box : Box2 ) : this

box - Box to intersect with.

Returns the intersection of this and box, setting the upper bound of this box to the lesser of the two boxes' upper bounds and the lower bound of this box to the greater of the two boxes' lower bounds.

.intersectsBox ( box : Box2 ) : Boolean

box - Box to check for intersection against.

Determines whether or not this box intersects box.

.isEmpty () : Boolean

Returns true if this box includes zero points within its bounds.
Note that a box with equal lower and upper bounds still includes one point, the one both bounds share.

.makeEmpty () : this

Makes this box empty.

.set ( min : Vector2, max : Vector2 ) : this

min - (required ) Vector2 representing the lower (x, y) boundary of the box.
max - (required) Vector2 representing the upper (x, y) boundary of the box.

Sets the lower and upper (x, y) boundaries of this box.
Please note that this method only copies the values from the given objects.

.setFromCenterAndSize ( center : Vector2, size : Vector2 ) : this

center - Desired center position of the box (Vector2).
size - Desired x and y dimensions of the box (Vector2).

Centers this box on center and sets this box's width and height to the values specified in size.

.setFromPoints ( points : Array ) : this

points - Array of Vector2s that the resulting box will contain.

Sets the upper and lower bounds of this box to include all of the points in points.

.translate ( offset : Vector2 ) : this

offset - Direction and distance of offset.

Adds offset to both the upper and lower bounds of this box, effectively moving this box offset units in 2D space.

.union ( box : Box2 ) : this

box - Box that will be unioned with this box.

Unions this box with box, setting the upper bound of this box to the greater of the two boxes' upper bounds and the lower bound of this box to the lesser of the two boxes' lower bounds.

Source

src/math/Box2.js

Box3

Represents an axis-aligned bounding box (AABB) in 3D space.

Code Example

const box = new THREE.Box3(); const mesh = new THREE.Mesh( new THREE.SphereGeometry(), new THREE.MeshBasicMaterial() ); // ensure the bounding box is computed for its geometry // this should be done only once (assuming static geometries) mesh.geometry.computeBoundingBox(); // ... // in the animation loop, compute the current bounding box with the world matrix box.copy( mesh.geometry.boundingBox ).applyMatrix4( mesh.matrixWorld );

Constructor

Box3( min : Vector3, max : Vector3 )

min - (optional) Vector3 representing the lower (x, y, z) boundary of the box. Default is ( + Infinity, + Infinity, + Infinity ).
max - (optional) Vector3 representing the upper (x, y, z) boundary of the box. Default is ( - Infinity, - Infinity, - Infinity ).

Creates a Box3 bounded by min and max.

Properties

.isBox3 : Boolean

Read-only flag to check if a given object is of type Box3.

.min : Vector3

Vector3 representing the lower (x, y, z) boundary of the box.
Default is ( + Infinity, + Infinity, + Infinity ).

.max : Vector3

Vector3 representing the upper (x, y, z) boundary of the box.
Default is ( - Infinity, - Infinity, - Infinity ).

Methods

.applyMatrix4 ( matrix : Matrix4 ) : this

matrix - The Matrix4 to apply

Transforms this Box3 with the supplied matrix.

.clampPoint ( point : Vector3, target : Vector3 ) : Vector3

point - Vector3 to clamp.
target — the result will be copied into this Vector3.

Clamps the point within the bounds of this box.

.clone () : Box3

Returns a new Box3 with the same min and max as this one.

.containsBox ( box : Box3 ) : Boolean

box - Box3 to test for inclusion.

Returns true if this box includes the entirety of box. If this and box are identical,
this function also returns true.

.containsPoint ( point : Vector3 ) : Boolean

point - Vector3 to check for inclusion.

Returns true if the specified point lies within or on the boundaries of this box.

.copy ( box : Box3 ) : this

box - Box3 to copy.

Copies the min and max from box to this box.

.distanceToPoint ( point : Vector3 ) : Float

point - Vector3 to measure distance to.

Returns the distance from any edge of this box to the specified point. If the point lies inside of this box, the distance will be 0.

.equals ( box : Box3 ) : Boolean

box - Box to compare with this one.

Returns true if this box and box share the same lower and upper bounds.

.expandByObject ( object : Object3D, precise : Boolean ) : this

object - Object3D to expand the box by.
precise - (optional) expand the bounding box as little as necessary at the expense of more computation. Default is false.

Expands the boundaries of this box to include object and its children, accounting for the object's, and children's, world transforms. The function may result in a larger box than strictly necessary (unless the precise parameter is set to true).

.expandByPoint ( point : Vector3 ) : this

point - Vector3 that should be included in the box.

Expands the boundaries of this box to include point.

.expandByScalar ( scalar : Float ) : this

scalar - Distance to expand the box by.

Expands each dimension of the box by scalar. If negative, the dimensions of the box will be contracted.

.expandByVector ( vector : Vector3 ) : this

vector - Vector3 to expand the box by.

Expands this box equilaterally by vector. The width of this box will be expanded by the x component of vector in both directions. The height of this box will be expanded by the y component of vector in both directions. The depth of this box will be expanded by the z component of vector in both directions.

.getBoundingSphere ( target : Sphere ) : Sphere

target — the result will be copied into this Sphere.

Gets a Sphere that bounds the box.

.getCenter ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns the center point of the box as a Vector3.

.getParameter ( point : Vector3, target : Vector3 ) : Vector3

point - Vector3.
target — the result will be copied into this Vector3.

Returns a point as a proportion of this box's width, height and depth.

.getSize ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns the width, height and depth of this box.

.intersect ( box : Box3 ) : this

box - Box to intersect with.

Computes the intersection of this and box, setting the upper bound of this box to the lesser of the two boxes' upper bounds and the lower bound of this box to the greater of the two boxes' lower bounds. If there's no overlap, makes this box empty.

.intersectsBox ( box : Box3 ) : Boolean

box - Box to check for intersection against.

Determines whether or not this box intersects box.

.intersectsPlane ( plane : Plane ) : Boolean

plane - Plane to check for intersection against.

Determines whether or not this box intersects plane.

.intersectsSphere ( sphere : Sphere ) : Boolean

sphere - Sphere to check for intersection against.

Determines whether or not this box intersects sphere.

.intersectsTriangle ( triangle : Triangle ) : Boolean

triangle - Triangle to check for intersection against.

Determines whether or not this box intersects triangle.

.isEmpty () : Boolean

Returns true if this box includes zero points within its bounds.
Note that a box with equal lower and upper bounds still includes one point, the one both bounds share.

.makeEmpty () : this

Makes this box empty.

.set ( min : Vector3, max : Vector3 ) : this

min - Vector3 representing the lower (x, y, z) boundary of the box.
max - Vector3 representing the upper (x, y, z) boundary of the box.

Sets the lower and upper (x, y, z) boundaries of this box.
Please note that this method only copies the values from the given objects.

.setFromArray ( array : Array ) : this

array -- An array of position data that the resulting box will envelop.

Sets the upper and lower bounds of this box to include all of the data in array.

.setFromBufferAttribute ( attribute : BufferAttribute ) : this

attribute - A buffer attribute of position data that the resulting box will envelop.

Sets the upper and lower bounds of this box to include all of the data in attribute.

.setFromCenterAndSize ( center : Vector3, size : Vector3 ) : this

center, - Desired center position of the box.
size - Desired x, y and z dimensions of the box.

Centers this box on center and sets this box's width, height and depth to the values specified
in size

.setFromObject ( object : Object3D, precise : Boolean ) : this

object - Object3D to compute the bounding box of.
precise - (optional) compute the smallest world-axis-aligned bounding box at the expense of more computation. Default is false.

Computes the world-axis-aligned bounding box of an Object3D (including its children), accounting for the object's, and children's, world transforms. The function may result in a larger box than strictly necessary.

.setFromPoints ( points : Array ) : this

points - Array of Vector3s that the resulting box will contain.

Sets the upper and lower bounds of this box to include all of the points in points.

.translate ( offset : Vector3 ) : this

offset - Direction and distance of offset.

Adds offset to both the upper and lower bounds of this box, effectively moving this box offset units in 3D space.

.union ( box : Box3 ) : this

box - Box that will be unioned with this box.

Computes the union of this box and box, setting the upper bound of this box to the greater of the two boxes' upper bounds and the lower bound of this box to the lesser of the two boxes' lower bounds.

Source

src/math/Box3.js

Color

Class representing a color.

A Color instance is represented by RGB components in the linear working color space, which defaults to LinearSRGBColorSpace. Inputs conventionally using SRGBColorSpace (such as hexadecimals and CSS strings) are converted to the working color space automatically.

// converted automatically from SRGBColorSpace to LinearSRGBColorSpace const color = new THREE.Color().setHex( 0x112233 );

Source color spaces may be specified explicitly, to ensure correct conversions.

// assumed already LinearSRGBColorSpace; no conversion const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 ); // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );

If THREE.ColorManagement is disabled, no conversions occur. For details, see Color management.

Iterating through a Color instance will yield its components (r, g, b) in the corresponding order.

Code Examples

A Color can be initialised in any of the following ways:

//empty constructor - will default white const color1 = new THREE.Color(); //Hexadecimal color (recommended) const color2 = new THREE.Color( 0xff0000 ); //RGB string const color3 = new THREE.Color("rgb(255, 0, 0)"); const color4 = new THREE.Color("rgb(100%, 0%, 0%)"); //X11 color name - all 140 color names are supported. //Note the lack of CamelCase in the name const color5 = new THREE.Color( 'skyblue' ); //HSL string const color6 = new THREE.Color("hsl(0, 100%, 50%)"); //Separate RGB values between 0 and 1 const color7 = new THREE.Color( 1, 0, 0 );

Constructor

Color( r : Color_Hex_or_String, g : Float, b : Float )

r - (optional) If arguments g and b are defined, the red component of the color. If they are not defined, it can be a hexadecimal triplet (recommended), a CSS-style string, or another Color instance.
g - (optional) If it is defined, the green component of the color.
b - (optional) If it is defined, the blue component of the color.

Note that standard method of specifying color in three.js is with a hexadecimal triplet, and that method is used throughout the rest of the documentation.

When all arguments are defined then r is the red component, g is the green component and b is the blue component of the color.
When only r is defined:

Properties

.isColor : Boolean

Read-only flag to check if a given object is of type Color.

.r : Float

Red channel value between 0.0 and 1.0. Default is 1.

.g : Float

Green channel value between 0.0 and 1.0. Default is 1.

.b : Float

Blue channel value between 0.0 and 1.0. Default is 1.

Methods

.add ( color : Color ) : this

Adds the RGB values of color to the RGB values of this color.

.addColors ( color1 : Color, color2 : Color ) : this

Sets this color's RGB values to the sum of the RGB values of color1 and color2.

.addScalar ( s : Number ) : this

Adds s to the RGB values of this color.

.applyMatrix3 ( m : Matrix3 ) : this

Applies the transform m to this color's RGB components.

.clone () : Color

Returns a new Color with the same r, g and b values as this one.

.copy ( color : Color ) : this

Copies the r, g and b parameters from color in to this color.

.convertLinearToSRGB () : this

Converts this color from LinearSRGBColorSpace to SRGBColorSpace.

.convertSRGBToLinear () : this

Converts this color from SRGBColorSpace to LinearSRGBColorSpace.

.copyLinearToSRGB ( color : Color ) : this

color — Color to copy.
Copies the given color into this color, and then converts this color from LinearSRGBColorSpace to SRGBColorSpace.

.copySRGBToLinear ( color : Color ) : this

color — Color to copy.
Copies the given color into this color, and then converts this color from SRGBColorSpace to LinearSRGBColorSpace.

.equals ( color : Color ) : Boolean

Compares the RGB values of color with those of this object. Returns true if they are the same, false otherwise.

.fromArray ( array : Array, offset : Integer ) : this

array - Array of floats in the form [ r, g, b ].
offset - An optional offset into the array.

Sets this color's components based on an array formatted like [ r, g, b ].

.fromBufferAttribute ( attribute : BufferAttribute, index : Integer ) : this

attribute - the source attribute.
index - index in the attribute.

Sets this color's components from the attribute.

.getHex ( colorSpace : string = SRGBColorSpace ) : Integer

Returns the hexadecimal value of this color.

.getHexString ( colorSpace : string = SRGBColorSpace ) : String

Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').

.getHSL ( target : Object, colorSpace : string = LinearSRGBColorSpace ) : Object

target — the result will be copied into this Object. Adds h, s and l keys to the object (if not already present).

Convert this Color's r, g and b values to HSL format and returns an object of the form: { h: 0, s: 0, l: 0 }

.getRGB ( target : Color, colorSpace : string = LinearSRGBColorSpace ) : Color

target — the result will be copied into this object.

Returns the RGB values of this color as an instance of Color.

.getStyle ( colorSpace : string = SRGBColorSpace ) : String

Returns the value of this color as a CSS style string. Example: rgb(255,0,0).

.lerp ( color : Color, alpha : Float ) : this

color - color to converge on.
alpha - interpolation factor in the closed interval [0, 1].

Linearly interpolates this color's RGB values toward the RGB values of the passed argument. The alpha argument can be thought of as the ratio between the two colors, where 0.0 is this color and 1.0 is the first argument.

.lerpColors ( color1 : Color, color2 : Color, alpha : Float ) : this

color1 - the starting Color.
color2 - Color to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Sets this color to be the color linearly interpolated between color1 and color2 where alpha is the percent distance along the line connecting the two colors - alpha = 0 will be color1, and alpha = 1 will be color2.

.lerpHSL ( color : Color, alpha : Float ) : this

color - color to converge on.
alpha - interpolation factor in the closed interval [0, 1].

Linearly interpolates this color's HSL values toward the HSL values of the passed argument. It differs from the classic .lerp by not interpolating straight from one color to the other, but instead going through all the hues in between those two colors. The alpha argument can be thought of as the ratio between the two colors, where 0.0 is this color and 1.0 is the first argument.

.multiply ( color : Color ) : this

Multiplies this color's RGB values by the given color's RGB values.

.multiplyScalar ( s : Number ) : this

Multiplies this color's RGB values by s.

.offsetHSL ( h : Float, s : Float, l : Float ) : this

Adds the given h, s, and l to this color's values. Internally, this converts the color's r, g and b values to HSL, adds h, s, and l, and then converts the color back to RGB.

.set ( r : Color_Hex_or_String, g : Float, b : Float ) : this

r - (optional) If arguments g and b are defined, the red component of the color. If they are not defined, it can be a hexadecimal triplet (recommended), a CSS-style string, or another Color instance.
g - (optional) If it is defined, the green component of the color.
b - (optional) If it is defined, the blue component of the color.

See the Constructor above for full details about possible arguments. Delegates to .copy, .setStyle, .setRGB or .setHex depending on input type.

.setFromVector3 ( vector : Vector3 ) : this

Sets this colors's r, g and b components from the x, y, and z components of the specified vector.

.setHex ( hex : Integer, colorSpace : string = SRGBColorSpace ) : this

hexhexadecimal triplet format.

Sets this color from a hexadecimal value.

.setHSL ( h : Float, s : Float, l : Float, colorSpace : string = LinearSRGBColorSpace ) : this

h — hue value between 0.0 and 1.0
s — saturation value between 0.0 and 1.0
l — lightness value between 0.0 and 1.0

Sets color from HSL values.

.setRGB ( r : Float, g : Float, b : Float, colorSpace : string = LinearSRGBColorSpace ) : this

r — Red channel value between 0.0 and 1.0.
g — Green channel value between 0.0 and 1.0.
b — Blue channel value between 0.0 and 1.0.

Sets this color from RGB values.

.setScalar ( scalar : Float ) : this

scalar — a value between 0.0 and 1.0.

Sets all three color components to the value scalar.

.setStyle ( style : String, colorSpace : string = SRGBColorSpace ) : this

style — color as a CSS-style string.

Sets this color from a CSS-style string. For example, "rgb(250, 0,0)", "rgb(100%, 0%, 0%)", "hsl(0, 100%, 50%)", "#ff0000", "#f00", or "red" ( or any X11 color name - all 140 color names are supported ).
Translucent colors such as "rgba(255, 0, 0, 0.5)" and "hsla(0, 100%, 50%, 0.5)" are also accepted, but the alpha-channel coordinate will be discarded.

Note that for X11 color names, multiple words such as Dark Orange become the string 'darkorange'.

.setColorName ( style : String, colorSpace : string = SRGBColorSpace ) : this

style — color name ( from X11 color names ).

Sets this color from a color name. Faster than .setStyle method if you don't need the other CSS-style formats.

For convenience, the list of names is exposed in Color.NAMES as a hash: Color.NAMES.aliceblue // returns 0xF0F8FF

.sub ( color : Color ) : this

Subtracts the RGB components of the given color from the RGB components of this color. If this results in a negative component, that component is set to zero.

.toArray ( array : Array, offset : Integer ) : Array

array - An optional array to store the color to.
offset - An optional offset into the array.

Returns an array of the form [ r, g, b ].

.toJSON () : Number

This methods defines the serialization result of Color. Returns the color as a hexadecimal value.

Source

src/math/Color.js

Cylindrical

A point's cylindrical coordinates.

Constructor

Cylindrical( radius : Float, theta : Float, y : Float )

radius - distance from the origin to a point in the x-z plane. Default is 1.0.
theta - counterclockwise angle in the x-z plane measured in radians from the positive z-axis. Default is 0.
y - height above the x-z plane. Default is 0.

Properties

.radius : Float

.theta : Float

.y : Float

Methods

.clone () : Cylindrical

Returns a new cylindrical with the same radius, theta and y properties as this one.

.copy ( other : Cylindrical ) : this

Copies the values of the passed Cylindrical's radius, theta and y properties to this cylindrical.

.set ( radius : Float, theta : Float, y : Float ) : this

Sets values of this cylindrical's radius, theta and y properties.

.setFromVector3 ( vec3 : Vector3 ) : this

Sets values of this cylindrical's radius, theta and y properties from the Vector3.

.setFromCartesianCoords ( x : Float, y : Float, z : Float ) : this

Sets values of this cylindrical's radius, theta and y properties from Cartesian coordinates.

Source

src/math/Cylindrical.js

Euler

A class representing Euler Angles.

Euler angles describe a rotational transformation by rotating an object on its various axes in specified amounts per axis, and a specified axis order.

Iterating through a Euler instance will yield its components (x, y, z, order) in the corresponding order.

Code Example

const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' ); const b = new THREE.Vector3( 1, 0, 1 ); b.applyEuler(a);

Constructor

Euler( x : Float, y : Float, z : Float, order : String )

x - (optional) the angle of the x axis in radians. Default is 0.
y - (optional) the angle of the y axis in radians. Default is 0.
z - (optional) the angle of the z axis in radians. Default is 0.
order - (optional) a string representing the order that the rotations are applied, defaults to 'XYZ' (must be upper case).

Properties

.isEuler : Boolean

Read-only flag to check if a given object is of type Euler.

.order : String

The order in which to apply rotations. Default is 'XYZ', which means that the object will first be rotated around its X axis, then its Y axis and finally its Z axis. Other possibilities are: 'YZX', 'ZXY', 'XZY', 'YXZ' and 'ZYX'. These must be in upper case.

Three.js uses intrinsic Tait-Bryan angles. This means that rotations are performed with respect to the local coordinate system. That is, for order 'XYZ', the rotation is first around the local-X axis (which is the same as the world-X axis), then around local-Y (which may now be different from the world Y-axis), then local-Z (which may be different from the world Z-axis).

.x : Float

The current value of the x component.

.y : Float

The current value of the y component.

.z : Float

The current value of the z component.

Methods

.copy ( euler : Euler ) : this

Copies value of euler to this euler.

.clone () : Euler

Returns a new Euler with the same parameters as this one.

.equals ( euler : Euler ) : Boolean

Checks for strict equality of this euler and euler.

.fromArray ( array : Array ) : this

array of length 3 or 4. The optional 4th argument corresponds to the order.

Assigns this euler's x angle to array[0].
Assigns this euler's y angle to array[1].
Assigns this euler's z angle to array[2].
Optionally assigns this euler's order to array[3].

.reorder ( newOrder : String ) : this

Resets the euler angle with a new order by creating a quaternion from this euler angle and then setting this euler angle with the quaternion and the new order.

Warning: this discards revolution information.

.set ( x : Float, y : Float, z : Float, order : String ) : this

x - the angle of the x axis in radians.
y - the angle of the y axis in radians.
z - the angle of the z axis in radians.
order - (optional) a string representing the order that the rotations are applied.

Sets the angles of this euler transform and optionally the order.

.setFromRotationMatrix ( m : Matrix4, order : String ) : this

m - a Matrix4 of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
order - (optional) a string representing the order that the rotations are applied.
Sets the angles of this euler transform from a pure rotation matrix based on the orientation specified by order.

.setFromQuaternion ( q : Quaternion, order : String ) : this

q - a normalized quaternion.
order - (optional) a string representing the order that the rotations are applied.
Sets the angles of this euler transform from a normalized quaternion based on the orientation specified by order.

.setFromVector3 ( vector : Vector3, order : String ) : this

vector - Vector3.
order - (optional) a string representing the order that the rotations are applied.

Set the x, y and z, and optionally update the order.

.toArray ( array : Array, offset : Integer ) : Array

array - (optional) array to store the euler in.
offset (optional) offset in the array.
Returns an array of the form [x, y, z, order ].

Source

src/math/Euler.js

Frustum

Frustums are used to determine what is inside the camera's field of view. They help speed up the rendering process - objects which lie outside a camera's frustum can safely be excluded from rendering.

This class is mainly intended for use internally by a renderer for calculating a camera or shadowCamera's frustum.

Constructor

Frustum(p0 : Plane, p1 : Plane, p2 : Plane, p3 : Plane, p4 : Plane, p5 : Plane)

p0 - (optional) defaults to a new Plane.
p1 - (optional) defaults to a new Plane.
p2 - (optional) defaults to a new Plane.
p3 - (optional) defaults to a new Plane.
p4 - (optional) defaults to a new Plane.
p5 - (optional) defaults to a new Plane.

Creates a new Frustum.

Properties

.planes : Array

Array of 6 planes.

Methods

.clone () : Frustum

Return a new Frustum with the same parameters as this one.

.containsPoint ( point : Vector3 ) : Boolean

point - Vector3 to test.

Checks to see if the frustum contains the point.

.copy ( frustum : Frustum ) : this

frustum - The frustum to copy

Copies the properties of the passed frustum into this one.

.intersectsBox ( box : Box3 ) : Boolean

box - Box3 to check for intersection.

Return true if box intersects with this frustum.

.intersectsObject ( object : Object3D ) : Boolean

Checks whether the object's bounding sphere is intersecting the Frustum.

Note that the object must have a geometry so that the bounding sphere can be calculated.

.intersectsSphere ( sphere : Sphere ) : Boolean

sphere - Sphere to check for intersection.

Return true if sphere intersects with this frustum.

.intersectsSprite ( sprite : Sprite ) : Boolean

Checks whether the sprite is intersecting the Frustum.

.set ( p0 : Plane, p1 : Plane, p2 : Plane, p3 : Plane, p4 : Plane, p5 : Plane ) : this

Sets the frustum from the passed planes. No plane order is implied.
Note that this method only copies the values from the given objects.

.setFromProjectionMatrix ( matrix : Matrix4 ) : this

matrix - Projection Matrix4 used to set the planes

Sets the frustum planes from the projection matrix.

Source

src/math/Frustum.js

Interpolant

Abstract base class of interpolants over parametric samples.

The parameter domain is one dimensional, typically the time or a path along a curve defined by the data.

The sample values can have any dimensionality and derived classes may apply special interpretations to the data.

This class provides the interval seek in a Template Method, deferring the actual interpolation to derived classes.

Time complexity is O(1) for linear access crossing at most two points and O(log N) for random access, where N is the number of positions.

References: http://www.oodesign.com/template-method-pattern.html

Constructor

Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer )

parameterPositions -- array of positions
sampleValues -- array of samples
sampleSize -- number of samples
resultBuffer -- buffer to store the interpolation results.

Note: This is not designed to be called directly.

Properties

.parameterPositions : null

.resultBuffer : null

.sampleValues : null

.settings : Object

Optional, subclass-specific settings structure.

.valueSize : null

Methods

.evaluate ( t : Number ) : Array

Evaluate the interpolant at position t.

Source

src/math/Interpolant.js

Line3

A geometric line segment represented by a start and end point.

Constructor

Line3( start : Vector3, end : Vector3 )

start - Start of the line segment. Default is (0, 0, 0).
end - End of the line segment. Default is (0, 0, 0).

Creates a new Line3.

Properties

.start : Vector3

Vector3 representing the start point of the line.

.end : Vector3

Vector3 representing the end point of the line.

Methods

.applyMatrix4 ( matrix : Matrix4 ) : this

Applies a matrix transform to the line segment.

.at ( t : Float, target : Vector3 ) : Vector3

t - Use values 0-1 to return a position along the line segment.
target — the result will be copied into this Vector3.

Returns a vector at a certain position along the line. When t = 0, it returns the start vector, and when t = 1 it returns the end vector.

.clone () : Line3

Returns a new Line3 with the same start and end vectors as this one.

.closestPointToPoint ( point : Vector3, clampToLine : Boolean, target : Vector3 ) : Vector3

point - return the closest point on the line to this point.
clampToLine - whether to clamp the returned value to the line segment.
target — the result will be copied into this Vector3.

Returns the closets point on the line. If clampToLine is true, then the returned value will be clamped to the line segment.

.closestPointToPointParameter ( point : Vector3, clampToLine : Boolean ) : Float

point - the point for which to return a point parameter.
clampToLine - Whether to clamp the result to the range [0, 1].

Returns a point parameter based on the closest point as projected on the line segment. If clampToLine is true, then the returned value will be between 0 and 1.

.copy ( line : Line3 ) : this

Copies the passed line's start and end vectors to this line.

.delta ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns the delta vector of the line segment ( end vector minus the start vector).

.distance () : Float

Returns the Euclidean distance (straight-line distance) between the line's start and end points.

.distanceSq () : Float

Returns the square of the Euclidean distance (straight-line distance) between the line's start and end vectors.

.equals ( line : Line3 ) : Boolean

line - Line3 to compare with this one.

Returns true if both line's start and end points are equal.

.getCenter ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns the center of the line segment.

.set ( start : Vector3, end : Vector3 ) : this

start - set the start point of the line.
end - set the end point of the line.

Sets the start and end values by copying the provided vectors.

Source

src/math/Line3.js

MathUtils

An object with several math utility functions.

Functions

.clamp ( value : Float, min : Float, max : Float ) : Float

value — Value to be clamped.
min — Minimum value.
max — Maximum value.

Clamps the value to be between min and max.

.degToRad ( degrees : Float ) : Float

Converts degrees to radians.

.euclideanModulo ( n : Integer, m : Integer ) : Integer

n, m - Integers

Computes the Euclidean modulo of m % n, that is: ( ( n % m ) + m ) % m

.generateUUID ( ) : UUID

Generate a UUID (universally unique identifier).

.isPowerOfTwo ( n : Number ) : Boolean

Return true if n is a power of 2.

.inverseLerp ( x : Float, y : Float, value : Float ) : Float

x - Start point.
y - End point.
value - A value between start and end.

Returns the percentage in the closed interval [0, 1] of the given value between the start and end point.

.lerp ( x : Float, y : Float, t : Float ) : Float

x - Start point.
y - End point.
t - interpolation factor in the closed interval [0, 1].

Returns a value linearly interpolated from two known points based on the given interval - t = 0 will return x and t = 1 will return y.

.damp ( x : Float, y : Float, lambda : Float, dt : Float ) : Float

x - Current point.
y - Target point.
lambda - A higher lambda value will make the movement more sudden, and a lower value will make the movement more gradual.
dt - Delta time in seconds.

Smoothly interpolate a number from x toward y in a spring-like manner using the dt to maintain frame rate independent movement. For details, see Frame rate independent damping using lerp.

.mapLinear ( x : Float, a1 : Float, a2 : Float, b1 : Float, b2 : Float ) : Float

x — Value to be mapped.
a1 — Minimum value for range A.
a2 — Maximum value for range A.
b1 — Minimum value for range B.
b2 — Maximum value for range B.

Linear mapping of x from range [a1, a2] to range [b1, b2].

.pingpong ( x : Float, length : Float ) : Float

x — The value to pingpong.
length — The positive value the function will pingpong to. Default is 1.

Returns a value that alternates between 0 and length : Float.

.ceilPowerOfTwo ( n : Number ) : Integer

Returns the smallest power of 2 that is greater than or equal to n.

.floorPowerOfTwo ( n : Number ) : Integer

Returns the largest power of 2 that is less than or equal to n.

.radToDeg ( radians : Float ) : Float

Converts radians to degrees.

.randFloat ( low : Float, high : Float ) : Float

Random float in the interval [low, high].

.randFloatSpread ( range : Float ) : Float

Random float in the interval [- range / 2, range / 2].

.randInt ( low : Integer, high : Integer ) : Integer

Random integer in the interval [low, high].

.seededRandom ( seed : Integer ) : Float

Deterministic pseudo-random float in the interval [0, 1]. The integer seed is optional.

.smoothstep ( x : Float, min : Float, max : Float ) : Float

x - The value to evaluate based on its position between min and max.
min - Any x value below min will be 0.
max - Any x value above max will be 1.

Returns a value between 0-1 that represents the percentage that x has moved between min and max, but smoothed or slowed down the closer X is to the min and max.

See Smoothstep for details.

.smootherstep ( x : Float, min : Float, max : Float ) : Float

x - The value to evaluate based on its position between min and max.
min - Any x value below min will be 0.
max - Any x value above max will be 1.

Returns a value between 0-1. A variation on smoothstep that has zero 1st and 2nd order derivatives at x=0 and x=1.

.setQuaternionFromProperEuler ( q : Quaternion, a : Float, b : Float, c : Float, order : String ) : undefined

q - the quaternion to be set
a - the rotation applied to the first axis, in radians
b - the rotation applied to the second axis, in radians
c - the rotation applied to the third axis, in radians
order - a string specifying the axes order: 'XYX', 'XZX', 'YXY', 'YZY', 'ZXZ', or 'ZYZ'

Sets quaternion q from the intrinsic Proper Euler Angles defined by angles a, b, and c, and order order.
Rotations are applied to the axes in the order specified by order: rotation by angle a is applied first, then by angle b, then by angle c. Angles are in radians.

Source

src/math/MathUtils.js

Matrix2

A class representing a 2x2 matrix.

Code Example

const m = new Matrix2();

A Note on Row-Major and Column-Major Ordering

The constructor and set() method take arguments in row-major order, while internally they are stored in the elements array in column-major order.

This means that calling m.set( 11, 12, 21, 22 ); will result in the elements array containing: m.elements = [ 11, 21, 12, 22 ]; and internally all calculations are performed using column-major ordering. However, as the actual ordering makes no difference mathematically and most people are used to thinking about matrices in row-major order, the three.js documentation shows matrices in row-major order. Just bear in mind that if you are reading the source code, you'll have to take the transpose of any matrices outlined here to make sense of the calculations.

Constructor

Matrix2( n11 : Number, n12 : Number, n21 : Number, n22 : Number )

Creates a 2x2 matrix with the given arguments in row-major order. If no arguments are provided, the constructor initializes the Matrix2 to the 3x3 identity matrix.

Properties

.elements : Array

A column-major list of matrix values.

Methods

.fromArray ( array : Array, offset : Integer ) : this

array - the array to read the elements from.
offset - (optional) index of first element in the array. Default is 0.

Sets the elements of this matrix based on an array in column-major format.

.identity () : this

Resets this matrix to the 2x2 identity matrix:

[ 1 0 0 1 ]

.set ( n11 : Float, n12 : Float, n21 : Float, n22 : Float ) : this

Sets the 2x2 matrix values to the given row-major sequence of values:

[ n11 n12 n21 n22 ]

Source

src/math/Matrix2.js

Matrix3

A class representing a 3x3 matrix.

Code Example

const m = new Matrix3();

A Note on Row-Major and Column-Major Ordering

The constructor and set() method take arguments in row-major order, while internally they are stored in the elements array in column-major order.

This means that calling m.set( 11, 12, 13, 21, 22, 23, 31, 32, 33 ); will result in the elements array containing: m.elements = [ 11, 21, 31, 12, 22, 32, 13, 23, 33 ]; and internally all calculations are performed using column-major ordering. However, as the actual ordering makes no difference mathematically and most people are used to thinking about matrices in row-major order, the three.js documentation shows matrices in row-major order. Just bear in mind that if you are reading the source code, you'll have to take the transpose of any matrices outlined here to make sense of the calculations.

Constructor

Matrix3( n11 : Number, n12 : Number, n13 : Number, n21 : Number, n22 : Number, n23 : Number, n31 : Number, n32 : Number, n33 : Number )

Creates a 3x3 matrix with the given arguments in row-major order. If no arguments are provided, the constructor initializes the Matrix3 to the 3x3 identity matrix.

Properties

.elements : Array

A column-major list of matrix values.

Methods

.clone () : Matrix3

Creates a new Matrix3 and with identical elements to this one.

.copy ( m : Matrix3 ) : this

Copies the elements of matrix m into this matrix.

.determinant () : Float

Computes and returns the determinant of this matrix.

.equals ( m : Matrix3 ) : Boolean

Return true if this matrix and m are equal.

.extractBasis ( xAxis : Vector3, yAxis : Vector3, zAxis : Vector3 ) : this

Extracts the basis of this matrix into the three axis vectors provided. If this matrix is:

[ a b c d e f g h i ]

then the xAxis, yAxis, zAxis will be set to:

xAxis = [ a d g ] , yAxis = [ b e h ] , and zAxis = [ c f i ]

.fromArray ( array : Array, offset : Integer ) : this

array - the array to read the elements from.
offset - (optional) index of first element in the array. Default is 0.

Sets the elements of this matrix based on an array in column-major format.

.invert () : this

Inverts this matrix, using the analytic method. You can not invert with a determinant of zero. If you attempt this, the method produces a zero matrix instead.

.getNormalMatrix ( m : Matrix4 ) : this

m - Matrix4

Sets this matrix as the upper left 3x3 of the normal matrix of the passed matrix4. The normal matrix is the inverse transpose of the matrix m.

.identity () : this

Resets this matrix to the 3x3 identity matrix:

[ 1 0 0 0 1 0 0 0 1 ]

.makeRotation ( theta : Float ) : this

theta — Rotation angle in radians. Positive values rotate counterclockwise.

Sets this matrix as a 2D rotational transformation by theta radians. The resulting matrix will be:

[ cos θ -sin θ 0 sin θ cos θ 0 0 0 1 ]

.makeScale ( x : Float, y : Float ) : this

x - the amount to scale in the X axis.
y - the amount to scale in the Y axis.
Sets this matrix as a 2D scale transform:

[ x 0 0 0 y 0 0 0 1 ]

.makeTranslation ( v : Vector2 ) : this

.makeTranslation ( x : Float, y : Float ) : this

v a translation transform from vector.
or
x - the amount to translate in the X axis.
y - the amount to translate in the Y axis.
Sets this matrix as a 2D translation transform:

[ 1 0 x 0 1 y 0 0 1 ]

.multiply ( m : Matrix3 ) : this

Post-multiplies this matrix by m.

.multiplyMatrices ( a : Matrix3, b : Matrix3 ) : this

Sets this matrix to a x b.

.multiplyScalar ( s : Float ) : this

Multiplies every component of the matrix by the scalar value s.

.rotate ( theta : Float ) : this

Rotates this matrix by the given angle (in radians).

.scale ( sx : Float, sy : Float ) : this

Scales this matrix with the given scalar values.

.set ( n11 : Float, n12 : Float, n13 : Float, n21 : Float, n22 : Float, n23 : Float, n31 : Float, n32 : Float, n33 : Float ) : this

Sets the 3x3 matrix values to the given row-major sequence of values:

[ n11 n12 n13 n21 n22 n23 n31 n32 n33 ]

.premultiply ( m : Matrix3 ) : this

Pre-multiplies this matrix by m.

.setFromMatrix4 ( m : Matrix4 ) : this

Set this matrix to the upper 3x3 matrix of the Matrix4 m.

.setUvTransform ( tx : Float, ty : Float, sx : Float, sy : Float, rotation : Float, cx : Float, cy : Float ) : this

tx - offset x
ty - offset y
sx - repeat x
sy - repeat y
rotation - rotation, in radians. Positive values rotate counterclockwise
cx - center x of rotation
cy - center y of rotation

Sets the UV transform matrix from offset, repeat, rotation, and center.

.toArray ( array : Array, offset : Integer ) : Array

array - (optional) array to store the resulting vector in. If not given a new array will be created.
offset - (optional) offset in the array at which to put the result.

Writes the elements of this matrix to an array in column-major format.

.translate ( tx : Float, ty : Float ) : this

Translates this matrix by the given scalar values.

.transpose () : this

Transposes this matrix in place.

.transposeIntoArray ( array : Array ) : this

array - array to store the resulting vector in.

Transposes this matrix into the supplied array, and returns itself unchanged.

Source

src/math/Matrix3.js

Matrix4

A class representing a 4x4 matrix.

The most common use of a 4x4 matrix in 3D computer graphics is as a Transformation Matrix. For an introduction to transformation matrices as used in WebGL, check out this tutorial.

This allows a Vector3 representing a point in 3D space to undergo transformations such as translation, rotation, shear, scale, reflection, orthogonal or perspective projection and so on, by being multiplied by the matrix. This is known as applying the matrix to the vector.

Every Object3D has three associated Matrix4s:

CamerasObject3D.normalMatrixMatrix3

A Note on Row-Major and Column-Major Ordering

The constructor and set() method take arguments in row-major order, while internally they are stored in the elements array in column-major order.

This means that calling const m = new THREE.Matrix4(); m.set( 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44 ); will result in the elements array containing: m.elements = [ 11, 21, 31, 41, 12, 22, 32, 42, 13, 23, 33, 43, 14, 24, 34, 44 ]; and internally all calculations are performed using column-major ordering. However, as the actual ordering makes no difference mathematically and most people are used to thinking about matrices in row-major order, the three.js documentation shows matrices in row-major order. Just bear in mind that if you are reading the source code, you'll have to take the transpose of any matrices outlined here to make sense of the calculations.

Extracting position, rotation and scale

There are several options available for extracting position, rotation and scale from a Matrix4.

Constructor

Matrix4( n11 : Number, n12 : Number, n13 : Number, n14 : Number, n21 : Number, n22 : Number, n23 : Number, n24 : Number, n31 : Number, n32 : Number, n33 : Number, n34 : Number, n41 : Number, n42 : Number, n43 : Number, n44 : Number )

Creates a 4x4 matrix with the given arguments in row-major order. If no arguments are provided, the constructor initializes the Matrix4 to the 4x4 identity matrix.

Properties

.elements : Array

A column-major list of matrix values.

Methods

.clone () : Matrix4

Creates a new Matrix4 with identical elements to this one.

.compose ( position : Vector3, quaternion : Quaternion, scale : Vector3 ) : this

Sets this matrix to the transformation composed of position, quaternion and scale.

.copy ( m : Matrix4 ) : this

Copies the elements of matrix m into this matrix.

.copyPosition ( m : Matrix4 ) : this

Copies the translation component of the supplied matrix m into this matrix's translation component.

.decompose ( position : Vector3, quaternion : Quaternion, scale : Vector3 ) : this

Decomposes this matrix into its position, quaternion and scale components.

Note: Not all matrices are decomposable in this way. For example, if an object has a non-uniformly scaled parent, then the object's world matrix may not be decomposable, and this method may not be appropriate.

.determinant () : Float

Computes and returns the determinant of this matrix.

Based on the method outlined here.

.equals ( m : Matrix4 ) : Boolean

Return true if this matrix and m are equal.

.extractBasis ( xAxis : Vector3, yAxis : Vector3, zAxis : Vector3 ) : this

Extracts the basis of this matrix into the three axis vectors provided. If this matrix is:

[ a b c d e f g h i j k l m n o p ]

then the xAxis, yAxis, zAxis will be set to:

xAxis = [ a e i ] , yAxis = [ b f j ] , and zAxis = [ c g k ]

.extractRotation ( m : Matrix4 ) : this

Extracts the rotation component of the supplied matrix m into this matrix's rotation component.

.fromArray ( array : Array, offset : Integer ) : this

array - the array to read the elements from.
offset - ( optional ) offset into the array. Default is 0.

Sets the elements of this matrix based on an array in column-major format.

.invert () : this

Inverts this matrix, using the analytic method. You can not invert with a determinant of zero. If you attempt this, the method produces a zero matrix instead.

.getMaxScaleOnAxis () : Float

Gets the maximum scale value of the 3 axes.

.identity () : this

Resets this matrix to the identity matrix.

.lookAt ( eye : Vector3, target : Vector3, up : Vector3 ) : this

Constructs a rotation matrix, looking from eye towards target oriented by the up vector.

.makeRotationAxis ( axis : Vector3, theta : Float ) : this

axis — Rotation axis, should be normalized.
theta — Rotation angle in radians.

Sets this matrix as rotation transform around axis by theta radians.
This is a somewhat controversial but mathematically sound alternative to rotating via Quaternions. See the discussion here.

.makeBasis ( xAxis : Vector3, yAxis : Vector3, zAxis : Vector3 ) : this

Set this to the basis matrix consisting of the three provided basis vectors:

[ xAxis.x yAxis.x zAxis.x 0 xAxis.y yAxis.y zAxis.y 0 xAxis.z yAxis.z zAxis.z 0 0 0 0 1 ]

.makePerspective ( left : Float, right : Float, top : Float, bottom : Float, near : Float, far : Float ) : this

Creates a perspective projection matrix. This is used internally by PerspectiveCamera.updateProjectionMatrix()

.makeOrthographic ( left : Float, right : Float, top : Float, bottom : Float, near : Float, far : Float ) : this

Creates an orthographic projection matrix. This is used internally by OrthographicCamera.updateProjectionMatrix().

.makeRotationFromEuler ( euler : Euler ) : this

Sets the rotation component (the upper left 3x3 matrix) of this matrix to the rotation specified by the given Euler Angle. The rest of the matrix is set to the identity. Depending on the order of the euler, there are six possible outcomes. See this page for a complete list.

.makeRotationFromQuaternion ( q : Quaternion ) : this

Sets the rotation component of this matrix to the rotation specified by q, as outlined here. The rest of the matrix is set to the identity. So, given q = w + xi + yj + zk, the resulting matrix will be:

[ 1 - 2 y 2 - 2 z 2 2 x y - 2 z w 2 x z + 2 y w 0 2 x y + 2 z w 1 - 2 x 2 - 2 z 2 2 y z - 2 x w 0 2 x z - 2 y w 2 y z + 2 x w 1 - 2 x 2 - 2 y 2 0 0 0 0 1 ]

.makeRotationX ( theta : Float ) : this

theta — Rotation angle in radians.

Sets this matrix as a rotational transformation around the X axis by theta (θ) radians. The resulting matrix will be:

[ 1 0 0 0 0 cos θ - sin θ 0 0 sin θ cos θ 0 0 0 0 1 ]

.makeRotationY ( theta : Float ) : this

theta — Rotation angle in radians.

Sets this matrix as a rotational transformation around the Y axis by theta (θ) radians. The resulting matrix will be:

[ cos θ 0 sin θ 0 0 1 0 0 - sin θ 0 cos θ 0 0 0 0 1 ]

.makeRotationZ ( theta : Float ) : this

theta — Rotation angle in radians.

Sets this matrix as a rotational transformation around the Z axis by theta (θ) radians. The resulting matrix will be:

[ cos θ - sin θ 0 0 sin θ cos θ 0 0 0 0 1 0 0 0 0 1 ]

.makeScale ( x : Float, y : Float, z : Float ) : this

x - the amount to scale in the X axis.
y - the amount to scale in the Y axis.
z - the amount to scale in the Z axis.

Sets this matrix as scale transform:

[ x 0 0 0 0 y 0 0 0 0 z 0 0 0 0 1 ]

.makeShear ( xy : Float, xz : Float, yx : Float, yz : Float, zx : Float, zy : Float ) : this

xy - the amount to shear X by Y.
xz - the amount to shear X by Z.
yx - the amount to shear Y by X.
yz - the amount to shear Y by Z.
zx - the amount to shear Z by X.
zy - the amount to shear Z by Y.

Sets this matrix as a shear transform:

[ 1 yx zx 0 xy 1 zy 0 xz yz 1 0 0 0 0 1 ]

.makeTranslation ( v : Vector3 ) : this

.makeTranslation ( x : Float, y : Float, z : Float ) : this // optional API

Sets this matrix as a translation transform from vector v, or numbers x, y and z:

[ 1 0 0 x 0 1 0 y 0 0 1 z 0 0 0 1 ]

.multiply ( m : Matrix4 ) : this

Post-multiplies this matrix by m.

.multiplyMatrices ( a : Matrix4, b : Matrix4 ) : this

Sets this matrix to a x b.

.multiplyScalar ( s : Float ) : this

Multiplies every component of the matrix by a scalar value s.

.premultiply ( m : Matrix4 ) : this

Pre-multiplies this matrix by m.

.scale ( v : Vector3 ) : this

Multiplies the columns of this matrix by vector v.

.set ( n11 : Float, n12 : Float, n13 : Float, n14 : Float, n21 : Float, n22 : Float, n23 : Float, n24 : Float, n31 : Float, n32 : Float, n33 : Float, n34 : Float, n41 : Float, n42 : Float, n43 : Float, n44 : Float ) : this

Set the elements of this matrix to the supplied row-major values n11, n12, ... n44.

.setFromMatrix3 ( m : Matrix3 ) : this

Set the upper 3x3 elements of this matrix to the values of the Matrix3 m.

.setPosition ( v : Vector3 ) : this

.setPosition ( x : Float, y : Float, z : Float ) : this // optional API

Sets the position component for this matrix from vector v, without affecting the rest of the matrix - i.e. if the matrix is currently:

[ a b c d e f g h i j k l m n o p ]

This becomes:

[ a b c v.x e f g v.y i j k v.z m n o p ]

.toArray ( array : Array, offset : Integer ) : Array

array - (optional) array to store the resulting vector in.
offset - (optional) offset in the array at which to put the result.

Writes the elements of this matrix to an array in column-major format.

.transpose () : this

Transposes this matrix.

Source

src/math/Matrix4.js

Plane

A two dimensional surface that extends infinitely in 3d space, represented in Hessian normal form by a unit length normal vector and a constant.

Constructor

Plane( normal : Vector3, constant : Float )

normal - (optional) a unit length Vector3 defining the normal of the plane. Default is (1, 0, 0).
constant - (optional) the signed distance from the origin to the plane. Default is 0.

Properties

.isPlane : Boolean

Read-only flag to check if a given object is of type Plane.

.normal : Vector3

.constant : Float

Methods

.applyMatrix4 ( matrix : Matrix4, optionalNormalMatrix : Matrix3 ) : this

matrix - the Matrix4 to apply.
optionalNormalMatrix - (optional) pre-computed normal Matrix3 of the Matrix4 being applied.

Apply a Matrix4 to the plane. The matrix must be an affine, homogeneous transform.
If supplying an optionalNormalMatrix, it can be created like so: const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );

.clone () : Plane

Returns a new plane with the same normal and constant as this one.

.coplanarPoint ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Returns a Vector3 coplanar to the plane, by calculating the projection of the normal vector at the origin onto the plane.

.copy ( plane : Plane ) : this

Copies the values of the passed plane's normal and constant properties to this plane.

.distanceToPoint ( point : Vector3 ) : Float

Returns the signed distance from the point to the plane.

.distanceToSphere ( sphere : Sphere ) : Float

Returns the signed distance from the sphere to the plane.

.equals ( plane : Plane ) : Boolean

Checks to see if two planes are equal (their normal and constant properties match).

.intersectLine ( line : Line3, target : Vector3 ) : Vector3

line - the Line3 to check for intersection.
target — the result will be copied into this Vector3.

Returns the intersection point of the passed line and the plane. Returns null if the line does not intersect. Returns the line's starting point if the line is coplanar with the plane.

.intersectsBox ( box : Box3 ) : Boolean

box - the Box3 to check for intersection.

Determines whether or not this plane intersects box.

.intersectsLine ( line : Line3 ) : Boolean

line - the Line3 to check for intersection.

Tests whether a line segment intersects with (passes through) the plane.

.intersectsSphere ( sphere : Sphere ) : Boolean

sphere - the Sphere to check for intersection.

Determines whether or not this plane intersects sphere.

.negate () : this

Negates both the normal vector and the constant.

.normalize () : this

Normalizes the normal vector, and adjusts the constant value accordingly.

.projectPoint ( point : Vector3, target : Vector3 ) : Vector3

point - the Vector3 to project onto the plane.
target — the result will be copied into this Vector3.

Projects a point onto the plane.

.set ( normal : Vector3, constant : Float ) : this

normal - a unit length Vector3 defining the normal of the plane.
constant - the signed distance from the origin to the plane.

Sets this plane's normal and constant properties by copying the values from the given normal.

.setComponents ( x : Float, y : Float, z : Float, w : Float ) : this

x - x value of the unit length normal vector.
y - y value of the unit length normal vector.
z - z value of the unit length normal vector.
w - the value of the plane's constant property.

Set the individual components that define the plane.

.setFromCoplanarPoints ( a : Vector3, b : Vector3, c : Vector3 ) : this

a - first point on the plane.
b - second point on the plane.
c - third point on the plane.

Defines the plane based on the 3 provided points. The winding order is assumed to be counter-clockwise, and determines the direction of the normal.

.setFromNormalAndCoplanarPoint ( normal : Vector3, point : Vector3 ) : this

normal - a unit length Vector3 defining the normal of the plane.
point - Vector3

Sets the plane's properties as defined by a normal and an arbitrary coplanar point.

.translate ( offset : Vector3 ) : this

offset - the amount to move the plane by.

Translates the plane by the distance defined by the offset vector. Note that this only affects the plane constant and will not affect the normal vector.

Source

src/math/Plane.js

Quaternion

Implementation of a quaternion.
Quaternions are used in three.js to represent rotations.

Iterating through a Quaternion instance will yield its components (x, y, z, w) in the corresponding order.

Note that three.js expects Quaternions to be normalized.

Code Example

const quaternion = new THREE.Quaternion(); quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); const vector = new THREE.Vector3( 1, 0, 0 ); vector.applyQuaternion( quaternion );

Constructor

Quaternion( x : Float, y : Float, z : Float, w : Float )

x - x coordinate
y - y coordinate
z - z coordinate
w - w coordinate

Properties

.isQuaternion : Boolean

Read-only flag to check if a given object is of type Quaternion.

.x : Float

.y : Float

.z : Float

.w : Float

Methods

.angleTo ( q : Quaternion ) : Float

Returns the angle between this quaternion and quaternion q in radians.

.clone () : Quaternion

Creates a new Quaternion with identical x, y, z and w properties to this one.

.conjugate () : this

Returns the rotational conjugate of this quaternion. The conjugate of a quaternion represents the same rotation in the opposite direction about the rotational axis.

.copy ( q : Quaternion ) : this

Copies the x, y, z and w properties of q into this quaternion.

.equals ( v : Quaternion ) : Boolean

v - Quaternion that this quaternion will be compared to.

Compares the x, y, z and w properties of v to the equivalent properties of this quaternion to determine if they represent the same rotation.

.dot ( v : Quaternion ) : Float

Calculates the dot product of quaternions v and this one.

.fromArray ( array : Array, offset : Integer ) : this

array - array of format (x, y, z, w) used to construct the quaternion.
offset - (optional) an offset into the array.

Sets this quaternion's x, y, z and w properties from an array.

.identity () : this

Sets this quaternion to the identity quaternion; that is, to the quaternion that represents "no rotation".

.invert () : this

Inverts this quaternion - calculates the conjugate. The quaternion is assumed to have unit length.

.length () : Float

Computes the Euclidean length (straight-line length) of this quaternion, considered as a 4 dimensional vector.

.lengthSq () : Float

Computes the squared Euclidean length (straight-line length) of this quaternion, considered as a 4 dimensional vector. This can be useful if you are comparing the lengths of two quaternions, as this is a slightly more efficient calculation than length().

.normalize () : this

Normalizes this quaternion - that is, calculated the quaternion that performs the same rotation as this one, but has length equal to 1.

.multiply ( q : Quaternion ) : this

Multiplies this quaternion by q.

.multiplyQuaternions ( a : Quaternion, b : Quaternion ) : this

Sets this quaternion to a x b.
Adapted from the method outlined here.

.premultiply ( q : Quaternion ) : this

Pre-multiplies this quaternion by q.

.random () : this

Sets this quaternion to a uniformly random, normalized quaternion.

.rotateTowards ( q : Quaternion, step : Float ) : this

q - The target quaternion.
step - The angular step in radians.

Rotates this quaternion by a given angular step to the defined quaternion q. The method ensures that the final quaternion will not overshoot q.

.slerp ( qb : Quaternion, t : Float ) : this

qb - The other quaternion rotation
t - interpolation factor in the closed interval [0, 1].

Handles the spherical linear interpolation between quaternions. t represents the amount of rotation between this quaternion (where t is 0) and qb (where t is 1). This quaternion is set to the result. Also see the static version of the slerp below. // rotate a mesh towards a target quaternion mesh.quaternion.slerp( endQuaternion, 0.01 );

.slerpQuaternions ( qa : Quaternion, qb : Quaternion, t : Float ) : this

Performs a spherical linear interpolation between the given quaternions and stores the result in this quaternion.

.set ( x : Float, y : Float, z : Float, w : Float ) : this

Sets x, y, z, w properties of this quaternion.

.setFromAxisAngle ( axis : Vector3, angle : Float ) : this

Sets this quaternion from rotation specified by axis and angle.
Adapted from the method here.
Axis is assumed to be normalized, angle is in radians.

.setFromEuler ( euler : Euler ) : this

Sets this quaternion from the rotation specified by Euler angle.

.setFromRotationMatrix ( m : Matrix4 ) : this

m - a Matrix4 of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
Sets this quaternion from rotation component of m.
Adapted from the method here.

.setFromUnitVectors ( vFrom : Vector3, vTo : Vector3 ) : this

Sets this quaternion to the rotation required to rotate direction vector vFrom to direction vector vTo.
Adapted from the method here.
vFrom and vTo are assumed to be normalized.

.toArray ( array : Array, offset : Integer ) : Array

array - An optional array to store the quaternion. If not specified, a new array will be created.
offset - (optional) if specified, the result will be copied into this Array.

Returns the numerical elements of this quaternion in an array of format [x, y, z, w].

.toJSON () : Array

This methods defines the serialization result of Quaternion. Returns the numerical elements of this quaternion in an array of format [x, y, z, w].

.fromBufferAttribute ( attribute : BufferAttribute, index : Integer ) : this

attribute - the source attribute.
index - index in the attribute.

Sets x, y, z, w properties of this quaternion from the attribute.

Static Methods

.slerpFlat ( dst : Array, dstOffset : Integer, src0 : Array, srcOffset0 : Integer, src1 : Array, srcOffset1 : Integer, t : Float ) : undefined

dst - The output array.
dstOffset - An offset into the output array.
src0 - The source array of the starting quaternion.
srcOffset0 - An offset into the array src0.
src1 - The source array of the target quaternion.
srcOffset1 - An offset into the array src1.
t - Normalized interpolation factor (between 0 and 1).

This SLERP implementation assumes the quaternion data are managed in flat arrays.

.multiplyQuaternionsFlat ( dst : Array, dstOffset : Integer, src0 : Array, srcOffset0 : Integer, src1 : Array, srcOffset1 : Integer ) : Array

dst - The output array.
dstOffset - An offset into the output array.
src0 - The source array of the starting quaternion.
srcOffset0 - An offset into the array src0.
src1 - The source array of the target quaternion.
srcOffset1 - An offset into the array src1.

This multiplication implementation assumes the quaternion data are managed in flat arrays.

Source

src/math/Quaternion.js

Ray

A ray that emits from an origin in a certain direction. This is used by the Raycaster to assist with raycasting. Raycasting is used for mouse picking (working out what objects in the 3D space the mouse is over) amongst other things.

Constructor

Ray( origin : Vector3, direction : Vector3 )

origin - (optional) the origin of the Ray. Default is a Vector3 at (0, 0, 0).
direction - Vector3 The direction of the Ray. This must be normalized (with Vector3.normalize) for the methods to operate properly. Default is a Vector3 at (0, 0, -1).

Creates a new Ray.

Properties

.origin : Vector3

The origin of the Ray. Default is a Vector3 at (0, 0, 0).

.direction : Vector3

The direction of the Ray. This must be normalized (with Vector3.normalize) for the methods to operate properly. Default is a Vector3 at (0, 0, -1).

Methods

.applyMatrix4 ( matrix4 : Matrix4 ) : this

matrix4 - the Matrix4 to apply to this Ray.

Transform this Ray by the Matrix4.

.at ( t : Float, target : Vector3 ) : Vector3

t - the distance along the Ray to retrieve a position for.
target — the result will be copied into this Vector3.

Get a Vector3 that is a given distance along this Ray.

.clone () : Ray

Creates a new Ray with identical origin and direction to this one.

.closestPointToPoint ( point : Vector3, target : Vector3 ) : Vector3

point - the point to get the closest approach to.
target — the result will be copied into this Vector3.

Get the point along this Ray that is closest to the Vector3 provided.

.copy ( ray : Ray ) : this

Copies the origin and direction properties of ray into this ray.

.distanceSqToPoint ( point : Vector3 ) : Float

point - the Vector3 to compute a distance to.

Get the squared distance of the closest approach between the Ray and the Vector3.

.distanceSqToSegment ( v0 : Vector3, v1 : Vector3, optionalPointOnRay : Vector3, optionalPointOnSegment : Vector3 ) : Float

v0 - the start of the line segment.
v1 - the end of the line segment.
optionalPointOnRay - (optional) if this is provided, it receives the point on this Ray that is closest to the segment.
optionalPointOnSegment - (optional) if this is provided, it receives the point on the line segment that is closest to this Ray.

Get the squared distance between this Ray and a line segment.

.distanceToPlane ( plane : Plane ) : Float

plane - the Plane to get the distance to.

Get the distance from origin to the Plane, or null if the Ray doesn't intersect the Plane.

.distanceToPoint ( point : Vector3 ) : Float

point - Vector3 The Vector3 to compute a distance to.

Get the distance of the closest approach between the Ray and the point.

.equals ( ray : Ray ) : Boolean

ray - the Ray to compare to.

Returns true if this and the other ray have equal origin and direction.

.intersectBox ( box : Box3, target : Vector3 ) : Vector3

box - the Box3 to intersect with.
target — the result will be copied into this Vector3.

Intersect this Ray with a Box3, returning the intersection point or null if there is no intersection.

.intersectPlane ( plane : Plane, target : Vector3 ) : Vector3

plane - the Plane to intersect with.
target — the result will be copied into this Vector3.

Intersect this Ray with a Plane, returning the intersection point or null if there is no intersection.

.intersectSphere ( sphere : Sphere, target : Vector3 ) : Vector3

sphere - the Sphere to intersect with.
target — the result will be copied into this Vector3.

Intersect this Ray with a Sphere, returning the intersection point or null if there is no intersection.

.intersectTriangle ( a : Vector3, b : Vector3, c : Vector3, backfaceCulling : Boolean, target : Vector3 ) : Vector3

a, b, c - The Vector3 points making up the triangle.
backfaceCulling - whether to use backface culling.
target — the result will be copied into this Vector3.

Intersect this Ray with a triangle, returning the intersection point or null if there is no intersection.

.intersectsBox ( box : Box3 ) : Boolean

box - the Box3 to intersect with.

Return true if this Ray intersects with the Box3.

.intersectsPlane ( plane : Plane ) : Boolean

plane - the Plane to intersect with.

Return true if this Ray intersects with the Plane.

.intersectsSphere ( sphere : Sphere ) : Boolean

sphere - the Sphere to intersect with.

Return true if this Ray intersects with the Sphere.

.lookAt ( v : Vector3 ) : this

v - The Vector3 to look at.

Adjusts the direction of the ray to point at the vector in world coordinates.

.recast ( t : Float ) : this

t - The distance along the Ray to interpolate.

Shift the origin of this Ray along its direction by the distance given.

.set ( origin : Vector3, direction : Vector3 ) : this

origin - the origin of the Ray.
direction - the direction of the Ray. This must be normalized (with Vector3.normalize) for the methods to operate properly.

Sets this ray's origin and direction properties by copying the values from the given objects.

Source

src/math/Ray.js

Sphere

A sphere defined by a center and radius.

Constructor

Sphere( center : Vector3, radius : Float )

center - center of the sphere. Default is a Vector3 at (0, 0, 0).
radius - radius of the sphere. Default is -1.

Creates a new Sphere.

Properties

.center : Vector3

A Vector3 defining the center of the sphere. Default is (0, 0, 0).

.isSphere : Boolean

Read-only flag to check if a given object is of type Sphere.

.radius : Float

The radius of the sphere. Default is -1.

Methods

.applyMatrix4 ( matrix : Matrix4 ) : this

matrix - the Matrix4 to apply

Transforms this sphere with the provided Matrix4.

.clampPoint ( point : Vector3, target : Vector3 ) : Vector3

point - Vector3 The point to clamp.
target — the result will be copied into this Vector3.

Clamps a point within the sphere. If the point is outside the sphere, it will clamp it to the closest point on the edge of the sphere. Points already inside the sphere will not be affected.

.clone () : Sphere

Returns a new sphere with the same center and radius as this one.

.containsPoint ( point : Vector3 ) : Boolean

point - the Vector3 to be checked

Checks to see if the sphere contains the provided point inclusive of the surface of the sphere.

.copy ( sphere : Sphere ) : this

Copies the values of the passed sphere's center and radius properties to this sphere.

.distanceToPoint ( point : Vector3 ) : Float

Returns the closest distance from the boundary of the sphere to the point. If the sphere contains the point, the distance will be negative.

.expandByPoint ( point : Vector3 ) : this

point - Vector3 that should be included in the sphere.

Expands the boundaries of this sphere to include point.

.isEmpty () : Boolean

Checks to see if the sphere is empty (the radius set to a negative number).
Spheres with a radius of 0 contain only their center point and are not considered to be empty.

.makeEmpty () : this

Makes the sphere empty by setting center to (0, 0, 0) and radius to -1.

.equals ( sphere : Sphere ) : Boolean

Checks to see if the two spheres' centers and radii are equal.

.getBoundingBox ( target : Box3 ) : Box3

target — the result will be copied into this Box3.

Returns aMinimum Bounding Box for the sphere.

.intersectsBox ( box : Box3 ) : Boolean

box - Box3 to check for intersection against.

Determines whether or not this sphere intersects a given box.

.intersectsPlane ( plane : Plane ) : Boolean

plane - Plane to check for intersection against.

Determines whether or not this sphere intersects a given plane.

.intersectsSphere ( sphere : Sphere ) : Boolean

sphere - Sphere to check for intersection against.

Checks to see if two spheres intersect.

.set ( center : Vector3, radius : Float ) : this

center - center of the sphere.
radius - radius of the sphere.

Sets the center and radius properties of this sphere.
Please note that this method only copies the values from the given center.

.setFromPoints ( points : Array, optionalCenter : Vector3 ) : this

points - an Array of Vector3 positions.
optionalCenter - Optional Vector3 position for the sphere's center.

Computes the minimum bounding sphere for an array of points. If optionalCenteris given, it is used as the sphere's center. Otherwise, the center of the axis-aligned bounding box encompassing points is calculated.

.translate ( offset : Vector3 ) : this

Translate the sphere's center by the provided offset Vector3.

.union ( sphere : Sphere ) : this

sphere - Bounding sphere that will be unioned with this sphere.

Expands this sphere to enclose both the original sphere and the given sphere.

Source

src/math/Sphere.js

Spherical

A point's spherical coordinates.

Constructor

Spherical( radius : Float, phi : Float, theta : Float )

radius - the radius, or the Euclidean distance (straight-line distance) from the point to the origin. Default is 1.0.
phi - polar angle in radians from the y (up) axis. Default is 0.
theta - equator angle in radians around the y (up) axis. Default is 0.

The poles (phi) are at the positive and negative y axis. The equator (theta) starts at positive z.

Properties

.radius : Float

.phi : Float

.theta : Float

Methods

.clone () : Spherical

Returns a new spherical with the same radius, phi and theta properties as this one.

.copy ( s : Spherical ) : this

Copies the values of the passed Spherical's radius, phi and theta properties to this spherical.

.makeSafe () : this

Restricts the polar angle phi to be between 0.000001 and pi - 0.000001.

.set ( radius : Float, phi : Float, theta : Float ) : this

Sets values of this spherical's radius, phi and theta properties.

.setFromVector3 ( vec3 : Vector3 ) : this

Sets values of this spherical's radius, phi and theta properties from the Vector3.

.setFromCartesianCoords ( x : Float, y : Float, z : Float ) : this

Sets values of this spherical's radius, phi and theta properties from Cartesian coordinates.

Source

src/math/Spherical.js

SphericalHarmonics3

Represents a third-order spherical harmonics (SH). Light probes use this class to encode lighting information.

Constructor

SphericalHarmonics3()

Creates a new instance of SphericalHarmonics3.

Properties

.coefficients : Array

An array holding the (9) SH coefficients. A single coefficient is represented as an instance of Vector3.

.isSphericalHarmonics3 : Boolean

Read-only flag to check if a given object is of type SphericalHarmonics3.

Methods

.add ( sh : SphericalHarmonics3 ) : this

sh - The SH to add.

Adds the given SH to this instance.

.addScaledSH ( sh : SphericalHarmonics3, scale : Number ) : this

sh - The SH to add.
scale - The scale factor.

A convenience method for performing .add() and .scale() at once.

.clone () : SphericalHarmonics3

Returns a new instance of SphericalHarmonics3 with equal coefficients.

.copy ( sh : SphericalHarmonics3 ) : this

sh - The SH to copy.

Copies the given SH to this instance.

.equals ( sh : SphericalHarmonics3 ) : Boolean

sh - The SH to compare with.

Returns true if the given SH and this instance have equal coefficients.

.fromArray ( array : Array, offset : Number ) : this

array - The array holding the numbers of the SH coefficients.
offset - (optional) The array offset.

Sets the coefficients of this instance from the given array.

.getAt ( normal : Vector3, target : Vector3 ) : Vector3

normal - The normal vector (assumed to be unit length).
target - The result vector.

Returns the radiance in the direction of the given normal.

.getIrradianceAt ( normal : Vector3, target : Vector3 ) : Vector3

normal - The normal vector (assumed to be unit length).
target - The result vector.

Returns the irradiance (radiance convolved with cosine lobe) in the direction of the given normal.

.lerp ( sh : SphericalHarmonics3, alpha : Number ) : this

sh - The SH to interpolate with.
alpha - The alpha factor.

Linear interpolates between the given SH and this instance by the given alpha factor.

.scale ( scale : Number ) : this

scale - The scale factor.

Scales this SH by the given scale factor.

.set ( coefficients : Array ) : this

coefficients - An array of SH coefficients.

Sets the given SH coefficients to this instance.

.toArray ( array : Array, offset : Number ) : Array

array - (optional) The target array.
offset - (optional) The array offset.

Returns an array with the coefficients, or copies them into the provided array. The coefficients are represented as numbers.

.zero () : this

Sets all SH coefficients to 0.

Static Methods

.getBasisAt ( normal : Vector3, shBasis : Array ) : undefined

normal - The normal vector (assumed to be unit length).
shBasis - The resulting SH basis.

Computes the SH basis for the given normal vector.

Source

src/math/SphericalHarmonics3.js

Triangle

A geometric triangle as defined by three Vector3s representing its three corners.

Constructor

Triangle( a : Vector3, b : Vector3, c : Vector3 )

a - the first corner of the triangle. Default is a Vector3 at (0, 0, 0).
b - the second corner of the triangle. Default is a Vector3 at (0, 0, 0).
c - the final corner of the triangle. Default is a Vector3 at (0, 0, 0).

Creates a new Triangle.

Properties

.a : Vector3

The first corner of the triangle. Default is a Vector3 at (0, 0, 0).

.b : Vector3

The second corner of the triangle. Default is a Vector3 at (0, 0, 0).

.c : Vector3

The final corner of the triangle. Default is a Vector3 at (0, 0, 0).

Methods

.clone () : Triangle

Returns a new triangle with the same a, b and c properties as this one.

.closestPointToPoint ( point : Vector3, target : Vector3 ) : Vector3

point - Vector3
target — the result will be copied into this Vector3.

Returns the closest point on the triangle to point.

.containsPoint ( point : Vector3 ) : Boolean

point - Vector3 to check.

Returns true if the passed point, when projected onto the plane of the triangle, lies within the triangle.

.copy ( triangle : Triangle ) : this

Copies the values of the passed triangles's a, b and c properties to this triangle.

.equals ( triangle : Triangle ) : Boolean

Returns true if the two triangles have identical a, b and c properties.

.getArea () : Float

Return the area of the triangle.

.getBarycoord ( point : Vector3, target : Vector3 ) : Vector3

point - Vector3
target — the result will be copied into this Vector3.

Return a barycentric coordinate from the given vector. Returns null if the triangle is degenerate.

Picture of barycentric coordinates

.getMidpoint ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Calculate the midpoint of the triangle.

.getNormal ( target : Vector3 ) : Vector3

target — the result will be copied into this Vector3.

Calculate the normal vector of the triangle.

.getPlane ( target : Plane ) : Plane

target — the result will be copied into this Plane.

Calculate a plane based on the triangle. .

.getInterpolation ( point : Vector3, p1 : Vector3, p2 : Vector3, p3 : Vector3, v1 : Vector, v2 : Vector, v3 : Vector, target : Vector ) : Vector

point - Position of interpolated point.
p1 - Position of first vertex.
p2 - Position of second vertex.
p3 - Position of third vertex.
v1 - Value of first vertex.
v2 - Value of second vertex.
v3 - Value of third vertex.
target — Result will be copied into this Vector.

Returns the value barycentrically interpolated for the given point on the triangle. Returns null if the triangle is degenerate.

.getInterpolatedAttribute ( attribute : BufferAttribute, i1 : Number, i2 : Vector3, i3 : Number, barycoord : Vector3, target : Vector3 ) : Vector

attribute - The attribute to interpolate.
p1 - Index of first vertex.
p2 - Index of second vertex.
p3 - Index of third vertex.
barycoord - The barycoordinate value to use to interpolate.
target — Result will be copied into this Vector.

Returns the value barycentrically interpolated for the given attribute and indices.

.intersectsBox ( box : Box3 ) : Boolean

box - Box to check for intersection against.

Determines whether or not this triangle intersects box.

.isFrontFacing ( direction : Vector3 ) : Boolean

direction - The direction to test.

Whether the triangle is oriented towards the given direction or not.

.set ( a : Vector3, b : Vector3, c : Vector3 ) : this

Sets the triangle's a, b and c properties to the passed vector3s.
Please note that this method only copies the values from the given objects.

.setFromAttributeAndIndices ( attribute : BufferAttribute, i0 : Integer, i1 : Integer, i2 : Integer ) : this

attribute - BufferAttribute of vertex data
i0 - Integer index
i1 - Integer index
i2 - Integer index

Sets the triangle's vertices from the buffer attribute vertex data.

.setFromPointsAndIndices ( points : Array, i0 : Integer, i1 : Integer, i2 : Integer ) : this

points - Array of Vector3s
i0 - Integer index
i1 - Integer index
i2 - Integer index

Sets the triangle's vectors to the vectors in the array.

Source

src/math/Triangle.js

Vector2

Class representing a 2D vector. A 2D vector is an ordered pair of numbers (labeled x and y), which can be used to represent a number of things, such as:

There are other things a 2D vector can be used to represent, such as momentum vectors, complex numbers and so on, however these are the most common uses in three.js.

Iterating through a Vector2 instance will yield its components (x, y) in the corresponding order.

Code Example

const a = new THREE.Vector2( 0, 1 ); //no arguments; will be initialised to (0, 0) const b = new THREE.Vector2( ); const d = a.distanceTo( b );

Constructor

Vector2( x : Float, y : Float )

x - the x value of this vector. Default is 0.
y - the y value of this vector. Default is 0.

Creates a new Vector2.

Properties

.height : Float

Alias for y.

.isVector2 : Boolean

Read-only flag to check if a given object is of type Vector2.

.width : Float

Alias for x.

.x : Float

.y : Float

Methods

.add ( v : Vector2 ) : this

Adds v to this vector.

.addScalar ( s : Float ) : this

Adds the scalar value s to this vector's x and y values.

.addScaledVector ( v : Vector2, s : Float ) : this

Adds the multiple of v and s to this vector.

.addVectors ( a : Vector2, b : Vector2 ) : this

Sets this vector to a + b.

.angle () : Float

Computes the angle in radians of this vector with respect to the positive x-axis.

.angleTo ( v : Vector2 ) : Float

Returns the angle between this vector and vector v in radians.

.applyMatrix3 ( m : Matrix3 ) : this

Multiplies this vector (with an implicit 1 as the 3rd component) by m.

.ceil () : this

The x and y components of this vector are rounded up to the nearest integer value.

.clamp ( min : Vector2, max : Vector2 ) : this

min - the minimum x and y values.
max - the maximum x and y values in the desired range

If this vector's x or y value is greater than the max vector's x or y value, it is replaced by the corresponding value.

If this vector's x or y value is less than the min vector's x or y value, it is replaced by the corresponding value.

.clampLength ( min : Float, max : Float ) : this

min - the minimum value the length will be clamped to
max - the maximum value the length will be clamped to

If this vector's length is greater than the max value, it is replaced by the max value.

If this vector's length is less than the min value, it is replaced by the min value.

.clampScalar ( min : Float, max : Float ) : this

min - the minimum value the components will be clamped to
max - the maximum value the components will be clamped to

If this vector's x or y values are greater than the max value, they are replaced by the max value.

If this vector's x or y values are less than the min value, they are replaced by the min value.

.clone () : Vector2

Returns a new Vector2 with the same x and y values as this one.

.copy ( v : Vector2 ) : this

Copies the values of the passed Vector2's x and y properties to this Vector2.

.distanceTo ( v : Vector2 ) : Float

Computes the distance from this vector to v.

.manhattanDistanceTo ( v : Vector2 ) : Float

Computes the Manhattan distance from this vector to v.

.distanceToSquared ( v : Vector2 ) : Float

Computes the squared distance from this vector to v. If you are just comparing the distance with another distance, you should compare the distance squared instead as it is slightly more efficient to calculate.

.divide ( v : Vector2 ) : this

Divides this vector by v.

.divideScalar ( s : Float ) : this

Divides this vector by scalar s.

.dot ( v : Vector2 ) : Float

Calculates the dot product of this vector and v.

.cross ( v : Vector2 ) : Float

Calculates the cross product of this vector and v. Note that a 'cross-product' in 2D is not well-defined. This function computes a geometric cross-product often used in 2D graphics

.equals ( v : Vector2 ) : Boolean

Returns true if the components of this vector and v are strictly equal; false otherwise.

.floor () : this

The components of this vector are rounded down to the nearest integer value.

.fromArray ( array : Array, offset : Integer ) : this

array - the source array.
offset - (optional) offset into the array. Default is 0.

Sets this vector's x value to be array[ offset ] and y value to be array[ offset + 1 ].

.fromBufferAttribute ( attribute : BufferAttribute, index : Integer ) : this

attribute - the source attribute.
index - index in the attribute.

Sets this vector's x and y values from the attribute.

.getComponent ( index : Integer ) : Float

index - 0 or 1.

If index equals 0 returns the x value.
If index equals 1 returns the y value.

.length () : Float

Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).

.manhattanLength () : Float

Computes the Manhattan length of this vector.

.lengthSq () : Float

Computes the square of the Euclidean length (straight-line length) from (0, 0) to (x, y). If you are comparing the lengths of vectors, you should compare the length squared instead as it is slightly more efficient to calculate.

.lerp ( v : Vector2, alpha : Float ) : this

v - Vector2 to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Linearly interpolates between this vector and v, where alpha is the percent distance along the line - alpha = 0 will be this vector, and alpha = 1 will be v.

.lerpVectors ( v1 : Vector2, v2 : Vector2, alpha : Float ) : this

v1 - the starting Vector2.
v2 - Vector2 to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Sets this vector to be the vector linearly interpolated between v1 and v2 where alpha is the percent distance along the line connecting the two vectors - alpha = 0 will be v1, and alpha = 1 will be v2.

.negate () : this

Inverts this vector - i.e. sets x = -x and y = -y.

.normalize () : this

Converts this vector to a unit vector - that is, sets it equal to a vector with the same direction as this one, but length 1.

.max ( v : Vector2 ) : this

If this vector's x or y value is less than v's x or y value, replace that value with the corresponding max value.

.min ( v : Vector2 ) : this

If this vector's x or y value is greater than v's x or y value, replace that value with the corresponding min value.

.multiply ( v : Vector2 ) : this

Multiplies this vector by v.

.multiplyScalar ( s : Float ) : this

Multiplies this vector by scalar s.

.rotateAround ( center : Vector2, angle : Float ) : this

center - the point around which to rotate.
angle - the angle to rotate, in radians.

Rotates this vector around center by angle radians.

.round () : this

The components of this vector are rounded to the nearest integer value.

.roundToZero () : this

The components of this vector are rounded towards zero (up if negative, down if positive) to an integer value.

.set ( x : Float, y : Float ) : this

Sets the x and y components of this vector.

.setComponent ( index : Integer, value : Float ) : this

index - 0 or 1.
value - Float

If index equals 0 set x to value.
If index equals 1 set y to value

.setLength ( l : Float ) : this

Sets this vector to a vector with the same direction as this one, but length l.

.setScalar ( scalar : Float ) : this

Sets the x and y values of this vector both equal to scalar.

.setX ( x : Float ) : this

Replaces this vector's x value with x.

.setY ( y : Float ) : this

Replaces this vector's y value with y.

.sub ( v : Vector2 ) : this

Subtracts v from this vector.

.subScalar ( s : Float ) : this

Subtracts s from this vector's x and y components.

.subVectors ( a : Vector2, b : Vector2 ) : this

Sets this vector to a - b.

.toArray ( array : Array, offset : Integer ) : Array

array - (optional) array to store this vector to. If this is not provided, a new array will be created.
offset - (optional) optional offset into the array.

Returns an array [x, y], or copies x and y into the provided array.

.random () : this

Sets each component of this vector to a pseudo-random value between 0 and 1, excluding 1.

Source

src/math/Vector2.js

Vector3

Class representing a 3D vector. A 3D vector is an ordered triplet of numbers (labeled x, y, and z), which can be used to represent a number of things, such as:

There are other things a 3D vector can be used to represent, such as momentum vectors and so on, however these are the most common uses in three.js.

Iterating through a Vector3 instance will yield its components (x, y, z) in the corresponding order.

Code Example

const a = new THREE.Vector3( 0, 1, 0 ); //no arguments; will be initialised to (0, 0, 0) const b = new THREE.Vector3( ); const d = a.distanceTo( b );

Constructor

Vector3( x : Float, y : Float, z : Float )

x - the x value of this vector. Default is 0.
y - the y value of this vector. Default is 0.
z - the z value of this vector. Default is 0.

Creates a new Vector3.

Properties

.isVector3 : Boolean

Read-only flag to check if a given object is of type Vector3.

.x : Float

.y : Float

.z : Float

Methods

.add ( v : Vector3 ) : this

Adds v to this vector.

.addScalar ( s : Float ) : this

Adds the scalar value s to this vector's x, y and z values.

.addScaledVector ( v : Vector3, s : Float ) : this

Adds the multiple of v and s to this vector.

.addVectors ( a : Vector3, b : Vector3 ) : this

Sets this vector to a + b.

.applyAxisAngle ( axis : Vector3, angle : Float ) : this

axis - A normalized Vector3.
angle - An angle in radians.

Applies a rotation specified by an axis and an angle to this vector.

.applyEuler ( euler : Euler ) : this

Applies euler transform to this vector by converting the Euler object to a Quaternion and applying.

.applyMatrix3 ( m : Matrix3 ) : this

Multiplies this vector by m

.applyMatrix4 ( m : Matrix4 ) : this

Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and divides by perspective.

.applyNormalMatrix ( m : Matrix3 ) : this

Multiplies this vector by normal matrix m and normalizes the result.

.applyQuaternion ( quaternion : Quaternion ) : this

Applies a Quaternion transform to this vector.

.angleTo ( v : Vector3 ) : Float

Returns the angle between this vector and vector v in radians.

.ceil () : this

The x, y and z components of this vector are rounded up to the nearest integer value.

.clamp ( min : Vector3, max : Vector3 ) : this

min - the minimum x, y and z values.
max - the maximum x, y and z values in the desired range

If this vector's x, y or z value is greater than the max vector's x, y or z value, it is replaced by the corresponding value.

If this vector's x, y or z value is less than the min vector's x, y or z value, it is replaced by the corresponding value.

.clampLength ( min : Float, max : Float ) : this

min - the minimum value the length will be clamped to
max - the maximum value the length will be clamped to

If this vector's length is greater than the max value, the vector will be scaled down so its length is the max value.

If this vector's length is less than the min value, the vector will be scaled up so its length is the min value.

.clampScalar ( min : Float, max : Float ) : this

min - the minimum value the components will be clamped to
max - the maximum value the components will be clamped to

If this vector's x, y or z values are greater than the max value, they are replaced by the max value.

If this vector's x, y or z values are less than the min value, they are replaced by the min value.

.clone () : Vector3

Returns a new vector3 with the same x, y and z values as this one.

.copy ( v : Vector3 ) : this

Copies the values of the passed vector3's x, y and z properties to this vector3.

.cross ( v : Vector3 ) : this

Sets this vector to cross product of itself and v.

.crossVectors ( a : Vector3, b : Vector3 ) : this

Sets this vector to cross product of a and b.

.distanceTo ( v : Vector3 ) : Float

Computes the distance from this vector to v.

.manhattanDistanceTo ( v : Vector3 ) : Float

Computes the Manhattan distance from this vector to v.

.distanceToSquared ( v : Vector3 ) : Float

Computes the squared distance from this vector to v. If you are just comparing the distance with another distance, you should compare the distance squared instead as it is slightly more efficient to calculate.

.divide ( v : Vector3 ) : this

Divides this vector by v.

.divideScalar ( s : Float ) : this

Divides this vector by scalar s.

.dot ( v : Vector3 ) : Float

Calculate the dot product of this vector and v.

.equals ( v : Vector3 ) : Boolean

Returns true if the components of this vector and v are strictly equal; false otherwise.

.floor () : this

The components of this vector are rounded down to the nearest integer value.

.fromArray ( array : Array, offset : Integer ) : this

array - the source array.
offset - ( optional) offset into the array. Default is 0.

Sets this vector's x value to be array[ offset + 0 ], y value to be array[ offset + 1 ] and z value to be array[ offset + 2 ].

.fromBufferAttribute ( attribute : BufferAttribute, index : Integer ) : this

attribute - the source attribute.
index - index in the attribute.

Sets this vector's x, y and z values from the attribute.

.getComponent ( index : Integer ) : Float

index - 0, 1 or 2.

If index equals 0 returns the x value.
If index equals 1 returns the y value.
If index equals 2 returns the z value.

.length () : Float

Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).

.manhattanLength () : Float

Computes the Manhattan length of this vector.

.lengthSq () : Float

Computes the square of the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should compare the length squared instead as it is slightly more efficient to calculate.

.lerp ( v : Vector3, alpha : Float ) : this

v - Vector3 to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Linearly interpolate between this vector and v, where alpha is the percent distance along the line - alpha = 0 will be this vector, and alpha = 1 will be v.

.lerpVectors ( v1 : Vector3, v2 : Vector3, alpha : Float ) : this

v1 - the starting Vector3.
v2 - Vector3 to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Sets this vector to be the vector linearly interpolated between v1 and v2 where alpha is the percent distance along the line connecting the two vectors - alpha = 0 will be v1, and alpha = 1 will be v2.

.max ( v : Vector3 ) : this

If this vector's x, y or z value is less than v's x, y or z value, replace that value with the corresponding max value.

.min ( v : Vector3 ) : this

If this vector's x, y or z value is greater than v's x, y or z value, replace that value with the corresponding min value.

.multiply ( v : Vector3 ) : this

Multiplies this vector by v.

.multiplyScalar ( s : Float ) : this

Multiplies this vector by scalar s.

.multiplyVectors ( a : Vector3, b : Vector3 ) : this

Sets this vector equal to a * b, component-wise.

.negate () : this

Inverts this vector - i.e. sets x = -x, y = -y and z = -z.

.normalize () : this

Convert this vector to a unit vector - that is, sets it equal to a vector with the same direction as this one, but length 1.

.project ( camera : Camera ) : this

camera — camera to use in the projection.

Projects this vector from world space into the camera's normalized device coordinate (NDC) space.

.projectOnPlane ( planeNormal : Vector3 ) : this

planeNormal - A vector representing a plane normal.

Projects this vector onto a plane by subtracting this vector projected onto the plane's normal from this vector.

.projectOnVector ( v : Vector3 ) : this

Projects this vector onto v.

.reflect ( normal : Vector3 ) : this

normal - the normal to the reflecting plane

Reflect this vector off of plane orthogonal to normal. Normal is assumed to have unit length.

.round () : this

The components of this vector are rounded to the nearest integer value.

.roundToZero () : this

The components of this vector are rounded towards zero (up if negative, down if positive) to an integer value.

.set ( x : Float, y : Float, z : Float ) : this

Sets the x, y and z components of this vector.

.setComponent ( index : Integer, value : Float ) : this

index - 0, 1 or 2.
value - Float

If index equals 0 set x to value.
If index equals 1 set y to value.
If index equals 2 set z to value

.setFromColor ( color : Color ) : this

Sets this vector's x, y and z components from the r, g, and b components of the specified color.

.setFromCylindrical ( c : Cylindrical ) : this

Sets this vector from the cylindrical coordinates c.

.setFromCylindricalCoords ( radius : Float, theta : Float, y : Float ) : this

Sets this vector from the cylindrical coordinates radius, theta and y.

.setFromEuler ( euler : Euler ) : this

Sets this vector's x, y and z components from the x, y, and z components of the specified Euler Angle.

.setFromMatrixColumn ( matrix : Matrix4, index : Integer ) : this

Sets this vector's x, y and z components from index column of matrix.

.setFromMatrix3Column ( matrix : Matrix3, index : Integer ) : this

Sets this vector's x, y and z components from index column of matrix.

.setFromMatrixPosition ( m : Matrix4 ) : this

Sets this vector to the position elements of the transformation matrix m.

.setFromMatrixScale ( m : Matrix4 ) : this

Sets this vector to the scale elements of the transformation matrix m.

.setFromSpherical ( s : Spherical ) : this

Sets this vector from the spherical coordinates s.

.setFromSphericalCoords ( radius : Float, phi : Float, theta : Float ) : this

Sets this vector from the spherical coordinates radius, phi and theta.

.setLength ( l : Float ) : this

Set this vector to a vector with the same direction as this one, but length l.

.setScalar ( scalar : Float ) : this

Set the x, y and z values of this vector both equal to scalar.

.setX ( x : Float ) : this

Replace this vector's x value with x.

.setY ( y : Float ) : this

Replace this vector's y value with y.

.setZ ( z : Float ) : this

Replace this vector's z value with z.

.sub ( v : Vector3 ) : this

Subtracts v from this vector.

.subScalar ( s : Float ) : this

Subtracts s from this vector's x, y and z components.

.subVectors ( a : Vector3, b : Vector3 ) : this

Sets this vector to a - b.

.toArray ( array : Array, offset : Integer ) : Array

array - (optional) array to store this vector to. If this is not provided a new array will be created.
offset - (optional) optional offset into the array.

Returns an array [x, y, z], or copies x, y and z into the provided array.

.transformDirection ( m : Matrix4 ) : this

Transforms the direction of this vector by a matrix (the upper left 3 x 3 subset of a m) and then normalizes the result.

.unproject ( camera : Camera ) : this

camera — camera to use in the projection.

Projects this vector from the camera's normalized device coordinate (NDC) space into world space.

.random () : this

Sets each component of this vector to a pseudo-random value between 0 and 1, excluding 1.

.randomDirection () : this

Sets this vector to a uniformly random point on a unit sphere.

Source

src/math/Vector3.js

Vector4

Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers (labeled x, y, z, and w), which can be used to represent a number of things, such as:

There are other things a 4D vector can be used to represent, however these are the most common uses in three.js.

Iterating through a Vector4 instance will yield its components (x, y, z, w) in the corresponding order.

Code Example

const a = new THREE.Vector4( 0, 1, 0, 0 ); //no arguments; will be initialised to (0, 0, 0, 1) const b = new THREE.Vector4( ); const d = a.dot( b );

Constructor

Vector4( x : Float, y : Float, z : Float, w : Float )

x - the x value of this vector. Default is 0.
y - the y value of this vector. Default is 0.
z - the z value of this vector. Default is 0.
w - the w value of this vector. Default is 1.

Creates a new Vector4.

Properties

.isVector4 : Boolean

Read-only flag to check if a given object is of type Vector4.

.x : Float

.y : Float

.z : Float

.w : Float

.width : Float

Alias for z.

.height : Float

Alias for w.

Methods

.add ( v : Vector4 ) : this

Adds v to this vector.

.addScalar ( s : Float ) : this

Adds the scalar value s to this vector's x, y, z and w values.

.addScaledVector ( v : Vector4, s : Float ) : this

Adds the multiple of v and s to this vector.

.addVectors ( a : Vector4, b : Vector4 ) : this

Sets this vector to a + b.

.applyMatrix4 ( m : Matrix4 ) : this

Multiplies this vector by 4 x 4 m.

.ceil () : this

The x, y, z and w components of this vector are rounded up to the nearest integer value.

.clamp ( min : Vector4, max : Vector4 ) : this

min - the minimum x, y, z and w values.
max - the maximum x, y, z and w values in the desired range

If this vector's x, y, z or w value is greater than the max vector's x, y, z or w value, it is replaced by the corresponding value.

If this vector's x, y, z or w value is less than the min vector's x, y, z or w value, it is replaced by the corresponding value.

.clampLength ( min : Float, max : Float ) : this

min - the minimum value the length will be clamped to
max - the maximum value the length will be clamped to

If this vector's length is greater than the max value, it is replaced by the max value.

If this vector's length is less than the min value, it is replaced by the min value.

.clampScalar ( min : Float, max : Float ) : this

min - the minimum value the components will be clamped to
max - the maximum value the components will be clamped to

If this vector's x, y, z or w values are greater than the max value, they are replaced by the max value.

If this vector's x, y, z or w values are less than the min value, they are replaced by the min value.

.clone () : Vector4

Returns a new Vector4 with the same x, y, z and w values as this one.

.copy ( v : Vector4 ) : this

Copies the values of the passed Vector4's x, y, z and w properties to this Vector4.

.divide ( v : Vector4 ) : this

Divides this vector by v.

.divideScalar ( s : Float ) : this

Divides this vector by scalar s.

.dot ( v : Vector4 ) : Float

Calculates the dot product of this vector and v.

.equals ( v : Vector4 ) : Boolean

Returns true if the components of this vector and v are strictly equal; false otherwise.

.floor () : this

The components of this vector are rounded down to the nearest integer value.

.fromArray ( array : Array, offset : Integer ) : this

array - the source array.
offset - (optional) offset into the array. Default is 0.

Sets this vector's x value to be array[ offset + 0 ], y value to be array[ offset + 1 ] z value to be array[ offset + 2 ] and w value to be array[ offset + 3 ].

.fromBufferAttribute ( attribute : BufferAttribute, index : Integer ) : this

attribute - the source attribute.
index - index in the attribute.

Sets this vector's x, y, z and w values from the attribute.

.getComponent ( index : Integer ) : Float

index - 0, 1, 2 or 3.

If index equals 0 returns the x value.
If index equals 1 returns the y value.
If index equals 2 returns the z value.
If index equals 3 returns the w value.

.length () : Float

Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).

.manhattanLength () : Float

Computes the Manhattan length of this vector.

.lengthSq () : Float

Computes the square of the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should compare the length squared instead as it is slightly more efficient to calculate.

.lerp ( v : Vector4, alpha : Float ) : this

v - Vector4 to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Linearly interpolates between this vector and v, where alpha is the percent distance along the line - alpha = 0 will be this vector, and alpha = 1 will be v.

.lerpVectors ( v1 : Vector4, v2 : Vector4, alpha : Float ) : this

v1 - the starting Vector4.
v2 - Vector4 to interpolate towards.
alpha - interpolation factor, typically in the closed interval [0, 1].

Sets this vector to be the vector linearly interpolated between v1 and v2 where alpha is the percent distance along the line connecting the two vectors - alpha = 0 will be v1, and alpha = 1 will be v2.

.negate () : this

Inverts this vector - i.e. sets x = -x, y = -y, z = -z and w = -w.

.normalize () : this

Converts this vector to a unit vector - that is, sets it equal to a vector with the same direction as this one, but length 1.

.max ( v : Vector4 ) : this

If this vector's x, y, z or w value is less than v's x, y, z or w value, replace that value with the corresponding max value.

.min ( v : Vector4 ) : this

If this vector's x, y, z or w value is greater than v's x, y, z or w value, replace that value with the corresponding min value.

.multiply ( v : Vector4 ) : this

Multiplies this vector by v.

.multiplyScalar ( s : Float ) : this

Multiplies this vector by scalar s.

.round () : this

The components of this vector are rounded to the nearest integer value.

.roundToZero () : this

The components of this vector are rounded towards zero (up if negative, down if positive) to an integer value.

.set ( x : Float, y : Float, z : Float, w : Float ) : this

Sets the x, y, z and w components of this vector.

.setAxisAngleFromQuaternion ( q : Quaternion ) : this

q - a normalized Quaternion

Sets the x, y and z components of this vector to the quaternion's axis and w to the angle.

.setAxisAngleFromRotationMatrix ( m : Matrix4 ) : this

m - a Matrix4 of which the upper left 3x3 matrix is a pure rotation matrix.

Sets the x, y and z to the axis of rotation and w to the angle.

.setFromMatrixPosition ( m : Matrix4 ) : this

Sets this vector to the position elements of the transformation matrix m.

.setComponent ( index : Integer, value : Float ) : this

index - 0, 1, 2 or 3.
value - Float

If index equals 0 set x to value.
If index equals 1 set y to value.
If index equals 2 set z to value.
If index equals 3 set w to value.

.setLength ( l : Float ) : this

Sets this vector to a vector with the same direction as this one, but length l.

.setScalar ( scalar : Float ) : this

Sets the x, y, z and w values of this vector both equal to scalar.

.setX ( x : Float ) : this

Replaces this vector's x value with x.

.setY ( y : Float ) : this

Replaces this vector's y value with y.

.setZ ( z : Float ) : this

Replaces this vector's z value with z.

.setW ( w : Float ) : this

Replaces this vector's w value with w.

.sub ( v : Vector4 ) : this

Subtracts v from this vector.

.subScalar ( s : Float ) : this

Subtracts s from this vector's x, y, z and w components.

.subVectors ( a : Vector4, b : Vector4 ) : this

Sets this vector to a - b.

.toArray ( array : Array, offset : Integer ) : Array

array - (optional) array to store this vector to. If this is not provided, a new array will be created.
offset - (optional) optional offset into the array.

Returns an array [x, y, z, w], or copies x, y, z and w into the provided array.

.random () : this

Sets each component of this vector to a pseudo-random value between 0 and 1, excluding 1.

Source

src/math/Vector4.js

Interpolant

CubicInterpolant

Code Example

const interpolant = new THREE.CubicInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, new Float32Array( 1 ) ); interpolant.evaluate( 0.5 );

Constructor

CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer )

parameterPositions -- array of positions
sampleValues -- array of samples
sampleSize -- number of samples
resultBuffer -- buffer to store the interpolation results.

Properties

.parameterPositions : null

.resultBuffer : null

.sampleValues : null

.settings : Object

.valueSize : null

Methods

.evaluate ( t : Number ) : Array

Evaluate the interpolant at position t.

Source

src/math/interpolants/CubicInterpolant.js

Interpolant

DiscreteInterpolant

Code Example

const interpolant = new THREE.DiscreteInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, new Float32Array( 1 ) ); interpolant.evaluate( 0.5 );

Constructor

DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer )

parameterPositions -- array of positions
sampleValues -- array of samples
sampleSize -- number of samples
resultBuffer -- buffer to store the interpolation results.

Properties

.parameterPositions : null

.resultBuffer : null

.sampleValues : null

.settings : Object

.valueSize : null

Methods

.evaluate ( t : Number ) : Array

Evaluate the interpolant at position t.

Source

src/math/interpolants/DiscreteInterpolant.js

Interpolant

LinearInterpolant

Code Example

const interpolant = new THREE.LinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, new Float32Array( 1 ) ); interpolant.evaluate( 0.5 );

Constructor

LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer )

parameterPositions -- array of positions
sampleValues -- array of samples
sampleSize -- number of samples
resultBuffer -- buffer to store the interpolation results.

Properties

.parameterPositions : null

.resultBuffer : null

.sampleValues : null

.settings : Object

.valueSize : null

Methods

.evaluate ( t : Number ) : Array

Evaluate the interpolant at position t.

Source

src/math/interpolants/LinearInterpolant.js

Interpolant

QuaternionLinearInterpolant

Code Example

const interpolant = new THREE.QuaternionLinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, new Float32Array( 1 ) ); interpolant.evaluate( 0.5 );

Constructor

QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer )

parameterPositions -- array of positions
sampleValues -- array of samples
sampleSize -- number of samples
resultBuffer -- buffer to store the interpolation results.

Properties

.parameterPositions : null

.resultBuffer : null

.sampleValues : null

.settings : Object

.valueSize : null

Methods

.evaluate ( t : Number ) : Array

Evaluate the interpolant at position t.

Source

src/math/interpolants/QuaternionLinearInterpolant.js

Mesh

BatchedMesh

A special version of Mesh with multi draw batch rendering support. Use BatchedMesh if you have to render a large number of objects with the same material but with different geometries or world transformations. The usage of BatchedMesh will help you to reduce the number of draw calls and thus improve the overall rendering performance in your application.

If the WEBGL_multi_draw extension is not supported then a less performant fallback is used.

Code Example

const box = new THREE.BoxGeometry( 1, 1, 1 ); const sphere = new THREE.SphereGeometry( 1, 12, 12 ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); // initialize and add geometries into the batched mesh const batchedMesh = new BatchedMesh( 10, 5000, 10000, material ); const boxGeometryId = batchedMesh.addGeometry( box ); const sphereGeometryId = batchedMesh.addGeometry( sphere ); // create instances of those geometries const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId ); const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId ); const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId ); const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId ); // position the geometries batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 ); batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 ); batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 ); batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 ); scene.add( batchedMesh );

Examples

WebGL / mesh / batch

Constructor

BatchedMesh( maxInstanceCount : Integer, maxVertexCount : Integer, maxIndexCount : Integer, material : Material, )

maxInstanceCount - the max number of individual instances planned to be added and rendered.
maxVertexCount - the max number of vertices to be used by all unique geometries.
maxIndexCount - the max number of indices to be used by all unique geometries.
material - an instance of Material. Default is a new MeshBasicMaterial.

Properties

See the base Mesh class for common properties.

.boundingBox : Box3

This bounding box encloses all instances of the BatchedMesh. Can be calculated with .computeBoundingBox(). Default is null.

.boundingSphere : Sphere

This bounding sphere encloses all instances of the BatchedMesh. Can be calculated with .computeBoundingSphere(). Default is null.

.perObjectFrustumCulled : Boolean

If true then the individual objects within the BatchedMesh are frustum culled. Default is true.

.sortObjects : Boolean

If true then the individual objects within the BatchedMesh are sorted to improve overdraw-related artifacts. If the material is marked as "transparent" objects are rendered back to front and if not then they are rendered front to back. Default is true.

.maxInstanceCount : Integer

The maximum number of individual instances that can be stored in the BatchedMesh. Read only.

.isBatchedMesh : Boolean

Read-only flag to check if a given object is of type BatchedMesh.

Methods

See the base Mesh class for common methods.

.computeBoundingBox () : undefined

Computes the bounding box, updating .boundingBox attribute.
Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null.

.computeBoundingSphere () : undefined

Computes the bounding sphere, updating .boundingSphere attribute.
Bounding spheres aren't computed by default. They need to be explicitly computed, otherwise they are null.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.setCustomSort ( sortFunction : Function ) : this

Takes a sort a function that is run before render. The function takes a list of instances to sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.

.getColorAt ( instanceId : Integer, target : Color ) : undefined

instanceId: The id of an instance to get the color of.

target: The target object to copy the color in to.

Get the color of the defined geometry.

.getMatrixAt ( instanceId : Integer, target : Matrix4 ) : Matrix4

instanceId: The id of an instance to get the matrix of.

target: This 4x4 matrix will be set to the local transformation matrix of the defined instance.

Get the local transformation matrix of the defined instance.

.getVisibleAt ( instanceId : Integer ) : Boolean

instanceId: The id of an instance to get the visibility state of.

Get whether the given instance is marked as "visible" or not.

.getGeometryRangeAt ( geometryId : Integer, target : Object ) : Object

geometryId: The id of the geometry to get the range of.

target: Optional target object to copy the range in to.

Get the range representing the subset of triangles related to the attached geometry, indicating the starting offset and count, or null if invalid.

Return an object of the form:

{ start: Integer, count: Integer }

.getGeometryIdAt ( instanceId : Integer ) : Integer

instanceId: The id of an instance to get the geometryIndex of.

Get the geometryIndex of the defined instance.

.setColorAt ( instanceId : Integer, color : Color ) : undefined

instanceId: The id of the instance to set the color of.

color: The color to set the instance to.

Sets the given color to the defined geometry instance.

.setMatrixAt ( instanceId : Integer, matrix : Matrix4 ) : this

instanceId: The id of an instance to set the matrix of.

matrix: A 4x4 matrix representing the local transformation of a single instance.

Sets the given local transformation matrix to the defined instance.

.setVisibleAt ( instanceId : Integer, visible : Boolean ) : this

instanceId: The id of the instance to set the visibility of.

visible: A boolean value indicating the visibility state.

Sets the visibility of the instance at the given index.

.setGeometryIdAt ( instanceId : Integer, geometryId : Integer ) : this

instanceId: The id of the instance to set the geometryIndex of.

geometryId: The geometryIndex to be use by the instance.

Sets the geometryIndex of the instance at the given index.

.addGeometry ( geometry : BufferGeometry, reservedVertexRange : Integer, reservedIndexRange : Integer ) : Integer

geometry: The geometry to add into the BatchedMesh.

reservedVertexRange: Optional parameter specifying the amount of vertex buffer space to reserve for the added geometry. This is necessary if it is planned to set a new geometry at this index at a later time that is larger than the original geometry. Defaults to the length of the given geometry vertex buffer.

reservedIndexRange: Optional parameter specifying the amount of index buffer space to reserve for the added geometry. This is necessary if it is planned to set a new geometry at this index at a later time that is larger than the original geometry. Defaults to the length of the given geometry index buffer.

Adds the given geometry to the BatchedMesh and returns the associated geometry id referring to it to be used in other functions.

.deleteGeometry ( geometryId : Integer ) : Integer

geometryId: The id of a geometry to remove from the BatchedMesh that was previously added via "addGeometry". Any instances referencing this geometry will also be removed as a side effect.

.addInstance ( geometryId : Integer ) : Integer

geometryId: The id of a previously added geometry via "addGeometry" to add into the BatchedMesh to render.

Adds a new instance to the BatchedMesh using the geometry of the given geometryId and returns a new id referring to the new instance to be used by other functions.

.deleteInstance ( instanceId : Integer ) : Integer

instanceId: The id of an instance to remove from the BatchedMesh that was previously added via "addInstance".

Removes an existing instance from the BatchedMesh using the given instanceId.

.setGeometryAt ( geometryId : Integer, geometry : BufferGeometry ) : Integer

geometryId: Which geometry id to replace with this geometry.

geometry: The geometry to substitute at the given geometry id.

Replaces the geometry at geometryId with the provided geometry. Throws an error if there is not enough space reserved for geometry. Calling this will change all instances that are rendering that geometry.

.optimize () : this

Repacks the sub geometries in BatchedMesh to remove any unused space remaining from previously deleted geometry, freeing up space to add new geometry.

.setGeometrySize ( maxVertexCount, maxIndexCount ) : this

Resizes the available space in BatchedMesh's vertex and index buffer attributes to the provided sizes. If the provided arguments shrink the geometry buffers but there is not enough unused space at the end of the geometry attributes then an error is thrown.

maxVertexCount - the max number of vertices to be used by all unique geometries to resize to.
maxIndexCount - the max number of indices to be used by all unique geometries to resize to.

.setInstanceCount ( maxInstanceCount ) : this

Resizes the necessary buffers to support the provided number of instances. If the provided arguments shrink the number of instances but there are not enough unused ids at the end of the list then an error is thrown.

maxInstanceCount - the max number of individual instances that can be added and rendered by the BatchedMesh.

Source

src/objects/BatchedMesh.js

Object3D

Bone

A bone which is part of a Skeleton. The skeleton in turn is used by the SkinnedMesh. Bones are almost identical to a blank Object3D.

Code Example

const root = new THREE.Bone(); const child = new THREE.Bone(); root.add( child ); child.position.y = 5;

Constructor

Bone( )

Creates a new Bone.

Properties

See the base Object3D class for common properties.

.isBone : Boolean

Read-only flag to check if a given object is of type Bone.

.type : String

Set to 'Bone', this can be used to find all Bones in a scene.

Methods

See the base Object3D class for common methods.

Source

src/objects/Bone.js

Group

ClippingGroup

A special version of the Group object that defines clipping planes for decendant objects. ClippingGroups can be nested, with clipping planes accumulating by type: intersection or union.

Note: ClippingGroup is only supported with WebGPURenderer.

Constructor

ClippingGroup( )

Properties

See the base Group class for common properties.

.isClippingGroup : Boolean

Read-only flag to check if a given object is of type ClippingGroup.

.clippingPlanes : Array

User-defined clipping planes specified as THREE.Plane objects in world space. These planes apply to the objects that are children of this ClippingGroup. Points in space whose signed distance to the plane is negative are clipped (not rendered). See the webgpu / clipping example. Default is [].

.enabled : Boolean

Determines if the clipping planes defined by this object are applied. Default is true.

.clipIntersection : Boolean

Changes the behavior of clipping planes so that only their intersection is clipped, rather than their union. Default is false.

.clipShadows : Boolean

Defines whether to clip shadows according to the clipping planes specified by this ClippingGroup. Default is false.

Methods

See the base Object3D class for common methods.

Source

src/objects/ClippingGroup.js

Object3D

Group

This is almost identical to an Object3D. Its purpose is to make working with groups of objects syntactically clearer.

Code Example

const geometry = new THREE.BoxGeometry( 1, 1, 1 ); const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} ); const cubeA = new THREE.Mesh( geometry, material ); cubeA.position.set( 100, 100, 0 ); const cubeB = new THREE.Mesh( geometry, material ); cubeB.position.set( -100, -100, 0 ); //create a group and add the two cubes //These cubes can now be rotated / scaled etc as a group const group = new THREE.Group(); group.add( cubeA ); group.add( cubeB ); scene.add( group );

Constructor

Group( )

Properties

See the base Object3D class for common properties.

.isGroup : Boolean

Read-only flag to check if a given object is of type Group.

.type : String

A string 'Group'. This should not be changed.

Methods

See the base Object3D class for common methods.

Source

src/objects/Group.js

Mesh

InstancedMesh

A special version of Mesh with instanced rendering support. Use InstancedMesh if you have to render a large number of objects with the same geometry and material(s) but with different world transformations. The usage of InstancedMesh will help you to reduce the number of draw calls and thus improve the overall rendering performance in your application.

Examples

WebGL / instancing / dynamic
WebGL / instancing / performance
WebGL / instancing / scatter
WebGL / instancing / raycast

Constructor

InstancedMesh( geometry : BufferGeometry, material : Material, count : Integer )

geometry - an instance of BufferGeometry.
material — a single or an array of Material. Default is a new MeshBasicMaterial.
count - the number of instances.

Properties

See the base Mesh class for common properties.

.boundingBox : Box3

This bounding box encloses all instances of the InstancedMesh. Can be calculated with .computeBoundingBox(). Default is null.

.boundingSphere : Sphere

This bounding sphere encloses all instances of the InstancedMesh. Can be calculated with .computeBoundingSphere(). Default is null.

.count : Integer

The number of instances. The count value passed into the constructor represents the maximum number of instances of this mesh. You can change the number of instances at runtime to an integer value in the range [0, count].

If you need more instances than the original count value, you have to create a new InstancedMesh.

.instanceColor : InstancedBufferAttribute

Represents the colors of all instances. null by default. You have to set its needsUpdate flag to true if you modify instanced data via .setColorAt().

.instanceMatrix : InstancedBufferAttribute

Represents the local transformation of all instances. You have to set its needsUpdate flag to true if you modify instanced data via .setMatrixAt().

.morphTexture : DataTexture

Represents the morph target weights of all instances. You have to set its needsUpdate flag to true if you modify instanced data via .setMorphAt().

.isInstancedMesh : Boolean

Read-only flag to check if a given object is of type InstancedMesh.

Methods

See the base Mesh class for common methods.

.computeBoundingBox () : undefined

Computes the bounding box of the instanced mesh, and updates the .boundingBox attribute. The bounding box is not computed by the engine; it must be computed by your app. You may need to recompute the bounding box if an instance is transformed via .setMatrixAt().

.computeBoundingSphere () : undefined

Computes the bounding sphere of the instanced mesh, and updates the .boundingSphere attribute. The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. You may need to recompute the bounding sphere if an instance is transformed via .setMatrixAt().

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.getColorAt ( index : Integer, color : Color ) : undefined

index: The index of an instance. Values have to be in the range [0, count].

color: This color object will be set to the color of the defined instance.

Get the color of the defined instance.

.getMatrixAt ( index : Integer, matrix : Matrix4 ) : undefined

index: The index of an instance. Values have to be in the range [0, count].

matrix: This 4x4 matrix will be set to the local transformation matrix of the defined instance.

Get the local transformation matrix of the defined instance.

.getMorphAt ( index : Integer, mesh : Mesh ) : undefined

index: The index of an instance. Values have to be in the range [0, count].

mesh: The .morphTargetInfluences property of this mesh will be filled with the morph target weights of the defined instance.

Get the morph target weights of the defined instance.

.setColorAt ( index : Integer, color : Color ) : undefined

index: The index of an instance. Values have to be in the range [0, count].

color: The color of a single instance.

Sets the given color to the defined instance. Make sure you set .instanceColor.needsUpdate to true after updating all the colors.

.setMatrixAt ( index : Integer, matrix : Matrix4 ) : undefined

index: The index of an instance. Values have to be in the range [0, count].

matrix: A 4x4 matrix representing the local transformation of a single instance.

Sets the given local transformation matrix to the defined instance. Make sure you set .instanceMatrix.needsUpdate to true after updating all the matrices.

.setMorphAt ( index : Integer, mesh : Mesh ) : undefined

index: The index of an instance. Values have to be in the range [0, count].

mesh: A mesh with .morphTargetInfluences property containing the morph target weights of a single instance.

Sets the morph target weights to the defined instance. Make sure you set .morphTexture.needsUpdate to true after updating all the influences.

Source

src/objects/InstancedMesh.js

Object3D

Line

A continuous line.

This is nearly the same as LineSegments; the only difference is that it is rendered using gl.LINE_STRIP instead of gl.LINES

Code Example

const material = new THREE.LineBasicMaterial({ color: 0x0000ff }); const points = []; points.push( new THREE.Vector3( - 10, 0, 0 ) ); points.push( new THREE.Vector3( 0, 10, 0 ) ); points.push( new THREE.Vector3( 10, 0, 0 ) ); const geometry = new THREE.BufferGeometry().setFromPoints( points ); const line = new THREE.Line( geometry, material ); scene.add( line );

Constructor

Line( geometry : BufferGeometry, material : Material )

geometry — vertices representing the line segment(s). Default is a new BufferGeometry.
material — material for the line. Default is a new LineBasicMaterial.

Properties

See the base Object3D class for common properties.

.geometry : BufferGeometry

Vertices representing the line segment(s).

.isLine : Boolean

Read-only flag to check if a given object is of type Line.

.material : Material

Material for the line.

.morphTargetInfluences : Array

An array of weights typically from 0-1 that specify how much of the morph is applied. Undefined by default, but reset to a blank array by .updateMorphTargets().

.morphTargetDictionary : Object

A dictionary of morphTargets based on the morphTarget.name property. Undefined by default, but rebuilt .updateMorphTargets().

Methods

See the base Object3D class for common methods.

.computeLineDistances () : this

Computes an array of distance values which are necessary for LineDashedMaterial. For each vertex in the geometry, the method calculates the cumulative length from the current point to the very beginning of the line.

.raycast ( raycaster : Raycaster, intersects : Array ) : undefined

Get intersections between a casted Ray and this Line. Raycaster.intersectObject will call this method.

.updateMorphTargets () : undefined

Updates the morphTargets to have no influence on the object. Resets the .morphTargetInfluences and .morphTargetDictionary properties.

Source

src/objects/Line.js

Object3DLine

LineLoop

A continuous line that connects back to the start.

This is nearly the same as Line; the only difference is that it is rendered using gl.LINE_LOOP instead of gl.LINE_STRIP, which draws a straight line to the next vertex, and connects the last vertex back to the first.

Constructor

LineLoop( geometry : BufferGeometry, material : Material )

geometry — List of vertices representing points on the line loop.
material — Material for the line. Default is LineBasicMaterial.

Properties

See the base Line class for common properties.

.isLineLoop : Boolean

Read-only flag to check if a given object is of type LineLoop.

Methods

See the base Line class for common methods.

Source

src/objects/LineLoop.js

Object3DLine

LineSegments

A series of lines drawn between pairs of vertices.

This is nearly the same as Line; the only difference is that it is rendered using gl.LINES instead of gl.LINE_STRIP.

Constructor

LineSegments( geometry : BufferGeometry, material : Material )

geometry — Pair(s) of vertices representing each line segment(s).
material — Material for the line. Default is LineBasicMaterial.

Properties

See the base Line class for common properties.

.isLineSegments : Boolean

Read-only flag to check if a given object is of type LineSegments.

Methods

See the base Line class for common methods.

Source

src/objects/LineSegments.js

Object3D

LOD

Level of Detail - show meshes with more or less geometry based on distance from the camera.

Every level is associated with an object, and rendering can be switched between them at the distances specified. Typically you would create, say, three meshes, one for far away (low detail), one for mid range (medium detail) and one for close up (high detail).

Code Example

const lod = new THREE.LOD(); //Create spheres with 3 levels of detail and create new LOD levels for them for( let i = 0; i < 3; i++ ) { const geometry = new THREE.IcosahedronGeometry( 10, 3 - i ); const mesh = new THREE.Mesh( geometry, material ); lod.addLevel( mesh, i * 75 ); } scene.add( lod );

Examples

webgl / lod

Constructor

LOD( )

Creates a new LOD.

Properties

See the base Object3D class for common properties.

.autoUpdate : Boolean

Whether the LOD object is updated automatically by the renderer per frame or not. If set to false, you have to call LOD.update() in the render loop by yourself. Default is true.

.isLOD : Boolean

Read-only flag to check if a given object is of type LOD.

.levels : Array

An array of level objects

Each level is an object with the following properties:
object - The Object3D to display at this level.
distance - The distance at which to display this level of detail.
hysteresis - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.

Methods

See the base Object3D class for common methods.

.addLevel ( object : Object3D, distance : Float, hysteresis : Float ) : this

object - The Object3D to display at this level.
distance - The distance at which to display this level of detail. Default 0.0.
hysteresis - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance. Default 0.0.

Adds a mesh that will display at a certain distance and greater. Typically the further away the distance, the lower the detail on the mesh.

.removeLevel ( distance : Float) : Boolean

distance - Distance of the level to delete.

Removes an existing level, based on the distance from the camera. Returns true when the level has been removed. Otherwise false.

.getCurrentLevel () : Integer

Get the currently active LOD level. As index of the levels array.

.getObjectForDistance ( distance : Float ) : Object3D

Get a reference to the first Object3D (mesh) that is greater than distance.

.raycast ( raycaster : Raycaster, intersects : Array ) : undefined

Get intersections between a casted Ray and this LOD. Raycaster.intersectObject will call this method.

.toJSON ( meta ) : Object

Create a JSON structure with details of this LOD object.

.update ( camera : Camera ) : undefined

Set the visibility of each level's object based on distance from the camera.

Source

src/objects/LOD.js

Object3D

Mesh

Class representing triangular polygon mesh based objects. Also serves as a base for other classes such as SkinnedMesh.

Code Example

const geometry = new THREE.BoxGeometry( 1, 1, 1 ); const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh );

Constructor

Mesh( geometry : BufferGeometry, material : Material )

geometry — (optional) an instance of BufferGeometry. Default is a new BufferGeometry.
material — (optional) a single or an array of Material. Default is a new MeshBasicMaterial

Properties

See the base Object3D class for common properties.

.geometry : BufferGeometry

An instance of BufferGeometry (or derived classes), defining the object's structure.

.isMesh : Boolean

Read-only flag to check if a given object is of type Mesh.

.material : Material

An instance of material derived from the Material base class or an array of materials, defining the object's appearance. Default is a MeshBasicMaterial.

.morphTargetInfluences : Array

An array of weights typically from 0-1 that specify how much of the morph is applied. Undefined by default, but reset to a blank array by updateMorphTargets.

.morphTargetDictionary : Object

A dictionary of morphTargets based on the morphTarget.name property. Undefined by default, but rebuilt updateMorphTargets.

Methods

See the base Object3D class for common methods.

.getVertexPosition ( index : Integer, target : Vector3 ) : Vector3

Get the local-space position of the vertex at the given index, taking into account the current animation state of both morph targets and skinning.

.raycast ( raycaster : Raycaster, intersects : Array ) : undefined

Get intersections between a casted ray and this mesh. Raycaster.intersectObject will call this method, but the results are not ordered.

.updateMorphTargets () : undefined

Updates the morphTargets to have no influence on the object. Resets the morphTargetInfluences and morphTargetDictionary properties.

Source

src/objects/Mesh.js

Object3D

Points

A class for displaying points. The points are rendered by the WebGLRenderer using gl.POINTS.

Constructor

Points( geometry : BufferGeometry, material : Material )

geometry — (optional) an instance of BufferGeometry. Default is a new BufferGeometry.
material — (optional) a Material. Default is a new PointsMaterial.

Properties

See the base Object3D class for common properties.

.geometry : BufferGeometry

An instance of BufferGeometry (or derived classes), defining the object's structure.

.isPoints : Boolean

Read-only flag to check if a given object is of type Points.

.material : Material

An instance of Material, defining the object's appearance. Default is a PointsMaterial.

.morphTargetInfluences : Array

An array of weights typically from 0-1 that specify how much of the morph is applied. Undefined by default, but reset to a blank array by updateMorphTargets.

.morphTargetDictionary : Object

A dictionary of morphTargets based on the morphTarget.name property. Undefined by default, but rebuilt updateMorphTargets.

Methods

See the base Object3D class for common methods.

.raycast ( raycaster : Raycaster, intersects : Array ) : undefined

Get intersections between a casted ray and this Points. Raycaster.intersectObject will call this method.

.updateMorphTargets () : undefined

Updates the morphTargets to have no influence on the object. Resets the morphTargetInfluences and morphTargetDictionary properties.

Source

src/objects/Points.js

Skeleton

Use an array of bones to create a skeleton that can be used by a SkinnedMesh.

Code Example

// Create a simple "arm" const bones = []; const shoulder = new THREE.Bone(); const elbow = new THREE.Bone(); const hand = new THREE.Bone(); shoulder.add( elbow ); elbow.add( hand ); bones.push( shoulder ); bones.push( elbow ); bones.push( hand ); shoulder.position.y = -5; elbow.position.y = 0; hand.position.y = 5; const armSkeleton = new THREE.Skeleton( bones );

See the SkinnedMesh page for an example of usage with standard BufferGeometry.

Constructor

Skeleton( bones : Array, boneInverses : Array )

bones - The array of bones. Default is an empty array.
boneInverses - (optional) An array of Matrix4s.

Creates a new Skeleton.

Properties

.bones : Array

The array of bones. Note this is a copy of the original array, not a reference, so you can modify the original array without effecting this one.

.boneInverses : Array

An array of Matrix4s that represent the inverse of the matrixWorld of the individual bones.

.boneMatrices : Float32Array

The array buffer holding the bone data when using a vertex texture.

.boneTexture : DataTexture

The DataTexture holding the bone data when using a vertex texture.

Methods

.clone () : Skeleton

Returns a clone of this Skeleton object.

.calculateInverses () : undefined

Generates the boneInverses array if not provided in the constructor.

.computeBoneTexture () : this

Computes an instance of DataTexture in order to pass the bone data more efficiently to the shader. The texture is assigned to boneTexture.

.pose () : undefined

Returns the skeleton to the base pose.

.update () : undefined

Updates the boneMatrices and boneTexture after changing the bones. This is called automatically by the WebGLRenderer if the skeleton is used with a SkinnedMesh.

.getBoneByName ( name : String ) : Bone

name -- String to match to the Bone's .name property.

Searches through the skeleton's bone array and returns the first with a matching name.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

src/objects/Skeleton.js

Object3DMesh

SkinnedMesh

A mesh that has a Skeleton with bones that can then be used to animate the vertices of the geometry.

Code Example

const geometry = new THREE.CylinderGeometry( 5, 5, 5, 5, 15, 5, 30 ); // create the skin indices and skin weights manually // (typically a loader would read this data from a 3D model for you) const position = geometry.attributes.position; const vertex = new THREE.Vector3(); const skinIndices = []; const skinWeights = []; for ( let i = 0; i < position.count; i ++ ) { vertex.fromBufferAttribute( position, i ); // compute skinIndex and skinWeight based on some configuration data const y = ( vertex.y + sizing.halfHeight ); const skinIndex = Math.floor( y / sizing.segmentHeight ); const skinWeight = ( y % sizing.segmentHeight ) / sizing.segmentHeight; skinIndices.push( skinIndex, skinIndex + 1, 0, 0 ); skinWeights.push( 1 - skinWeight, skinWeight, 0, 0 ); } geometry.setAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( skinIndices, 4 ) ); geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeights, 4 ) ); // create skinned mesh and skeleton const mesh = new THREE.SkinnedMesh( geometry, material ); const skeleton = new THREE.Skeleton( bones ); // see example from THREE.Skeleton const rootBone = skeleton.bones[ 0 ]; mesh.add( rootBone ); // bind the skeleton to the mesh mesh.bind( skeleton ); // move the bones and manipulate the model skeleton.bones[ 0 ].rotation.x = -0.1; skeleton.bones[ 1 ].rotation.x = 0.2;

Constructor

SkinnedMesh( geometry : BufferGeometry, material : Material )

geometry - an instance of BufferGeometry.
material - (optional) an instance of Material. Default is a new MeshBasicMaterial.

Properties

See the base Mesh class for common properties.

.bindMode : String

Either AttachedBindMode or DetachedBindMode. AttachedBindMode means the skinned mesh shares the same world space as the skeleton. This is not true when using DetachedBindMode which is useful when sharing a skeleton across multiple skinned meshes. Default is AttachedBindMode.

.bindMatrix : Matrix4

The base matrix that is used for the bound bone transforms.

.bindMatrixInverse : Matrix4

The base matrix that is used for resetting the bound bone transforms.

.boundingBox : Box3

The bounding box of the SkinnedMesh. Can be calculated with .computeBoundingBox(). Default is null.

.boundingSphere : Sphere

The bounding sphere of the SkinnedMesh. Can be calculated with .computeBoundingSphere(). Default is null.

.isSkinnedMesh : Boolean

Read-only flag to check if a given object is of type SkinnedMesh.

.skeleton : Skeleton

Skeleton representing the bone hierarchy of the skinned mesh.

Methods

See the base Mesh class for common methods.

.bind ( skeleton : Skeleton, bindMatrix : Matrix4 ) : undefined

skeleton - Skeleton created from a Bones tree.
bindMatrix - Matrix4 that represents the base transform of the skeleton.

Bind a skeleton to the skinned mesh. The bindMatrix gets saved to .bindMatrix property and the .bindMatrixInverse gets calculated.

.clone () : SkinnedMesh

This method does currently not clone an instance of SkinnedMesh correctly. Please use SkeletonUtils.clone() in the meanwhile.

.computeBoundingBox () : undefined

Computes the bounding box of the skinned mesh, and updates the .boundingBox attribute. The bounding box is not computed by the engine; it must be computed by your app. If the skinned mesh is animated, the bounding box should be recomputed per frame.

.computeBoundingSphere () : undefined

Computes the bounding sphere of the skinned mesh, and updates the .boundingSphere attribute. The bounding sphere is automatically computed by the engine when it is needed, e.g., for ray casting and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed per frame.

.normalizeSkinWeights () : undefined

Normalizes the skin weights.

.pose () : undefined

This method sets the skinned mesh in the rest pose (resets the pose).

.applyBoneTransform ( index : Integer, vector : Vector3 ) : Vector3

Applies the bone transform associated with the given index to the given position vector. Returns the updated vector.

Source

src/objects/SkinnedMesh.js

Object3D

Sprite

A sprite is a plane that always faces towards the camera, generally with a partially transparent texture applied.

Sprites do not cast shadows, setting castShadow = true will have no effect.

Code Example

const map = new THREE.TextureLoader().load( 'sprite.png' ); const material = new THREE.SpriteMaterial( { map: map } ); const sprite = new THREE.Sprite( material ); scene.add( sprite );

Constructor

Sprite( material : Material )

material - (optional) an instance of SpriteMaterial. Default is a white SpriteMaterial.

Creates a new Sprite.

Properties

See the base Object3D class for common properties.

.isSprite : Boolean

Read-only flag to check if a given object is of type Sprite.

.material : SpriteMaterial

An instance of SpriteMaterial, defining the object's appearance. Default is a white SpriteMaterial.

.center : Vector2

The sprite's anchor point, and the point around which the sprite rotates. A value of (0.5, 0.5) corresponds to the midpoint of the sprite. A value of (0, 0) corresponds to the lower left corner of the sprite. The default is (0.5, 0.5).

Methods

See the base Object3D class for common methods.

.copy ( sprite : Sprite ) : this

Copies the properties of the passed sprite to this one.

.raycast ( raycaster : Raycaster, intersects : Array ) : undefined

Get intersections between a casted ray and this sprite. Raycaster.intersectObject() will call this method. The raycaster must be initialized by calling Raycaster.setFromCamera() before raycasting against sprites.

Source

src/objects/Sprite.js

WebGLRenderer

The WebGL renderer displays your beautifully crafted scenes using WebGL.

Constructor

WebGLRenderer( parameters : Object )

parameters - (optional) object with properties defining the renderer's behavior. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing. The following are valid parameters:

canvas - A canvas where the renderer draws its output. This corresponds to the domElement property below. If not passed in here, a new canvas element will be created.
context - This can be used to attach the renderer to an existing RenderingContext. Default is null.
precision - Shader precision. Can be "highp", "mediump" or "lowp". Defaults to "highp" if supported by the device.
alpha - controls the default clear alpha value. When set to true, the value is 0. Otherwise it's 1. Default is false.
premultipliedAlpha - whether the renderer will assume that colors have premultiplied alpha. Default is true.
antialias - whether to perform antialiasing. Default is false.
stencil - whether the drawing buffer has a stencil buffer of at least 8 bits. Default is false.
preserveDrawingBuffer - whether to preserve the buffers until manually cleared or overwritten. Default is false.
powerPreference - Provides a hint to the user agent indicating what configuration of GPU is suitable for this WebGL context. Can be "high-performance", "low-power" or "default". Default is "default". See WebGL spec for details.
failIfMajorPerformanceCaveat - whether the renderer creation will fail upon low performance is detected. Default is false. See WebGL spec for details.
depth - whether the drawing buffer has a depth buffer of at least 16 bits. Default is true.
logarithmicDepthBuffer - whether to use a logarithmic depth buffer. It may be necessary to use this if dealing with huge differences in scale in a single scene. Note that this setting uses gl_FragDepth if available which disables the Early Fragment Test optimization and can cause a decrease in performance. Default is false. See the camera / logarithmicdepthbuffer example. reverseDepthBuffer - whether to use a reverse depth buffer. Requires the EXT_clip_control extension. This is a more faster and accurate version than logarithmic depth buffer. Default is false.

Properties

.autoClear : Boolean

Defines whether the renderer should automatically clear its output before rendering a frame. Default is true.

.autoClearColor : Boolean

If autoClear is true, defines whether the renderer should clear the color buffer. Default is true.

.autoClearDepth : Boolean

If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true.

.autoClearStencil : Boolean

If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true.

.capabilities : Object

An object containing details about the capabilities of the current RenderingContext.
- floatFragmentTextures: whether the context supports the OES_texture_float extension.
- floatVertexTextures: true if floatFragmentTextures and vertexTextures are both true.
- getMaxAnisotropy(): Returns the maximum available anisotropy.
- getMaxPrecision(): Returns the maximum available precision for vertex and fragment shaders.
- isWebGL2: true if the context in use is a WebGL2RenderingContext object.
- logarithmicDepthBuffer: true if the logarithmicDepthBuffer was set to true in the constructor.
- maxAttributes: The value of gl.MAX_VERTEX_ATTRIBS.
- maxCubemapSize: The value of gl.MAX_CUBE_MAP_TEXTURE_SIZE. Maximum height * width of cube map textures that a shader can use.
- maxFragmentUniforms: The value of gl.MAX_FRAGMENT_UNIFORM_VECTORS. The number of uniforms that can be used by a fragment shader.
- maxSamples: The value of gl.MAX_SAMPLES. Maximum number of samples in context of Multisample anti-aliasing (MSAA).
- maxTextureSize: The value of gl.MAX_TEXTURE_SIZE. Maximum height * width of a texture that a shader use.
- maxTextures: The value of gl.MAX_TEXTURE_IMAGE_UNITS. The maximum number of textures that can be used by a shader.
- maxVaryings: The value of gl.MAX_VARYING_VECTORS. The number of varying vectors that can used by shaders.
- maxVertexTextures: The value of gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS. The number of textures that can be used in a vertex shader.
- maxVertexUniforms: The value of gl.MAX_VERTEX_UNIFORM_VECTORS. The maximum number of uniforms that can be used in a vertex shader.
- precision: The shader precision currently being used by the renderer.
- reverseDepthBuffer: true if the reverseDepthBuffer was set to true in the constructor and the context supports the EXT_clip_control extension.
- vertexTextures: true if .maxVertexTextures : Integeris greater than 0 (i.e. vertex textures can be used).

.clippingPlanes : Array

User-defined clipping planes specified as THREE.Plane objects in world space. These planes apply globally. Points in space whose dot product with the plane is negative are cut away. Default is [].

.debug : Object

- checkShaderErrors: If it is true, defines whether material shader programs are checked for errors during compilation and linkage process. It may be useful to disable this check in production for performance gain. It is strongly recommended to keep these checks enabled during development. If the shader does not compile and link - it will not work and associated material will not render. Default is true.
- onShaderError( gl, program, glVertexShader, glFragmentShader ): A callback function that can be used for custom error reporting. The callback receives the WebGL context, an instance of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader. Assigning a custom function disables the default error reporting. Default is null.

.domElement : DOMElement

A canvas where the renderer draws its output.
This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page like so:
document.body.appendChild( renderer.domElement );

.extensions : Object

- get( extensionName : String ): Used to check whether various extensions are supported and returns an object with details of the extension if available. This method can check for the following extensions:

- has( extensionName : String ): true if the extension is supported.

.outputColorSpace : string

Defines the output color space of the renderer. Default is THREE.SRGBColorSpace.

If a render target has been set using .setRenderTarget then renderTarget.texture.colorSpace will be used instead.

See the texture constants page for details of other formats.

.info : Object

An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields:

By default these data are reset at each render call but when having multiple render passes per frame (e.g. when using post processing) it can be preferred to reset with a custom pattern. First, set autoReset to false. renderer.info.autoReset = false; Call reset() whenever you have finished to render a single frame. renderer.info.reset();

.localClippingEnabled : Boolean

Defines whether the renderer respects object-level clipping planes. Default is false.

.properties : Object

Used internally by the renderer to keep track of various sub object properties.

.renderLists : WebGLRenderLists

Used internally to handle ordering of scene object rendering.

.shadowMap : WebGLShadowMap

This contains the reference to the shadow map, if used.
- enabled: If set, use shadow maps in the scene. Default is false.
- autoUpdate: Enables automatic updates to the shadows in the scene. Default is true.
If you do not require dynamic lighting / shadows, you may set this to false when the renderer is instantiated.
- needsUpdate: When set to true, shadow maps in the scene will be updated in the next render call. Default is false.
If you have disabled automatic updates to shadow maps (shadowMap.autoUpdate = false), you will need to set this to true and then make a render call to update the shadows in your scene.
- type: Defines shadow map type (unfiltered, percentage close filtering, percentage close filtering with bilinear filtering in shader). Options are:

Renderer constants

.sortObjects : Boolean

Defines whether the renderer should sort objects. Default is true.

Note: Sorting is used to attempt to properly render objects that have some degree of transparency. By definition, sorting objects may not work in all cases. Depending on the needs of application, it may be necessary to turn off sorting and use other methods to deal with transparency rendering e.g. manually determining each object's rendering order.

.state : Object

Contains functions for setting various properties of the WebGLRenderer.context state.

.toneMapping : Constant

Default is NoToneMapping. See the Renderer constants for other choices.

.toneMappingExposure : Number

Exposure level of tone mapping. Default is 1.

.xr : WebXRManager

Provides access to the WebXR related interface of the renderer.

Methods

.clear ( color : Boolean, depth : Boolean, stencil : Boolean ) : undefined

Tells the renderer to clear its color, depth or stencil drawing buffer(s). This method initializes the color buffer to the current clear color value.
Arguments default to true.

.clearColor ( ) : undefined

Clear the color buffer. Equivalent to calling .clear( true, false, false ).

.clearDepth ( ) : undefined

Clear the depth buffer. Equivalent to calling .clear( false, true, false ).

.clearStencil ( ) : undefined

Clear the stencil buffers. Equivalent to calling .clear( false, false, true ).

.compile ( scene : Object3D, camera : Camera, targetScene : Scene ) : Set

Compiles all materials in the scene with the camera. This is useful to precompile shaders before the first rendering. If you want to add a 3D object to an existing scene, use the third optional parameter for applying the target scene.
Note that the (target) scene's lighting and environment should be configured before calling this method.

.compileAsync ( scene : Object3D, camera : Camera, targetScene : Scene ) : Promise

Asynchronous version of .compile(). The method returns a Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.

This method makes use of the KHR_parallel_shader_compile WebGL extension.

.copyFramebufferToTexture ( texture : FramebufferTexture, position : Vector2, level : Number ) : undefined

Copies pixels from the current WebGLFramebuffer into a 2D texture. Enables access to WebGLRenderingContext.copyTexImage2D.

.copyTextureToTexture ( srcTexture : Texture, dstTexture : Texture, srcRegion : Box2 | srcRegion : Box3, dstPosition : Vector2 | dstPosition : Vector3, srcLevel : Number, dstLevel : Number ) : undefined

Copies the pixels of a texture in the bounds 'srcRegion' in the destination texture starting from the given position. 2D Texture, 3D Textures, or a mix of the two can be used as source and destination texture arguments for copying between layers of 3d textures.
The depthTexture and texture property of render targets are supported as well.
When using render target textures as srcTexture and dstTexture, you must make sure both render targets are initialized e.g. via .initRenderTarget().

.dispose ( ) : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.forceContextLoss () : undefined

Simulate loss of the WebGL context. This requires support for the WEBGL_lose_context extensions.

.forceContextRestore ( ) : undefined

Simulate restore of the WebGL context. This requires support for the WEBGL_lose_context extensions.

.getClearAlpha () : Float

Returns a float with the current clear alpha. Ranges from 0 to 1.

.getClearColor ( target : Color ) : Color

Returns a THREE.Color instance with the current clear color.

.getContext () : WebGL2RenderingContext

Return the current WebGL context.

.getContextAttributes () : WebGLContextAttributes

Returns an object that describes the attributes set on the WebGL context when it was created.

.getActiveCubeFace () : Integer

Returns the current active cube face.

.getActiveMipmapLevel () : Integer

Returns the current active mipmap level.

.getRenderTarget () : RenderTarget

Returns the current RenderTarget if there are; returns null otherwise.

.getCurrentViewport ( target : Vector4 ) : Vector4

target — the result will be copied into this Vector4.

Returns the current viewport.

.getDrawingBufferSize ( target : Vector2 ) : Vector2

target — the result will be copied into this Vector2.

Returns the width and height of the renderer's drawing buffer, in pixels.

.getPixelRatio () : number

Returns current device pixel ratio used.

.getScissor ( target : Vector4 ) : Vector4

target — the result will be copied into this Vector4.

Returns the scissor region.

.getScissorTest () : Boolean

Returns true if scissor test is enabled; returns false otherwise.

.getSize ( target : Vector2 ) : Vector2

target — the result will be copied into this Vector2.

Returns the width and height of the renderer's output canvas, in pixels.

.getViewport ( target : Vector4 ) : Vector4

target — the result will be copied into this Vector4.

Returns the viewport.

.initTexture ( texture : Texture ) : undefined

Initializes the given texture. Useful for preloading a texture rather than waiting until first render (which can cause noticeable lags due to decode and GPU upload overhead).

.initRenderTarget ( target : WebGLRenderTarget ) : undefined

Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data can be copied into it using .copyTextureToTexture before it has been rendered to.

.resetGLState ( ) : undefined

Reset the GL state to default. Called internally if the WebGL context is lost.

.readRenderTargetPixels ( renderTarget : WebGLRenderTarget, x : Float, y : Float, width : Float, height : Float, buffer : TypedArray, activeCubeFaceIndex : Integer ) : undefined

buffer - Uint8Array is the only destination type supported in all cases, other types are renderTarget and platform dependent. See WebGL spec for details.

Reads the pixel data from the renderTarget into the buffer you pass in. This is a wrapper around WebGLRenderingContext.readPixels().

For reading out a WebGLCubeRenderTarget use the optional parameter activeCubeFaceIndex to determine which face should be read.

.readRenderTargetPixelsAsync ( renderTarget : WebGLRenderTarget, x : Float, y : Float, width : Float, height : Float, buffer : TypedArray, activeCubeFaceIndex : Integer ) : Promise

Asynchronous, non-blocking version of .readRenderTargetPixels. The returned promise resolves once the buffer data is ready to be used.

See the interactive / cubes / gpu example.

.render ( scene : Object3D, camera : Camera ) : undefined

Render a scene or another type of object using a camera.
The render is done to a previously specified renderTarget set by calling .setRenderTarget or to the canvas as usual.
By default render buffers are cleared before rendering but you can prevent this by setting the property autoClear to false. If you want to prevent only certain buffers being cleared you can set either the autoClearColor, autoClearStencil or autoClearDepth properties to false. To forcibly clear one or more buffers call .clear.

.resetState () : undefined

Can be used to reset the internal WebGL state. This method is mostly relevant for applications which share a single WebGL context across multiple WebGL libraries.

.setAnimationLoop ( callback : Function ) : undefined

callback — The function will be called every available frame. If null is passed it will stop any already ongoing animation.

A built in function that can be used instead of requestAnimationFrame. For WebXR projects this function must be used.

.setClearAlpha ( alpha : Float ) : undefined

Sets the clear alpha. Valid input is a float between 0.0 and 1.0.

.setClearColor ( color : Color, alpha : Float ) : undefined

Sets the clear color and opacity.

.setPixelRatio ( value : number ) : undefined

Sets device pixel ratio. This is usually used for HiDPI device to prevent blurring output canvas.

.setRenderTarget ( renderTarget : WebGLRenderTarget, activeCubeFace : Integer, activeMipmapLevel : Integer ) : undefined

renderTarget -- The renderTarget that needs to be activated. When null is given, the canvas is set as the active render target instead.
activeCubeFace -- Specifies the active cube side (PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5) of WebGLCubeRenderTarget. When passing a WebGLArrayRenderTarget or WebGL3DRenderTarget this indicates the z layer to render in to (optional).
activeMipmapLevel -- Specifies the active mipmap level (optional).

This method sets the active rendertarget.

.setScissor ( x : Integer, y : Integer, width : Integer, height : Integer ) : undefined
.setScissor ( vector : Vector4 ) : undefined

The x, y, width, and height parameters of the scissor region.
Optionally, a 4-component vector specifying the parameters of the region.

Sets the scissor region from (x, y) to (x + width, y + height).
(x, y) is the lower-left corner of the scissor region.

.setScissorTest ( boolean : Boolean ) : undefined

Enable or disable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions.

.setOpaqueSort ( method : Function ) : undefined

Sets the custom opaque sort function for the WebGLRenderLists. Pass null to use the default painterSortStable function.

.setTransparentSort ( method : Function ) : undefined

Sets the custom transparent sort function for the WebGLRenderLists. Pass null to use the default reversePainterSortStable function.

.setSize ( width : Integer, height : Integer, updateStyle : Boolean ) : undefined

Resizes the output canvas to (width, height) with device pixel ratio taken into account, and also sets the viewport to fit that size, starting in (0, 0). Setting updateStyle to false prevents any style changes to the output canvas.

.setViewport ( x : Integer, y : Integer, width : Integer, height : Integer ) : undefined
.setViewport ( vector : Vector4 ) : undefined

The x, y, width, and height parameters of the viewport.
Optionally, a 4-component vector specifying the parameters of a viewport.

Sets the viewport to render from (x, y) to (x + width, y + height).
(x, y) is the lower-left corner of the region.

Source

src/renderers/WebGLRenderer.js

WebGLRenderTarget

A render target is a buffer where the video card draws pixels for a scene that is being rendered in the background. It is used in different effects, such as applying postprocessing to a rendered image before displaying it on the screen.

Constructor

WebGLRenderTarget(width : Number, height : Number, options : Object)

width - The width of the renderTarget. Default is 1.
height - The height of the renderTarget. Default is 1.
options - optional object that holds texture parameters for an auto-generated target texture and depthBuffer/stencilBuffer booleans. For an explanation of the texture parameters see Texture. The following are valid options:

wrapS - default is ClampToEdgeWrapping.
wrapT - default is ClampToEdgeWrapping.
magFilter - default is LinearFilter.
minFilter - default is LinearFilter.
generateMipmaps - default is false.
format - default is RGBAFormat.
type - default is UnsignedByteType.
anisotropy - default is 1. See Texture.anisotropy
colorSpace - default is NoColorSpace.
internalFormat - default is null.
depthBuffer - default is true.
stencilBuffer - default is false.
resolveDepthBuffer - default is true.
resolveStencilBuffer - default is true.
samples - default is 0.
count - default is 1.

Creates a new WebGLRenderTarget

Properties

.isWebGLRenderTarget : Boolean

Read-only flag to check if a given object is of type WebGLRenderTarget.

.width : number

The width of the render target.

.height : number

The height of the render target.

.scissor : Vector4

A rectangular area inside the render target's viewport. Fragments that are outside the area will be discarded.

.scissorTest : Boolean

Indicates whether the scissor test is active or not.

.viewport : Vector4

The viewport of this render target.

.texture : Texture

This texture instance holds the rendered pixels. Use it as input for further processing.

.textures : Texture

An array holding the texture references of multiple render targets configured with the count option.

.depthBuffer : Boolean

Renders to the depth buffer. Default is true.

.stencilBuffer : Boolean

Renders to the stencil buffer. Default is false.

.resolveDepthBuffer : Boolean

Defines whether the depth buffer should be resolved when rendering into a multisampled render target. Default is true.

.resolveStencilBuffer : Boolean

Defines whether the stencil buffer should be resolved when rendering into a multisampled render target. This property has no effect when .resolveDepthBuffer is set to false. Default is true.

.depthTexture : DepthTexture

If set, the scene depth will be rendered to this texture. Default is null.

.samples : Number

Defines the count of MSAA samples. Default is 0.

Methods

.setSize ( width : Number, height : Number ) : undefined

Sets the size of the render target.

.clone () : WebGLRenderTarget

Creates a copy of this render target.

.copy ( source : WebGLRenderTarget ) : this

Adopts the settings of the given render target.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

EventDispatcher methods are available on this class.

Source

src/renderers/WebGLRenderTarget.js

WebGLRenderTarget

WebGL3DRenderTarget

Represents a three-dimensional render target.

Constructor

WebGL3DRenderTarget( width : Number, height : Number, depth : Number, options : Object )

width - the width of the render target, in pixels. Default is 1.
height - the height of the render target, in pixels. Default is 1.
depth - the depth of the render target. Default is 1.
options - optional object that holds texture parameters for an auto-generated target texture and depthBuffer/stencilBuffer booleans. See WebGLRenderTarget for details.

Creates a new WebGL3DRenderTarget.

Properties

See WebGLRenderTarget for inherited properties.

.depth : number

The depth of the render target.

.texture : Data3DTexture

The texture property is overwritten with an instance of Data3DTexture.

Methods

See WebGLRenderTarget for inherited methods.

Source

src/renderers/WebGL3DRenderTarget.js

WebGLRenderTarget

WebGLArrayRenderTarget

This type of render target represents an array of textures.

Examples

WebGL / render target / array

Constructor

WebGLArrayRenderTarget( width : Number, height : Number, depth : Number, options : Object )

width - the width of the render target, in pixels. Default is 1.
height - the height of the render target, in pixels. Default is 1.
depth - the depth/layer count of the render target. Default is 1.
options - optional object that holds texture parameters for an auto-generated target texture and depthBuffer/stencilBuffer booleans. See WebGLRenderTarget for details.

Creates a new WebGLArrayRenderTarget.

Properties

See WebGLRenderTarget for inherited properties.

.depth : number

The depth of the render target.

.texture : DataArrayTexture

The texture property is overwritten with an instance of DataArrayTexture.

Methods

See WebGLRenderTarget for inherited methods.

Source

src/renderers/WebGLArrayRenderTarget.js

WebGLRenderTarget

WebGLCubeRenderTarget

Used by the CubeCamera as its WebGLRenderTarget.

Examples

See CubeCamera for examples.

Constructor

WebGLCubeRenderTarget(size : Number, options : Object)

size - the size, in pixels. Default is 1.
options - (optional) object that holds texture parameters for an auto-generated target texture and depthBuffer/stencilBuffer booleans. For an explanation of the texture parameters see Texture. The following are valid options:

wrapS - default is ClampToEdgeWrapping.
wrapT - default is ClampToEdgeWrapping.
magFilter - default is .LinearFilter.
minFilter - default is LinearFilter.
generateMipmaps - default is false.
format - default is RGBAFormat.
type - default is UnsignedByteType.
anisotropy - default is 1. See Texture.anisotropy
colorSpace - default is NoColorSpace.
depthBuffer - default is true.
stencilBuffer - default is false.

Creates a new WebGLCubeRenderTarget

Properties

See WebGLRenderTarget for inherited properties.

Methods

See WebGLRenderTarget for inherited methods.

.fromEquirectangularTexture ( renderer : WebGLRenderer, texture : Texture ) : this

renderer — the renderer.
texture — the equirectangular texture.

Use this method if you want to convert an equirectangular panorama to the cubemap format.

.clear ( renderer : WebGLRenderer, color : Boolean, depth : Boolean, stencil : Boolean ) : undefined

Call this to clear the renderTarget's color, depth, and/or stencil buffers. The color buffer is set to the renderer's current clear color. Arguments default to true.

Source

src/renderers/WebGLCubeRenderTarget.js

ShaderChunk

Shader chunks for WebGL Shader library

Properties

Methods

Source

src/renderers/shaders/ShaderChunk.js

ShaderLib

Webgl Shader Library for three.js

Properties

Methods

Source

src/renderers/shaders/ShaderLib.js

UniformsLib

Uniforms library for shared webgl shaders

Properties

Methods

Source

src/renderers/shaders/UniformsLib.js

UniformsUtils

Provides utility functions for managing uniforms.

Methods

.clone ( src : Object ) : Object

src -- An object representing uniform definitions.

Clones the given uniform definitions by performing a deep-copy. That means if the value of a uniform refers to an object like a Vector3 or Texture, the cloned uniform will refer to a new object reference.

.merge ( uniforms : Array ) : Object

uniforms -- An array of objects containing uniform definitions.

Merges the given uniform definitions into a single object. Since the method internally uses .clone(), it performs a deep-copy when producing the merged uniform definitions.

Source

src/renderers/shaders/UniformsUtils.js

WebXRManager

This class represents an abstraction of the WebXR Device API and is internally used by WebGLRenderer. WebXRManager also provides a public interface that allows users to enable/disable XR and perform XR related tasks like for instance retrieving controllers.

Properties

.cameraAutoUpdate : Boolean

Whether the manager's XR camera should be automatically updated or not. Default is true.

.enabled : Boolean

This flag notifies the renderer to be ready for XR rendering. Default is false. Set it to true if you are going to use XR in your app.

.isPresenting : Boolean

Whether XR presentation is active or not. Default is false. This flag is read-only and automatically set by WebXRManager.

Methods

.getCamera () : ArrayCamera

Returns an instance of ArrayCamera which represents the XR camera of the active XR session. For each view it holds a separate camera object in its cameras property.

The camera's fov is currently not used and does not reflect the fov of the XR camera. If you need the fov on app level, you have to compute in manually from the XR camera's projection matrices.

.getController ( index : Integer ) : Group

index — The index of the controller.

Returns a Group representing the so called target ray space of the XR controller. Use this space for visualizing 3D objects that support the user in pointing tasks like UI interaction.

.getControllerGrip ( index : Integer ) : Group

index — The index of the controller.

Returns a Group representing the so called grip space of the XR controller. Use this space if the user is going to hold other 3D objects like a lightsaber.

Note: If you want to show something in the user's hand AND offer a pointing ray at the same time, you'll want to attached the handheld object to the group returned by .getControllerGrip() and the ray to the group returned by .getController(). The idea is to have two different groups in two different coordinate spaces for the same WebXR controller.

.getFoveation () : Float

Returns the amount of foveation used by the XR compositor for the projection layer.

.getHand ( index : Integer ) : Group

index — The index of the controller.

Returns a Group representing the so called hand or joint space of the XR controller. Use this space for visualizing the user's hands when no physical controllers are used.

.getReferenceSpace () : String

Returns the reference space.

.getSession () : XRSession

Returns the XRSession object which allows a more fine-grained management of active WebXR sessions on application level.

.setFoveation ( foveation : Float ) : undefined

foveation — The foveation to set.

Specifies the amount of foveation used by the XR compositor for the layer. Must be a value between 0 and 1.

.setFramebufferScaleFactor ( framebufferScaleFactor : Float ) : undefined

framebufferScaleFactor — The framebuffer scale factor to set.

Specifies the scaling factor to use when determining the size of the framebuffer when rendering to a XR device. The value is relative to the default XR device display resolution. Default is 1. A value of 0.5 would specify a framebuffer with 50% of the display's native resolution.

Note: It is not possible to change the framebuffer scale factor while presenting XR content.

.setReferenceSpace ( referenceSpace : XRReferenceSpace ) : undefined

referenceSpace — A custom reference space.

Can be used to configure a custom reference space which overwrites the default reference space.

.setReferenceSpaceType ( referenceSpaceType : String ) : undefined

referenceSpaceType — The reference space type to set.

Can be used to configure a spatial relationship with the user's physical environment. Depending on how the user moves in 3D space, setting an appropriate reference space can improve tracking. Default is local-floor. Please check out the MDN for possible values and their use cases.

.updateCamera ( camera : PerspectiveCamera ) : undefined

Updates the state of the XR camera. Use this method on app level if you set .cameraAutoUpdate to false. The method requires the non-XR camera of the scene as a parameter. The passed in camera's transformation is automatically adjusted to the position of the XR camera when calling this method.

Note: It is not possible to change the reference space type while presenting XR content.

Source

src/renderers/webxr/WebXRManager.js

Fog

This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance.

Code Example

const scene = new THREE.Scene(); scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );

Constructor

Fog( color : Integer, near : Float, far : Float )

The color parameter is passed to the Color constructor to set the color property. Color can be a hexadecimal integer or a CSS-style string.

Properties

.isFog : Boolean

Read-only flag to check if a given object is of type Fog.

.name : String

Optional name of the object (doesn't need to be unique). Default is an empty string.

.color : Color

Fog color. Example: If set to black, far away objects will be rendered black.

.near : Float

The minimum distance to start applying fog. Objects that are less than 'near' units from the active camera won't be affected by fog.

Default is 1.

.far : Float

The maximum distance at which fog stops being calculated and applied. Objects that are more than 'far' units away from the active camera won't be affected by fog.

Default is 1000.

Methods

.clone () : Fog

Returns a new fog instance with the same parameters as this one.

.toJSON () : Object

Return fog data in JSON format.

Source

src/scenes/Fog.js

FogExp2

This class contains the parameters that define exponential squared fog, which gives a clear view near the camera and a faster than exponentially densening fog farther from the camera.

Code Example

const scene = new THREE.Scene(); scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );

Constructor

FogExp2( color : Integer, density : Float )

The color parameter is passed to the Color constructor to set the color property. Color can be a hexadecimal integer or a CSS-style string.

Properties

.isFogExp2 : Boolean

Read-only flag to check if a given object is of type FogExp2.

.name : String

Optional name of the object (doesn't need to be unique). Default is an empty string.

.color : Color

Fog color. Example: If set to black, far away objects will be rendered black.

.density : Float

Defines how fast the fog will grow dense.

Default is 0.00025.

Methods

.clone () : FogExp2

Returns a new FogExp2 instance with the same parameters as this one.

.toJSON () : Object

Return FogExp2 data in JSON format.

Source

src/scenes/FogExp2.js

Object3D

Scene

Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras.

Constructor

Scene()

Create a new scene object.

Properties

.background : Object

Defines the background of the scene. Default is null. Valid inputs are:

zoomview

.backgroundBlurriness : Float

Sets the blurriness of the background. Only influences environment maps assigned to Scene.background. Valid input is a float between 0 and 1. Default is 0.

.backgroundIntensity : Float

Attenuates the color of the background. Only applies to background textures. Default is 1.

.backgroundRotation : Euler

The rotation of the background in radians. Only influences environment maps assigned to Scene.background. Default is (0,0,0).

.environment : Texture

Sets the environment map for all physical materials in the scene. However, it's not possible to overwrite an existing texture assigned to MeshStandardMaterial.envMap. Default is null.

.environmentIntensity : Float

Attenuates the color of the environment. Only influences environment maps assigned to Scene.environment. Default is 1.

.environmentRotation : Euler

The rotation of the environment map in radians. Only influences physical materials in the scene when .environment is used. Default is (0,0,0).

.fog : Fog

A fog instance defining the type of fog that affects everything rendered in the scene. Default is null.

.isScene : Boolean

Read-only flag to check if a given object is of type Scene.

.overrideMaterial : Material

Forces everything in the scene to be rendered with the defined material. Default is null.

Methods

.toJSON ( meta : Object ) : Object

meta -- object containing metadata such as textures or images for the scene.
Convert the scene to three.js JSON Object/Scene format.

Source

src/scenes/Scene.js

Texture

CanvasTexture

Creates a texture from a canvas element.

This is almost the same as the base Texture class, except that it sets needsUpdate to true immediately.

Constructor

CanvasTexture( canvas : HTMLElement, mapping : Constant, wrapS : Constant, wrapT : Constant, magFilter : Constant, minFilter : Constant, format : Constant, type : Constant, anisotropy : Number )

canvas -- The HTML canvas element from which to load the texture.
mapping -- How the image is applied to the object. An object type of THREE.UVMapping. See mapping constants for other choices.
wrapS -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
wrapT -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is THREE.LinearFilter. See magnification filter constants for other choices.
minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is THREE.LinearMipmapLinearFilter. See minification filter constants for other choices.
format -- The format used in the texture. See format constants for other choices.
type -- Default is THREE.UnsignedByteType. See type constants for other choices.
anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.

Properties

See the base Texture class for common properties.

.isCanvasTexture : Boolean

Read-only flag to check if a given object is of type CanvasTexture.

.needsUpdate : Boolean

True by default. This is required so that the canvas data is loaded.

Methods

See the base Texture class for common methods.

Source

src/textures/CanvasTexture.js

Texture

CompressedTexture

Creates a texture based on data in compressed form, for example from a DDS file.

For use with the CompressedTextureLoader.

Constructor

CompressedTexture( mipmaps : Array, width : Number, height : Number, format : Constant, type : Constant, mapping : Constant, wrapS : Constant, wrapT : Constant, magFilter : Constant, minFilter : Constant, anisotropy : Number, colorSpace : Constant )

mipmaps -- The mipmaps array should contain objects with data, width and height. The mipmaps should be of the correct format and type.
width -- The width of the biggest mipmap.
height -- The height of the biggest mipmap.
format -- The format used in the mipmaps. See ST3C Compressed Texture Formats, PVRTC Compressed Texture Formats and ETC Compressed Texture Format for other choices.
type -- Default is THREE.UnsignedByteType. See type constants for other choices.
mapping -- How the image is applied to the object. An object type of THREE.UVMapping. See mapping constants for other choices.
wrapS -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
wrapT -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is THREE.LinearFilter. See magnification filter constants for other choices.
minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is THREE.LinearMipmapLinearFilter. See minification filter constants for other choices.
anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.
colorSpace -- The default is THREE.NoColorSpace. See color space constants for other choices.

Properties

Texture

.flipY : Boolean

False by default. Flipping textures does not work for compressed textures.

.generateMipmaps : Boolean

False by default. Mipmaps can't be generated for compressed textures

.image : Object

Overridden with a object containing width and height.

.isCompressedTexture : Boolean

Read-only flag to check if a given object is of type CompressedTexture.

Methods

See the base Texture class for common methods.

Source

src/textures/CompressedTexture.js

CompressedTexture

CompressedArrayTexture

Creates an texture 2D array based on data in compressed form, for example from a DDS file.

For use with the CompressedTextureLoader.

Constructor

CompressedArrayTexture( mipmaps : Array, width : Number, height : Number, format : Constant, type : Constant )

mipmaps -- The mipmaps array should contain objects with data, width and height. The mipmaps should be of the correct format and type.
width -- The width of the biggest mipmap.
height -- The height of the biggest mipmap.
depth -- The number of layers of the 2D array texture.
format -- The format used in the mipmaps. See ST3C Compressed Texture Formats, PVRTC Compressed Texture Formats and ETC Compressed Texture Format for other choices.
type -- Default is THREE.UnsignedByteType. See type constants for other choices.

Properties

CompressedTexture

.wrapR : number

This defines how the texture is wrapped in the depth direction.
The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping. See the texture constants page for details.

.image : Object

Overridden with a object containing width, height, and depth.

.layerUpdates : Set

A set of all layers which need to be updated in the texture. See addLayerUpdate.

.isCompressedArrayTexture : Boolean

Read-only flag to check if a given object is of type CompressedArrayTexture.

Methods

.addLayerUpdate ( layerIndex ) : addLayerUpdate

Describes that a specific layer of the texture needs to be updated. Normally when needsUpdate is set to true, the entire compressed texture array is sent to the GPU. Marking specific layers will only transmit subsets of all mipmaps associated with a specific depth in the array which is often much more performant.

.clearLayerUpdates () : clearLayerUpdates

Resets the layer updates registry. See addLayerUpdate.

See the base CompressedTexture class for common methods.

Source

src/textures/CompressedArrayTexture.js

Texture

CubeTexture

Creates a cube texture made up of six images.

Code Example

const loader = new THREE.CubeTextureLoader(); loader.setPath( 'textures/cube/pisa/' ); const textureCube = loader.load( [ 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png' ] ); const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );

Constructor

CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace )

CubeTexture is almost equivalent in functionality and usage to Texture. The only differences are that the images are an array of 6 images as opposed to a single image, and the mapping options are THREE.CubeReflectionMapping (default) or THREE.CubeRefractionMapping

Properties

See the base Texture class for common properties.

.flipY : Boolean

If set to true, the texture is flipped along the vertical axis when uploaded to the GPU. Default is false.

.isCubeTexture : Boolean

Read-only flag to check if a given object is of type CubeTexture.

Methods

See the base Texture class for common methods.

Source

src/textures/CubeTexture.js

Texture

Data3DTexture

Creates a three-dimensional texture from raw data, with parameters to divide it into width, height, and depth.

Constructor

Data3DTexture( data : TypedArray, width : Number, height : Number, depth : Number )

data -- ArrayBufferView of the texture.
width -- width of the texture.
height -- height of the texture.
depth -- depth of the texture.

Code Example

This creates a Data3DTexture with repeating data, 0 to 255

// create a buffer with some data const sizeX = 64; const sizeY = 64; const sizeZ = 64; const data = new Uint8Array( sizeX * sizeY * sizeZ ); let i = 0; for ( let z = 0; z < sizeZ; z ++ ) { for ( let y = 0; y < sizeY; y ++ ) { for ( let x = 0; x < sizeX; x ++ ) { data[ i ] = i % 256; i ++; } } } // use the buffer to create the texture const texture = new THREE.Data3DTexture( data, sizeX, sizeY, sizeZ ); texture.needsUpdate = true;

Examples

WebGL / texture3d
WebGL / texture3d / partialupdate
WebGL / volume / cloud
WebGL / volume / perlin

Properties

See the base Texture class for common properties.

.flipY : Boolean

Whether the texture is flipped along the Y axis when uploaded to the GPU. Default is false.

.generateMipmaps : Boolean

Whether to generate mipmaps (if possible) for the texture. Default is false.

.image : Image

Overridden with a record type holding data, width and height and depth.

.isData3DTexture : Boolean

Read-only flag to check if a given object is of type Data3DTexture.

.magFilter : number

How the texture is sampled when a texel covers more than one pixel. The default is THREE.NearestFilter, which uses the value of the closest texel.

See the texture constants page for details.

.minFilter : number

How the texture is sampled when a texel covers less than one pixel. The default is THREE.NearestFilter, which uses the value of the closest texel.

See the texture constants page for details.

.unpackAlignment : number

1 by default. Specifies the alignment requirements for the start of each pixel row in memory. The allowable values are 1 (byte-alignment), 2 (rows aligned to even-numbered bytes), 4 (word-alignment), and 8 (rows start on double-word boundaries). See glPixelStorei for more information.

.wrapR : number

This defines how the texture is wrapped in the depth direction.
The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping. See the texture constants page for details.

Methods

See the base Texture class for common methods.

Source

src/textures/Data3DTexture.js

Texture

DataArrayTexture

Creates an array of textures directly from raw data, width and height and depth.

Constructor

DataArrayTexture( data, width, height, depth )

The data argument must be an ArrayBufferView. The properties inherited from Texture are the default, except magFilter and minFilter default to THREE.NearestFilter. The properties flipY and generateMipmaps are initially set to false.

The interpretation of the data depends on type and format: If the type is THREE.UnsignedByteType, a Uint8Array will be useful for addressing the texel data. If the format is THREE.RGBAFormat, data needs four values for one texel; Red, Green, Blue and Alpha (typically the opacity).
For the packed types, THREE.UnsignedShort4444Type and THREE.UnsignedShort5551Type all color components of one texel can be addressed as bitfields within an integer element of a Uint16Array.
In order to use the types THREE.FloatType and THREE.HalfFloatType, the WebGL implementation must support the respective extensions OES_texture_float and OES_texture_half_float. In order to use THREE.LinearFilter for component-wise, bilinear interpolation of the texels based on these types, the WebGL extensions OES_texture_float_linear or OES_texture_half_float_linear must also be present.

Code Example

This creates a DataArrayTexture where each texture has a different color.

// create a buffer with color data const width = 512; const height = 512; const depth = 100; const size = width * height; const data = new Uint8Array( 4 * size * depth ); for ( let i = 0; i < depth; i ++ ) { const color = new THREE.Color( Math.random(), Math.random(), Math.random() ); const r = Math.floor( color.r * 255 ); const g = Math.floor( color.g * 255 ); const b = Math.floor( color.b * 255 ); for ( let j = 0; j < size; j ++ ) { const stride = ( i * size + j ) * 4; data[ stride ] = r; data[ stride + 1 ] = g; data[ stride + 2 ] = b; data[ stride + 3 ] = 255; } } // used the buffer to create a DataArrayTexture const texture = new THREE.DataArrayTexture( data, width, height, depth ); texture.needsUpdate = true;

Examples

WebGL / texture2darray
WebGL / rendertarget / texture2darray

Properties

See the base Texture class for common properties.

.flipY : Boolean

Whether the texture is flipped along the Y axis when uploaded to the GPU. Default is false.

.generateMipmaps : Boolean

Whether to generate mipmaps (if possible) for the texture. Default is false.

.image : Object

Overridden with a object holding data, width, height, and depth.

.isDataArrayTexture : Boolean

Read-only flag to check if a given object is of type DataArrayTexture.

.magFilter : number

How the texture is sampled when a texel covers more than one pixel. The default is THREE.NearestFilter, which uses the value of the closest texel.

See the texture constants page for details.

.minFilter : number

How the texture is sampled when a texel covers less than one pixel. The default is THREE.NearestFilter, which uses the value of the closest texel.

See the texture constants page for details.

.unpackAlignment : number

1 by default. Specifies the alignment requirements for the start of each pixel row in memory. The allowable values are 1 (byte-alignment), 2 (rows aligned to even-numbered bytes), 4 (word-alignment), and 8 (rows start on double-word boundaries). See glPixelStorei for more information.

.wrapR : number

This defines how the texture is wrapped in the depth direction.
The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping. See the texture constants page for details.

.layerUpdates : Set

A set of all layers which need to be updated in the texture. See addLayerUpdate.

Methods

.addLayerUpdate ( layerIndex ) : addLayerUpdate

Describes that a specific layer of the texture needs to be updated. Normally when needsUpdate is set to true, the entire compressed texture array is sent to the GPU. Marking specific layers will only transmit subsets of all mipmaps associated with a specific depth in the array which is often much more performant.

.clearLayerUpdates () : clearLayerUpdates

Resets the layer updates registry. See addLayerUpdate.

See the base Texture class for common methods.

Source

src/textures/DataArrayTexture.js

Texture

DataTexture

Creates a texture directly from raw data, width and height.

Constructor

DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace )

The data argument must be an ArrayBufferView. Further parameters correspond to the properties inherited from Texture, where both magFilter and minFilter default to THREE.NearestFilter.

The interpretation of the data depends on type and format: If the type is THREE.UnsignedByteType, a Uint8Array will be useful for addressing the texel data. If the format is THREE.RGBAFormat, data needs four values for one texel; Red, Green, Blue and Alpha (typically the opacity).
For the packed types, THREE.UnsignedShort4444Type and THREE.UnsignedShort5551Type all color components of one texel can be addressed as bitfields within an integer element of a Uint16Array.
In order to use the types THREE.FloatType and THREE.HalfFloatType, the WebGL implementation must support the respective extensions OES_texture_float and OES_texture_half_float. In order to use THREE.LinearFilter for component-wise, bilinear interpolation of the texels based on these types, the WebGL extensions OES_texture_float_linear or OES_texture_half_float_linear must also be present.

Code Example

// create a buffer with color data const width = 512; const height = 512; const size = width * height; const data = new Uint8Array( 4 * size ); const color = new THREE.Color( 0xffffff ); const r = Math.floor( color.r * 255 ); const g = Math.floor( color.g * 255 ); const b = Math.floor( color.b * 255 ); for ( let i = 0; i < size; i ++ ) { const stride = i * 4; data[ stride ] = r; data[ stride + 1 ] = g; data[ stride + 2 ] = b; data[ stride + 3 ] = 255; } // used the buffer to create a DataTexture const texture = new THREE.DataTexture( data, width, height ); texture.needsUpdate = true;

Properties

See the base Texture class for common properties.

.flipY : Boolean

If set to true, the texture is flipped along the vertical axis when uploaded to the GPU. Default is false.

.generateMipmaps : Boolean

Whether to generate mipmaps (if possible) for a texture. False by default.

.image : Object

Overridden with a object holding data, width, and height.

.isDataTexture : Boolean

Read-only flag to check if a given object is of type DataTexture.

.unpackAlignment : number

1 by default. Specifies the alignment requirements for the start of each pixel row in memory. The allowable values are 1 (byte-alignment), 2 (rows aligned to even-numbered bytes), 4 (word-alignment), and 8 (rows start on double-word boundaries). See glPixelStorei for more information.

Methods

See the base Texture class for common methods.

Source

src/textures/DataTexture.js

Texture

DepthTexture

This class can be used to automatically save the depth information of a rendering into a texture.

Examples

depth / texture

Constructor

DepthTexture( width : Number, height : Number, type : Constant, mapping : Constant, wrapS : Constant, wrapT : Constant, magFilter : Constant, minFilter : Constant, anisotropy : Number, format : Constant )

width -- width of the texture.
height -- height of the texture.
type -- Default is THREE.UnsignedIntType. See DepthTexture.type for other choices.
mapping -- See mapping mode constants for details.
wrapS -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
wrapT -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is THREE.NearestFilter. See magnification filter constants for other choices.
minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is THREE.NearestFilter. See minification filter constants for other choices.
anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.
format -- must be either DepthFormat (default) or DepthStencilFormat. See format constants for details.

Properties

See the base Texture class for common properties - the following are also part of the texture class, but have different defaults here.

format

Either DepthFormat (default) or DepthStencilFormat. See format constants for details.

type

Default is THREE.UnsignedIntType. The following are options and how they map to internal gl depth format types depending on the stencil format, as well: THREE.UnsignedIntType -- Uses DEPTH_COMPONENT24 or DEPTH24_STENCIL8 internally.
THREE.FloatType -- Uses DEPTH_COMPONENT32F or DEPTH32F_STENCIL8 internally.
THREE.UnsignedShortType -- Uses DEPTH_COMPONENT16 internally. Stencil buffer is unsupported when using this type.

magFilter

How the texture is sampled when a texel covers more than one pixel. The default is THREE.NearestFilter. See magnification filter constants for other choices.

minFilter

How the texture is sampled when a texel covers less than one pixel. The default is THREE.NearestFilter. See magnification filter constants for other choices.

flipY

Depth textures do not need to be flipped so this is false by default.

.generateMipmaps

Depth textures do not use mipmaps.

.isDepthTexture : Boolean

Read-only flag to check if a given object is of type DepthTexture.

.compareFunction : number

This is used to define the comparison function used when comparing texels in the depth texture to the value in the depth buffer. Default is null which means comparison is disabled.

See the texture constants page for details of other functions.

Methods

See the base Texture class for common methods.

Source

src/textures/DepthTexture.js

Texture

FramebufferTexture

This class can only be used in combination with WebGLRenderer.copyFramebufferToTexture().

const pixelRatio = window.devicePixelRatio; const textureSize = 128 * pixelRatio; // instantiate a framebuffer texture const frameTexture = new FramebufferTexture( textureSize, textureSize ); // calculate start position for copying part of the frame data const vector = new Vector2(); vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 ); vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 ); // render the scene renderer.clear(); renderer.render( scene, camera ); // copy part of the rendered frame into the framebuffer texture renderer.copyFramebufferToTexture( frameTexture, vector );

Examples

webgl_framebuffer_texture

Constructor

FramebufferTexture( width : Number, height : Number )

width -- The width of the texture.
height -- The height of the texture.

Properties

See the base Texture class for common properties.

.generateMipmaps : Boolean

Whether to generate mipmaps for the FramebufferTexture. Default value is false.

.isFramebufferTexture : Boolean

Read-only flag to check if a given object is of type FramebufferTexture.

.magFilter : number

How the texture is sampled when a texel covers more than one pixel. The default is THREE.NearestFilter, which uses the value of the closest texel.

See texture constants for details.

.minFilter : number

How the texture is sampled when a texel covers less than one pixel. The default is THREE.NearestFilter, which uses the value of the closest texel.

See texture constants for details.

.needsUpdate : Boolean

True by default. This is required so that the canvas data is loaded.

Methods

See the base Texture class for common methods.

Source

src/textures/FramebufferTexture.js

Source

Represents the data source of a texture.

Constructor

Source( data : Any )

data -- The data definition of a texture. Default is null.

Properties

.data : Any

The actual data of a texture. The type of this property depends on the texture that uses this instance.

.isSource : Boolean

Read-only flag to check if a given object is of type Source.

.needsUpdate : Boolean

When the property is set to true, the engine allocates the memory for the texture (if necessary) and triggers the actual texture upload to the GPU next time the source is used.

.dataReady : Boolean

This property is only relevant when .needUpdate is set to true and provides more control on how texture data should be processed. When dataReady is set to false, the engine performs the memory allocation (if necessary) but does not transfer the data into the GPU memory. Default is true.

.uuid : String

UUID of this object instance. This gets automatically assigned, so this shouldn't be edited.

.version : Integer

This starts at 0 and counts how many times .needsUpdate is set to true.

Methods

.toJSON ( meta : Object ) : Object

meta -- optional object containing metadata.
Convert the data source to three.js JSON Object/Scene format.

Source

src/textures/Source.js

Texture

Create a texture to apply to a surface or as a reflection or refraction map.

Note: After the initial use of a texture, its dimensions, format, and type cannot be changed. Instead, call .dispose() on the texture and instantiate a new one.

Code Example

// load a texture, set wrap mode to repeat const texture = new THREE.TextureLoader().load( "textures/water.jpg" ); texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set( 4, 4 );

Constructor

Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace )

Properties

.id : Integer

Readonly - unique number for this texture instance.

.isTexture : Boolean

Read-only flag to check if a given object is of type Texture.

.uuid : String

UUID of this object instance. This gets automatically assigned, so this shouldn't be edited.

.name : String

Optional name of the object (doesn't need to be unique). Default is an empty string.

.image : Image

An image object, typically created using the TextureLoader.load method. This can be any image (e.g., PNG, JPG, GIF, DDS) or video (e.g., MP4, OGG/OGV) type supported by three.js.

To use video as a texture you need to have a playing HTML5 video element as a source for your texture image and continuously update this texture as long as video is playing - the VideoTexture class handles this automatically.

.mipmaps : Array

Array of user-specified mipmaps (optional).

.mapping : number

How the image is applied to the object. An object type of THREE.UVMapping is the default, where the U,V coordinates are used to apply the map.
See the texture constants page for other mapping types.

.channel : Integer

Lets you select the uv attribute to map the texture to. 0 for uv, 1 for uv1, 2 for uv2 and 3 for uv3.

.wrapS : number

This defines how the texture is wrapped horizontally and corresponds to U in UV mapping.
The default is THREE.ClampToEdgeWrapping, where the edge is clamped to the outer edge texels. The other two choices are THREE.RepeatWrapping and THREE.MirroredRepeatWrapping. See the texture constants page for details.

.wrapT : number

This defines how the texture is wrapped vertically and corresponds to V in UV mapping.
The same choices are available as for .wrapS : number.

NOTE: tiling of images in textures only functions if image dimensions are powers of two (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, ...) in terms of pixels. Individual dimensions need not be equal, but each must be a power of two. This is a limitation of WebGL, not three.js.

.magFilter : number

How the texture is sampled when a texel covers more than one pixel. The default is THREE.LinearFilter, which takes the four closest texels and bilinearly interpolates among them. The other option is THREE.NearestFilter, which uses the value of the closest texel.
See the texture constants page for details.

.minFilter : number

How the texture is sampled when a texel covers less than one pixel. The default is THREE.LinearMipmapLinearFilter, which uses mipmapping and a trilinear filter.

See the texture constants page for all possible choices.

.anisotropy : number

The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.capabilities.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.

.format : number

The default is THREE.RGBAFormat.

See the texture constants page for details of other formats.

.internalFormat : String

The default value is obtained using a combination of .format and .type.
The GPU format allows the developer to specify how the data is going to be stored on the GPU.

See the texture constants page for details regarding all supported internal formats.

.type : number

This must correspond to the .format. The default is THREE.UnsignedByteType, which will be used for most texture formats.

See the texture constants page for details of other formats.

.offset : Vector2

How much a single repetition of the texture is offset from the beginning, in each direction U and V. Typical range is 0.0 to 1.0.

.repeat : Vector2

How many times the texture is repeated across the surface, in each direction U and V. If repeat is set greater than 1 in either direction, the corresponding Wrap parameter should also be set to THREE.RepeatWrapping or THREE.MirroredRepeatWrapping to achieve the desired tiling effect.

.rotation : number

How much the texture is rotated around the center point, in radians. Positive values are counter-clockwise. Default is 0.

.center : Vector2

The point around which rotation occurs. A value of (0.5, 0.5) corresponds to the center of the texture. Default is (0, 0), the lower left.

.matrixAutoUpdate : Boolean

Whether to update the texture's uv-transform .matrix from the texture properties .offset, .repeat, .rotation, and .center. True by default. Set this to false if you are specifying the uv-transform matrix directly.

.matrix : Matrix3

The uv-transform matrix for the texture. Updated by the renderer from the texture properties .offset, .repeat, .rotation, and .center when the texture's .matrixAutoUpdate property is true. When .matrixAutoUpdate property is false, this matrix may be set manually. Default is the identity matrix.

.generateMipmaps : Boolean

Whether to generate mipmaps (if possible) for a texture. True by default. Set this to false if you are creating mipmaps manually.

.premultiplyAlpha : Boolean

If set to true, the alpha channel, if present, is multiplied into the color channels when the texture is uploaded to the GPU. Default is false.

Note that this property has no effect for ImageBitmap. You need to configure on bitmap creation instead. See ImageBitmapLoader.

.flipY : Boolean

If set to true, the texture is flipped along the vertical axis when uploaded to the GPU. Default is true.

Note that this property has no effect for ImageBitmap. You need to configure on bitmap creation instead. See ImageBitmapLoader.

.unpackAlignment : number

4 by default. Specifies the alignment requirements for the start of each pixel row in memory. The allowable values are 1 (byte-alignment), 2 (rows aligned to even-numbered bytes), 4 (word-alignment), and 8 (rows start on double-word boundaries). See glPixelStorei for more information.

.colorSpace : string

THREE.NoColorSpace is the default. Textures containing color data should be annotated with THREE.SRGBColorSpace or THREE.LinearSRGBColorSpace.

.version : Integer

This starts at 0 and counts how many times .needsUpdate is set to true.

.onUpdate : Function

A callback function, called when the texture is updated (e.g., when needsUpdate has been set to true and then the texture is used).

.needsUpdate : Boolean

Set this to true to trigger an update next time the texture is used. Particularly important for setting the wrap mode.

.userData : Object

An object that can be used to store custom data about the texture. It should not hold references to functions as these will not be cloned. Default is an empty object {}.

.source : Source

The data definition of a texture. A reference to the data source can be shared across textures. This is often useful in context of spritesheets where multiple textures render the same data but with different texture transformations.

Methods

EventDispatcher methods are available on this class.

.updateMatrix () : undefined

Update the texture's uv-transform .matrix from the texture properties .offset, .repeat, .rotation, and .center.

.clone () : Texture

Make copy of the texture. Note this is not a "deep copy", the image is shared. Besides, cloning a texture does not automatically mark it for a texture upload. You have to set .needsUpdate to true as soon as its image property (the data source) is fully loaded or ready.

.toJSON ( meta : Object ) : Object

meta -- optional object containing metadata.
Convert the texture to three.js JSON Object/Scene format.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.transformUv ( uv : Vector2 ) : Vector2

Transform the uv based on the value of this texture's .offset, .repeat, .wrapS, .wrapT and .flipY properties.

Source

src/textures/Texture.js

Texture

VideoTexture

Creates a texture for use with a video.

Note: After the initial use of a texture, the video cannot be changed. Instead, call .dispose() on the texture and instantiate a new one.

Code Example

// assuming you have created a HTML video element with id="video" const video = document.getElementById( 'video' ); const texture = new THREE.VideoTexture( video );

Examples

materials / video
materials / video / webcam
video / kinect
video / panorama / equirectangular
vr / video

Constructor

VideoTexture( video : Video, mapping : Constant, wrapS : Constant, wrapT : Constant, magFilter : Constant, minFilter : Constant, format : Constant, type : Constant, anisotropy : Number )

video -- The video element to use as the texture.
mapping -- How the image is applied to the object. An object type of THREE.UVMapping. See mapping constants for other choices.
wrapS -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
wrapT -- The default is THREE.ClampToEdgeWrapping. See wrap mode constants for other choices.
magFilter -- How the texture is sampled when a texel covers more than one pixel. The default is THREE.LinearFilter. See magnification filter constants for other choices.
minFilter -- How the texture is sampled when a texel covers less than one pixel. The default is THREE.LinearFilter. See minification filter constants for other choices.
format -- The default is THREE.RGBAFormat. See format constants for other choices.
type -- Default is THREE.UnsignedByteType. See type constants for other choices.
anisotropy -- The number of samples taken along the axis through the pixel that has the highest density of texels. By default, this value is 1. A higher value gives a less blurry result than a basic mipmap, at the cost of more texture samples being used. Use renderer.getMaxAnisotropy() to find the maximum valid anisotropy value for the GPU; this value is usually a power of 2.

Properties

See the base Texture class for common properties.

.generateMipmaps : Boolean

Whether to generate mipmaps. false by default.

.isVideoTexture : Boolean

Read-only flag to check if a given object is of type VideoTexture.

.needsUpdate : Boolean

You will not need to set this manually here as it is handled by the update() method.

Methods

See the base Texture class for common methods.

.update () : undefined

This is called automatically and sets .needsUpdate to true every time a new frame is available.

Source

src/textures/VideoTexture.js

CCDIKSolver

A solver for IK with CCD Algorithm.

CCDIKSolver solves Inverse Kinematics Problem with CCD Algorithm. CCDIKSolver is designed to work with SkinnedMesh but also can be used with MMDLoader or GLTFLoader skeleton.

Import

CCDIKSolver is an add-on, and must be imported explicitly. See Installation / Addons.

import { CCDIKSolver } from 'three/addons/animation/CCDIKSolver.js';

Code Example

let ikSolver; // // Bones hierarchy: // // root // ├── bone0 // │ └── bone1 // │ └── bone2 // │ └── bone3 // └── target // // Positioned as follow on the cylinder: // // o <- target (y = 20) // // +----o----+ <- bone3 (y = 12) // | | // | o | <- bone2 (y = 4) // | | // | o | <- bone1 (y = -4) // | | // +----oo---+ <- root, bone0 (y = -12) // let bones = [] // "root" let rootBone = new Bone(); rootBone.position.y = -12; bones.push( rootBone ); // "bone0" let prevBone = new Bone(); prevBone.position.y = 0; rootBone.add( prevBone ); bones.push( prevBone ); // "bone1", "bone2", "bone3" for ( let i = 1; i <= 3; i ++ ) { const bone = new Bone(); bone.position.y = 8; bones.push( bone ); prevBone.add( bone ); prevBone = bone; } // "target" const targetBone = new Bone(); targetBone.position.y = 24 + 8 rootBone.add( targetBone ); bones.push( targetBone ); // // skinned mesh // const mesh = new SkinnedMesh( geometry, material ); const skeleton = new Skeleton( bones ); mesh.add( bones[ 0 ] ); // "root" bone mesh.bind( skeleton ); // // ikSolver // const iks = [ { target: 5, // "target" effector: 4, // "bone3" links: [ { index: 3 }, { index: 2 }, { index: 1 } ] // "bone2", "bone1", "bone0" } ]; ikSolver = new CCDIKSolver( mesh, iks ); function render() { ikSolver?.update(); renderer.render( scene, camera ); }

Examples

webgl_animation_skinning_ik
webgl_loader_mmd
webgl_loader_mmd_pose
webgl_loader_mmd_audio

Constructor

CCDIKSolver( mesh : SkinnedMesh, iks : Array )

meshSkinnedMesh for which CCDIKSolver solves IK problem.
iks — An array of Object specifying IK parameter. target, effector, and link-index are index integers in .skeleton.bones. The bones relation should be "links[ n ], links[ n - 1 ], ..., links[ 0 ], effector" in order from parent to child.

Creates a new CCDIKSolver.

Properties

.iks : Array

An array of IK parameter passed to the constructor.

.mesh : SkinnedMesh

SkinnedMesh passed to the constructor.

Methods

.createHelper () : CCDIKHelper

Return CCDIKHelper. You can visualize IK bones by adding the helper to scene.

.update () : this

Update IK bones quaternion by solving CCD algorithm.

.updateOne ( ikParam : Object ) : this

Update an IK bone quaternion by solving CCD algorithm.

Source

examples/jsm/animation/CCDIKSolver.js

MMDAnimationHelper

A animation helper for MMD resources.

MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader with MMD special features as IK, Grant, and Physics. It uses CCDIKSolver and MMDPhysics inside.

Import

MMDAnimationHelper is an add-on, and must be imported explicitly. See Installation / Addons.

import { MMDAnimationHelper } from 'three/addons/animation/MMDAnimationHelper.js';

Code Example

// Instantiate a helper const helper = new MMDAnimationHelper(); // Load MMD resources and add to helper new MMDLoader().loadWithAnimation( 'models/mmd/miku.pmd', 'models/mmd/dance.vmd', function ( mmd ) { helper.add( mmd.mesh, { animation: mmd.animation, physics: true } ); scene.add( mmd.mesh ); new THREE.AudioLoader().load( 'audios/mmd/song.mp3', function ( buffer ) { const listener = new THREE.AudioListener(); const audio = new THREE.Audio( listener ).setBuffer( buffer ); listener.position.z = 1; scene.add( audio ); scene.add( listener ); } ); } ); function render() { helper.update( clock.getDelta() ); renderer.render( scene, camera ); }

Examples

webgl_loader_mmd
webgl_loader_mmd_pose
webgl_loader_mmd_audio

Constructor

MMDAnimationHelper( params : Object )

params — (optional)

Creates a new MMDAnimationHelper.

Properties

.audio : Audio

An Audio added to helper.

.camera : Camera

An Camera added to helper.

.meshes : Array

An array of SkinnedMesh added to helper.

.objects : WeakMap

A WeakMap which holds animation stuffs used in helper for objects added to helper. For example, you can access AnimationMixer for an added SkinnedMesh with "helper.objects.get( mesh ).mixer"

.onBeforePhysics : Function

An optional callback that is executed immediately before the physics calculation for an SkinnedMesh. This function is called with the SkinnedMesh.

Methods

.add ( object : Object3D, params : Object ) : MMDAnimationHelper

objectSkinnedMesh, Camera, or Audio
params — (optional)

Add an SkinnedMesh, Camera, or Audio to helper and setup animation. The animation durations of added objects are synched. If camera/audio has already been added, it'll be replaced with a new one.

.enable ( key : String, enabled : Boolean ) : MMDAnimationHelper

key — Allowed strings are 'animation', 'ik', 'grant', 'physics', and 'cameraAnimation'.
enabled — true is enable, false is disable

Enable/Disable an animation feature

.pose ( mesh : SkinnedMesh, vpd : Object, params : Object ) : MMDAnimationHelper

meshSkinnedMesh which changes the posing. It doesn't need to be added to helper.
vpd — VPD content obtained by MMDLoader.loadVPD
params — (optional)

Changes the posing of SkinnedMesh as VPD content specifies.

.remove ( object : Object3D ) : MMDAnimationHelper

objectSkinnedMesh, Camera, or Audio

Remove an SkinnedMesh, Camera, or Audio from helper.

.update ( delta : Number ) : MMDAnimationHelper

delta — number in second

Advance mixer time and update the animations of objects added to helper

Source

examples/jsm/animation/MMDAnimationHelper.js

MMDPhysics

A Physics handler for MMD resources.

MMDPhysics calculates Physics for model loaded by MMDLoader with ammo.js (Bullet-based JavaScript Physics engine).

Import

MMDPhysics is an add-on, and must be imported explicitly. See Installation / Addons.

import { MMDPhysics } from 'three/addons/animation/MMDPhysics.js';

Code Example

let physics; // Load MMD resources and instantiate MMDPhysics new MMDLoader().load( 'models/mmd/miku.pmd', function ( mesh ) { physics = new MMDPhysics( mesh ) scene.add( mesh ); } ); function render() { const delta = clock.getDelta(); animate( delta ); // update bones if ( physics !== undefined ) physics.update( delta ); renderer.render( scene, camera ); }

Examples

webgl_loader_mmd
webgl_loader_mmd_audio

Constructor

MMDPhysics( mesh : SkinnedMesh, rigidBodyParams : Array, constraintParams : Array, params : Object )

meshSkinnedMesh for which MMDPhysics calculates Physics.
rigidBodyParams — An array of Object specifying Rigid Body parameters.
constraintParams — (optional) An array of Object specifying Constraint parameters.
params — (optional)

Creates a new MMDPhysics.

Properties

.mesh : Array

SkinnedMesh passed to the constructor.

Methods

.createHelper () : MMDPhysicsHelper

Return MMDPhysicsHelper. You can visualize Rigid bodies by adding the helper to scene.

.reset () : this

Resets Rigid bodies transform to current bone's.

.setGravity ( gravity : Vector3 ) : this

gravity — Direction and volume of gravity.

Set gravity.

.update ( delta : Number ) : this

delta — Time in second.

Advance Physics calculation and updates bones.

.warmup ( cycles : Integer ) : this

delta — Time in second.

Warm up Rigid bodies. Calculates cycles steps.

Source

examples/jsm/animation/MMDPhysics.js

Controls

ArcballControls

Arcball controls allow the camera to be controlled by a virtual trackball with full touch support and advanced navigation functionality.
Cursor/finger positions and movements are mapped over a virtual trackball surface represented by a gizmo and mapped in intuitive and consistent camera movements. Dragging cursor/fingers will cause camera to orbit around the center of the trackball in a conservative way (returning to the starting point will make the camera to return to its starting orientation).

In addition to supporting pan, zoom and pinch gestures, Arcball controls provide focus functionality with a double click/tap for intuitively moving the object's point of interest in the center of the virtual trackball. Focus allows a much better inspection and navigation in complex environment. Moreover Arcball controls allow FOV manipulation (in a vertigo-style method) and z-rotation. Saving and restoring of Camera State is supported also through clipboard (use ctrl+c and ctrl+v shortcuts for copy and paste the state).

Unlike OrbitControls and TrackballControls, ArcballControls doesn't require .update to be called externally in an animation loop when animations are on.

To use this, as with all files in the /examples directory, you will have to include the file separately in your HTML.

Import

ArcballControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { ArcballControls } from 'three/addons/controls/ArcballControls.js';

Code Example

const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); const controls = new ArcballControls( camera, renderer.domElement, scene ); controls.addEventListener( 'change', function () { renderer.render( scene, camera ); } ); //controls.update() must be called after any manual changes to the camera's transform camera.position.set( 0, 20, 100 ); controls.update();

Examples

misc / controls / arcball

Constructor

ArcballControls( camera : Camera, domElement : HTMLDOMElement, scene : Scene )

camera: (required) The camera to be controlled. The camera must not be a child of another object, unless that object is the scene itself.

domElement: The HTML element used for event listeners. (optional)

scene: The scene rendered by the camera. If not given, gizmos cannot be shown. (optional)

Events

change

Fires when the camera has been transformed by the controls.

start

Fires when an interaction was initiated.

end

Fires when an interaction has finished.

Properties

See the base Controls class for common properties.

.adjustNearFar : Boolean

If true, camera's near and far values will be adjusted every time zoom is performed trying to maintain the same visible portion given by initial near and far values ( PerspectiveCamera only ). Default is false.

.camera : Camera

The camera being controlled.

.cursorZoom : Boolean

Set to true to make zoom become cursor centered.

.dampingFactor : Float

The damping inertia used if .enableAnimations is set to true.

.enableAnimations : Boolean

Set to true to enable animations for rotation (damping) and focus operation. Default is true.

.enableFocus : Boolean

Enable or disable camera focusing on double-tap (or click) operations. Default is true.

.enableGrid : Boolean

When set to true, a grid will appear when panning operation is being performed (desktop interaction only). Default is false.

.enablePan : Boolean

Enable or disable camera panning. Default is true.

.enableRotate : Boolean

Enable or disable camera rotation. Default is true.

.enableZoom : Boolean

Enable or disable zooming of the camera.

.focusAnimationTime : Float

Duration time of focus animation.

.maxDistance : Float

How far you can dolly out ( PerspectiveCamera only ). Default is Infinity.

.maxZoom : Float

How far you can zoom out ( OrthographicCamera only ). Default is Infinity.

.minDistance : Float

How far you can dolly in ( PerspectiveCamera only ). Default is 0.

.minZoom : Float

How far you can zoom in ( OrthographicCamera only ). Default is 0.

.radiusFactor : Float

The size of the gizmo relative to the screen width and height. Default is 0.67.

.rotateSpeed : Float

Speed of rotation. Default is 1.

.scaleFactor : Float

The scaling factor used when performing zoom operation.

.scene : Scene

The scene rendered by the camera.

.wMax : Float

Maximum angular velocity allowed on rotation animation start.

Methods

See the base Controls class for common methods.

.activateGizmos ( isActive : Boolean ) : undefined

Make gizmos more or less visible.

.copyState () : undefined

Copy the current state to clipboard (as a readable JSON text).

.pasteState () : undefined

Set the controls state from the clipboard, assumes that the clipboard stores a JSON text as saved from .copyState.

.reset () : undefined

Reset the controls to their state from either the last time the .saveState was called, or the initial state.

.saveState () : undefined

Save the current state of the controls. This can later be recovered with .reset.

.setCamera ( camera : Camera ) : undefined

Set the camera to be controlled. Must be called in order to set a new camera to be controlled.

.setGizmosVisible ( value : Boolean ) : undefined

Set the visible property of gizmos.

.setTbRadius ( value : Float ) : undefined

Update the radiusFactor value, redraw the gizmo and send a changeEvent to visualise the changes.

.setMouseAction ( operation : String, mouse, key ) : Boolean

Set a new mouse action by specifying the operation to be performed and a mouse/key combination. In case of conflict, replaces the existing one.

Operations can be specified as 'ROTATE', 'PAN', 'FOV' or 'ZOOM'.
Mouse inputs can be specified as mouse buttons 0, 1 and 2 or 'WHEEL' for wheel notches.
Keyboard modifiers can be specified as 'CTRL', 'SHIFT' or null if not needed.

.unsetMouseAction ( mouse, key ) : Boolean

Removes a mouse action by specifying its mouse/key combination.

Mouse inputs can be specified as mouse buttons 0, 1 and 2 or 'WHEEL' for wheel notches.
Keyboard modifiers can be specified as 'CTRL', 'SHIFT' or null if not needed.

.getRaycaster () : Raycaster

Returns the Raycaster object that is used for user interaction. This object is shared between all instances of ArcballControls. If you set the .layers property of the ArcballControls, you will also want to set the .layers property on the Raycaster with a matching value, or else the ArcballControls won't work as expected.

Source

examples/jsm/controls/ArcballControls.js

Controls

DragControls

This class can be used to provide a drag'n'drop interaction.

Import

DragControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { DragControls } from 'three/addons/controls/DragControls.js';

Code Example

const controls = new DragControls( objects, camera, renderer.domElement ); // add event listener to highlight dragged objects controls.addEventListener( 'dragstart', function ( event ) { event.object.material.emissive.set( 0xaaaaaa ); } ); controls.addEventListener( 'dragend', function ( event ) { event.object.material.emissive.set( 0x000000 ); } );

Examples

misc / controls / drag

Constructor

DragControls( objects : Array, camera : Camera, domElement : HTMLDOMElement )

objects: An array of draggable 3D objects.

camera: The camera of the rendered scene.

domElement: The HTML element used for event listeners. (optional)

Creates a new instance of DragControls.

Events

dragstart

Fires when the user starts to drag a 3D object.

drag

Fires when the user drags a 3D object.

dragend

Fires when the user has finished dragging a 3D object.

hoveron

Fires when the pointer is moved onto a 3D object, or onto one of its children.

hoveroff

Fires when the pointer is moved out of a 3D object.

Properties

See the base Controls class for common properties.

.objects : Array

An array of draggable 3D objects.

.raycaster : Raycaster

The internal raycaster used for detecting 3D objects.

.recursive : Boolean

Whether children of draggable objects can be dragged independently from their parent. Default is true.

.rotateSpeed : Float

The speed at which the object will rotate when dragged in rotate mode. The higher the number the faster the rotation. Default is 1.

.transformGroup : Boolean

This option only works if the DragControls.objects array contains a single draggable group object. If set to true, DragControls does not transform individual objects but the entire group. Default is false.

Methods

See the base Controls class for common methods.

Source

examples/jsm/controls/DragControls.js

Controls

FirstPersonControls

This class is an alternative implementation of FlyControls.

Import

FirstPersonControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { FirstPersonControls } from 'three/addons/controls/FirstPersonControls.js';

Examples

webgl / geometry / terrain

Constructor

FirstPersonControls( object : Camera, domElement : HTMLDOMElement )

object: The camera to be controlled.

domElement: The HTML element used for event listeners. (optional)

Creates a new instance of FirstPersonControls.

Properties

.activeLook : Boolean

Whether or not it's possible to look around. Default is true.

.autoForward : Boolean

Whether or not the camera is automatically moved forward. Default is false.

.constrainVertical : Boolean

Whether or not looking around is vertically constrained by [.verticalMin, .verticalMax]. Default is false.

.heightCoef : Number

Determines how much faster the camera moves when it's y-component is near .heightMax. Default is 1.

.heightMax : Number

Upper camera height limit used for movement speed adjustment. Default is 1.

.heightMin : Number

Lower camera height limit used for movement speed adjustment. Default is 0.

.heightSpeed : Boolean

Whether or not the camera's height influences the forward movement speed. Default is false. Use the properties .heightCoef, .heightMin and .heightMax for configuration.

.lookVertical : Boolean

Whether or not it's possible to vertically look around. Default is true.

.lookSpeed : Number

The look around speed. Default is 0.005.

.mouseDragOn : Boolean

Whether or not the mouse is pressed down. Read-only property.

.movementSpeed : Number

The movement speed. Default is 1.

.verticalMax : Number

How far you can vertically look around, upper limit. Range is 0 to Math.PI radians. Default is Math.PI.

.verticalMin : Number

How far you can vertically look around, lower limit. Range is 0 to Math.PI radians. Default is 0.

Methods

.handleResize () : undefined

Should be called if the application window is resized.

.lookAt ( vector : Vector3 ) : FirstPersonControls
.lookAt ( x : Float, y : Float, z : Float ) : FirstPersonControls

vector - A vector representing the target position.

Optionally, the x, y, z components of the world space position.

Ensures the controls orient the camera towards the defined target position.

Source

examples/jsm/controls/FirstPersonControls.js

Controls

FlyControls

FlyControls enables a navigation similar to fly modes in DCC tools like Blender. You can arbitrarily transform the camera in 3D space without any limitations (e.g. focus on a specific target).

Import

FlyControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { FlyControls } from 'three/addons/controls/FlyControls.js';

Examples

misc / controls / fly

Constructor

FlyControls( object : Camera, domElement : HTMLDOMElement )

object: The camera to be controlled.

domElement: The HTML element used for event listeners. (optional)

Creates a new instance of FlyControls.

Events

change

Fires when the camera has been transformed by the controls.

Properties

See the base Controls class for common properties.

.autoForward : Boolean

If set to true, the camera automatically moves forward (and does not stop) when initially translated. Default is false.

.dragToLook : Boolean

If set to true, you can only look around by performing a drag interaction. Default is false.

.movementSpeed : Number

The movement speed. Default is 1.

.rollSpeed : Number

The rotation speed. Default is 0.005.

Methods

See the base Controls class for common methods.

Source

examples/jsm/controls/FlyControls.js

OrbitControls

MapControls

MapControls is intended for transforming a camera over a map from bird's eye perspective. The class shares its implementation with OrbitControls but uses a specific preset for mouse/touch interaction and disables screen space panning by default.

Import

MapControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { MapControls } from 'three/addons/controls/MapControls.js';

Code Example

const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); camera.position.set( 0, 20, 100 ); const controls = new MapControls( camera, renderer.domElement ); controls.enableDamping = true; function animate() { requestAnimationFrame( animate ); // required if controls.enableDamping or controls.autoRotate are set to true controls.update(); renderer.render( scene, camera ); }

Examples

misc / controls / map

Constructor

MapControls( object : Camera, domElement : HTMLDOMElement )

object: (required) The camera to be controlled. The camera must not be a child of another object, unless that object is the scene itself.

domElement: The HTML element used for event listeners.

Events

See the base OrbitControls class for common events.

Properties

See the base OrbitControls class for common properties.

.mouseButtons : Object

This object contains references to the mouse actions used by the controls. controls.mouseButtons = { LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.ROTATE }

.screenSpacePanning : Boolean

Defines how the camera's position is translated when panning. If true, the camera pans in screen space. Otherwise, the camera pans in the plane orthogonal to the camera's up direction. Default is false.

.touches : Object

This object contains references to the touch actions used by the controls. controls.touches = { ONE: THREE.TOUCH.PAN, TWO: THREE.TOUCH.DOLLY_ROTATE }

Methods

See the base OrbitControls class for common methods.

Source

examples/jsm/controls/MapControls.js

Controls

OrbitControls

Orbit controls allow the camera to orbit around a target.
To use this, as with all files in the /examples directory, you will have to include the file separately in your HTML.

Import

OrbitControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

Code Example

const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); const controls = new OrbitControls( camera, renderer.domElement ); //controls.update() must be called after any manual changes to the camera's transform camera.position.set( 0, 20, 100 ); controls.update(); function animate() { requestAnimationFrame( animate ); // required if controls.enableDamping or controls.autoRotate are set to true controls.update(); renderer.render( scene, camera ); }

Examples

misc / controls / orbit

Constructor

OrbitControls( object : Camera, domElement : HTMLDOMElement )

object: (required) The camera to be controlled. The camera must not be a child of another object, unless that object is the scene itself.

domElement: The HTML element used for event listeners. (optional)

Events

change

Fires when the camera has been transformed by the controls.

start

Fires when an interaction was initiated.

end

Fires when an interaction has finished.

Properties

See the base Controls class for common properties.

.autoRotate : Boolean

Set to true to automatically rotate around the target.
Note that if this is enabled, you must call .update () in your animation loop. If you want the auto-rotate speed to be independent of the frame rate (the refresh rate of the display), you must pass the time deltaTime, in seconds, to .update().

.autoRotateSpeed : Float

How fast to rotate around the target if .autoRotate is true. Default is 2.0, which equates to 30 seconds per orbit at 60fps.
Note that if .autoRotate is enabled, you must call .update () in your animation loop.

.dampingFactor : Float

The damping inertia used if .enableDamping is set to true. Default is 0.05.
Note that for this to work, you must call .update () in your animation loop.

.enableDamping : Boolean

Set to true to enable damping (inertia), which can be used to give a sense of weight to the controls. Default is false.
Note that if this is enabled, you must call .update () in your animation loop.

.enablePan : Boolean

Enable or disable camera panning. Default is true.

.enableRotate : Boolean

Enable or disable horizontal and vertical rotation of the camera. Default is true.
Note that it is possible to disable a single axis by setting the min and max of the polar angle or azimuth angle to the same value, which will cause the vertical or horizontal rotation to be fixed at that value.

.enableZoom : Boolean

Enable or disable zooming (dollying) of the camera.

.keyPanSpeed : Float

How fast to pan the camera when the keyboard is used. Default is 7.0 pixels per keypress.

.keys : Object

This object contains references to the keycodes for controlling camera panning. Default is the 4 arrow keys. controls.keys = { LEFT: 'ArrowLeft', //left arrow UP: 'ArrowUp', // up arrow RIGHT: 'ArrowRight', // right arrow BOTTOM: 'ArrowDown' // down arrow } See KeyboardEvent.code for a full list of keycodes.

.maxAzimuthAngle : Float

How far you can orbit horizontally, upper limit. If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ). Default is Infinity.

.maxDistance : Float

How far you can dolly out ( PerspectiveCamera only ). Default is Infinity.

.maxPolarAngle : Float

How far you can orbit vertically, upper limit. Range is 0 to Math.PI radians, and default is Math.PI.

.maxZoom : Float

How far you can zoom out ( OrthographicCamera only ). Default is Infinity.

.minTargetRadius : Float

How close you can get the target to the 3D .cursor. Default is 0.

.maxTargetRadius : Float

How far you can move the target from the 3D .cursor. Default is Infinity.

.minAzimuthAngle : Float

How far you can orbit horizontally, lower limit. If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ). Default is Infinity.

.minDistance : Float

How far you can dolly in ( PerspectiveCamera only ). Default is 0.

.minPolarAngle : Float

How far you can orbit vertically, lower limit. Range is 0 to Math.PI radians, and default is 0.

.minZoom : Float

How far you can zoom in ( OrthographicCamera only ). Default is 0.

.mouseButtons : Object

This object contains references to the mouse actions used by the controls. controls.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN }

.panSpeed : Float

Speed of panning. Default is 1.

.position0 : Vector3

Used internally by the .saveState and .reset methods.

.rotateSpeed : Float

Speed of rotation. Default is 1.

.screenSpacePanning : Boolean

Defines how the camera's position is translated when panning. If true, the camera pans in screen space. Otherwise, the camera pans in the plane orthogonal to the camera's up direction. Default is true.

.target0 : Vector3

Used internally by the .saveState and .reset methods.

.target : Vector3

The focus point of the controls, the .object orbits around this. It can be updated manually at any point to change the focus of the controls.

.cursor : Vector3

The focus point of the .minTargetRadius and .maxTargetRadius limits. It can be updated manually at any point to change the center of interest for the .target.

.touches : Object

This object contains references to the touch actions used by the controls. controls.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN }

.zoom0 : Float

Used internally by the .saveState and .reset methods.

.zoomSpeed : Float

Speed of zooming / dollying. Default is 1.

.zoomToCursor : Boolean

Setting this property to true allows to zoom to the cursor's position. Default is false.

Methods

See the base Controls class for common methods.

.getAzimuthalAngle () : radians

Get the current horizontal rotation, in radians.

.getPolarAngle () : radians

Get the current vertical rotation, in radians.

.getDistance () : Float

Returns the distance from the camera to the target.

.listenToKeyEvents ( domElement : HTMLDOMElement ) : undefined

Adds key event listeners to the given DOM element. window is a recommended argument for using this method.

.reset () : undefined

Reset the controls to their state from either the last time the .saveState was called, or the initial state.

.saveState () : undefined

Save the current state of the controls. This can later be recovered with .reset.

.stopListenToKeyEvents () : undefined

Removes the key event listener previously defined with .listenToKeyEvents().

.update ( deltaTime : Number ) : Boolean

Update the controls. Must be called after any manual changes to the camera's transform, or in the update loop if .autoRotate or .enableDamping are set. deltaTime, in seconds, is optional, and is only required if you want the auto-rotate speed to be independent of the frame rate (the refresh rate of the display).

Source

examples/jsm/controls/OrbitControls.js

Controls

PointerLockControls

The implementation of this class is based on the Pointer Lock API. PointerLockControls is a perfect choice for first person 3D games.

Import

PointerLockControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js';

Code Example

const controls = new PointerLockControls( camera, document.body ); // add event listener to show/hide a UI (e.g. the game's menu) controls.addEventListener( 'lock', function () { menu.style.display = 'none'; } ); controls.addEventListener( 'unlock', function () { menu.style.display = 'block'; } );

Examples

misc / controls / pointerlock

Constructor

PointerLockControls( camera : Camera, domElement : HTMLDOMElement )

camera: The camera of the rendered scene.

domElement: The HTML element used for event listeners.

Creates a new instance of PointerLockControls.

Events

change

Fires when the user moves the mouse.

lock

Fires when the pointer lock status is "locked" (in other words: the mouse is captured).

unlock

Fires when the pointer lock status is "unlocked" (in other words: the mouse is not captured anymore).

Properties

See the base Controls class for common properties.

.isLocked : Boolean

Whether or not the controls are locked.

.maxPolarAngle : Float

Camera pitch, upper limit. Range is 0 to Math.PI radians. Default is Math.PI.

.minPolarAngle : Float

Camera pitch, lower limit. Range is 0 to Math.PI radians. Default is 0.

.pointerSpeed : Float

Multiplier for how much the pointer movement influences the camera rotation. Default is 1.

Methods

See the base Controls class for common methods.

.getDirection ( target : Vector3 ) : Vector3

target: The target vector.

Returns the look direction of the camera.

.lock () : undefined

Activates the pointer lock.

.moveForward ( distance : Number ) : undefined

distance: The signed distance.

Moves the camera forward parallel to the xz-plane. Assumes camera.up is y-up.

.moveRight ( distance : Number ) : undefined

distance: The signed distance.

Moves the camera sidewards parallel to the xz-plane.

.unlock () : undefined

Exits the pointer lock.

Source

examples/jsm/controls/PointerLockControls.js

Controls

TrackballControls

TrackballControls is similar to OrbitControls. However, it does not maintain a constant camera up vector. That means if the camera orbits over the “north” and “south” poles, it does not flip to stay "right side up".

Import

TrackballControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { TrackballControls } from 'three/addons/controls/TrackballControls.js';

Examples

misc / controls / trackball

Constructor

TrackballControls( camera : Camera, domElement : HTMLDOMElement )

camera: The camera of the rendered scene.

domElement: The HTML element used for event listeners. (optional)

Creates a new instance of TrackballControls.

Events

change

Fires when the camera has been transformed by the controls.

start

Fires when an interaction (e.g. touch) was initiated.

end

Fires when an interaction has finished.

Properties

See the base Controls class for common properties.

.dynamicDampingFactor : Number

Defines the intensity of damping. Only considered if staticMoving is set to false. Default is 0.2.

.keys : Array

KeyA, KeyS, KeyD

.maxDistance : Number

How far you can dolly out ( PerspectiveCamera only ). Default is Infinity.

.minDistance : Number

How far you can dolly in ( PerspectiveCamera only ). Default is 0.

.maxZoom : Float

How far you can zoom out ( OrthographicCamera only ). Default is Infinity.

.minZoom : Float

How far you can zoom in ( OrthographicCamera only ). Default is 0.

.mouseButtons : Object

.noPan : Boolean

Whether or not panning is disabled. Default is false.

.noRotate : Boolean

Whether or not rotation is disabled. Default is false.

.noZoom : Boolean

Whether or not zooming is disabled. Default is false.

.panSpeed : Number

The pan speed. Default is 0.3.

.rotateSpeed : Number

The rotation speed. Default is 1.0.

.screen : Object

handleResize

.staticMoving : Boolean

Whether or not damping is disabled. Default is false.

.target : Vector3

The focus point of the controls.

.zoomSpeed : Number

The zoom speed. Default is 1.2.

Methods

See the base Controls class for common methods.

.handleResize () : undefined

Should be called if the application window is resized.

.reset () : undefined

Resets the controls to its initial state.

Source

examples/jsm/controls/TrackballControls.js

Controls

TransformControls

This class can be 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.

TransformControls expects that its attached 3D object is part of the scene graph.

Import

TransformControls is an add-on, and must be imported explicitly. See Installation / Addons.

import { TransformControls } from 'three/addons/controls/TransformControls.js';

Examples

misc / controls / transform

Constructor

TransformControls( camera : Camera, domElement : HTMLDOMElement )

camera: The camera of the rendered scene.

domElement: The HTML element used for event listeners. (optional)

Creates a new instance of TransformControls.

Events

change

Fires if any type of change (object or property change) is performed. Property changes are separate events you can add event listeners to. The event type is "propertyname-changed".

mouseDown

Fires if a pointer (mouse/touch) becomes active.

mouseUp

Fires if a pointer (mouse/touch) is no longer active.

objectChange

Fires if the controlled 3D object is changed.

Properties

See the base Controls class for common properties.

.axis : String

The current transformation axis.

.camera : Camera

The camera of the rendered scene.

.dragging : Boolean

Whether or not dragging is currently performed. Read-only property.

.mode : String

The current transformation mode. Possible values are "translate", "rotate" and "scale". Default is translate.

.rotationSnap : Number

By default, 3D objects are continuously rotated. If you set this property to a numeric value (radians), you can define in which steps the 3D object should be rotated. Default is null.

.showX : Boolean

Whether or not the x-axis helper should be visible. Default is true.

.showY : Boolean

Whether or not the y-axis helper should be visible. Default is true.

.showZ : Boolean

Whether or not the z-axis helper should be visible. Default is true.

.size : Number

The size of the helper UI (axes/planes). Default is 1.

.space : String

Defines in which coordinate space transformations should be performed. Possible values are "world" and "local". Default is world.

.translationSnap : Number

By default, 3D objects are continuously translated. If you set this property to a numeric value (world units), you can define in which steps the 3D object should be translated. Default is null.

.minX : Number

The minimum allowed X position during translation. Default is -Infinity.

.maxX : Number

The maximum allowed X position during translation. Default is Infinity.

.minY : Number

The minimum allowed Y position during translation. Default is -Infinity.

.maxY : Number

The maximum allowed Y position during translation. Default is Infinity.

.minZ : Number

The minimum allowed Z position during translation. Default is -Infinity.

.maxZ : Number

The maximum allowed Z position during translation. Default is Infinity.

Methods

See the base Controls class for common methods.

.attach ( object : Object3D ) : TransformControls

object: The 3D object that should be transformed.

Sets the 3D object that should be transformed and ensures the controls UI is visible.

.detach () : TransformControls

Removes the current 3D object from the controls and makes the helper UI invisible.

.getHelper () : Object3D

Returns the visual representation of the controls. Add the helper to your scene to visually transform the attached 3D object.

.getRaycaster () : Raycaster

Returns the Raycaster object that is used for user interaction. This object is shared between all instances of TransformControls. If you set the .layers property of the TransformControls, you will also want to set the .layers property on the Raycaster with a matching value, or else the TransformControls won't work as expected.

.getMode () : String

Returns the transformation mode.

.reset () : undefined

Resets the object's position, rotation and scale to when the current transform began.

.setMode ( mode : String ) : undefined

mode: The transformation mode.

Sets the transformation mode.

.setRotationSnap ( rotationSnap : Number ) : undefined

rotationSnap: The rotation snap.

Sets the rotation snap.

.setScaleSnap ( scaleSnap : Number ) : undefined

scaleSnap: The scale snap.

Sets the scale snap.

.setSize ( size : Number ) : undefined

size: The size of the helper UI.

Sets the size of the helper UI.

.setSpace ( space : String ) : undefined

space: The coordinate space in which transformations are applied.

Sets the coordinate space in which transformations are applied.

.setTranslationSnap ( translationSnap : Number ) : undefined

translationSnap: The translation snap.

Sets the translation snap.

Source

examples/jsm/controls/TransformControls.js

BufferGeometry

ConvexGeometry

ConvexGeometry can be used to generate a convex hull for a given array of 3D points. The average time complexity for this task is considered to be O(nlog(n)).

Import

ConvexGeometry is an add-on, and must be imported explicitly. See Installation / Addons.

import { ConvexGeometry } from 'three/addons/geometries/ConvexGeometry.js';

Code Example

const geometry = new ConvexGeometry( points ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh );

Examples

geometry / convex

Constructor

ConvexGeometry( points : Array )

points — Array of Vector3s that the resulting convex hull will contain.

Source

examples/jsm/geometries/ConvexGeometry.js

BufferGeometry

DecalGeometry

DecalGeometry can be used to create a decal mesh that serves different kinds of purposes e.g. adding unique details to models, performing dynamic visual environmental changes or covering seams.

Import

DecalGeometry is an add-on, and must be imported explicitly. See Installation / Addons.

import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js';

Code Example

const geometry = new DecalGeometry( mesh, position, orientation, size ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh );

Examples

WebGL / decals

Constructor

DecalGeometry( mesh : Mesh, position : Vector3, orientation : Euler, size : Vector3 )

mesh — Any mesh object.
position — Position of the decal projector.
orientation — Orientation of the decal projector.
size — Size of the decal projector.

Source

examples/jsm/geometries/DecalGeometry.js

BufferGeometry

ParametricGeometry

Generate geometry representing a parametric surface.

Import

ParametricGeometry is an add-on, and must be imported explicitly. See Installation / Addons.

import { ParametricGeometry } from 'three/addons/geometries/ParametricGeometry.js';

Code Example

const geometry = new THREE.ParametricGeometry( THREE.ParametricGeometries.klein, 25, 25 ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const klein = new THREE.Mesh( geometry, material ); scene.add( klein );

Constructor

ParametricGeometry(func : Function, slices : Integer, stacks : Integer)

func — A function that takes in a u and v value each between 0 and 1 and modifies a third Vector3 argument. Default is a function that generates a curved plane surface.
slices — The count of slices to use for the parametric function. Default is 8.
stacks — The count of stacks to use for the parametric function. Default is 8.

Properties

See the base BufferGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base BufferGeometry class for common methods.

Source

examples/jsm/geometries/ParametricGeometry.js

BufferGeometry

TeapotGeometry

TeapotGeometry tessellates the famous Utah teapot database by Martin Newell.

Import

TeapotGeometry is an add-on, and must be imported explicitly. See Installation / Addons.

import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';

Code Example

const geometry = new TeapotGeometry( 50, 18 ); const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); const teapot = new THREE.Mesh( geometry, material ); scene.add( teapot );

Constructor

TeapotGeometry(size : Integer, segments : Integer, bottom : Boolean, lid : Boolean, body : Boolean, fitLid : Boolean, blinn : Boolean)

size — Relative scale of the teapot. Optional; Defaults to 50.
segments — Number of line segments to subdivide each patch edge. Optional; Defaults to 10.
bottom — Whether the bottom of the teapot is generated or not. Optional; Defaults to true.
lid — Whether the lid is generated or not. Optional; Defaults to true.
body — Whether the body is generated or not. Optional; Defaults to true.
fitLid — Whether the lid is slightly stretched to prevent gaps between the body and lid or not. Optional; Defaults to true.
blinn — Whether the teapot is scaled vertically for better aesthetics or not. Optional; Defaults to true.

Properties

See the base BufferGeometry class for common properties.

Methods

See the base BufferGeometry class for common methods.

Source

examples/jsm/geometries/TeapotGeometry.js

BufferGeometryExtrudeGeometry

TextGeometry

A class for generating text as a single geometry. It is constructed by providing a string of text, and a set of parameters consisting of a loaded font and settings for the geometry's parent ExtrudeGeometry. See the FontLoader page for additional details.

Import

TextGeometry is an add-on, and must be imported explicitly. See Installation / Addons.

import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';

Code Example

const loader = new FontLoader(); loader.load( 'fonts/helvetiker_regular.typeface.json', function ( font ) { const geometry = new TextGeometry( 'Hello three.js!', { font: font, size: 80, depth: 5, curveSegments: 12, bevelEnabled: true, bevelThickness: 10, bevelSize: 8, bevelOffset: 0, bevelSegments: 5 } ); } );

Examples

geometry / text

Constructor

TextGeometry(text : String, parameters : Object)

text — The text that needs to be shown.
parameters — Object that can contains the following parameters.

Available Fonts

TextGeometry uses typeface.json generated fonts. Some existing fonts can be found located in /examples/fonts and must be included in the page.

Font Weight Style File Path
helvetiker normal normal /examples/fonts/helvetiker_regular.typeface.json
helvetiker bold normal /examples/fonts/helvetiker_bold.typeface.json
optimer normal normal /examples/fonts/optimer_regular.typeface.json
optimer bold normal /examples/fonts/optimer_bold.typeface.json
gentilis normal normal /examples/fonts/gentilis_regular.typeface.json
gentilis bold normal /examples/fonts/gentilis_bold.typeface.json
droid sans normal normal /examples/fonts/droid/droid_sans_regular.typeface.json
droid sans bold normal /examples/fonts/droid/droid_sans_bold.typeface.json
droid serif normal normal /examples/fonts/droid/droid_serif_regular.typeface.json
droid serif bold normal /examples/fonts/droid/droid_serif_bold.typeface.json

Properties

See the base ExtrudeGeometry class for common properties.

.parameters : Object

An object with a property for each of the constructor parameters. Any modification after instantiation does not change the geometry.

Methods

See the base ExtrudeGeometry class for common methods.

Source

examples/jsm/geometries/TextGeometry.js

Object3DMesh

LightProbeHelper

Renders a sphere to visualize a light probe in the scene.

Import

LightProbeHelper is an add-on, and must be imported explicitly. See Installation / Addons.

import { LightProbeHelper } from 'three/addons/helpers/LightProbeHelper.js';

Code Example

const helper = new LightProbeHelper( lightProbe, 1 ); scene.add( helper );

Examples

WebGL / lightprobe / cubecamera

Constructor

LightProbeHelper( lightProbe : LightProbe, size : Number )

lightProbe -- the light probe.
size -- size of the helper sphere

Properties

See the base Mesh class for common properties.

.lightProbe : LightProbe

The light probe.

.size : Number

The size of the helper sphere.

Methods

See the base Mesh class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

examples/jsm/helpers/LightProbeHelper.js

Object3DLine

PositionalAudioHelper

This helper displays the directional cone of a PositionalAudio.

Import

PositionalAudioHelper is an add-on, and must be imported explicitly. See Installation / Addons.

import { PositionalAudioHelper } from 'three/addons/helpers/PositionalAudioHelper.js';

Code Example

const positionalAudio = new THREE.PositionalAudio( listener ); positionalAudio.setDirectionalCone( 180, 230, 0.1 ); const helper = new PositionalAudioHelper( positionalAudio ); positionalAudio.add( helper );

Examples

webaudio / orientation

Constructor

PositionalAudioHelper( audio : PositionalAudio, range : Number )

audio -- The PositionalAudio to be visualized.

range -- (optional) The range of the directional cone.

divisionsInnerAngle -- (optional) The amount of divisions of the inner part of the directional cone.

divisionsOuterAngle -- (optional) The amount of divisions of the outer part of the directional cone.

Properties

See the base Object3D class for common properties.

.audio : PositionalAudio

PositionalAudio to be visualized.

.range : Number

The range of the directional cone.

.divisionsInnerAngle : Number

The amount of divisions of the inner part of the directional cone.

.divisionsOuterAngle : Number

The amount of divisions of the outer part of the directional cone.

Methods

See the base Line class for common methods.

.update () : undefined

Updates the helper.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

examples/jsm/helpers/PositionalAudioHelper.js

Object3DLine

RectAreaLightHelper

Creates a visual aid for a RectAreaLight.

Import

RectAreaLightHelper is an add-on, and must be imported explicitly. See Installation / Addons.

import { RectAreaLightHelper } from 'three/addons/helpers/RectAreaLightHelper.js';

Code Example

const light = new THREE.RectAreaLight( 0xffffbb, 1.0, 5, 5 ); const helper = new RectAreaLightHelper( light ); light.add( helper ); // helper must be added as a child of the light

Constructor

RectAreaLightHelper( light : RectAreaLight, color : Hex )

light -- The light being visualized.

color -- (optional) if this is not the set the helper will take the color of the light.

Properties

See the base Object3D class for common properties.

.light : RectAreaLight

Reference to the RectAreaLight being visualized.

.color : hex

The color parameter passed in the constructor. Default is undefined. If this is changed, the helper's color will update the next time update is called.

Methods

See the base Line class for common methods.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

examples/jsm/helpers/RectAreaLightHelper.js

Object3DLineLineSegments

VertexNormalsHelper

Visualizes an object's vertex normals. Requires that normals have been specified in a custom attribute or have been calculated using computeVertexNormals.

Import

VertexNormalsHelper is an add-on, and must be imported explicitly. See Installation / Addons.

import { VertexNormalsHelper } from 'three/addons/helpers/VertexNormalsHelper.js';

Code Example

const geometry = new THREE.BoxGeometry( 10, 10, 10, 2, 2, 2 ); const material = new THREE.MeshStandardMaterial(); const mesh = new THREE.Mesh( geometry, material ); const helper = new VertexNormalsHelper( mesh, 1, 0xff0000 ); scene.add( mesh ); scene.add( helper );

Examples

WebGL / helpers

Constructor

VertexNormalsHelper( object : Object3D, size : Number, color : Hex )

object -- object for which to render vertex normals.
size -- (optional) length of the arrows. Default is 1.
color -- (optional) hex color of the arrows. Default is 0xff0000.

Properties

See the base LineSegments class for common properties.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the object's matrixWorld.

.object : Object3D

The object for which the vertex normals are being visualized.

.size : Number

Length of the arrows. Default is 1.

Methods

See the base LineSegments class for common methods.

.update () : undefined

Updates the vertex tangents preview based on the object's world transform.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

examples/jsm/helpers/VertexNormalsHelper.js

Object3DLineLineSegments

VertexTangentsHelper

Visualizes an object's vertex tangents. Requires that tangents have been specified in a custom attribute or have been calculated using computeTangents.

Import

VertexTangentsHelper is an add-on, and must be imported explicitly. See Installation / Addons.

import { VertexTangentsHelper } from 'three/addons/helpers/VertexTangentsHelper.js';

Code Example

const geometry = new THREE.BoxGeometry( 10, 10, 10, 2, 2, 2 ); const material = new THREE.MeshStandardMaterial(); const mesh = new THREE.Mesh( geometry, material ); const helper = new VertexTangentsHelper( mesh, 1, 0x00ffff ); scene.add( mesh ); scene.add( helper );

Examples

WebGL / helpers

Constructor

VertexTangentsHelper( object : Object3D, size : Number, color : Hex )

object -- object for which to render vertex tangents.
size -- (optional) length of the arrows. Default is 1.
color -- (optional) hex color of the arrows. Default is 0x00ffff.

Properties

See the base LineSegments class for common properties.

.matrixAutoUpdate : Object

See Object3D.matrixAutoUpdate. Set to false here as the helper is using the object's matrixWorld.

.object : Object3D

The object for which the vertex tangents are being visualized.

.size : Number

Length of the arrows. Default is 1.

Methods

See the base LineSegments class for common methods.

.update () : undefined

Updates the vertex tangents preview based on the object's world transform.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

Source

examples/jsm/helpers/VertexTangentsHelper.js

LightProbeGenerator

Utility class for creating instances of LightProbe.

Import

LightProbeGenerator is an add-on, and must be imported explicitly. See Installation / Addons.

import { LightProbeGenerator } from 'three/addons/lights/LightProbeGenerator.js';

Examples

WebGL / light probe
WebGL / light probe / cube camera

Static Methods

.fromCubeTexture ( cubeTexture : CubeTexture ) : LightProbe

Creates a light probe from the given (radiance) environment map. The method expects that the environment map is represented as a cube texture.

.fromCubeRenderTarget ( renderer : WebGLRenderer, cubeRenderTarget : WebGLCubeRenderTarget ) : LightProbe

Creates a light probe from the given (radiance) environment map. The method expects that the environment map is represented as a cube render target.

The format of the cube render target must be set to RGBA.

Source

examples/jsm/lights/LightProbeGenerator.js

Object3DMeshLineSegments2

Line2

A polyline drawn between vertices.

This adds functionality beyond Line, like arbitrary line width and changing width to be in world units. It extends LineSegments2, simplifying constructing segments from a chain of points.

Import

Line2 is an add-on, and therefore must be imported explicitly. See Installation / Addons.

import { Line2 } from 'three/addons/lines/Line2.js';

Examples

WebGL / lines / fat
WebGL / lines / fat / raycasting
WebGPU / lines / fat / raycasting

Constructor

Line2( geometry : LineGeometry, material : LineMaterial )

geometry — (optional) Pair(s) of vertices representing each line segment.
material — (optional) Material for the line. Default is a LineMaterial with random color.

Properties

See the base LineSegments2 class for common properties.

.isLine2 : Boolean

Read-only flag to check if a given object is of type Line2.

Methods

See the base LineSegments2 class for common methods.

Source

examples/jsm/lines/Line2.js

BufferGeometryInstancedBufferGeometryLineSegmentsGeometry

LineGeometry

A chain of vertices, forming a polyline.

This is used in Line2 to describe the shape.

Import

LineGeometry is an add-on, and therefore must be imported explicitly. See Installation / Addons.

import { LineGeometry } from 'three/addons/lines/LineGeometry.js';

Examples

WebGL / lines / fat
WebGL / lines / fat / raycasting
WebGPU / lines / fat / raycasting

Constructor

LineGeometry()

Creates a new geometry. Call setPositions to add segments.

Properties

See the base LineSegmentsGeometry class for common properties.

.isLineGeometry : Boolean

Read-only flag to check if a given object is of type LineGeometry.

Methods

See the base LineSegmentsGeometry class for common methods.

.fromLine ( line : Line ) : this

Copy the vertex positions of a Line object into this geometry. Assumes the source geometry is not using indices.

.setColors ( array : Array ) : this

Replace the per-vertex colors. Every triple describes a line vertex: [r1, g1, b1]. The array can be an Array or Float32Array.

.setPositions ( array : Array ) : this

Replace the vertex positions with a new set. The array can be an Array or Float32Array. The length must be a multiple of three.

.setFromPoints ( points : Array ) : this

Replace the vertex positions with an array of points. Can be either a Vector3 or Vector2 array.

Source

examples/jsm/lines/LineGeometry.js

MaterialShaderMaterial

LineMaterial

A material for drawing wireframe-style geometries. Unlike LineBasicMaterial, it supports arbitrary line widths and allows using world units instead of screen space units. This material is used with LineSegments2 and Line2.

Lines are always rendered with round caps and round joints.

Examples

WebGL / lines / fat
WebGL / lines / fat / raycasting
WebGL / lines / fat / wireframe
WebGPU / lines / fat / raycasting

Constructor

LineMaterial( parameters : Object )

parameters - (optional) an object with one or more properties defining the material's appearance. Any property of the material (including any property inherited from ShaderMaterial) can be passed in here.

The exception is the property color, which can be passed in as a number or hexadecimal string and is 0xffffff (white) by default. Color.set( color ) is called internally.

Properties

See the base ShaderMaterial class for common properties.

.color : Color

Color of the material, by default set to white (0xffffff).

.dashed : Boolean

Whether the line is dashed, or solid. Default is false.

.dashOffset : number

Where in the dash cycle the dash starts. Default is 0.

.dashScale : number

The scale of the dashes and gaps. Default is 1.

.dashSize : number

The size of the dash. Default is 1.

.gapSize : number

The size of the gap. Default is 1.

.linewidth : Float

Controls line thickness. Default is 1.

.resolution : Vector2

The size of the viewport, in screen pixels. This must be kept updated to make screen-space rendering accurate. The LineSegments2.onBeforeRender callback performs the update for visible objects. Default is [1, 1].

.worldUnits : Boolean

Whether the material's sizes (width, dash gaps) are in world units. Default is false (screen space units.)

Methods

See the base ShaderMaterial class for common methods.

Source

examples/jsm/lines/LineMaterial.js

Object3DMesh

LineSegments2

A series of lines drawn between pairs of vertices.

This adds functionality beyond LineSegments, like arbitrary line width and changing width to be in world units. The Line2 extends this object, forming a polyline instead of individual segments.

Import

LineSegments2 is an add-on, and therefore must be imported explicitly. See Installation / Addons.

import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';

Example

WebGL / lines / fat / raycasting

Constructor

LineSegments2( geometry : LineSegmentsGeometry, material : LineMaterial )

geometry — (optional) Pair(s) of vertices representing each line segment.
material — (optional) Material for the line. Default is a LineMaterial with random color.

Properties

See the base Mesh class for common properties.

.isLineSegments2 : Boolean

Read-only flag to check if a given object is of type LineSegments2.

Methods

See the base Mesh class for common methods.

.onBeforeRender ( renderer : WebGLRenderer ) : undefined

Called by the framework to update the material's resolution property, needed for screen-scaled widths.

If your object is not visible to a camera (e.g. by layers or visible,) you must call this manually whenever the viewport changes.

Source

examples/jsm/lines/LineSegments2.js

BufferGeometryInstancedBufferGeometry

LineSegmentsGeometry

A series of vertex pairs, forming line segments.

This is used in LineSegments2 to describe the shape.

Import

LineSegmentsGeometry is an add-on, and therefore must be imported explicitly. See Installation / Addons.

import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';

Example

WebGL / lines / fat / raycasting

Constructor

LineSegmentsGeometry()

Creates a new geometry. Call setPositions to add segments.

Properties

See the base InstancedBufferGeometry class for common properties.

.isLineSegmentsGeometry : Boolean

Read-only flag to check if a given object is of type LineSegmentsGeometry.

Methods

See the base Mesh class for common methods.

.fromEdgesGeometry ( geometry : EdgesGeometry ) : this

Copy the vertex positions of an edge geometry into this geometry.

.fromLineSegments ( lineSegments : LineSegments ) : this

Copy the vertex positions of a LineSegments object into this geometry. Assumes the source geometry is not using indices.

.fromMesh ( mesh : Mesh ) : this

Copy the vertex positions of a mesh object into this geometry.

.fromWireframeGeometry ( geometry : WireframeGeometry ) : this

Copy the vertex positions of a wireframe geometry into this geometry.

.setColors ( array : Array ) : this

Replace the per-vertex colors. Every sixtuple describes a segment: [r1, g1, b1, r2, g2, b2]. The array can be an Array or Float32Array.

.setPositions ( array : Array ) : this

Replace the vertex positions with a new set. The array can be an Array or Float32Array. The length must be a multiple of six.

See also positions.

.toJSON () : undefined

Unimplemented.

Source

examples/jsm/lines/LineSegmentsGeometry.js

Loader

3DMLoader

A loader for Rhinoceros 3d files and objects.

Rhinoceros is a 3D modeler used to create, edit, analyze, document, render, animate, and translate NURBS curves, surfaces, breps, extrusions, point clouds, as well as polygon meshes and SubD objects. rhino3dm.js is compiled to WebAssembly from the open source geometry library openNURBS. The loader currently uses rhino3dm.js 8.4.0.

Import

3DMLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { Rhino3dmLoader } from 'three/addons/loaders/3DMLoader.js';

Supported Conversions

The 3DMLoader converts Rhino objects to the following three.js types:

3dm type three.js type
Point Points
PointSet / PointCloud Points
TextDot Sprite
Curve Line 1
Mesh Mesh
Extrusion Mesh 2
BREP Mesh 2
SubD Mesh 3
InstanceReferences Object3D
DirectionalLight DirectionalLight
PointLight PointLight
RectangularLight RectAreaLight
SpotLight SpotLight
File3dm Object3D 4
Material / Physically Based Material MeshPhysicalMaterial

Notes:

1 NURBS curves are discretized to a hardcoded resolution.

2 Types which are based on BREPs and NURBS surfaces are represented with their "Render Mesh". Render meshes might not be associated with these objects if they have not been displayed in an appropriate display mode in Rhino (i.e. "Shaded", "Rendered", etc), or are created programmatically, for example, via Grasshopper or directly with the rhino3dm library. As of rhino3dm.js@8.0.0-beta2, BrepFace and Extrusions can be assigned a mesh representation, but these must be generated by the user.

3 SubD objects are represented by subdividing their control net.

4 Whether a Rhino Document (File3dm) is loaded or parsed, the returned object is an Object3D with all Rhino objects (File3dmObject) as children. File3dm layers and other file level properties are added to the resulting object's userData.

5 All resulting three.js objects have useful properties from the Rhino object (i.e. layer index, name, etc.) populated in their userData object.

6 Rhino and Three.js have a different coordinate system. Upon import, you should rotate the resulting Object3D by -90º in x or set the THREE.Object3D.DEFAULT_UP at the beginning of your application: THREE.Object3D.DEFAULT_UP.set( 0, 0, 1 ); Keep in mind that this will affect the orientation of all of the Object3Ds in your application.

Examples

webgl_loader_3dm


Constructor

Rhino3dmLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new Rhino3dmLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : Object3D

url — A string containing the path/URL of the .3dm file.
onLoad — A function to be called after the loading is successfully completed.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading from url and call the onLoad function with the resulting Object3d.

// Instantiate a loader const loader = new Rhino3dmLoader(); // Specify path to a folder containing WASM/JS libraries or a CDN. // For example, /jsm/libs/rhino3dm/ is the location of the library inside the three.js repository // loader.setLibraryPath( '/path_to_library/rhino3dm/' ); loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/rhino3dm@8.4.0/' ); // Load a 3DM file loader.load( // resource URL 'model.3dm', // called when the resource is loaded function ( object ) { scene.add( object ); }, // called as loading progresses function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

.parse ( buffer : ArrayBuffer, onLoad : Function, onProgress : Function, onError : Function ) : Object3D

buffer — An ArrayBuffer representing the Rhino File3dm document.
onLoad — A function to be called after the loading is successfully completed.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Parse a File3dm ArrayBuffer and call the onLoad function with the resulting Object3d. See this example for further reference.

import rhino3dm from 'https://cdn.jsdelivr.net/npm/rhino3dm@8.4.0' // Instantiate a loader const loader = new Rhino3dmLoader(); // Specify path to a folder containing WASM/JS libraries or a CDN. loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/rhino3dm@8.4.0' ); const rhino = await rhino3dm(); console.log('Loaded rhino3dm.'); // create Rhino Document and add a point to it const doc = new rhino.File3dm(); const ptA = [0, 0, 0]; const point = new rhino.Point( ptA ); doc.objects().add( point, null ); // create a copy of the doc.toByteArray data to get an ArrayBuffer const buffer = new Uint8Array( doc.toByteArray() ).buffer; loader.parse( buffer, function ( object ) { scene.add( object ); } );

.setLibraryPath ( value : String ) : this

value — Path to folder containing the JS and WASM libraries.

// Instantiate a loader const loader = new Rhino3dmLoader(); // Specify path to a folder containing the WASM/JS library: loader.setLibraryPath( '/path_to_library/rhino3dm/' ); // or from a CDN: loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/rhino3dm@8.4.0' );

.setWorkerLimit ( workerLimit : Number ) : this

workerLimit - Maximum number of workers to be allocated. Default is 4.

Sets the maximum number of Web Workers to be used during decoding. A lower limit may be preferable if workers are also for other tasks in the application.

.dispose () : this

Disposes of the loader resources and deallocates memory.

Source

examples/jsm/loaders/3DMLoader.js

Loader

DRACOLoader

A loader for geometry compressed with the Draco library.

Draco is an open source library for compressing and decompressing 3D meshes and point clouds. Compressed geometry can be significantly smaller, at the cost of additional decoding time on the client device.

Standalone Draco files have a .drc extension, and contain vertex positions, normals, colors, and other attributes. Draco files do not contain materials, textures, animation, or node hierarchies – to use these features, embed Draco geometry inside of a glTF file. A normal glTF file can be converted to a Draco-compressed glTF file using glTF-Pipeline. When using Draco with glTF, an instance of DRACOLoader will be used internally by GLTFLoader.

It is recommended to create one DRACOLoader instance and reuse it to avoid loading and creating multiple decoder instances.

Import

DRACOLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';

Code Example

// Instantiate a loader const loader = new DRACOLoader(); // Specify path to a folder containing WASM/JS decoding libraries. loader.setDecoderPath( '/examples/jsm/libs/draco/' ); // Optional: Pre-fetch Draco WASM/JS module. loader.preload(); // Load a Draco geometry loader.load( // resource URL 'model.drc', // called when the resource is loaded function ( geometry ) { const material = new THREE.MeshStandardMaterial( { color: 0x606060 } ); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); }, // called as loading progresses function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_draco

Browser compatibility

DRACOLoader will automatically use either the JS or the WASM decoding library, based on browser capabilities.



Constructor

DRACOLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new DRACOLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .drc file.
onLoad — A function to be called after the loading is successfully completed.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading from url and call the onLoad function with the decompressed geometry.

.setDecoderPath ( value : String ) : this

value — Path to folder containing the JS and WASM decoder libraries.

.setDecoderConfig ( config : Object ) : this

config.type - (Optional) "js" or "wasm".

Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.

.setWorkerLimit ( workerLimit : Number ) : this

workerLimit - Maximum number of workers to be allocated. Default is 4.

Sets the maximum number of Web Workers to be used during decoding. A lower limit may be preferable if workers are also for other tasks in the application.

.preload () : this

Requests the decoder libraries, if not already loaded.

.dispose () : this

Disposes of the decoder resources and deallocates memory. The decoder cannot be reloaded afterward.

Source

examples/jsm/loaders/DRACOLoader.js

Loader

FontLoader

Class for loading a font in JSON format. Returns a font, which is an array of Shapes representing the font. This uses the FileLoader internally for loading files.

You can convert fonts online using facetype.js

Import

FontLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { FontLoader } from 'three/addons/loaders/FontLoader.js';

Code Example

const loader = new FontLoader(); const font = loader.load( // resource URL 'fonts/helvetiker_bold.typeface.json', // onLoad callback function ( font ) { // do something with the font console.log( font ); }, // onProgress callback function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // onError callback function ( err ) { console.log( 'An error happened' ); } );

Examples

geometry / text / shapes
geometry / text

Constructor

FontLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new FontLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded font.
onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — Will be called when load errors.

Begin loading from url and pass the loaded font to onLoad.

.parse ( json : Object ) : Font

json — The JSON structure to parse.

Parse a JSON structure and return a font.

Source

examples/jsm/loaders/FontLoader.js

Loader

GLTFLoader

A loader for glTF 2.0 resources.

glTF (GL Transmission Format) is an open format specification for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb) format. External files store textures (.jpg, .png) and additional binary data (.bin). A glTF asset may deliver one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights, and/or cameras.

GLTFLoader uses ImageBitmapLoader whenever possible. Be advised that image bitmaps are not automatically GC-collected when they are no longer referenced, and they require special handling during the disposal process. More information in the How to dispose of objects guide.

Import

GLTFLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

Extensions

GLTFLoader supports the following glTF 2.0 extensions:

The following glTF 2.0 extension is supported by an external user plugin

1You can also manually process the extension after loading in your application. See Three.js glTF materials variants example.

Code Example

// Instantiate a loader const loader = new GLTFLoader(); // Optional: Provide a DRACOLoader instance to decode compressed mesh data const dracoLoader = new DRACOLoader(); dracoLoader.setDecoderPath( '/examples/jsm/libs/draco/' ); loader.setDRACOLoader( dracoLoader ); // Load a glTF resource loader.load( // resource URL 'models/gltf/duck/duck.gltf', // called when the resource is loaded function ( gltf ) { scene.add( gltf.scene ); gltf.animations; // Array<THREE.AnimationClip> gltf.scene; // THREE.Group gltf.scenes; // Array<THREE.Group> gltf.cameras; // Array<THREE.Camera> gltf.asset; // Object }, // called while loading is progressing function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_gltf

Textures

When loading textures externally (e.g., using TextureLoader) and applying them to a glTF model, textures must be configured. Textures referenced from the glTF model are configured automatically by GLTFLoader.

// If texture is used for color information (.map, .emissiveMap, .specularMap, ...), set color space texture.colorSpace = THREE.SRGBColorSpace; // UVs use the convention that (0, 0) corresponds to the upper left corner of a texture. texture.flipY = false;

Custom extensions

Metadata from unknown extensions is preserved as “.userData.gltfExtensions” on Object3D, Scene, and Material instances, or attached to the response “gltf” object. Example:

loader.load('foo.gltf', function ( gltf ) { const scene = gltf.scene; const mesh = scene.children[ 3 ]; const fooExtension = mesh.userData.gltfExtensions.EXT_foo; gltf.parser.getDependency( 'bufferView', fooExtension.bufferView ) .then( function ( fooBuffer ) { ... } ); } );

Constructor

GLTFLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new GLTFLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .gltf or .glb file.
onLoad — A function to be called after the loading is successfully completed. The function receives the loaded JSON response returned from parse.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading from url and call the callback function with the parsed response content.

.setDRACOLoader ( dracoLoader : DRACOLoader ) : this

dracoLoader — Instance of DRACOLoader, to be used for decoding assets compressed with the KHR_draco_mesh_compression extension.

Refer to this readme for the details of Draco and its decoder.

.setKTX2Loader ( ktx2Loader : KTX2Loader ) : this

ktx2Loader — Instance of KTX2Loader, to be used for loading KTX2 compressed textures.

.parse ( data : ArrayBuffer, path : String, onLoad : Function, onError : Function ) : undefined

data — glTF asset to parse, as an ArrayBuffer, JSON string or object.
path — The base path from which to find subsequent glTF resources such as textures and .bin data files.
onLoad — A function to be called when parse completes.
onError — (optional) A function to be called if an error occurs during parsing. The function receives error as an argument.

Parse a glTF-based ArrayBuffer, JSON string or object and fire onLoad callback when complete. The argument to onLoad will be an Object that contains loaded parts: .scene, .scenes, .cameras, .animations, and .asset.

Source

examples/jsm/loaders/GLTFLoader.js

Loader

KTX2Loader

Loader for KTX 2.0 GPU Texture containers.

KTX 2.0 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. While KTX 2.0 also allows other hardware-specific formats, this loader does not yet parse them.

This loader parses the KTX 2.0 container and transcodes to a supported GPU compressed texture format. The required WASM transcoder and JS wrapper are available from the examples/jsm/libs/basis directory.

Import

KTX2Loader is an add-on, and must be imported explicitly. See Installation / Addons.

import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';

Code Example

var ktx2Loader = new KTX2Loader(); ktx2Loader.setTranscoderPath( 'examples/jsm/libs/basis/' ); ktx2Loader.detectSupport( renderer ); ktx2Loader.load( 'diffuse.ktx2', function ( texture ) { var material = new THREE.MeshStandardMaterial( { map: texture } ); }, function () { console.log( 'onProgress' ); }, function ( e ) { console.error( e ); } );

Examples

webgl_loader_texture_ktx2

Browser compatibility

This loader relies on Web Assembly which is not supported in older browsers.



Constructor

KTX2Loader( manager : LoadingManager )

manager — The LoadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new KTX2Loader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : CompressedTexture

url — A string containing the path/URL of the .ktx2 file.
onLoad — A function to be called after the loading is successfully completed.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Load from url and call the onLoad function with the transcoded CompressedTexture.

.detectSupport ( renderer : WebGLRenderer ) : this

renderer — A renderer instance.

Detects hardware support for available compressed texture formats, to determine the output format for the transcoder. Must be called before loading a texture.

.setTranscoderPath ( path : String ) : this

path — Path to folder containing the WASM transcoder and JS wrapper.

The WASM transcoder and JS wrapper are available from the examples/jsm/libs/basis directory.

.setWorkerLimit ( limit : Number ) : this

limit — Maximum number of workers. Default is '4'.

Sets the maximum number of web workers to be allocated by this instance.

.dispose () : this

Disposes the loader object, de-allocating any Web Workers created.

Source

examples/jsm/loaders/KTX2Loader.js

Loader

LDrawLoader

A loader for LDraw resources.

LDraw (LEGO Draw) is an open format specification for describing LEGO and other construction set 3D models.

An LDraw asset (a text file usually with extension .ldr, .dat or .txt) can describe just a single construction piece, or an entire model. In the case of a model the LDraw file can reference other LDraw files, which are loaded from a library path set with setPartsLibraryPath. You usually download the LDraw official parts library, extract to a folder and point setPartsLibraryPath to it.

Library parts will be loaded by trial and error in subfolders 'parts', 'p' and 'models'. These file accesses are not optimal for web environment, so a script tool has been made to pack an LDraw file with all its dependencies into a single file, which loads much faster. See section 'Packing LDraw models'. The LDrawLoader example loads several packed files. The official parts library is not included due to its large size.

Import

LDrawLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { LDrawLoader } from 'three/addons/loaders/LDrawLoader.js';

Extensions

LDrawLoader supports the following extensions:

Code Example

// Instantiate a loader const loader = new LDrawLoader(); // Optionally set library parts path // loader.setPartsLibraryPath( path to library ); // Load a LDraw resource loader.load( // resource URL 'models/car.ldr_Packed.mpd', // called when the resource is loaded function ( group ) { // Optionally, use LDrawUtils.mergeObject() from // 'examples/jsm/utils/LDrawUtils.js' to merge all // geometries by material (it gives better runtime // performance, but building steps are lost) // group = LDrawUtils.mergeObject( group ); scene.add( group ); }, // called while loading is progressing function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_ldraw

Packing LDraw models

To pack a model with all its referenced files, download the Official LDraw parts library and use the following Node script: utils/packLDrawModel.js It contains instructions on how to setup the files and execute it.

Metadata in .userData

LDrawLoader returns a Group object which contains an object hierarchy. Depending of each subobject type, its .userData member will contain the following members:
In a Group, the userData member will contain:

In a Material, the userData member will contain:



Constructor

LDrawLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new LDrawLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the LDraw file.
onLoad — A function to be called after the loading is successfully completed. The function receives the loaded JSON response returned from parse.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading from url and call the callback function with the parsed response content.

.setPartsLibraryPath ( path : String ) : this

path — Path to library parts files to load referenced parts from. This is different from Loader.setPath, which indicates the path to load the main asset from.

This method must be called prior to .load unless the model to load does not reference library parts (usually it will be a model with all its parts packed in a single file)

.setFileMap ( fileMap : Map ) : this

map — Set a map from String to String which maps referenced library filenames to new filenames. If a fileMap is not specified (the default), library parts will be accessed by trial and error in subfolders 'parts', 'p' and 'models'.

.parse ( text : String, path : String, onLoad : Function, onError : Function ) : undefined

text — LDraw asset to parse, as string.
path — The base path from which to find other referenced LDraw asset files.
onLoad — A function to be called when parse completes.

Parse a LDraw file contents as a String and fire onLoad callback when complete. The argument to onLoad will be an Group that contains hierarchy of Group, Mesh and LineSegments (with other part data in .userData fields).

.getMaterial ( colourCode : String ) : Material

colourCode — Color code to get the associated Material.

.getMainMaterial () : String

Returns the Material for the main LDraw color.

For an already loaded LDraw asset, returns the Material associated with the main color code. This method can be useful to modify the main material of a model or part that exposes it.

The main color code is the standard way to color an LDraw part. It is '16' for triangles and '24' for edges. Usually a complete model will not expose the main color (that is, no part uses the code '16' at the top level, because they are assigned other specific colors) An LDraw part file on the other hand will expose the code '16' to be colored, and can have additional fixed colors.

.getMainEdgeMaterial () : String

Returns the Material for the edges main LDraw color.

.preloadMaterials ( path : String ) : void

path — Path of the LDraw materials asset.

This async method preloads materials from a single LDraw file. In the official parts library there is a special file which is loaded always the first (LDConfig.ldr) and contains all the standard color codes. This method is intended to be used with not packed files, for example in an editor where materials are preloaded and parts are loaded on demand.

Source

examples/jsm/loaders/LDrawLoader.js

Loader

LUT3dlLoader

A 3D LUT loader that supports the .3dl file format.
Based on the following references:

Import

LUT3dlLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { LUT3dlLoader } from 'three/addons/loaders/LUT3dlLoader.js';

Constructor

LUT3dlLoader( manager : LoadingManager )

manager — The LoadingManager to use. Defaults to DefaultLoadingManager

Creates a new LUT3dlLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .3dl file.
onLoad — (optional) A function to be called after the loading is successfully completed. The function receives the result of the parse method.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and return the loaded LUT.

.parse ( input : String ) : Object

input — The 3dl data string.

Parse a 3dl data string and fire onLoad callback when complete. The argument to onLoad will be an object containing the following LUT data: .size, .texture and .texture3D.

.setType ( type : Number ) : this

type - The texture type. See the texture constants page for details.

Sets the desired texture type. Only THREE.UnsignedByteType and THREE.FloatType are supported. The default is THREE.UnsignedByteType.

Source

examples/jsm/loaders/LUT3dlLoader.js

Loader

LUTCubeLoader

A 3D LUT loader that supports the .cube file format.
Based on the following reference:

Import

LUTCubeLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { LUTCubeLoader } from 'three/addons/loaders/LUTCubeLoader.js';

Constructor

LUTCubeLoader( manager : LoadingManager )

manager — The LoadingManager to use. Defaults to DefaultLoadingManager

Creates a new LUTCubeLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .cube file.
onLoad — (optional) A function to be called after the loading is successfully completed. The function receives the result of the parse method.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and return the loaded LUT.

.parse ( input : String ) : Object

input — The cube data string.

Parse a cube data string and fire onLoad callback when complete. The argument to onLoad will be an object containing the following LUT data: .title, .size, .domainMin, .domainMax, .texture and .texture3D.

.setType ( type : Number ) : this

type - The texture type. See the texture constants page for details.

Sets the desired texture type. Only THREE.UnsignedByteType and THREE.FloatType are supported. The default is THREE.UnsignedByteType.

Source

examples/jsm/loaders/LUTCubeLoader.js

Loader

MMDLoader

A loader for MMD resources.

MMDLoader creates Three.js Objects from MMD resources as PMD, PMX, VMD, and VPD files. See MMDAnimationHelper for MMD animation handling as IK, Grant, and Physics.

If you want raw content of MMD resources, use .loadPMD/PMX/VMD/VPD methods.

Import

MMDLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { MMDLoader } from 'three/addons/loaders/MMDLoader.js';

Code Example

// Instantiate a loader const loader = new MMDLoader(); // Load a MMD model loader.load( // path to PMD/PMX file 'models/mmd/miku.pmd', // called when the resource is loaded function ( mesh ) { scene.add( mesh ); }, // called when loading is in progress function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_mmd
webgl_loader_mmd_pose
webgl_loader_mmd_audio

Constructor

MMDLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new MMDLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .pmd or .pmx file.
onLoad — A function to be called after the loading is successfully completed.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading PMD/PMX model file from url and fire the callback function with the parsed SkinnedMesh containing BufferGeometry and an array of MeshToonMaterial.

.loadAnimation ( url : String, object : Object3D, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string or an array of string containing the path/URL of the .vmd file(s).If two or more files are specified, they'll be merged.
objectSkinnedMesh or Camera. Clip and its tracks will be fitting to this object.
onLoad — A function to be called after the loading is successfully completed.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading VMD motion file(s) from url(s) and fire the callback function with the parsed AnimationClip.

.loadWithAnimation ( modelUrl : String, vmdUrl : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

modelUrl — A string containing the path/URL of the .pmd or .pmx file.
vmdUrl — A string or an array of string containing the path/URL of the .vmd file(s).
onLoad — A function to be called after the loading is successfully completed.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, that contains .total and .loaded bytes.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading PMD/PMX model file and VMD motion file(s) from urls and fire the callback function with an Object containing parsed SkinnedMesh and AnimationClip fitting to the SkinnedMesh.

.setAnimationPath ( animationPath : String ) : this

animationPath — Base path for loading animation data (VMD/VPD files).

Set the base path for additional resources like textures.

Source

examples/jsm/loaders/MMDLoader.js

Loader

MTLLoader

A loader for loading an .mtl resource, used internally by OBJLoader.
The Material Template Library format (MTL) or .MTL File Format is a companion file format to .OBJ that describes surface shading (material) properties of objects within one or more .OBJ files.

Import

MTLLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { MTLLoader } from 'three/addons/loaders/MTLLoader.js';

Constructor

MTLLoader( loadingManager : LoadingManager )

loadingManager — LoadingManager to use. Defaults to DefaultLoadingManager

Creates a new MTLLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .mtl file.
onLoad — (optional) A function to be called after the loading is successfully completed. The function receives the loaded MTLLoader.MaterialCreator instance.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and return the loaded material.

.setMaterialOptions ( options : Object ) : this

options — required

Set of options on how to construct the materials

.parse ( [param:String text, param:String path] ) : MTLLoaderMaterialCreator

text — The textual mtl structure to parse. path — The path to the MTL file.

Parse a mtl text structure and return a MTLLoader.MaterialCreator instance.

Source

examples/jsm/loaders/MTLLoader.js

Loader

OBJLoader

A loader for loading a .obj resource.
The OBJ file format is a simple data-format that represents 3D geometry in a human readable format as the position of each vertex, the UV position of each texture coordinate vertex, vertex normals, and the faces that make each polygon defined as a list of vertices, and texture vertices.

Import

OBJLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';

Code Example

// instantiate a loader const loader = new OBJLoader(); // load a resource loader.load( // resource URL 'models/monster.obj', // called when resource is loaded function ( object ) { scene.add( object ); }, // called when loading is in progress function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_obj

Constructor

OBJLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new OBJLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .obj file.
onLoad — (optional) A function to be called after the loading is successfully completed. The function receives the loaded Object3D as an argument.
onProgress — (optional) A function to be called while the loading is in progress. The function receives a XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives error as an argument.

Begin loading from url and call onLoad with the parsed response content.

.parse ( text : String ) : Object3D

text — The textual obj structure to parse.

Returns an Object3D. It contains the parsed meshes as Mesh and lines as LineSegments.
All geometry is created as BufferGeometry. Default materials are created as MeshPhongMaterial.
If an obj object or group uses multiple materials while declaring faces, geometry groups and an array of materials are used.

.setMaterials ( materials : MTLLoader.MaterialCreator ) : this

MTLLoader.MaterialCreator materials - A MaterialCreator instance.

Sets materials loaded by MTLLoader or any other supplier of a MTLLoader.MaterialCreator.

Source

examples/jsm/loaders/OBJLoader.js

Loader

PCDLoader

A loader for the PCD (Point Cloud Data) file format. PCDLoader supports ASCII and (compressed) binary files as well as the following PCD fields:

Import

PCDLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { PCDLoader } from 'three/addons/loaders/PCDLoader.js';

Code Example

// instantiate a loader const loader = new PCDLoader(); // load a resource loader.load( // resource URL 'pointcloud.pcd', // called when the resource is loaded function ( points ) { scene.add( points ); }, // called when loading is in progress function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_pcd

Constructor

PCDLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new PCDLoader.

Properties

See the base Loader class for common properties.

littleEndian

Default value is true.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .pcd file.
onLoad — (optional) A function to be called after loading is successfully completed. The function receives loaded Object3D as an argument.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and call onLoad with the parsed response content.

.parse ( data : Arraybuffer,url : String ) : Object3D

data — The binary structure to parse.

url — The file name or file url.

Parse an pcd binary structure and return an Object3D.
The object is converted to Points with a BufferGeometry and a PointsMaterial.

Source

examples/jsm/loaders/PCDLoader.js

Loader

PDBLoader

A loader for loading a .pdb resource.
The Protein Data Bank file format is a textual file describing the three-dimensional structures of molecules.

Import

PDBLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { PDBLoader } from 'three/addons/loaders/PDBLoader.js';

Code Example

// instantiate a loader const loader = new PDBLoader(); // load a PDB resource loader.load( // resource URL 'models/pdb/caffeine.pdb', // called when the resource is loaded function ( pdb ) { const geometryAtoms = pdb.geometryAtoms; const geometryBonds = pdb.geometryBonds; const json = pdb.json; console.log( 'This molecule has ' + json.atoms.length + ' atoms' ); }, // called when loading is in progress function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_pdb

Constructor

PDBLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new PDBLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .pdb file.
onLoad — (optional) A function to be called after loading is successfully completed. The function receives the object having the following properties. geometryAtoms, geometryBonds and the JSON structure.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and call onLoad with the parsed response content.

.parse ( text : String ) : Object

text — The textual pdb structure to parse.

Parse a pdb text and return a JSON structure.

Source

examples/jsm/loaders/PDBLoader.js

Loader

SVGLoader

A loader for loading a .svg resource.
Scalable Vector Graphics is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation.

Import

SVGLoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { SVGLoader } from 'three/addons/loaders/SVGLoader.js';

Code Example

// instantiate a loader const loader = new SVGLoader(); // load a SVG resource loader.load( // resource URL 'data/svgSample.svg', // called when the resource is loaded function ( data ) { const paths = data.paths; const group = new THREE.Group(); for ( let i = 0; i < paths.length; i ++ ) { const path = paths[ i ]; const material = new THREE.MeshBasicMaterial( { color: path.color, side: THREE.DoubleSide, depthWrite: false } ); const shapes = SVGLoader.createShapes( path ); for ( let j = 0; j < shapes.length; j ++ ) { const shape = shapes[ j ]; const geometry = new THREE.ShapeGeometry( shape ); const mesh = new THREE.Mesh( geometry, material ); group.add( mesh ); } } scene.add( group ); }, // called when loading is in progress function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } );

Examples

webgl_loader_svg

Constructor

SVGLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new SVGLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — A string containing the path/URL of the .svg file.
onLoad — (optional) A function to be called after loading is successfully completed. The function receives an array of ShapePath as an argument.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and call onLoad with the response content.

Static Methods

.createShapes ( shape : ShapePath ) : Array

shape — A ShapePath from the array of ShapePath, given as argument in the onLoad function for the load function of SVGLoader.

Returns one or more Shape objects created from the shape : ShapePath provided as an argument in this function.

Source

examples/jsm/loaders/SVGLoader.js

Loader

TGALoader

A loader for loading a .tga resource.
TGA is a raster graphics, image file format.

Import

TGALoader is an add-on, and must be imported explicitly. See Installation / Addons.

import { TGALoader } from 'three/addons/loaders/TGALoader.js';

Code Example

// instantiate a loader const loader = new TGALoader(); // load a resource const texture = loader.load( // resource URL 'textures/crate_grey8.tga' // called when loading is completed function ( texture ) { console.log( 'Texture is loaded' ); }, // called when the loading is in progress function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when the loading fails function ( error ) { console.log( 'An error happened' ); } ); const material = new THREE.MeshPhongMaterial( { color: 0xffffff, map: texture } );

Examples

webgl_loader_texture_tga

Constructor

TGALoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new TGALoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : DataTexture

url — A string containing the path/URL of the .tga file.
onLoad — (optional) A function to be called after loading is successfully completed. The function receives loaded DataTexture as an argument.
onProgress — (optional) A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes. If the server does not set the Content-Length header; .total will be 0.
onError — (optional) A function to be called if an error occurs during loading. The function receives the error as an argument.

Begin loading from url and pass the loaded texture to onLoad. The texture is also directly returned for immediate use (but may not be fully loaded).

Source

examples/jsm/loaders/TGALoader.js

Mesh

Lensflare

Creates a simulated lens flare that tracks a light. Lensflare can only be used when setting the alpha context parameter of WebGLRenderer to true.

Import

Lensflare is an add-on, and must be imported explicitly. See Installation / Addons.

import { Lensflare, LensflareElement } from 'three/addons/objects/Lensflare.js';

Code Example

const light = new THREE.PointLight( 0xffffff, 1.5, 2000 ); const textureLoader = new THREE.TextureLoader(); const textureFlare0 = textureLoader.load( "textures/lensflare/lensflare0.png" ); const textureFlare1 = textureLoader.load( "textures/lensflare/lensflare2.png" ); const textureFlare2 = textureLoader.load( "textures/lensflare/lensflare3.png" ); const lensflare = new Lensflare(); lensflare.addElement( new LensflareElement( textureFlare0, 512, 0 ) ); lensflare.addElement( new LensflareElement( textureFlare1, 512, 0 ) ); lensflare.addElement( new LensflareElement( textureFlare2, 60, 0.6 ) ); light.add( lensflare );

Examples

WebGL / lensflares

Constructor

LensflareElement( texture : Texture, size : Float, distance : Float, color : Color )

texture - THREE.Texture to use for the flare.
size - (optional) size in pixels
distance - (optional) (0-1) from light source (0 = at light source)
color - (optional) the Color of the lens flare

Properties

See the base Mesh class for common properties.

Source

examples/jsm/objects/Lensflare.js

Mesh

Sky

Sky creates a ready to go sky environment for your scenes.

Import

Sky is an add-on, and therefore must be imported explicitly. See Installation / Addons.

import { Sky } from 'three/addons/objects/Sky.js';

Code Example

const sky = new Sky(); sky.scale.setScalar( 450000 ); const phi = MathUtils.degToRad( 90 ); const theta = MathUtils.degToRad( 180 ); const sunPosition = new Vector3().setFromSphericalCoords( 1, phi, theta ); sky.material.uniforms.sunPosition.value = sunPosition; scene.add( sky );

Examples

misc / objects / Sky

Constructor

Sky()

Create a new Sky instance.

Properties

Sky instance is a Mesh with a pre-defined ShaderMaterial, so every property described here should be set using Uniforms.

.turbidity : Number

Haziness of the Sky.

.rayleigh : Number

For a more detailed explanation see: Rayleigh scattering .

.mieCoefficient : Number

Mie scattering amount.

.mieDirectionalG : Number

Mie scattering direction.

.sunPosition : Vector3

The position of the sun.

.up : Vector3

The sun's elevation from the horizon, in degrees.

Source

examples/jsm/objects/Sky.js

EffectComposer

Used to implement post-processing effects in three.js. The class manages a chain of post-processing passes to produce the final visual result. Post-processing passes are executed in order of their addition/insertion. The last pass is automatically rendered to screen.

Import

EffectComposer is an add-on, and must be imported explicitly. See Installation / Addons.

import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';

Examples

postprocessing
postprocessing advanced
postprocessing backgrounds
postprocessing transition
postprocessing depth-of-field
postprocessing depth-of-field 2
postprocessing fxaa
postprocessing glitch
postprocessing godrays
postprocessing gtao
postprocessing masking
postprocessing material ao
postprocessing outline
postprocessing pixelate
postprocessing procedural
postprocessing rgb halftone
postprocessing sao
postprocessing smaa
postprocessing sobel
postprocessing ssaa
postprocessing ssao
postprocessing taa
postprocessing unreal bloom
postprocessing unreal bloom selective

Constructor

EffectComposer( renderer : WebGLRenderer, renderTarget : WebGLRenderTarget )

renderer -- The renderer used to render the scene.
renderTarget -- (optional) A preconfigured render target internally used by EffectComposer.

Properties

.passes : Array

An array representing the (ordered) chain of post-processing passes.

.readBuffer : WebGLRenderTarget

A reference to the internal read buffer. Passes usually read the previous render result from this buffer.

.renderer : WebGLRenderer

A reference to the internal renderer.

.renderToScreen : Boolean

Whether the final pass is rendered to the screen (default framebuffer) or not.

.writeBuffer : WebGLRenderTarget

A reference to the internal write buffer. Passes usually write their result into this buffer.

Methods

.addPass ( pass : Pass ) : undefined

pass -- The pass to add to the pass chain.

Adds the given pass to the pass chain.

.dispose () : undefined

Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.

.insertPass ( pass : Pass, index : Integer ) : undefined

pass -- The pass to insert into the pass chain.
index -- Defines the position in the pass chain where the pass should be inserted.

Inserts the given pass into the pass chain at the given index.

.isLastEnabledPass ( passIndex : Integer ) : Boolean

passIndex -- The pass to check.

Returns true if the pass for the given index is the last enabled pass in the pass chain. Used by EffectComposer to determine when a pass should be rendered to screen.

.removePass ( pass : Pass ) : undefined

pass -- The pass to remove from the pass chain.

Removes the given pass from the pass chain.

.render ( deltaTime : Float ) : undefined

deltaTime -- The delta time value.

Executes all enabled post-processing passes in order to produce the final frame.

.reset ( renderTarget : WebGLRenderTarget ) : undefined

renderTarget -- (optional) A preconfigured render target internally used by EffectComposer..

Resets the internal state of the EffectComposer.

.setPixelRatio ( pixelRatio : Float ) : undefined

pixelRatio -- The device pixel ratio.

Sets device pixel ratio. This is usually used for HiDPI device to prevent blurring output. Thus, the semantic of the method is similar to WebGLRenderer.setPixelRatio().

.setSize ( width : Integer, height : Integer ) : undefined

width -- The width of the EffectComposer.
height -- The height of the EffectComposer.

Resizes the internal render buffers and passes to (width, height) with device pixel ratio taken into account. Thus, the semantic of the method is similar to WebGLRenderer.setSize().

.swapBuffers () : undefined

Swaps the internal read/write buffers.

Source

examples/jsm/postprocessing/EffectComposer.js

DRACOExporter

An exporter to compress geometry with the Draco library.

Draco is an open source library for compressing and decompressing 3D meshes and point clouds. Compressed geometry can be significantly smaller, at the cost of additional decoding time on the client device.

Standalone Draco files have a .drc extension, and contain vertex positions, normals, colors, and other attributes. Draco files do not contain materials, textures, animation, or node hierarchies – to use these features, embed Draco geometry inside of a glTF file. A normal glTF file can be converted to a Draco-compressed glTF file using glTF-Pipeline.

Import

DRACOExporter is an add-on, and must be imported explicitly. See Installation / Addons.

import { DRACOExporter } from 'three/addons/exporters/DRACOExporter.js';

Code Example

// Instantiate a exporter const exporter = new DRACOExporter(); // Parse the input and generate the DRACO encoded output const binaryData = exporter.parse( mesh, options );

Examples

misc_exporter_draco

Constructor

DRACOExporter()

Creates a new DRACOExporter.

Methods

.parse ( object : Mesh | object : Points, options : Object ) : Int8Array

object | object — Mesh or Points to encode.
options — Optional export options

Source

examples/jsm/exporters/DRACOExporter.js

EXRExporter

An exporter for EXR.

EXR ( Extended Dynamic Range) is an open format specification for professional-grade image storage format of the motion picture industry. The purpose of format is to accurately and efficiently represent high-dynamic-range scene-linear image data and associated metadata. The library is widely used in host application software where accuracy is critical, such as photorealistic rendering, texture access, image compositing, deep compositing, and DI.

Import

EXRExporter is an add-on, and must be imported explicitly. See Installation / Addons.

import { EXRExporter } from 'three/addons/exporters/EXRExporter.js';

Code Example

// Instantiate a exporter const exporter = new EXRExporter(); // Parse the input render target data and generate the EXR output const EXR = exporter.parse( renderer, renderTarget, options ); downloadFile( EXR );

Constructor

EXRExporter()

Creates a new EXRExporter.

Methods

.parse ( renderer : WebGLRenderer, renderTarget : WebGLRenderTarget, options : Object ) : null

renderTarget — WebGLRenderTarget containing data used for exporting EXR image.
options — Export options.

Generates a .exr output from the input render target.

.parse ( dataTexture : DataTexture, options : Object ) : null

dataTexture — DataTexture containing data used for exporting EXR image.
options — Export options (details above).

Generates a .exr output from the input data texture.

Source

examples/jsm/exporters/EXRExporter.js

GLTFExporter

An exporter for glTF 2.0.

glTF (GL Transmission Format) is an open format specification for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb) format. External files store textures (.jpg, .png) and additional binary data (.bin). A glTF asset may deliver one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights, and/or cameras.

Import

GLTFExporter is an add-on, and must be imported explicitly. See Installation / Addons.

import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';

Extensions

GLTFExporter supports the following glTF 2.0 extensions:

The following glTF 2.0 extension is supported by an external user plugin

Code Example

// Instantiate a exporter const exporter = new GLTFExporter(); // Parse the input and generate the glTF output exporter.parse( scene, // called when the gltf has been generated function ( gltf ) { console.log( gltf ); downloadJSON( gltf ); }, // called when there is an error in the generation function ( error ) { console.log( 'An error happened' ); }, options );

Examples

misc_exporter_gltf

Constructor

GLTFExporter()

Creates a new GLTFExporter.

Methods

.parse ( input : Object3D, onCompleted : Function, onError : Function, options : Object ) : undefined

input — Scenes or objects to export. Valid options:

onCompleted
onError
options

Generates a .gltf (JSON) or .glb (binary) output from the input (Scenes or Objects)

.parseAsync ( input : Object3D, options : Object ) : Promise

Generates a .gltf (JSON) or .glb (binary) output from the input (Scenes or Objects).

This is just like the .parse() method, but instead of accepting callbacks it returns a promise that resolves with the result, and otherwise accepts the same options.

Source

examples/jsm/exporters/GLTFExporter.js

OBJExporter

An exporter for the OBJ file format.

OBJExporter is not able to export material data into MTL files so only geometry data are supported.

Import

OBJExporter is an add-on, and must be imported explicitly. See Installation / Addons.

import { OBJExporter } from 'three/addons/exporters/OBJExporter.js';

Code Example

// Instantiate an exporter const exporter = new OBJExporter(); // Parse the input and generate the OBJ output const data = exporter.parse( scene ); downloadFile( data );

Constructor

OBJExporter()

Creates a new OBJExporter.

Methods

.parse ( object : Object3D ) : String

object — Object3D to be exported.

Generates a string holding the OBJ data.

Source

examples/jsm/exporters/OBJExporter.js

PLYExporter

An exporter for PLY.

PLY (Polygon or Stanford Triangle Format) is a file format for efficient delivery and loading of simple, static 3D content in a dense format. Both binary and ascii formats are supported. PLY can store vertex positions, colors, normals and uv coordinates. No textures or texture references are saved.

Import

PLYExporter is an add-on, and must be imported explicitly. See Installation / Addons.

import { PLYExporter } from 'three/addons/exporters/PLYExporter.js';

Code Example

// Instantiate an exporter const exporter = new PLYExporter(); // Parse the input and generate the ply output const data = exporter.parse( scene, options ); downloadFile( data );

Constructor

PLYExporter()

Creates a new PLYExporter.

Methods

.parse ( input : Object3D, onDone : Function, options : Object ) : Object

input — Object3D
onCompleted — Will be called when the export completes. The argument will be the generated ply ascii or binary ArrayBuffer.
options — Export options

Generates ply file data as string or ArrayBuffer (ascii or binary) output from the input object. The data that is returned is the same that is passed into the "onCompleted" function. If the object is composed of multiple children and geometry, they are merged into a single mesh in the file.

Source

examples/jsm/exporters/PLYExporter.js

STLExporter

An exporter for the STL file format.

STL files describe only the surface geometry of a three-dimensional object without any representation of color, texture or other common model attributes. The STL format specifies both ASCII and binary representations, with binary being more compact. STL files contain no scale information or indexes, and the units are arbitrary.

Import

STLExporter is an add-on, and must be imported explicitly. See Installation / Addons.

import { STLExporter } from 'three/addons/exporters/STLExporter.js';

Code Example

// Instantiate an exporter const exporter = new STLExporter(); // Configure export options const options = { binary: true } // Parse the input and generate the STL encoded output const result = exporter.parse( mesh, options );

Examples

misc_exporter_stl

Constructor

STLExporter()

Creates a new STLExporter.

Methods

.parse ( scene : Object3D, options : Object ) : Object

scene — Scene, Mesh, or other Object3D based class containing Meshes to encode.
options — Optional export options

Source

examples/jsm/exporters/STLExporter.js

Lut

Represents a lookup table for colormaps. It is used to determine the color values from a range of data values.

Import

Lut is an add-on, and must be imported explicitly. See Installation / Addons.

import { Lut } from 'three/addons/math/Lut.js';

Code Example

const lut = new Lut( 'rainbow', 512 ); const color = lut.getColor( 0.5 );

Constructor

Lut( colormap : String, count : Number )

colormap - Sets a colormap from predefined colormaps. Available colormaps are: rainbow, cooltowarm, blackbody, grayscale. Default is rainbow.
count - Sets the number of colors used to represent the data array. Default is 32.

Properties

.lut : Array

The lookup table for the selected color map represented as an array of Colors.

.map : Array

The currently selected color map. Default is the rainbow color map.

.minV : Number

The minimum value to be represented with the lookup table. Default is 0.

.maxV : Number

The maximum value to be represented with the lookup table. Default is 1.

.n : Number

The number of colors of the current selected color map. Default is 32.

Methods

.copy ( lut : Lut ) : this this : Lut

color — Lut to copy.

Copies the given lut.

.addColorMap ( name : String, arrayOfColors : Array ) : this

name — The name of the color map.
arrayOfColors — An array of color values. Each value is an array holding a threshold and the actual color value as a hexadecimal number.

Adds a color map to this Lut instance.

.createCanvas () : HTMLCanvasElement

Creates a canvas in order to visualize the lookup table as a texture.

.getColor ( alpha : Number ) : Color

value -- the data value to be displayed as a color.

Returns an instance of Color for the given data value.

.setColorMap ( colormap : String, count : Number ) : this

colormap — The name of the color map.
count — The number of colors. Default is 32.

Configure the lookup table for the given color map and number of colors.

.setMin ( minV : Number ) : this

minV — The minimum value to be represented with the lookup table

Sets this Lut with the minimum value to be represented.

.setMax ( maxV : Number ) : this

maxV — The maximum value to be represented with the lookup table.

Sets this Lut with the maximum value to be represented.

.updateCanvas ( canvas : HTMLCanvasElement ) : HTMLCanvasElement

Updates the canvas with the Lut's data.

Source

examples/jsm/math/Lut.js

MeshSurfaceSampler

Utility class for sampling weighted random points on the surface of a mesh.

Weighted sampling is useful for effects like heavier foliage growth in certain areas of terrain, or concentrated particle emissions from specific parts of a mesh. Vertex weights may be written programmatically, or painted by hand as vertex colors in 3D tools like Blender.

Import

MeshSurfaceSampler is an add-on, and must be imported explicitly. See Installation / Addons.

import { MeshSurfaceSampler } from 'three/addons/math/MeshSurfaceSampler.js';

Code Example

// Create a sampler for a Mesh surface. const sampler = new MeshSurfaceSampler( surfaceMesh ) .setWeightAttribute( 'color' ) .build(); const mesh = new THREE.InstancedMesh( sampleGeometry, sampleMaterial, 100 ); const position = new THREE.Vector3(); const matrix = new THREE.Matrix4(); // Sample randomly from the surface, creating an instance of the sample // geometry at each sample point. for ( let i = 0; i < 100; i ++ ) { sampler.sample( position ); matrix.makeTranslation( position.x, position.y, position.z ); mesh.setMatrixAt( i, matrix ); } scene.add( mesh );

Examples

webgl_instancing_scatter

Constructor

MeshSurfaceSampler( mesh : Mesh )

mesh — Surface mesh from which to sample.

Creates a new MeshSurfaceSampler. If the input geometry is indexed, a non-indexed copy is made. After construction, the sampler is not able to return samples until build is called.

Methods

.setWeightAttribute ( name : String ) : this

Specifies a vertex attribute to be used as a weight when sampling from the surface. Faces with higher weights are more likely to be sampled, and those with weights of zero will not be sampled at all. For vector attributes, only .x is used in sampling.

If no weight attribute is selected, sampling is randomly distributed by area.

.build () : this

Processes the input geometry and prepares to return samples. Any configuration of the geometry or sampler must occur before this method is called. Time complexity is O(n) for a surface with n faces.

.sample ( targetPosition : Vector3, targetNormal : Vector3, targetColor : Color, targetUV : Vector2 ) : this

Selects a random point on the surface of the input geometry, returning the position and optionally the normal vector, color and UV Coordinate at that point. Time complexity is O(log n) for a surface with n faces.

Source

examples/jsm/math/MeshSurfaceSampler.js

OBB

Represents an oriented bounding box (OBB) in 3D space.

Import

OBB is an add-on, and must be imported explicitly. See Installation / Addons.

import { OBB } from 'three/addons/math/OBB.js';

Examples

webgl_math_obb

Constructor

OBB( center : Vector3, halfSize : Vector3, rotation : Matrix3 )

center — The center of the OBB. (optional)
halfSize — Positive halfwidth extents of the OBB along each axis. (optional)
rotation — The rotation of the OBB. (optional)

Creates a new OBB.

Properties

.center : Vector3

The center of the OBB. Default is ( 0, 0, 0 ).

.halfSize : Vector3

Positive halfwidth extents of the OBB along each axis. Default is ( 0, 0, 0 ).

.rotation : Matrix3

The rotation of the OBB. Default is the identity matrix.

Methods

.applyMatrix4 ( matrix : Matrix4 ) : this

matrix — A 4x4 transformation matrix.

Applies the given transformation matrix to this OBB. This method can be used to transform the bounding volume with the world matrix of a 3D object in order to keep both entities in sync.

.clampPoint ( point : Vector3, clampedPoint : Vector3 ) : Vector3

point — The point that should be clamped within the bounds of this OBB.
clampedPoint — The result will be copied into this vector.

Clamps the given point within the bounds of this OBB.

.clone () : OBB

Creates a cloned OBB for this instance.

.containsPoint ( point : Vector3 ) : Boolean

point — The point to test.

Whether the given point lies within this OBB or not.

.copy ( obb : OBB ) : this

obb — The OBB to copy.

Copies the properties of the given OBB to this OBB.

.equals ( obb : OBB ) : Boolean

obb — The OBB to test.

Whether the given OBB is equal to this OBB or not.

.fromBox3 ( box3 : Box3 ) : this

box3 — An AABB.

Defines an OBB based on the given AABB.

.getSize ( size : Vector3 ) : Vector3

size — The result will be copied into this vector.

Returns the size of this OBB into the given vector.

.intersectsBox3 ( box3 : Box3 ) : Boolean

box3 — The AABB to test.

Whether the given AABB intersects this OBB or not.

.intersectsSphere ( sphere : Sphere ) : Boolean

sphere — The bounding sphere to test.

Whether the given bounding sphere intersects this OBB or not.

.intersectsOBB ( obb : OBB, epsilon : Number ) : Boolean

obb — The OBB to test.
epsilon — An optional numeric value to counteract arithmetic errors. Default is Number.EPSILON.

Whether the given OBB intersects this OBB or not.

.intersectsPlane ( plane : Plane ) : Boolean

plane — The plane to test.

Whether the given plane intersects this OBB or not.

.intersectsRay ( ray : Ray ) : Boolean

ray — The ray to test.

Whether the given ray intersects this OBB or not.

.intersectRay ( ray : Ray, intersectionPoint : Vector3 ) : Vector3

ray — The ray to test.
intersectionPoint — The result will be copied into this vector.

Performs a Ray/OBB intersection test and stores the intersection point to the given 3D vector. If no intersection is detected, null is returned.

.set ( center : Vector3, halfSize : Vector3, rotation : Matrix3 ) : this

center — The center of the OBB.
halfSize — Positive halfwidth extents of the OBB along each axis.
rotation — The rotation of the OBB.

Defines the OBB for the given values.

Source

examples/jsm/math/OBB.js

Timer

This class is an alternative to Clock with a different API design and behavior. The goal is to avoid the conceptual flaws that became apparent in Clock over time.

Import

Timer is an add-on, and must be imported explicitly. See Installation / Addons.

import { Timer } from 'three/addons/misc/Timer.js';

Code Example

const timer = new Timer(); function animate( timestamp ) { requestAnimationFrame( animate ); // timestamp is optional timer.update( timestamp ); const delta = timer.getDelta(); // do something with delta renderer.render( scene, camera ); }

Examples

WebGL / morphtargets / sphere

Constructor

Timer()

Methods

.getDelta () : Number

Returns the time delta in seconds.

.getElapsed () : Number

Returns the elapsed time in seconds.

.setTimescale ( timescale : Number ) : this

Sets a time scale that scales the time delta in .update().

.reset () : this

Resets the time computation for the current simulation step.

.dispose () : this

Can be used to free all internal resources. Usually called when the timer instance isn't required anymore.

.update ( timestamp : Number ) : this

timestamp -- (optional) The current time in milliseconds. Can be obtained from the requestAnimationFrame callback argument. If not provided, the current time will be determined with performance.now.

Updates the internal state of the timer. This method should be called once per simulation step and before you perform queries against the timer (e.g. via .getDelta()).

Source

examples/jsm/misc/Timer.js

EdgeSplitModifier

EdgeSplitModifier is intended to modify the geometry "dissolving" the edges to give a smoother look.

Import

EdgeSplitModifier is an add-on, and therefore must be imported explicitly. See Installation / Addons.

import { EdgeSplitModifier } from 'three/addons/modifiers/EdgeSplitModifier.js';

Code Example

const geometry = new THREE.IcosahedronGeometry( 10, 3 ); const modifier = new EdgeSplitModifier(); const cutOffAngle = 0.5; const tryKeepNormals = false; modifier.modify( geometry, cutOffAngle, tryKeepNormals );

Examples

misc / modifiers / EdgeSplit

Constructor

EdgeSplitModifier()

Create a new EdgeSplitModifier object.

Methods

.modify ( geometry : geometry, cutOffAngle : cutOffAngle, tryKeepNormals : tryKeepNormals ) : undefined

Using interpolated vertex normals, the mesh faces will blur at the edges and appear smooth.
You can control the smoothness by setting the cutOffAngle.
To try to keep the original normals, set tryKeepNormals to true.

Source

examples/jsm/modifiers/EdgeSplitModifier.js

Face

Represents a section bounded by a specific amount of half-edges. The current implementation assumes that a face always consist of three edges.

Import

Face is an add-on, and must be imported explicitly. See Installation / Addons.

import { Face } from 'three/addons/math/ConvexHull.js';

Constructor

Face()

Creates a new instance of Face.

Properties

.normal : Vector3

The normal vector of the face. Default is a Vector3 at (0, 0, 0).

.midpoint : Vector3

The midpoint or centroid of the face. Default is a Vector3 at (0, 0, 0).

.area : Float

The area of the face. Default is 0.

.constant : Float

Signed distance from face to the origin. Default is 0.

.outside : VertexNode

Reference to a vertex in a vertex list this face can see. Default is null.

.mark : Integer

Marks if a face is visible or deleted. Default is 'Visible'.

.edge : HalfEdge

Reference to the base edge of a face. To retrieve all edges, you can use the 'next' reference of the current edge. Default is null.

Methods

.create ( a : VertexNode, b : VertexNode, c : VertexNode ) : Face

a - First vertex of the face.
b - Second vertex of the face.
c - Third vertex of the face.

Creates a face.

.getEdge ( i : Integer ) : HalfEdge

i - The index of the edge.

Returns an edge by the given index.

.compute () : this

Computes all properties of the face.

.distanceToPoint ( point : Vector3 ) : Float

point - Any point in 3D space.

Returns the signed distance from a given point to the plane representation of this face.

Source

examples/jsm/math/ConvexHull.js

HalfEdge

The basis for a half-edge data structure, also known as doubly connected edge list (DCEL).

Import

HalfEdge is an add-on, and must be imported explicitly. See Installation / Addons.

import { HalfEdge } from 'three/addons/math/ConvexHull.js';

Constructor

HalfEdge( vertex : VertexNode, face : Face )

vertex - VertexNode A reference to its destination vertex.
face - Face A reference to its face.

Creates a new instance of HalfEdge.

Properties

.vertex : VertexNode

Reference to the destination vertex. The origin vertex can be obtained by querying the destination of its twin, or of the previous half-edge. Default is undefined.

. : HalfEdge

Reference to the previous half-edge of the same face. Default is null.

. : HalfEdge

Reference to the next half-edge of the same face. Default is null.

.twin : HalfEdge

Reference to the twin half-edge to reach the opposite face. Default is null.

.face : Face

Each half-edge bounds a single face and thus has a reference to that face. Default is undefined.

Methods

.head () : VertexNode

Returns the destination vertex.

.tail () : VertexNode

Returns the origin vertex.

.length () : Float

Returns the Euclidean length (straight-line length) of the edge.

.lengthSquared () : Float

Returns the square of the Euclidean length (straight-line length) of the edge.

.setTwin ( edge : HalfEdge ) : this

edge - Any half-edge.

Sets the twin edge of this half-edge. It also ensures that the twin reference of the given half-edge is correctly set.

Source

examples/jsm/math/ConvexHull.js

ConvexHull

A convex hull class. Implements the Quickhull algorithm by: Dirk Gregorius. March 2014, Game Developers Conference: Implementing QuickHull.

Import

ConvexHull is an add-on, and must be imported explicitly. See Installation / Addons.

import { ConvexHull } from 'three/addons/math/ConvexHull.js';

Constructor

ConvexHull()

Creates a new instance of ConvexHull.

Properties

.assigned : VertexList

This vertex list holds all vertices that are assigned to a face. Default is an empty vertex list.

.faces : Array

The generated faces of the convex hull. Default is an empty array.

.newFaces : Array

This array holds the faces that are generated within a single iteration. Default is an empty array.

.tolerance : Float

The epsilon value that is used for internal comparative operations. The calculation of this value depends on the size of the geometry. Default is -1.

.unassigned : VertexList

This vertex list holds all vertices that are not assigned to a face. Default is an empty vertex list.

.vertices : Array

The internal representation of the given geometry data (an array of vertices).

Methods

.addAdjoiningFace ( eyeVertex : VertexNode, horizonEdge : HalfEdge ) : HalfEdge

eyeVertex - The vertex that is added to the hull.
horizonEdge - A single edge of the horizon.

Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head' in CCW order. All the half edges are created in CCW order thus the face is always pointing outside the hull

.addNewFaces ( eyeVertex : VertexNode, horizonEdge : HalfEdge ) : this

eyeVertex - The vertex that is added to the hull.
horizon - An array of half-edges that form the horizon.

Adds 'horizon.length' faces to the hull, each face will be linked with the horizon opposite face and the face on the left/right.

.addVertexToFace ( vertex : VertexNode, face : Face ) : this

vertex - The vertex to add.
face - The target face.

Adds a vertex to the 'assigned' list of vertices and assigns it to the given face.

.addVertexToHull ( eyeVertex : VertexNode ) : this

eyeVertex - The vertex that is added to the hull.

Adds a vertex to the hull with the following algorithm

.cleanup () : this

Cleans up internal properties after computing the convex hull.

.compute () : this

Starts the execution of the quick hull algorithm.

.computeExtremes () : Object

Computes the extremes values (min/max vectors) which will be used to compute the initial hull.

.computeHorizon ( eyePoint : Vector3, crossEdge : HalfEdge, face : Face, horizon : Array ) : this

eyePoint - The 3D-coordinates of a point.
crossEdge - The edge used to jump to the current face.
face - The current face being tested.
horizon - The edges that form part of the horizon in CCW order.

Computes a chain of half edges in CCW order called the 'horizon'. For an edge to be part of the horizon it must join a face that can see 'eyePoint' and a face that cannot see 'eyePoint'.

.computeInitialHull () : this

Computes the initial simplex assigning to its faces all the points that are candidates to form part of the hull.

.containsPoint ( point : Vector3 ) : this

point - A point in 3D space.

Returns true if the given point is inside this convex hull.

.deleteFaceVertices ( face : Face, absorbingFace : Face ) : this

face - The given face.
absorbingFace - An optional face that tries to absorb the vertices of the first face.

Removes all the visible vertices that 'face' is able to see.

.intersectRay ( ray : Ray, target : Vector3 ) : Vector3

ray - The given ray.
target - The target vector representing the intersection point.

Performs a ray intersection test with this convex hull. If no intersection is found, null is returned.

.intersectsRay ( ray : Ray ) : Boolean

ray - The given ray.

Returns true if the given ray intersects with this convex hull.

.makeEmpty () : this

Makes this convex hull empty.

.nextVertexToAdd () : VertexNode

Finds the next vertex to create faces with the current hull.

.reindexFaces () : this

Removes inactive (e.g. deleted) faces from the internal face list.

.removeAllVerticesFromFace ( face : Face ) : VertexNode

face - The given face.

Removes all the visible vertices that a given face is able to see which are stored in the 'assigned' vertex list.

.removeVertexFromFace ( vertex : VertexNode, face : Face ) : this

vertex - The vertex to remove.
face - The target face.

Removes a vertex from the 'assigned' list of vertices and from the given face. It also makes sure that the link from 'face' to the first vertex it sees in 'assigned' is linked correctly after the removal.

.resolveUnassignedPoints ( newFaces : Array ) : this

newFaces - An array of new faces.

Reassigns as many vertices as possible from the unassigned list to the new faces.

.setFromObject ( object : Object3D ) : this

object - Object3D to compute the convex hull of.

Computes the convex hull of an Object3D (including its children),accounting for the world transforms of both the object and its children.

.setFromPoints ( points : Array ) : this

points - Array of Vector3s that the resulting convex hull will contain.

Computes to convex hull for the given array of points.

Source

examples/jsm/math/ConvexHull.js

VertexNode

A vertex as a double linked list node.

Import

VertexNode is an add-on, and must be imported explicitly. See Installation / Addons.

import { VertexNode } from 'three/addons/math/ConvexHull.js';

Constructor

VertexNode( point : Vector3 )

point - Vector3 A point (x, y, z) in 3D space.

Creates a new instance of VertexNode.

Properties

.point : Vector3

A point (x, y, z) in 3D space. Default is undefined.

. : VertexNode

Reference to the previous vertex in the double linked list. Default is null.

. : VertexNode

Reference to the next vertex in the double linked list. Default is null.

.face : Face

Reference to the face that is able to see this vertex. Default is undefined.

Source

examples/jsm/math/ConvexHull.js

VertexList

A doubly linked list of vertices.

Import

VertexList is an add-on, and must be imported explicitly. See Installation / Addons.

import { VertexList } from 'three/addons/math/ConvexHull.js';

Constructor

VertexList()

Creates a new instance of VertexList.

Properties

.head : VertexNode

Reference to the first vertex of the linked list. Default is null.

.tail : VertexNode

Reference to the last vertex of the linked list. Default is null.

Methods

.first () : VertexNode

Returns the head reference.

.last () : VertexNode

Returns the tail reference.

.clear () : this

Clears the linked list.

.insertBefore ( target : Vertex, vertex : Vertex ) : this

target - The target vertex. It's assumed that this vertex belongs to the linked list.
vertex - The vertex to insert.

Inserts a vertex before a target vertex.

.insertAfter ( target : Vertex, vertex : Vertex ) : this

target - The target vertex. It's assumed that this vertex belongs to the linked list.
vertex - The vertex to insert.

Inserts a vertex after a target vertex.

.append ( vertex : Vertex ) : this

vertex - The vertex to append.

Appends a vertex to the end of the linked list.

.appendChain ( vertex : Vertex ) : this

vertex - The head vertex of a chain of vertices.

Appends a chain of vertices where the given vertex is the head.

.remove ( vertex : Vertex ) : this

vertex - The vertex to remove.

Removes a vertex from the linked list.

.removeSubList ( a : Vertex, b : Vertex ) : this

a - The head of the sublist.
b - The tail of the sublist.

Removes a sublist of vertices from the linked list.

.isEmpty () : Boolean

Returns true if the linked list is empty.

Source

examples/jsm/math/ConvexHull.js

CSS2DRenderer

CSS2DRenderer is a simplified version of CSS3DRenderer. The only transformation that is supported is translation.

The renderer is very useful if you want to combine HTML based labels with 3D objects. Here too, the respective DOM elements are wrapped into an instance of CSS2DObject and added to the scene graph.

CSS2DRenderer only supports 100% browser and display zoom.

Import

CSS2DRenderer is an add-on, and must be imported explicitly. See Installation / Addons.

import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';

Examples

css2d_label
molecules

Constructor

CSS2DRenderer( parameters : Object )

element - A HTMLElement where the renderer appends its child-elements. This corresponds to the domElement property below. If not passed in here, a new div element will be created.

Properties

.domElement : DOMElement

A HTMLElement where the renderer appends its child-elements.
This is automatically created by the renderer in the constructor (if not provided already).

Methods

.getSize () : Object

Returns an object containing the width and height of the renderer.

.render ( scene : Scene, camera : Camera ) : undefined

Renders a scene using a camera.

.setSize (width : Number, height : Number) : undefined

Resizes the renderer to (width, height).

Source

examples/jsm/renderers/CSS2DRenderer.js

CSS3DRenderer

CSS3DRenderer can be used to apply hierarchical 3D transformations to DOM elements via the CSS3 transform property. This renderer is particularly interesting if you want to apply 3D effects to a website without canvas based rendering. It can also be used in order to combine DOM elements with WebGL content.

There are, however, some important limitations:

CSS3DRendererCSS3DObjectCSS3DSprite

Import

CSS3DRenderer is an add-on, and must be imported explicitly. See Installation / Addons.

import { CSS3DRenderer } from 'three/addons/renderers/CSS3DRenderer.js';

Examples

molecules
orthographic camera
periodictable
sprites

Constructor

CSS3DRenderer( parameters : Object )

element - A HTMLElement where the renderer appends its child-elements. This corresponds to the domElement property below. If not passed in here, a new div element will be created.

Properties

.domElement : DOMElement

A HTMLElement where the renderer appends its child-elements.
This is automatically created by the renderer in the constructor (if not provided already).

Methods

.getSize () : Object

Returns an object containing the width and height of the renderer.

.render ( scene : Scene, camera : PerspectiveCamera ) : undefined

Renders a scene using a perspective camera.

.setSize (width : Number, height : Number) : undefined

Resizes the renderer to (width, height).

Source

examples/jsm/renderers/CSS3DRenderer.js

SVGRenderer

SVGRenderer can be used to render geometric data using SVG. The produced vector graphics are particular useful in the following use cases:

  • Animated logos or icons
  • Interactive 2D/3D diagrams or graphs
  • Interactive maps
  • Complex or animated user interfaces

SVGRenderer has various advantages. It produces crystal-clear and sharp output which is independent of the actual viewport resolution.
SVG elements can be styled via CSS. And they have good accessibility since it's possible to add metadata like title or description (useful for search engines or screen readers).

There are, however, some important limitations:

  • No advanced shading
  • No texture support
  • No shadow support

Import

SVGRenderer is an add-on, and must be imported explicitly. See Installation / Addons.

import { SVGRenderer } from 'three/addons/renderers/SVGRenderer.js';

Examples

lines
sandbox

Constructor

SVGRenderer()

Properties

.overdraw : Number

Number of fractional pixels to enlarge polygons in order to prevent anti-aliasing gaps. Range is [0..1]. Default is 0.5.

Methods

.clear () : undefined

Tells the renderer to clear its drawing surface.

.getSize () : Object

Returns an object containing the width and height of the renderer.

.render ( scene : Scene, camera : Camera ) : undefined

Renders a scene using a camera.

.setClearColor ( color : Color, alpha : number ) : undefined

Sets the clearColor and the clearAlpha.

.setPrecision ( precision : Number ) : undefined

Sets the precision of the data used to create a path.

.setQuality () : undefined

Sets the render quality. Possible values are low and high (default).

.setSize ( width : Number, height : Number ) : undefined

Resizes the renderer to (width, height).

Source

examples/jsm/renderers/SVGRenderer.js

BufferGeometryUtils

A class containing utility functions for BufferGeometry instances.

Import

BufferGeometryUtils is an add-on, and must be imported explicitly. See Installation / Addons.

import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';

Methods

.computeMikkTSpaceTangents ( geometry : BufferGeometry, MikkTSpace : Object, negateSign : Boolean = true ) : Object

Computes vertex tangents using the MikkTSpace algorithm. MikkTSpace generates the same tangents consistently, and is used in most modelling tools and normal map bakers. Use MikkTSpace for materials with normal maps, because inconsistent tangents may lead to subtle visual issues in the normal map, particularly around mirrored UV seams.

In comparison to this method, BufferGeometry.computeTangents (a custom algorithm) generates tangents that probably will not match the tangents in other software. The custom algorithm is sufficient for general use with a ShaderMaterial, and may be faster than MikkTSpace.

Returns the original BufferGeometry. Indexed geometries will be de-indexed. Requires position, normal, and uv attributes.

.computeMorphedAttributes ( [param:Mesh | Line | Points object] ) : Object

object -- Instance of Mesh | Line | Points.

Returns the current attributes (Position and Normal) of a morphed/skinned Object3D whose geometry is a BufferGeometry, together with the original ones: An Object with 4 properties: positionAttribute, normalAttribute, morphedPositionAttribute and morphedNormalAttribute. Helpful for Raytracing or Decals (i.e. a DecalGeometry applied to a morphed Object with a BufferGeometry will use the original BufferGeometry, not the morphed/skinned one, generating an incorrect result. Using this function to create a shadow Object3D the DecalGeometry can be correctly generated).

.estimateBytesUsed ( geometry : BufferGeometry ) : Number

geometry -- Instance of BufferGeometry to estimate the memory use of.

Returns the amount of bytes used by all attributes to represent the geometry.

.interleaveAttributes ( attributes : Array ) : InterleavedBufferAttribute

attributes -- Array of BufferAttribute instances.

Interleaves a set of attributes and returns a new array of corresponding attributes that share a single InterleavedBuffer instance. All attributes must have compatible types. If merge does not succeed, the method returns null.

.mergeAttributes ( attributes : Array ) : BufferAttribute

attributes -- Array of BufferAttribute instances.

Merges a set of attributes into a single instance. All attributes must have compatible properties and types, and InterleavedBufferAttributes are not supported. If merge does not succeed, the method returns null.

.mergeGeometries ( geometries : Array, useGroups : Boolean ) : BufferGeometry

geometries -- Array of BufferGeometry instances.
useGroups -- Whether groups should be generated for the merged geometry or not.

Merges a set of geometries into a single instance. All geometries must have compatible attributes. If merge does not succeed, the method returns null.

.mergeGroups ( geometry : BufferGeometry ) : BufferGeometry

geometry -- Instance of BufferGeometry to merge the groups of.

Merges the groups for the given geometry.

.mergeVertices ( geometry : BufferGeometry, tolerance : Number ) : BufferGeometry

geometry -- Instance of BufferGeometry to merge the vertices of.
tolerance -- The maximum allowable difference between vertex attributes to merge. Defaults to 1e-4.

Returns a new BufferGeometry with vertices for which all similar vertex attributes (within tolerance) are merged.

.toCreasedNormals ( geometry : BufferGeometry, creaseAngle : Number ) : BufferGeometry

Modifies the supplied geometry if it is non-indexed, otherwise creates a new, non-indexed geometry.

Returns the geometry with smooth normals everywhere except faces that meet at an angle greater than the crease angle.

.toTrianglesDrawMode ( geometry : BufferGeometry, drawMode : TrianglesDrawMode ) : BufferGeometry

geometry -- Instance of BufferGeometry.
drawMode -- The draw mode of the given geometry. Valid inputs are THREE.TriangleStripDrawMode and THREE.TriangleFanDrawMode.

Returns a new indexed geometry based on THREE.TrianglesDrawMode draw mode. This mode corresponds to the gl.TRIANGLES WebGL primitive.

Source

examples/jsm/utils/BufferGeometryUtils.js

CameraUtils

A class containing useful utility functions for camera manipulation.

Import

CameraUtils is an add-on, and must be imported explicitly. See Installation / Addons.

import * as CameraUtils from 'three/addons/utils/CameraUtils.js';

Methods

.frameCorners ( camera : PerspectiveCamera, bottomLeftCorner : Vector3, bottomRightCorner : Vector3, topLeftCorner : Vector3, estimateViewFrustum : boolean ) : undefined

Set a PerspectiveCamera's projectionMatrix and quaternion to exactly frame the corners of an arbitrary rectangle using Kooima's Generalized Perspective Projection formulation. NOTE: This function ignores the standard parameters; do not call updateProjectionMatrix() after this! toJSON will also not capture the off-axis matrix generated by this function.

Source

examples/jsm/utils/CameraUtils.js

SceneUtils

A class containing useful utility functions for scene manipulation.

Import

SceneUtils is an add-on, and must be imported explicitly. See Installation / Addons.

import * as SceneUtils from 'three/addons/utils/SceneUtils.js';

Methods

.createMeshesFromInstancedMesh ( instancedMesh : InstancedMesh ) : Group

instancedMesh -- The instanced mesh.

Creates a new group object that contains a new mesh for each instance of the given instanced mesh.

.createMeshesFromMultiMaterialMesh ( mesh : Mesh ) : Group

mesh -- A mesh with multiple materials.

Converts the given multi-material mesh into an instance of Group holding for each material a separate mesh.

.createMultiMaterialObject ( geometry : BufferGeometry, materials : Array ) : Group

geometry -- The geometry for the set of materials.
materials -- The materials for the object.

Creates a new Group that contains a new mesh for each material defined in materials. Beware that this is not the same as an array of materials which defines multiple materials for 1 mesh.
This is mostly useful for objects that need both a material and a wireframe implementation.

.reduceVertices ( object : Object3D, func : function, initialValue : T ) : T

object -- The object to traverse (uses traverseVisible internally).
func -- The binary function applied for the reduction. Must have the signature: (value: T, vertex: Vector3): T.
initialValue -- The value to initialize the reduction with. This is required as it also sets the reduction type, which is not required to be Vector3.

Akin to Array.prototype.reduce(), but operating on the vertices of all the visible descendant objects, in world space. Additionally, it can operate as a transform-reduce, returning a different type T than the Vector3 input. This can be useful for e.g. fitting a viewing frustum to the scene.

.sortInstancedMesh ( mesh : InstancedMesh, compareFn : Function ) : undefined

mesh -- InstancedMesh in which instances will be sorted.
compareFn -- Comparator function defining the sort order.

Sorts the instances within an InstancedMesh, according to a user-defined callback. The callback will be provided with two arguments, indexA and indexB, and must return a numerical value. See Array.prototype.sort for more information on sorting callbacks and their return values.

Because of the high performance cost, three.js does not sort InstancedMesh instances automatically. Manually sorting may be helpful to improve display of alpha blended materials (back to front), and to reduce overdraw in opaque materials (front to back).

.traverseGenerator ( object : Object3D ) : Generator

object -- The 3D object to traverse.

A generator based version of Object3D.traverse().

.traverseVisibleGenerator ( object : Object3D ) : Generator

object -- The 3D object to traverse.

A generator based version of Object3D.traverseVisible().

.traverseAncestorsGenerator ( object : Object3D ) : Generator

object -- The 3D object to traverse.

A generator based version of Object3D.traverseAncestors().

Source

examples/jsm/utils/SceneUtils.js

SkeletonUtils

Utility functions for Skeleton, SkinnedMesh, and Bone manipulation.

Import

SkeletonUtils is an add-on, and must be imported explicitly. See Installation / Addons.

import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';

Methods

.clone ( object : Object3D ) : Object3D

Clones the given object and its descendants, ensuring that any SkinnedMesh instances are correctly associated with their bones. Bones are also cloned, and must be descendants of the object passed to this method. Other data, like geometries and materials, are reused by reference.

.retarget ( target : SkeletonHelper, source : SkeletonHelper, options : Object ) : undefined

.retargetClip ( target : SkeletonHelper, source : SkeletonHelper, clip : AnimationClip, options : Object ) : AnimationClip

Source

examples/jsm/utils/SkeletonUtils.js

Group

XREstimatedLight

XREstimatedLight uses WebXR's light estimation to create a light probe, a directional light, and (optionally) an environment map that model the user's real-world environment and lighting.
As WebXR updates the light and environment estimation, XREstimatedLight automatically updates the light probe, directional light, and environment map.

It's important to specify light-estimation as an optional or required feature when creating the WebXR session, otherwise the light estimation can't work.

See here for browser compatibility information, as this is still an experimental feature in WebXR.

To use this, as with all files in the /examples directory, you will have to include the file separately in your HTML.

Import

XREstimatedLight is an add-on, and must be imported explicitly. See Installation / Addons.

import { XREstimatedLight } from 'three/addons/webxr/XREstimatedLight.js';

Code Example

renderer.xr.enabled = true; // Don't add the XREstimatedLight to the scene initially. // It doesn't have any estimated lighting values until an AR session starts. const xrLight = new XREstimatedLight( renderer ); xrLight.addEventListener( 'estimationstart' , () => { scene.add( xrLight ); if ( xrLight.environment ) { scene.environment = xrLight.environment; } } ); xrLight.addEventListener( 'estimationend', () => { scene.remove( xrLight ); scene.environment = null; } ); // In order for lighting estimation to work, 'light-estimation' must be included as either // an optional or required feature. document.body.appendChild( XRButton.createButton( renderer, { optionalFeatures: [ 'light-estimation' ] } ) );

Examples

webxr / light estimation

Constructor

XREstimatedLight( renderer : WebGLRenderer, environmentEstimation : Boolean )

renderer: (required) The renderer used to render the Scene. Mainly used to interact with WebXRManager.

environmentEstimation: If true, use WebXR to estimate an environment map.

Events

estimationstart

Fires when the estimated lighting values start being updated.

estimationend

Fires when the estimated lighting values stop being updated.

Properties

.environment : Texture

The environment map estimated by WebXR. This is only available if environmentEstimation is true.

It can be used as the Scene.environment, for MeshStandardMaterial.envMap, or as the Scene.background.

Source

examples/jsm/webxr/XREstimatedLight.js

WebGLProgram

Constructor for the GLSL program sent to vertex and fragment shaders, including default uniforms and attributes.

Built-in uniforms and attributes

Vertex shader (unconditional):

// = object.matrixWorld uniform mat4 modelMatrix; // = camera.matrixWorldInverse * object.matrixWorld uniform mat4 modelViewMatrix; // = camera.projectionMatrix uniform mat4 projectionMatrix; // = camera.matrixWorldInverse uniform mat4 viewMatrix; // = inverse transpose of modelViewMatrix uniform mat3 normalMatrix; // = camera position in world space uniform vec3 cameraPosition; // default vertex attributes provided by BufferGeometry attribute vec3 position; attribute vec3 normal; attribute vec2 uv;

Note that you can therefore calculate the position of a vertex in the vertex shader by: gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); or alternatively gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 );

Vertex shader (conditional):

#ifdef USE_TANGENT attribute vec4 tangent; #endif #if defined( USE_COLOR_ALPHA ) // vertex color attribute with alpha attribute vec4 color; #elif defined( USE_COLOR ) // vertex color attribute attribute vec3 color; #endif #ifdef USE_MORPHTARGETS attribute vec3 morphTarget0; attribute vec3 morphTarget1; attribute vec3 morphTarget2; attribute vec3 morphTarget3; #ifdef USE_MORPHNORMALS attribute vec3 morphNormal0; attribute vec3 morphNormal1; attribute vec3 morphNormal2; attribute vec3 morphNormal3; #else attribute vec3 morphTarget4; attribute vec3 morphTarget5; attribute vec3 morphTarget6; attribute vec3 morphTarget7; #endif #endif #ifdef USE_SKINNING attribute vec4 skinIndex; attribute vec4 skinWeight; #endif #ifdef USE_INSTANCING // Note that modelViewMatrix is not set when rendering an instanced model, // but can be calculated from viewMatrix * modelMatrix. // // Basic Usage: // gl_Position = projectionMatrix * viewMatrix * modelMatrix * instanceMatrix * vec4(position, 1.0); attribute mat4 instanceMatrix; #endif

Fragment shader:

uniform mat4 viewMatrix; uniform vec3 cameraPosition;

Constructor

WebGLProgram( renderer : WebGLRenderer, cacheKey : String, parameters : Object )

For parameters see WebGLRenderer.

Properties

.name : String

The name of the respective shader program.

.id : String

The identifier of this instance.

.cacheKey : String

This key enables the reusability of a single WebGLProgram for different materials.

.usedTimes : Integer

How many times this instance is used for rendering render items.

.program : Object

The actual shader program.

.vertexShader : WebGLShader

The vertex shader.

.fragmentShader : WebGLShader

The fragment shader.

Methods

.getUniforms () : Object

Returns a name-value mapping of all active uniform locations.

.getAttributes () : Object

Returns a name-value mapping of all active vertex attribute locations.

.destroy () : undefined

Destroys an instance of WebGLProgram.

Source

src/renderers/webgl/WebGLProgram.js