### Install and Run Local Examples Server
Source: https://github.com/protectwise/troika/blob/main/packages/troika-examples/README.md
Installs dependencies and starts a local web server for running Troika examples. Changes to source files trigger automatic rebuilds.
```bash
npm install
npm run examples
```
--------------------------------
### Build Troika Examples Bundle
Source: https://github.com/protectwise/troika/blob/main/packages/troika-examples/README.md
Installs dependencies and builds a production-ready bundle of the Troika examples for deployment.
```bash
npm install
npm run build-examples
```
--------------------------------
### Run Local Examples Server on Network
Source: https://github.com/protectwise/troika/blob/main/packages/troika-examples/README.md
Starts the local web server for Troika examples, making it accessible from other devices on the network by setting the SERVER_HOST environment variable.
```bash
SERVER_HOST=0.0.0.0 npm run examples
```
--------------------------------
### Install Three.js
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/index.md
Install a compatible version of Three.js alongside troika-3d. Refer to the Setup page for version compatibility details.
```sh
npm install three
```
--------------------------------
### Run Troika Examples
Source: https://github.com/protectwise/troika/blob/main/docs/getting-started/examples.md
Execute this command to build and serve the Troika examples locally. The examples will be accessible via your web browser.
```bash
npm run examples
```
--------------------------------
### Install troika-three-utils
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-utils/README.md
Install the package using npm. Ensure a compatible version of Three.js is also installed.
```sh
npm install troika-three-utils
```
```sh
npm install three
```
--------------------------------
### Install Troika Text and Three.js
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md
Install the troika-three-text package and a compatible version of Three.js using npm.
```sh
npm install troika-three-text
```
```sh
npm install three
```
--------------------------------
### Animating Camera with Transitions and Animations
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/scenes.md
Implement smooth camera movements and animations using descriptor objects. This example shows how to transition between positions and apply looping animations.
```javascript
camera={{
x: currentPos.x,
z: currentPos.z,
rotateY: currentPos.angle,
// Smoothly transition between positions:
transition: {
x: true,
z: true,
rotateY: true
},
// Bob in place:
animation: {
from: { y: 1.4 },
to: {y: 1.5},
duration: 3000,
direction: 'alternate',
iterations: Infinity
}
}}
```
--------------------------------
### Install Troika 3D
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/index.md
Install the troika-3d package using npm.
```sh
npm install troika-3d
```
--------------------------------
### Clone Troika Repository and Install Dependencies
Source: https://github.com/protectwise/troika/blob/main/docs/getting-started/examples.md
Use these commands to clone the Troika repository from GitHub and install the necessary project dependencies.
```bash
git clone https://github.com/protectwise/troika.git
cd troika
npm install
```
--------------------------------
### Install troika-animation
Source: https://github.com/protectwise/troika/blob/main/packages/troika-animation/README.md
Install the troika-animation package using npm if you intend to use it as a standalone library.
```sh
npm install troika-animation
```
--------------------------------
### Install troika-3d-text
Source: https://github.com/protectwise/troika/blob/main/packages/troika-3d-text/README.md
Install the troika-3d-text package using npm. Ensure a compatible version of Three.js is also installed.
```sh
npm install troika-3d-text
```
--------------------------------
### Install troika-core via NPM
Source: https://github.com/protectwise/troika/blob/main/packages/troika-core/README.md
Install the troika-core package directly from NPM. It is recommended to install Troika 3D or Troika 2D instead, as they include troika-core as a dependency.
```sh
npm install troika-core
```
--------------------------------
### Install React Dependencies
Source: https://github.com/protectwise/troika/blob/main/docs/getting-started/setup.md
Install 'react' and 'react-dom' if you plan to use Troika's React component wrappers like Canvas3D.
```sh
npm install --save react react-dom
```
--------------------------------
### Orthographic Camera Configuration with Troika-3D
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/scenes.md
Set up an orthographic camera using a custom facade. This example demonstrates how to define the camera's boundaries and aspect ratio based on container dimensions.
```javascript
import { OrthographicCamera3DFacade } from 'troika-3d'
//...
camera={{
facade: OrthographicCamera3DFacade,
z: 1,
top: height / 2,
bottom: -height / 2,
left: 0,
right: width
}}
```
--------------------------------
### Start a Tween with a Runner
Source: https://github.com/protectwise/troika/blob/main/packages/troika-animation/README.md
Instantiate a Runner and use its start method to begin the execution of a Tween. The Runner manages the animation loop and updates.
```javascript
import { Tween, Runner } from 'troika-animation'
const tween = new Tween(/*...*/)
const runner = new Runner()
runner.start(tween)
```
--------------------------------
### Install Optional Troika Packages
Source: https://github.com/protectwise/troika/blob/main/docs/getting-started/setup.md
Install additional Troika packages based on your project's specific requirements, such as 2D or text rendering.
```sh
npm install troika-2d
npm install troika-3d-text
etc...
```
--------------------------------
### Install Three.js Dependency
Source: https://github.com/protectwise/troika/blob/main/docs/getting-started/setup.md
Install the 'three' package as a peer dependency. This is required for all 3D-related Troika packages.
```sh
npm install --save three
```
--------------------------------
### Default Perspective Camera Configuration
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/scenes.md
Configure the camera for your 3D scene using a descriptor object. This example shows a perspective camera with specific position and field of view settings.
```javascript
camera={{
x: 5,
rotateY: -Math.PI / 2,
fov: 75,
far: 30
}}
```
--------------------------------
### Referencing Facade Instances with `ref`
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/scene-descriptors.md
Use the `ref` property to get a direct reference to a facade instance when it's created or destroyed. This is useful for imperative actions but should be used sparingly.
```javascript
function ballRefFunction(ballFacade) {
console.log('BallFacade was ' + (ballFacade ? 'created' : 'destroyed'))
}
//...
{
facade: BallFacade,
key: 'ball',
ref: ballRefFunction
}
```
--------------------------------
### Define Keyframe Animations
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/animations-and-transitions.md
Use the 'animation' property to define keyframe animations that run when a Facade is created. This example rotates an object indefinitely.
```javascript
{
facade: MyObject,
animation: {
0: {rotateY: 0},
100: {rotateY: Math.PI * 2},
duration: 1500,
iterations: Infinity
}
}
```
--------------------------------
### Setup ReactXRAware HOC for WebXR
Source: https://github.com/protectwise/troika/blob/main/docs/troika-xr/index.md
Use the ReactXRAware HOC to wrap your parent React component that manages the Canvas3D. This injects WebXR-related props and provides an xrLauncher element for initiating XR sessions. Place the xrLauncher outside the Canvas3D element.
```javascript
import { ReactXRAware } from './XRAware.js'
class App extends React.Component {
render() {
return
{
// This is the button that lets the user launch into XR!
this.props.xrLauncher
}
}
}
export const XRApp = ReactXRAware(App, {
//...XR options
})
```
--------------------------------
### Defining Scene Objects with Facades and Children
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/scenes.md
Structure your 3D scene by defining objects using descriptor objects, specifying their facades, properties, and hierarchical relationships. This example includes a group with nested spheres and custom objects.
```javascript
objects={
[
{
key: 'mainGroup',
z: -2,
facade: Group3DFacade,
children: [
{
facade: SphereFacade,
radius: 0.25,
x: -1,
'material.color': 0x3366cc
},
{
facade: CustomObjectFacade,
x: 1
}
]
}
]
}
```
--------------------------------
### Create a Facade Instance via Scene Descriptor
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/facades.md
Instantiate a facade and set its properties using a scene descriptor object. This object maps keys to facade classes and their initial values.
```javascript
{
key: 'thing1',
facade: MyThingFacade,
width: 100,
height: 45,
depth: 23,
color: '#336699'
}
```
--------------------------------
### Validate Release Readiness with npm Scripts
Source: https://github.com/protectwise/troika/blob/main/BUILD_NOTES.md
Run these commands to ensure the project is ready for a new release. They build the project, run tests, and perform linting.
```bash
npm run build
npm run test
npm run lint
npm run build-examples
```
--------------------------------
### Configure Spring-Based Transitions
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/animations-and-transitions.md
Configure spring-based transitions using 'spring: true', a named preset like 'wobbly', or a custom object with mass, tension, and friction. A delay can also be specified.
```javascript
transition: {
myProp: {
spring: true,
// or spring: 'wobbly',
// or spring: {mass, tension, friction},
delay: 250 //in ms, defaults to 0
}
}
```
--------------------------------
### Text Class Initialization and Usage
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md
Demonstrates how to import, instantiate, configure, and manage a Text object in a Three.js scene.
```APIDOC
## Text Class
### Description
Represents a mesh that renders text using signed distance fields (SDF) in a Three.js scene.
### Usage
```javascript
import { Text } from 'troika-three-text'
// Create an instance
const myText = new Text()
myScene.add(myText)
// Configure properties
myText.text = 'Hello world!'
myText.fontSize = 0.2
myText.position.z = -2
myText.color = 0x9966FF
// Synchronize changes (optional, but recommended for immediate updates)
myText.sync()
// Dispose of the instance when done to prevent memory leaks
myScene.remove(myText)
myText.dispose()
```
### Properties
Instances of `Text` support the following configuration properties:
#### `text` (string)
The string of text to be rendered. Newlines and repeating whitespace characters are honored.
Default: _none_
#### `anchorX` (number | string)
Defines the horizontal position in the text block that should line up with the local origin. Can be specified as a numeric `x` position in local units, a string percentage of the total text block width e.g. `'25%'`, or one of the following keyword strings: `'left'`, `'center'`, or `'right'`.
Default: `0`
#### `anchorY` (number | string)
Defines the vertical position in the text block that should line up with the local origin. Can be specified as a numeric `y` position in local units (note: down is negative y), a string percentage of the total text block height e.g. `'25%'`, or one of the following keyword strings: `'top'`, `'top-baseline'`, `'top-cap'`, `'top-ex'`, `'middle'`, `'bottom-baseline'`, or `'bottom'`.
Default: `0`
#### `clipRect` (Array)
If specified, defines the `[minX, minY, maxX, maxY]` of a rectangle outside of which all pixels will be discarded. This can be used for example to clip overflowing text when `whiteSpace='nowrap'`.
Default: _none_
#### `color` (number | string)
This is a shortcut for setting the `color` of the text's `material`. You can use this if you don't want to specify a whole custom `material` and just want to change its color. Use the `material` property if you want to control aspects of the material other than its color.
Default: _none_ - uses the color of the `material`
### Methods
#### `sync()`
Forces an update of the text geometry and rendering. It's a good idea to call this after changing properties that affect layout. If not called manually, it will be invoked automatically on the next render frame.
#### `dispose()`
Cleans up resources associated with the `Text` instance to prevent memory leaks. Should be called when the instance is no longer needed.
```
--------------------------------
### Configure Troika-three-text Pipeline Globally
Source: https://context7.com/protectwise/troika/llms.txt
Use `configureTextBuilder` before the first `Text` instance syncs to set defaults for font URL, SDF quality, texture atlas size, and worker usage. Ensure this is called once at app startup.
```javascript
import { configureTextBuilder } from 'troika-three-text'
// Call once at app startup, before any Text instances are created
configureTextBuilder({
defaultFontURL: '/fonts/MyAppFont.woff', // global fallback font
unicodeFontsURL: 'https://my-cdn.com/unicode-fonts-data', // self-host Noto fonts
sdfGlyphSize: 128, // higher quality (default: 64); must be power-of-two
sdfExponent: 9, // precision near glyph edges
textureWidth: 4096, // larger SDF atlas for many unique glyphs (default: 2048)
useWorker: false, // disable web worker (e.g., for strict CSP environments)
})
```
--------------------------------
### Enable Postprocessing Workaround for Troika-three-text
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md
Enable a special mode in the postprocessing library to ensure Troika-three-text's custom material is honored. This should be done once in your application's setup.
```javascript
import { OverrideMaterialManager } from 'postprocessing'
OverrideMaterialManager.workaroundEnabled = true
```
--------------------------------
### Create a Custom Facade Class
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/facades.md
Define a custom facade by extending the base Facade class. Implement constructor for initialization, getters/setters for property synchronization, afterUpdate for interdependent property updates, and destructor for cleanup.
```javascript
import { Facade } from 'troika-core'
export class MyThingFacade extends Facade {
// Instantiation:
constructor (parent) {
super(parent)
// Init backing object:
this._impl = new SuperComplicatedObject()
// Define state properties with initial values:
this.width = 1
this.height = 1
this.depth = 1
this.color = '#123456'
}
// Getter/setter for directly syncing a standalone property:
set color (value) {
this._impl.setColor(value)
}
get color () {
return this._impl.getColor()
}
// Handler for syncing interdependent properties:
afterUpdate () {
this._impl.setDimensions(this.width, this.height, this.depth)
super.afterUpdate() //don't forget the super call!
}
// Cleanup:
destructor () {
this._impl.teardown()
delete this._impl
super.destructor()
}
}
```
--------------------------------
### Create a basic Tween
Source: https://github.com/protectwise/troika/blob/main/packages/troika-animation/README.md
Create a Tween instance to animate a value from a start to an end point over a specified duration, with optional delay, easing, and iteration settings. A callback function is invoked on each frame with the tweened value.
```javascript
import { Tween } from 'troika-animation'
function onTweenFrame(tweenedValue) {
// ...do something with the tweenedValue
}
const tween = new Tween(
onTweenFrame, // callback
-100, // fromValue
100, // toValue
5000, // duration in ms
0, // delay
'easeOutExpo', // easing
1, // iterations
'forward', // direction
'number' // interpolation
)
```
--------------------------------
### Import Troika-3D-UI
Source: https://github.com/protectwise/troika/blob/main/packages/troika-3d-ui/README.md
Import the troika-3d-ui library for use in your project. Further API demonstration is pending.
```javascript
import troika3dUi from 'troika-3d-ui';
// TODO: DEMONSTRATE API
```
--------------------------------
### Get Caret and Selection Rectangles with Troika-three-text
Source: https://context7.com/protectwise/troika/llms.txt
After a `Text` syncs, `getCaretAtPoint` and `getSelectionRects` convert 2D text plane positions to caret or selection rectangles using the `textRenderInfo` object. These are useful for implementing text interaction features.
```javascript
import { Text, getCaretAtPoint, getSelectionRects } from 'troika-three-text'
import * as THREE from 'three'
const textMesh = new Text()
textMesh.text = 'Click me to place a cursor!'
textMesh.fontSize = 0.2
textMesh.anchorX = 'center'
textMesh.anchorY = 'middle'
textMesh.sync()
// After a raycast hit, convert 3D world point to 2D text-plane coords:
function onPointerClick(event) {
const raycaster = new THREE.Raycaster()
raycaster.setFromCamera(mouse, camera)
const hits = raycaster.intersectObject(textMesh)
if (hits.length) {
const localPoint = textMesh.worldToLocal(hits[0].point.clone())
const coords = textMesh.localPositionToTextCoords(localPoint) // {x, y}
// Find the nearest caret position
const caret = getCaretAtPoint(textMesh.textRenderInfo, coords.x, coords.y)
// caret: { x, y, height, charIndex }
console.log(`Click landed before character index ${caret.charIndex}`)
// Get selection rectangles for characters 5 through 12
const rects = getSelectionRects(textMesh.textRenderInfo, 5, 12)
// rects: Array<{ left, top, right, bottom }>
rects.forEach(r => drawHighlightRect(r.left, r.bottom, r.right, r.top))
}
}
```
--------------------------------
### `configureTextBuilder`
Source: https://context7.com/protectwise/troika/llms.txt
Globally configure the text pipeline for all `Text` instances. This function must be called before any `Text` instance performs its first sync, allowing you to set defaults for font URLs, SDF quality, and texture atlas size.
```APIDOC
## `configureTextBuilder` — Global text pipeline configuration
Must be called before any `Text` instance performs its first sync. Lets you set the default font URL, unicode fallback font hosting, SDF quality, texture atlas size, and worker usage.
### Parameters
- **defaultFontURL** (string, optional) - The global fallback font URL.
- **unicodeFontsURL** (string, optional) - URL for hosting Noto fonts for Unicode support.
- **sdfGlyphSize** (number, optional) - The quality of SDF glyphs (default: 64). Must be a power-of-two.
- **sdfExponent** (number, optional) - Precision near glyph edges.
- **textureWidth** (number, optional) - The width of the SDF texture atlas (default: 2048). Larger values are suitable for many unique glyphs.
- **useWorker** (boolean, optional) - Whether to use a web worker for text processing (default: true). Disable for strict CSP environments.
### Request Example
```js
import { configureTextBuilder } from 'troika-three-text'
configureTextBuilder({
defaultFontURL: '/fonts/MyAppFont.woff',
unicodeFontsURL: 'https://my-cdn.com/unicode-fonts-data',
sdfGlyphSize: 128,
sdfExponent: 9,
textureWidth: 4096,
useWorker: false,
})
```
```
--------------------------------
### Create Derived Material with Vertex Transformation
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-utils/docs/createDerivedMaterial.md
Use `createDerivedMaterial` to extend a `MeshStandardMaterial` with custom vertex shader code. This example adds a time-based wave animation to a plane mesh. Ensure `castShadow` is enabled and `customDepthMaterial` is set for shadow mapping.
```javascript
import { createDerivedMaterial} from 'troika-three-utils'
import { Mesh, MeshStandardMaterial, PlaneGeometry } from 'three'
const baseMaterial = new MeshStandardMaterial({color: 0xffcc00})
const customMaterial = createDerivedMaterial(
baseMaterial,
{
timeUniform: 'elapsed',
// Add GLSL to tweak the vertex... notice this modifies the `position`
// and `normal` attributes, which is normally not possible!
vertexTransform: `
float waveAmplitude = 0.1;
float waveX = uv.x * PI * 4.0 - mod(elapsed / 300.0, PI2);
float waveZ = sin(waveX) * waveAmplitude;
normal.xyz = normalize(vec3(-cos(waveX) * waveAmplitude, 0.0, 1.0));
position.z += waveZ;
`
}
)
const mesh = new Mesh(
new PlaneGeometry(1, 1, 64, 1),
customMaterial
)
// to enable directional light shadows:
mesh.castShadow = true
mesh.customDepthMaterial = customMaterial.getDepthMaterial()
```
--------------------------------
### Import Troika-2D
Source: https://github.com/protectwise/troika/blob/main/packages/troika-2d/README.md
Import the troika-2d library for use in your project. Further API demonstration is pending.
```javascript
import troika2d from 'troika-2d';
// TODO: DEMONSTRATE API
```
--------------------------------
### Publish New Version from Git Tag with Lerna
Source: https://github.com/protectwise/troika/blob/main/BUILD_NOTES.md
After checking out the tagged commit and ensuring you are logged into NPM, run this command to publish the new version to the NPM registry.
```bash
npm run build
npm login
npx lerna publish from-git
```
--------------------------------
### Define and Use a Worker Module with Dependencies
Source: https://github.com/protectwise/troika/blob/main/packages/troika-worker-utils/README.md
Demonstrates defining a simple worker module that returns a primitive value, and another module that depends on the first. The second module's init function receives the value from the first, and its return value is a function that can be called from the main thread.
```javascript
import { defineWorkerModule } from 'troika-worker-utils'
// A simple module with a value:
const workerModuleA = defineWorkerModule({
init: function() {
return Math.PI
}
})
// A module that depends on the previous module:
const workerModuleB = defineWorkerModule({
dependencies: [
workerModuleA
],
init: function(moduleAValue) {
// moduleAValue here is "I'm the value of Module A!" from the first init function
// This return function can be invoked by calling workerModuleB in the main thread:
let callCount = 0
return function(arg) {
return `Called module B ${++callCount} times, `
+ `with arg "${arg}". Module A's value was ${moduleAValue}.`
}
}
})
workerModuleB('foo') // "Called module B 1 times, with arg "foo". Module A's value was 3.141592653589793."
workerModuleB('bar') // "Called module B 2 times, with arg "bar". Module A's value was 3.141592653589793."
```
--------------------------------
### Create and Configure BezierMesh
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-utils/docs/BezierMesh.md
Instantiate BezierMesh and define its endpoints, control points, and radius. Add the mesh to the scene. This is useful for drawing curved lines with thickness.
```javascript
import { BezierMesh } from 'troika-three-utils'
const bezier = new BezierMesh()
bezier.pointA.set(-0.3, 0.4, -0.3)
bezier.controlA.set(0.7, 0.6, 0.4)
bezier.controlB.set(-0.6, -0.6, -0.6)
bezier.pointB.set(0.7, 0, -0.7)
bezier.radius = 0.01
scene.add(bezier)
```
--------------------------------
### Configure Duration-Based Transitions
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/animations-and-transitions.md
Customize duration-based transitions with parameters like duration, easing, delay, and interpolation. Defaults are provided if not specified.
```javascript
transition: {
z: {
duration: 1234, //in ms, defaults to 750
easing: 'easeInOutBounce', //easing function, defaults to 'easeOutCubic'
delay: 123, //in ms, defaults to 0
interpolate: 'number' //see "Interpolation" below
}
}
```
--------------------------------
### Object Methods
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/objects.md
A collection of methods for retrieving world transformations, projected screen coordinates, camera information, and for managing matrix updates.
```APIDOC
## Methods
- `getWorldPosition(Vector3?)` - Gets the world position of this object's origin. If a Vector3 is passed, the position will be written into that object, otherwise it will return a new Vector3. Assuming this is called in the facade's update phase, the world matrix will be up-to-date.
- `getProjectedPosition(x, y, z)` - Given x/y/z coordinates in _local_ space, calculates the projected _view_ space coordinates. Returns a Vector3 where `x` and `y` are the view position in screen pixels, and `z` is the worldspace distance from the camera.
- `getCameraPosition(Vector3?)` - Gets the current world position of the camera. If a Vector3 is passed, the position will be written into that object, otherwise it will return a new Vector3.
- `getCameraDistance()` - Returns the current distance in world units between this object's origin and the camera.
- `getCameraFacade()` - Returns a reference to the `CameraFacade` instance. This can be used to access low-level info about the camera such as its various matrices and projection attributes, but be careful not to make modifications to the camera as that can lead to things getting out of sync.
- `getSceneFacade()` - Returns a reference to the `SceneFacade` instance. This can be useful in a pinch, but it's usually better to pass any required scene-level values to each facade.
- `updateMatrices()` - Updates the underlying threeObject's `matrix` and `matrixWorld` to the current state of this object's transform and those of its ancestors, if necessary. This bypasses the `updateMatrix` and `updateMatrixWorld` methods of the Three.js objects with a more efficient approach that doesn't require traversing the entire tree prior to every render. As long as this is called from the `afterUpdate` lifecycle method or later, it can be safely assumed that the world matrices of all ancestors have already been similarly updated, so the result should always be accurate.
- `markWorldMatrixDirty()` - If the `threeObject.matrixWorld` is modified manually instead of via the [local transform properties](#local-transform-properties), as is sometimes required for more complex transformations, you should call this to update the internal caches and signal that child objects should update their own matrices to match.
```
--------------------------------
### Version a New Release Without Pushing to GitHub
Source: https://github.com/protectwise/troika/blob/main/BUILD_NOTES.md
Execute this Lerna command to version the release and create a Git tag locally without automatically pushing to GitHub. Manual push is required later.
```bash
npx lerna version --no-push
```
--------------------------------
### Version and Tag a New Release with Lerna
Source: https://github.com/protectwise/troika/blob/main/BUILD_NOTES.md
Use Lerna to version the release, update package.json files, and create a Git tag. This command will prompt for the version number.
```bash
npx lerna version
```
--------------------------------
### Instancing Uniforms with InstancedUniformsMesh
Source: https://github.com/protectwise/troika/blob/main/packages/three-instanced-uniforms-mesh/README.md
Demonstrates how to set instance-specific uniform values for 'metalness' and 'emissive' using MeshStandardMaterial. Calling `setUniformAt` automatically handles buffer attribute updates.
```javascript
import { InstancedUniformsMesh } from 'three-instanced-uniforms-mesh'
const count = 100
const mesh = new InstancedUniformsMesh(
someGeometry,
new MeshStandardMaterial(),
count
)
const color = new Color()
for (let i = 0; i < count; i++) {
mesh.setMatrixAt(i, someMatrixValue)
mesh.setUniformAt('metalness', i, Math.random())
mesh.setUniformAt('emissive', i, color.set(Math.random() * 0xffffff))
}
```
--------------------------------
### Create a SpringTween for physics-based animation
Source: https://github.com/protectwise/troika/blob/main/packages/troika-animation/README.md
Utilize SpringTween for animations driven by a spring physics simulation instead of a fixed duration. Configure the simulation with mass, tension, and friction, or use named presets.
```javascript
import { SpringTween } from 'troika-animation'
const tween = new SpringTween(
onTweenFrame, // callback
-100, // fromValue
100, // toValue
{
mass: 1,
tension: 170,
friction: 26
}, // spring simulation config, or the name of a preset
0 // delay
)
```
--------------------------------
### Implementing initThreeObject() for a Custom Object
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/objects.md
Use this method to create and return the Three.js Object3D instance for your facade. The geometry can be a singleton for performance.
```javascript
import { Object3DFacade } from 'troika-3d'
import { Mesh, BoxGeometry, MeshStandardMaterial } from 'three'
// It's often to define a singleton geometry instance that can be used
// across all instances of this object type:
const geometry = new BoxGeometry()
class MyObject extends Object3DFacade {
initThreeObject() {
return new Mesh(geometry, new MeshStandardMaterial())
}
afterUpdate() {
// The Mesh created above can be referenced as `threeObject`:
this.threeObject.material.color.set(this.color)
super.afterUpdate()
}
}
```
--------------------------------
### Configuring Lights in a 3D Scene
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/scenes.md
Define the main lights for your scene using an array of descriptor objects. Specify light types like 'ambient', 'directional', 'spot', 'point', or 'hemisphere', and optionally use custom facades.
```javascript
lights={
[
{type: 'ambient', color: 0x999999},
{type: 'directional', x: 1, y: 1, z: 1},
{facade: WanderingPointLight, color: 0xff0000}
]
}
```
--------------------------------
### Basic 3D Text Facade Configuration
Source: https://github.com/protectwise/troika/blob/main/docs/troika-3d/text.md
Configure a Text3DFacade for a Troika 3D scene. Ensure the font URL is valid and specify text content, font size, and color. Other properties from troika-three-text are also supported.
```javascript
import { Text3DFacade } from 'troika-3d-text'
{
key: 'text',
facade: Text3DFacade,
font: 'https://url/of/font.woff',
text: 'Hello World!',
fontSize: 0.1,
color: 0xccccff
//...other props
}
```
--------------------------------
### Define Transitions for Facade Properties
Source: https://github.com/protectwise/troika/blob/main/docs/troika-core/animations-and-transitions.md
Use the 'transition' property in a descriptor to animate changes to specified properties. 'true' uses a default duration-based transition, 'spring' uses a default spring-based transition, or provide a detailed configuration object.
```javascript
{
facade: MyObject,
x: xVal,
y: yVal,
z: zVal,
transition: {
x: true, // uses a default duration-based transition
y: 'spring', //uses a default spring-based transition
z: { //detailed transition parameters:
duration: 500,
easing: 'easeOutExpo'
}
}
}
```
--------------------------------
### Import Text from troika-three-text
Source: https://github.com/protectwise/troika/blob/main/packages/troika-3d-text/README.md
Import the Text facade from the troika-three-text package for standalone use.
```javascript
import { Text } from 'troika-three-text'
let myText = new Text()
```
--------------------------------
### Configure Global Unicode Fonts URL
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md
Set a custom URL for hosting unicode font data globally. This is useful for self-hosting font files instead of using the default CDN.
```javascript
import {configureTextBuilder} from 'troika-three-text'
configureTextBuilder({
unicodeFontsURL: 'https://my.host/unicode-fonts-data'
})
```
--------------------------------
### Preload Font and Glyphs with Troika-three-text
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md
Preload font files and optionally pre-generate SDF textures for specific characters to avoid long pauses when first displaying text. The callback function is executed once preloading is complete.
```javascript
import {preloadFont} from 'troika-three-text'
myApp.showLoadingScreen()
preloadFont(
{
font: 'path/to/myfontfile.woff',
characters: 'abcdefghijklmnopqrstuvwxyz'
},
() => {
myApp.showScene()
}
)
```
--------------------------------
### Import and Use Troika Text Mesh
Source: https://github.com/protectwise/troika/blob/main/packages/troika-three-text/README.md
Import the Text class and use it as a Three.js mesh. Remember to call `.sync()` after changing properties that affect layout and `.dispose()` when done to prevent memory leaks.
```js
import {Text} from 'troika-three-text'
```
```js
// Create:
const myText = new Text()
myScene.add(myText)
// Set properties to configure:
myText.text = 'Hello world!'
myText.fontSize = 0.2
myText.position.z = -2
myText.color = 0x9966FF
// Update the rendering:
myText.sync()
```
```js
myScene.remove(myText)
myText.dispose()
```