### Quick Start HTML Example
Source: https://sparkjs.dev/docs
This snippet demonstrates how to integrate Spark.js into an HTML file for a quick 3D visualization. It includes necessary imports and basic scene setup.
```html
```
--------------------------------
### Develop and Contribute to Spark.js
Source: https://sparkjs.dev/docs
Commands to set up the development environment for Spark.js, including installing dependencies, building the WebAssembly module, and starting the development server.
```bash
npm install
```
```bash
npm run build:wasm
```
```bash
npm run dev
```
--------------------------------
### Image to Splats Example
Source: https://sparkjs.dev/docs/procedural-splats
Example demonstrating loading an RGBA image, subsampling it, and filtering splats by opacity.
```javascript
// Load RGBA image from image.png, subsample it 2x
// horizontally and vertically, and create splats for
// the resulting pixels that have at least 10% opacity.
const image = imageSplats({
url: "./image.png",
subXY: 2,
forEachSplat: (width, height, index, center, scales, quaternion, opacity, color) => {
// Only keep splats with opacity 10% or higher
return (opacity >= 0.1) ? opacity : null;
},
});
scene.add(image);
```
--------------------------------
### Install Spark.js with NPM
Source: https://sparkjs.dev/docs
Use this command to install the Spark.js library into your project via NPM.
```bash
npm install @sparkjsdev/spark
```
--------------------------------
### Dyno Add Example
Source: https://sparkjs.dev/docs/dyno-stdlib
Demonstrates the use of Dyno blocks for arithmetic operations. Both class instantiation and helper function forms are shown.
```javascript
const sum = new dyno.Add({ a, b });
const sum = dyno.add(a, b);
```
--------------------------------
### Basic three.js Scene Setup and Animation
Source: https://sparkjs.dev/examples/js/vendor/three
This snippet demonstrates how to initialize a three.js scene, camera, and a rotating cube, then render it using WebGL. It requires the three.js library to be imported.
```javascript
import * as THREE from 'three';
const width = window.innerWidth, height = window.innerHeight;
// init
const camera = new THREE.PerspectiveCamera( 70, width / height, 0.01, 10 );
camera.position.z = 1;
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( width, height );
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );
// animation
function animate( time ) {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render( scene, camera );
}
```
--------------------------------
### Configure Pointer Controls with lil-gui
Source: https://sparkjs.dev/docs/controls
This snippet shows how to use `lil-gui` to create a GUI for adjusting pointer control settings like reversing rotation and pan directions. Ensure `lil-gui` is installed (`npm add lil-gui`).
```javascript
import GUI from "lil-gui";
const gui = new GUI({ title: "Settings + Controls" }).close();
const controlOptions = {
reversePointerFps: false,
reversePointerPan: false,
};
gui
.add(controlOptions, "reversePointerFps")
.name("Reverse Pointer FPS")
.onChange((value: boolean) => {
pointerControls.reverseRotate = value;
pointerControls.reverseScroll = value;
});
gui
.add(controlOptions, "reversePointerPan")
.name("Reverse Pointer Pan")
.onChange((value: boolean) => {
pointerControls.reverseSlide = value;
pointerControls.reverseSwipe = value;
});
```
--------------------------------
### Run build-lod Tool with npm
Source: https://sparkjs.dev/docs/lod-getting-started
Use this command to invoke the `build-lod` tool via npm. The `--` separator is crucial if your options start with a hyphen.
```bash
npm run build-lod -- my-splats.ply more-splats.spz [..options]
```
--------------------------------
### Raycasting with SplatMesh
Source: https://sparkjs.dev/docs/splat-mesh
This example demonstrates how to set up a THREE.Raycaster and use it to find intersections with objects in a scene, specifically identifying intersections with SplatMesh objects. It's recommended to call this method judiciously due to potential performance impacts with large datasets.
```javascript
const raycaster = new THREE.Raycaster();
canvas.addEventListener("click", (event) => {
raycaster.setFromCamera(new THREE.Vector2(
(event.clientX / canvas.width) * 2 - 1,
-(event.clientY / canvas.height) * 2 + 1,
), camera);
const intersects = raycaster.intersectObjects(scene.children);
const splatIndex = intersects.findIndex((i) => i.object instanceof SplatMesh);
});
```
--------------------------------
### Initialize SparkRenderer in Scene
Source: https://sparkjs.dev/docs/spark-renderer
Create a SparkRenderer instance and add it to your THREE.Scene. This is the basic setup for using Spark's splat rendering capabilities.
```javascript
const spark = new SparkRenderer({
renderer: myThreeJsWebGlRenderer,
});
const scene = new THREE.Scene();
scene.add(spark);
```
--------------------------------
### PackedSplats Instance Methods
Source: https://sparkjs.dev/docs/packed-splats
Provides methods to interact with an instance of PackedSplats, such as disposing of resources, managing splat capacity, getting and setting individual splats, iterating over all splats, and retrieving texture representations.
```APIDOC
## dispose()
### Description
Call this when you are finished with the PackedSplats and want to free any render targets + textures it holds.
### Method
`dispose()`
### Endpoint
N/A (Instance Method)
### Parameters
None
### Request Example
N/A
### Response
N/A
```
```APIDOC
## ensureSplats(numSplats)
### Description
Ensures that `this.packedArray` can fit `numSplats` splats. If it's too small, resize exponentially and copy over the original data. Typically you don't need to call this, because calling `this.setSplat(index, ...)` and `this.pushSplat(...)` will automatically call `ensureSplats()` so we have enough splats.
### Method
`ensureSplats(numSplats: number)`
### Endpoint
N/A (Instance Method)
### Parameters
* **numSplats** (number) - The minimum number of splats to ensure capacity for.
### Request Example
N/A
### Response
N/A
```
```APIDOC
## getSplat(index)
### Description
Unpack the 16-byte splat data at `index` into the THREE.js components `center`, `scales`, `quaternion`, `opacity`, and `color`.
### Method
`getSplat(index: number): { center: THREE.Vector3, scales: THREE.Vector3, quaternion: THREE.Quaternion, opacity: number, color: THREE.Color }`
### Endpoint
N/A (Instance Method)
### Parameters
* **index** (number) - The index of the splat to retrieve.
### Request Example
N/A
### Response
* **center** (THREE.Vector3) - The center position of the splat.
* **scales** (THREE.Vector3) - The scale of the splat.
* **quaternion** (THREE.Quaternion) - The orientation of the splat.
* **opacity** (number) - The opacity of the splat (0 to 1).
* **color** (THREE.Color) - The color of the splat (0 to 1).
```
```APIDOC
## setSplat(index, center, scales, quaternion, opacity, color)
### Description
Set all PackedSplat components at `index` with the provided splat attributes. This method ensures there is capacity for at least `index+1` splats.
### Method
`setSplat(index: number, center: THREE.Vector3, scales: THREE.Vector3, quaternion: THREE.Quaternion, opacity: number, color: THREE.Color)`
### Endpoint
N/A (Instance Method)
### Parameters
* **index** (number) - The index at which to set the splat.
* **center** (THREE.Vector3) - The center position of the splat.
* **scales** (THREE.Vector3) - The scale of the splat.
* **quaternion** (THREE.Quaternion) - The orientation of the splat.
* **opacity** (number) - The opacity of the splat (0 to 1).
* **color** (THREE.Color) - The color of the splat (0 to 1).
### Request Example
N/A
### Response
N/A
```
```APIDOC
## pushSplat(center, scales, quaternion, opacity, color)
### Description
Effectively calls `this.setSplat(this.numSplats++, center, ...)`, useful on construction where you just want to iterate and create a collection of splats.
### Method
`pushSplat(center: THREE.Vector3, scales: THREE.Vector3, quaternion: THREE.Quaternion, opacity: number, color: THREE.Color)`
### Endpoint
N/A (Instance Method)
### Parameters
* **center** (THREE.Vector3) - The center position of the splat.
* **scales** (THREE.Vector3) - The scale of the splat.
* **quaternion** (THREE.Quaternion) - The orientation of the splat.
* **opacity** (number) - The opacity of the splat (0 to 1).
* **color** (THREE.Color) - The color of the splat (0 to 1).
### Request Example
N/A
### Response
N/A
```
```APIDOC
## forEachSplat(callback)
### Description
Iterate over splats index `0..=(this.numSplats-1)`, unpack each splat and invoke the callback function with the splat attributes.
### Method
`forEachSplat(callback: (index: number, center: THREE.Vector3, scales: THREE.Vector3, quaternion: THREE.Quaternion, opacity: number, color: THREE.Color) => void)`
### Endpoint
N/A (Instance Method)
### Parameters
* **callback** (function) - A function to be called for each splat. It receives the splat's index and its unpacked attributes.
### Request Example
N/A
### Response
N/A
```
```APIDOC
## getTexture()
### Description
Returns a `THREE.DataArrayTexture` representing the PackedSplats content as a Uint32x4 data array texture.
### Method
`getTexture(): THREE.DataArrayTexture`
### Endpoint
N/A (Instance Method)
### Parameters
None
### Request Example
N/A
### Response
* **texture** (THREE.DataArrayTexture) - The data array texture representation of the splats.
```
```APIDOC
## getEmpty()
### Description
Can be used where you need an uninitialized `THREE.DataArrayTexture` like a uniform you will update with the result of `this.getTexture()` later.
### Method
`getEmpty(): THREE.DataArrayTexture`
### Endpoint
N/A (Instance Method)
### Parameters
None
### Request Example
N/A
### Response
* **texture** (THREE.DataArrayTexture) - An uninitialized data array texture.
```
--------------------------------
### Creating SplatMesh and Splats in Initializer
Source: https://sparkjs.dev/docs/procedural-splats
You can create a SplatMesh and its splats simultaneously using the constructSplats initializer. This simplifies setup when splats are generated during mesh creation.
```javascript
const mesh = new SplatMesh({
constructSplats: (splats) => {
for (let i = 0; i < NUM_SPLATS; ++i) {
// Compute splat #i
...
splats.pushSplat(center, scales, quaternion, opacity, color);
}
},
});
scene.add(mesh);
```
--------------------------------
### Instantiating and Using Dyno Blocks
Source: https://sparkjs.dev/docs/dyno-overview
Illustrates how to create instances of Dyno blocks like 'Add' and access their outputs.
```javascript
const { sum } = new dyno.Add({ a, b }).outputs;
// Or equivalently:
const { sum } = dyno.add(a, b).outputs;
// For Dynos that implement HasDynoOut you can also do
const sum = dyno.add(a, b);
```
--------------------------------
### Get Empty DataArrayTexture
Source: https://sparkjs.dev/docs/packed-splats
Provides an uninitialized THREE.DataArrayTexture. This can be used as a placeholder uniform that will later be updated with the result of getTexture().
```javascript
const emptyTexture = packedSplats.getEmpty();
```
--------------------------------
### Basic lil-gui Usage
Source: https://sparkjs.dev/examples/js/vendor/lil-gui
Demonstrates the fundamental usage of lil-gui by adding various controller types like checkboxes, buttons, text fields, number fields, sliders, and dropdowns. It also shows how to chain methods for customization and how to add color pickers.
```javascript
import GUI from 'lil-gui';
const gui = new GUI();
const myObject = {
myBoolean: true,
myFunction: function() { ... },
myString: 'lil-gui',
myNumber: 1
};
gui.add( myObject, 'myBoolean' ); // Checkbox
gui.add( myObject, 'myFunction' ); // Button
gui.add( myObject, 'myString' ); // Text Field
gui.add( myObject, 'myNumber' ); // Number Field
// Add sliders to number fields by passing min and max
gui.add( myObject, 'myNumber', 0, 1 );
gui.add( myObject, 'myNumber', 0, 100, 2 ); // snap to even numbers
// Create dropdowns by passing an array or object of named values
gui.add( myObject, 'myNumber', [ 0, 1, 2 ] );
gui.add( myObject, 'myNumber', { Label1: 0, Label2: 1, Label3: 2 } );
// Chainable methods
gui.add( myObject, 'myProperty' )
.name( 'Custom Name' )
.onChange( value => {
console.log( value );
} );
// Create color pickers for multiple color formats
const colorFormats = {
string: '#ffffff',
int: 0xffffff,
object: { r: 1, g: 1, b: 1 },
array: [ 1, 1, 1 ]
};
gui.addColor( colorFormats, 'string' );
```
--------------------------------
### Run build-lod with Multiple Files and Quality Option
Source: https://sparkjs.dev/docs/lod-getting-started
Process multiple splat files from a directory and apply the `--quality` option for higher-fidelity LoD generation.
```bash
npm run build-lod -- splats-dir/*.spz --quality
```
--------------------------------
### Get PackedSplats as DataArrayTexture
Source: https://sparkjs.dev/docs/packed-splats
Returns a THREE.DataArrayTexture representing the PackedSplats content. This texture is in Uint32x4 format and has dimensions suitable for GPU rendering.
```javascript
const texture = packedSplats.getTexture();
```
--------------------------------
### build-lod Command-Line Help
Source: https://sparkjs.dev/docs/lod-getting-started
Run `build-lod` without parameters to display its usage and available options.
```bash
npm run build-lod
Usage: build-lod
[--unlod] // Remove LoD nodes with children from file
[--csplat] [--gsplat] // Use compact (csplat) or higher-precision (default gsplat) splat encoding
[--quick] [--quality] // Use quick (tiny-lod) or quality (bhatt-lod) LoD method (default quick)
...
```
--------------------------------
### Get Unpacked Splat Data
Source: https://sparkjs.dev/docs/packed-splats
Unpacks the 16-byte splat data at a given index into its constituent THREE.js components: center, scales, quaternion, opacity, and color.
```javascript
const splatData = packedSplats.getSplat(index);
// splatData contains: { center, scales, quaternion, opacity, color }
```
--------------------------------
### Build and Run build-lod Directly with Cargo
Source: https://sparkjs.dev/docs/lod-getting-started
Build the Rust project for `build-lod` and then run it directly. Ensure you use the `--release` flag for optimal performance.
```bash
cd rust/build-lod
cargo build --release
cargo run --release -- my-splats.ply more-splats.spz [..options]
```
--------------------------------
### Create ExtSplats Instance
Source: https://sparkjs.dev/docs/ext-splats
Instantiate ExtSplats with various options for initialization, including file data, raw arrays, or procedural construction. Supports URL, file bytes, streams, and pre-existing extArrays.
```typescript
const extSplats = new ExtSplats({
url?: string;
fileBytes?: Uint8Array | ArrayBuffer;
fileType?: SplatFileType;
fileName?: string;
stream?: ReadableStream;
streamLength?: number;
maxSplats?: number;
extArrays?: [Uint32Array, Uint32Array];
numSplats?: number;
construct?: (splats: ExtSplats) => Promise | void;
onProgress?: (event: ProgressEvent) => void;
extra?: Record;
lod?: boolean | number;
nonLod?: boolean;
lodAbove?: number;
lodSplats?: ExtSplats;
});
```
--------------------------------
### Creating a DynoConst
Source: https://sparkjs.dev/docs/dyno-overview
Demonstrates creating a DynoConst for a float and a vec3 using the constructor and the helper function.
```javascript
new DynoConst("float", 1.0)
new DynoConst("vec3", new THREE.Vector3(1.0, 2.0, 3.0))
dynoConst("float", 1.0)
```
--------------------------------
### Initialize DRACOLoader with Decoder Path
Source: https://sparkjs.dev/examples/js/vendor/three/examples/jsm/libs/draco
Configure DRACOLoader by setting the path to the decoder files and optionally specifying the decoder type.
```javascript
var dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('path/to/decoders/');
dracoLoader.setDecoderConfig({type: 'js'}); // (Optional) Override detection of WASM support.
```
--------------------------------
### Load KTX2 Texture with Basis Transcoder
Source: https://sparkjs.dev/examples/js/vendor/three/examples/jsm/libs/basis
Demonstrates how to load a `.ktx2` texture using `KTX2Loader` and set up the Basis transcoder path. This is essential for using Basis Universal compressed textures in Three.js.
```javascript
const ktx2Loader = new KTX2Loader();
ktx2Loader.setTranscoderPath( 'examples/jsm/libs/basis/' );
ktx2Loader.detectSupport( renderer );
ktx2Loader.load( 'diffuse.ktx2', function ( texture ) {
const material = new THREE.MeshStandardMaterial( { map: texture } );
}, function () {
console.log( 'onProgress' );
}, function ( e ) {
console.error( e );
} );
```
--------------------------------
### Initialize FpsMovement Controls
Source: https://sparkjs.dev/docs/controls
Create an FpsMovement instance for first-person shooter style navigation using keyboard and mouse or a gamepad. Many parameters can be configured, including movement speeds, key mappings, and gamepad button actions.
```javascript
const fpsMovement = new FpsMovement({
moveSpeed?: number;
rollSpeed?: number;
stickThreshold?: number;
rotateSpeed?: number;
keycodeMoveMapping?: { [key: string]: THREE.Vector3 };
keycodeRotateMapping?: { [key: string]: THREE.Vector3 };
gamepadMapping?: {
[button: number]: "shift" | "ctrl" | "rollLeft" | "rollRight";
};
capsMultiplier?: number;
shiftMultiplier?: number;
ctrlMultiplier?: number;
xr?: THREE.WebXRManager;
});
```
--------------------------------
### SparkRenderer Constructor Options
Source: https://sparkjs.dev/docs/spark-renderer
Demonstrates the various parameters available when creating a new SparkRenderer instance. Configure rendering behavior like Level-of-Detail and sorting.
```javascript
const spark = new SparkRenderer({
renderer: THREE.WebGLRenderer;
maxStdDev?: number;
sortRadial?: boolean;
lodSplatScale?: number;
pagedExtSplats?: boolean;
target?: { width: number; height: number; doubleBuffer?: boolean },
});
```
--------------------------------
### Build LoD Splat Trees with Rust
Source: https://sparkjs.dev/docs/new-spark-renderer
Use this command to build LoD splat trees from existing splat files using the Rust crate. Optimized builds are recommended for performance.
```bash
cd spark/rust/build-lod
# "--release" for optimized builds, "--" separates arguments to build-lod
cargo run --release -- /path/to/splats.[spz|ply] [/path/to/other-splats.*]
# Outputs /path/to/splats-lod.spz
```
--------------------------------
### Load Pre-built LoD Tree with Paged Streaming
Source: https://sparkjs.dev/docs/spark-2.0-quick-start
Load a pre-built LoD tree from a .RAD file. Set paged: true for paged streaming.
```javascript
new SplatMesh({ url: "./my-splats-lod.rad", paged: true })
```
--------------------------------
### Load .splat and .ksplat SplatMesh via URL Extension
Source: https://sparkjs.dev/docs/loading-splats
Load `.splat` and `.ksplat` files by relying on file type inference from the URL's file extension. This method is used when auto-detection fails.
```javascript
const splats = new SplatMesh({ url: "./butterfly.splat" });
scene.add(splats);
const ksplats = new SplatMesh({ url: "./butterfly.ksplat" });
scene.add(ksplats);
```
--------------------------------
### Initialize SparkControls
Source: https://sparkjs.dev/docs/controls
Add intuitive keyboard, mouse, gamepad, or touch controls to your Spark application by creating a SparkControls instance. Update the controls in your render loop.
```javascript
const controls = new SparkControls({
canvas: HTMLCanvasElement;
});
renderer.setAnimationLoop((time) => {
renderer.render(scene, camera);
controls.update(camera);
});
```
--------------------------------
### Build LoD Tree from Command Line
Source: https://sparkjs.dev/docs/lod-getting-started
Pre-build the LoD tree from the command line using the 'build-lod' npm script. This generates .rad files for faster loading and streaming.
```bash
npm run build-lod -- my-splats.ply more-splats.spz --quality
```
--------------------------------
### Initialize snowBox Generator
Source: https://sparkjs.dev/docs/procedural-splats
This snippet demonstrates how to initialize the snowBox generator with various parameters to control particle behavior and appearance. It then adds the generated snow particles to the scene.
```javascript
const snowControls = generators.snowBox({
box,
minY,
numSplats,
density,
anisoScale,
minScale,
maxScale,
fallDirection,
fallVelocity,
wanderScale,
wanderVariance,
color1,
color2,
opacity,
onFrame,
});
scene.add(snowControls.snow);
```
--------------------------------
### Creating a SplatMesh
Source: https://sparkjs.dev/docs/splat-mesh
Instantiate a SplatMesh by providing various options for loading and configuring the splat data. This includes fetching from a URL, decoding file bytes, using streams, or providing packed splats. Optional callbacks for progress and loading completion are also available.
```typescript
const splats = new SplatMesh({
// Fetch PLY/SPZ/SPLAT/KSPLAT/SOG/ZIP/RAD file from URL
url?: string;
// Decode raw PLY/SPZ/SPLAT/KSPLAT/SOG/ZIP/RAD file bytes
fileBytes?: Uint8Array | ArrayBuffer;
// ReadableStream to read file from
stream?: ReadableStream;
// Length of stream in bytes
streamLength?: number;
// Use PackedSplats object as source
packedSplats?: PackedSplats;
// Reserve space for at least this many splats for construction
maxSplats?: number;
// Constructor callback to create splats
constructSplats?: (splats: PackedSplats) => Promise | void;
// Callback function called while downloading and initializing (default: undefined)
onProgress?: (event: ProgressEvent) => void;
// Callback for when mesh initialization is complete
onLoad?: (mesh: SplatMesh) => Promise | void;
// Toggle controls whether SplatEdits have an effect, default true
editable?: boolean;
// Controls whether SplatMesh participates in Three.js raycasting (default: true)
raycastable?: boolean;
// Minimum opacity for raycasting splats. (default: 0.2)
minRaycastOpacity?: number;
// Frame callback to update mesh. Call mesh.updateVersion() if we need to re-generate
onFrame?: ({
mesh,
time,
deltaTime,
}: { mesh: SplatMesh; time: number; deltaTime: number }) => void;
// Object-space and world-space splat modifiers to apply in sequence
objectModifiers?: GsplatModifier[];
worldModifiers?: GsplatModifier[];
// Override the default splat encoding ranges for the PackedSplats.
// (default: undefined)
splatEncoding?: SplatEncoding;
// Set to true to load/use "extended splat" encoding with float32 x/y/z,
// or use provided ExtSplats object
extSplats?: boolean | ExtSplats;
// Enable Level-of-Detail (LoD). If set to true, it will ensure the SplatMesh
// has a LoD version, whether it's pre-computed in a .RAD file, or generate it
// on-the-fly in a background WebWorker using the quick tiny-lod algorithm.
lod?: boolean | number;
// If set, the original non-LoDd input splats will be retained along with the LoD version.
// The original splats are in .packedSplats/.extSplats, while the LoD version is contained
// within those in .packedSplats.lodSplats/.extSplats.lodSplats.
nonLod?: boolean;
// If unset, will default to using LoD if the LoD version is available, otherwise
// falling back to the non-LoD version. If set to true, will force the use of the
// LoD version if both exist, and vice versa if set to false.
enableLod?: boolean;
// LoD detail scale to apply for this particular SplatMesh. 2.0 will 2x the detail
// while 0.5 well result in 2x coarser (2x larger splats on average).
lodScale?: number;
// Set this to true to enable paged splat streaming from a .RAD file.
paged?: boolean | PagedSplats | SplatPager;
});
// Add to scene to show splats
scene.add(splats);
```
--------------------------------
### Constructing a Grid of Splats
Source: https://sparkjs.dev/docs/procedural-splats
Use the constructGrid utility to create a grid of splats within specified extents. Optional parameters control step size, radius, shadow scale, opacity, and color.
```javascript
import { constructGrid } from "@sparkjsdev/spark";
const grid = new SplatMesh({
constructSplats: (splats) => constructGrid({
splats,
extents: new THREE.Box3(
new THREE.Vector3(-10, -10, -10),
new THREE.Vector3(10, 10, 10),
),
}),
});
scene.add(grid);
```
--------------------------------
### Load Pre-built LoD .rad File
Source: https://sparkjs.dev/docs/lod-getting-started
Load the .rad file generated by the build-lod script into a SplatMesh. The 'lod: true' flag is not needed as the .rad file contains this information.
```javascript
const splats = new SplatMesh({ url: "./my-splats-lod.rad" });
scene.add(splats);
```
--------------------------------
### Initialize PointerControls
Source: https://sparkjs.dev/docs/controls
Implement pointer, mouse, and touch controls for desktop and mobile applications by creating a PointerControls instance. Configure rotation, sliding, and scrolling speeds, as well as inertia and reverse directions.
```javascript
const pointerControls = new PointerControls({
canvas: HTMLCanvasElement;
rotateSpeed?: number;
slideSpeed?: number;
scrollSpeed?: number;
reverseRotate?: boolean;
reverseSlide?: boolean;
reverseSwipe?: boolean;
reverseScroll?: boolean;
moveInertia?: number;
rotateInertia?: number;
doublePress?: ({
position,
intervalMs,
}: { position: THREE.Vector2; intervalMs: number }) => void;
})
```
--------------------------------
### Initialize NewSparkRenderer
Source: https://sparkjs.dev/docs/spark-2.0-quick-start
Replace SparkRenderer with NewSparkRenderer for Spark 2.0. Add the new renderer to your scene.
```javascript
const spark = new NewSparkRenderer({
renderer: THREE.WebGLRenderer,
});
scene.add(spark);
```
--------------------------------
### Accessing DynoOutput from splitGsplat
Source: https://sparkjs.dev/docs/dyno-overview
Shows how to access typed outputs like 'opacity' from the dyno.splitGsplat function.
```javascript
// opacity is a DynoOutput and also a DynoVal<"float">
const { opacity } = dyno.splitGsplat(gsplat);
```
--------------------------------
### Pack a Splat into a uvec4 (GLSL)
Source: https://sparkjs.dev/docs/packed-splats
Use the `packSplat` GLSL utility function to pack all splat components into a `uvec4`.
```glsl
uvec4 packSplat(vec3 center, vec3 scales, vec4 quaternion, vec4 rgba);
```
--------------------------------
### SparkControls Initialization
Source: https://sparkjs.dev/docs/controls
Instantiate SparkControls to add keyboard, mouse, gamepad, or mobile multi-touch navigation to your scene. It internally manages FpsMovement and PointerControls.
```APIDOC
## SparkControls
### Description
Initializes Spark controls for scene navigation.
### Constructor
`new SparkControls({ canvas: HTMLCanvasElement })`
### Parameters
#### Required Parameters
- **canvas** (HTMLCanvasElement) - The HTML canvas element to attach controls to.
### Usage Example
```javascript
const controls = new SparkControls({
canvas: myCanvasElement
});
renderer.setAnimationLoop((time) => {
renderer.render(scene, camera);
controls.update(camera);
});
```
```
--------------------------------
### Load .splat and .ksplat SplatMesh with Explicit fileType
Source: https://sparkjs.dev/docs/loading-splats
Explicitly set the `fileType` property when creating a `SplatMesh` for formats like `.splat` and `.ksplat` if the URL lacks an obvious file extension.
```javascript
// File type can't be auto-detected, so we set it explicitly
scene.add(new SplatMesh({
url: "splatBin/0123456789abcdef",
fileType: SplatFileType.SPLAT,
}));
scene.add(new SplatMesh({
url: "ksplatBin/fedcba9876543210",
fileType: SplatFileType.KSPLAT,
}));
```
--------------------------------
### Enable Extended Splats for Loaded Files
Source: https://sparkjs.dev/docs/lod-getting-started
Enable 'ExtSplats' when creating a SplatMesh to use a 32 bytes/splat encoding with float32 coordinates for increased precision, especially for files with huge coordinates.
```javascript
new SplatMesh({ url: "./my-splats.spz", extSplats: true });
```
--------------------------------
### Initialize SparkRenderer with Covariance Splats
Source: https://sparkjs.dev/docs/new-features-2.0
Enable a new internal encoding that stores the 3D symmetric covariance matrix instead of scale+rotation. This allows for non-uniform scaling and is backward-compatible with existing splat Dyno pipelines.
```javascript
new SparkRenderer({ covSplats: true })
```
--------------------------------
### SparkRenderer Configuration Options
Source: https://sparkjs.dev/docs/spark-renderer
This section outlines the optional parameters that can be passed to the SparkRenderer to customize its behavior and rendering output. These parameters allow fine-grained control over detail scaling, foveation, render targets, and shader programs.
```APIDOC
## SparkRenderer Optional Parameters
### Description
This document details the optional parameters that can be configured for the SparkRenderer, affecting Level of Detail (LoD), rendering quality, target rendering, and shader customization.
### Parameters
#### Optional Parameters
- **lodSplatScale** (number) - Optional - Scale factor for target # splats for LoD. Defaults to `1.0`.
- **lodRenderScale** (number) - Optional - Determines the minimum screen pixel size of LoD splats. Defaults to `1.0`.
- **pagedExtSplats** (boolean) - Optional - Whether to use extended Gsplat encoding for paged splats. Defaults to `false`.
- **maxPagedSplats** (number) - Optional - Allocation size of paged splats. Must be a multiple of the page size (65536). Defaults vary by platform.
- **numLodFetchers** (number) - Optional - Number of parallel chunk fetchers for LoD. Defaults to `3`.
- **coneFov0** (number) - Optional - Full-width angle in degrees of fixed foveation cone with no foveation applied. Defaults to `90.0`.
- **coneFov** (number) - Optional - Full-width angle in degrees of fixed foveation cone with reduced resolution. Defaults to `120.0`.
- **coneFoveate** (number) - Optional - Foveation scale to apply to LoD splats at the edge of `coneFov`. Defaults to `0.4`.
- **behindFoveate** (number) - Optional - Foveation scale to apply to LoD splats behind the viewer. Defaults to `0.2`.
- **target** (object) - Optional - Configures an offline render target for the `SparkRenderer`. Defaults to `undefined`.
- **target.width** (number) - Width of the render target in pixels.
- **target.height** (number) - Height of the render target in pixels.
- **target.doubleBuffer** (boolean) - Enables double buffering for recursive viewports. Defaults to `false`.
- **target.superXY** (number) - Super-sampling factor for the render target. Values 1-4 supported. Defaults to `1`.
- **extraUniforms** (object) - Optional - Extra uniform values to pass to the shader. Defaults to `undefined`.
- **vertexShader** (string) - Optional - Path to a custom vertex shader. Defaults to `undefined`.
- **fragmentShader** (string) - Optional - Path to a custom fragment shader. Defaults to `undefined`.
- **transparent** (boolean) - Optional - Set the splat shader material to be transparent. Defaults to `true`.
- **depthTest** (boolean) - Optional - Enable depth testing for splat shader material. Defaults to `true`.
- **depthWrite** (boolean) - Optional - Enable depth writing for splat shader material. Defaults to `false`.
```
--------------------------------
### Create a PackedSplats Instance
Source: https://sparkjs.dev/docs/packed-splats
Instantiate a PackedSplats object. You can provide options to load data from a URL, file bytes, a stream, or a raw packed array. Alternatively, use the 'construct' callback for procedural generation.
```typescript
const packedSplats = new PackedSplats({
url?: string;
fileBytes?: Uint8Array | ArrayBuffer;
fileType?: SplatFileType;
fileName?: string;
stream?: ReadableStream;
streamLength?: number;
maxSplats?: number;
packedArray?: Uint32Array;
numSplats?: number;
construct?: (splats: PackedSplats) => Promise | void;
onProgress?: (event: ProgressEvent) => void;
extra?: Record;
splatEncoding?: SplatEncoding;
lod?: boolean | number;
nonLod?: boolean;
lodAbove?: number;
lodSplats?: PackedSplats;
});
```
--------------------------------
### Load Auto-Detectable SplatMesh
Source: https://sparkjs.dev/docs/loading-splats
Load and create a `SplatMesh` directly from auto-detectable formats like `.ply` or `.spz`. The format can be inferred from file content even without a file extension.
```javascript
const splats = new SplatMesh({ url: "./butterfly.ply" });
scene.add(splats);
// No file extension but we can auto-detect format from the contents
scene.add(new SplatMesh({ url: "plyBin/0123456789abcdef" }));
scene.add(new SplatMesh({ url: "spzBin/fedcba9876543210" }));
```
--------------------------------
### renderEnvMap({ scene, worldCenter, ... })
Source: https://sparkjs.dev/docs/spark-renderer
Renders the scene to an environment map, pre-filters it, and returns a THREE.Texture suitable for `THREE.MeshStandardMaterial.envMap`.
```APIDOC
## `renderEnvMap({ scene, worldCenter, ... })`
### Description
Renders out the scene to an environment map that can be used for image-based lighting or similar applications. First updates splats, sorts them with respect to the provided `worldCenter`, renders 6 cube faces, then pre-filters them using `THREE.PMREMGenerator` and returns a `THREE.Texture` that can assigned directly to a `THREE.MeshStandardMaterial.envMap` property for environment mapped lighting.
### Method
(Not specified, assumed to be a method call)
### Endpoint
(Not applicable)
### Parameters
#### Path Parameters
(None)
#### Query Parameters
(None)
#### Request Body
- **scene** (object) - Required - The scene object to render.
- **worldCenter** (object) - Required - The world center to render from.
- **...** - Additional parameters may be accepted.
```
--------------------------------
### Constructing a Sphere of Splats
Source: https://sparkjs.dev/docs/procedural-splats
Use constructSpherePoints to create splats arranged in a sphere. Control the sphere's origin, radius, recursion depth, and filtering. Optional parameters allow customization of point radius, thickness, and color.
```javascript
import { constructSpherePoints } from "@sparkjsdev/spark";
const sphere = new SplatMesh({
constructSplats: (splats) => constructSpherePoints({
splats,
maxDepth: 4,
}),
});
scene.add(sphere);
```
--------------------------------
### Clone three.js Repository with Shallow Depth
Source: https://sparkjs.dev/examples/js/vendor/three
Use this command to clone the three.js repository while significantly reducing download size by excluding the full commit history. This is useful if you only need the latest code.
```bash
git clone --depth=1 https://github.com/mrdoob/three.js.git
```
--------------------------------
### renderCubeMap({ scene, worldCenter, ... })
Source: https://sparkjs.dev/docs/spark-renderer
Renders the scene to a cube map for applications like image-based lighting or depth maps, returning a THREE.CubeTexture.
```APIDOC
## `renderCubeMap({ scene, worldCenter, ... })`
### Description
Renders out the scene to a cube map that can used for Image-based lighting, rendering out depth maps, or similar applications, and returns a `THREE.CubeTexture`.
### Method
(Not specified, assumed to be a method call)
### Endpoint
(Not applicable)
### Parameters
#### Path Parameters
(None)
#### Query Parameters
(None)
#### Request Body
- **scene** (object) - Required - The scene object to render.
- **worldCenter** (object) - Required - The world center to render from.
- **...** - Additional parameters may be accepted.
```
--------------------------------
### FpsMovement Class
Source: https://sparkjs.dev/docs/controls
Provides first-person shooter style controls using keyboard, mouse, or gamepad. It can also utilize WebXR controllers.
```APIDOC
## FpsMovement
### Description
Implements familiar first-person shooter controls using keyboard, mouse, or gamepad.
### Constructor
`new FpsMovement({ moveSpeed?: number, rollSpeed?: number, stickThreshold?: number, rotateSpeed?: number, keycodeMoveMapping?: { [key: string]: THREE.Vector3 }, keycodeRotateMapping?: { [key: string]: THREE.Vector3 }, gamepadMapping?: { [button: number]: "shift" | "ctrl" | "rollLeft" | "rollRight" }, capsMultiplier?: number, shiftMultiplier?: number, ctrlMultiplier?: number, xr?: THREE.WebXRManager })`
### Parameters
#### Optional Parameters
- **moveSpeed** (number) - Default: `1.0`. Base movement speed.
- **rollSpeed** (number) - Default: `2.0`. Speed of roll rotation.
- **stickThreshold** (number) - Default: `0.1`. Deadzone for gamepad analog sticks.
- **rotateSpeed** (number) - Default: `2.0`. Speed of rotation when using gamepad or keys.
- **keycodeMoveMapping** ({ [key: string]: THREE.Vector3 }) - Default: `{...WASD_KEYCODE_MOVE, ...ARROW_KEYCODE_MOVE}`. Maps keyboard keys to movement directions.
- **keycodeRotateMapping** ({ [key: string]: THREE.Vector3 }) - Default: `{...QE_KEYCODE_ROTATE, ...ARROW_KEYCODE_ROTATE}`. Maps keyboard keys to rotation directions.
- **gamepadMapping** ({ [button: number]: "shift" | "ctrl" | "rollLeft" | "rollRight" }) - Default: `{4: "rollLeft", 5: "rollRight", 6: "ctrl", 7: "shift"}`. Maps gamepad buttons to actions.
- **capsMultiplier** (number) - Default: `10.0`. Speed multiplier when Caps Lock is active.
- **shiftMultiplier** (number) - Default: `5.0`. Speed multiplier when Shift is held.
- **ctrlMultiplier** (number) - Default: `0.2`. Speed multiplier when Ctrl is held.
- **xr** (THREE.WebXRManager) - Optional WebXR manager for XR controller stick support.
### Update Method
`update(deltaTime, control)`
#### Description
Call this method in your render loop to process input and apply transformations to the controlled object.
#### Parameters
- **deltaTime** (number) - Time in seconds since the last update.
- **control** (THREE.Camera | THREE.Object3D) - The object to control (e.g., `THREE.Camera` or an `Object3D` containing it).
### Usage Example
```javascript
const fpsMovement = new FpsMovement({
moveSpeed: 2.0,
rotateSpeed: 3.0
});
renderer.setAnimationLoop((time) => {
// ... other logic ...
fpsMovement.update(deltaTime, camera);
renderer.render(scene, camera);
});
```
```
--------------------------------
### Unpack a Splat from a uvec4 (GLSL)
Source: https://sparkjs.dev/docs/packed-splats
Use the `unpackSplat` GLSL utility function to unpack splat components from a `uvec4` into output variables.
```glsl
void unpackSplat(uvec4 packed, out vec3 center, out vec3 scales, out vec4 quaternion, out vec4 rgba);
```
--------------------------------
### Constructing Splats with Initializer Callback
Source: https://sparkjs.dev/docs/procedural-splats
The construct initializer callback allows procedural generation of splats when creating a PackedSplats object. This is useful for complex or dynamic splat arrangements.
```javascript
const splats = new PackedSplats({
construct: (splats) => {
...
for (let i = 0; i < NUM_SPLATS; ++i) {
// Compute splat #i
...
splats.pushSplat(center, scales, quaternion, opacity, color);
}
},
});
```
--------------------------------
### renderTarget({ scene, camera })
Source: https://sparkjs.dev/docs/spark-renderer
Renders the scene to a specified render target. Ensure `spark.update()` is awaited before calling for correct sorting in offline render loops.
```APIDOC
## `renderTarget({ scene, camera })`
### Description
Render the scene to the render target (specified using the `target` parameter during construction). To ensure correct sorting in an offline render loop, make sure you call and await `spark.update({ scene, scene })` before calling this method. If `doubleBuffer: true` was set during target construction, this will swap the back buffer and target, and return the target.
### Method
(Not specified, assumed to be a method call)
### Endpoint
(Not applicable)
### Parameters
#### Path Parameters
(None)
#### Query Parameters
(None)
#### Request Body
- **scene** (object) - Required - The scene object to render.
- **camera** (object) - Required - The camera object to render from.
```
--------------------------------
### readTarget()
Source: https://sparkjs.dev/docs/spark-renderer
Reads back the previously rendered target image as a Uint8Array of RGBA values. Performs downsampling with averaging if `superXY` was set greater than 1.
```APIDOC
## `readTarget()`
### Description
Read back the previously rendered target image as a Uint8Array of packed RGBA values (in that order). If `superXY` was set greater than `1` then downsampling is performed in the target pixel array with simple averaging to derive the returned pixel values. Subsequent calls to `this.readTarget()` will reuse the same buffers to minimize memory allocations.
### Method
(Not specified, assumed to be a method call)
### Endpoint
(Not applicable)
### Parameters
(None)
### Response
#### Success Response (200)
- **Uint8Array** - Packed RGBA pixel values.
```
--------------------------------
### forEachSplat(callback)
Source: https://sparkjs.dev/docs/splat-mesh
Iterates over all splats in the `packedSplats` array and invokes a callback function for each splat. The callback receives the splat's index, center, scales, quaternion, opacity, and color.
```APIDOC
## forEachSplat(callback: (index, center, scales, quaternion, opacity, color) => void)
This method iterates over all splats in this instance's `packedSplats`, invoking the provided callback with `index: number` in `0..=(this.numSplats-1)`, `center: THREE.Vector3`, `scales: THREE.Vector3`, `quaternion: THREE.Quaternion`, `opacity: number` (0..1), and `color: THREE.Color` (rgb values in 0..1). Note that the objects passed in as `center` etc. are the same for every callback invocation: they are reused for efficiency. _Changing these values has no effect_ as they are decoded/unpacked copies of the underlying data. To update the `packedSplats`, call `.packedSplats.setSplat(index, center, scales, quaternion, opacity, color)`.
```