Skip to content
kmamalPublic
forked from mrdoob/three.js

About

Fork of three.js that can render to windows

Resources

Stars

2 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

@kmamal/three

Fork of three.js that can render to real windows using @kmamal/sdl, @kmamal/gl (WebGL2) and @kmamal/gpu (WebGPU).

Installing

Install the fork and the packages for the renderers you use:

{
  "dependencies": {
    "@kmamal/three": "*",
    "@kmamal/sdl": "*",
    "@kmamal/gl": "*",
    "@kmamal/gpu": "*"
  }
}

You only need @kmamal/gl for WebGLRenderer and @kmamal/gpu for WebGPU. Add @kmamal/audio for audio and @kmamal/lil-gui for the GUI.

Usage

Pass the SDL window to the renderer instead of a canvas.

import sdl from '@kmamal/sdl'
import * as THREE from '@kmamal/three/webgpu'

const window = sdl.video.createWindow({ title: "Hello, Three!", webgpu: true, resizable: true })

const renderer = new THREE.WebGPURenderer({ window })
await renderer.init()
renderer.setClearColor(0xff0000)

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera()

renderer.setAnimationLoop(() => {
  renderer.render(scene, camera)
})

window.on('close', () => {
  renderer.dispose()
})

For WebGLRenderer, create the window with opengl: true and import from '@kmamal/three'. WebGPURenderer also works with forceWebGL: true on an opengl: true window.

  • render() presents the frame by itself. There is no swap() to call.
  • Resizing is up to you, as in a browser: call renderer.setSize(window.pixelWidth, window.pixelHeight, false) and update the camera aspect from the window's resize event.
  • renderer.dispose() does not destroy the window.
  • antialias: true works on both renderers.

Input

renderer.domElement is an object with the parts of the DOM that three.js addons use: addEventListener, getBoundingClientRect(), clientWidth, ownerDocument, setPointerCapture() and so on. SDL mouse, wheel and keyboard events arrive as pointerdown, pointermove, pointerup, pointercancel, wheel, keydown and keyup, followed by the compatibility events a browser sends: mousedown, mousemove, mouseup, click, dblclick, auxclick and contextmenu (canceling pointerdown suppresses the mouse* ones, as in a browser). Each event is a single object dispatched to the canvas, then ownerDocument, then ownerDocument.defaultView; target stays the canvas and stopPropagation() ends the walk. key comes from the keyboard layout and code from the physical key (the SDL scancode), so KeyW is the same key on every layout.

requestPointerLock() on the canvas or on document.body turns on the window's relative mouse mode and sets document.pointerLockElement; pointer events then target the locked element and carry movementX/movementY. document.exitPointerLock(), Escape and losing focus release it, and pointerlockchange fires on the document each time.

OrbitControls, MapControls, TrackballControls, ArcballControls, FlyControls, FirstPersonControls and TransformControls respond to SDL input. Dragging a TransformControls gizmo handle translates and scales objects along the picked axis, with snapping. Touch input arrives as single-pointer mouse events. SDL captures the mouse while a button is held, so a drag that leaves the window keeps delivering pointermove events (with coordinates outside the window) and ends with a pointerup. setPointerCapture() itself is a no-op.

