Skip to main content

mtlx-viewer

Shared three.js MaterialX preview viewer, used by the mtlx.ben3d.ca website, the VS Code extension and mtlx view. Everything here pulls in three.js; the three-free pieces live at mtlx-viewer/settings, mtlx-viewer/diagnostics and mtlx-viewer/capabilities.

Other​

parseEnvironmentFile()​

function parseEnvironmentFile(data, source): Promise<Texture<unknown, TextureEventMap>>;

Parse an equirectangular IBL from its file extension (.hdr, .exr, .png, .jpg).

Parameters​

ParameterType
dataArrayBuffer
sourcestring

Returns​

Promise<Texture<unknown, TextureEventMap>>


createEnvironmentSwitcher()​

function createEnvironmentSwitcher<Source>(
load,
prepare,
apply
): object;

Owns the active filtered environment and discards superseded asynchronous loads.

Type Parameters​

Type ParameterDefault type
Source extends objectTexture<unknown, TextureEventMap>

Parameters​

ParameterType
load(kind) => Promise<Source>
prepare(texture) => object
apply(texture) => void

Returns​

object

NameType
set()(kind) => Promise<boolean>
dispose()() => void

LoadingProgress​

Overall loading progress, including processing and the first render.

Properties​

PropertyType
totalProgressnumber
reason"material-load" | "environment-update" | "geometry-update"

LoadingTracker​

Aggregate overlapping activities. Progress never moves backwards within a loading cycle.

Constructors​

Constructor​
new LoadingTracker(publish): LoadingTracker;
Parameters​
ParameterType
publish(progress) => void
Returns​

LoadingTracker

Methods​

reset()​
reset(): void;
Returns​

void

start()​
start(reason): (progress) => void;
Parameters​
ParameterType
reason"material-load" | "environment-update" | "geometry-update"
Returns​

(progress) => void


MaterialProgress​

Download progress for the material file, excluding preview assets and rendering setup.

Properties​

PropertyTypeDescription
loadednumber-
totalnumber | nullFile size in bytes, or null when the server does not provide a usable Content-Length.
progressnumber | nullFraction from 0 to 1, or null while the file size is unknown.

readMaterialResponse()​

function readMaterialResponse(
response,
signal,
onProgress
): Promise<ArrayBuffer>;

Read a material response, reporting immediately, every 250 ms, and on completion.

Parameters​

ParameterType
responseResponse
signalAbortSignal
onProgress(progress) => void

Returns​

Promise<ArrayBuffer>


createViewerRendering()​

function createViewerRendering(
renderer,
scene,
camera,
initial?
): object;

Shared HDR pipeline. Initialize the renderer before creating this owner, then dispose it before the renderer.

Parameters​

ParameterTypeDefault value
rendererWebGPURendererundefined
sceneSceneundefined
cameraPerspectiveCameraundefined
initial?RenderingSettingsDEFAULT_RENDERING_SETTINGS

Returns​

NameTypeDescription
configure()(next) => void-
render()() => voidSynchronous after renderer.init(); throws on shader compilation failure.
dispose()() => void-

createViewerRenderer()​

function createViewerRenderer(scope, options): Promise<WebGPURenderer>;

Own the renderer before async initialization so replacement/unmount can always clean it up.

Parameters​

ParameterType
scopeCleanupScope
options{ width: number; height: number; canvas?: HTMLCanvasElement; updateStyle?: boolean; }
options.widthnumber
options.heightnumber
options.canvas?HTMLCanvasElement
options.updateStyle?boolean

Returns​

Promise<WebGPURenderer>


observeViewerResize()​

function observeViewerResize(
scope,
element,
renderer,
camera,
updateStyle?,
onResize?
): void;

Parameters​

ParameterTypeDefault value
scopeCleanupScopeundefined
elementHTMLElementundefined
rendererWebGPURendererundefined
cameraPerspectiveCameraundefined
updateStyle?booleantrue
onResize?() => voidundefined

Returns​

void


applyViewerRenderingSettings()​

function applyViewerRenderingSettings(
renderer,
scene,
rendering,
settings
): void;

Parameters​

