katachi-runtime 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -106,11 +106,23 @@ class Assets {
106
106
  }
107
107
 
108
108
  class Stage {
109
- constructor(canvas: HTMLCanvasElement, options?: { autoRotate?: boolean; zoom?: boolean }); // drag to orbit, scroll to zoom; zoom: false leaves scrolling to the page; draws nothing while off screen
110
- show(assets: Assets, name: string, props?: VehicleProps): Promise<Model | undefined>; // undefined if another model was shown meanwhile
109
+ constructor(canvas: HTMLCanvasElement, options?: StageOptions); // drag to orbit, scroll to zoom; draws nothing while off screen
110
+ show(assets: Assets, name: string, props?: VehicleProps): Promise<Model | undefined>; // resolves once drawn; undefined if another model was shown meanwhile
111
+ view(direction?: [number, number, number], options?: { duration?: number }): Promise<boolean>; // flies around the model to look from there, or back to model.view; false if the user took over
112
+ setAutoRotate(on: boolean): void;
113
+ setLighting(lighting: "studio" | "night", options?: { duration?: number }): void; // fades the studio light to night and back
114
+ pick(clientX: number, clientY: number): THREE.Object3D | null; // the bone or mesh under a pointer, read from the GPU
115
+ photo(width: number, height: number): Promise<Blob>; // PNG of the current view, transparent background
111
116
  dispose(): void;
112
117
  }
113
118
 