Loading assets

  • Images are decoded with sharp, so TextureLoader, ImageLoader, CubeTextureLoader and GLTFLoader read PNG, JPEG, WebP, GIF, TIFF, SVG and HEIF from http(s):, file:, data: and blob: URLs, and from plain file paths relative to the current directory.
  • FileLoader reads local files too.
  • XML loaders work: SVGLoader, ColladaLoader, 3MFLoader, AMFLoader and KMZLoader are tested on the sample models, as is FileLoader with responseType: 'document'. VTKLoader (XML PolyData with ASCII arrays) and MaterialXLoader (all sample files) are tested too. UltraHDRLoader is tested against Ultra HDR JPEGs generated by the test suite (gain map range, gamma, offsets, little- and big-endian MPF, upsampled gain maps); it decodes through platform.createImageBitmap. new platform.DOMParser() is a parser built on @xmldom/xmldom, with the namespace-aware queries, CSS selectors, style, sheet and id members these loaders use. Large files are parsed in JavaScript, at roughly 7 MB/s for element-dense XML and much faster for text-heavy files such as Collada float arrays: a 20 MB 3MF model loads in about 4 seconds and a 14 MB 3MF with textures in about 3.
  • DRACOLoader and KTX2Loader run their decoders in worker_threads. Give them an absolute path ending in / for setDecoderPath() or setTranscoderPath(), for example the examples/jsm/libs/draco/ directory of this package.
  • Rhino3dmLoader works with the rhino3dm library (set loader.setLibraryPath() to the directory of the installed package, with a trailing /). Text dots become sprites whose label canvas is sized by platform.devicePixelRatio, the pixel ratio of the first window (or the scale of the first display before any window exists).
  • ImageBitmapLoader works and GLTFLoader uses it. Bitmaps are decoded by sharp and honor imageOrientation: 'flipY' and premultiplyAlpha: 'premultiply'; platform.createImageBitmap and platform.isImageBitmap are the hooks.
  • new platform.Worker(url), platform.fetch(url, init) and the other hooks are exported as platform from '@kmamal/three'.
  • platform.setFetchRoot(dir) makes platform.fetch resolve paths starting with /, such as /models/a.glb, under dir, like a web server root. The real absolute path is not tried while a root is set. file: URLs and relative paths are unaffected. platform.setFetchRoot(null) turns this off again.

2D canvas

document.createElement('canvas') and new OffscreenCanvas() are available through the platform, backed by @napi-rs/canvas (Skia). Use createCanvasElement() or platform.createElement('canvas') to create one, and platform.OffscreenCanvas and platform.ImageData for the other classes.

  • CanvasTexture works on all renderers, including text drawn with fillText(), alpha, and redrawing with needsUpdate.
  • ImageUtils.getDataURL(), texture and scene JSON serialization, GLTFExporter (binary and JSON) and SVGLoader gradients work.
  • Text uses the system fonts that Skia finds. Register more with GlobalFonts from @napi-rs/canvas.
  • Addons that create canvases through platform.createElement() include GLTFExporter, USDZExporter, SVGLoader, Lut, FlakesTexture, UVsDebug, ViewHelper, LUTImageLoader, LightProbeGenerator, VolumeSlice and the shadow map viewers.
  • Addons that need a real DOM do not work: HTMLMesh, AsciiEffect, Text2D, and the helpers that draw a renderer's own canvas into a 2D canvas.

GUI

examples/jsm/libs/lil-gui.module.js re-exports @kmamal/lil-gui, which implements the lil-gui API (add, addColor, addFolder, onChange, listen, save/load and so on) for SDL. Install it next to @kmamal/three to use the GUI in the examples or in your own code. Each root new GUI() opens its own window, and folders share their root's window. GUI.destroyAll() closes every GUI window, and the windows keep the process alive like any SDL window. See its README for the details.

Examples

Ported examples are plain Node scripts next to the original HTML, for example examples/webgl_geometry_cube.mjs. Run them with node examples/webgl_geometry_cube.mjs from any directory.

The .mjs files are generated from the untouched upstream HTML by utils/port-examples.js, plus small hand-written patches in utils/port-examples/patches/ for examples that need more than the mechanical conversion (multiple windows, for example). npm run port-examples regenerates them and npm run port-examples-check fails if a file drifted; after editing an example by hand, run node utils/port-examples.js --update-patches <name>. Examples that use npm packages which import three (three-mesh-bvh, postprocessing and others) rely on node_modules/three being utils/three-alias, a package named three whose files are this package's, so both names load the same modules.

They open their window through examples/jsm/utils/SDLWindow.js:

import * as THREE from '@kmamal/three';
import { createWindow, window } from '@kmamal/three/addons/utils/SDLWindow.js';

const sdlWindow = createWindow( { title: 'three.js webgl - geometry - cube', api: 'webgl' } );