ParameterType
renderer{ toneMappingExposure: number; }
renderer.toneMappingExposurenumber
scene{ environmentIntensity: number; environmentRotation: { y: number; }; backgroundRotation: { y: number; }; }
scene.environmentIntensitynumber
scene.environmentRotation{ y: number; }
scene.environmentRotation.ynumber
scene.backgroundRotation{ y: number; }
scene.backgroundRotation.ynumber
rendering{ configure(settings): void; }
rendering.configure(settings) => void
settingsRenderingSettings & object

Returns​

void


dataUrlToArrayBuffer()​

function dataUrlToArrayBuffer(dataUrl): ArrayBuffer;

Decode a base64 data: URL (e.g. a bundler-inlined asset) into bytes; data: URLs are not fetchable under strict CSP.

Parameters​

ParameterType
dataUrlstring

Returns​

ArrayBuffer


ScreenshotOptions​

Properties​

PropertyTypeDescription
width?numberExact output pixels; an omitted dimension preserves the current canvas aspect ratio.
height?number-
mimeType?"image/png" | "image/jpeg" | "image/webp"Defaults to PNG. JPEG cannot preserve transparency and composites it over white.
quality?numberJPEG/WebP encoding quality, from 0 to 1.
background?"none" | "white" | "environment"Defaults to the current backdrop; none preserves alpha in PNG/WebP.

ViewerOptions​

Methods​

loadGeometry()?​
loadGeometry?(name): Promise<{
data: ArrayBuffer;
manager?: LoadingManager;
}>;

Host-configured geometries beyond totem/sphere/cube/plane; manager resolves glTF sidecar files.

Parameters​
ParameterType
namestring
Returns​

Promise<{ data: ArrayBuffer; manager?: LoadingManager; }>

onReport()?​
onReport?(report): void;
Parameters​
ParameterType
reportPreviewReport
Returns​

void

onCameraChange()?​
onCameraChange?(settings): void;

Current camera framing after initialization and each orbit/pan/zoom change.

Parameters​
ParameterType
settingsRequired<CameraSettings>
Returns​

void

onError()?​
onError?(message): void;

The frame loop failed after startup; the viewer is already disposed.

Parameters​
ParameterType
messagestring
Returns​

void

Properties​

PropertyTypeDescription
signal?AbortSignalCancel an in-progress compilation when an editor supplies a newer document.
canvas?HTMLCanvasElementRender into this canvas; otherwise a canvas is created and appended to container.
containerHTMLElementSized against; a created canvas is appended here.
dataArrayBuffer-
fileNamestring-
alt?stringAccessible description of the material, applied to the focusable canvas.
shaderBallArrayBuffer-
settingsViewerSettings-
playing?booleanWhether MaterialX <time>/<frame> nodes advance from the first frame; defaults to true.
loadEnvironment(kind) => Promise<Texture<unknown, TextureEventMap>>-
resolveUrl?(url) => string | undefinedRewrite texture URLs the document references (e.g. to blob: URLs of bytes the host already read).
onLog?(message) => void-
onStatus?(patch) => voidTransient status text; empty when cleared.
onProgress?(progress) => voidOverall progress for setup, resources, settings changes, and rendering.
onStage?(stage) => voidLoading milestones for progress UI.

Viewer​

Methods​

getCameraSettings()​
getCameraSettings(): Required<CameraSettings>;

Capture current framing, including user orbit, pan and zoom, for a share link.

Returns​

Required<CameraSettings>

setPlaying()​
setPlaying(playing): void;
Parameters​
ParameterType
playingboolean
Returns​

void

setAlt()​
setAlt(alt?): void;

Update the accessible description without reloading; empty/undefined restores the default.

Parameters​
ParameterType
alt?string
Returns​

void

setSettings()​
setSettings(settings): Promise<ViewerSettings>;

Apply a full settings object; only changed fields do work. Resolves to what actually took effect.

Parameters​
ParameterType
settingsViewerSettings
Returns​

Promise<ViewerSettings>

replaceMaterial()​
replaceMaterial(data, fileName): void;

Compile a new document into the running scene, keeping the renderer, environment, camera and geometry. Reports through onReport; throws (and keeps the previous material) on a parse failure.

Parameters​
ParameterType
dataArrayBuffer
fileNamestring
Returns​

void

toBlob()​
toBlob(options?): Promise<Blob>;

Capture a completed preview frame, including postprocessing, without changing the on-screen view.

Parameters​
ParameterType
options?ScreenshotOptions
Returns​

Promise<Blob>

dispose()​
dispose(): void;
Returns​

void

Properties​

