From 52a612f3c34896b615798a0e3fc354205df93a1f Mon Sep 17 00:00:00 2001 From: Michael Herzog Date: Thu, 27 Feb 2025 11:03:32 +0100 Subject: [PATCH] Docs: More JSDoc. (#30620) --- src/loaders/AnimationLoader.js | 31 ++++ src/loaders/AudioLoader.js | 31 ++++ src/loaders/BufferGeometryLoader.js | 34 ++++ src/loaders/Cache.js | 45 +++++ src/loaders/CompressedTextureLoader.js | 27 ++- src/loaders/CubeTextureLoader.js | 45 +++++ src/loaders/DataTextureLoader.js | 27 ++- src/loaders/FileLoader.js | 57 +++++++ src/loaders/ImageBitmapLoader.js | 57 +++++++ src/loaders/ImageLoader.js | 30 ++++ src/loaders/Loader.js | 2 - src/loaders/LoaderUtils.js | 26 +++ src/loaders/LoadingManager.js | 142 ++++++++++++++++ src/loaders/MaterialLoader.js | 57 +++++++ src/loaders/ObjectLoader.js | 53 ++++++ src/loaders/TextureLoader.js | 33 ++++ src/math/MathUtils.js | 223 +++++++++++++++++++++++++ utils/docs/jsdoc.config.json | 3 +- 18 files changed, 913 insertions(+), 10 deletions(-) diff --git a/src/loaders/AnimationLoader.js b/src/loaders/AnimationLoader.js index 661dab954034cd..80fe6399722d5b 100644 --- a/src/loaders/AnimationLoader.js +++ b/src/loaders/AnimationLoader.js @@ -2,14 +2,39 @@ import { AnimationClip } from '../animation/AnimationClip.js'; import { FileLoader } from './FileLoader.js'; import { Loader } from './Loader.js'; +/** + * Class for loading animation clips in the JSON format. The files are internally + * loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.AnimationLoader(); + * const animations = await loader.loadAsync( 'animations/animation.js' ); + * ``` + * + * @augments Loader + */ class AnimationLoader extends Loader { + /** + * Constructs a new animation loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and pass the loaded animations as an array + * holding instances of {@link AnimationClip} to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Array)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ load( url, onLoad, onProgress, onError ) { const scope = this; @@ -44,6 +69,12 @@ class AnimationLoader extends Loader { } + /** + * Parses the given JSON object and returns an array of animation clips. + * + * @param {Object} json - The serialized animation clips. + * @return {Array} The parsed animation clips. + */ parse( json ) { const animations = []; diff --git a/src/loaders/AudioLoader.js b/src/loaders/AudioLoader.js index cc42e8f6705cac..58fb739bf015b3 100644 --- a/src/loaders/AudioLoader.js +++ b/src/loaders/AudioLoader.js @@ -2,14 +2,45 @@ import { AudioContext } from '../audio/AudioContext.js'; import { FileLoader } from './FileLoader.js'; import { Loader } from './Loader.js'; +/** + * Class for loading audio buffers. Audios are internally + * loaded via {@link FileLoader}. + * + * ```js + * const audioListener = new THREE.AudioListener(); + * const ambientSound = new THREE.Audio( audioListener ); + * + * const loader = new THREE.AudioLoader(); + * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' ); + * + * ambientSound.setBuffer( audioBuffer ); + * ambientSound.play(); + * ``` + * + * @augments Loader + */ class AudioLoader extends Loader { + /** + * Constructs a new audio loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and passes the loaded audio buffer + * to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ load( url, onLoad, onProgress, onError ) { const scope = this; diff --git a/src/loaders/BufferGeometryLoader.js b/src/loaders/BufferGeometryLoader.js index dd8a7d8f150719..a93dfaba4b4003 100644 --- a/src/loaders/BufferGeometryLoader.js +++ b/src/loaders/BufferGeometryLoader.js @@ -10,14 +10,42 @@ import { InterleavedBufferAttribute } from '../core/InterleavedBufferAttribute.j import { InterleavedBuffer } from '../core/InterleavedBuffer.js'; import { getTypedArray } from '../utils.js'; +/** + * Class for loading geometries. The files are internally + * loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.BufferGeometryLoader(); + * const geometry = await loader.loadAsync( 'models/json/pressure.json' ); + * + * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } ); + * const object = new THREE.Mesh( geometry, material ); + * scene.add( object ); + * ``` + * + * @augments Loader + */ class BufferGeometryLoader extends Loader { + /** + * Constructs a new geometry loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ load( url, onLoad, onProgress, onError ) { const scope = this; @@ -52,6 +80,12 @@ class BufferGeometryLoader extends Loader { } + /** + * Parses the given JSON object and returns a geometry. + * + * @param {Object} json - The serialized geometry. + * @return {BufferGeometry} The parsed geometry. + */ parse( json ) { const interleavedBufferMap = {}; diff --git a/src/loaders/Cache.js b/src/loaders/Cache.js index 25af8cd283a482..f830551e992a0c 100644 --- a/src/loaders/Cache.js +++ b/src/loaders/Cache.js @@ -1,9 +1,36 @@ +/** + * @class + * @classdesc A simple caching system, used internally by {@link FileLoader}. + * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app. + * @hideconstructor + */ const Cache = { + /** + * Whether caching is enabled or not. + * + * @static + * @type {boolean} + * @default false + */ enabled: false, + /** + * A dictionary that holds cached files. + * + * @static + * @type {Object} + */ files: {}, + /** + * Adds a cache entry with a key to reference the file. If this key already + * holds a file, it is overwritten. + * + * @static + * @param {string} key - The key to reference the cached file. + * @param {Object} file - The file to be cached. + */ add: function ( key, file ) { if ( this.enabled === false ) return; @@ -14,6 +41,13 @@ const Cache = { }, + /** + * Gets the cached value for the given key. + * + * @static + * @param {string} key - The key to reference the cached file. + * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned. + */ get: function ( key ) { if ( this.enabled === false ) return; @@ -24,12 +58,23 @@ const Cache = { }, + /** + * Removes the cached file associated with the given key. + * + * @static + * @param {string} key - The key to reference the cached file. + */ remove: function ( key ) { delete this.files[ key ]; }, + /** + * Remove all values from the cache. + * + * @static + */ clear: function () { this.files = {}; diff --git a/src/loaders/CompressedTextureLoader.js b/src/loaders/CompressedTextureLoader.js index 02ef233412d314..38460e01ec3be0 100644 --- a/src/loaders/CompressedTextureLoader.js +++ b/src/loaders/CompressedTextureLoader.js @@ -4,19 +4,40 @@ import { CompressedTexture } from '../textures/CompressedTexture.js'; import { Loader } from './Loader.js'; /** - * Abstract Base class to block based textures loader (dds, pvr, ...) + * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC. + * Textures are internally loaded via {@link FileLoader}. * - * Sub classes have to implement the parse() method which will be used in load(). + * Derived classes have to implement the `parse()` method which holds the parsing + * for the respective format. + * + * @abstract + * @augments Loader */ - class CompressedTextureLoader extends Loader { + /** + * Constructs a new compressed texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and passes the loaded compressed texture + * to the `onLoad()` callback. 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. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {CompressedTexture} The compressed texture. + */ load( url, onLoad, onProgress, onError ) { const scope = this; diff --git a/src/loaders/CubeTextureLoader.js b/src/loaders/CubeTextureLoader.js index 5115f570df2f59..642a452882b43e 100644 --- a/src/loaders/CubeTextureLoader.js +++ b/src/loaders/CubeTextureLoader.js @@ -3,14 +3,59 @@ import { CubeTexture } from '../textures/CubeTexture.js'; import { Loader } from './Loader.js'; import { SRGBColorSpace } from '../constants.js'; +/** + * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}. + * + * The loader returns an instance of {@link 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. + * + * 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. + * + * The loaded cube textureis in sRGB color space. Meaning {@link Texture#colorSpace} + * is set to `SRGBColorSpace` by default. + * + * ```js + * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' ); + * const cubeTexture = await loader.loadAsync( [ + * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png' + * ] ); + * scene.background = cubeTexture; + * ``` + * + * @augments Loader + */ class CubeTextureLoader extends Loader { + /** + * Constructs a new cube texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and pass the fully loaded cube texture + * to the `onLoad()` callback. The method also returns a new cube texture object which can + * directly be used for material creation. If you do it this way, the cube texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {Array} urls - Array of 6 URLs to images, one for each side of the + * cube texture. The urls should be specified in the following order: pos-x, + * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well. + * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {CubeTexture} The cube texture. + */ load( urls, onLoad, onProgress, onError ) { const texture = new CubeTexture(); diff --git a/src/loaders/DataTextureLoader.js b/src/loaders/DataTextureLoader.js index 8a730ba06ed457..1f25bf994a38e9 100644 --- a/src/loaders/DataTextureLoader.js +++ b/src/loaders/DataTextureLoader.js @@ -4,19 +4,40 @@ import { DataTexture } from '../textures/DataTexture.js'; import { Loader } from './Loader.js'; /** - * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) + * Abstract base class for loading binary texture formats RGBE, EXR or TGA. + * Textures are internally loaded via {@link FileLoader}. * - * Sub classes have to implement the parse() method which will be used in load(). + * Derived classes have to implement the `parse()` method which holds the parsing + * for the respective format. + * + * @abstract + * @augments Loader */ - class DataTextureLoader extends Loader { + /** + * Constructs a new data texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and passes the loaded data texture + * to the `onLoad()` callback. 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. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {DataTexture} The data texture. + */ load( url, onLoad, onProgress, onError ) { const scope = this; diff --git a/src/loaders/FileLoader.js b/src/loaders/FileLoader.js index b558d01a7e631c..d3edfa15521b82 100644 --- a/src/loaders/FileLoader.js +++ b/src/loaders/FileLoader.js @@ -14,14 +14,59 @@ class HttpError extends Error { } +/** + * A low level class for loading resources with the Fetch API, used internally by + * most loaders. It can also be used directly to load any file type that does + * not have a loader. + * + * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;` + * once to your application. + * + * ```js + * const loader = new THREE.FileLoader(); + * const data = await loader.loadAsync( 'example.txt' ); + * ``` + * + * @augments Loader + */ class FileLoader extends Loader { + /** + * Constructs a new file loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); + /** + * The expected mime type. + * + * @type {string|undefined} + * @default undefined + */ + this.mimeType = undefined; + + /** + * The expected response type. + * + * @type {('arraybuffer'|'blob'|'document'|'json'|''|undefined)} + * @default undefined + */ + this.responseType = undefined; + } + /** + * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(any)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {any|undefined} The cached resource if available. + */ load( url, onLoad, onProgress, onError ) { if ( url === undefined ) url = ''; @@ -268,6 +313,12 @@ class FileLoader extends Loader { } + /** + * Sets the expected response type. + * + * @param {('arraybuffer'|'blob'|'document'|'json'|''|undefined)} value - The response type. + * @return {FileLoader} A reference to this file loader. + */ setResponseType( value ) { this.responseType = value; @@ -275,6 +326,12 @@ class FileLoader extends Loader { } + /** + * Sets the expected mime type of the loaded file. + * + * @param {string|undefined} value - The mime type. + * @return {FileLoader} A reference to this file loader. + */ setMimeType( value ) { this.mimeType = value; diff --git a/src/loaders/ImageBitmapLoader.js b/src/loaders/ImageBitmapLoader.js index 986e23cad9fdd0..d68756e6490f08 100644 --- a/src/loaders/ImageBitmapLoader.js +++ b/src/loaders/ImageBitmapLoader.js @@ -1,12 +1,47 @@ import { Cache } from './Cache.js'; import { Loader } from './Loader.js'; +/** + * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}. + * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare + * textures for rendering. + * + * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps. + * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU. + * + * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead. + * + * Also note that unlike {@link FileLoader}, this loader does not avoid multiple concurrent requests to the same URL. + * + * ```js + * const loader = new THREE.ImageBitmapLoader(); + * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed + * const imageBitmap = await loader.loadAsync( 'image.png' ); + * + * const texture = new THREE.Texture( imageBitmap ); + * texture.needsUpdate = true; + * ``` + * + * @augments Loader + */ class ImageBitmapLoader extends Loader { + /** + * Constructs a new image bitmap loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); + /** + * This flag can be used for type testing. + * + * @type {boolean} + * @readonly + * @default true + */ this.isImageBitmapLoader = true; if ( typeof createImageBitmap === 'undefined' ) { @@ -21,10 +56,23 @@ class ImageBitmapLoader extends Loader { } + /** + * Represents the loader options. + * + * @type {Object} + * @default {premultiplyAlpha:'none'} + */ this.options = { premultiplyAlpha: 'none' }; } + /** + * Sets the given loader options. The structure of the object must match the `options` parameter of + * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}. + * + * @param {Object} options - The loader options to set. + * @return {ImageBitmapLoader} A reference to this image bitmap loader. + */ setOptions( options ) { this.options = options; @@ -33,6 +81,15 @@ class ImageBitmapLoader extends Loader { } + /** + * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {ImageBitmap|undefined} The image bitmap. + */ load( url, onLoad, onProgress, onError ) { if ( url === undefined ) url = ''; diff --git a/src/loaders/ImageLoader.js b/src/loaders/ImageLoader.js index c6d593c27baa12..287b14a42c60f9 100644 --- a/src/loaders/ImageLoader.js +++ b/src/loaders/ImageLoader.js @@ -2,14 +2,44 @@ import { Cache } from './Cache.js'; import { Loader } from './Loader.js'; import { createElementNS } from '../utils.js'; +/** + * A loader for loading images. The class loads images with the HTML `Image` API. + * + * ```js + * const loader = new THREE.ImageLoader(); + * const image = await loader.loadAsync( 'image.png' ); + * ``` + * Please note that `ImageLoader` has dropped support for progress + * events in `r84`. For an `ImageLoader` that supports progress events, see + * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}. + * + * @augments Loader + */ class ImageLoader extends Loader { + /** + * Constructs a new image loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and passes the loaded image + * to the `onLoad()` callback. The method also returns a new `Image` object which can + * directly be used for texture creation. If you do it this way, the texture + * may pop up in your scene once the respective loading process is finished. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Image)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {Image} The image. + */ load( url, onLoad, onProgress, onError ) { if ( this.path !== undefined ) url = this.path + url; diff --git a/src/loaders/Loader.js b/src/loaders/Loader.js index 426a64bdb2ea71..563e76e66b6f4c 100644 --- a/src/loaders/Loader.js +++ b/src/loaders/Loader.js @@ -176,7 +176,6 @@ class Loader { /** * Callback for onProgress in loaders. * - * * @callback onProgressCallback * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status. */ @@ -184,7 +183,6 @@ class Loader { /** * Callback for onError in loaders. * - * * @callback onErrorCallback * @param {Error} error - The error which occurred during the loading process. */ diff --git a/src/loaders/LoaderUtils.js b/src/loaders/LoaderUtils.js index 0b499146a80750..68a2e6e0dec5b3 100644 --- a/src/loaders/LoaderUtils.js +++ b/src/loaders/LoaderUtils.js @@ -1,5 +1,16 @@ +/** + * A class with loader utility functions. + */ class LoaderUtils { + /** + * The function takes a stream of bytes as input and returns a string + * representation. + * + * @deprecated since r165. Use the native `TextDecoder` API instead. + * @param {TypedArray} array - A stream of bytes as a typed array. + * @return {string} The decoded text. + */ static decodeText( array ) { // @deprecated, r165 console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' ); @@ -36,6 +47,12 @@ class LoaderUtils { } + /** + * Extracts the base URL from the given URL. + * + * @param {string} url -The URL to extract the base URL from. + * @return {string} The extracted base URL. + */ static extractUrlBase( url ) { const index = url.lastIndexOf( '/' ); @@ -46,6 +63,15 @@ class LoaderUtils { } + /** + * 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. + * + * @param {string} url -The URL to resolve. + * @param {string} path - The base path for relative URLs to be resolved against. + * @return {string} The resolved URL. + */ static resolveURL( url, path ) { // Invalid URL diff --git a/src/loaders/LoadingManager.js b/src/loaders/LoadingManager.js index 4d53e5768a22b1..bae742a457c878 100644 --- a/src/loaders/LoadingManager.js +++ b/src/loaders/LoadingManager.js @@ -1,5 +1,29 @@ +/** + * 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. + * + * 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. + * + * ```js + * const manager = new THREE.LoadingManager(); + * manager.onLoad = () => console.log( 'Loading complete!' ); + * + * const loader1 = new OBJLoader( manager ); + * const loader2 = new ColladaLoader( manager ); + * ``` + */ class LoadingManager { + /** + * Constructs a new loading manager. + * + * @param {Function} [onLoad] - Executes when all items have been loaded. + * @param {Function} [onProgress] - Executes when single items have been loaded. + * @param {Function} [onError] - Executes when an error occurs. + */ constructor( onLoad, onProgress, onError ) { const scope = this; @@ -13,11 +37,44 @@ class LoadingManager { // Refer to #5689 for the reason why we don't set .onStart // in the constructor + /** + * Executes when an item starts loading. + * + * @type {Function|undefined} + * @default undefined + */ this.onStart = undefined; + + /** + * Executes when all items have been loaded. + * + * @type {Function|undefined} + * @default undefined + */ this.onLoad = onLoad; + + /** + * Executes when single items have been loaded. + * + * @type {Function|undefined} + * @default undefined + */ this.onProgress = onProgress; + + /** + * Executes when an error occurs. + * + * @type {Function|undefined} + * @default undefined + */ this.onError = onError; + /** + * This should be called by any loader using the manager when the loader + * starts loading an item. + * + * @param {string} url - The URL to load. + */ this.itemStart = function ( url ) { itemsTotal ++; @@ -36,6 +93,12 @@ class LoadingManager { }; + /** + * This should be called by any loader using the manager when the loader + * ended loading an item. + * + * @param {string} url - The URL of the loaded item. + */ this.itemEnd = function ( url ) { itemsLoaded ++; @@ -60,6 +123,12 @@ class LoadingManager { }; + /** + * This should be called by any loader using the manager when the loader + * encounters an error when loading an item. + * + * @param {string} url - The URL of the item that produces an error. + */ this.itemError = function ( url ) { if ( scope.onError !== undefined ) { @@ -70,6 +139,13 @@ class LoadingManager { }; + /** + * 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. + * + * @param {string} url - The URL to load. + * @return {string} The resolved URL. + */ this.resolveURL = function ( url ) { if ( urlModifier ) { @@ -82,6 +158,40 @@ class LoadingManager { }; + /** + * 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. + * + * ```js + * 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 ) ); + * + * } ); + * ``` + * + * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL. + * @return {LoadingManager} A reference to this loading manager. + */ this.setURLModifier = function ( transform ) { urlModifier = transform; @@ -90,6 +200,20 @@ class LoadingManager { }; + /** + * 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. + * + * ```js + * // add handler for TGA textures + * manager.addHandler( /\.tga$/i, new TGALoader() ); + * ``` + * + * @param {string} regex - A regular expression. + * @param {Loader} loader - A loader that should handle matched cases. + * @return {LoadingManager} A reference to this loading manager. + */ this.addHandler = function ( regex, loader ) { handlers.push( regex, loader ); @@ -98,6 +222,12 @@ class LoadingManager { }; + /** + * Removes the loader for the given regular expression. + * + * @param {string} regex - A regular expression. + * @return {LoadingManager} A reference to this loading manager. + */ this.removeHandler = function ( regex ) { const index = handlers.indexOf( regex ); @@ -112,6 +242,12 @@ class LoadingManager { }; + /** + * Can be used to retrieve the registered loader for the given file path. + * + * @param {string} file - The file path. + * @return {?Loader} The registered loader. Returns `null` if no loader was found. + */ this.getHandler = function ( file ) { for ( let i = 0, l = handlers.length; i < l; i += 2 ) { @@ -137,6 +273,12 @@ class LoadingManager { } +/** + * The global default loading manager. + * + * @constant + * @type {LoadingManager} + */ const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager(); export { DefaultLoadingManager, LoadingManager }; diff --git a/src/loaders/MaterialLoader.js b/src/loaders/MaterialLoader.js index bc5349d236874b..d76c4b6f5b42f0 100644 --- a/src/loaders/MaterialLoader.js +++ b/src/loaders/MaterialLoader.js @@ -27,15 +27,46 @@ import { Material, } from '../materials/Materials.js'; +/** + * Class for loading geometries. The files are internally + * loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.MaterialLoader(); + * const material = await loader.loadAsync( 'material.json' ); + * ``` + * This loader does not support node materials. Use {@link NodeMaterialLoader} instead. + * + * @augments Loader + */ class MaterialLoader extends Loader { + /** + * Constructs a new material loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); + + /** + * A dictionary holding textures used by the material. + * + * @type {Object} + */ this.textures = {}; } + /** + * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Material)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ load( url, onLoad, onProgress, onError ) { const scope = this; @@ -70,6 +101,12 @@ class MaterialLoader extends Loader { } + /** + * Parses the given JSON object and returns a material. + * + * @param {Object} json - The serialized material. + * @return {Material} The parsed material. + */ parse( json ) { const textures = this.textures; @@ -335,6 +372,13 @@ class MaterialLoader extends Loader { } + /** + * Textures are not embebbed in the material JSON so they have + * to be injected before the loading process starts. + * + * @param {Object} value - A dictionary holding textures for material properties. + * @return {MaterialLoader} A reference to this material loader. + */ setTextures( value ) { this.textures = value; @@ -342,12 +386,25 @@ class MaterialLoader extends Loader { } + /** + * Creates a material for the given type. + * + * @param {string} type - The material type. + * @return {Material} The new material. + */ createMaterialFromType( type ) { return MaterialLoader.createMaterialFromType( type ); } + /** + * Creates a material for the given type. + * + * @static + * @param {string} type - The material type. + * @return {Material} The new material. + */ static createMaterialFromType( type ) { const materialLib = { diff --git a/src/loaders/ObjectLoader.js b/src/loaders/ObjectLoader.js index 89f66255f03a3d..c70ccd17380f21 100644 --- a/src/loaders/ObjectLoader.js +++ b/src/loaders/ObjectLoader.js @@ -63,14 +63,43 @@ import { getTypedArray } from '../utils.js'; import { Box3 } from '../math/Box3.js'; import { Sphere } from '../math/Sphere.js'; +/** + * A loader for loading a JSON resource in the [JSON Object/Scene format]{@link https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4}. + * The files are internally loaded via {@link FileLoader}. + * + * ```js + * const loader = new THREE.ObjectLoader(); + * const obj = await loader.loadAsync( 'models/json/example.json' ); + * scene.add( obj ); + * + * // Alternatively, to parse a previously loaded JSON structure + * const object = await loader.parseAsync( a_json_object ); + * scene.add( object ); + * ``` + * + * @augments Loader + */ class ObjectLoader extends Loader { + /** + * Constructs a new object loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Object3D)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @param {onErrorCallback} onError - Executed when errors occur. + */ load( url, onLoad, onProgress, onError ) { const scope = this; @@ -117,6 +146,14 @@ class ObjectLoader extends Loader { } + /** + * Async version of {@link ObjectLoader#load}. + * + * @async + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {onProgressCallback} onProgress - Executed while the loading is in progress. + * @return {Promise} A Promise that resolves with the loaded 3D object. + */ async loadAsync( url, onProgress ) { const scope = this; @@ -145,6 +182,14 @@ class ObjectLoader extends Loader { } + /** + * Parses the given JSON. This is used internally by {@link ObjectLoader#load} + * but can also be used directly to parse a previously loaded JSON structure. + * + * @param {Object} json - The serialized 3D object. + * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded. + * @return {Object3D} The parsed 3D object. + */ parse( json, onLoad ) { const animations = this.parseAnimations( json.animations ); @@ -191,6 +236,12 @@ class ObjectLoader extends Loader { } + /** + * Async version of {@link ObjectLoader#parse}. + * + * @param {Object} json - The serialized 3D object. + * @return {Promise} A Promise that resolves with the parsed 3D object. + */ async parseAsync( json ) { const animations = this.parseAnimations( json.animations ); @@ -212,6 +263,8 @@ class ObjectLoader extends Loader { } + // internals + parseShapes( json ) { const shapes = {}; diff --git a/src/loaders/TextureLoader.js b/src/loaders/TextureLoader.js index 4adc1ec8fa4aed..a619463c90450f 100644 --- a/src/loaders/TextureLoader.js +++ b/src/loaders/TextureLoader.js @@ -2,14 +2,47 @@ import { ImageLoader } from './ImageLoader.js'; import { Texture } from '../textures/Texture.js'; import { Loader } from './Loader.js'; +/** + * Class for loading textures. Images are internally + * loaded via {@link ImageLoader}. + * + * ```js + * const loader = new THREE.TextureLoader(); + * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' ); + * + * const material = new THREE.MeshBasicMaterial( { map:texture } ); + * ``` + * Please note that `TextureLoader` has dropped support for progress + * events in `r84`. For a `TextureLoader` that supports progress events, see + * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}. + * + * @augments Loader + */ class TextureLoader extends Loader { + /** + * Constructs a new texture loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ constructor( manager ) { super( manager ); } + /** + * Starts loading from the given URL and pass the fully loaded texture + * to the `onLoad()` callback. 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. + * + * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI. + * @param {function(Texture)} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} onProgress - Unsupported in this loader. + * @param {onErrorCallback} onError - Executed when errors occur. + * @return {Texture} The texture. + */ load( url, onLoad, onProgress, onError ) { const texture = new Texture(); diff --git a/src/math/MathUtils.js b/src/math/MathUtils.js index 7a78120e5a7a8f..e813f506b0127c 100644 --- a/src/math/MathUtils.js +++ b/src/math/MathUtils.js @@ -470,30 +470,253 @@ function normalize( value, array ) { } +/** + * @class + * @classdesc A collection of math utility functions. + * @hideconstructor + */ const MathUtils = { DEG2RAD: DEG2RAD, RAD2DEG: RAD2DEG, + /** + * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier} + * (universally unique identifier). + * + * @static + * @method + * @return {string} The UUID. + */ generateUUID: generateUUID, + /** + * Clamps the given value between min and max. + * + * @static + * @method + * @param {number} value - The value to clamp. + * @param {number} min - The min value. + * @param {number} max - The max value. + * @return {number} The clamped value. + */ clamp: clamp, + /** + * Computes the Euclidean modulo of the given parameters that + * is `( ( n % m ) + m ) % m`. + * + * @static + * @method + * @param {number} n - The first parameter. + * @param {number} m - The second parameter. + * @return {number} The Euclidean modulo. + */ euclideanModulo: euclideanModulo, + /** + * Performs a linear mapping from range `` to range `` + * for the given value. + * + * @static + * @method + * @param {number} x - The value to be mapped. + * @param {number} a1 - Minimum value for range A. + * @param {number} a2 - Maximum value for range A. + * @param {number} b1 - Minimum value for range B. + * @param {number} b2 - Maximum value for range B. + * @return {number} The mapped value. + */ mapLinear: mapLinear, + /** + * Returns the percentage in the closed interval `[0, 1]` of the given value + * between the start and end point. + * + * @static + * @method + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} value - A value between start and end. + * @return {number} The interpolation factor. + */ inverseLerp: inverseLerp, + /** + * 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`. + * + * @static + * @method + * @param {number} x - The start point + * @param {number} y - The end point. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {number} The interpolated value. + */ lerp: lerp, + /** + * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta + * time to maintain frame rate independent movement. For details, see + * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}. + * + * @static + * @method + * @param {number} x - The current point. + * @param {number} y - The target point. + * @param {number} lambda - A higher lambda value will make the movement more sudden, + * and a lower value will make the movement more gradual. + * @param {number} dt - Delta time in seconds. + * @return {number} The interpolated value. + */ damp: damp, + /** + * Returns a value that alternates between `0` and the given `length` parameter. + * + * @static + * @method + * @param {number} x - The value to pingpong. + * @param {number} [length=1] - The positive value the function will pingpong to. + * @return {number} The alternated value. + */ pingpong: pingpong, + /** + * Returns a value in the range `[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]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details. + * + * @static + * @method + * @param {number} x - The value to evaluate based on its position between min and max. + * @param {number} min - The min value. Any x value below min will be `0`. + * @param {number} max - The max value. Any x value above max will be `1`. + * @return {number} The alternated value. + */ smoothstep: smoothstep, + /** + * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations} + * that has zero 1st and 2nd order derivatives at x=0 and x=1. + * + * @static + * @method + * @param {number} x - The value to evaluate based on its position between min and max. + * @param {number} min - The min value. Any x value below min will be `0`. + * @param {number} max - The max value. Any x value above max will be `1`. + * @return {number} The alternated value. + */ smootherstep: smootherstep, + /** + * Returns a random integer from `` interval. + * + * @static + * @method + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random integer. + */ randInt: randInt, + /** + * Returns a random float from `` interval. + * + * @static + * @method + * @param {number} low - The lower value boundary. + * @param {number} high - The upper value boundary + * @return {number} A random float. + */ randFloat: randFloat, + /** + * Returns a random integer from `<-range/2, range/2>` interval. + * + * @static + * @method + * @param {number} range - Defines the value range. + * @return {number} A random float. + */ randFloatSpread: randFloatSpread, + /** + * Returns a deterministic pseudo-random float in the interval `[0, 1]`. + * + * @static + * @method + * @param {number} [s] - The integer seed. + * @return {number} A random float. + */ seededRandom: seededRandom, + /** + * Converts degrees to radians. + * + * @static + * @method + * @param {number} degrees - A value in degrees. + * @return {number} The converted value in radians. + */ degToRad: degToRad, + /** + * Converts radians to degrees. + * + * @static + * @method + * @param {number} radians - A value in radians. + * @return {number} The converted value in degrees. + */ radToDeg: radToDeg, + /** + * Returns `true` if the given number is a power of two. + * + * @static + * @method + * @param {number} value - The value to check. + * @return {boolean} Whether the given number is a power of two or not. + */ isPowerOfTwo: isPowerOfTwo, + /** + * Returns the smallest power of two that is greater than or equal to the given number. + * + * @static + * @method + * @param {number} value - The value to find a POT for. + * @return {number} The smallest power of two that is greater than or equal to the given number. + */ ceilPowerOfTwo: ceilPowerOfTwo, + /** + * Returns the largest power of two that is less than or equal to the given number. + * + * @static + * @method + * @param {number} value - The value to find a POT for. + * @return {number} The largest power of two that is less than or equal to the given number. + */ floorPowerOfTwo: floorPowerOfTwo, + /** + * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles} + * defined by the given angles and 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`. + * + * @static + * @method + * @param {Quaternion} q - The quaternion to set. + * @param {number} a - The rotation applied to the first axis, in radians. + * @param {number} b - The rotation applied to the second axis, in radians. + * @param {number} c - The rotation applied to the third axis, in radians. + * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order. + */ setQuaternionFromProperEuler: setQuaternionFromProperEuler, + /** + * Normalizes the given value according to the given typed array. + * + * @static + * @method + * @param {number} value - The float value in the range `[0,1]` to normalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The normalize value. + */ normalize: normalize, + /** + * Denormalizes the given value according to the given typed array. + * + * @static + * @method + * @param {number} value - The value to denormalize. + * @param {TypedArray} array - The typed array that defines the data type of the value. + * @return {number} The denormalize (float) value in the range `[0,1]`. + */ denormalize: denormalize }; diff --git a/utils/docs/jsdoc.config.json b/utils/docs/jsdoc.config.json index 0898c11c6b484c..664d4b38cb4a70 100644 --- a/utils/docs/jsdoc.config.json +++ b/utils/docs/jsdoc.config.json @@ -21,8 +21,7 @@ "src/geometries", "src/helpers", "src/lights", - "src/loaders/nodes", - "src/loaders/Loader.js", + "src/loaders", "src/materials/nodes", "src/materials/Material.js", "src/math",