119
+ interface StageOptions {
120
+ autoRotate?: boolean;
121
+ zoom?: boolean; // false leaves the wheel and vertical swipes to the page
122
+ entrance?: boolean; // the camera glides in when a model is shown
123
+ inset?: { top?: number; bottom?: number }; // pixels the model stays clear of, for controls over the canvas
124
+ }
125
+
114
126
  class Model {
115
127
  name: string;
116
128
  root: THREE.Group; // add this to your scene
@@ -137,6 +149,8 @@ class Vehicle extends Model {
137
149
  setLights(on: boolean): void;
138
150
  openings(): Opening[];
139
151
  setOpen(name: Opening, amount: number): void; // 0 to 1
152
+ openingOf(node: THREE.Object3D): Opening | null; // the door or panel a picked node belongs to
153
+ static views: { front; side; rear; top }; // directions for Stage.view
140
154
  extras(): number[];
141
155
  extraEnabled(id: number): boolean;
142
156
  setExtra(id: number, enabled: boolean): void;
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Assets, type ModEntry, type ModelEntry, type ModelKind, type PedEntry, type PieceEntry, type VehicleEntry, type WheelEntry } from "./assets";
2
2
  export { Character } from "./character";
3
3
  export { Model } from "./model";
4
- export { Stage, ThumbnailRenderer, type StageOptions, type ThumbnailFormat } from "./stage";
4
+ export { Stage, ThumbnailRenderer, type Direction, type StageInset, type StageLighting, type StageOptions, type ThumbnailFormat } from "./stage";
5
5
  export { Vehicle, type Color, type Opening, type PaintName, type VehicleProps } from "./vehicle";
package/index.js CHANGED
@@ -1338,6 +1338,7 @@ class Vehicle extends Model {
1338
1338
  wheelTypes;
1339
1339
  paints;
1340
1340
  loader;
1341
+ static views = { front: [0, 0.12, -1], side: [-1, 0.1, 0], rear: [0, 0.16, 1], top: [0, 1, 0.04] };
1341
1342
  view = [-0.6, 0.25, -0.75];
1342
1343
  rest = new Map;
1343
1344
  hidden;
@@ -1431,6 +1432,14 @@ class Vehicle extends Model {
1431
1432
  bone.rotateZ(turn[2] * open);
1432
1433
  bone.position.set(rest.position.x + slide[0] * open, rest.position.y + slide[1] * open, rest.position.z + slide[2] * open);
1433
1434
  }
1435
+ openingOf(node) {
1436
+ for (let part = node;part; part = part.parent) {
1437
+ const opening = this.openings().find((name) => OPENINGS[name].bone === part?.name);
1438
+ if (opening)
1439
+ return opening;
1440
+ }
1441
+ return null;
1442
+ }
1434
1443
  extras() {
1435
1444
  return [...this.extraStates.keys()].sort((a, b) => a - b);
1436
1445
  }
@@ -1649,12 +1658,157 @@ class Assets {
1649
1658
  }
1650
1659
  }
1651
1660
  // src/stage.ts
1652
- import * as THREE5 from "three";
1661
+ import * as THREE6 from "three";
1653
1662
  import { OrbitControls } from "three/addons/controls/OrbitControls.js";
1654
- var KEY_DIRECTION = new THREE5.Vector3(-0.55, 1, 0.35).normalize();
1663
+
1664
+ // src/picker.ts
1665
+ import * as THREE5 from "three";
1666
+ var CODE_BITS = 8;
1667
+ var CODE_MASK = 255;
1668
+ var VERTEX = `
1669
+ #include <common>
1670
+ #include <skinning_pars_vertex>
1671
+ attribute vec3 pickCode;
1672
+ uniform vec3 objectCode;
1673
+ uniform bool perVertex;
1674
+ varying vec3 vCode;
1675
+ void main() {
1676
+ vCode = perVertex ? pickCode : objectCode;
1677
+ #include <skinbase_vertex>
1678
+ #include <begin_vertex>
1679
+ #include <skinning_vertex>
1680
+ #include <project_vertex>
1681
+ }
1682
+ `;
1683
+ var FRAGMENT = `
1684
+ varying vec3 vCode;
1685
+ void main() {
1686
+ gl_FragColor = vec4(vCode, 1.0);
1687
+ }
1688
+ `;
1689
+ function encode(code) {
1690
+ return [code & CODE_MASK, code >> CODE_BITS];
1691
+ }
1692
+
1693
+ class Picker {
1694
+ target = new THREE5.WebGLRenderTarget(1, 1);
1695
+ pixel = new Uint8Array(4);
1696
+ codes = new Map;
1697
+ nodes = [];
1698
+ clearColor = new THREE5.Color;
1699
+ material = new THREE5.ShaderMaterial({
1700
+ vertexShader: VERTEX,
1701
+ fragmentShader: FRAGMENT,
1702
+ uniforms: { objectCode: { value: new THREE5.Vector3 }, perVertex: { value: false } }
1703
+ });
1704
+ constructor() {
1705
+ this.material.onBeforeRender = (_renderer, _scene, _camera, geometry, object) => {
1706
+ const perVertex = geometry.hasAttribute("pickCode");
1707
+ const [low, high] = encode(perVertex ? 0 : this.codeOf(object));
1708
+ this.material.uniforms.perVertex.value = perVertex;
1709
+ this.material.uniforms.objectCode.value.set(low / CODE_MASK, high / CODE_MASK, 0);
1710
+ this.material.uniformsNeedUpdate = true;
1711
+ };
1712
+ }
1713
+ pick(renderer, scene, root, camera, x, y, width, height) {
1714
+ this.prepare(root);
1715
+ const hidden = scene.children.filter((child) => child !== root && child.visible && child.isMesh);
1716
+ const previous = { target: renderer.getRenderTarget(), alpha: renderer.getClearAlpha(), shadows: renderer.shadowMap.autoUpdate };
1717
+ renderer.getClearColor(this.clearColor);
1718
+ for (const child of hidden)
1719
+ child.visible = false;
1720
+ scene.overrideMaterial = this.material;
1721
+ renderer.shadowMap.autoUpdate = false;
1722
+ const view = camera.view && { ...camera.view };
1723
+ camera.setViewOffset(view?.fullWidth ?? width, view?.fullHeight ?? height, x + (view?.offsetX ?? 0), y + (view?.offsetY ?? 0), 1, 1);
1724
+ renderer.setRenderTarget(this.target);
1725
+ renderer.setClearColor(0, 0);
1726
+ renderer.clear();
1727
+ renderer.render(scene, camera);
1728
+ renderer.readRenderTargetPixels(this.target, 0, 0, 1, 1, this.pixel);
1729
+ renderer.setRenderTarget(previous.target);
1730
+ renderer.setClearColor(this.clearColor, previous.alpha);
1731
+ renderer.shadowMap.autoUpdate = previous.shadows;
1732
+ if (view)
1733
+ camera.setViewOffset(view.fullWidth, view.fullHeight, view.offsetX, view.offsetY, view.width, view.height);
1734
+ else
1735
+ camera.clearViewOffset();
1736
+ scene.overrideMaterial = null;
1737
+ for (const child of hidden)
1738
+ child.visible = true;
1739
+ const code = this.pixel[0] + (this.pixel[1] << CODE_BITS);
1740
+ return this.nodes[code - 1] ?? null;
1741
+ }
1742
+ async warm(renderer, root, camera, scene) {
1743
+ this.prepare(root);
1744
+ const meshes = [];
1745
+ root.traverse((object) => {
1746
+ const mesh = object;
1747
+ if (mesh.isMesh)
1748
+ meshes.push([mesh, mesh.material]);
1749
+ });
1750
+ for (const [mesh] of meshes)
1751
+ mesh.material = this.material;
1752
+ const compiled = renderer.compileAsync(root, camera, scene);
1753
+ for (const [mesh, material] of meshes)
1754
+ mesh.material = material;
1755
+ await compiled;
1756
+ }
1757
+ dispose() {
1758
+ this.target.dispose();
1759
+ this.material.dispose();
1760
+ }
1761
+ prepare(root) {
1762
+ root.traverse((object) => {
1763
+ const mesh = object;
1764
+ if (!mesh.isSkinnedMesh || mesh.geometry.hasAttribute("pickCode"))
1765
+ return;
1766
+ const indices = mesh.geometry.getAttribute("skinIndex");
1767
+ const weights = mesh.geometry.getAttribute("skinWeight");
1768
+ const boneCodes = mesh.skeleton.bones.map((bone) => encode(this.codeOf(bone)));
1769
+ const meshCode = encode(this.codeOf(mesh));
1770
+ const codes = new Uint8Array(indices.count * 3);
1771
+ const influences = weights.itemSize;
1772
+ const read = (attribute, vertex, influence) => attribute instanceof THREE5.BufferAttribute ? attribute.array[vertex * influences + influence] : attribute.getComponent(vertex, influence);
1773
+ for (let vertex = 0;vertex < indices.count; vertex++) {
1774
+ let heaviest = 0;
1775
+ for (let influence = 1;influence < influences; influence++) {
1776
+ if (read(weights, vertex, influence) > read(weights, vertex, heaviest))
1777
+ heaviest = influence;
1778
+ }
1779
+ const [low, high] = boneCodes[read(indices, vertex, heaviest)] ?? meshCode;
1780
+ codes[vertex * 3] = low;
1781
+ codes[vertex * 3 + 1] = high;
1782
+ }
1783
+ mesh.geometry.setAttribute("pickCode", new THREE5.BufferAttribute(codes, 3, true));
1784
+ });
1785
+ }
1786
+ codeOf(node) {
1787
+ let code = this.codes.get(node);
1788
+ if (code === undefined) {
1789
+ this.nodes.push(node);
1790
+ code = this.nodes.length;
1791
+ this.codes.set(node, code);
1792
+ }
1793
+ return code;
1794
+ }
1795
+ }
1796
+
1797
+ // src/stage.ts
1798
+ var KEY_DIRECTION = new THREE6.Vector3(-0.55, 1, 0.35).normalize();
1655
1799
  var AUTO_ROTATE_SPEED = 0.8;
1656
1800
  var STAGE_MARGIN = 1.12;
1657
1801
  var TURN_SAMPLES = 24;
1802
+ var VIEW_DURATION = 900;
1803
+ var LIGHTING_DURATION = 1200;
1804
+ var ENTRANCE_DURATION = 1800;
1805
+ var ENTRANCE_TURN = 0.7;
1806
+ var ENTRANCE_DROP = 0.2;
1807
+ var ENTRANCE_PULL = 1.5;
1808
+ var LIGHTINGS = {
1809
+ studio: { environment: 1.15, key: 1.9, keyColor: new THREE6.Color(16774118), fill: 0.7, exposure: 0.7, shadow: 0.25 },
1810
+ night: { environment: 0.08, key: 0.55, keyColor: new THREE6.Color(9414911), fill: 0.12, exposure: 1, shadow: 0.12 }
1811
+ };
1658
1812
  var SOFT_BOXES = [
1659
1813
  [0.1, [30, 0.1, 30], [0, -1.3, 0]],
1660
1814
  [5, [3.2, 0.1, 15], [-6.5, 6, 0]],
@@ -1663,12 +1817,17 @@ var SOFT_BOXES = [
1663
1817
  [2.2, [0.1, 2.2, 18], [-12, 0.6, 0]],
1664
1818
  [2.2, [0.1, 2.2, 18], [12, 0.6, 0]]
1665
1819
  ];
1820
+ var mix = (from, to, amount) => from + (to - from) * amount;
1821
+ var easeInOutCubic = (t) => t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;
1822
+ var easeOutQuint = (t) => 1 - (1 - t) ** 5;
1823
+ var smoothstep = (t) => t * t * (3 - 2 * t);
1824
+ var shortestTurn = (angle) => Math.atan2(Math.sin(angle), Math.cos(angle));
1666
1825
  function studio() {
1667
- const scene = new THREE5.Scene;
1668
- scene.background = new THREE5.Color(0.16, 0.16, 0.16);
1669
- const geometry = new THREE5.BoxGeometry;
1826
+ const scene = new THREE6.Scene;
1827
+ scene.background = new THREE6.Color(0.16, 0.16, 0.16);
1828
+ const geometry = new THREE6.BoxGeometry;
1670
1829
  for (const [brightness, size, position] of SOFT_BOXES) {
1671
- const box = new THREE5.Mesh(geometry, new THREE5.MeshBasicMaterial({ color: new THREE5.Color(brightness, brightness, brightness) }));
1830
+ const box = new THREE6.Mesh(geometry, new THREE6.MeshBasicMaterial({ color: new THREE6.Color(brightness, brightness, brightness) }));
1672
1831
  box.scale.fromArray(size);
1673
1832
  box.position.fromArray(position);
1674
1833
  scene.add(box);
@@ -1677,22 +1836,34 @@ function studio() {
1677
1836
  }
1678
1837
 
1679
1838
  class Lighting {
1680
- key = new THREE5.DirectionalLight(16774118, 1.9);
1839
+ renderer;
1840
+ scene;
1841
+ key = new THREE6.DirectionalLight;
1842
+ fill = new THREE6.DirectionalLight(14674431);
1681
1843
  environment;
1682
1844
  constructor(renderer, scene, camera) {
1683
- renderer.toneMapping = THREE5.ACESFilmicToneMapping;
1684
- renderer.toneMappingExposure = 0.7;
1845
+ this.renderer = renderer;
1846
+ this.scene = scene;
1847
+ renderer.toneMapping = THREE6.ACESFilmicToneMapping;
1685
1848
  renderer.shadowMap.enabled = true;
1686
- const pmrem = new THREE5.PMREMGenerator(renderer);
1849
+ const pmrem = new THREE6.PMREMGenerator(renderer);
1687
1850
  this.environment = pmrem.fromScene(studio(), 0.008, 0.1, 80, { size: 512 });
1688
1851
  pmrem.dispose();
1689
1852
  scene.environment = this.environment.texture;
1690
- scene.environmentIntensity = 1.15;
1691
1853
  this.key.castShadow = true;
1692
1854
  this.key.shadow.mapSize.setScalar(2048);
1693
1855
  this.key.shadow.radius = 6;
1694
- camera.add(new THREE5.DirectionalLight(14674431, 0.7));
1856
+ camera.add(this.fill);
1695
1857
  scene.add(this.key, camera);
1858
+ this.blend(0);
1859
+ }
1860
+ blend(night) {
1861
+ const { studio: day, night: dark } = LIGHTINGS;
1862
+ this.renderer.toneMappingExposure = mix(day.exposure, dark.exposure, night);
1863
+ this.scene.environmentIntensity = mix(day.environment, dark.environment, night);
1864
+ this.key.intensity = mix(day.key, dark.key, night);
1865
+ this.key.color.lerpColors(day.keyColor, dark.keyColor, night);
1866
+ this.fill.intensity = mix(day.fill, dark.fill, night);
1696
1867
  }
1697
1868
  fit(radius) {
1698
1869
  this.key.position.copy(KEY_DIRECTION).multiplyScalar(radius * 3);
@@ -1703,30 +1874,40 @@ class Lighting {
1703
1874
  dispose() {
1704
1875
  this.environment.dispose();
1705
1876
  this.key.dispose();
1877
+ this.fill.dispose();
1706
1878
  }
1707
1879
  }
1708
1880
 
1709
1881
  class Stage {
1710
1882
  canvas;
1711
1883
  renderer;
1712
- scene = new THREE5.Scene;
1713
- camera = new THREE5.PerspectiveCamera(30, 1, 0.05, 300);
1884
+ scene = new THREE6.Scene;
1885
+ camera = new THREE6.PerspectiveCamera(30, 1, 0.05, 300);
1714
1886
  controls;
1715
1887
  lighting;
1716
- ground = new THREE5.Mesh(new THREE5.PlaneGeometry(4, 4), new THREE5.ShadowMaterial({ opacity: 0.25 }));
1888
+ ground = new THREE6.Mesh(new THREE6.PlaneGeometry(4, 4), new THREE6.ShadowMaterial({ opacity: LIGHTINGS.studio.shadow }));
1717
1889
  resizer;
1718
1890
  watcher;
1891
+ entrance;
1892
+ inset;
1719
1893
  subject = null;
1894
+ picker = null;
1895
+ size = new THREE6.Vector3;
1720
1896
  showing = 0;
1721
1897
  visible = true;
1898
+ night = 0;
1899
+ flight = null;
1900
+ fade = null;
1722
1901
  constructor(canvas, options = {}) {
1723
1902
  this.canvas = canvas;
1724
- this.renderer = new THREE5.WebGLRenderer({ canvas, antialias: true, alpha: true });
1903
+ this.renderer = new THREE6.WebGLRenderer({ canvas, antialias: true, alpha: true });
1725
1904
  this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
1726
1905
  this.lighting = new Lighting(this.renderer, this.scene, this.camera);
1727
1906
  this.ground.rotation.x = -Math.PI / 2;
1728
1907
  this.ground.receiveShadow = true;
1729
1908
  this.scene.add(this.ground);
1909
+ this.entrance = options.entrance ?? false;
1910
+ this.inset = { top: options.inset?.top ?? 0, bottom: options.inset?.bottom ?? 0 };
1730
1911
  this.controls = new OrbitControls(this.camera, canvas);
1731
1912
  this.controls.enableDamping = true;
1732
1913
  this.controls.maxPolarAngle = Math.PI / 2 - 0.02;
@@ -1735,7 +1916,7 @@ class Stage {
1735
1916
  if (!this.controls.enableZoom)
1736
1917
  canvas.style.touchAction = "pan-y";
1737
1918
  this.controls.autoRotateSpeed = AUTO_ROTATE_SPEED;
1738
- this.controls.addEventListener("start", this.stopRotating);
1919
+ this.controls.addEventListener("start", this.yieldToUser);
1739
1920
  this.watcher = new IntersectionObserver(([entry]) => {
1740
1921
  this.visible = entry.isIntersecting;
1741
1922
  });
@@ -1743,9 +1924,10 @@ class Stage {
1743
1924
  this.resizer = new ResizeObserver(() => this.resize());
1744
1925
  this.resizer.observe(canvas);
1745
1926
  this.resize();
1746
- this.renderer.setAnimationLoop(() => {
1927
+ this.renderer.setAnimationLoop((time) => {
1747
1928
  if (!this.visible || canvas.clientWidth === 0)
1748
1929
  return;
1930
+ this.advance(time);
1749
1931
  this.controls.update();
1750
1932
  this.renderer.render(this.scene, this.camera);
1751
1933
  });
@@ -1756,44 +1938,131 @@ class Stage {
1756
1938
  this.scene.remove(this.subject.root);
1757
1939
  this.subject.dispose();
1758
1940
  this.subject = null;
1941
+ this.picker?.dispose();
1942
+ this.picker = null;
1759
1943
  assets.clear();
1760
1944
  }
1761
1945
  const subject = await assets.load(name, props);
1946
+ const picker = new Picker;
1947
+ if (showing === this.showing) {
1948
+ await Promise.all([
1949
+ this.renderer.compileAsync(subject.root, this.camera, this.scene),
1950
+ this.renderer.compileAsync(this.scene, this.camera),
1951
+ picker.warm(this.renderer, subject.root, this.camera, this.scene)
1952
+ ]);
1953
+ }
1762
1954
  if (showing !== this.showing) {
1763
1955
  subject.dispose();
1956
+ picker.dispose();
1764
1957
  return;
1765
1958
  }
1766
1959
  this.subject = subject;
1960
+ this.picker = picker;
1767
1961
  this.frame(subject);
1962
+ if (this.entrance)
1963
+ this.enter();
1964
+ this.renderer.render(this.scene, this.camera);
1768
1965
  return subject;
1769
1966
  }
1967
+ view(direction, { duration = VIEW_DURATION } = {}) {
1968
+ if (!this.subject)
1969
+ return Promise.resolve(false);
1970
+ this.controls.autoRotate = false;
1971
+ return this.fly(this.offset(direction ?? this.subject.view), duration, easeInOutCubic);
1972
+ }
1973
+ setAutoRotate(on) {
1974
+ this.controls.autoRotate = on;
1975
+ }
1976
+ setLighting(lighting, { duration = LIGHTING_DURATION } = {}) {
1977
+ this.fade = { from: this.night, to: lighting === "night" ? 1 : 0, start: performance.now(), duration: Math.max(duration, 1) };
1978
+ }
1979
+ pick(clientX, clientY) {
1980
+ if (!this.subject || !this.picker)
1981
+ return null;
1982
+ const bounds = this.canvas.getBoundingClientRect();
1983
+ return this.picker.pick(this.renderer, this.scene, this.subject.root, this.camera, clientX - bounds.left, clientY - bounds.top, bounds.width, bounds.height);
1984
+ }
1985
+ photo(width, height) {
1986
+ const ratio = this.renderer.getPixelRatio();
1987
+ this.renderer.setPixelRatio(1);
1988
+ this.renderer.setSize(width, height, false);
1989
+ this.camera.aspect = width / height;
1990
+ this.camera.clearViewOffset();
1991
+ this.renderer.render(this.scene, this.camera);
1992
+ const photo = new Promise((resolve, reject) => this.canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("Could not encode the photo")), "image/png"));
1993
+ this.renderer.setPixelRatio(ratio);
1994
+ this.resize();
1995
+ this.renderer.render(this.scene, this.camera);
1996
+ return photo;
1997
+ }
1770
1998
  dispose() {
1771
1999
  this.showing++;
2000
+ this.flight?.done(false);
1772
2001
  this.subject?.dispose();
2002
+ this.picker?.dispose();
1773
2003
  this.resizer.disconnect();
1774
2004
  this.watcher.disconnect();
1775
2005
  this.renderer.setAnimationLoop(null);
1776
- this.controls.removeEventListener("start", this.stopRotating);
2006
+ this.controls.removeEventListener("start", this.yieldToUser);
1777
2007
  this.controls.dispose();
1778
2008
  this.lighting.dispose();
1779
2009
  this.renderer.dispose();
1780
2010
  this.renderer.forceContextLoss();
1781
2011
  }
1782
- stopRotating = () => {
2012
+ yieldToUser = () => {
1783
2013
  this.controls.autoRotate = false;
2014
+ this.flight?.done(false);
2015
+ this.flight = null;
1784
2016
  };
1785
- frame(subject) {
1786
- const size = subject.placeAtOrigin().getSize(new THREE5.Vector3);
1787
- this.scene.add(subject.root);
1788
- const slopeY = Math.tan(THREE5.MathUtils.degToRad(this.camera.fov / 2));
2017
+ advance(now) {
2018
+ const { flight, fade } = this;
2019
+ if (flight) {
2020
+ const progress = THREE6.MathUtils.clamp((now - flight.start) / flight.duration, 0, 1);
2021
+ const eased = flight.ease(progress);
2022
+ const { from, to } = flight;
2023
+ this.camera.position.setFromSphericalCoords(mix(from.radius, to.radius, eased), mix(from.phi, to.phi, eased), mix(from.theta, to.theta, eased)).add(this.controls.target);
2024
+ if (progress === 1) {
2025
+ this.flight = null;
2026
+ flight.done(true);
2027
+ }
2028
+ }
2029
+ if (fade) {
2030
+ const progress = THREE6.MathUtils.clamp((now - fade.start) / fade.duration, 0, 1);
2031
+ this.night = mix(fade.from, fade.to, smoothstep(progress));
2032
+ this.lighting.blend(this.night);
2033
+ this.ground.material.opacity = mix(LIGHTINGS.studio.shadow, LIGHTINGS.night.shadow, this.night);
2034
+ if (progress === 1)
2035
+ this.fade = null;
2036
+ }
2037
+ }
2038
+ fly(offset, duration, ease) {
2039
+ this.flight?.done(false);
2040
+ const from = new THREE6.Spherical().setFromVector3(this.camera.position.clone().sub(this.controls.target));
2041
+ const to = new THREE6.Spherical().setFromVector3(offset);
2042
+ to.theta = from.theta + shortestTurn(to.theta - from.theta);
2043
+ return new Promise((done) => {
2044
+ this.flight = { from, to, start: performance.now(), duration: Math.max(duration, 1), ease, done };
2045
+ });
2046
+ }
2047
+ enter() {
2048
+ const hero = this.camera.position.clone().sub(this.controls.target);
2049
+ const start = new THREE6.Spherical().setFromVector3(hero);
2050
+ start.theta += ENTRANCE_TURN;
2051
+ start.phi = Math.min(start.phi + ENTRANCE_DROP, this.controls.maxPolarAngle);
2052
+ start.radius *= ENTRANCE_PULL;
2053
+ this.camera.position.setFromSpherical(start).add(this.controls.target);
2054
+ this.controls.update();
2055
+ this.fly(hero, ENTRANCE_DURATION, easeOutQuint);
2056
+ }
2057
+ offset(direction) {
2058
+ const { size } = this;
2059
+ const slopeY = Math.tan(THREE6.MathUtils.degToRad(this.camera.fov / 2));
1789
2060
  const slopeX = slopeY * this.camera.aspect;
1790
- const radius = size.length() / 2;
1791
2061
  const reach = Math.hypot(size.x, size.z) / 2;
1792
- const target = new THREE5.Vector3(0, size.y / 2, 0);
1793
- const toCamera = new THREE5.Vector3(...subject.view).normalize();
1794
- const right = new THREE5.Vector3().crossVectors(new THREE5.Vector3(0, 1, 0), toCamera).normalize();
1795
- const up = new THREE5.Vector3().crossVectors(toCamera, right);
1796
- const point = new THREE5.Vector3;
2062
+ const toCamera = new THREE6.Vector3(...direction).normalize();
2063
+ const right = new THREE6.Vector3().crossVectors(new THREE6.Vector3(0, 1, 0), toCamera).normalize();
2064
+ const up = new THREE6.Vector3().crossVectors(toCamera, right);
2065
+ const point = new THREE6.Vector3;
1797
2066
  let distance = 0;
1798
2067
  for (let turn = 0;turn < TURN_SAMPLES; turn++) {
1799
2068
  const angle = turn / TURN_SAMPLES * Math.PI * 2;
@@ -1803,22 +2072,34 @@ class Stage {
1803
2072
  distance = Math.max(distance, depth + Math.abs(point.dot(right)) * STAGE_MARGIN / slopeX, depth + Math.abs(point.dot(up)) * STAGE_MARGIN / slopeY);
1804
2073
  }
1805
2074
  }
2075
+ return toCamera.multiplyScalar(distance);
2076
+ }
2077
+ frame(subject) {
2078
+ this.size = subject.placeAtOrigin().getSize(new THREE6.Vector3);
2079
+ this.scene.add(subject.root);
2080
+ const radius = this.size.length() / 2;
2081
+ const target = new THREE6.Vector3(0, this.size.y / 2, 0);
1806
2082
  this.lighting.fit(radius);
1807
2083
  this.ground.scale.setScalar(radius);
1808
2084
  Object.assign(this.camera, { near: radius * 0.02, far: radius * 20 }).updateProjectionMatrix();
1809
2085
  this.controls.target.copy(target);
1810
2086
  this.controls.minDistance = radius * 0.2;
1811
2087
  this.controls.maxDistance = radius * 8;
1812
- this.camera.position.copy(target).addScaledVector(toCamera, distance);
2088
+ this.camera.position.copy(target).add(this.offset(subject.view));
1813
2089
  this.controls.update();
1814
2090
  }
1815
2091
  resize() {
1816
2092
  const { clientWidth: width, clientHeight: height } = this.canvas;
1817
2093
  if (width === 0 || height === 0)
1818
2094
  return;
2095
+ const { top, bottom } = this.inset;
2096
+ const framed = Math.max(height - top - bottom, 1);
1819
2097
  this.renderer.setSize(width, height, false);
1820
- this.camera.aspect = width / height;
1821
- this.camera.updateProjectionMatrix();
2098
+ this.camera.aspect = width / framed;
2099
+ if (top || bottom)
2100
+ this.camera.setViewOffset(width, framed, 0, -top, width, height);
2101
+ else
2102
+ this.camera.updateProjectionMatrix();
1822
2103
  }
1823
2104
  }
1824
2105
  var FIELD_OF_VIEW = 20;
@@ -1831,14 +2112,14 @@ class ThumbnailRenderer {
1831
2112
  size;
1832
2113
  format;
1833
2114
  renderer;
1834
- scene = new THREE5.Scene;
1835
- camera = new THREE5.PerspectiveCamera(FIELD_OF_VIEW, 1);
2115
+ scene = new THREE6.Scene;
2116
+ camera = new THREE6.PerspectiveCamera(FIELD_OF_VIEW, 1);
1836
2117
  lighting;
1837
2118
  pixels;
1838
2119
  constructor(size = 512, format = "png") {
1839
2120
  this.size = size;
1840
2121
  this.format = format;
1841
- this.renderer = new THREE5.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
2122
+ this.renderer = new THREE6.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
1842
2123
  this.renderer.setSize(size, size, false);
1843
2124
  this.renderer.setClearColor(0, 0);
1844
2125
  this.lighting = new Lighting(this.renderer, this.scene, this.camera);
@@ -1846,15 +2127,15 @@ class ThumbnailRenderer {
1846
2127
  }
1847
2128
  async render(model, view = model.view) {
1848
2129
  const box = model.placeAtOrigin();
1849
- const center = box.getCenter(new THREE5.Vector3);
1850
- const radius = box.getSize(new THREE5.Vector3).length() / 2;
1851
- const toCamera = new THREE5.Vector3(...view).normalize();
1852
- const right = new THREE5.Vector3().crossVectors(new THREE5.Vector3(0, 1, 0), toCamera).normalize();
1853
- const up = new THREE5.Vector3().crossVectors(toCamera, right);
1854
- const slope = Math.tan(THREE5.MathUtils.degToRad(FIELD_OF_VIEW / 2));
2130
+ const center = box.getCenter(new THREE6.Vector3);
2131
+ const radius = box.getSize(new THREE6.Vector3).length() / 2;
2132
+ const toCamera = new THREE6.Vector3(...view).normalize();
2133
+ const right = new THREE6.Vector3().crossVectors(new THREE6.Vector3(0, 1, 0), toCamera).normalize();
2134
+ const up = new THREE6.Vector3().crossVectors(toCamera, right);
2135
+ const slope = Math.tan(THREE6.MathUtils.degToRad(FIELD_OF_VIEW / 2));
1855
2136
  let distance = 0;
1856
2137
  for (let corner = 0;corner < 8; corner++) {
1857
- const point = new THREE5.Vector3(corner & 1 ? box.max.x : box.min.x, corner & 2 ? box.max.y : box.min.y, corner & 4 ? box.max.z : box.min.z).sub(center);
2138
+ const point = new THREE6.Vector3(corner & 1 ? box.max.x : box.min.x, corner & 2 ? box.max.y : box.min.y, corner & 4 ? box.max.z : box.min.z).sub(center);
1858
2139
  const extent = Math.max(Math.abs(point.dot(right)), Math.abs(point.dot(up))) * MARGIN;
1859
2140
  distance = Math.max(distance, point.dot(toCamera) + extent / slope);
1860
2141
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "katachi-runtime",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Show converted GTA V models in the browser with three.js.",
5
5
  "type": "module",
6
6
  "exports": {
package/picker.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import * as THREE from "three";
2
+ export declare class Picker {
3
+ private readonly target;
4
+ private readonly pixel;
5
+ private readonly codes;
6
+ private readonly nodes;
7
+ private readonly clearColor;
8
+ private readonly material;
9
+ constructor();
10
+ pick(renderer: THREE.WebGLRenderer, scene: THREE.Scene, root: THREE.Object3D, camera: THREE.PerspectiveCamera, x: number, y: number, width: number, height: number): THREE.Object3D | null;
11
+ warm(renderer: THREE.WebGLRenderer, root: THREE.Object3D, camera: THREE.Camera, scene: THREE.Scene): Promise<void>;
12
+ dispose(): void;
13
+ private prepare;
14
+ private codeOf;
15
+ }
package/stage.d.ts CHANGED
@@ -1,9 +1,18 @@
1
+ import * as THREE from "three";
1
2
  import type { Assets } from "./assets";
2
3
  import type { Model } from "./model";
3
4
  import type { VehicleProps } from "./vehicle";
5
+ export type Direction = readonly [number, number, number];
6
+ export type StageLighting = "studio" | "night";
7
+ export interface StageInset {
8
+ top?: number;
9
+ bottom?: number;
10
+ }
4
11
  export interface StageOptions {
5
12
  autoRotate?: boolean;
6
13
  zoom?: boolean;
14
+ entrance?: boolean;
15
+ inset?: StageInset;
7
16
  }
8
17
  /** An interactive 3D view of one model, drawn on a canvas. Drag to orbit, scroll to zoom. */
9
18
  export declare class Stage {
@@ -16,15 +25,35 @@ export declare class Stage {
16
25
  private readonly ground;
17
26
  private readonly resizer;
18
27
  private readonly watcher;
28
+ private readonly entrance;
29
+ private readonly inset;
19
30
  private subject;
31
+ private picker;
32
+ private size;
20
33
  private showing;
21
34
  private visible;
35
+ private night;
36
+ private flight;
37
+ private fade;
22
38
  constructor(canvas: HTMLCanvasElement, options?: StageOptions);
23
39
  /** Loads a model and shows it in place of the current one. Resolves to `undefined` if another model was shown meanwhile. */
24
40
  show(assets: Assets, name: string, props?: VehicleProps): Promise<Model | undefined>;
41
+ view(direction?: Direction, { duration }?: {
42
+ duration?: number;
43
+ }): Promise<boolean>;
44
+ setAutoRotate(on: boolean): void;
45
+ setLighting(lighting: StageLighting, { duration }?: {
46
+ duration?: number;
47
+ }): void;
48
+ pick(clientX: number, clientY: number): THREE.Object3D | null;
49
+ photo(width: number, height: number): Promise<Blob>;
25
50
  /** Frees the renderer and the model on show. */
26
51
  dispose(): void;
27
- private readonly stopRotating;
52
+ private readonly yieldToUser;
53
+ private advance;
54
+ private fly;
55
+ private enter;
56
+ private offset;
28
57
  private frame;
29
58
  private resize;
30
59
  }
package/vehicle.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import * as THREE from "three";
1
2
  import type { ModEntry, VehicleEntry, WheelEntry } from "./assets";
2
3
  import type { ModelLoader } from "./loader";
3
4
  import { Model } from "./model";
@@ -64,6 +65,12 @@ export declare class Vehicle extends Model {
64
65
  private readonly wheelTypes;
65
66
  private readonly paints;
66
67
  private readonly loader;
68
+ static readonly views: {
69
+ readonly front: readonly [0, 0.12, -1];
70
+ readonly side: readonly [-1, 0.1, 0];
71
+ readonly rear: readonly [0, 0.16, 1];
72
+ readonly top: readonly [0, 1, 0.04];
73
+ };
67
74
  readonly view: readonly [-0.6, 0.25, -0.75];
68
75
  private readonly rest;
69
76
  private readonly hidden;
@@ -89,6 +96,7 @@ export declare class Vehicle extends Model {
89
96
  openings(): Opening[];
90
97
  /** Opens a door or panel, from 0 (closed) to 1 (fully open). */
91
98
  setOpen(name: Opening, amount: number): void;
99
+ openingOf(node: THREE.Object3D): Opening | null;
92
100
  /** Lists this vehicle's extra IDs. */
93
101
  extras(): number[];
94
102
  /** Returns whether an extra is shown. */