PropertyModifierTypeDescription
disposedreadonlyboolean-
scenereadonlyMtlxScene-
camerareadonlyPerspectiveCamera-
controlsreadonlyOrbitControls-
playingreadonlybooleanWhether MaterialX <time>/<frame> nodes run forward; scene.animated says whether the document has any.

createViewer()​

function createViewer(options): Promise<Viewer>;

Builds the viewer and renders the first frame; rejects (already disposed) on any setup failure.

Parameters​

ParameterType
optionsViewerOptions

Returns​

Promise<Viewer>

Viewer​

MtlxSceneOptions​

Options for createMtlxScene.

Methods​

onTranslationMessage()?​
onTranslationMessage?(entry): void;

Loader translation log entries (e.g. an unsupported node or an ignored surface input). Errors never throw: parsing continues with a partial material, matching MaterialXView which ignores what it can't render.

Parameters​
ParameterType
entry{ severity: "error" | "warning"; message: string; }
entry.severity"error" | "warning"
entry.messagestring
Returns​

void

Properties​

PropertyTypeDescription
dataArrayBufferRaw .mtlx / .mtlx.zip bytes.
fileNamestringPassed through to MaterialXLoader for resource-path resolution and archive sniffing.
materialName?stringDefaults to the document's last material (matches prior single-material behavior).
geometry?stringDefaults to 'totem'.
autoRotate?booleanDefaults to true.
shaderBallArrayBufferThe shaderball (https://mtlx-static.ben3d.ca/viewer/shaderball.glb) used for the 'totem' geometry.
manager?LoadingManagerSupply your own if you need onProgress/onError wiring (e.g. for texture blobs).
resolveUrl?(url) => string | undefinedRewrite texture URLs the document references (e.g. to blob: URLs of bytes the host already read).

MtlxScene​

A live MaterialX preview scene, returned by createMtlxScene.

Methods​

dispose()​
dispose(): void;

Releases owned geometries, materials and textures; safe to call repeatedly.

Returns​

void

setMaterial()​
setMaterial(name): void;
Parameters​
ParameterType
namestring
Returns​

void

replaceMaterials()​
replaceMaterials(data, fileName): void;

Parse a new document and show it on the current geometry, keeping the camera and orientation. The previous materials stay in place when the new document fails to parse.

Parameters​
ParameterType
dataArrayBuffer
fileNamestring
Returns​

void

hasGeometry()​
hasGeometry(name): boolean;
Parameters​
ParameterType
namestring
Returns​

boolean

setGeometry()​
setGeometry(kind): void;
Parameters​
ParameterType
kindstring
Returns​

void

addGeometry()​
addGeometry(
name,
data,
manager?
): Promise<void>;

Load an additional named glTF/GLB geometry; this scene owns its resources.

Parameters​
ParameterType
namestring
dataArrayBuffer
manager?LoadingManager
Returns​

Promise<void>

resetCamera()​
resetCamera(options?): void;

Restore every geometry's orientation and the initial camera framing.

Parameters​
ParameterType
options?{ resetObjects?: boolean; }
options.resetObjects?boolean
Returns​

void

reframe()​
reframe(): void;

After the viewport aspect changes, re-fit the object while keeping the user's orbit direction and relative zoom.

Returns​

void

update()​
update(deltaSeconds): void;

Call every frame; advances the auto-rotation.

Parameters​
ParameterType
deltaSecondsnumber
Returns​

void

Properties​

PropertyTypeDescription
rootGroupAdd this to your THREE.Scene.
materialNamesstring[]-
activeMaterialstring-
geometrystring-
autoRotateboolean-
animatedbooleanThe current document uses <time> or <frame> nodes, so it changes as time runs.

createMtlxScene()​

function createMtlxScene(
camera,
controls,
options
): Promise<MtlxScene>;

Parses a MaterialX document and builds a swappable preview scene for it. Add the returned scene's .root to your THREE.Scene and call .update(deltaSeconds) each frame.

Parameters​

ParameterType
cameraPerspectiveCamera
controls{ target: Vector3; update: () => void; enableDamping?: boolean; }
controls.targetVector3
controls.update() => void
controls.enableDamping?boolean
optionsMtlxSceneOptions

Returns​

Promise<MtlxScene>

Example​

const scene = await createMtlxScene(camera, controls, { data, fileName, shaderBall });
threeScene.add(scene.root);