const renderer = new THREE.WebGLRenderer( { antialias: true, window: sdlWindow } );
renderer.setSize( window.innerWidth, window.innerHeight );

window.addEventListener( 'resize', () => renderer.setSize( window.innerWidth, window.innerHeight ) );
  • createWindow() takes api: 'webgl' for a WebGLRenderer and api: 'webgpu' for a WebGPURenderer. Pass forceWebGL: true if the WebGPURenderer is created with forceWebGL.
  • window and document are the same objects the renderer canvas dispatches input events to. window has innerWidth, innerHeight, devicePixelRatio, requestAnimationFrame(), fires resize when the SDL window changes size and load once the script has run, and calls onresize/onload style handlers. They refer to the first window created, like platform.window and platform.document.
  • location.search comes from the command line: node examples/webgpu_compile_async.mjs count=10 sees ?count=10. Assigning location.href or location.search, or calling location.reload(), restarts the script with the new arguments.
  • alert(), confirm() and prompt() print their message; confirm() returns false and prompt() its default value.
  • Relative asset paths resolve from the examples/ directory and paths starting with / from the package root, as when the HTML was served from the repository root.
  • Stats from libs/stats.module.js keeps its API and shows the frame rate in the window title, for example three.js webgl - geometry - cube - 60 fps, 16 ms. setStatus() and setTitle() change the title directly.
  • new GUI() windows are closed and the process exits when any example window closes.
  • A WebGLRenderer window works together with GUI windows because the GUI uses a software renderer. Under i3 the example window stays tiled and the GUI windows float.

How it works

src/platform/Platform.js is a registry of everything three.js used to take from browser globals: requestAnimationFrame, navigator.gpu, fetch, presenting a frame, canvas and element creation, and the browser classes (platform.Image, ImageBitmap, OffscreenCanvas, ImageData, DOMParser, FileReader, Worker, ProgressEvent) and navigator.clipboard (platform.clipboard, backed by the SDL clipboard). Ported code replaces a global with the same name on platform, for example new DOMParser() becomes new platform.DOMParser() and window.innerWidth becomes platform.window.innerWidth. The GPUBufferUsage, GPUTextureUsage and GPUMapMode constants are plain numbers in WebGPUConstants.js, so importing the WebGPU renderer does not load @kmamal/gpu until it is used. There is no browser implementation: platform is backed by src/platform/sdl/, which provides an SDLCanvas, the event bridge, image decoding, a fetch for local files, and a worker shim. setPlatform() can still override individual hooks, for example to stub them in tests. The package entry points (@kmamal/three, @kmamal/three/webgpu, @kmamal/three/tsl) resolve straight to src/, so addons that import '@kmamal/three' always share this one instance.

Limitations

  • The window surface for WebGPURenderer is bgra8unorm, like a browser canvas.
  • Audio runs on @kmamal/audio, a Web Audio API implementation over @kmamal/sdl. platform.AudioContext and platform.Audio come from it (the ported examples use them instead of browser globals), and its fetch is routed through the platform so new platform.Audio('sounds/x.mp3') resolves like the other example assets. Rendering happens on the main thread, so long stalls cause dropouts. There are no video textures, no XR, no HTMLTexture and no CSS renderers.
  • @kmamal/gl exposes the S3TC, ETC2, ASTC, BPTC and RGTC compressed texture extensions that the GPU driver supports, so KTX2Loader picks a compressed format. Without support it falls back to uncompressed RGBA.

Tests

npm test                       # lint, upstream unit tests (the TSL/GPU ones in hidden windows), platform unit tests
npm run test-platform          # the SDL platform layer and the GUI, no display or GPU needed
npm run test-platform-window   # real windows: resizing, controls driven by SDL events, context loss
npm run test-e2e               # every example against its browser screenshot, see test/e2e/README.md

The window tests need a display and a GPU, and skip themselves otherwise. On a tiling window manager, windows are made floating through i3-msg when I3SOCK is set, so the resize tests can run. Tests for @kmamal/gl and @kmamal/gpu features live in those packages.

About

Fork of three.js that can render to windows

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages