code stringlengths 0 56.1M | repo_name stringlengths 3 57 | path stringlengths 2 176 | language stringclasses 672 values | license stringclasses 8 values | size int64 0 56.8M |
|---|---|---|---|---|---|
export * from "./context";
| cchudzicki/mathbox | src/node.js | JavaScript | mit | 27 |
import { Traits as TraitsValue } from "./primitives/types/traits";
type Traits = typeof TraitsValue;
interface GetTraitsNode {
id: ReturnType<Traits["node"]["id"]["validate"]>;
classes: ReturnType<Traits["node"]["classes"]["validate"]>;
}
interface SetTraitsNode {
/**
* Unique ID
* @default `null`
* @example `"sampler"`
*/
id: Parameters<Traits["node"]["id"]["validate"]>[0];
/**
* Custom classes
* @default `[]`
* @example `["big"]`
*/
classes: Parameters<Traits["node"]["classes"]["validate"]>[0];
}
interface GetTraitsEntity {
active: ReturnType<Traits["entity"]["active"]["validate"]>;
}
interface SetTraitsEntity {
/**
* Updates continuously
* @default `true`
*/
active: Parameters<Traits["entity"]["active"]["validate"]>[0];
}
interface GetTraitsObject {
visible: ReturnType<Traits["object"]["visible"]["validate"]>;
}
interface SetTraitsObject {
/**
* Visibility for rendering
* @default `true`
*/
visible: Parameters<Traits["object"]["visible"]["validate"]>[0];
}
interface GetTraitsUnit {
scale: ReturnType<Traits["unit"]["scale"]["validate"]>;
fov: ReturnType<Traits["unit"]["fov"]["validate"]>;
focus: ReturnType<Traits["unit"]["focus"]["validate"]>;
}
interface SetTraitsUnit {
/**
* (Vertical) Reference scale of viewport in pixels
* @default `null`
* @example `720`
*/
scale: Parameters<Traits["unit"]["scale"]["validate"]>[0];
/**
* (Vertical) Field-of-view to calibrate units for (degrees)
* @default `null`
* @example `60`
*/
fov: Parameters<Traits["unit"]["fov"]["validate"]>[0];
/**
* Camera focus distance in world units
* @default `1`
*/
focus: Parameters<Traits["unit"]["focus"]["validate"]>[0];
}
interface GetTraitsSpan {
range: ReturnType<Traits["span"]["range"]["validate"]>;
}
interface SetTraitsSpan {
/**
* Range on axis
* @default `[-1, 1]`
*/
range: Parameters<Traits["span"]["range"]["validate"]>[0];
}
interface GetTraitsView {
range: ReturnType<Traits["view"]["range"]["validate"]>;
}
interface SetTraitsView {
/**
* 4D range in view
* @default `[[-1, 1], [-1, 1], [-1, 1], [-1, 1]]`
*/
range: Parameters<Traits["view"]["range"]["validate"]>[0];
}
interface GetTraitsView3 {
position: ReturnType<Traits["view3"]["position"]["validate"]>;
quaternion: ReturnType<Traits["view3"]["quaternion"]["validate"]>;
rotation: ReturnType<Traits["view3"]["rotation"]["validate"]>;
scale: ReturnType<Traits["view3"]["scale"]["validate"]>;
eulerOrder: ReturnType<Traits["view3"]["eulerOrder"]["validate"]>;
}
interface SetTraitsView3 {
/**
* 3D Position
* @default `[0, 0, 0]`
*/
position: Parameters<Traits["view3"]["position"]["validate"]>[0];
/**
* 3D Quaternion
* @default `[0, 0, 0, 1]`
*/
quaternion: Parameters<Traits["view3"]["quaternion"]["validate"]>[0];
/**
* 3D Euler rotation
* @default `[0, 0, 0]`
*/
rotation: Parameters<Traits["view3"]["rotation"]["validate"]>[0];
/**
* 3D Scale
* @default `[1, 1, 1]`
*/
scale: Parameters<Traits["view3"]["scale"]["validate"]>[0];
/**
* Euler order
* @default `xyz`
*/
eulerOrder: Parameters<Traits["view3"]["eulerOrder"]["validate"]>[0];
}
interface GetTraitsView4 {
position: ReturnType<Traits["view4"]["position"]["validate"]>;
scale: ReturnType<Traits["view4"]["scale"]["validate"]>;
}
interface SetTraitsView4 {
/**
* 4D Position
* @default `[0, 0, 0, 0]`
*/
position: Parameters<Traits["view4"]["position"]["validate"]>[0];
/**
* 4D Scale
* @default `[1, 1, 1, 1]`
*/
scale: Parameters<Traits["view4"]["scale"]["validate"]>[0];
}
interface GetTraitsLayer {
depth: ReturnType<Traits["layer"]["depth"]["validate"]>;
fit: ReturnType<Traits["layer"]["fit"]["validate"]>;
}
interface SetTraitsLayer {
/**
* 3D Depth
* @default `1`
*/
depth: Parameters<Traits["layer"]["depth"]["validate"]>[0];
/**
* Fit to (contain, cover, x, y)
* @default `y`
*/
fit: Parameters<Traits["layer"]["fit"]["validate"]>[0];
}
interface GetTraitsVertex {
pass: ReturnType<Traits["vertex"]["pass"]["validate"]>;
}
interface SetTraitsVertex {
/**
* Vertex pass (data, view, world, eye)
* @default `"view"`
*/
pass: Parameters<Traits["vertex"]["pass"]["validate"]>[0];
}
interface GetTraitsFragment {
pass: ReturnType<Traits["fragment"]["pass"]["validate"]>;
gamma: ReturnType<Traits["fragment"]["gamma"]["validate"]>;
}
interface SetTraitsFragment {
/**
* Fragment pass (color, light, rgba)
* @default `"light"`
*/
pass: Parameters<Traits["fragment"]["pass"]["validate"]>[0];
/**
* Pass RGBA values in sRGB instead of linear RGB
* @default `false`
*/
gamma: Parameters<Traits["fragment"]["gamma"]["validate"]>[0];
}
interface GetTraitsTransform3 {
position: ReturnType<Traits["transform3"]["position"]["validate"]>;
quaternion: ReturnType<Traits["transform3"]["quaternion"]["validate"]>;
rotation: ReturnType<Traits["transform3"]["rotation"]["validate"]>;
eulerOrder: ReturnType<Traits["transform3"]["eulerOrder"]["validate"]>;
scale: ReturnType<Traits["transform3"]["scale"]["validate"]>;
matrix: ReturnType<Traits["transform3"]["matrix"]["validate"]>;
}
interface SetTraitsTransform3 {
/**
* 3D Position
* @default `[0, 0, 0]`
*/
position: Parameters<Traits["transform3"]["position"]["validate"]>[0];
/**
* 3D Quaternion
* @default `[0, 0, 0, 1]`
*/
quaternion: Parameters<Traits["transform3"]["quaternion"]["validate"]>[0];
/**
* 3D Euler rotation
* @default `[0, 0, 0]`
*/
rotation: Parameters<Traits["transform3"]["rotation"]["validate"]>[0];
/**
* 3D Euler order
* @default `xyz`
*/
eulerOrder: Parameters<Traits["transform3"]["eulerOrder"]["validate"]>[0];
/**
* 3D Scale
* @default `[1, 1, 1]`
*/
scale: Parameters<Traits["transform3"]["scale"]["validate"]>[0];
/**
* 3D Projective Matrix
* @default `[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]`
*/
matrix: Parameters<Traits["transform3"]["matrix"]["validate"]>[0];
}
interface GetTraitsTransform4 {
position: ReturnType<Traits["transform4"]["position"]["validate"]>;
scale: ReturnType<Traits["transform4"]["scale"]["validate"]>;
matrix: ReturnType<Traits["transform4"]["matrix"]["validate"]>;
}
interface SetTraitsTransform4 {
/**
* 4D Position
* @default `[0, 0, 0, 0]`
*/
position: Parameters<Traits["transform4"]["position"]["validate"]>[0];
/**
* 4D Scale
* @default `[1, 1, 1, 1]`
*/
scale: Parameters<Traits["transform4"]["scale"]["validate"]>[0];
/**
* 4D Affine Matrix
* @default `[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]`
*/
matrix: Parameters<Traits["transform4"]["matrix"]["validate"]>[0];
}
interface GetTraitsCamera {
proxy: ReturnType<Traits["camera"]["proxy"]["validate"]>;
position: ReturnType<Traits["camera"]["position"]["validate"]>;
quaternion: ReturnType<Traits["camera"]["quaternion"]["validate"]>;
rotation: ReturnType<Traits["camera"]["rotation"]["validate"]>;
lookAt: ReturnType<Traits["camera"]["lookAt"]["validate"]>;
up: ReturnType<Traits["camera"]["up"]["validate"]>;
eulerOrder: ReturnType<Traits["camera"]["eulerOrder"]["validate"]>;
fov: ReturnType<Traits["camera"]["fov"]["validate"]>;
}
interface SetTraitsCamera {
/**
* Re-use existing camera
* @default `false`
*/
proxy: Parameters<Traits["camera"]["proxy"]["validate"]>[0];
/**
* 3D Position
* @default `null`
* @example `[1, 2, 3]`
*/
position: Parameters<Traits["camera"]["position"]["validate"]>[0];
/**
* 3D Quaternion
* @default `null`
* @example `[0.707, 0, 0, 0.707]`
*/
quaternion: Parameters<Traits["camera"]["quaternion"]["validate"]>[0];
/**
* 3D Euler rotation
* @default `null`
* @example `[π/2, 0, 0]`
*/
rotation: Parameters<Traits["camera"]["rotation"]["validate"]>[0];
/**
* 3D Look at
* @default `null`
* @example `[2, 3, 4]`
*/
lookAt: Parameters<Traits["camera"]["lookAt"]["validate"]>[0];
/**
* 3D Up
* @default `null`
* @example `[0, 1, 0]`
*/
up: Parameters<Traits["camera"]["up"]["validate"]>[0];
/**
* 3D Euler order
* @default `"xyz"`
*/
eulerOrder: Parameters<Traits["camera"]["eulerOrder"]["validate"]>[0];
/**
* Field-of-view (degrees)
* @default `null`
* @example `60`
*/
fov: Parameters<Traits["camera"]["fov"]["validate"]>[0];
}
interface GetTraitsPolar {
bend: ReturnType<Traits["polar"]["bend"]["validate"]>;
helix: ReturnType<Traits["polar"]["helix"]["validate"]>;
}
interface SetTraitsPolar {
/**
* Amount of polar bend
* @default `1`
*/
bend: Parameters<Traits["polar"]["bend"]["validate"]>[0];
/**
* Expand into helix
* @default `0`
*/
helix: Parameters<Traits["polar"]["helix"]["validate"]>[0];
}
interface GetTraitsSpherical {
bend: ReturnType<Traits["spherical"]["bend"]["validate"]>;
}
interface SetTraitsSpherical {
/**
* Amount of spherical bend
* @default `1`
*/
bend: Parameters<Traits["spherical"]["bend"]["validate"]>[0];
}
interface GetTraitsStereographic {
bend: ReturnType<Traits["stereographic"]["bend"]["validate"]>;
}
interface SetTraitsStereographic {
/**
* Amount of stereographic bend
* @default `1`
*/
bend: Parameters<Traits["stereographic"]["bend"]["validate"]>[0];
}
interface GetTraitsInterval {
axis: ReturnType<Traits["interval"]["axis"]["validate"]>;
}
interface SetTraitsInterval {
/**
* Axis
* @default `1`
*/
axis: Parameters<Traits["interval"]["axis"]["validate"]>[0];
}
interface GetTraitsArea {
axes: ReturnType<Traits["area"]["axes"]["validate"]>;
}
interface SetTraitsArea {
/**
* Axis pair
* @default `[1, 2]`
*/
axes: Parameters<Traits["area"]["axes"]["validate"]>[0];
}
interface GetTraitsVolume {
axes: ReturnType<Traits["volume"]["axes"]["validate"]>;
}
interface SetTraitsVolume {
/**
* Axis triplet
* @default `[1, 2, 3]`
*/
axes: Parameters<Traits["volume"]["axes"]["validate"]>[0];
}
interface GetTraitsOrigin {
origin: ReturnType<Traits["origin"]["origin"]["validate"]>;
}
interface SetTraitsOrigin {
/**
* 4D Origin
* @default `[0, 0, 0, 0]`
*/
origin: Parameters<Traits["origin"]["origin"]["validate"]>[0];
}
interface GetTraitsScale {
divide: ReturnType<Traits["scale"]["divide"]["validate"]>;
unit: ReturnType<Traits["scale"]["unit"]["validate"]>;
base: ReturnType<Traits["scale"]["base"]["validate"]>;
mode: ReturnType<Traits["scale"]["mode"]["validate"]>;
start: ReturnType<Traits["scale"]["start"]["validate"]>;
end: ReturnType<Traits["scale"]["end"]["validate"]>;
zero: ReturnType<Traits["scale"]["zero"]["validate"]>;
factor: ReturnType<Traits["scale"]["factor"]["validate"]>;
nice: ReturnType<Traits["scale"]["nice"]["validate"]>;
}
interface SetTraitsScale {
/**
* Number of divisions
* @default `10`
*/
divide: Parameters<Traits["scale"]["divide"]["validate"]>[0];
/**
* Reference unit
* @default `1`
*/
unit: Parameters<Traits["scale"]["unit"]["validate"]>[0];
/**
* Power base for sub/super units
* @default `10`
*/
base: Parameters<Traits["scale"]["base"]["validate"]>[0];
/**
* Scale type
* @default `"linear"`
*/
mode: Parameters<Traits["scale"]["mode"]["validate"]>[0];
/**
* Include start
* @default `true`
*/
start: Parameters<Traits["scale"]["start"]["validate"]>[0];
/**
* Include end
* @default `true`
*/
end: Parameters<Traits["scale"]["end"]["validate"]>[0];
/**
* Include zero
* @default `true`
*/
zero: Parameters<Traits["scale"]["zero"]["validate"]>[0];
/**
* Scale factor
* @default `1`
*/
factor: Parameters<Traits["scale"]["factor"]["validate"]>[0];
/**
* Snap to nice numbers
* @default `true`
*/
nice: Parameters<Traits["scale"]["nice"]["validate"]>[0];
}
interface GetTraitsGrid {
lineX: ReturnType<Traits["grid"]["lineX"]["validate"]>;
lineY: ReturnType<Traits["grid"]["lineY"]["validate"]>;
crossed: ReturnType<Traits["grid"]["crossed"]["validate"]>;
closedX: ReturnType<Traits["grid"]["closedX"]["validate"]>;
closedY: ReturnType<Traits["grid"]["closedY"]["validate"]>;
}
interface SetTraitsGrid {
/**
* Draw X lines
* @default `true`
*/
lineX: Parameters<Traits["grid"]["lineX"]["validate"]>[0];
/**
* Draw Y lines
* @default `true`
*/
lineY: Parameters<Traits["grid"]["lineY"]["validate"]>[0];
/**
* UVWO map on matching axes
* @default `true`
*/
crossed: Parameters<Traits["grid"]["crossed"]["validate"]>[0];
/**
* Close X lines
* @default `false`
*/
closedX: Parameters<Traits["grid"]["closedX"]["validate"]>[0];
/**
* Close Y lines
* @default `false`
*/
closedY: Parameters<Traits["grid"]["closedY"]["validate"]>[0];
}
interface GetTraitsAxis {
detail: ReturnType<Traits["axis"]["detail"]["validate"]>;
crossed: ReturnType<Traits["axis"]["crossed"]["validate"]>;
}
interface SetTraitsAxis {
/**
* Geometric detail
* @default `1`
*/
detail: Parameters<Traits["axis"]["detail"]["validate"]>[0];
/**
* UVWO map on matching axis
* @default `true`
*/
crossed: Parameters<Traits["axis"]["crossed"]["validate"]>[0];
}
interface GetTraitsData {
data: ReturnType<Traits["data"]["data"]["validate"]>;
expr: ReturnType<Traits["data"]["expr"]["validate"]>;
bind: ReturnType<Traits["data"]["bind"]["validate"]>;
live: ReturnType<Traits["data"]["live"]["validate"]>;
}
interface SetTraitsData {
/**
* Data array
* @default `null`
*/
data: Parameters<Traits["data"]["data"]["validate"]>[0];
/**
* Data emitter expression
* @default `null`
*/
expr: Parameters<Traits["data"]["expr"]["validate"]>[0];
/**
*
*/
bind: Parameters<Traits["data"]["bind"]["validate"]>[0];
/**
* Update continuously
* @default `true`
*/
live: Parameters<Traits["data"]["live"]["validate"]>[0];
}
interface GetTraitsBuffer {
channels: ReturnType<Traits["buffer"]["channels"]["validate"]>;
items: ReturnType<Traits["buffer"]["items"]["validate"]>;
fps: ReturnType<Traits["buffer"]["fps"]["validate"]>;
hurry: ReturnType<Traits["buffer"]["hurry"]["validate"]>;
limit: ReturnType<Traits["buffer"]["limit"]["validate"]>;
realtime: ReturnType<Traits["buffer"]["realtime"]["validate"]>;
observe: ReturnType<Traits["buffer"]["observe"]["validate"]>;
aligned: ReturnType<Traits["buffer"]["aligned"]["validate"]>;
}
interface SetTraitsBuffer {
/**
* Number of channels
* @default `4`
*/
channels: Parameters<Traits["buffer"]["channels"]["validate"]>[0];
/**
* Number of items
* @default `4`
*/
items: Parameters<Traits["buffer"]["items"]["validate"]>[0];
/**
* Frames-per-second update rate
* @default `null`
* @example `60`
*/
fps: Parameters<Traits["buffer"]["fps"]["validate"]>[0];
/**
* Maximum frames to hurry per frame
* @default `5`
*/
hurry: Parameters<Traits["buffer"]["hurry"]["validate"]>[0];
/**
* Maximum frames to track
* @default `60`
*/
limit: Parameters<Traits["buffer"]["limit"]["validate"]>[0];
/**
* Run on real time, not clock time
* @default `false`
*/
realtime: Parameters<Traits["buffer"]["realtime"]["validate"]>[0];
/**
* Pass clock time to data
* @default `false`
*/
observe: Parameters<Traits["buffer"]["observe"]["validate"]>[0];
/**
* Use (fast) integer lookups
* @default `false`
*/
aligned: Parameters<Traits["buffer"]["aligned"]["validate"]>[0];
}
interface GetTraitsSampler {
centered: ReturnType<Traits["sampler"]["centered"]["validate"]>;
padding: ReturnType<Traits["sampler"]["padding"]["validate"]>;
}
interface SetTraitsSampler {
/**
* Centered instead of corner sampling
* @default `false`
*/
centered: Parameters<Traits["sampler"]["centered"]["validate"]>[0];
/**
* Number of samples padding
* @default `0`
*/
padding: Parameters<Traits["sampler"]["padding"]["validate"]>[0];
}
interface GetTraitsArray {
width: ReturnType<Traits["array"]["width"]["validate"]>;
bufferWidth: ReturnType<Traits["array"]["bufferWidth"]["validate"]>;
history: ReturnType<Traits["array"]["history"]["validate"]>;
}
interface SetTraitsArray {
/**
* Array width
* @default `1`
*/
width: Parameters<Traits["array"]["width"]["validate"]>[0];
/**
* Array buffer width
* @default `1`
*/
bufferWidth: Parameters<Traits["array"]["bufferWidth"]["validate"]>[0];
/**
* Array history
* @default `1`
*/
history: Parameters<Traits["array"]["history"]["validate"]>[0];
}
interface GetTraitsMatrix {
width: ReturnType<Traits["matrix"]["width"]["validate"]>;
height: ReturnType<Traits["matrix"]["height"]["validate"]>;
history: ReturnType<Traits["matrix"]["history"]["validate"]>;
bufferWidth: ReturnType<Traits["matrix"]["bufferWidth"]["validate"]>;
bufferHeight: ReturnType<Traits["matrix"]["bufferHeight"]["validate"]>;
}
interface SetTraitsMatrix {
/**
* Matrix width
* @default `1`
*/
width: Parameters<Traits["matrix"]["width"]["validate"]>[0];
/**
* Matrix height
* @default `1`
*/
height: Parameters<Traits["matrix"]["height"]["validate"]>[0];
/**
* Matrix history
* @default `1`
*/
history: Parameters<Traits["matrix"]["history"]["validate"]>[0];
/**
* Matrix buffer width
* @default `1`
*/
bufferWidth: Parameters<Traits["matrix"]["bufferWidth"]["validate"]>[0];
/**
* Matrix buffer height
* @default `1`
*/
bufferHeight: Parameters<Traits["matrix"]["bufferHeight"]["validate"]>[0];
}
interface GetTraitsVoxel {
width: ReturnType<Traits["voxel"]["width"]["validate"]>;
height: ReturnType<Traits["voxel"]["height"]["validate"]>;
depth: ReturnType<Traits["voxel"]["depth"]["validate"]>;
bufferWidth: ReturnType<Traits["voxel"]["bufferWidth"]["validate"]>;
bufferHeight: ReturnType<Traits["voxel"]["bufferHeight"]["validate"]>;
bufferDepth: ReturnType<Traits["voxel"]["bufferDepth"]["validate"]>;
}
interface SetTraitsVoxel {
/**
* Voxel width
* @default `1`
*/
width: Parameters<Traits["voxel"]["width"]["validate"]>[0];
/**
* Voxel height
* @default `1`
*/
height: Parameters<Traits["voxel"]["height"]["validate"]>[0];
/**
* Voxel depth
* @default `1`
*/
depth: Parameters<Traits["voxel"]["depth"]["validate"]>[0];
/**
* Voxel buffer width
* @default `1`
*/
bufferWidth: Parameters<Traits["voxel"]["bufferWidth"]["validate"]>[0];
/**
* Voxel buffer height
* @default `1`
*/
bufferHeight: Parameters<Traits["voxel"]["bufferHeight"]["validate"]>[0];
/**
* Voxel buffer depth
* @default `1`
*/
bufferDepth: Parameters<Traits["voxel"]["bufferDepth"]["validate"]>[0];
}
interface GetTraitsResolve {
expr: ReturnType<Traits["resolve"]["expr"]["validate"]>;
items: ReturnType<Traits["resolve"]["items"]["validate"]>;
}
interface SetTraitsResolve {
/**
*
*/
expr: Parameters<Traits["resolve"]["expr"]["validate"]>[0];
/**
*
*/
items: Parameters<Traits["resolve"]["items"]["validate"]>[0];
}
interface GetTraitsStyle {
opacity: ReturnType<Traits["style"]["opacity"]["validate"]>;
color: ReturnType<Traits["style"]["color"]["validate"]>;
blending: ReturnType<Traits["style"]["blending"]["validate"]>;
zWrite: ReturnType<Traits["style"]["zWrite"]["validate"]>;
zTest: ReturnType<Traits["style"]["zTest"]["validate"]>;
zIndex: ReturnType<Traits["style"]["zIndex"]["validate"]>;
zBias: ReturnType<Traits["style"]["zBias"]["validate"]>;
zOrder: ReturnType<Traits["style"]["zOrder"]["validate"]>;
}
interface SetTraitsStyle {
/**
* Opacity
* @default `1`
*/
opacity: Parameters<Traits["style"]["opacity"]["validate"]>[0];
/**
* Color
* @default `"rgb(128, 128, 128)"`
*/
color: Parameters<Traits["style"]["color"]["validate"]>[0];
/**
* Blending mode ('no, normal, add, subtract, multiply)
* @default `"normal"`
*/
blending: Parameters<Traits["style"]["blending"]["validate"]>[0];
/**
* Write Z buffer
* @default `true`
*/
zWrite: Parameters<Traits["style"]["zWrite"]["validate"]>[0];
/**
* Test Z buffer
* @default `true`
*/
zTest: Parameters<Traits["style"]["zTest"]["validate"]>[0];
/**
* Z-Index (2D stacking)
* @default `0`
*/
zIndex: Parameters<Traits["style"]["zIndex"]["validate"]>[0];
/**
* Z-Bias (3D stacking)
* @default `0`
*/
zBias: Parameters<Traits["style"]["zBias"]["validate"]>[0];
/**
* Z-Order (drawing order)
* @default `null`
* @example `2`
*/
zOrder: Parameters<Traits["style"]["zOrder"]["validate"]>[0];
}
interface GetTraitsGeometry {
points: ReturnType<Traits["geometry"]["points"]["validate"]>;
colors: ReturnType<Traits["geometry"]["colors"]["validate"]>;
}
interface SetTraitsGeometry {
/**
* Points data source
* @default `<`
*/
points: Parameters<Traits["geometry"]["points"]["validate"]>[0];
/**
* Colors data source
* @default `null`
* @example `"#colors"`
*/
colors: Parameters<Traits["geometry"]["colors"]["validate"]>[0];
}
interface GetTraitsPoint {
size: ReturnType<Traits["point"]["size"]["validate"]>;
sizes: ReturnType<Traits["point"]["sizes"]["validate"]>;
shape: ReturnType<Traits["point"]["shape"]["validate"]>;
optical: ReturnType<Traits["point"]["optical"]["validate"]>;
fill: ReturnType<Traits["point"]["fill"]["validate"]>;
depth: ReturnType<Traits["point"]["depth"]["validate"]>;
}
interface SetTraitsPoint {
/**
* Point size
* @default `4`
*/
size: Parameters<Traits["point"]["size"]["validate"]>[0];
/**
* Point sizes data source
* @default `null`
* @example `"#sizes"`
*/
sizes: Parameters<Traits["point"]["sizes"]["validate"]>[0];
/**
* Point shape (circle, square, diamond, up, down, left, right)
* @default `"circle"`
*/
shape: Parameters<Traits["point"]["shape"]["validate"]>[0];
/**
* Optical or exact sizing
* @default `true`
*/
optical: Parameters<Traits["point"]["optical"]["validate"]>[0];
/**
* Fill shape
* @default `true`
*/
fill: Parameters<Traits["point"]["fill"]["validate"]>[0];
/**
* Depth scaling
* @default `1`
*/
depth: Parameters<Traits["point"]["depth"]["validate"]>[0];
}
interface GetTraitsLine {
width: ReturnType<Traits["line"]["width"]["validate"]>;
depth: ReturnType<Traits["line"]["depth"]["validate"]>;
join: ReturnType<Traits["line"]["join"]["validate"]>;
stroke: ReturnType<Traits["line"]["stroke"]["validate"]>;
proximity: ReturnType<Traits["line"]["proximity"]["validate"]>;
closed: ReturnType<Traits["line"]["closed"]["validate"]>;
}
interface SetTraitsLine {
/**
* Line width
* @default `2`
*/
width: Parameters<Traits["line"]["width"]["validate"]>[0];
/**
* Depth scaling
* @default `1`
*/
depth: Parameters<Traits["line"]["depth"]["validate"]>[0];
/**
*
*/
join: Parameters<Traits["line"]["join"]["validate"]>[0];
/**
* Line stroke (solid, dotted, dashed)
* @default `"solid"`
*/
stroke: Parameters<Traits["line"]["stroke"]["validate"]>[0];
/**
* Proximity threshold
* @default `null`
* @example `10`
*/
proximity: Parameters<Traits["line"]["proximity"]["validate"]>[0];
/**
* Close line
* @default `false`
*/
closed: Parameters<Traits["line"]["closed"]["validate"]>[0];
}
interface GetTraitsMesh {
fill: ReturnType<Traits["mesh"]["fill"]["validate"]>;
shaded: ReturnType<Traits["mesh"]["shaded"]["validate"]>;
map: ReturnType<Traits["mesh"]["map"]["validate"]>;
lineBias: ReturnType<Traits["mesh"]["lineBias"]["validate"]>;
}
interface SetTraitsMesh {
/**
* Fill mesh
* @default `true`
*/
fill: Parameters<Traits["mesh"]["fill"]["validate"]>[0];
/**
* Shade mesh
* @default `false`
*/
shaded: Parameters<Traits["mesh"]["shaded"]["validate"]>[0];
/**
* Texture map source
* @default `null`
* @example `"#map"`
*/
map: Parameters<Traits["mesh"]["map"]["validate"]>[0];
/**
* Z-Bias for lines on fill
* @default `5`
*/
lineBias: Parameters<Traits["mesh"]["lineBias"]["validate"]>[0];
}
interface GetTraitsStrip {
line: ReturnType<Traits["strip"]["line"]["validate"]>;
}
interface SetTraitsStrip {
/**
* Draw line
* @default `false`
*/
line: Parameters<Traits["strip"]["line"]["validate"]>[0];
}
interface GetTraitsFace {
line: ReturnType<Traits["face"]["line"]["validate"]>;
}
interface SetTraitsFace {
/**
* Draw line
* @default `false`
*/
line: Parameters<Traits["face"]["line"]["validate"]>[0];
}
interface GetTraitsArrow {
size: ReturnType<Traits["arrow"]["size"]["validate"]>;
start: ReturnType<Traits["arrow"]["start"]["validate"]>;
end: ReturnType<Traits["arrow"]["end"]["validate"]>;
}
interface SetTraitsArrow {
/**
* Arrow size
* @default `3`
*/
size: Parameters<Traits["arrow"]["size"]["validate"]>[0];
/**
* Draw start arrow
* @default `true`
*/
start: Parameters<Traits["arrow"]["start"]["validate"]>[0];
/**
* Draw end arrow
* @default `true`
*/
end: Parameters<Traits["arrow"]["end"]["validate"]>[0];
}
interface GetTraitsTicks {
normal: ReturnType<Traits["ticks"]["normal"]["validate"]>;
size: ReturnType<Traits["ticks"]["size"]["validate"]>;
epsilon: ReturnType<Traits["ticks"]["epsilon"]["validate"]>;
}
interface SetTraitsTicks {
/**
* Normal for reference plane
* @default `true`
*/
normal: Parameters<Traits["ticks"]["normal"]["validate"]>[0];
/**
* Tick size
* @default `10`
*/
size: Parameters<Traits["ticks"]["size"]["validate"]>[0];
/**
* Tick epsilon
* @default `0.0001`
*/
epsilon: Parameters<Traits["ticks"]["epsilon"]["validate"]>[0];
}
interface GetTraitsAttach {
offset: ReturnType<Traits["attach"]["offset"]["validate"]>;
snap: ReturnType<Traits["attach"]["snap"]["validate"]>;
depth: ReturnType<Traits["attach"]["depth"]["validate"]>;
}
interface SetTraitsAttach {
/**
* 2D offset
* @default `[0, -20]`
*/
offset: Parameters<Traits["attach"]["offset"]["validate"]>[0];
/**
* Snap to pixel
* @default `false`
*/
snap: Parameters<Traits["attach"]["snap"]["validate"]>[0];
/**
* Depth scaling
* @default `0`
*/
depth: Parameters<Traits["attach"]["depth"]["validate"]>[0];
}
interface GetTraitsFormat {
digits: ReturnType<Traits["format"]["digits"]["validate"]>;
data: ReturnType<Traits["format"]["data"]["validate"]>;
expr: ReturnType<Traits["format"]["expr"]["validate"]>;
live: ReturnType<Traits["format"]["live"]["validate"]>;
}
interface SetTraitsFormat {
/**
* Digits of precision
* @default `null`
* @example `2`
*/
digits: Parameters<Traits["format"]["digits"]["validate"]>[0];
/**
* Array of labels
* @default `null`
* @example `["Grumpy", "Sleepy", "Sneezy"]`
*/
data: Parameters<Traits["format"]["data"]["validate"]>[0];
/**
* Label formatter expression
* @default `null`
*/
expr: Parameters<Traits["format"]["expr"]["validate"]>[0];
/**
* Update continuously
* @default `true`
*/
live: Parameters<Traits["format"]["live"]["validate"]>[0];
}
interface GetTraitsFont {
font: ReturnType<Traits["font"]["font"]["validate"]>;
style: ReturnType<Traits["font"]["style"]["validate"]>;
variant: ReturnType<Traits["font"]["variant"]["validate"]>;
weight: ReturnType<Traits["font"]["weight"]["validate"]>;
detail: ReturnType<Traits["font"]["detail"]["validate"]>;
sdf: ReturnType<Traits["font"]["sdf"]["validate"]>;
}
interface SetTraitsFont {
/**
* Font family
* @default `"sans-serif"`
*/
font: Parameters<Traits["font"]["font"]["validate"]>[0];
/**
* Font style
* @default `""`
* @example `"italic"`
*/
style: Parameters<Traits["font"]["style"]["validate"]>[0];
/**
* Font variant
* @default `""`
* @example `"small-caps"`
*/
variant: Parameters<Traits["font"]["variant"]["validate"]>[0];
/**
* Font weight
* @default `""`
* @example `"bold"`
*/
weight: Parameters<Traits["font"]["weight"]["validate"]>[0];
/**
* Font detail
* @default `24`
*/
detail: Parameters<Traits["font"]["detail"]["validate"]>[0];
/**
* Signed distance field range
* @default `5`
*/
sdf: Parameters<Traits["font"]["sdf"]["validate"]>[0];
}
interface GetTraitsLabel {
text: ReturnType<Traits["label"]["text"]["validate"]>;
size: ReturnType<Traits["label"]["size"]["validate"]>;
outline: ReturnType<Traits["label"]["outline"]["validate"]>;
expand: ReturnType<Traits["label"]["expand"]["validate"]>;
background: ReturnType<Traits["label"]["background"]["validate"]>;
}
interface SetTraitsLabel {
/**
* Text source
* @default `"<"`
*/
text: Parameters<Traits["label"]["text"]["validate"]>[0];
/**
* Text size
* @default `16`
*/
size: Parameters<Traits["label"]["size"]["validate"]>[0];
/**
* Outline size
* @default `2`
*/
outline: Parameters<Traits["label"]["outline"]["validate"]>[0];
/**
* Expand glyphs
* @default `0`
*/
expand: Parameters<Traits["label"]["expand"]["validate"]>[0];
/**
* Outline background
* @default `"rgb(255, 255, 255)"`
*/
background: Parameters<Traits["label"]["background"]["validate"]>[0];
}
interface GetTraitsOverlay {
opacity: ReturnType<Traits["overlay"]["opacity"]["validate"]>;
zIndex: ReturnType<Traits["overlay"]["zIndex"]["validate"]>;
}
interface SetTraitsOverlay {
/**
* Opacity
* @default `1`
*/
opacity: Parameters<Traits["overlay"]["opacity"]["validate"]>[0];
/**
* Z-Index (2D stacking)
* @default `0`
*/
zIndex: Parameters<Traits["overlay"]["zIndex"]["validate"]>[0];
}
interface GetTraitsDom {
points: ReturnType<Traits["dom"]["points"]["validate"]>;
html: ReturnType<Traits["dom"]["html"]["validate"]>;
size: ReturnType<Traits["dom"]["size"]["validate"]>;
outline: ReturnType<Traits["dom"]["outline"]["validate"]>;
zoom: ReturnType<Traits["dom"]["zoom"]["validate"]>;
color: ReturnType<Traits["dom"]["color"]["validate"]>;
attributes: ReturnType<Traits["dom"]["attributes"]["validate"]>;
pointerEvents: ReturnType<Traits["dom"]["pointerEvents"]["validate"]>;
}
interface SetTraitsDom {
/**
* Points data source
* @default `"<"`
*/
points: Parameters<Traits["dom"]["points"]["validate"]>[0];
/**
* HTML data source
* @default `"<"`
*/
html: Parameters<Traits["dom"]["html"]["validate"]>[0];
/**
* Text size
* @default `16`
*/
size: Parameters<Traits["dom"]["size"]["validate"]>[0];
/**
* Outline size
* @default `2`
*/
outline: Parameters<Traits["dom"]["outline"]["validate"]>[0];
/**
* HTML zoom
* @default `1`
*/
zoom: Parameters<Traits["dom"]["zoom"]["validate"]>[0];
/**
* Color
* @default `"rgb(255, 255, 255)"`
*/
color: Parameters<Traits["dom"]["color"]["validate"]>[0];
/**
* HTML attributes
* @default `null`
* @example `{"style": {"color": "red"}}`
*/
attributes: Parameters<Traits["dom"]["attributes"]["validate"]>[0];
/**
* Allow pointer events
* @default `false`
*/
pointerEvents: Parameters<Traits["dom"]["pointerEvents"]["validate"]>[0];
}
interface GetTraitsTexture {
minFilter: ReturnType<Traits["texture"]["minFilter"]["validate"]>;
magFilter: ReturnType<Traits["texture"]["magFilter"]["validate"]>;
type: ReturnType<Traits["texture"]["type"]["validate"]>;
}
interface SetTraitsTexture {
/**
* Texture minification filtering
* @default `"nearest"`
*/
minFilter: Parameters<Traits["texture"]["minFilter"]["validate"]>[0];
/**
* Texture magnification filtering
* @default `"nearest"`
*/
magFilter: Parameters<Traits["texture"]["magFilter"]["validate"]>[0];
/**
* Texture data type
* @default `"float"`
*/
type: Parameters<Traits["texture"]["type"]["validate"]>[0];
}
interface GetTraitsShader {
sources: ReturnType<Traits["shader"]["sources"]["validate"]>;
language: ReturnType<Traits["shader"]["language"]["validate"]>;
code: ReturnType<Traits["shader"]["code"]["validate"]>;
uniforms: ReturnType<Traits["shader"]["uniforms"]["validate"]>;
}
interface SetTraitsShader {
/**
* Sampler sources
* @default `null`
* @example `["#pressure", "#divergence"]`
*/
sources: Parameters<Traits["shader"]["sources"]["validate"]>[0];
/**
* Shader language
* @default `"glsl"`
*/
language: Parameters<Traits["shader"]["language"]["validate"]>[0];
/**
* Shader code
* @default `""`
*/
code: Parameters<Traits["shader"]["code"]["validate"]>[0];
/**
* Shader uniform objects (three.js style)
* @default `null`
* @example `{ time: { type: 'f', value: 3 }}`
*/
uniforms: Parameters<Traits["shader"]["uniforms"]["validate"]>[0];
}
interface GetTraitsInclude {
shader: ReturnType<Traits["include"]["shader"]["validate"]>;
}
interface SetTraitsInclude {
/**
* Shader to use
* @default `"<"`
*/
shader: Parameters<Traits["include"]["shader"]["validate"]>[0];
}
interface GetTraitsOperator {
source: ReturnType<Traits["operator"]["source"]["validate"]>;
}
interface SetTraitsOperator {
/**
* Input source
* @default `"<"`
*/
source: Parameters<Traits["operator"]["source"]["validate"]>[0];
}
interface GetTraitsSpread {
unit: ReturnType<Traits["spread"]["unit"]["validate"]>;
items: ReturnType<Traits["spread"]["items"]["validate"]>;
width: ReturnType<Traits["spread"]["width"]["validate"]>;
height: ReturnType<Traits["spread"]["height"]["validate"]>;
depth: ReturnType<Traits["spread"]["depth"]["validate"]>;
alignItems: ReturnType<Traits["spread"]["alignItems"]["validate"]>;
alignWidth: ReturnType<Traits["spread"]["alignWidth"]["validate"]>;
alignHeight: ReturnType<Traits["spread"]["alignHeight"]["validate"]>;
alignDepth: ReturnType<Traits["spread"]["alignDepth"]["validate"]>;
}
interface SetTraitsSpread {
/**
* Spread per item (absolute) or array (relative)
* @default `"relative"`
*/
unit: Parameters<Traits["spread"]["unit"]["validate"]>[0];
/**
* Items offset
* @default `null`
* @example `[1.5, 0, 0, 0]`
*/
items: Parameters<Traits["spread"]["items"]["validate"]>[0];
/**
* Width offset
* @default `null`
* @example `[1.5, 0, 0, 0]`
*/
width: Parameters<Traits["spread"]["width"]["validate"]>[0];
/**
* Height offset
* @default `null`
* @example `[1.5, 0, 0, 0]`
*/
height: Parameters<Traits["spread"]["height"]["validate"]>[0];
/**
* Depth offset
* @default `null`
* @example `[1.5, 0, 0, 0]`
*/
depth: Parameters<Traits["spread"]["depth"]["validate"]>[0];
/**
* Items alignment
* @default `0`
*/
alignItems: Parameters<Traits["spread"]["alignItems"]["validate"]>[0];
/**
* Width alignment
* @default `0`
*/
alignWidth: Parameters<Traits["spread"]["alignWidth"]["validate"]>[0];
/**
* Height alignment
* @default `0`
*/
alignHeight: Parameters<Traits["spread"]["alignHeight"]["validate"]>[0];
/**
* Depth alignment
* @default `0`
*/
alignDepth: Parameters<Traits["spread"]["alignDepth"]["validate"]>[0];
}
interface GetTraitsGrow {
scale: ReturnType<Traits["grow"]["scale"]["validate"]>;
items: ReturnType<Traits["grow"]["items"]["validate"]>;
width: ReturnType<Traits["grow"]["width"]["validate"]>;
height: ReturnType<Traits["grow"]["height"]["validate"]>;
depth: ReturnType<Traits["grow"]["depth"]["validate"]>;
}
interface SetTraitsGrow {
/**
* Scale factor
* @default `1`
*/
scale: Parameters<Traits["grow"]["scale"]["validate"]>[0];
/**
* Items alignment
* @default `null`
* @example `0`
*/
items: Parameters<Traits["grow"]["items"]["validate"]>[0];
/**
* Width alignment
* @default `null`
* @example `0`
*/
width: Parameters<Traits["grow"]["width"]["validate"]>[0];
/**
* Height alignment
* @default `null`
* @example `0`
*/
height: Parameters<Traits["grow"]["height"]["validate"]>[0];
/**
* Depth alignment
* @default `null`
* @example `0`
*/
depth: Parameters<Traits["grow"]["depth"]["validate"]>[0];
}
interface GetTraitsSplit {
order: ReturnType<Traits["split"]["order"]["validate"]>;
axis: ReturnType<Traits["split"]["axis"]["validate"]>;
length: ReturnType<Traits["split"]["length"]["validate"]>;
overlap: ReturnType<Traits["split"]["overlap"]["validate"]>;
}
interface SetTraitsSplit {
/**
* Axis order
* @default `"wxyz"`
*/
order: Parameters<Traits["split"]["order"]["validate"]>[0];
/**
* Axis to split
* @default `null`
* @example `x`
*/
axis: Parameters<Traits["split"]["axis"]["validate"]>[0];
/**
* Tuple length
* @default `1`
*/
length: Parameters<Traits["split"]["length"]["validate"]>[0];
/**
* Tuple overlap
* @default `1`
*/
overlap: Parameters<Traits["split"]["overlap"]["validate"]>[0];
}
interface GetTraitsJoin {
order: ReturnType<Traits["join"]["order"]["validate"]>;
axis: ReturnType<Traits["join"]["axis"]["validate"]>;
overlap: ReturnType<Traits["join"]["overlap"]["validate"]>;
}
interface SetTraitsJoin {
/**
* Axis order
* @default `"wxyz"`
*/
order: Parameters<Traits["join"]["order"]["validate"]>[0];
/**
* Axis to join
* @default `null`
* @example `x`
*/
axis: Parameters<Traits["join"]["axis"]["validate"]>[0];
/**
* Tuple overlap
* @default `1`
*/
overlap: Parameters<Traits["join"]["overlap"]["validate"]>[0];
}
interface GetTraitsSwizzle {
order: ReturnType<Traits["swizzle"]["order"]["validate"]>;
}
interface SetTraitsSwizzle {
/**
* Swizzle order
* @default `xyzw`
*/
order: Parameters<Traits["swizzle"]["order"]["validate"]>[0];
}
interface GetTraitsTranspose {
order: ReturnType<Traits["transpose"]["order"]["validate"]>;
}
interface SetTraitsTranspose {
/**
* Transpose order
* @default `xyzw`
*/
order: Parameters<Traits["transpose"]["order"]["validate"]>[0];
}
interface GetTraitsRepeat {
items: ReturnType<Traits["repeat"]["items"]["validate"]>;
width: ReturnType<Traits["repeat"]["width"]["validate"]>;
height: ReturnType<Traits["repeat"]["height"]["validate"]>;
depth: ReturnType<Traits["repeat"]["depth"]["validate"]>;
}
interface SetTraitsRepeat {
/**
* Repeat items
* @default `1`
*/
items: Parameters<Traits["repeat"]["items"]["validate"]>[0];
/**
* Repeat width
* @default `1`
*/
width: Parameters<Traits["repeat"]["width"]["validate"]>[0];
/**
* Repeat height
* @default `1`
*/
height: Parameters<Traits["repeat"]["height"]["validate"]>[0];
/**
* Repeat depth
* @default `1`
*/
depth: Parameters<Traits["repeat"]["depth"]["validate"]>[0];
}
interface GetTraitsSlice {
items: ReturnType<Traits["slice"]["items"]["validate"]>;
width: ReturnType<Traits["slice"]["width"]["validate"]>;
height: ReturnType<Traits["slice"]["height"]["validate"]>;
depth: ReturnType<Traits["slice"]["depth"]["validate"]>;
}
interface SetTraitsSlice {
/**
* Slice from, to items (excluding to)
* @default `null`
* @example `[2, 4]`
*/
items: Parameters<Traits["slice"]["items"]["validate"]>[0];
/**
* Slice from, to width (excluding to)
* @default `null`
* @example `[2, 4]`
*/
width: Parameters<Traits["slice"]["width"]["validate"]>[0];
/**
* Slice from, to height (excluding to)
* @default `null`
* @example `[2, 4]`
*/
height: Parameters<Traits["slice"]["height"]["validate"]>[0];
/**
* Slice from, to depth (excluding to)
* @default `null`
* @example `[2, 4]`
*/
depth: Parameters<Traits["slice"]["depth"]["validate"]>[0];
}
interface GetTraitsLerp {
size: ReturnType<Traits["lerp"]["size"]["validate"]>;
items: ReturnType<Traits["lerp"]["items"]["validate"]>;
width: ReturnType<Traits["lerp"]["width"]["validate"]>;
height: ReturnType<Traits["lerp"]["height"]["validate"]>;
depth: ReturnType<Traits["lerp"]["depth"]["validate"]>;
}
interface SetTraitsLerp {
/**
* Scaling mode (relative, absolute)
* @default `"absolute"`
*/
size: Parameters<Traits["lerp"]["size"]["validate"]>[0];
/**
* Lerp to items
* @default `null`
* @example `5`
*/
items: Parameters<Traits["lerp"]["items"]["validate"]>[0];
/**
* Lerp to width
* @default `null`
* @example `5`
*/
width: Parameters<Traits["lerp"]["width"]["validate"]>[0];
/**
* Lerp to height
* @default `null`
* @example `5`
*/
height: Parameters<Traits["lerp"]["height"]["validate"]>[0];
/**
* Lerp to depth
* @default `null`
* @example `5`
*/
depth: Parameters<Traits["lerp"]["depth"]["validate"]>[0];
}
interface GetTraitsSubdivide {
items: ReturnType<Traits["subdivide"]["items"]["validate"]>;
width: ReturnType<Traits["subdivide"]["width"]["validate"]>;
height: ReturnType<Traits["subdivide"]["height"]["validate"]>;
depth: ReturnType<Traits["subdivide"]["depth"]["validate"]>;
bevel: ReturnType<Traits["subdivide"]["bevel"]["validate"]>;
lerp: ReturnType<Traits["subdivide"]["lerp"]["validate"]>;
}
interface SetTraitsSubdivide {
/**
* Divisions of items
* @default `null`
* @example `5`
*/
items: Parameters<Traits["subdivide"]["items"]["validate"]>[0];
/**
* Divisions of width
* @default `null`
* @example `5`
*/
width: Parameters<Traits["subdivide"]["width"]["validate"]>[0];
/**
* Divisions of height
* @default `null`
* @example `5`
*/
height: Parameters<Traits["subdivide"]["height"]["validate"]>[0];
/**
* Divisions of depth
* @default `null`
* @example `5`
*/
depth: Parameters<Traits["subdivide"]["depth"]["validate"]>[0];
/**
* Fraction to end outward from vertices
* @default `1`
*/
bevel: Parameters<Traits["subdivide"]["bevel"]["validate"]>[0];
/**
* Interpolate values with computed indices
* @default `true`
*/
lerp: Parameters<Traits["subdivide"]["lerp"]["validate"]>[0];
}
interface GetTraitsResample {
indices: ReturnType<Traits["resample"]["indices"]["validate"]>;
channels: ReturnType<Traits["resample"]["channels"]["validate"]>;
sample: ReturnType<Traits["resample"]["sample"]["validate"]>;
size: ReturnType<Traits["resample"]["size"]["validate"]>;
items: ReturnType<Traits["resample"]["items"]["validate"]>;
width: ReturnType<Traits["resample"]["width"]["validate"]>;
height: ReturnType<Traits["resample"]["height"]["validate"]>;
depth: ReturnType<Traits["resample"]["depth"]["validate"]>;
}
interface SetTraitsResample {
/**
* Resample indices
* @default `4`
*/
indices: Parameters<Traits["resample"]["indices"]["validate"]>[0];
/**
* Resample channels
* @default `4`
*/
channels: Parameters<Traits["resample"]["channels"]["validate"]>[0];
/**
* Source sampling (relative, absolute)
* @default `"relative"`
*/
sample: Parameters<Traits["resample"]["sample"]["validate"]>[0];
/**
* Scaling mode (relative, absolute)
* @default `"absolute"`
*/
size: Parameters<Traits["resample"]["size"]["validate"]>[0];
/**
* Resample factor items
* @default `null`
* @example `10`
*/
items: Parameters<Traits["resample"]["items"]["validate"]>[0];
/**
* Resample factor width
* @default `null`
* @example `10`
*/
width: Parameters<Traits["resample"]["width"]["validate"]>[0];
/**
* Resample factor height
* @default `null`
* @example `10`
*/
height: Parameters<Traits["resample"]["height"]["validate"]>[0];
/**
* Resample factor depth
* @default `null`
* @example `10`
*/
depth: Parameters<Traits["resample"]["depth"]["validate"]>[0];
}
interface GetTraitsReadback {
type: ReturnType<Traits["readback"]["type"]["validate"]>;
expr: ReturnType<Traits["readback"]["expr"]["validate"]>;
data: ReturnType<Traits["readback"]["data"]["validate"]>;
channels: ReturnType<Traits["readback"]["channels"]["validate"]>;
items: ReturnType<Traits["readback"]["items"]["validate"]>;
width: ReturnType<Traits["readback"]["width"]["validate"]>;
height: ReturnType<Traits["readback"]["height"]["validate"]>;
depth: ReturnType<Traits["readback"]["depth"]["validate"]>;
}
interface SetTraitsReadback {
/**
* Readback data type (float, unsignedByte)
* @default `"float"`
*/
type: Parameters<Traits["readback"]["type"]["validate"]>[0];
/**
* Readback consume expression
* @default `null`
*/
expr: Parameters<Traits["readback"]["expr"]["validate"]>[0];
/**
* Readback data buffer (read only)
* @default `[]`
*/
data: Parameters<Traits["readback"]["data"]["validate"]>[0];
/**
* Readback channels (read only)
* @default `4`
*/
channels: Parameters<Traits["readback"]["channels"]["validate"]>[0];
/**
* Readback items (read only)
* @default `1`
*/
items: Parameters<Traits["readback"]["items"]["validate"]>[0];
/**
* Readback width (read only)
* @default `1`
*/
width: Parameters<Traits["readback"]["width"]["validate"]>[0];
/**
* Readback height (read only)
* @default `1`
*/
height: Parameters<Traits["readback"]["height"]["validate"]>[0];
/**
* Readback depth (read only)
* @default `1`
*/
depth: Parameters<Traits["readback"]["depth"]["validate"]>[0];
}
interface GetTraitsRoot {
speed: ReturnType<Traits["root"]["speed"]["validate"]>;
camera: ReturnType<Traits["root"]["camera"]["validate"]>;
}
interface SetTraitsRoot {
/**
* Global speed
* @default `1`
*/
speed: Parameters<Traits["root"]["speed"]["validate"]>[0];
/**
* Active camera
* @default `"[camera]"`
*/
camera: Parameters<Traits["root"]["camera"]["validate"]>[0];
}
interface GetTraitsInherit {
source: ReturnType<Traits["inherit"]["source"]["validate"]>;
traits: ReturnType<Traits["inherit"]["traits"]["validate"]>;
}
interface SetTraitsInherit {
/**
* Inherit from node
* @default `"<"`
*/
source: Parameters<Traits["inherit"]["source"]["validate"]>[0];
/**
* Inherit traits
* @default `[]`
*/
traits: Parameters<Traits["inherit"]["traits"]["validate"]>[0];
}
interface GetTraitsRtt {
size: ReturnType<Traits["rtt"]["size"]["validate"]>;
width: ReturnType<Traits["rtt"]["width"]["validate"]>;
height: ReturnType<Traits["rtt"]["height"]["validate"]>;
history: ReturnType<Traits["rtt"]["history"]["validate"]>;
}
interface SetTraitsRtt {
/**
*
*/
size: Parameters<Traits["rtt"]["size"]["validate"]>[0];
/**
* RTT width
* @default `null`
* @example `640`
*/
width: Parameters<Traits["rtt"]["width"]["validate"]>[0];
/**
* RTT height
* @default `null`
* @example `360`
*/
height: Parameters<Traits["rtt"]["height"]["validate"]>[0];
/**
* RTT history
* @default `1`
*/
history: Parameters<Traits["rtt"]["history"]["validate"]>[0];
}
interface GetTraitsCompose {
alpha: ReturnType<Traits["compose"]["alpha"]["validate"]>;
}
interface SetTraitsCompose {
/**
* Compose with alpha transparency
* @default `false`
*/
alpha: Parameters<Traits["compose"]["alpha"]["validate"]>[0];
}
interface GetTraitsPresent {
index: ReturnType<Traits["present"]["index"]["validate"]>;
directed: ReturnType<Traits["present"]["directed"]["validate"]>;
length: ReturnType<Traits["present"]["length"]["validate"]>;
}
interface SetTraitsPresent {
/**
* Present slide number
* @default `1`
*/
index: Parameters<Traits["present"]["index"]["validate"]>[0];
/**
* Apply directional transitions
* @default `true`
*/
directed: Parameters<Traits["present"]["directed"]["validate"]>[0];
/**
* Presentation length (computed)
* @default `0`
*/
length: Parameters<Traits["present"]["length"]["validate"]>[0];
}
interface GetTraitsSlide {
order: ReturnType<Traits["slide"]["order"]["validate"]>;
steps: ReturnType<Traits["slide"]["steps"]["validate"]>;
early: ReturnType<Traits["slide"]["early"]["validate"]>;
late: ReturnType<Traits["slide"]["late"]["validate"]>;
from: ReturnType<Traits["slide"]["from"]["validate"]>;
to: ReturnType<Traits["slide"]["to"]["validate"]>;
}
interface SetTraitsSlide {
/**
* Slide order
* @default `0`
*/
order: Parameters<Traits["slide"]["order"]["validate"]>[0];
/**
* Slide steps
* @default `1`
*/
steps: Parameters<Traits["slide"]["steps"]["validate"]>[0];
/**
* Appear early steps
* @default `0`
*/
early: Parameters<Traits["slide"]["early"]["validate"]>[0];
/**
* Stay late steps
* @default `0`
*/
late: Parameters<Traits["slide"]["late"]["validate"]>[0];
/**
* Appear from step
* @default `null`
* @example `2`
*/
from: Parameters<Traits["slide"]["from"]["validate"]>[0];
/**
* Disappear on step
* @default `null`
* @example `4`
*/
to: Parameters<Traits["slide"]["to"]["validate"]>[0];
}
interface GetTraitsTransition {
stagger: ReturnType<Traits["transition"]["stagger"]["validate"]>;
enter: ReturnType<Traits["transition"]["enter"]["validate"]>;
exit: ReturnType<Traits["transition"]["exit"]["validate"]>;
delay: ReturnType<Traits["transition"]["delay"]["validate"]>;
delayEnter: ReturnType<Traits["transition"]["delayEnter"]["validate"]>;
delayExit: ReturnType<Traits["transition"]["delayExit"]["validate"]>;
duration: ReturnType<Traits["transition"]["duration"]["validate"]>;
durationEnter: ReturnType<Traits["transition"]["durationEnter"]["validate"]>;
durationExit: ReturnType<Traits["transition"]["durationExit"]["validate"]>;
}
interface SetTraitsTransition {
/**
* Stagger dimensions
* @default `[0, 0, 0, 0]`
* @example `[2, 1, 0, 0]`
*/
stagger: Parameters<Traits["transition"]["stagger"]["validate"]>[0];
/**
* Enter state
* @default `null`
* @example `0.5`
*/
enter: Parameters<Traits["transition"]["enter"]["validate"]>[0];
/**
* Exit state
* @default `null`
* @example `0.5`
*/
exit: Parameters<Traits["transition"]["exit"]["validate"]>[0];
/**
* Transition delay
* @default `0`
*/
delay: Parameters<Traits["transition"]["delay"]["validate"]>[0];
/**
* Transition enter delay
* @default `null`
* @example `0.3`
*/
delayEnter: Parameters<Traits["transition"]["delayEnter"]["validate"]>[0];
/**
* Transition exit delay
* @default `null`
* @example `0.3`
*/
delayExit: Parameters<Traits["transition"]["delayExit"]["validate"]>[0];
/**
* Transition duration
* @default `0.3`
*/
duration: Parameters<Traits["transition"]["duration"]["validate"]>[0];
/**
* Transition enter duration
* @default `0.3`
*/
durationEnter: Parameters<
Traits["transition"]["durationEnter"]["validate"]
>[0];
/**
* Transition exit duration
* @default `0.3`
*/
durationExit: Parameters<Traits["transition"]["durationExit"]["validate"]>[0];
}
interface GetTraitsMove {
from: ReturnType<Traits["move"]["from"]["validate"]>;
to: ReturnType<Traits["move"]["to"]["validate"]>;
}
interface SetTraitsMove {
/**
* Enter from
* @default `[0, 0, 0, 0]`
*/
from: Parameters<Traits["move"]["from"]["validate"]>[0];
/**
* Exit to
* @default `[0, 0, 0, 0]`
*/
to: Parameters<Traits["move"]["to"]["validate"]>[0];
}
interface GetTraitsSeek {
seek: ReturnType<Traits["seek"]["seek"]["validate"]>;
}
interface SetTraitsSeek {
/**
* Seek to time
* @default `null`
* @example `4`
*/
seek: Parameters<Traits["seek"]["seek"]["validate"]>[0];
}
interface GetTraitsTrack {
target: ReturnType<Traits["track"]["target"]["validate"]>;
script: ReturnType<Traits["track"]["script"]["validate"]>;
ease: ReturnType<Traits["track"]["ease"]["validate"]>;
}
interface SetTraitsTrack {
/**
* Animation target
* @default `"<"`
*/
target: Parameters<Traits["track"]["target"]["validate"]>[0];
/**
* Animation script
* @default `{}`
* @example `{ "0": { props: { color: "red" }, expr: { size: function (t) { return Math.sin(t) + 1; }}}, "1": ...}`
*/
script: Parameters<Traits["track"]["script"]["validate"]>[0];
/**
* Animation ease (linear, cosine, binary, hold)
* @default `"cosine"`
*/
ease: Parameters<Traits["track"]["ease"]["validate"]>[0];
}
interface GetTraitsTrigger {
trigger: ReturnType<Traits["trigger"]["trigger"]["validate"]>;
}
interface SetTraitsTrigger {
/**
* Trigger on step
* @default `1`
*/
trigger: Parameters<Traits["trigger"]["trigger"]["validate"]>[0];
}
interface GetTraitsStep {
playback: ReturnType<Traits["step"]["playback"]["validate"]>;
stops: ReturnType<Traits["step"]["stops"]["validate"]>;
delay: ReturnType<Traits["step"]["delay"]["validate"]>;
duration: ReturnType<Traits["step"]["duration"]["validate"]>;
pace: ReturnType<Traits["step"]["pace"]["validate"]>;
speed: ReturnType<Traits["step"]["speed"]["validate"]>;
rewind: ReturnType<Traits["step"]["rewind"]["validate"]>;
skip: ReturnType<Traits["step"]["skip"]["validate"]>;
realtime: ReturnType<Traits["step"]["realtime"]["validate"]>;
}
interface SetTraitsStep {
/**
* Playhead ease (linear, cosine, binary, hold)
* @default `"linear"`
*/
playback: Parameters<Traits["step"]["playback"]["validate"]>[0];
/**
* Playhead stops
* @default `null`
* @example `[0, 1, 3, 5]`
*/
stops: Parameters<Traits["step"]["stops"]["validate"]>[0];
/**
* Step delay
* @default `0`
*/
delay: Parameters<Traits["step"]["delay"]["validate"]>[0];
/**
* Step duration
* @default `0.3`
*/
duration: Parameters<Traits["step"]["duration"]["validate"]>[0];
/**
* Step pace
* @default `0`
*/
pace: Parameters<Traits["step"]["pace"]["validate"]>[0];
/**
* Step speed
* @default `1`
*/
speed: Parameters<Traits["step"]["speed"]["validate"]>[0];
/**
* Step rewind factor
* @default `2`
*/
rewind: Parameters<Traits["step"]["rewind"]["validate"]>[0];
/**
* Speed up through skips
* @default `true`
*/
skip: Parameters<Traits["step"]["skip"]["validate"]>[0];
/**
* Run on real time, not clock time
* @default `false`
*/
realtime: Parameters<Traits["step"]["realtime"]["validate"]>[0];
}
interface GetTraitsPlay {
delay: ReturnType<Traits["play"]["delay"]["validate"]>;
pace: ReturnType<Traits["play"]["pace"]["validate"]>;
speed: ReturnType<Traits["play"]["speed"]["validate"]>;
from: ReturnType<Traits["play"]["from"]["validate"]>;
to: ReturnType<Traits["play"]["to"]["validate"]>;
realtime: ReturnType<Traits["play"]["realtime"]["validate"]>;
loop: ReturnType<Traits["play"]["loop"]["validate"]>;
}
interface SetTraitsPlay {
/**
* Play delay
* @default `0`
*/
delay: Parameters<Traits["play"]["delay"]["validate"]>[0];
/**
* Play pace
* @default `1`
*/
pace: Parameters<Traits["play"]["pace"]["validate"]>[0];
/**
* Play speed
* @default `1`
*/
speed: Parameters<Traits["play"]["speed"]["validate"]>[0];
/**
* Play from
* @default `0`
*/
from: Parameters<Traits["play"]["from"]["validate"]>[0];
/**
* Play until
* @default `Infinity`
*/
to: Parameters<Traits["play"]["to"]["validate"]>[0];
/**
* Run on real time, not clock time
* @default `false`
*/
realtime: Parameters<Traits["play"]["realtime"]["validate"]>[0];
/**
* Loop
* @default `false`
*/
loop: Parameters<Traits["play"]["loop"]["validate"]>[0];
}
interface GetTraitsNow {
now: ReturnType<Traits["now"]["now"]["validate"]>;
seek: ReturnType<Traits["now"]["seek"]["validate"]>;
pace: ReturnType<Traits["now"]["pace"]["validate"]>;
speed: ReturnType<Traits["now"]["speed"]["validate"]>;
}
interface SetTraitsNow {
/**
* Current moment
* @default `null`
* @example `1444094929.619`
*/
now: Parameters<Traits["now"]["now"]["validate"]>[0];
/**
* Seek to time
* @default `null`
*/
seek: Parameters<Traits["now"]["seek"]["validate"]>[0];
/**
* Time pace
* @default `1`
*/
pace: Parameters<Traits["now"]["pace"]["validate"]>[0];
/**
* Time speed
* @default `1`
*/
speed: Parameters<Traits["now"]["speed"]["validate"]>[0];
}
/**
* Normalized properties for {@link MathboxSelection.area | area}.
* @category data
*/
export interface AreaPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsMatrix,
GetTraitsTexture,
GetTraitsArea {}
/**
* Properties for {@link MathboxSelection.area | area}.
* @category data
*/
export interface AreaProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsMatrix,
SetTraitsTexture,
SetTraitsArea {}
/**
* Normalized properties for {@link MathboxSelection.array | array}.
* @category data
*/
export interface ArrayPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsArray,
GetTraitsTexture {}
/**
* Properties for {@link MathboxSelection.array | array}.
* @category data
*/
export interface ArrayProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsArray,
SetTraitsTexture {}
/**
* Normalized properties for {@link MathboxSelection.axis | axis}.
* @category draw
*/
export interface AxisPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsAxis,
GetTraitsSpan,
GetTraitsInterval,
GetTraitsArrow,
GetTraitsOrigin {}
/**
* Properties for {@link MathboxSelection.axis | axis}.
* @category draw
*/
export interface AxisProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsAxis,
SetTraitsSpan,
SetTraitsInterval,
SetTraitsArrow,
SetTraitsOrigin {}
/**
* Normalized properties for {@link MathboxSelection.camera | camera}.
* @category camera
*/
export interface CameraPropsNormalized extends GetTraitsNode, GetTraitsCamera {}
/**
* Properties for {@link MathboxSelection.camera | camera}.
* @category camera
*/
export interface CameraProps extends SetTraitsNode, SetTraitsCamera {}
/**
* Normalized properties for {@link MathboxSelection.cartesian | cartesian}.
* @category view
*/
export interface CartesianPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsView3,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.cartesian | cartesian}.
* @category view
*/
export interface CartesianProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsView3,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.cartesian4 | cartesian4}.
* @category view
*/
export interface Cartesian4PropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsView4,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.cartesian4 | cartesian4}.
* @category view
*/
export interface Cartesian4Props
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsView4,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.clamp | clamp}.
* @category operator
*/
export interface ClampPropsNormalized
extends GetTraitsNode,
GetTraitsOperator {}
/**
* Properties for {@link MathboxSelection.clamp | clamp}.
* @category operator
*/
export interface ClampProps extends SetTraitsNode, SetTraitsOperator {}
/**
* Normalized properties for {@link MathboxSelection.clock | clock}.
* @category time
*/
export interface ClockPropsNormalized
extends GetTraitsNode,
GetTraitsSeek,
GetTraitsPlay {}
/**
* Properties for {@link MathboxSelection.clock | clock}.
* @category time
*/
export interface ClockProps
extends SetTraitsNode,
SetTraitsSeek,
SetTraitsPlay {}
/**
* Normalized properties for {@link MathboxSelection.compose | compose}.
* @category rtt
*/
export interface ComposePropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsOperator,
GetTraitsStyle,
GetTraitsCompose {}
/**
* Properties for {@link MathboxSelection.compose | compose}.
* @category rtt
*/
export interface ComposeProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsOperator,
SetTraitsStyle,
SetTraitsCompose {}
/**
* Normalized properties for {@link MathboxSelection.dom | dom}.
* @category overlay
*/
export interface DomPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsOverlay,
GetTraitsDom,
GetTraitsAttach {}
/**
* Properties for {@link MathboxSelection.dom | dom}.
* @category overlay
*/
export interface DomProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsOverlay,
SetTraitsDom,
SetTraitsAttach {}
/**
* Normalized properties for {@link MathboxSelection.face | face}.
* @category draw
*/
export interface FacePropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsMesh,
GetTraitsFace,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.face | face}.
* @category draw
*/
export interface FaceProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsMesh,
SetTraitsFace,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.format | format}.
* @category text
*/
export interface FormatPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsTexture,
GetTraitsFormat,
GetTraitsFont {}
/**
* Properties for {@link MathboxSelection.format | format}.
* @category text
*/
export interface FormatProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsTexture,
SetTraitsFormat,
SetTraitsFont {}
/**
* Normalized properties for {@link MathboxSelection.fragment | fragment}.
* @category transform
*/
export interface FragmentPropsNormalized
extends GetTraitsNode,
GetTraitsInclude,
GetTraitsFragment {}
/**
* Properties for {@link MathboxSelection.fragment | fragment}.
* @category transform
*/
export interface FragmentProps
extends SetTraitsNode,
SetTraitsInclude,
SetTraitsFragment {}
/**
* Normalized properties for {@link MathboxSelection.grid | grid}.
* @category draw
*/
export interface GridPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsGrid,
GetTraitsArea,
GetTraitsOrigin {}
/**
* Properties for {@link MathboxSelection.grid | grid}.
* @category draw
*/
export interface GridProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsGrid,
SetTraitsArea,
SetTraitsOrigin {}
/**
* Normalized properties for {@link MathboxSelection.group | group}.
* @category base
*/
export interface GroupPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsEntity {}
/**
* Properties for {@link MathboxSelection.group | group}.
* @category base
*/
export interface GroupProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsEntity {}
/**
* Normalized properties for {@link MathboxSelection.grow | grow}.
* @category operator
*/
export interface GrowPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsGrow {}
/**
* Properties for {@link MathboxSelection.grow | grow}.
* @category operator
*/
export interface GrowProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsGrow {}
/**
* Normalized properties for {@link MathboxSelection.html | html}.
* @category overlay
*/
export interface HtmlPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsVoxel {}
/**
* Properties for {@link MathboxSelection.html | html}.
* @category overlay
*/
export interface HtmlProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsVoxel {}
/**
* Normalized properties for {@link MathboxSelection.inherit | inherit}.
* @category base
*/
export type InheritPropsNormalized = GetTraitsNode;
/**
* Properties for {@link MathboxSelection.inherit | inherit}.
* @category base
*/
export type InheritProps = SetTraitsNode;
/**
* Normalized properties for {@link MathboxSelection.interval | interval}.
* @category data
*/
export interface IntervalPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsTexture,
GetTraitsArray,
GetTraitsSpan,
GetTraitsInterval,
GetTraitsSampler {}
/**
* Properties for {@link MathboxSelection.interval | interval}.
* @category data
*/
export interface IntervalProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsTexture,
SetTraitsArray,
SetTraitsSpan,
SetTraitsInterval,
SetTraitsSampler {}
/**
* Normalized properties for {@link MathboxSelection.join | join}.
* @category operator
*/
export interface JoinPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsJoin {}
/**
* Properties for {@link MathboxSelection.join | join}.
* @category operator
*/
export interface JoinProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsJoin {}
/**
* Normalized properties for {@link MathboxSelection.label | label}.
* @category text
*/
export interface LabelPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLabel,
GetTraitsAttach,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.label | label}.
* @category text
*/
export interface LabelProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLabel,
SetTraitsAttach,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.layer | layer}.
* @category transform
*/
export interface LayerPropsNormalized
extends GetTraitsNode,
GetTraitsVertex,
GetTraitsLayer {}
/**
* Properties for {@link MathboxSelection.layer | layer}.
* @category transform
*/
export interface LayerProps
extends SetTraitsNode,
SetTraitsVertex,
SetTraitsLayer {}
/**
* Normalized properties for {@link MathboxSelection.lerp | lerp}.
* @category operator
*/
export interface LerpPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsLerp {}
/**
* Properties for {@link MathboxSelection.lerp | lerp}.
* @category operator
*/
export interface LerpProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsLerp {}
/**
* Normalized properties for {@link MathboxSelection.line | line}.
* @category draw
*/
export interface LinePropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsArrow,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.line | line}.
* @category draw
*/
export interface LineProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsArrow,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.mask | mask}.
* @category transform
*/
export interface MaskPropsNormalized extends GetTraitsNode, GetTraitsInclude {}
/**
* Properties for {@link MathboxSelection.mask | mask}.
* @category transform
*/
export interface MaskProps extends SetTraitsNode, SetTraitsInclude {}
/**
* Normalized properties for {@link MathboxSelection.matrix | matrix}.
* @category data
*/
export interface MatrixPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsTexture,
GetTraitsMatrix {}
/**
* Properties for {@link MathboxSelection.matrix | matrix}.
* @category data
*/
export interface MatrixProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsTexture,
SetTraitsMatrix {}
/**
* Normalized properties for {@link MathboxSelection.memo | memo}.
* @category operator
*/
export interface MemoPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsTexture {}
/**
* Properties for {@link MathboxSelection.memo | memo}.
* @category operator
*/
export interface MemoProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsTexture {}
/**
* Normalized properties for {@link MathboxSelection.move | move}.
* @category present
*/
export interface MovePropsNormalized
extends GetTraitsNode,
GetTraitsTransition,
GetTraitsVertex,
GetTraitsMove {}
/**
* Properties for {@link MathboxSelection.move | move}.
* @category present
*/
export interface MoveProps
extends SetTraitsNode,
SetTraitsTransition,
SetTraitsVertex,
SetTraitsMove {}
/**
* Normalized properties for {@link MathboxSelection.now | now}.
* @category time
*/
export interface NowPropsNormalized extends GetTraitsNode, GetTraitsNow {}
/**
* Properties for {@link MathboxSelection.now | now}.
* @category time
*/
export interface NowProps extends SetTraitsNode, SetTraitsNow {}
/**
* Normalized properties for {@link MathboxSelection.play | play}.
* @category present
*/
export interface PlayPropsNormalized
extends GetTraitsNode,
GetTraitsTrack,
GetTraitsTrigger,
GetTraitsPlay {}
/**
* Properties for {@link MathboxSelection.play | play}.
* @category present
*/
export interface PlayProps
extends SetTraitsNode,
SetTraitsTrack,
SetTraitsTrigger,
SetTraitsPlay {}
/**
* Normalized properties for {@link MathboxSelection.point | point}.
* @category draw
*/
export interface PointPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsPoint,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.point | point}.
* @category draw
*/
export interface PointProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsPoint,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.polar | polar}.
* @category view
*/
export interface PolarPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsView3,
GetTraitsPolar,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.polar | polar}.
* @category view
*/
export interface PolarProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsView3,
SetTraitsPolar,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.present | present}.
* @category present
*/
export interface PresentPropsNormalized
extends GetTraitsNode,
GetTraitsPresent {}
/**
* Properties for {@link MathboxSelection.present | present}.
* @category present
*/
export interface PresentProps extends SetTraitsNode, SetTraitsPresent {}
/**
* Normalized properties for {@link MathboxSelection.readback | readback}.
* @category operator
*/
export interface ReadbackPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsReadback,
GetTraitsEntity {}
/**
* Properties for {@link MathboxSelection.readback | readback}.
* @category operator
*/
export interface ReadbackProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsReadback,
SetTraitsEntity {}
/**
* Normalized properties for {@link MathboxSelection.repeat | repeat}.
* @category operator
*/
export interface RepeatPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsRepeat {}
/**
* Properties for {@link MathboxSelection.repeat | repeat}.
* @category operator
*/
export interface RepeatProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsRepeat {}
/**
* Normalized properties for {@link MathboxSelection.resample | resample}.
* @category operator
*/
export interface ResamplePropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsResample,
GetTraitsInclude {}
/**
* Properties for {@link MathboxSelection.resample | resample}.
* @category operator
*/
export interface ResampleProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsResample,
SetTraitsInclude {}
/**
* Normalized properties for {@link MathboxSelection.retext | retext}.
* @category text
*/
export interface RetextPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsResample,
GetTraitsInclude {}
/**
* Properties for {@link MathboxSelection.retext | retext}.
* @category text
*/
export interface RetextProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsResample,
SetTraitsInclude {}
/**
* Normalized properties for {@link MathboxSelection.reveal | reveal}.
* @category present
*/
export interface RevealPropsNormalized
extends GetTraitsNode,
GetTraitsTransition {}
/**
* Properties for {@link MathboxSelection.reveal | reveal}.
* @category present
*/
export interface RevealProps extends SetTraitsNode, SetTraitsTransition {}
/**
* Normalized properties for {@link MathboxSelection.root | root}.
* @category base
*/
export interface RootPropsNormalized
extends GetTraitsNode,
GetTraitsRoot,
GetTraitsVertex,
GetTraitsUnit {}
/**
* Properties for {@link MathboxSelection.root | root}.
* @category base
*/
export interface RootProps
extends SetTraitsNode,
SetTraitsRoot,
SetTraitsVertex,
SetTraitsUnit {}
/**
* Normalized properties for {@link MathboxSelection.rtt | rtt}.
* @category rtt
*/
export interface RttPropsNormalized
extends GetTraitsNode,
GetTraitsRoot,
GetTraitsVertex,
GetTraitsTexture,
GetTraitsRtt {}
/**
* Properties for {@link MathboxSelection.rtt | rtt}.
* @category rtt
*/
export interface RttProps
extends SetTraitsNode,
SetTraitsRoot,
SetTraitsVertex,
SetTraitsTexture,
SetTraitsRtt {}
/**
* Normalized properties for {@link MathboxSelection.scale | scale}.
* @category data
*/
export interface ScalePropsNormalized
extends GetTraitsNode,
GetTraitsInterval,
GetTraitsSpan,
GetTraitsScale,
GetTraitsOrigin {}
/**
* Properties for {@link MathboxSelection.scale | scale}.
* @category data
*/
export interface ScaleProps
extends SetTraitsNode,
SetTraitsInterval,
SetTraitsSpan,
SetTraitsScale,
SetTraitsOrigin {}
/**
* Normalized properties for {@link MathboxSelection.shader | shader}.
* @category shader
*/
export interface ShaderPropsNormalized extends GetTraitsNode, GetTraitsShader {}
/**
* Properties for {@link MathboxSelection.shader | shader}.
* @category shader
*/
export interface ShaderProps extends SetTraitsNode, SetTraitsShader {}
/**
* Normalized properties for {@link MathboxSelection.slice | slice}.
* @category operator
*/
export interface SlicePropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsSlice {}
/**
* Properties for {@link MathboxSelection.slice | slice}.
* @category operator
*/
export interface SliceProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsSlice {}
/**
* Normalized properties for {@link MathboxSelection.slide | slide}.
* @category present
*/
export interface SlidePropsNormalized extends GetTraitsNode, GetTraitsSlide {}
/**
* Properties for {@link MathboxSelection.slide | slide}.
* @category present
*/
export interface SlideProps extends SetTraitsNode, SetTraitsSlide {}
/**
* Normalized properties for {@link MathboxSelection.spherical | spherical}.
* @category view
*/
export interface SphericalPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsView3,
GetTraitsSpherical,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.spherical | spherical}.
* @category view
*/
export interface SphericalProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsView3,
SetTraitsSpherical,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.split | split}.
* @category operator
*/
export interface SplitPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsSplit {}
/**
* Properties for {@link MathboxSelection.split | split}.
* @category operator
*/
export interface SplitProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsSplit {}
/**
* Normalized properties for {@link MathboxSelection.spread | spread}.
* @category operator
*/
export interface SpreadPropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsSpread {}
/**
* Properties for {@link MathboxSelection.spread | spread}.
* @category operator
*/
export interface SpreadProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsSpread {}
/**
* Normalized properties for {@link MathboxSelection.step | step}.
* @category present
*/
export interface StepPropsNormalized
extends GetTraitsNode,
GetTraitsTrack,
GetTraitsStep,
GetTraitsTrigger {}
/**
* Properties for {@link MathboxSelection.step | step}.
* @category present
*/
export interface StepProps
extends SetTraitsNode,
SetTraitsTrack,
SetTraitsStep,
SetTraitsTrigger {}
/**
* Normalized properties for {@link MathboxSelection.stereographic | stereographic}.
* @category view
*/
export interface StereographicPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsView3,
GetTraitsStereographic,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.stereographic | stereographic}.
* @category view
*/
export interface StereographicProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsView3,
SetTraitsStereographic,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.stereographic4 | stereographic4}.
* @category view
*/
export interface Stereographic4PropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsView4,
GetTraitsStereographic,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.stereographic4 | stereographic4}.
* @category view
*/
export interface Stereographic4Props
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsView4,
SetTraitsStereographic,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.strip | strip}.
* @category draw
*/
export interface StripPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsMesh,
GetTraitsStrip,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.strip | strip}.
* @category draw
*/
export interface StripProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsMesh,
SetTraitsStrip,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.subdivide | subdivide}.
* @category operator
*/
export interface SubdividePropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsSubdivide {}
/**
* Properties for {@link MathboxSelection.subdivide | subdivide}.
* @category operator
*/
export interface SubdivideProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsSubdivide {}
/**
* Normalized properties for {@link MathboxSelection.surface | surface}.
* @category draw
*/
export interface SurfacePropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsMesh,
GetTraitsGeometry,
GetTraitsGrid {}
/**
* Properties for {@link MathboxSelection.surface | surface}.
* @category draw
*/
export interface SurfaceProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsMesh,
SetTraitsGeometry,
SetTraitsGrid {}
/**
* Normalized properties for {@link MathboxSelection.swizzle | swizzle}.
* @category operator
*/
export interface SwizzlePropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsSwizzle {}
/**
* Properties for {@link MathboxSelection.swizzle | swizzle}.
* @category operator
*/
export interface SwizzleProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsSwizzle {}
/**
* Normalized properties for {@link MathboxSelection.text | text}.
* @category text
*/
export interface TextPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsTexture,
GetTraitsVoxel,
GetTraitsFont {}
/**
* Properties for {@link MathboxSelection.text | text}.
* @category text
*/
export interface TextProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsTexture,
SetTraitsVoxel,
SetTraitsFont {}
/**
* Normalized properties for {@link MathboxSelection.ticks | ticks}.
* @category draw
*/
export interface TicksPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsTicks,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.ticks | ticks}.
* @category draw
*/
export interface TicksProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsTicks,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.transform | transform}.
* @category transform
*/
export interface TransformPropsNormalized
extends GetTraitsNode,
GetTraitsVertex,
GetTraitsTransform3 {}
/**
* Properties for {@link MathboxSelection.transform | transform}.
* @category transform
*/
export interface TransformProps
extends SetTraitsNode,
SetTraitsVertex,
SetTraitsTransform3 {}
/**
* Normalized properties for {@link MathboxSelection.transform4 | transform4}.
* @category transform
*/
export interface Transform4PropsNormalized
extends GetTraitsNode,
GetTraitsVertex,
GetTraitsTransform4 {}
/**
* Properties for {@link MathboxSelection.transform4 | transform4}.
* @category transform
*/
export interface Transform4Props
extends SetTraitsNode,
SetTraitsVertex,
SetTraitsTransform4 {}
/**
* Normalized properties for {@link MathboxSelection.transpose | transpose}.
* @category operator
*/
export interface TransposePropsNormalized
extends GetTraitsNode,
GetTraitsOperator,
GetTraitsTranspose {}
/**
* Properties for {@link MathboxSelection.transpose | transpose}.
* @category operator
*/
export interface TransposeProps
extends SetTraitsNode,
SetTraitsOperator,
SetTraitsTranspose {}
/**
* Normalized properties for {@link MathboxSelection.unit | unit}.
* @category base
*/
export interface UnitPropsNormalized extends GetTraitsNode, GetTraitsUnit {}
/**
* Properties for {@link MathboxSelection.unit | unit}.
* @category base
*/
export interface UnitProps extends SetTraitsNode, SetTraitsUnit {}
/**
* Normalized properties for {@link MathboxSelection.vector | vector}.
* @category draw
*/
export interface VectorPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsStyle,
GetTraitsLine,
GetTraitsArrow,
GetTraitsGeometry {}
/**
* Properties for {@link MathboxSelection.vector | vector}.
* @category draw
*/
export interface VectorProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsStyle,
SetTraitsLine,
SetTraitsArrow,
SetTraitsGeometry {}
/**
* Normalized properties for {@link MathboxSelection.vertex | vertex}.
* @category transform
*/
export interface VertexPropsNormalized
extends GetTraitsNode,
GetTraitsInclude,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.vertex | vertex}.
* @category transform
*/
export interface VertexProps
extends SetTraitsNode,
SetTraitsInclude,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.view | view}.
* @category view
*/
export interface ViewPropsNormalized
extends GetTraitsNode,
GetTraitsObject,
GetTraitsView,
GetTraitsVertex {}
/**
* Properties for {@link MathboxSelection.view | view}.
* @category view
*/
export interface ViewProps
extends SetTraitsNode,
SetTraitsObject,
SetTraitsView,
SetTraitsVertex {}
/**
* Normalized properties for {@link MathboxSelection.volume | volume}.
* @category data
*/
export interface VolumePropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsTexture,
GetTraitsVoxel,
GetTraitsVolume {}
/**
* Properties for {@link MathboxSelection.volume | volume}.
* @category data
*/
export interface VolumeProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsTexture,
SetTraitsVoxel,
SetTraitsVolume {}
/**
* Normalized properties for {@link MathboxSelection.voxel | voxel}.
* @category data
*/
export interface VoxelPropsNormalized
extends GetTraitsNode,
GetTraitsBuffer,
GetTraitsData,
GetTraitsTexture,
GetTraitsVoxel {}
/**
* Properties for {@link MathboxSelection.voxel | voxel}.
* @category data
*/
export interface VoxelProps
extends SetTraitsNode,
SetTraitsBuffer,
SetTraitsData,
SetTraitsTexture,
SetTraitsVoxel {}
| cchudzicki/mathbox | src/node_types.ts | TypeScript | mit | 85,385 |
import { DOM } from "./dom.js";
export const Classes = { dom: DOM };
| cchudzicki/mathbox | src/overlay/classes.js | JavaScript | mit | 70 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as VDOM from "../util/vdom.js";
import { Overlay } from "./overlay.js";
export class DOM extends Overlay {
static initClass() {
this.prototype.el = VDOM.element;
this.prototype.hint = VDOM.hint;
this.prototype.apply = VDOM.apply;
this.prototype.recycle = VDOM.recycle;
}
init(_options) {
return (this.last = null);
}
dispose() {
this.unmount();
return super.dispose();
}
mount() {
const overlay = document.createElement("div");
overlay.classList.add("mathbox-overlay");
this.element.appendChild(overlay);
return (this.overlay = overlay);
}
unmount(_overlay) {
if (this.overlay && this.overlay.parentNode) {
this.element.removeChild(this.overlay);
}
return (this.overlay = null);
}
render(el) {
// Lazy mounting
if (!this.overlay) {
this.mount();
}
// Wrap naked string or array in a div
if (["string", "number"].includes(typeof el)) {
el = this.el("div", null, el);
}
if (el instanceof Array) {
el = this.el("div", null, el);
}
// Create empty div if el is null
if (el == null) {
el = this.el("div");
}
// See if it can be mounted directly
const naked = el.type === "div";
// Fetch last DOM state
let { last } = this;
// Start with root node
const { overlay } = this;
const node = naked ? overlay : overlay.childNodes[0];
const parent = naked ? overlay.parentNode : overlay;
// Create phantom DOM state if mounting into existing element
if (!last && node) {
last = this.el("div");
}
// Update DOM
this.apply(el, last, node, parent, 0);
this.last = el;
// Recycle old descriptors
if (last != null) {
this.recycle(last);
}
}
}
DOM.initClass();
| cchudzicki/mathbox | src/overlay/dom.js | JavaScript | mit | 2,215 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
export class OverlayFactory {
constructor(classes, canvas) {
this.classes = classes;
this.canvas = canvas;
const div = document.createElement("div");
div.classList.add("mathbox-overlays");
this.div = div;
}
inject() {
const element = this.canvas.parentNode;
if (!element) {
throw new Error("Canvas not inserted into document.");
}
return element.insertBefore(this.div, this.canvas);
}
unject() {
const element = this.div.parentNode;
return element.removeChild(this.div);
}
getTypes() {
return Object.keys(this.classes);
}
make(type, options) {
return new this.classes[type](this.div, options);
}
}
| cchudzicki/mathbox | src/overlay/factory.js | JavaScript | mit | 986 |
export { OverlayFactory as Factory } from "./factory.js";
export * from "./classes.js";
export * from "./overlay.js";
| cchudzicki/mathbox | src/overlay/index.js | JavaScript | mit | 118 |
.mathbox-overlays {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
pointer-events: none;
transform-style: preserve-3d;
overflow: hidden;
}
.mathbox-overlays > div {
transform-style: preserve-3d;
}
.mathbox-overlay > div {
position: absolute;
will-change: transform, opacity;
}
.mathbox-label {
font-family: sans-serif;
}
.mathbox-outline-1 {
text-shadow: -1px -1px 0px rgb(255, 255, 255), 1px 1px 0px rgb(255, 255, 255),
-1px 1px 0px rgb(255, 255, 255), 1px -1px 0px rgb(255, 255, 255),
1px 0px 1px rgb(255, 255, 255), -1px 0px 1px rgb(255, 255, 255),
0px -1px 1px rgb(255, 255, 255), 0px 1px 1px rgb(255, 255, 255);
}
.mathbox-outline-2 {
text-shadow: 0px -2px 0px rgb(255, 255, 255), 0px 2px 0px rgb(255, 255, 255),
-2px 0px 0px rgb(255, 255, 255), 2px 0px 0px rgb(255, 255, 255),
-1px -2px 0px rgb(255, 255, 255), -2px -1px 0px rgb(255, 255, 255),
-1px 2px 0px rgb(255, 255, 255), -2px 1px 0px rgb(255, 255, 255),
1px 2px 0px rgb(255, 255, 255), 2px 1px 0px rgb(255, 255, 255),
1px -2px 0px rgb(255, 255, 255), 2px -1px 0px rgb(255, 255, 255);
}
.mathbox-outline-3 {
text-shadow: 3px 0px 0px rgb(255, 255, 255), -3px 0px 0px rgb(255, 255, 255),
0px 3px 0px rgb(255, 255, 255), 0px -3px 0px rgb(255, 255, 255),
-2px -2px 0px rgb(255, 255, 255), -2px 2px 0px rgb(255, 255, 255),
2px 2px 0px rgb(255, 255, 255), 2px -2px 0px rgb(255, 255, 255),
-1px -2px 1px rgb(255, 255, 255), -2px -1px 1px rgb(255, 255, 255),
-1px 2px 1px rgb(255, 255, 255), -2px 1px 1px rgb(255, 255, 255),
1px 2px 1px rgb(255, 255, 255), 2px 1px 1px rgb(255, 255, 255),
1px -2px 1px rgb(255, 255, 255), 2px -1px 1px rgb(255, 255, 255);
}
.mathbox-outline-4 {
text-shadow: 4px 0px 0px rgb(255, 255, 255), -4px 0px 0px rgb(255, 255, 255),
0px 4px 0px rgb(255, 255, 255), 0px -4px 0px rgb(255, 255, 255),
-3px -2px 0px rgb(255, 255, 255), -3px 2px 0px rgb(255, 255, 255),
3px 2px 0px rgb(255, 255, 255), 3px -2px 0px rgb(255, 255, 255),
-2px -3px 0px rgb(255, 255, 255), -2px 3px 0px rgb(255, 255, 255),
2px 3px 0px rgb(255, 255, 255), 2px -3px 0px rgb(255, 255, 255),
-1px -2px 1px rgb(255, 255, 255), -2px -1px 1px rgb(255, 255, 255),
-1px 2px 1px rgb(255, 255, 255), -2px 1px 1px rgb(255, 255, 255),
1px 2px 1px rgb(255, 255, 255), 2px 1px 1px rgb(255, 255, 255),
1px -2px 1px rgb(255, 255, 255), 2px -1px 1px rgb(255, 255, 255);
}
.mathbox-outline-fill,
.mathbox-outline-fill * {
color: #fff !important;
}
| cchudzicki/mathbox | src/overlay/overlay.css | CSS | mit | 2,521 |
export class Overlay {
constructor(element, options) {
this.element = element;
if (typeof this.init === "function") {
this.init(options);
}
}
dispose() {}
}
| cchudzicki/mathbox | src/overlay/overlay.js | JavaScript | mit | 182 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
export class PrimitiveFactory {
constructor(definitions, context) {
this.context = context;
this.classes = definitions.Classes;
this.helpers = definitions.Helpers;
}
getTypes() {
return Object.keys(this.classes);
}
make(type, options, binds = null) {
if (options == null) {
options = {};
}
const klass = this.classes[type];
if (klass == null) {
throw new Error(`Unknown primitive class \`${type}\``);
}
const node = new klass.model(
type,
klass.defaults,
options,
binds,
klass,
this.context.attributes
);
// NOTE: keep for side effects.
new klass(node, this.context, this.helpers);
return node;
}
}
| cchudzicki/mathbox | src/primitives/factory.js | JavaScript | mit | 1,081 |
import * as types from "./types";
export { PrimitiveFactory as Factory } from "./factory.js";
export * from "./primitive.js";
export const Types = types;
| cchudzicki/mathbox | src/primitives/index.js | JavaScript | mit | 155 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as Model from "../model";
import { Binder } from "threestrap/src/binder.js";
export class Primitive {
static initClass() {
this.Node = Model.Node;
this.Group = Model.Group;
// Class default
this.model = this.Node;
this.defaults = null;
this.traits = null;
this.props = null;
this.finals = null;
this.freeform = false;
}
constructor(node, _context, helpers) {
this.node = node;
this._context = _context;
this._renderables = this._context.renderables;
this._attributes = this._context.attributes;
this._shaders = this._context.shaders;
this._overlays = this._context.overlays;
this._animator = this._context.animator;
this._types = this._attributes.types;
// Link up node 1-to-1
this.node.controller = this;
// This node has been inserted/removed
this.node.on("added", (_event) => this._added());
this.node.on("removed", (_event) => this._removed());
// Property change (if mounted)
this.node.on("change", (event) => {
if (this._root) {
return this.change(event.changed, event.touched);
}
});
// Store local refs
this.reconfigure();
// Attribute getter / helpers
this._get = this.node.get.bind(this.node);
this._helpers = helpers(this, this.node.traits);
// Keep track of various handlers to do auto-cleanup on unmake()
this._handlers = { inherit: {}, listen: [], watch: [], compute: [] };
// Detached initially
this._root = this._parent = null;
// Friendly constructor
this.init();
}
is(trait) {
return this.traits.hash[trait];
}
// Primitive lifecycle
init() {}
make() {}
made() {}
unmake(_rebuild) {}
unmade() {}
change(_changed, _touched, _init) {}
// Force property reinit
refresh() {
return this.change({}, {}, true);
}
// Destroy and create cycle
rebuild() {
if (this._root) {
this._removed(true);
return this._added();
}
}
// Reconfigure traits/props
reconfigure(config) {
if (config != null) {
this.node.configure(config, this._attributes);
}
this.traits = this.node.traits;
return (this.props = this.node.props);
}
// This node has been inserted
_added() {
let e, left;
this._parent =
this.node.parent != null ? this.node.parent.controller : undefined;
this._root = this.node.root != null ? this.node.root.controller : undefined;
this.node.clock =
(left = this._inherit("clock")) != null ? left : this._root;
try {
try {
this.make();
this.refresh();
return this.made();
} catch (error) {
e = error;
this.node.print("warn");
console.error(e);
throw e;
}
} catch (error1) {
e = error1;
try {
return this._removed();
// eslint-disable-next-line no-empty
} catch (error2) {}
}
}
_removed(rebuild) {
if (rebuild == null) {
rebuild = false;
}
this.unmake(rebuild);
this._unlisten();
this._unattach();
this._uncompute();
this._root = null;
this._parent = null;
return this.unmade(rebuild);
}
// Bind event listeners to methods
_listen(object, type, method, self) {
if (self == null) {
self = this;
}
if (object instanceof Array) {
for (const o of Array.from(object)) {
return this.__listen(o, type, method, self);
}
}
return this.__listen(object, type, method, self);
}
__listen(object, type, method, self) {
if (self == null) {
self = this;
}
if (typeof object === "string") {
object = this._inherit(object);
}
if (object != null) {
const handler = method.bind(self);
handler.node = this.node;
object.on(type, handler);
this._handlers.listen.push([object, type, handler]);
}
return object;
}
_unlisten() {
if (!this._handlers.listen.length) {
return;
}
for (const [object, type, handler] of Array.from(this._handlers.listen)) {
object.off(type, handler);
}
return (this._handlers.listen = []);
}
// Find parent with certain trait
_inherit(trait) {
const cached = this._handlers.inherit[trait];
if (cached !== undefined) {
return cached;
}
return (this._handlers.inherit[trait] =
this._parent != null
? this._parent._find(trait != null ? trait : null)
: undefined);
}
_find(trait) {
if (this.is(trait)) {
return this;
}
return this._parent != null ? this._parent._find(trait) : undefined;
}
_uninherit() {
return (this._handlers.inherit = {});
}
// Attach to controller by trait and watch the selector
_attach(selector, trait, method, self, start, optional, multiple) {
if (self == null) {
self = this;
}
if (start == null) {
start = this;
}
if (optional == null) {
optional = false;
}
if (multiple == null) {
multiple = false;
}
const filter = function (node) {
if (node != null && Array.from(node.traits).includes(trait)) {
return node;
}
};
const map = (node) => (node != null ? node.controller : undefined);
const flatten = function (list) {
if (list == null) {
return list;
}
let out = [];
for (const sub of Array.from(list)) {
if (sub instanceof Array) {
out = out.concat(sub);
} else {
out.push(sub);
}
}
return out;
};
const resolve = (selector) => {
// Direct JS binding, no watcher.
let node, nodes;
if (typeof selector === "object") {
node = selector;
// API object
if (node != null ? node._up : undefined) {
selector = multiple ? node._targets : [node[0]];
return selector;
}
// Array of things
if (node instanceof Array) {
selector = multiple ? flatten(node.map(resolve)) : resolve(node[0]);
return selector;
}
// Node
if (node instanceof Model.Node) {
return [node];
}
// Auto-link selector '<'
} else if (typeof selector === "string" && selector[0] === "<") {
let match;
let discard = 0;
if ((match = selector.match(/^<([0-9])+$/))) {
discard = +match[1] - 1;
}
if (selector.match(/^<+$/)) {
discard = +selector.length - 1;
}
nodes = [];
// Implicitly associated node (scan backwards until we find one)
let previous = start.node;
while (previous) {
// Find previous node
const { parent } = previous;
if (!parent) {
break;
}
previous = parent.children[previous.index - 1];
// If we reached the first child, ascend if nothing found yet
if (!previous && !nodes.length) {
previous = parent;
}
// Include if matched
node = null;
if (filter(previous)) {
node = previous;
}
if (node != null && discard-- <= 0) {
nodes.push(node);
}
// Return solo match
if (!multiple && nodes.length) {
return nodes;
}
}
// Return list match
if (multiple && nodes.length) {
return nodes;
}
// Selector binding
} else if (typeof selector === "string") {
const watcher = method.bind(self);
this._handlers.watch.push(watcher);
const selection = this._root.watch(selector, watcher);
if (!multiple) {
if (filter(selection[0])) {
node = selection[0];
}
if (node != null) {
return [node];
}
} else {
nodes = selection.filter(filter);
if (nodes.length) {
return nodes;
}
}
}
// Nothing found
if (!optional) {
console.warn(this.node.toMarkup());
throw new Error(
`${this.node.toString()} - Could not find ${trait} \`${selector}\``
);
}
if (multiple) {
return [];
} else {
return null;
}
};
// Resolve selection recursively
const nodes = flatten(resolve(selector));
// Return node's controllers if found
if (multiple) {
if (nodes != null) {
return nodes.map(map);
} else {
return null;
}
} else {
if (nodes != null) {
return map(nodes[0]);
} else {
return null;
}
}
}
// Remove watcher attachments
_unattach() {
if (!this._handlers.watch.length) {
return;
}
for (const watcher of Array.from(this._handlers.watch)) {
if (watcher != null) {
watcher.unwatch();
}
}
return (this._handlers.watch = []);
}
// Bind a computed value to a prop
_compute(key, expr) {
this._handlers.compute.push(key);
return this.node.bind(key, expr, true);
}
// Remove prop bindings
_uncompute() {
if (!this._handlers.compute.length) {
return;
}
for (const key of Array.from(this._handlers.compute)) {
this.node.unbind(key, true);
}
return (this._handlers.compute = []);
}
}
Primitive.initClass();
Binder.apply(Primitive.prototype);
| cchudzicki/mathbox | src/primitives/primitive.js | JavaScript | mit | 9,934 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "./parent.js";
export class Group extends Parent {
static initClass() {
this.traits = ["node", "object", "entity", "visible", "active"];
}
make() {
this._helpers.visible.make();
return this._helpers.active.make();
}
unmake() {
this._helpers.visible.unmake();
return this._helpers.active.unmake();
}
}
Group.initClass();
| cchudzicki/mathbox | src/primitives/types/base/group.js | JavaScript | mit | 740 |
export * from "./group.js";
export * from "./inherit.js";
export * from "./root.js";
export * from "./unit.js";
| cchudzicki/mathbox | src/primitives/types/base/index.js | JavaScript | mit | 112 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "./parent.js";
export class Inherit extends Parent {
static initClass() {
this.traits = ["node", "bind"];
}
make() {
// Bind to attached trait source
return this._helpers.bind.make([{ to: "inherit.source", trait: "node" }]);
}
unmake() {
return this._helpers.bind.unmake();
}
_find(trait) {
if (this.bind.source && Array.from(this.props.traits).includes(trait)) {
return this.bind.source._inherit(trait);
}
return super._find();
}
}
Inherit.initClass();
| cchudzicki/mathbox | src/primitives/types/base/inherit.js | JavaScript | mit | 940 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Primitive } from "../../primitive.js";
export class Parent extends Primitive {
static initClass() {
this.model = Primitive.Group;
this.traits = ["node"];
}
}
Parent.initClass();
| cchudzicki/mathbox | src/primitives/types/base/parent.js | JavaScript | mit | 492 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "./parent.js";
export class Root extends Parent {
static initClass() {
this.traits = ["node", "root", "clock", "scene", "vertex", "unit"];
}
init() {
this.size = null;
this.cameraEvent = { type: "root.camera" };
this.preEvent = { type: "root.pre" };
this.updateEvent = { type: "root.update" };
this.renderEvent = { type: "root.render" };
this.postEvent = { type: "root.post" };
this.clockEvent = { type: "clock.tick" };
return (this.camera = null);
}
make() {
return this._helpers.unit.make();
}
unmake() {
return this._helpers.unit.unmake();
}
change(changed, touched, init) {
if (changed["root.camera"] || init) {
this._unattach();
this._attach(
this.props.camera,
"camera",
this.setCamera,
this,
this,
true
);
return this.setCamera();
}
}
adopt(renderable) {
return Array.from(renderable.renders).map((object) =>
this._context.scene.add(object)
);
}
unadopt(renderable) {
return Array.from(renderable.renders).map((object) =>
this._context.scene.remove(object)
);
}
select(selector) {
return this.node.model.select(selector);
}
watch(selector, handler) {
return this.node.model.watch(selector, handler);
}
unwatch(handler) {
return this.node.model.unwatch(handler);
}
resize(size) {
this.size = size;
return this.trigger({
type: "root.resize",
size,
});
}
getSize() {
return this.size;
}
getSpeed() {
return this.props.speed;
}
getUnit() {
return this._helpers.unit.get();
}
getUnitUniforms() {
return this._helpers.unit.uniforms();
}
pre() {
this.getCamera().updateProjectionMatrix();
this.trigger(this.clockEvent);
return this.trigger(this.preEvent);
}
update() {
return this.trigger(this.updateEvent);
}
render() {
return this.trigger(this.renderEvent);
}
post() {
return this.trigger(this.postEvent);
}
setCamera() {
const camera = __guard__(
this.select(this.props.camera)[0],
(x) => x.controller
);
if (this.camera !== camera) {
this.camera = camera;
return this.trigger({ type: "root.camera" });
}
}
getCamera() {
let left;
return (left = this.camera != null ? this.camera.getCamera() : undefined) !=
null
? left
: this._context.defaultCamera;
}
getTime() {
return this._context.time;
}
// End transform chain here
vertex(shader, pass) {
if (pass === 2) {
return shader.pipe("view.position");
}
if (pass === 3) {
return shader.pipe("root.position");
}
return shader;
}
}
Root.initClass();
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/base/root.js | JavaScript | mit | 3,495 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as GLSL from "../../../util/glsl.js";
import { Primitive } from "../../primitive.js";
export class Source extends Primitive {
static initClass() {
this.traits = ["node", "source", "index"];
}
made() {
// Notify of buffer reallocation
return this.trigger({
type: "source.rebuild",
});
}
indexShader(shader) {
return shader.pipe(GLSL.identity("vec4"));
}
sourceShader(shader) {
return shader.pipe(GLSL.identity("vec4"));
}
getDimensions() {
return {
items: 1,
width: 1,
height: 1,
depth: 1,
};
}
getActiveDimensions() {
return this.getDimensions();
}
getIndexDimensions() {
return this.getActiveDimensions();
}
getFutureDimensions() {
return this.getActiveDimensions();
}
}
Source.initClass();
| cchudzicki/mathbox | src/primitives/types/base/source.js | JavaScript | mit | 1,176 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "./parent.js";
export class Unit extends Parent {
static initClass() {
this.traits = ["node", "unit"];
}
make() {
return this._helpers.unit.make();
}
unmake() {
return this._helpers.unit.unmake();
}
getUnit() {
return this._helpers.unit.get();
}
getUnitUniforms() {
return this._helpers.unit.uniforms();
}
}
Unit.initClass();
| cchudzicki/mathbox | src/primitives/types/base/unit.js | JavaScript | mit | 684 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UThree from "../../../util/three.js";
import { Euler } from "three/src/math/Euler.js";
import { Primitive } from "../../primitive.js";
import { Quaternion } from "three/src/math/Quaternion.js";
export class Camera extends Primitive {
static initClass() {
this.traits = ["node", "camera"];
}
init() {}
make() {
const camera = this._context.defaultCamera;
this.camera = this.props.proxy ? camera : camera.clone();
this.euler = new Euler();
return (this.quat = new Quaternion());
}
unmake() {}
getCamera() {
return this.camera;
}
change(changed, touched, init) {
if (
changed["camera.position"] ||
changed["camera.quaternion"] ||
changed["camera.rotation"] ||
changed["camera.lookAt"] ||
changed["camera.up"] ||
changed["camera.fov"] ||
init
) {
const { position, quaternion, rotation, lookAt, up, fov } = this.props;
// Apply transform conservatively to avoid conflicts with controls / proxy
if (position != null) {
this.camera.position.copy(position);
}
if (quaternion != null || rotation != null || lookAt != null) {
if (lookAt != null) {
this.camera.lookAt(lookAt);
} else {
this.camera.quaternion.set(0, 0, 0, 1);
}
if (rotation != null) {
this.euler.setFromVector3(
rotation,
UThree.swizzleToEulerOrder(this.props.eulerOrder)
);
this.quat.setFromEuler(this.euler);
this.camera.quaternion.multiply(this.quat);
}
if (quaternion != null) {
this.camera.quaternion.multiply(quaternion);
}
}
if (fov != null && this.camera.fov != null) {
this.camera.fov = fov;
}
if (up != null) {
this.camera.up.copy(up);
}
return this.camera.updateMatrix();
}
}
}
Camera.initClass();
| cchudzicki/mathbox | src/primitives/types/camera/camera.js | JavaScript | mit | 2,346 |
export * from "./camera.js";
| cchudzicki/mathbox | src/primitives/types/camera/index.js | JavaScript | mit | 29 |
/* eslint-disable sort-imports */
import { Group, Inherit, Root, Unit } from "./base";
import { Camera } from "./camera";
import { Area, Array_, Interval, Matrix, Scale, Volume, Voxel } from "./data";
import {
Axis,
Face,
Grid,
Line,
Point,
Strip,
Surface,
Ticks,
Vector,
} from "./draw";
import { DOM, HTML } from "./overlay";
import { Format, Label, Retext, Text } from "./text";
import { Clock, Now } from "./time";
import {
Fragment,
Layer,
Mask,
Transform3,
Transform4,
Vertex,
} from "./transform";
import {
Clamp,
Grow,
Join,
Lerp,
Memo,
Readback,
Repeat,
Resample,
Slice,
Split,
Spread,
Subdivide,
Swizzle,
Transpose,
} from "./operator";
import { Move, Play, Present, Reveal, Slide, Step } from "./present";
import { Compose, RTT } from "./rtt";
import {
Cartesian,
Cartesian4,
Polar,
Spherical,
Stereographic,
Stereographic4,
View,
} from "./view";
import { Shader } from "./shader";
export const Classes = {
axis: Axis,
face: Face,
grid: Grid,
line: Line,
point: Point,
strip: Strip,
surface: Surface,
ticks: Ticks,
vector: Vector,
view: View,
cartesian: Cartesian,
cartesian4: Cartesian4,
polar: Polar,
spherical: Spherical,
stereographic: Stereographic,
stereographic4: Stereographic4,
transform: Transform3,
transform4: Transform4,
vertex: Vertex,
fragment: Fragment,
layer: Layer,
mask: Mask,
array: Array_,
interval: Interval,
matrix: Matrix,
area: Area,
voxel: Voxel,
volume: Volume,
scale: Scale,
html: HTML,
dom: DOM,
text: Text,
format: Format,
label: Label,
retext: Retext,
clamp: Clamp,
grow: Grow,
join: Join,
lerp: Lerp,
memo: Memo,
readback: Readback,
resample: Resample,
repeat: Repeat,
swizzle: Swizzle,
spread: Spread,
split: Split,
slice: Slice,
subdivide: Subdivide,
transpose: Transpose,
group: Group,
inherit: Inherit,
root: Root,
unit: Unit,
shader: Shader,
camera: Camera,
rtt: RTT,
compose: Compose,
clock: Clock,
now: Now,
move: Move,
play: Play,
present: Present,
reveal: Reveal,
slide: Slide,
step: Step,
};
| cchudzicki/mathbox | src/primitives/types/classes.js | JavaScript | mit | 2,162 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Matrix } from "./matrix.js";
export class Area extends Matrix {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"matrix",
"texture",
"raw",
"span:x",
"span:y",
"area",
"sampler:x",
"sampler:y",
];
}
updateSpan() {
let inverseX, inverseY;
const dimensions = this.props.axes;
let { width } = this.props;
let { height } = this.props;
const { centeredX } = this.props;
const { centeredY } = this.props;
const padX = this.props.paddingX;
const padY = this.props.paddingY;
const rangeX = this._helpers.span.get("x.", dimensions[0]);
const rangeY = this._helpers.span.get("y.", dimensions[1]);
this.aX = rangeX.x;
this.aY = rangeY.x;
const spanX = rangeX.y - rangeX.x;
const spanY = rangeY.y - rangeY.x;
width += padX * 2;
height += padY * 2;
if (centeredX) {
inverseX = 1 / Math.max(1, width);
this.aX += (spanX * inverseX) / 2;
} else {
inverseX = 1 / Math.max(1, width - 1);
}
if (centeredY) {
inverseY = 1 / Math.max(1, height);
this.aY += (spanY * inverseY) / 2;
} else {
inverseY = 1 / Math.max(1, height - 1);
}
this.bX = spanX * inverseX;
this.bY = spanY * inverseY;
this.aX += padX * this.bX;
return (this.aY += padY * this.bY);
}
callback(callback) {
this.updateSpan();
if (this.last === callback) {
return this._callback;
}
this.last = callback;
if (callback.length <= 5) {
return (this._callback = (emit, i, j) => {
const x = this.aX + this.bX * i;
const y = this.aY + this.bY * j;
return callback(emit, x, y, i, j);
});
} else {
return (this._callback = (emit, i, j) => {
const x = this.aX + this.bX * i;
const y = this.aY + this.bY * j;
return callback(emit, x, y, i, j, this.bufferClock, this.bufferStep);
});
}
}
make() {
super.make();
this._helpers.span.make();
return this._listen(this, "span.range", this.updateSpan);
}
unmake() {
super.unmake();
return this._helpers.span.unmake();
}
}
Area.initClass();
| cchudzicki/mathbox | src/primitives/types/data/area.js | JavaScript | mit | 2,628 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../../util/data.js";
import { Buffer } from "./buffer.js";
export class Array_ extends Buffer {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"array",
"texture",
"raw",
];
}
init() {
this.buffer = this.spec = null;
this.space = {
width: 0,
history: 0,
};
this.used = { width: 0 };
this.storage = "arrayBuffer";
this.passthrough = (emit, x) => emit(x, 0, 0, 0);
return super.init();
}
sourceShader(shader) {
const dims = this.getDimensions();
this.alignShader(dims, shader);
return this.buffer.shader(shader);
}
getDimensions() {
return {
items: this.items,
width: this.space.width,
height: this.space.history,
depth: 1,
};
}
getActiveDimensions() {
return {
items: this.items,
width: this.used.width,
height: this.buffer.getFilled(),
depth: 1,
};
}
getFutureDimensions() {
return {
items: this.items,
width: this.used.width,
height: this.space.history,
depth: 1,
};
}
getRawDimensions() {
return {
items: this.items,
width: this.space.width,
height: 1,
depth: 1,
};
}
make() {
super.make();
// Read sampling parameters
const minFilter =
this.minFilter != null ? this.minFilter : this.props.minFilter;
const magFilter =
this.magFilter != null ? this.magFilter : this.props.magFilter;
const type = this.type != null ? this.type : this.props.type;
// Read given dimensions
const { width } = this.props;
const { history } = this.props;
const reserve = this.props.bufferWidth;
const { channels } = this.props;
const { items } = this.props;
let dims = (this.spec = { channels, items, width });
this.items = dims.items;
this.channels = dims.channels;
// Init to right size if data supplied
const { data } = this.props;
dims = UData.getDimensions(data, dims);
const { space } = this;
space.width = Math.max(reserve, dims.width || 1);
space.history = history;
// Create array buffer
return (this.buffer = this._renderables.make(this.storage, {
width: space.width,
history: space.history,
channels,
items,
minFilter,
magFilter,
type,
}));
}
unmake() {
super.unmake();
if (this.buffer) {
this.buffer.dispose();
return (this.buffer = this.spec = null);
}
}
change(changed, touched, init) {
if (
touched["texture"] ||
changed["history.history"] ||
changed["buffer.channels"] ||
changed["buffer.items"] ||
changed["array.bufferWidth"]
) {
return this.rebuild();
}
if (!this.buffer) {
return;
}
if (changed["array.width"]) {
const { width } = this.props;
if (width > this.space.width) {
return this.rebuild();
}
}
if (
changed["data.map"] ||
changed["data.data"] ||
changed["data.resolve"] ||
changed["data.expr"] ||
init
) {
return this.buffer.setCallback(this.emitter());
}
}
callback(callback) {
if (callback.length <= 2) {
return callback;
} else {
return (emit, i) => {
return callback(emit, i, this.bufferClock, this.bufferStep);
};
}
}
update() {
if (!this.buffer) {
return;
}
const { data } = this.props;
const { space, used } = this;
const l = used.width;
const filled = this.buffer.getFilled();
this.syncBuffer((abort) => {
if (data != null) {
const dims = UData.getDimensions(data, this.spec);
// Grow width if needed
if (dims.width > space.width) {
abort();
return this.rebuild();
}
used.width = dims.width;
this.buffer.setActive(used.width);
if (typeof this.buffer.callback.rebind === "function") {
this.buffer.callback.rebind(data);
}
return this.buffer.update();
} else {
let width = this.spec.width || 1;
this.buffer.setActive(width);
width = this.buffer.update();
return (used.width = width);
}
});
if (used.width !== l || filled !== this.buffer.getFilled()) {
return this.trigger({
type: "source.resize",
});
}
}
}
Array_.initClass();
| cchudzicki/mathbox | src/primitives/types/data/array.js | JavaScript | mit | 4,922 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS202: Simplify dynamic range loops
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Data } from "./data.js";
export class Buffer extends Data {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"texture",
];
}
init() {
this.bufferSlack = 0;
this.bufferFrames = 0;
this.bufferTime = 0;
this.bufferDelta = 0;
this.bufferClock = 0;
this.bufferStep = 0;
super.init();
}
make() {
super.make();
return (this.clockParent = this._inherit("clock"));
}
unmake() {
return super.unmake();
}
rawBuffer() {
return this.buffer;
}
emitter() {
const { channels, items } = this.props;
return super.emitter(channels, items);
}
change(changed, touched, init) {
if (changed["buffer.fps"] || init) {
const { fps } = this.props;
return (this.bufferSlack = fps ? 0.5 / fps : 0);
}
}
syncBuffer(callback) {
let delta, step;
if (!this.buffer) {
return;
}
const { live, fps, hurry, limit, realtime, observe } = this.props;
const filled = this.buffer.getFilled();
if (!!filled && !live) {
return;
}
const time = this.clockParent.getTime();
if (fps != null) {
const slack = this.bufferSlack;
const speed = time.step / time.delta;
delta = realtime ? time.delta : time.step;
const frame = 1 / fps;
step = realtime && observe ? speed * frame : frame;
this.bufferSlack = Math.min(limit / fps, slack + delta);
this.bufferDelta = delta;
this.bufferStep = step;
let frames = Math.min(hurry, Math.floor(slack * fps));
if (!filled) {
frames = Math.max(1, frames);
}
let stop = false;
const abort = () => (stop = true);
return (() => {
const result = [];
for (
let i = 0, end = frames, asc = 0 <= end;
asc ? i < end : i > end;
asc ? i++ : i--
) {
this.bufferTime += delta;
this.bufferClock += step;
if (stop) {
break;
}
callback(abort, this.bufferFrames++, i, frames);
result.push((this.bufferSlack -= frame));
}
return result;
})();
} else {
this.bufferTime = time.time;
this.bufferDelta = time.delta;
this.bufferClock = time.clock;
this.bufferStep = time.step;
return callback(function () {}, this.bufferFrames++, 0, 1);
}
}
alignShader(dims, shader) {
const { minFilter, magFilter, aligned } = this.props;
const mixed =
(dims.items > 1 && dims.width > 1) || (dims.height > 1 && dims.depth > 1);
if (aligned || !mixed) {
return;
}
const nearest =
minFilter === this.node.attributes["texture.minFilter"].enum.nearest &&
magFilter === this.node.attributes["texture.magFilter"].enum.nearest;
if (!nearest) {
console.warn(
`${this.node.toString()} - Cannot use linear min/magFilter with 3D/4D sampling`
);
}
return shader.pipe("map.xyzw.align");
}
}
Buffer.initClass();
| cchudzicki/mathbox | src/primitives/types/data/buffer.js | JavaScript | mit | 3,591 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../../util/data.js";
import { Source } from "../base/source.js";
export class Data extends Source {
static initClass() {
this.traits = ["node", "data", "source", "index", "entity", "active"];
}
init() {
this.dataEmitter = null;
return (this.dataSizes = null);
}
emitter(channels, items) {
let emitter, resolve;
const { data, bind, expr } = this.props;
if (data != null) {
// Make new emitter if data geometry doesn't match
const last = this.dataSizes;
const sizes = UData.getSizes(data);
if (!last || last.length !== sizes.length) {
// Create data thunk to copy (multi-)array
const thunk = UData.getThunk(data);
this.dataEmitter = this.callback(
UData.makeEmitter(thunk, items, channels)
);
this.dataSizes = sizes;
}
emitter = this.dataEmitter;
} else if (resolve != null) {
// Hook up data-bound expression to its source
resolve = this._inherit("resolve");
emitter = this.callback(resolve.callback(bind));
} else if (expr != null) {
// Convert given free expression to appropriate callback
emitter = this.callback(expr);
} else {
// Passthrough
emitter = this.callback(this.passthrough);
}
return emitter;
}
callback(callback) {
return callback != null ? callback : function () {};
}
update() {}
make() {
this._helpers.active.make();
// Always run update at least once to prime JS VM optimization for entering elements
this.first = true;
return this._listen("root", "root.update", () => {
if (this.isActive || this.first) {
this.update();
}
return (this.first = false);
});
}
unmake() {
this._helpers.active.unmake();
this.dataEmitter = null;
return (this.dataSizes = null);
}
}
Data.initClass();
| cchudzicki/mathbox | src/primitives/types/data/data.js | JavaScript | mit | 2,314 |
export * from "./array.js";
export * from "./interval.js";
export * from "./matrix.js";
export * from "./area.js";
export * from "./voxel.js";
export * from "./volume.js";
export * from "./scale.js";
| cchudzicki/mathbox | src/primitives/types/data/index.js | JavaScript | mit | 200 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Array_ } from "./array.js";
export class Interval extends Array_ {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"texture",
"array",
"span",
"interval",
"sampler",
"raw",
];
}
updateSpan() {
let inverse;
const dimension = this.props.axis;
let { width } = this.props;
const { centered } = this.props;
const pad = this.props.padding;
const range = this._helpers.span.get("", dimension);
width += pad * 2;
this.a = range.x;
const span = range.y - range.x;
if (centered) {
inverse = 1 / Math.max(1, width);
this.a += (span * inverse) / 2;
} else {
inverse = 1 / Math.max(1, width - 1);
}
this.b = span * inverse;
return (this.a += pad * this.b);
}
callback(callback) {
this.updateSpan();
if (this.last === callback) {
return this._callback;
}
this.last = callback;
if (callback.length <= 3) {
return (this._callback = (emit, i) => {
const x = this.a + this.b * i;
return callback(emit, x, i);
});
} else {
return (this._callback = (emit, i) => {
const x = this.a + this.b * i;
return callback(emit, x, i, this.bufferClock, this.bufferStep);
});
}
}
make() {
super.make();
this._helpers.span.make();
return this._listen(this, "span.range", this.updateSpan);
}
unmake() {
super.unmake();
return this._helpers.span.unmake();
}
}
Interval.initClass();
| cchudzicki/mathbox | src/primitives/types/data/interval.js | JavaScript | mit | 1,958 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../../util/data.js";
import { Buffer } from "./buffer.js";
export class Matrix extends Buffer {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"texture",
"matrix",
"raw",
];
}
init() {
this.buffer = this.spec = null;
this.space = {
width: 0,
height: 0,
history: 0,
};
this.used = {
width: 0,
height: 0,
};
this.storage = "matrixBuffer";
this.passthrough = (emit, x, y) => emit(x, y, 0, 0);
return super.init();
}
sourceShader(shader) {
const dims = this.getDimensions();
this.alignShader(dims, shader);
return this.buffer.shader(shader);
}
getDimensions() {
return {
items: this.items,
width: this.space.width,
height: this.space.height,
depth: this.space.history,
};
}
getActiveDimensions() {
return {
items: this.items,
width: this.used.width,
height: this.used.height,
depth: this.buffer.getFilled(),
};
}
getFutureDimensions() {
return {
items: this.items,
width: this.used.width,
height: this.used.height,
depth: this.space.history,
};
}
getRawDimensions() {
return {
items: this.items,
width: this.space.width,
height: this.space.height,
depth: 1,
};
}
make() {
super.make();
// Read sampling parameters
const minFilter =
this.minFilter != null ? this.minFilter : this.props.minFilter;
const magFilter =
this.magFilter != null ? this.magFilter : this.props.magFilter;
const type = this.type != null ? this.type : this.props.type;
// Read given dimensions
const { width } = this.props;
const { height } = this.props;
const { history } = this.props;
const reserveX = this.props.bufferWidth;
const reserveY = this.props.bufferHeight;
const { channels } = this.props;
const { items } = this.props;
let dims = (this.spec = { channels, items, width, height });
this.items = dims.items;
this.channels = dims.channels;
// Init to right size if data supplied
const { data } = this.props;
dims = UData.getDimensions(data, dims);
const { space } = this;
space.width = Math.max(reserveX, dims.width || 1);
space.height = Math.max(reserveY, dims.height || 1);
space.history = history;
// Create matrix buffer
return (this.buffer = this._renderables.make(this.storage, {
width: space.width,
height: space.height,
history: space.history,
channels,
items,
minFilter,
magFilter,
type,
}));
}
unmake() {
super.unmake();
if (this.buffer) {
this.buffer.dispose();
return (this.buffer = this.spec = null);
}
}
change(changed, touched, init) {
if (
touched["texture"] ||
changed["matrix.history"] ||
changed["buffer.channels"] ||
changed["buffer.items"] ||
changed["matrix.bufferWidth"] ||
changed["matrix.bufferHeight"]
) {
return this.rebuild();
}
if (!this.buffer) {
return;
}
if (changed["matrix.width"]) {
const { width } = this.props;
if (width > this.space.width) {
return this.rebuild();
}
}
if (changed["matrix.height"]) {
const { height } = this.props;
if (height > this.space.height) {
return this.rebuild();
}
}
if (
changed["data.map"] ||
changed["data.data"] ||
changed["data.resolve"] ||
changed["data.expr"] ||
init
) {
return this.buffer.setCallback(this.emitter());
}
}
callback(callback) {
if (callback.length <= 3) {
return callback;
} else {
return (emit, i, j) => {
return callback(emit, i, j, this.bufferClock, this.bufferStep);
};
}
}
update() {
if (!this.buffer) {
return;
}
const { data } = this.props;
const { space, used } = this;
const w = used.width;
const h = used.height;
const filled = this.buffer.getFilled();
this.syncBuffer((abort) => {
if (data != null) {
const dims = UData.getDimensions(data, this.spec);
// Grow if needed
if (dims.width > space.width || dims.height > space.height) {
abort();
return this.rebuild();
}
used.width = dims.width;
used.height = dims.height;
this.buffer.setActive(used.width, used.height);
if (typeof this.buffer.callback.rebind === "function") {
this.buffer.callback.rebind(data);
}
return this.buffer.update();
} else {
let _w;
const width = this.spec.width || 1;
const height = this.spec.height || 1;
this.buffer.setActive(width, height);
const length = this.buffer.update();
used.width = _w = width;
used.height = Math.ceil(length / _w);
if (used.height === 1) {
return (used.width = length);
}
}
});
if (
used.width !== w ||
used.height !== h ||
filled !== this.buffer.getFilled()
) {
return this.trigger({
type: "source.resize",
});
}
}
}
Matrix.initClass();
| cchudzicki/mathbox | src/primitives/types/data/matrix.js | JavaScript | mit | 5,766 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../../util/data.js";
import { Data } from "./data.js";
export class Resolve extends Data {
static initClass() {
this.traits = ["node", "data", "active", "source", "index", "voxel"];
}
init() {
this.buffer = this.spec = null;
this.space = {
width: 0,
height: 0,
depth: 0,
};
this.used = {
width: 0,
height: 0,
depth: 0,
};
return super.init();
}
sourceShader(shader) {
return this.buffer.shader(shader);
}
getDimensions() {
const { space } = this;
return {
items: this.items,
width: space.width,
height: space.height,
depth: space.depth,
};
}
getActiveDimensions() {
const { used } = this;
return {
items: this.items,
width: used.width,
height: used.height,
depth: used.depth * this.buffer.getFilled(),
};
}
make() {
super.make();
// Read given dimensions
const { width } = this.props;
const { height } = this.props;
const { depth } = this.props;
const reserveX = this.props.bufferWidth;
const reserveY = this.props.bufferHeight;
const reserveZ = this.props.bufferDepth;
let dims = (this.spec = { channels: 1, items: 1, width, height, depth });
// Init to right size if data supplied
const { data } = this.props;
dims = UData.getDimensions(data, dims);
const { space } = this;
space.width = Math.max(reserveX, dims.width || 1);
space.height = Math.max(reserveY, dims.height || 1);
space.depth = Math.max(reserveZ, dims.depth || 1);
if (this.spec.width == null) {
this.spec.width = 1;
}
if (this.spec.height == null) {
this.spec.height = 1;
}
if (this.spec.depth == null) {
this.spec.depth = 1;
}
// Create voxel buffer to hold item state
// (enter, exit)
return (this.buffer = this._renderables.make("voxelBuffer", {
width: space.width,
height: space.height,
depth: space.depth,
channels: 2,
items: 1,
}));
}
// Decorate emit callback for a bound source
callback() {}
//
emitter() {
return super.emitter(1, 1);
}
change(changed, touched, init) {
super.change();
if (!this.buffer) {
return;
}
if (changed["voxel.width"]) {
const { width } = this.props;
if (width > this.space.width) {
return this.rebuild();
}
}
if (changed["voxel.height"]) {
const { height } = this.props;
if (height > this.space.height) {
return this.rebuild();
}
}
if (changed["voxel.depth"]) {
const { depth } = this.props;
if (depth > this.space.depth) {
return this.rebuild();
}
}
if (
changed["data.map"] ||
changed["data.data"] ||
changed["data.resolve"] ||
init
) {
return this.buffer.setCallback(this.emitter());
}
}
update() {
let length;
if (!this.buffer) {
return;
}
const filled = this.buffer.getFilled();
if (!!filled && !this.props.live) {
return;
}
const { data } = this.props;
const { space } = this;
const { used } = this;
const l = used.length;
if (data != null) {
const dims = UData.getDimensions(data, this.spec);
// Grow length if needed
if (dims.width > space.length) {
this.rebuild();
}
used.length = dims.width;
this.buffer.setActive(used.length);
this.buffer.callback.rebind(data);
this.buffer.update();
} else {
this.buffer.setActive(this.spec.width);
length = this.buffer.update();
used.length = length;
}
this.filled = true;
if (used.length !== l || filled !== this.buffer.getFilled()) {
return this.trigger({
type: "source.resize",
});
}
}
}
Resolve.initClass();
| cchudzicki/mathbox | src/primitives/types/data/resolve.js | JavaScript | mit | 4,308 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UAxis from "../../../util/axis.js";
import { Source } from "../base/source.js";
export class Scale extends Source {
static initClass() {
this.traits = [
"node",
"source",
"index",
"interval",
"span",
"scale",
"raw",
"origin",
];
}
init() {
return (this.used = this.space = this.scaleAxis = this.sampler = null);
}
rawBuffer() {
return this.buffer;
}
sourceShader(shader) {
return shader.pipe(this.sampler);
}
getDimensions() {
return {
items: 1,
width: this.space,
height: 1,
depth: 1,
};
}
getActiveDimensions() {
return {
items: 1,
width: this.used,
height: this.buffer.getFilled(),
depth: 1,
};
}
getRawDimensions() {
return this.getDimensions();
}
make() {
// Prepare data buffer of tick positions
let samples;
this.space = samples = this._helpers.scale.divide("");
this.buffer = this._renderables.make("dataBuffer", {
width: samples,
channels: 1,
items: 1,
});
// Prepare position shader
const positionUniforms = {
scaleAxis: this._attributes.make(this._types.vec4()),
scaleOffset: this._attributes.make(this._types.vec4()),
};
this.scaleAxis = positionUniforms.scaleAxis.value;
this.scaleOffset = positionUniforms.scaleOffset.value;
// Build sampler
const p = (this.sampler = this._shaders.shader());
// Require buffer sampler as callback
p.require(this.buffer.shader(this._shaders.shader(), 1));
// Shader to expand scalars to 4D vector on an axis.
p.pipe("scale.position", positionUniforms);
this._helpers.span.make();
// Monitor view range
return this._listen(this, "span.range", this.updateRanges);
}
unmake() {
this.scaleAxis = null;
return this._helpers.span.unmake();
}
change(changed, touched, init) {
if (changed["scale.divide"]) {
return this.rebuild();
}
if (
touched["view"] ||
touched["interval"] ||
touched["span"] ||
touched["scale"] ||
init
) {
return this.updateRanges();
}
}
updateRanges() {
const { used } = this;
// Fetch range along axis
const { axis, origin } = this.props;
const range = this._helpers.span.get("", axis);
// Calculate scale along axis
const min = range.x;
const max = range.y;
const ticks = this._helpers.scale.generate("", this.buffer, min, max);
UAxis.setDimension(this.scaleAxis, axis);
UAxis.setOrigin(this.scaleOffset, axis, origin);
// Clip to number of ticks
this.used = ticks.length;
// Notify of resize
if (this.used !== used) {
return this.trigger({
type: "source.resize",
});
}
}
}
Scale.initClass();
| cchudzicki/mathbox | src/primitives/types/data/scale.js | JavaScript | mit | 3,192 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Voxel } from "./voxel.js";
export class Volume extends Voxel {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"texture",
"voxel",
"span:x",
"span:y",
"span:z",
"volume",
"sampler:x",
"sampler:y",
"sampler:z",
"raw",
];
}
updateSpan() {
let inverseX, inverseY, inverseZ;
const dimensions = this.props.axes;
let { width } = this.props;
let { height } = this.props;
let { depth } = this.props;
const { centeredX } = this.props;
const { centeredY } = this.props;
const { centeredZ } = this.props;
const padX = this.props.paddingX;
const padY = this.props.paddingY;
const padZ = this.props.paddingZ;
const rangeX = this._helpers.span.get("x.", dimensions[0]);
const rangeY = this._helpers.span.get("y.", dimensions[1]);
const rangeZ = this._helpers.span.get("z.", dimensions[2]);
this.aX = rangeX.x;
this.aY = rangeY.x;
this.aZ = rangeZ.x;
const spanX = rangeX.y - rangeX.x;
const spanY = rangeY.y - rangeY.x;
const spanZ = rangeZ.y - rangeZ.x;
width += padX * 2;
height += padY * 2;
depth += padZ * 2;
if (centeredX) {
inverseX = 1 / Math.max(1, width);
this.aX += (spanX * inverseX) / 2;
} else {
inverseX = 1 / Math.max(1, width - 1);
}
if (centeredY) {
inverseY = 1 / Math.max(1, height);
this.aY += (spanY * inverseY) / 2;
} else {
inverseY = 1 / Math.max(1, height - 1);
}
if (centeredZ) {
inverseZ = 1 / Math.max(1, depth);
this.aZ += (spanZ * inverseZ) / 2;
} else {
inverseZ = 1 / Math.max(1, depth - 1);
}
this.bX = spanX * inverseX;
this.bY = spanY * inverseY;
this.bZ = spanZ * inverseZ;
this.aX += this.bX * padX;
this.aY += this.bY * padY;
return (this.aZ += this.bZ * padY);
}
callback(callback) {
this.updateSpan();
if (this.last === callback) {
return this._callback;
}
this.last = callback;
if (callback.length <= 7) {
return (this._callback = (emit, i, j, k) => {
const x = this.aX + this.bX * i;
const y = this.aY + this.bY * j;
const z = this.aZ + this.bZ * k;
return callback(emit, x, y, z, i, j, k);
});
} else {
return (this._callback = (emit, i, j, k) => {
const x = this.aX + this.bX * i;
const y = this.aY + this.bY * j;
const z = this.aZ + this.bZ * k;
return callback(
emit,
x,
y,
z,
i,
j,
k,
this.bufferClock,
this.bufferStep
);
});
}
}
make() {
super.make();
this._helpers.span.make();
return this._listen(this, "span.range", this.updateSpan);
}
unmake() {
super.unmake();
return this._helpers.span.unmake();
}
}
Volume.initClass();
| cchudzicki/mathbox | src/primitives/types/data/volume.js | JavaScript | mit | 3,363 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS002: Fix invalid constructor
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../../util/data.js";
import { Buffer } from "./buffer.js";
export class Voxel extends Buffer {
constructor(...args) {
super(...args);
this.update = this.update.bind(this);
}
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"texture",
"voxel",
"raw",
];
}
init() {
this.buffer = this.spec = null;
this.space = {
width: 0,
height: 0,
depth: 0,
};
this.used = {
width: 0,
height: 0,
depth: 0,
};
this.storage = "voxelBuffer";
this.passthrough = (emit, x, y, z) => emit(x, y, z, 0);
super.init();
}
sourceShader(shader) {
const dims = this.getDimensions();
this.alignShader(dims, shader);
return this.buffer.shader(shader);
}
getDimensions() {
return {
items: this.items,
width: this.space.width,
height: this.space.height,
depth: this.space.depth,
};
}
getActiveDimensions() {
return {
items: this.items,
width: this.used.width,
height: this.used.height,
depth: this.used.depth * this.buffer.getFilled(),
};
}
getRawDimensions() {
return this.getDimensions();
}
make() {
super.make();
// Read sampling parameters
const minFilter =
this.minFilter != null ? this.minFilter : this.props.minFilter;
const magFilter =
this.magFilter != null ? this.magFilter : this.props.magFilter;
const type = this.type != null ? this.type : this.props.type;
// Read given dimensions
const { width } = this.props;
const { height } = this.props;
const { depth } = this.props;
const reserveX = this.props.bufferWidth;
const reserveY = this.props.bufferHeight;
const reserveZ = this.props.bufferDepth;
const { channels } = this.props;
const { items } = this.props;
let dims = (this.spec = { channels, items, width, height, depth });
this.items = dims.items;
this.channels = dims.channels;
// Init to right size if data supplied
const { data } = this.props;
dims = UData.getDimensions(data, dims);
const { space } = this;
space.width = Math.max(reserveX, dims.width || 1);
space.height = Math.max(reserveY, dims.height || 1);
space.depth = Math.max(reserveZ, dims.depth || 1);
// Create voxel buffer
return (this.buffer = this._renderables.make(this.storage, {
width: space.width,
height: space.height,
depth: space.depth,
channels,
items,
minFilter,
magFilter,
type,
}));
}
unmake() {
super.unmake();
if (this.buffer) {
this.buffer.dispose();
return (this.buffer = this.spec = null);
}
}
change(changed, touched, init) {
if (
touched["texture"] ||
changed["buffer.channels"] ||
changed["buffer.items"] ||
changed["voxel.bufferWidth"] ||
changed["voxel.bufferHeight"] ||
changed["voxel.bufferDepth"]
) {
return this.rebuild();
}
if (!this.buffer) {
return;
}
if (changed["voxel.width"]) {
const { width } = this.props;
if (width > this.space.width) {
return this.rebuild();
}
}
if (changed["voxel.height"]) {
const { height } = this.props;
if (height > this.space.height) {
return this.rebuild();
}
}
if (changed["voxel.depth"]) {
const { depth } = this.props;
if (depth > this.space.depth) {
return this.rebuild();
}
}
if (
changed["data.map"] ||
changed["data.data"] ||
changed["data.resolve"] ||
changed["data.expr"] ||
init
) {
return this.buffer.setCallback(this.emitter());
}
}
callback(callback) {
if (callback.length <= 4) {
return callback;
} else {
return (emit, i, j, k) => {
return callback(emit, i, j, k, this.bufferClock, this.bufferStep);
};
}
}
update() {
if (!this.buffer) {
return;
}
const { data } = this.props;
const { space, used } = this;
const w = used.width;
const h = used.height;
const d = used.depth;
const filled = this.buffer.getFilled();
this.syncBuffer((abort) => {
if (data != null) {
const dims = UData.getDimensions(data, this.spec);
// Grow dimensions if needed
if (
dims.width > space.width ||
dims.height > space.height ||
dims.depth > space.depth
) {
abort();
return this.rebuild();
}
used.width = dims.width;
used.height = dims.height;
used.depth = dims.depth;
this.buffer.setActive(used.width, used.height, used.depth);
if (typeof this.buffer.callback.rebind === "function") {
this.buffer.callback.rebind(data);
}
return this.buffer.update();
} else {
let _h, _w;
const width = this.spec.width || 1;
const height = this.spec.height || 1;
const depth = this.spec.depth || 1;
this.buffer.setActive(width, height, depth);
const length = this.buffer.update();
used.width = _w = width;
used.height = _h = height;
used.depth = Math.ceil(length / _w / _h);
if (used.depth === 1) {
used.height = Math.ceil(length / _w);
if (used.height === 1) {
return (used.width = length);
}
}
}
});
if (
used.width !== w ||
used.height !== h ||
used.depth !== d ||
filled !== this.buffer.getFilled()
) {
return this.trigger({
type: "source.resize",
});
}
}
}
Voxel.initClass();
| cchudzicki/mathbox | src/primitives/types/data/voxel.js | JavaScript | mit | 6,247 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UAxis from "../../../util/axis.js";
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Axis extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"axis",
"span",
"interval",
"arrow",
"position",
"origin",
"shade",
];
this.defaults = {
end: true,
zBias: -1,
};
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.axisPosition =
this.axisStep =
this.resolution =
this.line =
this.arrows =
null;
}
make() {
// Prepare position shader
const positionUniforms = {
axisPosition: this._attributes.make(this._types.vec4()),
axisStep: this._attributes.make(this._types.vec4()),
};
this.axisPosition = positionUniforms.axisPosition.value;
this.axisStep = positionUniforms.axisStep.value;
// Build transform chain
let position = this._shaders.shader();
position.pipe("axis.position", positionUniforms);
position = this._helpers.position.pipeline(position);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const arrowUniforms = this._helpers.arrow.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Line geometry
const { detail } = this.props;
const samples = detail + 1;
this.resolution = 1 / detail;
// Clip start/end for terminating arrow
const { start, end } = this.props;
// Stroke style
const { stroke, join } = this.props;
// Build transition mask lookup
let mask = this._helpers.object.mask();
// Build fragment material lookup
const material = this._helpers.shade.pipeline() || false;
// Indexing by fixed or by given axis
const { crossed, axis } = this.props;
if (!crossed && mask != null && axis > 1) {
const swizzle = ["x000", "y000", "z000", "w000"][axis];
mask = this._helpers.position.swizzle(mask, swizzle);
}
// Make line renderable
const uniforms = UJS.merge(
arrowUniforms,
lineUniforms,
styleUniforms,
unitUniforms
);
this.line = this._renderables.make("line", {
uniforms,
samples,
position,
clip: start || end,
stroke,
join,
mask,
material,
});
// Make arrow renderables
this.arrows = [];
if (start) {
this.arrows.push(
this._renderables.make("arrow", {
uniforms,
flip: true,
samples,
position,
mask,
material,
})
);
}
if (end) {
this.arrows.push(
this._renderables.make("arrow", {
uniforms,
samples,
position,
mask,
material,
})
);
}
// Visible, object and span traits
this._helpers.visible.make();
this._helpers.object.make(this.arrows.concat([this.line]));
this._helpers.span.make();
// Monitor view range
return this._listen(this, "span.range", this.updateRanges);
}
unmake() {
this._helpers.visible.unmake();
this._helpers.object.unmake();
return this._helpers.span.unmake();
}
change(changed, touched, init) {
if (
changed["axis.detail"] ||
changed["line.stroke"] ||
changed["line.join"] ||
changed["axis.crossed"] ||
(changed["interval.axis"] && this.props.crossed)
) {
return this.rebuild();
}
if (touched["interval"] || touched["span"] || touched["view"] || init) {
return this.updateRanges();
}
}
updateRanges() {
const { axis, origin } = this.props;
const range = this._helpers.span.get("", axis);
const min = range.x;
const max = range.y;
UAxis.setDimension(this.axisPosition, axis).multiplyScalar(min);
UAxis.setDimension(this.axisStep, axis).multiplyScalar(
(max - min) * this.resolution
);
return UAxis.addOrigin(this.axisPosition, axis, origin);
}
}
Axis.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/axis.js | JavaScript | mit | 4,609 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Face extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"mesh",
"face",
"geometry",
"position",
"bind",
"shade",
];
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.face = null;
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const { items, width, height, depth } = dims;
if (this.face) {
this.face.geometry.clip(width, height, depth, items);
}
if (this.line) {
this.line.geometry.clip(items, width, height, depth);
}
if (this.bind.map != null) {
const map = this.bind.map.getActiveDimensions();
if (this.face) {
return this.face.geometry.map(
map.width,
map.height,
map.depth,
map.items
);
}
}
}
make() {
// Bind to attached data sources
let color, uniforms;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
{ to: "mesh.map", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Fetch position and transform to view
let position = this.bind.points.sourceShader(this._shaders.shader());
position = this._helpers.position.pipeline(position);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Auto z-bias wireframe over surface
const wireUniforms = {};
wireUniforms.styleZBias = this._attributes.make(this._types.number());
this.wireZBias = wireUniforms.styleZBias;
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const { items, width, height, depth } = dims;
// Get display properties
const { line, shaded, fill, stroke, join } = this.props;
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Build texture map lookup
const map = this._helpers.shade.map(
this.bind.map != null
? this.bind.map.sourceShader(this._shaders.shader())
: undefined
);
// Build fragment material lookup
const material = this._helpers.shade.pipeline();
const faceMaterial = material || shaded;
const lineMaterial = material || false;
const objects = [];
// Make line renderable
if (line) {
// Swizzle face edges into segments
const swizzle = this._shaders.shader();
swizzle.pipe(UGLSL.swizzleVec4("yzwx"));
swizzle.pipe(position);
uniforms = UJS.merge(
unitUniforms,
lineUniforms,
styleUniforms,
wireUniforms
);
this.line = this._renderables.make("line", {
uniforms,
samples: items,
strips: width,
ribbons: height,
layers: depth,
position: swizzle,
color,
stroke,
join,
material: lineMaterial,
mask,
closed: true,
});
objects.push(this.line);
}
// Make face renderable
if (fill) {
uniforms = UJS.merge(unitUniforms, styleUniforms, {});
this.face = this._renderables.make("face", {
uniforms,
width,
height,
depth,
items,
position,
color,
material: faceMaterial,
mask,
map,
});
objects.push(this.face);
}
this._helpers.visible.make();
return this._helpers.object.make(objects);
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
return (this.face = this.line = null);
}
change(changed, touched, init) {
if (changed["geometry.points"] || touched["mesh"]) {
return this.rebuild();
}
if (changed["style.zBias"] || changed["mesh.lineBias"] || init) {
const { fill, zBias, lineBias } = this.props;
return (this.wireZBias.value = zBias + (fill ? lineBias : 0));
}
}
}
Face.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/face.js | JavaScript | mit | 4,986 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UAxis from "../../../util/axis.js";
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Grid extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"grid",
"area",
"position",
"origin",
"shade",
"axis:x",
"axis:y",
"scale:x",
"scale:y",
"span:x",
"span:y",
];
this.defaults = {
width: 1,
zBias: -2,
};
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.axes = null;
}
make() {
// Build transition mask lookup
let axis;
let mask = this._helpers.object.mask();
// Build fragment material lookup
const material = this._helpers.shade.pipeline() || false;
axis = (first, second, transpose) => {
// Prepare data buffer of tick positions
let position;
const detail = this._get(first + "axis.detail");
const samples = detail + 1;
const resolution = 1 / detail;
const strips = this._helpers.scale.divide(second);
const buffer = this._renderables.make("dataBuffer", {
width: strips,
channels: 1,
});
// Prepare position shader
const positionUniforms = {
gridPosition: this._attributes.make(this._types.vec4()),
gridStep: this._attributes.make(this._types.vec4()),
gridAxis: this._attributes.make(this._types.vec4()),
};
const values = {
gridPosition: positionUniforms.gridPosition.value,
gridStep: positionUniforms.gridStep.value,
gridAxis: positionUniforms.gridAxis.value,
};
// Build transform chain
const p = (position = this._shaders.shader());
// Align second grid with first in mask space if requested
if (transpose != null && mask != null) {
mask = this._helpers.position.swizzle(mask, transpose);
}
// Require buffer sampler as callback
p.require(buffer.shader(this._shaders.shader(), 2));
// Calculate grid position
p.pipe("grid.position", positionUniforms);
// Apply view transform
position = this._helpers.position.pipeline(p);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
const uniforms = UJS.merge(lineUniforms, styleUniforms, unitUniforms);
// Make line renderable
const line = this._renderables.make("line", {
uniforms,
samples,
strips,
position,
stroke,
join,
mask,
material,
});
// Store axis object for manipulation later
return { first, second, resolution, samples, line, buffer, values };
};
// Generate both line sets
const { lineX, lineY, crossed, axes } = this.props;
const transpose = ["0000", "x000", "y000", "z000", "w000"][axes[1]];
// Stroke style
const { stroke, join } = this.props;
this.axes = [];
lineX && this.axes.push(axis("x.", "y.", null));
lineY && this.axes.push(axis("y.", "x.", crossed ? null : transpose));
// Register lines
const lines = (() => {
const result = [];
for (axis of this.axes) {
result.push(axis.line);
}
return result;
})();
this._helpers.visible.make();
this._helpers.object.make(lines);
this._helpers.span.make();
// Monitor view range
return this._listen(this, "span.range", this.updateRanges);
}
unmake() {
this._helpers.visible.unmake();
this._helpers.object.unmake();
this._helpers.span.unmake();
for (const axis of this.axes) {
axis.buffer.dispose();
}
this.axes = null;
}
change(changed, touched, init) {
if (
changed["x.axis.detail"] ||
changed["y.axis.detail"] ||
changed["x.axis.factor"] ||
changed["y.axis.factor"] ||
changed["grid.lineX"] ||
changed["grid.lineY"] ||
changed["line.stroke"] ||
changed["line.join"] ||
changed["grid.crossed"] ||
(changed["grid.axes"] && this.props.crossed)
) {
return this.rebuild();
}
if (
touched["x"] ||
touched["y"] ||
touched["area"] ||
touched["grid"] ||
touched["view"] ||
init
) {
return this.updateRanges();
}
}
updateRanges() {
const axis = (x, y, range1, range2, axis) => {
const { second, resolution, samples, line, buffer, values } = axis;
// Set line steps along first axis
let min = range1.x;
let max = range1.y;
UAxis.setDimension(values.gridPosition, x).multiplyScalar(min);
UAxis.setDimension(values.gridStep, x).multiplyScalar(
(max - min) * resolution
);
// Add origin on remaining two axes
UAxis.addOrigin(values.gridPosition, axes, origin);
// Calculate scale along second axis
min = range2.x;
max = range2.y;
const ticks = this._helpers.scale.generate(second, buffer, min, max);
UAxis.setDimension(values.gridAxis, y);
// Clip to number of ticks
const n = ticks.length;
return line.geometry.clip(samples, n, 1, 1);
};
// Fetch grid range in both dimensions
const { axes, origin } = this.props;
const range1 = this._helpers.span.get("x.", axes[0]);
const range2 = this._helpers.span.get("y.", axes[1]);
// Update both line sets
const { lineX, lineY } = this.props;
if (lineX) {
axis(axes[0], axes[1], range1, range2, this.axes[0]);
}
if (lineY) {
axis(axes[1], axes[0], range2, range1, this.axes[+lineX]);
}
window.cake1 = this.axes[0].buffer;
window.cake2 = this.axes[1].buffer;
window.cake3 = this.axes[0];
}
}
Grid.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/grid.js | JavaScript | mit | 6,450 |
export * from "./axis.js";
export * from "./face.js";
export * from "./grid.js";
export * from "./line.js";
export * from "./point.js";
export * from "./strip.js";
export * from "./surface.js";
export * from "./ticks.js";
export * from "./vector.js";
| cchudzicki/mathbox | src/primitives/types/draw/index.js | JavaScript | mit | 251 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Line extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"arrow",
"geometry",
"position",
"bind",
"shade",
];
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.line = this.arrows = null;
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const samples = dims.width;
const strips = dims.height;
const ribbons = dims.depth;
const layers = dims.items;
this.line.geometry.clip(samples, strips, ribbons, layers);
return Array.from(this.arrows).map((arrow) =>
arrow.geometry.clip(samples, strips, ribbons, layers)
);
}
make() {
// Bind to attached data sources
let color;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Build transform chain
let position = this._shaders.shader();
// Fetch position
position = this.bind.points.sourceShader(position);
// Transform position to view
position = this._helpers.position.pipeline(position);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const arrowUniforms = this._helpers.arrow.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Clip start/end for terminating arrow
const { start, end } = this.props;
// Stroke style
const { stroke, join, proximity } = this.props;
this.proximity = proximity;
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const samples = dims.width;
const strips = dims.height;
const ribbons = dims.depth;
const layers = dims.items;
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Build fragment material lookup
const material = this._helpers.shade.pipeline() || false;
// Make line renderable
const uniforms = UJS.merge(
arrowUniforms,
lineUniforms,
styleUniforms,
unitUniforms
);
this.line = this._renderables.make("line", {
uniforms,
samples,
strips,
ribbons,
layers,
position,
color,
clip: start || end,
stroke,
join,
proximity,
mask,
material,
});
// Make arrow renderables
this.arrows = [];
if (start) {
this.arrows.push(
this._renderables.make("arrow", {
uniforms,
flip: true,
samples,
strips,
ribbons,
layers,
position,
color,
mask,
material,
})
);
}
if (end) {
this.arrows.push(
this._renderables.make("arrow", {
uniforms,
samples,
strips,
ribbons,
layers,
position,
color,
mask,
material,
})
);
}
this._helpers.visible.make();
return this._helpers.object.make(this.arrows.concat([this.line]));
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
return (this.line = this.arrows = null);
}
change(changed, _touched, _init) {
if (
changed["geometry.points"] ||
changed["line.stroke"] ||
changed["line.join"] ||
changed["arrow.start"] ||
changed["arrow.end"]
) {
return this.rebuild();
}
if (changed["line.proximity"]) {
if ((this.proximity != null) !== (this.props.proximity != null)) {
return this.rebuild();
}
}
}
}
Line.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/line.js | JavaScript | mit | 4,641 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Point extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"point",
"geometry",
"position",
"bind",
"shade",
];
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.point = null;
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const { items, width, height, depth } = dims;
return this.point.geometry.clip(width, height, depth, items);
}
make() {
// Bind to attached data sources
let color, size;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
{ to: "point.sizes", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Build transform chain
let position = this._shaders.shader();
// Fetch position and transform to view
position = this.bind.points.sourceShader(position);
position = this._helpers.position.pipeline(position);
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const { items, width, height, depth } = dims;
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const pointUniforms = this._helpers.point.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build size lookup
if (this.bind.sizes) {
size = this._shaders.shader();
this.bind.sizes.sourceShader(size);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Build fragment material lookup
const material = this._helpers.shade.pipeline() || false;
// Point style
const { shape } = this.props;
const { fill } = this.props;
const { optical } = this.props;
// Make point renderable
const uniforms = UJS.merge(unitUniforms, pointUniforms, styleUniforms);
this.point = this._renderables.make("point", {
uniforms,
width,
height,
depth,
items,
position,
color,
size,
shape,
optical,
fill,
mask,
material,
});
this._helpers.visible.make();
this._helpers.object.make([this.point]);
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
this.point = null;
}
change(changed, _touched, _init) {
if (
changed["geometry.points"] ||
changed["point.shape"] ||
changed["point.fill"]
) {
return this.rebuild();
}
}
}
Point.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/point.js | JavaScript | mit | 3,402 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Strip extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"mesh",
"strip",
"geometry",
"position",
"bind",
"shade",
];
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.strip = null;
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const { items, width, height, depth } = dims;
if (this.strip) {
this.strip.geometry.clip(width, height, depth, items);
}
if (this.line) {
this.line.geometry.clip(items, width, height, depth);
}
if (this.bind.map != null) {
const map = this.bind.map.getActiveDimensions();
if (this.strip) {
return this.strip.geometry.map(
map.width,
map.height,
map.depth,
map.items
);
}
}
}
make() {
// Bind to attached data sources
let color, uniforms;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
{ to: "mesh.map", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Build transform chain
let position = this._shaders.shader();
// Fetch position
position = this.bind.points.sourceShader(position);
// Transform position to view
position = this._helpers.position.pipeline(position);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Get display properties
const { line, shaded, fill, stroke, join } = this.props;
// Auto z-bias wireframe over surface
const wireUniforms = {};
wireUniforms.styleZBias = this._attributes.make(this._types.number());
this.wireZBias = wireUniforms.styleZBias;
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const { items, width, height, depth } = dims;
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
color = this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Build texture map lookup
this._helpers.shade.map(
this.bind.map != null
? this.bind.map.sourceShader(this._shaders.shader())
: undefined
);
// Build fragment material lookup
const material = this._helpers.shade.pipeline();
const faceMaterial = material || shaded;
const lineMaterial = material || false;
const objects = [];
// Make line renderable
if (line) {
// Swizzle strip edges into segments
const swizzle = this._shaders.shader();
swizzle.pipe(UGLSL.swizzleVec4("yzwx"));
swizzle.pipe(position);
uniforms = UJS.merge(
unitUniforms,
lineUniforms,
styleUniforms,
wireUniforms
);
this.line = this._renderables.make("line", {
uniforms,
samples: items,
strips: width,
ribbons: height,
layers: depth,
position: swizzle,
color,
stroke,
join,
mask,
material: lineMaterial,
});
objects.push(this.line);
}
// Make strip renderable
if (fill) {
uniforms = UJS.merge(styleUniforms, {});
this.strip = this._renderables.make("strip", {
uniforms,
width,
height,
depth,
items,
position,
color,
material: faceMaterial,
});
objects.push(this.strip);
}
this._helpers.visible.make();
return this._helpers.object.make(objects);
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
return (this.strip = null);
}
change(changed, touched, init) {
if (changed["geometry.points"] || touched["mesh"]) {
return this.rebuild();
}
if (changed["style.zBias"] || changed["mesh.lineBias"] || init) {
const { fill, zBias, lineBias } = this.props;
return (this.wireZBias.value = zBias + (fill ? lineBias : 0));
}
}
}
Strip.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/strip.js | JavaScript | mit | 4,992 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UJS from "../../../util/js.js";
import { Color } from "three/src/math/Color.js";
import { Primitive } from "../../primitive.js";
export class Surface extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"mesh",
"geometry",
"surface",
"position",
"grid",
"bind",
"shade",
];
this.defaults = {
lineX: false,
lineY: false,
};
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.lineX = this.lineY = this.surface = null;
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const { width, height, depth, items } = dims;
if (this.surface) {
this.surface.geometry.clip(width, height, depth, items);
}
if (this.lineX) {
this.lineX.geometry.clip(width, height, depth, items);
}
if (this.lineY) {
this.lineY.geometry.clip(height, width, depth, items);
}
if (this.bind.map != null) {
const map = this.bind.map.getActiveDimensions();
if (this.surface) {
return this.surface.geometry.map(
map.width,
map.height,
map.depth,
map.items
);
}
}
}
make() {
// Bind to attached data sources
let color;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
{ to: "mesh.map", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Build transform chain
let position = this._shaders.shader();
// Fetch position and transform to view
position = this.bind.points.sourceShader(position);
position = this._helpers.position.pipeline(position);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const wireUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const surfaceUniforms = this._helpers.surface.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Darken wireframe if needed for contrast
// Auto z-bias wireframe over surface
wireUniforms.styleColor = this._attributes.make(this._types.color());
wireUniforms.styleZBias = this._attributes.make(this._types.number());
this.wireColor = wireUniforms.styleColor.value;
this.wireZBias = wireUniforms.styleZBias;
this.wireScratch = new Color();
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const { width, height, depth, items } = dims;
// Get display properties
const {
shaded,
fill,
lineX,
lineY,
closedX,
closedY,
stroke,
join,
proximity,
crossed,
} = this.props;
const objects = [];
this.proximity = proximity;
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Build texture map lookup
const map = this._helpers.shade.map(
this.bind.map != null
? this.bind.map.sourceShader(this._shaders.shader())
: undefined
);
// Build fragment material lookup
const material = this._helpers.shade.pipeline();
const faceMaterial = material || shaded;
const lineMaterial = material || false;
// Make line and surface renderables
const { swizzle, swizzle2 } = this._helpers.position;
let uniforms = UJS.merge(
unitUniforms,
lineUniforms,
styleUniforms,
wireUniforms
);
const zUnits = lineX || lineY ? -50 : 0;
if (lineX) {
this.lineX = this._renderables.make("line", {
uniforms,
samples: width,
strips: height,
ribbons: depth,
layers: items,
position,
color,
zUnits: -zUnits,
stroke,
join,
mask,
material: lineMaterial,
proximity,
closed: closedX || closed,
});
objects.push(this.lineX);
}
if (lineY) {
this.lineY = this._renderables.make("line", {
uniforms,
samples: height,
strips: width,
ribbons: depth,
layers: items,
position: swizzle2(position, "yxzw", "yxzw"),
color: swizzle(color, "yxzw"),
zUnits: -zUnits,
stroke,
join,
mask: swizzle(mask, crossed ? "xyzw" : "yxzw"),
material: lineMaterial,
proximity,
closed: closedY || closed,
});
objects.push(this.lineY);
}
if (fill) {
uniforms = UJS.merge(unitUniforms, surfaceUniforms, styleUniforms);
this.surface = this._renderables.make("surface", {
uniforms,
width,
height,
surfaces: depth,
layers: items,
position,
color,
zUnits,
stroke,
material: faceMaterial,
mask,
map,
intUV: true,
closedX: closedX || closed,
closedY: closedY || closed,
});
objects.push(this.surface);
}
this._helpers.visible.make();
return this._helpers.object.make(objects);
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
return (this.lineX = this.lineY = this.surface = null);
}
_convertGammaToLinear(color, gammaFactor = 2.0) {
color.r = Math.pow(color.r, gammaFactor);
color.g = Math.pow(color.g, gammaFactor);
color.b = Math.pow(color.b, gammaFactor);
return color;
}
_convertLinearToGamma(color, gammaFactor = 2.0) {
const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
color.r = Math.pow(color.r, safeInverse);
color.g = Math.pow(color.g, safeInverse);
color.b = Math.pow(color.b, safeInverse);
return color;
}
change(changed, touched, init) {
if (
changed["geometry.points"] ||
changed["mesh.shaded"] ||
changed["mesh.fill"] ||
changed["line.stroke"] ||
changed["line.join"] ||
touched["grid"]
) {
return this.rebuild();
}
if (
changed["style.color"] ||
changed["style.zBias"] ||
changed["mesh.fill"] ||
changed["mesh.lineBias"] ||
init
) {
const { fill, color, zBias, lineBias } = this.props;
this.wireZBias.value = zBias + (fill ? lineBias : 0);
this.wireColor.copy(color);
if (fill) {
const c = this.wireScratch;
c.setRGB(color.x, color.y, color.z);
this._convertLinearToGamma(
this._convertGammaToLinear(c).multiplyScalar(0.75)
);
this.wireColor.x = c.r;
this.wireColor.y = c.g;
this.wireColor.z = c.b;
}
}
if (changed["line.proximity"]) {
if ((this.proximity != null) !== (this.props.proximity != null)) {
return this.rebuild();
}
}
}
}
Surface.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/surface.js | JavaScript | mit | 7,589 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Ticks extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"ticks",
"geometry",
"position",
"bind",
"shade",
];
}
init() {
return (this.tickStrip = this.line = null);
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const active = +(dims.items > 0);
const strips = dims.width * active;
const ribbons = dims.height * active;
const layers = dims.depth * active;
this.line.geometry.clip(2, strips, ribbons, layers);
return this.tickStrip.set(0, strips - 1);
}
make() {
// Bind to attached data sources
let color, position;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
const uniforms = UJS.merge(lineUniforms, styleUniforms, unitUniforms);
// Prepare position shader
const positionUniforms = {
tickEpsilon: this.node.attributes["ticks.epsilon"],
tickSize: this.node.attributes["ticks.size"],
tickNormal: this.node.attributes["ticks.normal"],
tickStrip: this._attributes.make(this._types.vec2(0, 0)),
worldUnit: uniforms.worldUnit,
focusDepth: uniforms.focusDepth,
};
this.tickStrip = positionUniforms.tickStrip.value;
// Build transform chain
const p = (position = this._shaders.shader());
// Require buffer sampler as callback
p.require(this.bind.points.sourceShader(this._shaders.shader()));
// Require view transform as callback
p.require(this._helpers.position.pipeline(this._shaders.shader()));
// Link to tick shader
p.pipe("ticks.position", positionUniforms);
// Stroke style
const { stroke, join } = this.props;
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const strips = dims.width;
const ribbons = dims.height;
const layers = dims.depth;
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Build fragment material lookup
const material = this._helpers.shade.pipeline() || false;
// Make line renderable
const { swizzle } = this._helpers.position;
this.line = this._renderables.make("line", {
uniforms,
samples: 2,
strips,
ribbons,
layers,
position,
color,
stroke,
join,
mask: swizzle(mask, "yzwx"),
material,
});
this._helpers.visible.make();
return this._helpers.object.make([this.line]);
}
made() {
return this.resize();
}
unmake() {
this.line = null;
this._helpers.visible.unmake();
return this._helpers.object.unmake();
}
change(changed, _touched, _init) {
if (
changed["geometry.points"] ||
changed["line.stroke"] ||
changed["line.join"]
) {
return this.rebuild();
}
}
}
Ticks.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/ticks.js | JavaScript | mit | 3,937 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Vector extends Primitive {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"style",
"line",
"arrow",
"geometry",
"position",
"bind",
"shade",
];
}
constructor(node, context, helpers) {
super(node, context, helpers);
this.line = this.arrows = null;
}
resize() {
if (this.bind.points == null) {
return;
}
const dims = this.bind.points.getActiveDimensions();
const samples = dims.items;
const strips = dims.width;
const ribbons = dims.height;
const layers = dims.depth;
this.line.geometry.clip(samples, strips, ribbons, layers);
return Array.from(this.arrows).map((arrow) =>
arrow.geometry.clip(samples, strips, ribbons, layers)
);
}
make() {
// Bind to attached data sources
let color;
this._helpers.bind.make([
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
// Build transform chain
let position = this._shaders.shader();
// Fetch position
this.bind.points.sourceShader(position);
// Transform position to view
this._helpers.position.pipeline(position);
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const lineUniforms = this._helpers.line.uniforms();
const arrowUniforms = this._helpers.arrow.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Clip start/end for terminating arrow
const { start, end } = this.props;
// Stroke style
const { stroke, join, proximity } = this.props;
this.proximity = proximity;
// Fetch geometry dimensions
const dims = this.bind.points.getDimensions();
const samples = dims.items;
const strips = dims.width;
const ribbons = dims.height;
const layers = dims.depth;
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
let mask = this._helpers.object.mask();
// Build fragment material lookup
let material = this._helpers.shade.pipeline() || false;
// Swizzle vector to line
const { swizzle, swizzle2 } = this._helpers.position;
position = swizzle2(position, "yzwx", "yzwx");
color = swizzle(color, "yzwx");
mask = swizzle(mask, "yzwx");
material = swizzle(material, "yzwx");
// Make line renderable
const uniforms = UJS.merge(
arrowUniforms,
lineUniforms,
styleUniforms,
unitUniforms
);
this.line = this._renderables.make("line", {
uniforms,
samples,
ribbons,
strips,
layers,
position,
color,
clip: start || end,
stroke,
join,
proximity,
mask,
material,
});
// Make arrow renderables
this.arrows = [];
if (start) {
this.arrows.push(
this._renderables.make("arrow", {
uniforms,
flip: true,
samples,
ribbons,
strips,
layers,
position,
color,
mask,
material,
})
);
}
if (end) {
this.arrows.push(
this._renderables.make("arrow", {
uniforms,
samples,
ribbons,
strips,
layers,
position,
color,
mask,
material,
})
);
}
this._helpers.visible.make();
return this._helpers.object.make(this.arrows.concat([this.line]));
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
return (this.line = this.arrows = null);
}
change(changed, _touched, _init) {
if (
changed["geometry.points"] ||
changed["line.stroke"] ||
changed["line.join"] ||
changed["arrow.start"] ||
changed["arrow.end"]
) {
return this.rebuild();
}
if (changed["line.proximity"]) {
if ((this.proximity != null) !== (this.props.proximity != null)) {
return this.rebuild();
}
}
}
}
Vector.initClass();
| cchudzicki/mathbox | src/primitives/types/draw/vector.js | JavaScript | mit | 4,871 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../util/glsl.js";
import * as UTicks from "../../util/ticks.js";
import { NormalBlending } from "three/src/constants.js";
import { Vector2 } from "three/src/math/Vector2.js";
import { Vector3 } from "three/src/math/Vector3.js";
/*
This is the general dumping ground for trait behavior.
Helpers are auto-attached to primitives that have the matching trait
*/
const helpers = {
bind: {
make(slots) {
if (this.bind == null) {
this.bind = {};
}
if (this.bound == null) {
this.bound = [];
}
// Fetch attached objects and bind to them
// Attach rebuild watcher for DOM changes to bound nodes
for (const slot of Array.from(slots)) {
let { callback } = slot;
const { to, trait, optional, unique, multiple } = slot;
if (callback == null) {
callback = this.rebuild;
}
const name = to.split(/\./g).pop();
const selector = this._get(to);
// Find by selector
let source = null;
if (selector != null) {
let start = this;
let done = false;
while (!done) {
// Keep scanning back until a new node is found
start = source = this._attach(
selector,
trait,
callback,
this,
start,
optional,
multiple
);
const isUnique =
unique && (source == null || this.bound.indexOf(source) < 0);
done = multiple || optional || !unique || isUnique;
}
}
// Monitor source for reallocation / resize
if (source != null) {
if (this.resize != null) {
this._listen(source, "source.resize", this.resize);
}
if (callback) {
this._listen(source, "source.rebuild", callback);
}
if (multiple) {
for (const s of Array.from(source)) {
this.bound.push(s);
}
} else {
this.bound.push(source);
}
}
this.bind[name] = source;
}
return null;
},
unmake() {
if (!this.bind) {
return;
}
delete this.bind;
return delete this.bound;
},
},
span: {
make() {
// Look up nearest view to inherit from
// Monitor size changes
this.spanView = this._inherit("view");
return this._listen("view", "view.range", () =>
this.trigger({ type: "span.range" })
);
},
unmake() {
return delete this.spanView;
},
get: (function () {
const def = new Vector2(-1, 1);
return function (prefix, dimension) {
// Return literal range
let left;
const range = this._get(prefix + "span.range");
if (range != null) {
return range;
}
// Inherit from view
return (left =
this.spanView != null ? this.spanView.axis(dimension) : undefined) !=
null
? left
: def;
};
})(),
},
scale: {
// Divisions to allocate on scale
divide(prefix) {
const divide = this._get(prefix + "scale.divide");
const factor = this._get(prefix + "scale.factor");
return Math.round((divide * 2.5) / factor);
},
// Generate ticks on scale
generate(prefix, buffer, min, max) {
const mode = this._get(prefix + "scale.mode");
const divide = this._get(prefix + "scale.divide");
const unit = this._get(prefix + "scale.unit");
const base = this._get(prefix + "scale.base");
const factor = this._get(prefix + "scale.factor");
const start = this._get(prefix + "scale.start");
const end = this._get(prefix + "scale.end");
const zero = this._get(prefix + "scale.zero");
const nice = this._get(prefix + "scale.nice");
const ticks = UTicks.make(
mode,
min,
max,
divide,
unit,
base,
factor,
start,
end,
zero,
nice
);
buffer.copy(ticks);
return ticks;
},
},
style: {
// Return bound style uniforms
uniforms() {
return {
styleColor: this.node.attributes["style.color"],
styleOpacity: this.node.attributes["style.opacity"],
styleZBias: this.node.attributes["style.zBias"],
styleZIndex: this.node.attributes["style.zIndex"],
};
},
},
arrow: {
// Return bound arrow style uniforms
uniforms() {
const { start } = this.props;
const { end } = this.props;
const space = this._attributes.make(
this._types.number(1.25 / (start + end))
);
const style = this._attributes.make(this._types.vec2(+start, +end));
const size = this.node.attributes["arrow.size"];
return {
clipStyle: style,
clipRange: size,
clipSpace: space,
arrowSpace: space,
arrowSize: size,
};
},
},
point: {
// Return bound point style uniforms
uniforms() {
return {
pointSize: this.node.attributes["point.size"],
pointDepth: this.node.attributes["point.depth"],
};
},
},
line: {
// Return bound line style uniforms
uniforms() {
return {
lineWidth: this.node.attributes["line.width"],
lineDepth: this.node.attributes["line.depth"],
lineProximity: this.node.attributes["line.proximity"],
};
},
},
surface: {
// Return bound surface style uniforms
uniforms() {
return {};
},
},
shade: {
pipeline(shader) {
if (!this._inherit("fragment")) {
return shader;
}
if (shader == null) {
shader = this._shaders.shader();
}
for (let pass = 0; pass <= 2; pass++) {
shader = __guard__(this._inherit("fragment"), (x) =>
x.fragment(shader, pass)
);
}
shader.pipe("fragment.map.rgba");
return shader;
},
map(shader) {
if (!shader) {
return shader;
}
return (shader = this._shaders
.shader()
.pipe("mesh.map.uvwo")
.pipe(shader));
},
},
position: {
pipeline(shader) {
if (!this._inherit("vertex")) {
return shader;
}
if (shader == null) {
shader = this._shaders.shader();
}
for (let pass = 0; pass <= 3; pass++) {
shader = __guard__(this._inherit("vertex"), (x) =>
x.vertex(shader, pass)
);
}
return shader;
},
swizzle(shader, order) {
if (shader) {
return this._shaders
.shader()
.pipe(UGLSL.swizzleVec4(order))
.pipe(shader);
}
},
swizzle2(shader, order1, order2) {
if (shader) {
return this._shaders
.shader()
.split()
.pipe(UGLSL.swizzleVec4(order1))
.next()
.pipe(UGLSL.swizzleVec4(order2))
.join()
.pipe(shader);
}
},
},
visible: {
make() {
const e = { type: "visible.change" };
let visible = null;
this.setVisible = function (vis) {
if (vis != null) {
visible = vis;
}
return onVisible();
};
const onVisible = () => {
let left;
const last = this.isVisible;
let self =
(left = visible != null ? visible : this._get("object.visible")) !=
null
? left
: true;
if (visibleParent != null) {
if (self) {
self = visibleParent.isVisible;
}
}
this.isVisible = self;
if (last !== this.isVisible) {
return this.trigger(e);
}
};
const visibleParent = this._inherit("visible");
if (visibleParent) {
this._listen(visibleParent, "visible.change", onVisible);
}
if (this.is("object")) {
this._listen(this.node, "change:object", onVisible);
}
return onVisible();
},
unmake() {
return delete this.isVisible;
},
},
active: {
make() {
const e = { type: "active.change" };
let active = null;
this.setActive = function (act) {
if (act != null) {
active = act;
}
return onActive();
};
const onActive = () => {
let left;
const last = this.isActive;
let self =
(left = active != null ? active : this._get("entity.active")) != null
? left
: true;
if (activeParent != null) {
if (self) {
self = activeParent.isActive;
}
}
this.isActive = self;
if (last !== this.isActive) {
return this.trigger(e);
}
};
const activeParent = this._inherit("active");
if (activeParent) {
this._listen(activeParent, "active.change", onActive);
}
if (this.is("entity")) {
this._listen(this.node, "change:entity", onActive);
}
return onActive();
},
unmake() {
return delete this.isActive;
},
},
object: {
// Generic 3D renderable wrapper, handles the fiddly Three.js bits that require a 'style recalculation'.
//
// Pass renderables to nearest root for rendering
// Track visibility from parent and notify children
// Track blends / transparency for three.js materials
make(objects) {
// Aggregate rendered three objects for reference
let blending, zOrder;
if (objects == null) {
objects = [];
}
this.objects = objects;
this.renders = this.objects.reduce((a, b) => a.concat(b.renders), []);
const objectScene = this._inherit("scene");
let opacity = (blending = zOrder = null);
const hasStyle = Array.from(this.traits).includes("style");
opacity = 1;
blending = NormalBlending;
let zWrite = true;
let zTest = true;
if (hasStyle) {
({ opacity } = this.props);
({ blending } = this.props);
({ zOrder } = this.props);
({ zWrite } = this.props);
({ zTest } = this.props);
}
const onChange = (event) => {
const { changed } = event;
let refresh = null;
if (changed["style.opacity"]) {
refresh = opacity = this.props.opacity;
}
if (changed["style.blending"]) {
refresh = blending = this.props.blending;
}
if (changed["style.zOrder"]) {
refresh = zOrder = this.props.zOrder;
}
if (changed["style.zWrite"]) {
refresh = zWrite = this.props.zWrite;
}
if (changed["style.zTest"]) {
refresh = zTest = this.props.zTest;
}
if (refresh != null) {
return onVisible();
}
};
const onVisible = () => {
const order = zOrder != null ? -zOrder : this.node.order;
const visible =
(this.isVisible != null ? this.isVisible : true) && opacity > 0;
if (visible) {
if (hasStyle) {
return (() => {
const result = [];
for (const o of Array.from(this.objects)) {
o.show(opacity < 1, blending, order);
result.push(o.depth(zWrite, zTest));
}
return result;
})();
} else {
return (() => {
const result1 = [];
for (const o of Array.from(this.objects)) {
result1.push(o.show(true, blending, order));
}
return result1;
})();
}
} else {
return (() => {
const result2 = [];
for (const o of Array.from(this.objects)) {
result2.push(o.hide());
}
return result2;
})();
}
};
this._listen(this.node, "change:style", onChange);
this._listen(this.node, "reindex", onVisible);
this._listen(this, "visible.change", onVisible);
for (const object of Array.from(this.objects)) {
objectScene.adopt(object);
}
return onVisible();
},
unmake(dispose) {
let object;
if (dispose == null) {
dispose = true;
}
if (!this.objects) {
return;
}
const objectScene = this._inherit("scene");
for (object of Array.from(this.objects)) {
objectScene.unadopt(object);
}
if (dispose) {
return (() => {
const result = [];
for (object of Array.from(this.objects)) {
result.push(object.dispose());
}
return result;
})();
}
},
mask() {
let mask, shader;
if (!(mask = this._inherit("mask"))) {
return;
}
return (shader = mask.mask(shader));
},
},
unit: {
make() {
let focusDepth,
pixelRatio,
pixelUnit,
renderAspect,
renderHeight,
renderOdd,
renderScale,
renderScaleInv,
renderWidth,
viewHeight,
viewWidth,
worldUnit;
let π = Math.PI;
this.unitUniforms = {
renderScaleInv: (renderScaleInv = this._attributes.make(
this._types.number(1)
)),
renderScale: (renderScale = this._attributes.make(
this._types.number(1)
)),
renderAspect: (renderAspect = this._attributes.make(
this._types.number(1)
)),
renderWidth: (renderWidth = this._attributes.make(
this._types.number(0)
)),
renderHeight: (renderHeight = this._attributes.make(
this._types.number(0)
)),
viewWidth: (viewWidth = this._attributes.make(this._types.number(0))),
viewHeight: (viewHeight = this._attributes.make(this._types.number(0))),
pixelRatio: (pixelRatio = this._attributes.make(this._types.number(1))),
pixelUnit: (pixelUnit = this._attributes.make(this._types.number(1))),
worldUnit: (worldUnit = this._attributes.make(this._types.number(1))),
focusDepth: (focusDepth = this._attributes.make(this._types.number(1))),
renderOdd: (renderOdd = this._attributes.make(this._types.vec2())),
};
const top = new Vector3();
const bottom = new Vector3();
const handler = () => {
let camera, size;
if ((size = root != null ? root.getSize() : undefined) == null) {
return;
}
π = Math.PI;
const { scale } = this.props;
const { fov } = this.props;
const focus =
this.props.focus != null
? this.props.focus
: this.inherit("unit").props.focus;
const isAbsolute = scale === null;
// Measure live FOV to be able to accurately predict anti-aliasing in
// perspective
let measure = 1;
if ((camera = root != null ? root.getCamera() : undefined)) {
const m = camera.projectionMatrix;
// Measure top to bottom
top.set(0, -0.5, 1).applyMatrix4(m);
bottom.set(0, 0.5, 1).applyMatrix4(m);
top.sub(bottom);
measure = top.y;
}
// Calculate device pixel ratio
const dpr = size.renderHeight / size.viewHeight;
// Calculate correction for fixed on-screen size regardless of FOV
const fovtan = fov != null ? measure * Math.tan((fov * π) / 360) : 1;
// Calculate device pixels per virtual pixel
const pixel = isAbsolute ? dpr : (size.renderHeight / scale) * fovtan;
// Calculate device pixels per world unit
const rscale = (size.renderHeight * measure) / 2;
// Calculate world units per virtual pixel
const world = pixel / rscale;
viewWidth.value = size.viewWidth;
viewHeight.value = size.viewHeight;
renderWidth.value = size.renderWidth;
renderHeight.value = size.renderHeight;
renderAspect.value = size.aspect;
renderScale.value = rscale;
renderScaleInv.value = 1 / rscale;
pixelRatio.value = dpr;
pixelUnit.value = pixel;
worldUnit.value = world;
focusDepth.value = focus;
return renderOdd.value
.set(size.renderWidth % 2, size.renderHeight % 2)
.multiplyScalar(0.5);
};
//console.log 'worldUnit', world, pixel, rscale, isAbsolute
const root = this.is("root") ? this : this._inherit("root");
//@_listen root, 'root.resize', handler
//@_listen root, 'root.camera', handler
//@_listen @node, 'change:unit', handler
this._listen(root, "root.update", handler);
return handler();
},
unmake() {
return delete this.unitUniforms;
},
get() {
const u = {};
for (const k in this.unitUniforms) {
const v = this.unitUniforms[k];
u[k] = v.value;
}
return u;
},
uniforms() {
return this.unitUniforms;
},
},
};
export const Helpers = function (object, traits) {
const h = {};
for (const trait of Array.from(traits)) {
let methods;
if (!(methods = helpers[trait])) {
continue;
}
h[trait] = {};
for (const key in methods) {
const method = methods[key];
h[trait][key] = method.bind(object);
}
}
return h;
};
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/helpers.js | JavaScript | mit | 18,230 |
export * from "./classes.js";
export { Types } from "./types_typed";
export * from "./traits";
export * from "./helpers.js";
| cchudzicki/mathbox | src/primitives/types/index.js | JavaScript | mit | 125 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Operator } from "./operator.js";
export class Clamp extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "clamp"];
}
indexShader(shader) {
shader.pipe(this.operator);
return super.indexShader(shader);
}
sourceShader(shader) {
shader.pipe(this.operator);
return super.sourceShader(shader);
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Max index on all 4 dimensions
const uniforms = { clampLimit: this._attributes.make(this._types.vec4()) };
this.clampLimit = uniforms.clampLimit;
// Build shader to clamp along all dimensions
const transform = this._shaders.shader();
transform.pipe("clamp.position", uniforms);
return (this.operator = transform);
}
unmake() {
return super.unmake();
}
resize() {
if (this.bind.source != null) {
const dims = this.bind.source.getActiveDimensions();
this.clampLimit.value.set(
dims.width - 1,
dims.height - 1,
dims.depth - 1,
dims.items - 1
);
}
return super.resize();
}
change(changed, touched, _init) {
if (touched["operator"] || touched["clamp"]) {
return this.rebuild();
}
}
}
Clamp.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/clamp.js | JavaScript | mit | 1,713 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Operator } from "./operator.js";
export class Grow extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "grow"];
}
sourceShader(shader) {
return shader.pipe(this.operator);
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Uniforms
const uniforms = {
growScale: this.node.attributes["grow.scale"],
growMask: this._attributes.make(this._types.vec4()),
growAnchor: this._attributes.make(this._types.vec4()),
};
this.growMask = uniforms.growMask.value;
this.growAnchor = uniforms.growAnchor.value;
// Build shader to spread data on one dimension
const transform = this._shaders.shader();
transform.require(this.bind.source.sourceShader(this._shaders.shader()));
transform.pipe("grow.position", uniforms);
return (this.operator = transform);
}
unmake() {
return super.unmake();
}
resize() {
this.update();
return super.resize();
}
update() {
// Size to fit to include future history
const dims = this.bind.source.getFutureDimensions();
const order = ["width", "height", "depth", "items"];
const m = (d, anchor) => ((d || 1) - 1) * (0.5 - anchor * 0.5);
return (() => {
const result = [];
for (let i = 0; i < order.length; i++) {
const key = order[i];
const anchor = this.props[key];
this.growMask.setComponent(i, +(anchor == null));
result.push(
this.growAnchor.setComponent(
i,
anchor != null ? m(dims[key], anchor) : 0
)
);
}
return result;
})();
}
change(changed, touched, _init) {
if (touched["operator"]) {
return this.rebuild();
}
if (touched["grow"]) {
return this.update();
}
}
}
Grow.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/grow.js | JavaScript | mit | 2,351 |
export * from "./clamp.js";
export * from "./grow.js";
export * from "./join.js";
export * from "./lerp.js";
export * from "./memo.js";
export * from "./readback.js";
export * from "./resample.js";
export * from "./repeat.js";
export * from "./swizzle.js";
export * from "./spread.js";
export * from "./split.js";
export * from "./slice.js";
export * from "./subdivide.js";
export * from "./transpose.js";
| cchudzicki/mathbox | src/primitives/types/operator/index.js | JavaScript | mit | 406 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
/*
split:
order: Types.transpose('wxyz')
axis: Types.axis()
overlap: Types.int(0)
*/
export class Join extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "join"];
}
indexShader(shader) {
shader.pipe(this.operator);
return super.indexShader(shader);
}
sourceShader(shader) {
shader.pipe(this.operator);
return super.sourceShader(shader);
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
_resample(dims) {
let left;
let dim;
const { order, axis, stride } = this;
const labels = ["width", "height", "depth", "items"];
const mapped = order.map((x) => labels[x - 1]);
const index = order.indexOf(axis);
let set = (() => {
const result = [];
for (dim of Array.from(mapped)) {
result.push(dims[dim]);
}
return result;
})();
const product = ((left = set[index + 1]) != null ? left : 1) * stride;
set.splice(index, 2, product);
set = set.slice(0, 3);
set.push(1);
const out = {};
for (let i = 0; i < mapped.length; i++) {
dim = mapped[i];
out[dim] = set[i];
}
//console.log 'join', order, axis, length, stride
//console.log dims, out
return out;
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
const { order } = this.props;
let { axis } = this.props;
let { overlap } = this.props;
/*
Calculate index transform
order: wxyz
length: 3
overlap: 1
axis: w
index: 0
rest: 00xy
axis: x
index: 1
rest: w00y
axis: y
index: 2
rest: wx00
axis: z
index: 3
rest: wxy0
*/
const permute = order.join("");
if (axis == null) {
axis = order[0];
}
const index = permute.indexOf(axis);
const rest = permute.replace(axis, "00").substring(0, 4);
const labels = [null, "width", "height", "depth", "items"];
const major = labels[axis];
// Prepare uniforms
const dims = this.bind.source.getDimensions();
const length = dims[major];
overlap = Math.min(length - 1, overlap);
const stride = length - overlap;
const uniforms = {
joinStride: this._attributes.make(this._types.number(stride)),
joinStrideInv: this._attributes.make(this._types.number(1 / stride)),
};
// Build shader to split a dimension into two
const transform = this._shaders.shader();
transform.require(UGLSL.swizzleVec4(axis, 1));
transform.require(UGLSL.swizzleVec4(rest, 4));
transform.require(UGLSL.injectVec4([index, index + 1]));
transform.pipe("join.position", uniforms);
transform.pipe(UGLSL.invertSwizzleVec4(order));
this.operator = transform;
this.order = order;
this.axis = axis;
this.overlap = overlap;
this.length = length;
return (this.stride = stride);
}
unmake() {
return super.unmake();
}
change(changed, touched, _init) {
if (touched["join"] || touched["operator"]) {
return this.rebuild();
}
}
}
Join.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/join.js | JavaScript | mit | 4,068 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
export class Lerp extends Operator {
static initClass() {
this.traits = [
"node",
"bind",
"operator",
"source",
"index",
"lerp",
"sampler:x",
"sampler:y",
"sampler:z",
"sampler:w",
];
}
indexShader(shader) {
shader.pipe(this.indexer);
return super.indexShader(shader);
}
sourceShader(shader) {
return shader.pipe(this.operator);
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
_resample(dims) {
const r = this.resampled;
const c = this.centered;
const p = this.padding;
if (this.relativeSize) {
if (!c.items) {
dims.items--;
}
if (!c.width) {
dims.width--;
}
if (!c.height) {
dims.height--;
}
if (!c.depth) {
dims.depth--;
}
if (r.items != null) {
dims.items *= r.items;
}
if (r.width != null) {
dims.width *= r.width;
}
if (r.height != null) {
dims.height *= r.height;
}
if (r.depth != null) {
dims.depth *= r.depth;
}
if (!c.items) {
dims.items++;
}
if (!c.width) {
dims.width++;
}
if (!c.height) {
dims.height++;
}
if (!c.depth) {
dims.depth++;
}
dims.items -= p.items * 2;
dims.width -= p.width * 2;
dims.height -= p.height * 2;
dims.depth -= p.depth * 2;
} else {
if (r.items != null) {
dims.items = r.items;
}
if (r.width != null) {
dims.width = r.width;
}
if (r.height != null) {
dims.height = r.height;
}
if (r.depth != null) {
dims.depth = r.depth;
}
}
dims.items = Math.max(0, Math.floor(dims.items));
dims.width = Math.max(0, Math.floor(dims.width));
dims.height = Math.max(0, Math.floor(dims.height));
dims.depth = Math.max(0, Math.floor(dims.depth));
return dims;
}
make() {
let i, key;
super.make();
if (this.bind.source == null) {
return;
}
// Get resampled dimensions
const { size, items, width, height, depth } = this.props;
// Sampler behavior
const relativeSize =
size === this.node.attributes["lerp.size"].enum.relative;
this.resampled = {};
if (items != null) {
this.resampled.items = items;
}
if (width != null) {
this.resampled.width = width;
}
if (height != null) {
this.resampled.height = height;
}
if (depth != null) {
this.resampled.depth = depth;
}
this.centered = {};
this.centered.items = this.props.centeredW;
this.centered.width = this.props.centeredX;
this.centered.height = this.props.centeredY;
this.centered.depth = this.props.centeredZ;
this.padding = {};
this.padding.items = this.props.paddingW;
this.padding.width = this.props.paddingX;
this.padding.height = this.props.paddingY;
this.padding.depth = this.props.paddingZ;
// Build shader to resample data
const operator = this._shaders.shader();
const indexer = this._shaders.shader();
// Uniforms
const uniforms = {
resampleFactor: this._attributes.make(this._types.vec4(0, 0, 0, 0)),
resampleBias: this._attributes.make(this._types.vec4(0, 0, 0, 0)),
};
this.resampleFactor = uniforms.resampleFactor;
this.resampleBias = uniforms.resampleBias;
// Has resize props?
const resize =
items != null || width != null || height != null || depth != null;
// Add padding
operator.pipe("resample.padding", uniforms);
// Prepare centered sampling offset
const vec = [];
let any = false;
const iterable = ["width", "height", "depth", "items"];
for (i = 0; i < iterable.length; i++) {
key = iterable[i];
const centered = this.centered[key];
if (!any) {
any = centered;
}
vec[i] = centered ? "0.5" : "0.0";
}
let vec4;
// Add centered sampling offset (from source)
if (any && resize) {
vec4 = `vec4(${vec})`;
operator.pipe(UGLSL.binaryOperator(4, "+", vec4));
indexer.pipe(UGLSL.binaryOperator(4, "+", vec4));
}
// Addressing relative to target
if (resize) {
operator.pipe("resample.relative", uniforms);
indexer.pipe("resample.relative", uniforms);
} else {
operator.pipe(UGLSL.identity("vec4"));
indexer.pipe(UGLSL.identity("vec4"));
}
// Remove centered sampling offset (to target)
if (any && resize) {
operator.pipe(UGLSL.binaryOperator(4, "-", vec4));
indexer.pipe(UGLSL.binaryOperator(4, "-", vec4));
}
// Make sampler
let sampler = this.bind.source.sourceShader(this._shaders.shader());
// Iterate over dimensions (items, width, height, depth)
const iterable1 = ["width", "height", "depth", "items"];
for (i = 0; i < iterable1.length; i++) {
key = iterable1[i];
const id = `lerp.${key}`;
if (this.props[key] != null) {
sampler = this._shaders.shader().require(sampler);
sampler.pipe(id, uniforms);
}
}
// Combine operator and composite lerp sampler
operator.pipe(sampler);
this.operator = operator;
this.indexer = indexer;
return (this.relativeSize = relativeSize);
}
unmake() {
super.unmake();
return (this.operator = null);
}
resize() {
if (this.bind.source == null) {
return;
}
const dims = this.bind.source.getActiveDimensions();
const target = this.getActiveDimensions();
const axis = (key) => {
const centered = this.centered[key];
const pad = this.padding[key];
target[key] += pad * 2;
const res = centered
? dims[key] / Math.max(1, target[key])
: Math.max(1, dims[key] - 1) / Math.max(1, target[key] - 1);
return [res, pad];
};
const [rw, bw] = Array.from(axis("width"));
const [rh, bh] = Array.from(axis("height"));
const [rd, bd] = Array.from(axis("depth"));
const [ri, bi] = Array.from(axis("items"));
this.resampleFactor.value.set(rw, rh, rd, ri);
this.resampleBias.value.set(bw, bh, bd, bi);
return super.resize();
}
change(changed, touched, _init) {
if (touched["operator"] || touched["lerp"] || touched["sampler"]) {
return this.rebuild();
}
}
}
Lerp.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/lerp.js | JavaScript | mit | 7,268 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Operator } from "./operator";
export class Memo extends Operator {
static initClass() {
this.traits = [
"node",
"bind",
"active",
"operator",
"source",
"index",
"texture",
"memo",
];
}
sourceShader(shader) {
return this.memo.shaderAbsolute(shader, 1);
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Listen for updates
this._helpers.active.make();
this._listen("root", "root.update", () => {
if (this.isActive) {
return this.update();
}
});
// Read sampling parameters
const { minFilter, magFilter, type } = this.props;
// Fetch geometry dimensions
const dims = this.bind.source.getDimensions();
const { items, width, height, depth } = dims;
// Prepare memoization RTT
this.memo = this._renderables.make("memo", {
items,
width,
height,
depth,
minFilter,
magFilter,
type,
});
// Build shader to remap data (do it after RTT creation to allow feedback)
const operator = this._shaders.shader();
this.bind.source.sourceShader(operator);
// Make screen renderable inside RTT scene
this.compose = this._renderables.make("memoScreen", {
map: operator,
items,
width,
height,
depth,
});
this.memo.adopt(this.compose);
this.objects = [this.compose];
return (this.renders = this.compose.renders);
}
unmake() {
super.unmake();
if (this.bind.source != null) {
this._helpers.active.unmake();
this.memo.unadopt(this.compose);
this.memo.dispose();
return (this.memo = this.compose = null);
}
}
update() {
return this.memo != null ? this.memo.render() : undefined;
}
resize() {
if (this.bind.source == null) {
return;
}
// Fetch geometry dimensions
const dims = this.bind.source.getActiveDimensions();
const { width, height, depth } = dims;
// Cover only part of the RTT viewport
this.compose.cover(width, height, depth);
return super.resize();
}
change(changed, touched, _init) {
if (touched["texture"] || touched["operator"]) {
return this.rebuild();
}
}
}
Memo.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/memo.js | JavaScript | mit | 2,699 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Source } from "../base/source";
export class Operator extends Source {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index"];
}
indexShader(shader) {
return __guardMethod__(this.bind.source, "indexShader", (o) =>
o.indexShader(shader)
);
}
sourceShader(shader) {
return __guardMethod__(this.bind.source, "sourceShader", (o) =>
o.sourceShader(shader)
);
}
getDimensions() {
return this.bind.source.getDimensions();
}
getFutureDimensions() {
return this.bind.source.getFutureDimensions();
}
getActiveDimensions() {
return this.bind.source.getActiveDimensions();
}
getIndexDimensions() {
return this.bind.source.getIndexDimensions();
}
init() {
return (this.sourceSpec = [{ to: "operator.source", trait: "source" }]);
}
make() {
super.make();
// Bind to attached data sources
return this._helpers.bind.make(this.sourceSpec);
}
made() {
this.resize();
return super.made();
}
unmake() {
return this._helpers.bind.unmake();
}
resize(_rebuild) {
return this.trigger({
type: "source.resize",
});
}
}
Operator.initClass();
function __guardMethod__(obj, methodName, transform) {
if (
typeof obj !== "undefined" &&
obj !== null &&
typeof obj[methodName] === "function"
) {
return transform(obj, methodName);
} else {
return undefined;
}
}
| cchudzicki/mathbox | src/primitives/types/operator/operator.js | JavaScript | mit | 1,898 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Primitive } from "../../primitive.js";
export class Readback extends Primitive {
static initClass() {
this.traits = ["node", "bind", "operator", "readback", "entity", "active"];
this.finals = { channels: 4 };
}
init() {
this.emitter = this.root = null;
return (this.active = {});
}
make() {
super.make();
this._compute("readback.data", () =>
this.readback != null ? this.readback.data : undefined
);
this._compute("readback.items", () =>
this.readback != null ? this.readback.items : undefined
);
this._compute("readback.width", () =>
this.readback != null ? this.readback.width : undefined
);
this._compute("readback.height", () =>
this.readback != null ? this.readback.height : undefined
);
this._compute("readback.depth", () =>
this.readback != null ? this.readback.depth : undefined
);
// Bind to attached objects
this._helpers.bind.make([{ to: "operator.source", trait: "source" }]);
if (this.bind.source == null) {
return;
}
// Sampler props
const { type, channels, expr } = this.props;
// Listen for updates
this.root = this._inherit("root");
this._listen("root", "root.update", this.update);
// Fetch source dimensions
const { items, width, height, depth } = this.bind.source.getDimensions();
// Build shader to sample source data
const sampler = this.bind.source.sourceShader(this._shaders.shader());
// Prepare readback/memo RTT
this.readback = this._renderables.make("readback", {
map: sampler,
items,
width,
height,
depth,
channels,
type,
});
// Prepare readback consumer
if (expr != null) {
this.readback.setCallback(expr);
}
this._helpers.active.make();
}
unmake() {
if (this.readback != null) {
this.readback.dispose();
this.readback = null;
this.root = null;
this.emitter = null;
this.active = {};
}
this._helpers.active.unmake();
return this._helpers.bind.unmake();
}
update() {
if (this.readback == null) {
return;
}
if (this.isActive) {
this.readback.update(
this.root != null ? this.root.getCamera() : undefined
);
this.readback.post();
if (this.props.expr != null) {
this.readback.iterate();
}
}
}
resize() {
let sI, sJ;
if (this.readback == null) {
return;
}
// Fetch geometry/html dimensions
const { items, width, height, depth } =
this.bind.source.getActiveDimensions();
// Limit readback to active area
this.readback.setActive(items, width, height, depth);
// Recalculate iteration strides
this.strideI = sI = items;
this.strideJ = sJ = sI * width;
return (this.strideK = sJ * height);
}
change(changed, _touched, _init) {
if (changed["readback.type"]) {
return this.rebuild();
}
if (changed["readback.expr"] && this.readback) {
return this.readback.setCallback(this.props.expr);
}
}
}
Readback.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/readback.js | JavaScript | mit | 3,530 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Operator } from "./operator.js";
export class Repeat extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "repeat"];
}
indexShader(shader) {
shader.pipe(this.operator);
return super.indexShader(shader);
}
sourceShader(shader) {
shader.pipe(this.operator);
return super.sourceShader(shader);
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
_resample(dims) {
const r = this.resample;
return {
items: r.items * dims.items,
width: r.width * dims.width,
height: r.height * dims.height,
depth: r.depth * dims.depth,
};
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Repeat multipliers
this.resample = {};
// Modulus on all 4 dimensions
const uniforms = {
repeatModulus: this._attributes.make(this._types.vec4()),
};
this.repeatModulus = uniforms.repeatModulus;
// Build shader to repeat along all dimensions
const transform = this._shaders.shader();
transform.pipe("repeat.position", uniforms);
return (this.operator = transform);
}
unmake() {
return super.unmake();
}
resize() {
if (this.bind.source != null) {
const dims = this.bind.source.getActiveDimensions();
this.repeatModulus.value.set(
dims.width,
dims.height,
dims.depth,
dims.items
);
}
return super.resize();
}
change(changed, touched, init) {
if (touched["operator"] || touched["repeat"]) {
return this.rebuild();
}
if (init) {
return ["items", "width", "height", "depth"].map(
(key) => (this.resample[key] = this.props[key])
);
}
}
}
Repeat.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/repeat.js | JavaScript | mit | 2,510 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
export class Resample extends Operator {
static initClass() {
this.traits = [
"node",
"bind",
"operator",
"source",
"index",
"resample",
"sampler:x",
"sampler:y",
"sampler:z",
"sampler:w",
"include",
];
}
indexShader(shader) {
shader.pipe(this.indexer);
return super.indexShader(shader);
}
sourceShader(shader) {
return shader.pipe(this.operator);
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
_resample(dims) {
const r = this.resampled;
const c = this.centered;
const p = this.padding;
if (this.relativeSize) {
if (!c.items) {
dims.items--;
}
if (!c.width) {
dims.width--;
}
if (!c.height) {
dims.height--;
}
if (!c.depth) {
dims.depth--;
}
if (r.items != null) {
dims.items *= r.items;
}
if (r.width != null) {
dims.width *= r.width;
}
if (r.height != null) {
dims.height *= r.height;
}
if (r.depth != null) {
dims.depth *= r.depth;
}
if (!c.items) {
dims.items++;
}
if (!c.width) {
dims.width++;
}
if (!c.height) {
dims.height++;
}
if (!c.depth) {
dims.depth++;
}
dims.items -= p.items * 2;
dims.width -= p.width * 2;
dims.height -= p.height * 2;
dims.depth -= p.depth * 2;
} else {
if (r.items != null) {
dims.items = r.items;
}
if (r.width != null) {
dims.width = r.width;
}
if (r.height != null) {
dims.height = r.height;
}
if (r.depth != null) {
dims.depth = r.depth;
}
}
dims.items = Math.max(0, Math.floor(dims.items));
dims.width = Math.max(0, Math.floor(dims.width));
dims.height = Math.max(0, Math.floor(dims.height));
dims.depth = Math.max(0, Math.floor(dims.depth));
return dims;
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Bind to attached shader
this._helpers.bind.make([
{ to: "include.shader", trait: "shader", optional: true },
]);
// Get custom shader
const { indices, channels } = this.props;
const { shader } = this.bind;
// Get resampled dimensions (if any)
const { sample, size, items, width, height, depth } = this.props;
// Sampler behavior
const relativeSample =
sample === this.node.attributes["resample.sample"].enum.relative;
const relativeSize =
size === this.node.attributes["resample.size"].enum.relative;
this.resampled = {};
if (items != null) {
this.resampled.items = items;
}
if (width != null) {
this.resampled.width = width;
}
if (height != null) {
this.resampled.height = height;
}
if (depth != null) {
this.resampled.depth = depth;
}
this.centered = {};
this.centered.items = this.props.centeredW;
this.centered.width = this.props.centeredX;
this.centered.height = this.props.centeredY;
this.centered.depth = this.props.centeredZ;
this.padding = {};
this.padding.items = this.props.paddingW;
this.padding.width = this.props.paddingX;
this.padding.height = this.props.paddingY;
this.padding.depth = this.props.paddingZ;
// Build shader to resample data
const operator = this._shaders.shader();
const indexer = this._shaders.shader();
// Uniforms
const type = [
null,
this._types.number,
this._types.vec2,
this._types.vec3,
this._types.vec4,
][indices];
const uniforms = {
dataSize: this._attributes.make(type(0, 0, 0, 0)),
dataResolution: this._attributes.make(type(0, 0, 0, 0)),
targetSize: this._attributes.make(type(0, 0, 0, 0)),
targetResolution: this._attributes.make(type(0, 0, 0, 0)),
resampleFactor: this._attributes.make(this._types.vec4(0, 0, 0, 0)),
resampleBias: this._attributes.make(this._types.vec4(0, 0, 0, 0)),
};
this.dataResolution = uniforms.dataResolution;
this.dataSize = uniforms.dataSize;
this.targetResolution = uniforms.targetResolution;
this.targetSize = uniforms.targetSize;
this.resampleFactor = uniforms.resampleFactor;
this.resampleBias = uniforms.resampleBias;
// Has resize props?
const resize =
items != null || width != null || height != null || depth != null;
// Add padding
operator.pipe("resample.padding", uniforms);
// Add centered sampling offset
let vec = [];
let any = false;
const iterable = ["width", "height", "depth", "items"];
for (let i = 0; i < iterable.length; i++) {
const key = iterable[i];
const centered = this.centered[key];
if (!any) {
any = centered;
}
vec[i] = centered ? "0.5" : "0.0";
}
if (any) {
vec = `vec4(${vec})`;
// TODO is this right? seems like copy paste.
operator.pipe(UGLSL.binaryOperator(4, "+", vec));
if (resize) {
indexer.pipe(UGLSL.binaryOperator(4, "+", vec));
}
}
if (relativeSample) {
// Addressing relative to target
if (resize) {
operator.pipe("resample.relative", uniforms);
indexer.pipe("resample.relative", uniforms);
} else {
indexer.pipe(UGLSL.identity("vec4"));
}
}
if (shader != null) {
if (indices !== 4) {
operator.pipe(UGLSL.truncateVec(4, indices));
}
operator.callback();
if (indices !== 4) {
operator.pipe(UGLSL.extendVec(indices, 4));
}
if (any) {
operator.pipe(UGLSL.binaryOperator(4, "-", vec));
}
operator.pipe(this.bind.source.sourceShader(this._shaders.shader()));
if (channels !== 4) {
operator.pipe(UGLSL.truncateVec(4, channels));
}
operator.join();
if (this.bind.shader != null) {
operator.pipe(this.bind.shader.shaderBind(uniforms));
}
if (channels !== 4) {
operator.pipe(UGLSL.extendVec(channels, 4));
}
} else {
if (any) {
operator.pipe(UGLSL.binaryOperator(4, "-", vec));
}
operator.pipe(this.bind.source.sourceShader(this._shaders.shader()));
}
if (any && resize) {
indexer.pipe(UGLSL.binaryOperator(4, "-", vec));
}
this.operator = operator;
this.indexer = indexer;
this.indices = indices;
this.relativeSample = relativeSample;
return (this.relativeSize = relativeSize);
}
unmake() {
super.unmake();
return (this.operator = null);
}
resize() {
if (this.bind.source == null) {
return;
}
const dims = this.bind.source.getActiveDimensions();
const target = this.getActiveDimensions();
const axis = (key) => {
const centered = this.centered[key];
const pad = this.padding[key];
target[key] += pad * 2;
const res = centered
? dims[key] / Math.max(1, target[key])
: Math.max(1, dims[key] - 1) / Math.max(1, target[key] - 1);
return [res, pad];
};
const [rw, bw] = Array.from(axis("width"));
const [rh, bh] = Array.from(axis("height"));
const [rd, bd] = Array.from(axis("depth"));
const [ri, bi] = Array.from(axis("items"));
if (this.indices === 1) {
this.dataResolution.value = 1 / dims.width;
this.targetResolution.value = 1 / target.width;
this.dataSize.value = dims.width;
this.targetSize.value = target.width;
} else {
this.dataResolution.value.set(
1 / dims.width,
1 / dims.height,
1 / dims.depth,
1 / dims.items
);
this.targetResolution.value.set(
1 / target.width,
1 / target.height,
1 / target.depth,
1 / target.items
);
this.dataSize.value.set(dims.width, dims.height, dims.depth, dims.items);
this.targetSize.value.set(
target.width,
target.height,
target.depth,
target.items
);
}
this.resampleFactor.value.set(rw, rh, rd, ri);
this.resampleBias.value.set(bw, bh, bd, bi);
return super.resize();
}
change(changed, touched, _init) {
if (
touched["operator"] ||
touched["resample"] ||
touched["sampler"] ||
touched["include"]
) {
return this.rebuild();
}
}
}
Resample.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/resample.js | JavaScript | mit | 9,325 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Operator } from "./operator.js";
export class Slice extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "slice"];
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
sourceShader(shader) {
shader.pipe("slice.position", this.uniforms);
return this.bind.source.sourceShader(shader);
}
_resolve(key, dims) {
const range = this.props[key];
const dim = dims[key];
if (range == null) {
return [0, dim];
}
const index = function (i, dim) {
if (i < 0) {
return dim + i;
} else {
return i;
}
};
const start = index(Math.round(range.x), dim);
let end = index(Math.round(range.y), dim);
end = Math.max(start, end);
return [start, end - start];
}
_resample(dims) {
dims.width = this._resolve("width", dims)[1];
dims.height = this._resolve("height", dims)[1];
dims.depth = this._resolve("depth", dims)[1];
dims.items = this._resolve("items", dims)[1];
return dims;
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
return (this.uniforms = {
sliceOffset: this._attributes.make(this._types.vec4()),
});
}
unmake() {
return super.unmake();
}
resize() {
if (this.bind.source == null) {
return;
}
const dims = this.bind.source.getActiveDimensions();
this.uniforms.sliceOffset.value.set(
this._resolve("width", dims)[0],
this._resolve("height", dims)[0],
this._resolve("depth", dims)[0],
this._resolve("items", dims)[0]
);
return super.resize();
}
change(changed, touched, _init) {
if (touched["operator"]) {
return this.rebuild();
}
if (touched["slice"]) {
return this.resize();
}
}
}
Slice.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/slice.js | JavaScript | mit | 2,580 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
/*
split:
order: Types.transpose('wxyz')
axis: Types.axis()
length: Types.int(1)
overlap: Types.int(0)
*/
export class Split extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "split"];
}
indexShader(shader) {
shader.pipe(this.operator);
return super.indexShader(shader);
}
sourceShader(shader) {
shader.pipe(this.operator);
return super.sourceShader(shader);
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
_resample(dims) {
let dim;
const { order } = this;
const { axis } = this;
const { overlap } = this;
const { length } = this;
const { stride } = this;
const labels = ["width", "height", "depth", "items"];
const mapped = order.map((x) => labels[x - 1]);
const index = order.indexOf(axis);
let set = (() => {
const result = [];
for (dim of Array.from(mapped)) {
result.push(dims[dim]);
}
return result;
})();
const remain = Math.floor((set[index] - overlap) / stride);
set.splice(index, 1, length, remain);
set = set.slice(0, 4);
const out = {};
for (let i = 0; i < mapped.length; i++) {
dim = mapped[i];
out[dim] = set[i];
}
//console.log 'split', order, axis, length, stride
//console.log dims, out
return out;
}
make() {
let left;
super.make();
if (this.bind.source == null) {
return;
}
const { order } = this.props;
let { axis } = this.props;
let { overlap } = this.props;
const { length } = this.props;
/*
Calculate index transform
order: wxyz
length: 3
overlap: 1
axis: w
index: 0
split: wx
rest: 0yz0
s
axis: x
index: 1
split: xy
rest: w0z0
s
axis: y
index: 2
split: yz
rest: wx00
s
axis: z
index: 3
split: z0
rest: wxy0
s
*/
const permute = order.join("");
if (axis == null) {
axis = order[0];
}
const index = permute.indexOf(axis);
const split =
permute[index] + ((left = permute[index + 1]) != null ? left : 0);
const rest = permute.replace(split[1], "").replace(split[0], "0") + "0";
// Prepare uniforms
overlap = Math.min(length - 1, overlap);
const stride = length - overlap;
const uniforms = {
splitStride: this._attributes.make(this._types.number(stride)),
};
// Build shader to split a dimension into two
const transform = this._shaders.shader();
transform.require(UGLSL.swizzleVec4(split, 2));
transform.require(UGLSL.swizzleVec4(rest, 4));
transform.require(UGLSL.injectVec4(index));
transform.pipe("split.position", uniforms);
transform.pipe(UGLSL.invertSwizzleVec4(order));
this.operator = transform;
this.order = order;
this.axis = axis;
this.overlap = overlap;
this.length = length;
return (this.stride = stride);
}
unmake() {
return super.unmake();
}
change(changed, touched, _init) {
if (
changed["split.axis"] ||
changed["split.order"] ||
touched["operator"]
) {
return this.rebuild();
}
}
}
Split.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/split.js | JavaScript | mit | 4,227 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Operator } from "./operator.js";
export class Spread extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "spread"];
}
sourceShader(shader) {
return shader.pipe(this.operator);
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Uniforms
const uniforms = {
spreadMatrix: this._attributes.make(this._types.mat4()),
spreadOffset: this._attributes.make(this._types.vec4()),
};
this.spreadMatrix = uniforms.spreadMatrix;
this.spreadOffset = uniforms.spreadOffset;
// Build shader to spread data on one dimension
const transform = this._shaders.shader();
transform.require(this.bind.source.sourceShader(this._shaders.shader()));
transform.pipe("spread.position", uniforms);
return (this.operator = transform);
}
unmake() {
return super.unmake();
}
resize() {
this.update();
return super.resize();
}
update() {
// Size to fit to include future history
let key, i, k, v;
const dims = this.bind.source.getFutureDimensions();
const matrix = this.spreadMatrix.value;
const els = matrix.elements;
const order = ["width", "height", "depth", "items"];
const align = ["alignWidth", "alignHeight", "alignDepth", "alignItems"];
const { unit } = this.props;
const unitEnum = this.node.attributes["spread.unit"].enum;
const map = (() => {
switch (unit) {
case unitEnum.relative:
return (key, i, k, v) =>
(els[i * 4 + k] = v / Math.max(1, dims[key] - 1));
case unitEnum.absolute:
return (key, i, k, v) => (els[i * 4 + k] = v);
}
})();
return (() => {
const result = [];
for (i = 0; i < order.length; i++) {
let offset;
key = order[i];
const spread = this.props[key];
const anchor = this.props[align[i]];
if (spread != null) {
const d = dims[key] != null ? dims[key] : 1;
offset = -(d - 1) * (0.5 - anchor * 0.5);
} else {
offset = 0;
}
this.spreadOffset.value.setComponent(i, offset);
result.push(
(() => {
const result1 = [];
for (k = 0; k <= 3; k++) {
let left;
v =
(left = spread != null ? spread.getComponent(k) : undefined) !=
null
? left
: 0;
result1.push((els[i * 4 + k] = map(key, i, k, v)));
}
return result1;
})()
);
}
return result;
})();
}
change(changed, touched, _init) {
if (touched["operator"]) {
return this.rebuild();
}
if (touched["spread"]) {
return this.update();
}
}
}
Spread.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/spread.js | JavaScript | mit | 3,363 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
export class Subdivide extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "subdivide"];
}
indexShader(shader) {
shader.pipe(this.indexer);
return super.indexShader(shader);
}
sourceShader(shader) {
return shader.pipe(this.operator);
}
getDimensions() {
return this._resample(this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._resample(this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._resample(this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._resample(this.bind.source.getIndexDimensions());
}
_resample(dims) {
const r = this.resampled;
dims.items--;
dims.width--;
dims.height--;
dims.depth--;
if (r.items != null) {
dims.items *= r.items;
}
if (r.width != null) {
dims.width *= r.width;
}
if (r.height != null) {
dims.height *= r.height;
}
if (r.depth != null) {
dims.depth *= r.depth;
}
dims.items++;
dims.width++;
dims.height++;
dims.depth++;
return dims;
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Get resampled dimensions
let { lerp } = this.props;
const { items, width, height, depth } = this.props;
this.resampled = {};
if (items != null) {
this.resampled.items = items;
}
if (width != null) {
this.resampled.width = width;
}
if (height != null) {
this.resampled.height = height;
}
if (depth != null) {
this.resampled.depth = depth;
}
// Build shader to resample data
const operator = this._shaders.shader();
const indexer = this._shaders.shader();
// Uniforms
const uniforms = {
resampleFactor: this._attributes.make(this._types.vec4(0, 0, 0, 0)),
subdivideBevel: this.node.attributes["subdivide.bevel"],
};
this.resampleFactor = uniforms.resampleFactor;
this.resampleBias = uniforms.resampleBias;
// Has resize props?
const resize =
items != null || width != null || height != null || depth != null;
// Addressing relative to target
if (resize) {
operator.pipe("resample.relative", uniforms);
indexer.pipe("resample.relative", uniforms);
} else {
operator.pipe(UGLSL.identity("vec4"));
indexer.pipe(UGLSL.identity("vec4"));
}
// Make sampler
let sampler = this.bind.source.sourceShader(this._shaders.shader());
lerp = lerp ? ".lerp" : "";
// Iterate over dimensions (items, width, height, depth)
const iterable = ["width", "height", "depth", "items"];
for (let i = 0; i < iterable.length; i++) {
const key = iterable[i];
const id = `subdivide.${key}${lerp}`;
if (this.props[key] != null) {
sampler = this._shaders.shader().require(sampler);
sampler.pipe(id, uniforms);
}
}
// Combine operator and composite lerp sampler
operator.pipe(sampler);
this.operator = operator;
return (this.indexer = indexer);
}
unmake() {
super.unmake();
return (this.operator = null);
}
resize() {
if (this.bind.source == null) {
return;
}
const dims = this.bind.source.getActiveDimensions();
const target = this.getActiveDimensions();
const axis = (key) =>
Math.max(1, dims[key] - 1) / Math.max(1, target[key] - 1);
const rw = axis("width");
const rh = axis("height");
const rd = axis("depth");
const ri = axis("items");
this.resampleFactor.value.set(rw, rh, rd, ri);
return super.resize();
}
change(changed, touched, _init) {
if (touched["operator"] || touched["subdivide"]) {
return this.rebuild();
}
}
}
Subdivide.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/subdivide.js | JavaScript | mit | 4,342 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
export class Swizzle extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "swizzle"];
}
sourceShader(shader) {
shader = super.sourceShader(shader);
if (this.swizzler) {
shader.pipe(this.swizzler);
}
return shader;
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Swizzling order
const { order } = this.props;
if (order.join() !== "1234") {
return (this.swizzler = UGLSL.swizzleVec4(order, 4));
}
}
unmake() {
super.unmake();
return (this.swizzler = null);
}
change(changed, touched, _init) {
if (touched["swizzle"] || touched["operator"]) {
return this.rebuild();
}
}
}
Swizzle.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/swizzle.js | JavaScript | mit | 1,281 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Operator } from "./operator.js";
const labels = {
1: "width",
2: "height",
3: "depth",
4: "items",
};
export class Transpose extends Operator {
static initClass() {
this.traits = ["node", "bind", "operator", "source", "index", "transpose"];
}
indexShader(shader) {
if (this.swizzler) {
shader.pipe(this.swizzler);
}
return super.indexShader(shader);
}
sourceShader(shader) {
if (this.swizzler) {
shader.pipe(this.swizzler);
}
return super.sourceShader(shader);
}
getDimensions() {
return this._remap(this.transpose, this.bind.source.getDimensions());
}
getActiveDimensions() {
return this._remap(this.transpose, this.bind.source.getActiveDimensions());
}
getFutureDimensions() {
return this._remap(this.transpose, this.bind.source.getFutureDimensions());
}
getIndexDimensions() {
return this._remap(this.transpose, this.bind.source.getIndexDimensions());
}
_remap(transpose, dims) {
// Map dimensions onto their new axis
const out = {};
for (let i = 0; i <= 3; i++) {
const dst = labels[i + 1];
const src = labels[transpose[i]];
out[dst] = dims[src] != null ? dims[src] : 1;
}
return out;
}
make() {
super.make();
if (this.bind.source == null) {
return;
}
// Transposition order
const { order } = this.props;
if (order.join() !== "1234") {
this.swizzler = UGLSL.invertSwizzleVec4(order);
}
this.transpose = order;
// Notify of reallocation
return this.trigger({
type: "source.rebuild",
});
}
unmake() {
super.unmake();
return (this.swizzler = null);
}
change(changed, touched, _init) {
if (touched["transpose"] || touched["operator"]) {
return this.rebuild();
}
}
}
Transpose.initClass();
| cchudzicki/mathbox | src/primitives/types/operator/transpose.js | JavaScript | mit | 2,305 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Primitive } from "../../primitive.js";
export class DOM extends Primitive {
static initClass() {
this.traits = [
"node",
"bind",
"object",
"visible",
"overlay",
"dom",
"attach",
"position",
];
}
init() {
this.emitter = this.root = null;
this.active = {};
}
make() {
super.make();
// Bind to attached objects
this._helpers.bind.make([
{ to: "dom.html", trait: "html" },
{ to: "dom.points", trait: "source" },
]);
if (this.bind.points == null || this.bind.html == null) {
return;
}
// Listen for updates
this.root = this._inherit("root");
this._listen("root", "root.update", this.update);
this._listen("root", "root.post", this.post);
// Fetch geometry dimensions
const pointDims = this.bind.points.getDimensions();
const htmlDims = this.bind.html.getDimensions();
const items = Math.min(pointDims.items, htmlDims.items);
const width = Math.min(pointDims.width, htmlDims.width);
const height = Math.min(pointDims.height, htmlDims.height);
const depth = Math.min(pointDims.depth, htmlDims.depth);
// Build shader to sample position data
let position = this.bind.points.sourceShader(this._shaders.shader());
// Transform data into screen space
position = this._helpers.position.pipeline(position);
// Apply global projection
const projection = this._shaders.shader({ globals: ["projectionMatrix"] });
projection.pipe("project.readback");
position.pipe(projection);
// Build nop index shader
const indexer = this._shaders.shader();
// Prepare readback/memo RTT
this.readback = this._renderables.make("readback", {
map: position,
indexer,
items,
width,
height,
depth,
channels: 4,
stpq: true,
});
// Prepare overlay container VDOM
this.dom = this._overlays.make("dom");
this.dom.hint(items * width * height * depth * 2);
// Make sure we have enough for wrapping each given element once
// Prepare readback consumer
this.emitter = this.callback(this.bind.html.nodes());
this.readback.setCallback(this.emitter);
this._helpers.visible.make();
}
unmake() {
if (this.readback != null) {
this.readback.dispose();
this.dom.dispose();
this.readback = this.dom = null;
this.root = null;
this.emitter = null;
this.active = {};
}
this._helpers.bind.unmake();
this._helpers.visible.unmake();
}
update() {
if (this.readback == null) {
return;
}
if (this.props.visible) {
this.readback.update(
this.root != null ? this.root.getCamera() : undefined
);
this.readback.post();
this.readback.iterate();
}
}
post() {
if (this.readback == null) {
return;
}
this.dom.render(this.isVisible ? this.emitter.nodes() : null);
}
callback(data) {
// Create static consumer for the readback
let strideJ, strideK;
const uniforms = this._inherit("unit").getUnitUniforms();
const width = uniforms.viewWidth;
const height = uniforms.viewHeight;
const attr = this.node.attributes["dom.attributes"];
const size = this.node.attributes["dom.size"];
const zoom = this.node.attributes["dom.zoom"];
const color = this.node.attributes["dom.color"];
const outline = this.node.attributes["dom.outline"];
const pointer = this.node.attributes["dom.pointerEvents"];
const opacity = this.node.attributes["overlay.opacity"];
const zIndex = this.node.attributes["overlay.zIndex"];
const offset = this.node.attributes["attach.offset"];
const depth = this.node.attributes["attach.depth"];
const snap = this.node.attributes["attach.snap"];
const { el } = this.dom;
let nodes = [];
let styles = null;
let className = null;
let strideI = (strideJ = strideK = 0);
let colorString = "";
const f = function (x, y, z, w, i, j, k, l) {
// Get HTML item by offset
let v;
const index = l + strideI * i + strideJ * j + strideK * k;
const children = data[index];
// Clip behind camera or when invisible
const clip = w < 0;
// Depth blending
const iw = 1 / w;
const flatZ = 1 + (iw - 1) * depth.value;
const scale = clip ? 0 : flatZ;
// GL to CSS coordinate transform
const ox = +offset.value.x * scale;
const oy = +offset.value.y * scale;
let xx = (x + 1) * width.value * 0.5 + ox;
let yy = (y - 1) * height.value * 0.5 + oy;
// Handle zoom/scale
xx /= zoom.value;
yy /= zoom.value;
// Snap to pixel
if (snap.value) {
xx = Math.round(xx);
yy = Math.round(yy);
}
// Clip and apply opacity
const alpha = Math.min(0.999, clip ? 0 : opacity.value);
// Generate div
const props = {
className,
style: {
transform: `translate3d(${xx}px, ${-yy}px, ${
1 - w
}px) translate(-50%, -50%) scale(${scale},${scale})`,
opacity: alpha,
},
};
for (k in styles) {
v = styles[k];
props.style[k] = v;
}
// Merge in external attributes
const a = attr.value;
if (a != null) {
const s = a.style;
for (k in a) {
v = a[k];
if (!["style", "className"].includes(k)) {
props[k] = v;
}
}
if (s != null) {
for (k in s) {
v = s[k];
props.style[k] = v;
}
}
}
props.className +=
" " +
((a != null ? a.className : undefined) != null
? a != null
? a.className
: undefined
: "mathbox-label");
// Push node onto list
return nodes.push(el("div", props, children));
};
f.reset = () => {
nodes = [];
[strideI, strideJ, strideK] = Array.from([
this.strideI,
this.strideJ,
this.strideK,
]);
const c = color.value;
const m = (x) => Math.floor(x * 255);
colorString = c ? `rgb(${[m(c.x), m(c.y), m(c.z)]})` : "";
className = `mathbox-outline-${Math.round(outline.value)}`;
styles = {};
if (c) {
styles.color = colorString;
}
styles.fontSize = `${size.value}px`;
if (zoom.value !== 1) {
styles.zoom = zoom.value;
}
if (zIndex.value > 0) {
styles.zIndex = zIndex.value;
}
if (pointer.value) {
return (styles.pointerEvents = "auto");
}
};
f.nodes = () => nodes;
return f;
}
resize() {
let sI, sJ;
if (this.readback == null) {
return;
}
// Fetch geometry/html dimensions
const pointDims = this.bind.points.getActiveDimensions();
const htmlDims = this.bind.html.getActiveDimensions();
const items = Math.min(pointDims.items, htmlDims.items);
const width = Math.min(pointDims.width, htmlDims.width);
const height = Math.min(pointDims.height, htmlDims.height);
const depth = Math.min(pointDims.depth, htmlDims.depth);
// Limit readback to active area
this.readback.setActive(items, width, height, depth);
// Recalculate iteration strides
this.strideI = sI = htmlDims.items;
this.strideJ = sJ = sI * htmlDims.width;
this.strideK = sJ * htmlDims.height;
}
change(changed, _touched, _init) {
if (changed["dom.html"] || changed["dom.points"]) {
return this.rebuild();
}
}
}
DOM.initClass();
| cchudzicki/mathbox | src/primitives/types/overlay/dom.js | JavaScript | mit | 8,071 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Voxel } from "../data/voxel.js";
export class HTML extends Voxel {
static initClass() {
this.traits = ["node", "buffer", "active", "data", "voxel", "html"];
this.finals = { channels: 1 };
}
init() {
super.init();
this.storage = "pushBuffer";
}
make() {
super.make();
// Get our own size
const { items, width, height, depth } = this.getDimensions();
// Prepare DOM element factory
this.dom = this._overlays.make("dom");
return this.dom.hint(items * width * height * depth);
}
unmake() {
super.unmake();
if (this.dom != null) {
this.dom.dispose();
return (this.dom = null);
}
}
update() {
return super.update();
}
change(changed, touched, init) {
if (touched["html"]) {
return this.rebuild();
}
return super.change(changed, touched, init);
}
nodes() {
return this.buffer.read();
}
callback(callback) {
const { el } = this.dom;
if (callback.length <= 6) {
return (emit, i, j, k, l) => callback(emit, el, i, j, k, l);
} else {
return (emit, i, j, k, l) => {
return callback(
emit,
el,
i,
j,
k,
l,
this.bufferClock,
this.bufferStep
);
};
}
}
}
HTML.initClass();
| cchudzicki/mathbox | src/primitives/types/overlay/html.js | JavaScript | mit | 1,744 |
export * from "./html.js";
export * from "./dom.js";
| cchudzicki/mathbox | src/primitives/types/overlay/index.js | JavaScript | mit | 53 |
export * from "./move.js";
export * from "./play.js";
export * from "./present.js";
export * from "./reveal.js";
export * from "./slide.js";
export * from "./step.js";
| cchudzicki/mathbox | src/primitives/types/present/index.js | JavaScript | mit | 168 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Transition } from "./transition.js";
export class Move extends Transition {
static initClass() {
this.traits = ["node", "transition", "vertex", "move", "visible", "active"];
}
make() {
super.make();
const object = {
moveFrom: this.node.attributes["move.from"],
moveTo: this.node.attributes["move.to"],
};
for (const k in object) {
const v = object[k];
this.uniforms[k] = v;
}
}
vertex(shader, pass) {
let left;
if (pass === this.props.pass) {
shader.pipe("move.position", this.uniforms);
}
return (left = __guard__(this._inherit("vertex"), (x) =>
x.vertex(shader, pass)
)) != null
? left
: shader;
}
}
Move.initClass();
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/present/move.js | JavaScript | mit | 1,419 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Track } from "./track.js";
export class Play extends Track {
static initClass() {
this.traits = ["node", "track", "trigger", "play", "bind"];
}
init() {
super.init();
this.skew = null;
return (this.start = null);
}
reset(go) {
if (go == null) {
go = true;
}
this.skew = go ? 0 : null;
return (this.start = null);
}
make() {
super.make();
// Start on slide, or immediately if not inside slide
this._listen("slide", "slide.step", (e) => {
const { trigger } = this.props;
if (trigger != null && e.index === trigger) {
return this.reset();
}
if (trigger != null && e.index === 0) {
return this.reset(false);
}
});
if (!this.props.trigger || this._inherit("slide") == null) {
this.reset();
}
// Find parent clock
const parentClock = this._inherit("clock");
// Update clock
return this._listen(parentClock, "clock.tick", () => {
const { from, to, speed, pace, delay, realtime } = this.props;
const time = parentClock.getTime();
if (this.skew != null) {
const now = realtime ? time.time : time.clock;
const delta = realtime ? time.delta : time.step;
const ratio = speed / pace;
if (this.start == null) {
this.start = now;
}
this.skew += delta * (ratio - 1);
let offset = Math.max(0, now - this.start + this.skew - delay * ratio);
if (this.props.loop) {
offset = offset % (to - from);
}
this.playhead = Math.min(to, from + offset);
} else {
this.playhead = 0;
}
return this.update();
});
}
update() {
return super.update();
}
change(changed, touched, init) {
if (changed["trigger.trigger"] || changed["play.realtime"]) {
return this.rebuild();
}
return super.change(changed, touched, init);
}
}
Play.initClass();
| cchudzicki/mathbox | src/primitives/types/present/play.js | JavaScript | mit | 2,367 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS202: Simplify dynamic range loops
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class Present extends Parent {
static initClass() {
this.traits = ["node", "present"];
}
init() {}
make() {
this.nodes = [];
this.steps = [];
this.length = 0;
this.last = [];
this.index = 0;
this.dirty = [];
this._listen("root", "root.update", this.update);
return this._compute("present.length", () => this.length);
}
adopt(controller) {
const { node } = controller;
if (this.nodes.indexOf(controller) < 0) {
this.nodes.push(node);
}
return this.dirty.push(controller);
}
unadopt(controller) {
this.nodes = this.nodes.filter((x) => x !== controller);
return this.dirty.push(controller);
}
update() {
if (!this.dirty.length) {
return;
}
for (const controller of Array.from(this.dirty)) {
this.slideReset(controller);
}
[this.steps, this.indices] = Array.from(this.process(this.nodes));
this.length = this.steps.length;
this.index = null;
this.go(this.props.index);
return (this.dirty = []);
}
slideLatch(controller, enabled, step) {
return controller.slideLatch(enabled, step);
}
slideStep(controller, index, step) {
return controller.slideStep(this.mapIndex(controller, index), step);
}
slideRelease(controller, _step) {
return controller.slideRelease();
}
slideReset(controller) {
return controller.slideReset();
}
mapIndex(controller, index) {
return index - this.indices[controller.node._id];
}
process(nodes) {
// Grab nodes' path of slide parents
const slides = (nodes) =>
Array.from(nodes).map((el) => parents(el).filter(isSlide));
const traverse = (map) => (el) =>
(() => {
let ref, ref1;
const result = [];
while (el && (([el, ref] = Array.from((ref1 = [map(el), el]))), ref1)) {
result.push(ref);
}
return result;
})();
const parents = traverse(function (el) {
if (el.parent.traits.hash.present) {
return null;
} else {
return el.parent;
}
});
// Helpers
const isSlide = (el) => nodes.indexOf(el) >= 0;
// Order paths (leaf -> parent slide -> ...)
const order = (paths) =>
paths.sort(function (a, b) {
// Path lengths
const c = a.length;
const d = b.length;
// Compare from outside in
let e = Math.min(c, d);
for (
let i = 1, end = e, asc = 1 <= end;
asc ? i <= end : i >= end;
asc ? i++ : i--
) {
// inclusive end
const nodeA = a[c - i];
const nodeB = b[d - i];
// Explicit sibling order (natural)
const f = nodeA.props.order;
const g = nodeB.props.order;
if (f != null || g != null) {
if (f != null && g != null && (e = f - g) !== 0) {
return e;
}
if (f != null) {
return -1;
}
if (g != null) {
return 1;
}
}
// Document sibling order (inverted)
if (nodeB.order !== nodeA.order) {
return nodeB.order - nodeA.order;
}
}
// Different tree level
e = c - d;
if (e !== 0) {
return e;
}
// Equal
return 0;
});
const split = function (steps) {
const relative = [];
const absolute = [];
for (const step of Array.from(steps)) {
(step[0].props.steps != null ? relative : absolute).push(step);
}
return [relative, absolute];
};
const expand = function (lists) {
let step;
const [relative, absolute] = Array.from(lists);
const limit = 100;
const indices = {};
let steps = [];
const slide = function (step, index) {
let node;
const { props } = (node = step[0]);
const parent = step[1];
const parentIndex = parent != null ? indices[parent._id] : 0;
//throw "parent index missing" if !parentIndex?
const childIndex = index;
let from =
props.from != null
? parentIndex + props.from
: childIndex - props.early;
let to =
props.to != null
? parentIndex + props.to
: childIndex + props.steps + props.late;
from = Math.max(0, from);
to = Math.min(limit, to);
if (indices[node._id] == null) {
indices[node._id] = from;
}
for (
let i = from, end = to, asc = from <= end;
asc ? i < end : i > end;
asc ? i++ : i--
) {
steps[i] = (steps[i] != null ? steps[i] : (steps[i] = [])).concat(
step
);
}
return props.steps;
};
let i = 0;
for (step of Array.from(relative)) {
i += slide(step, i);
}
for (step of Array.from(absolute)) {
slide(step, 0);
}
// Dedupe and order
steps = (() => {
const result = [];
for (step of Array.from(steps)) {
result.push(finalize(dedupe(step)));
}
return result;
})();
return [steps, indices];
};
// Remove duplicates
const dedupe = function (step) {
if (step) {
return (() => {
const result = [];
for (let i = 0; i < step.length; i++) {
const node = step[i];
if (step.indexOf(node) === i) {
result.push(node);
}
}
return result;
})();
} else {
return [];
}
};
// Finalize individual step by document order
const finalize = (step) => step.sort((a, b) => a.order - b.order);
const paths = slides(nodes);
const steps = order(paths);
return expand(split(steps));
}
go(index) {
// Pad with an empty slide before and after for initial enter/final exit
let left;
let node;
index = Math.max(0, Math.min(this.length + 1, +index || 0));
const active = (left = this.steps[index - 1]) != null ? left : [];
const step = this.props.directed ? index - this.index : 1;
this.index = index;
const enter = (() => {
const result = [];
for (node of Array.from(active)) {
if (this.last.indexOf(node) < 0) {
result.push(node);
}
}
return result;
})();
const exit = (() => {
const result1 = [];
for (node of Array.from(this.last)) {
if (active.indexOf(node) < 0) {
result1.push(node);
}
}
return result1;
})();
const stay = (() => {
const result2 = [];
for (node of Array.from(active)) {
if (enter.indexOf(node) < 0 && exit.indexOf(node) < 0) {
result2.push(node);
}
}
return result2;
})();
const ascend = (nodes) => nodes.sort((a, b) => a.order - b.order);
const descend = (nodes) => nodes.sort((a, b) => b.order - a.order);
//const toStr = (x) => x.toString();
//console.log '============================================================'
//console.log 'go', index, {enter: enter.map(toStr), stay: stay.map(toStr), exit: exit.map(toStr)}
for (node of Array.from(ascend(enter))) {
this.slideLatch(node.controller, true, step);
}
for (node of Array.from(ascend(stay))) {
this.slideLatch(node.controller, null, step);
}
for (node of Array.from(ascend(exit))) {
this.slideLatch(node.controller, false, step);
}
for (node of Array.from(enter)) {
this.slideStep(node.controller, index, step);
}
for (node of Array.from(stay)) {
this.slideStep(node.controller, index, step);
}
for (node of Array.from(exit)) {
this.slideStep(node.controller, index, step);
}
for (node of Array.from(descend(enter))) {
this.slideRelease(node.controller);
}
for (node of Array.from(descend(stay))) {
this.slideRelease(node.controller);
}
for (node of Array.from(descend(exit))) {
this.slideRelease(node.controller);
}
this.last = active;
}
change(changed, touched, init) {
if (changed["present.index"] || init) {
return this.go(this.props.index);
}
}
}
Present.initClass();
| cchudzicki/mathbox | src/primitives/types/present/present.js | JavaScript | mit | 8,961 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Transition } from "./transition.js";
export class Reveal extends Transition {
static initClass() {
this.traits = ["node", "transition", "mask", "visible", "active"];
}
mask(shader) {
let left, s;
if (shader) {
s = this._shaders.shader();
s.pipe(UGLSL.identity("vec4"));
s.fan();
s.pipe(shader, this.uniforms);
s.next();
s.pipe("reveal.mask", this.uniforms);
s.end();
s.pipe("float combine(float a, float b) { return min(a, b); }");
} else {
s = this._shaders.shader();
s.pipe("reveal.mask", this.uniforms);
}
return (left = __guard__(this._inherit("mask"), (x) => x.mask(s))) != null
? left
: s;
}
}
Reveal.initClass();
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/present/reveal.js | JavaScript | mit | 1,467 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class Slide extends Parent {
static initClass() {
this.traits = ["node", "slide", "visible", "active"];
}
make() {
this._helpers.visible.make();
this._helpers.active.make();
if (!this._inherit("present")) {
throw new Error(
`${this.node.toString()} must be placed inside <present></present>`
);
}
return this._inherit("present").adopt(this);
}
unmake() {
this._helpers.visible.unmake();
this._helpers.active.unmake();
return this._inherit("present").unadopt(this);
}
change(changed, _touched, _init) {
if (
changed["slide.early"] ||
changed["slide.late"] ||
changed["slide.steps"] ||
changed["slide.from"] ||
changed["slide.to"]
) {
return this.rebuild();
}
}
slideLatch(enabled, step) {
//console.log 'slide:latch', @node.toString(), enabled, step
this.trigger({
type: "transition.latch",
step: step,
});
if (enabled != null) {
return this._instant(enabled);
}
}
slideStep(index, step) {
//console.log 'slide:step', @node.toString(), index, step
return this.trigger({
type: "slide.step",
index: index,
step: step,
});
}
slideRelease() {
//console.log 'slide:release', @node.toString()
return this.trigger({
type: "transition.release",
});
}
slideReset() {
this._instant(false);
return this.trigger({
type: "slide.reset",
});
}
_instant(enabled) {
//console.log 'slide:instant', @node.toString(), enabled
this.setVisible(enabled);
return this.setActive(enabled);
}
}
Slide.initClass();
| cchudzicki/mathbox | src/primitives/types/present/slide.js | JavaScript | mit | 2,121 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Track } from "./track.js";
export class Step extends Track {
static initClass() {
this.traits = ["node", "track", "step", "trigger", "bind"];
}
make() {
super.make();
const clock = this._inherit("clock");
if (this.actualIndex == null) {
this.actualIndex = null;
}
this.animateIndex = this._animator.make(this._types.number(0), {
clock,
realtime: this.props.realtime,
step: (value) => {
return (this.actualIndex = value);
},
});
if (this.lastIndex == null) {
this.lastIndex = null;
}
this.animateStep = this._animator.make(this._types.number(0), {
clock,
realtime: this.props.realtime,
step: (value) => {
this.playhead = value;
return this.update();
},
});
this.stops =
this.props.stops != null
? this.props.stops
: __range__(0, this.script.length, false);
// Seek instantly after reset
this._listen("slide", "slide.reset", (_e) => {
return (this.lastIndex = null);
});
// Update playhead in response to slide change
return this._listen("slide", "slide.step", (e) => {
let left;
let { duration } = this.props;
const { delay, pace, speed, playback, rewind, skip, trigger } =
this.props;
// Note: enter phase is from index 0 to 1
const i = Math.max(0, Math.min(this.stops.length - 1, e.index - trigger));
// Animation range
const from = this.playhead;
const to = this.stops[i];
// Seek if first step after reset
if (this.lastIndex == null && trigger) {
this.lastIndex = i;
this.animateStep.set(to);
this.animateIndex.set(i);
return;
}
// Calculate actual step from current offset (may be still animating)
let last =
(left = this.actualIndex != null ? this.actualIndex : this.lastIndex) !=
null
? left
: 0;
const step = i - last;
// Don't count duped stops
const skips = this.stops.slice(Math.min(last, i), Math.max(last, i));
let free = 0;
last = skips.shift();
for (const stop of Array.from(skips)) {
if (last === stop) {
free++;
}
last = stop;
}
// Remember last intended stop
this.lastIndex = i;
// Apply rewind factor
let factor = speed * (e.step >= 0 ? 1 : rewind);
// Pass through multiple steps at faster rate if skip is enabled
factor *= skip ? Math.max(1, Math.abs(step) - free) : 1;
// Apply pace
duration += (Math.abs(to - from) * pace) / factor;
if (from !== to) {
this.animateIndex.immediate(i, { delay, duration, ease: playback });
return this.animateStep.immediate(to, {
delay,
duration,
ease: playback,
});
}
});
}
made() {
return this.update();
}
unmake() {
this.animateIndex.dispose();
this.animateStep.dispose();
this.animateIndex = this.animateStep = null;
return super.unmake();
}
change(changed, touched, init) {
if (changed["step.stops"] || changed["step.realtime"]) {
return this.rebuild();
}
return super.change(changed, touched, init);
}
}
Step.initClass();
function __range__(left, right, inclusive) {
const range = [];
const ascending = left < right;
const end = !inclusive ? right : ascending ? right + 1 : right - 1;
for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
range.push(i);
}
return range;
}
| cchudzicki/mathbox | src/primitives/types/present/step.js | JavaScript | mit | 4,083 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS104: Avoid inline assignments
* DS205: Consider reworking code to avoid use of IIFEs
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as Ease from "../../../util/ease.js";
import { Primitive } from "../../primitive.js";
const deepCopy = function (x) {
const out = {};
for (const k in x) {
const v = x[k];
if (v instanceof Array) {
out[k] = v.slice();
} else if (v != null && typeof v === "object") {
out[k] = deepCopy(v);
} else {
out[k] = v;
}
}
return out;
};
export class Track extends Primitive {
static initClass() {
this.traits = ["node", "track", "seek", "bind"];
}
init() {
this.handlers = {};
this.script = null;
this.values = null;
this.playhead = 0;
this.velocity = null;
this.section = null;
return (this.expr = null);
}
make() {
// Bind to attached data sources
let ref;
this._helpers.bind.make([
{ to: "track.target", trait: "node", callback: null },
]);
const { script } = this.props;
const { node } = this.bind.target;
this.targetNode = node;
return (
([this.script, this.values, this.start, this.end] = Array.from(
(ref = this._process(node, script))
)),
ref
);
}
unmake() {
this.unbindExpr();
this._helpers.bind.unmake();
this.script =
this.values =
this.start =
this.end =
this.section =
this.expr =
null;
return (this.playhead = 0);
}
// Bind animated expressions
bindExpr(expr) {
this.unbindExpr();
this.expr = expr;
this.targetNode.bind(expr, true);
// Measure playhead velocity on attribute computation
const { clock } = this.targetNode;
const self = this;
return this._attributes.bind(
(this.measure = (function () {
let playhead = null;
return () => {
const { step } = clock.getTime();
if (playhead != null) {
self.velocity = (self.playhead - playhead) / step;
}
return (playhead = self.playhead);
};
})())
);
}
unbindExpr() {
if (this.expr != null) {
this.targetNode.unbind(this.expr, true);
}
if (this.measure != null) {
this._attributes.unbind(this.measure);
}
return (this.expr = this.measure = null);
}
// Process script steps by filling out missing props
_process(object, script) {
let k, key, last, message, s, step, v;
if (script instanceof Array) {
// Normalize array to numbered dict
s = {};
for (let i = 0; i < script.length; i++) {
step = script[i];
s[i] = step;
}
script = s;
}
// Normalize keyed steps to array of step objects
s = [];
for (key in script) {
step = script[key];
if (step == null) {
step = [];
}
if (step instanceof Array) {
// [props, expr] array
step = {
key: +key,
props: step[0] != null ? deepCopy(step[0]) : {},
expr: step[1] != null ? deepCopy(step[1]) : {},
};
} else {
if (step.key == null && !step.props && !step.expr) {
// Direct props object (iffy, but people will do this anyhow)
step = { props: deepCopy(step) };
} else {
// Proper step
step = deepCopy(step);
}
// Prepare step object
step.key = step.key != null ? +step.key : +key;
if (step.props == null) {
step.props = {};
}
if (step.expr == null) {
step.expr = {};
}
}
s.push(step);
}
script = s;
if (!script.length) {
return [[], {}, 0, 0];
}
// Sort by keys
script.sort((a, b) => a.key - b.key);
const start = script[0].key;
const end = script[script.length - 1].key;
// Connect steps
for (key in script) {
step = script[key];
if (last != null) {
last.next = step;
}
last = step;
}
// Last step leads to itself
last.next = last;
script = s;
// Determine starting props
const props = {};
const values = {};
for (key in script) {
step = script[key];
for (k in step.props) {
v = step.props[k];
props[k] = true;
}
}
for (key in script) {
step = script[key];
for (k in step.expr) {
v = step.expr[k];
props[k] = true;
}
}
for (k in props) {
props[k] = object.get(k);
}
try {
// Need two sources and one destination value for correct mixing of live expressions
for (k in props) {
values[k] = [
object.attribute(k).T.make(),
object.attribute(k).T.make(),
object.attribute(k).T.make(),
];
}
} catch (error) {
console.warn(this.node.toMarkup());
message = `${this.node.toString()} - Target ${object} has no \`${k}\` property`;
throw new Error(message);
}
const result = [];
// Normalize script props, insert held values
for (step of Array.from(script)) {
for (k in props) {
v = props[k];
v = object.validate(k, step.props[k] != null ? step.props[k] : v);
props[k] = step.props[k] = v;
if (step.expr[k] != null && typeof step.expr[k] !== "function") {
console.warn(this.node.toMarkup());
message = `${this.node.toString()} - Expression \`${
step.expr[k]
}\` on property \`${k}\` is not a function`;
throw new Error(message);
}
}
result.push(step);
}
return [result, values, start, end];
}
update() {
let { playhead } = this;
const { script } = this;
const { ease, seek } = this.props;
const node = this.targetNode;
if (seek != null) {
playhead = seek;
}
if (script.length) {
let k;
const find = function () {
let last = script[0];
for (let i = 0; i < script.length; i++) {
const step = script[i];
if (step.key > playhead) {
break;
}
last = step;
}
return last;
};
let { section } = this;
if (!section || playhead < section.key || playhead > section.next.key) {
section = find(script, playhead);
}
if (section === this.section) {
return;
}
this.section = section;
const from = section;
const to = section.next;
const start = from.key;
const end = to.key;
// Easing of playhead along track
const easeMethod = (() => {
switch (ease) {
case "linear":
case 0:
return Ease.clamp;
case "cosine":
case 1:
return Ease.cosine;
case "binary":
case 2:
return Ease.binary;
case "hold":
case 3:
return Ease.hold;
default:
return Ease.cosine;
}
})();
// Callback for live playhead interpolator (linear approx time travel)
const { clock } = node;
const getPlayhead = (time) => {
if (this.velocity == null) {
return this.playhead;
}
const now = clock.getTime();
return this.playhead + this.velocity * (time - now.time);
};
const getLerpFactor = (function () {
const scale = 1 / Math.max(0.0001, end - start);
return (time) => easeMethod((getPlayhead(time) - start) * scale, 0, 1);
})();
// Create prop expression interpolator
const live = (key) => {
const fromE = from.expr[key];
const toE = to.expr[key];
const fromP = from.props[key];
const toP = to.props[key];
const invalid = function () {
console.warn(node.toMarkup());
throw new Error(
`${this.node.toString()} - Invalid expression result on track \`${key}\``
);
};
const attr = node.attribute(key);
const values = this.values[key];
const animator = this._animator;
// Lerp between two expressions
if (fromE && toE) {
return ((values, _from, _to) =>
function (time, delta) {
let _from, _to;
values[0] = _from = attr.T.validate(
fromE(time, delta),
values[0],
invalid
);
values[1] = _to = attr.T.validate(
toE(time, delta),
values[1],
invalid
);
return (values[2] = animator.lerp(
attr.T,
_from,
_to,
getLerpFactor(time),
values[2]
));
})(values, from, to);
// Lerp between an expression and a constant
} else if (fromE) {
return ((values, _from, _to) =>
function (time, delta) {
let _from;
values[0] = _from = attr.T.validate(
fromE(time, delta),
values[0],
invalid
);
return (values[1] = animator.lerp(
attr.T,
_from,
toP,
getLerpFactor(time),
values[1]
));
})(values, from, to);
// Lerp between a constant and an expression
} else if (toE) {
return ((values, _from, _to) =>
function (time, delta) {
let _to;
values[0] = _to = attr.T.validate(
toE(time, delta),
values[0],
invalid
);
return (values[1] = animator.lerp(
attr.T,
fromP,
_to,
getLerpFactor(time),
values[1]
));
})(values, from, to);
// Lerp between two constants
} else {
return (
(values, _from, _to) => (time, _delta) =>
(values[0] = animator.lerp(
attr.T,
fromP,
toP,
getLerpFactor(time),
values[0]
))
)(values, from, to);
}
};
// Handle expr / props on both ends
const expr = {};
for (k in from.expr) {
if (expr[k] == null) {
expr[k] = live(k);
}
}
for (k in to.expr) {
if (expr[k] == null) {
expr[k] = live(k);
}
}
for (k in from.props) {
if (expr[k] == null) {
expr[k] = live(k);
}
}
for (k in to.props) {
if (expr[k] == null) {
expr[k] = live(k);
}
}
// Bind node props
return this.bindExpr(expr);
}
}
change(changed, touched, init) {
if (
changed["track.target"] ||
changed["track.script"] ||
changed["track.mode"]
) {
return this.rebuild();
}
if (changed["seek.seek"] || init) {
return this.update();
}
}
}
Track.initClass();
| cchudzicki/mathbox | src/primitives/types/present/track.js | JavaScript | mit | 11,591 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class Transition extends Parent {
static initClass() {
this.traits = [
"node",
"transition",
"transform",
"mask",
"visible",
"active",
];
}
init() {
this.animate = null;
this.uniforms = null;
this.state = {
isVisible: true,
isActive: true,
enter: 1,
exit: 1,
};
this.latched = null;
return (this.locked = null);
}
make() {
this.uniforms = {
transitionFrom: this._attributes.make(this._types.vec4()),
transitionTo: this._attributes.make(this._types.vec4()),
transitionActive: this._attributes.make(this._types.bool()),
transitionScale: this._attributes.make(this._types.vec4()),
transitionBias: this._attributes.make(this._types.vec4()),
transitionEnter: this._attributes.make(this._types.number()),
transitionExit: this._attributes.make(this._types.number()),
transitionSkew: this._attributes.make(this._types.number()),
};
const slideParent = this._inherit("slide");
const visibleParent = this._inherit("visible");
const activeParent = this._inherit("active");
this._listen(slideParent, "transition.latch", (e) => this.latch(e.step));
this._listen(slideParent, "transition.release", () => this.release());
this._listen(visibleParent, "visible.change", () => {
//console.log @node.toString(), 'visible.change ^', visibleParent.isVisible
return this.update((this.state.isVisible = visibleParent.isVisible));
});
this._listen(activeParent, "active.change", () => {
//console.log @node.toString(), 'active.change ^', activeParent.isActive
return this.update((this.state.isActive = activeParent.isActive));
});
this.animate = this._animator.make(this._types.vec2(1, 1), {
step: (value) => {
this.state.enter = value.x;
this.state.exit = value.y;
return this.update();
},
complete: (done) => this.complete(done),
});
return (this.move = this.props.from != null || this.props.to != null);
}
//@_helpers.visible.make()
//@_helpers.active.make()
unmake() {
return this.animate.dispose();
}
//@_helpers.visible.unmake()
//@_helpers.active.unmake()
latch(step) {
let latched;
this.locked = null;
this.latched = latched = {
isVisible: this.state.isVisible,
isActive: this.state.isActive,
step,
};
// Reset enter/exit animation if invisible
const visible = this.isVisible;
if (!visible) {
const forward = latched.step >= 0;
const [enter, exit] = Array.from(forward ? [0, 1] : [1, 0]);
return this.animate.set(enter, exit);
}
}
//console.log @node.toString(), 'transition::latch', @latched, enter, exit
release() {
// Get before/after and unlatch state
const { latched } = this;
const { state } = this;
this.latched = null;
//console.log @node.toString(), 'transition::release', JSON.parse JSON.stringify {latched, state}
//p = @; console.log '-> ', p.node.toString(), p.isVisible while p = p._inherit 'visible'
// Transition if visibility state change
if (latched.isVisible !== state.isVisible) {
// Maintain step direction
const forward = latched.step >= 0;
const visible = state.isVisible;
const [enter, exit] = Array.from(
visible ? [1, 1] : forward ? [1, 0] : [0, 1]
);
// Get duration
let { duration, durationEnter, durationExit } = this.props;
if (durationEnter == null) {
durationEnter = duration;
}
if (durationExit == null) {
durationExit = duration;
}
duration = visible * durationEnter + !visible * durationExit;
// Get delay
let { delay, delayEnter, delayExit } = this.props;
if (delayEnter == null) {
delayEnter = delay;
}
if (delayExit == null) {
delayExit = delay;
}
delay = visible * delayEnter + !visible * delayExit;
// Animate enter/exit
//console.log @node.toString(), '@animate.immediate', {x: enter, y: exit}, {duration, delay, ease: 'linear'}
this.animate.immediate(
{ x: enter, y: exit },
{ duration, delay, ease: "linear" }
);
// Lock visibility and active open during transition
this.locked = {
isVisible: true,
isActive: latched.isActive || state.isActive,
};
}
return this.update();
}
complete(done) {
if (!done) {
return;
}
this.locked = null;
return this.update();
}
update() {
if (this.latched != null) {
return;
} // latched
let { enter, exit } = this.props;
// Resolve transition state
if (enter == null) {
({ enter } = this.state);
}
if (exit == null) {
({ exit } = this.state);
}
const level = enter * exit;
let visible = level > 0;
const partial = level < 1;
this.uniforms.transitionEnter.value = enter;
this.uniforms.transitionExit.value = exit;
this.uniforms.transitionActive.value = partial;
// Resolve visibility state
if (visible) {
visible = !!this.state.isVisible;
}
if (this.locked != null) {
visible = this.locked.isVisible;
}
if (this.isVisible !== visible) {
this.isVisible = visible;
this.trigger({ type: "visible.change" });
}
// Resolve active state
const active = !!(
this.state.isActive ||
(this.locked != null ? this.locked.isActive : undefined)
);
if (this.isActive !== active) {
this.isActive = active;
return this.trigger({ type: "active.change" });
}
}
//console.log 'transition update', 'enter', enter, 'exit', exit, 'visible', visible, 'active', active
change(changed, touched, init) {
if (changed["transition.enter"] || changed["transition.exit"] || init) {
this.update();
}
if (changed["transition.stagger"] || init) {
const { stagger } = this.props;
// Precompute shader constants
const flipX = stagger.x < 0;
const flipY = stagger.y < 0;
const flipZ = stagger.z < 0;
const flipW = stagger.w < 0;
const staggerX = Math.abs(stagger.x);
const staggerY = Math.abs(stagger.y);
const staggerZ = Math.abs(stagger.z);
const staggerW = Math.abs(stagger.w);
this.uniforms.transitionSkew.value =
staggerX + staggerY + staggerZ + staggerW;
this.uniforms.transitionScale.value.set(
(1 - flipX * 2) * staggerX,
(1 - flipY * 2) * staggerY,
(1 - flipZ * 2) * staggerZ,
(1 - flipW * 2) * staggerW
);
return this.uniforms.transitionBias.value.set(
flipX * staggerX,
flipY * staggerY,
flipZ * staggerZ,
flipW * staggerW
);
}
}
}
Transition.initClass();
| cchudzicki/mathbox | src/primitives/types/present/transition.js | JavaScript | mit | 7,370 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Primitive } from "../../primitive.js";
export class Compose extends Primitive {
static initClass() {
this.traits = [
"node",
"bind",
"object",
"visible",
"operator",
"style",
"compose",
];
this.defaults = {
zWrite: false,
zTest: false,
color: "#ffffff",
};
}
init() {
return (this.compose = null);
}
//rebuild: () ->
// console.log 'compose.rebuild', @node.get(null, true), @bind.source?
// super()
resize() {
if (!this.compose || !this.bind.source) {
return;
}
const dims = this.bind.source.getActiveDimensions();
const { width } = dims;
const { height } = dims;
return this.remapUVScale.set(width, height);
}
make() {
// Bind to attached data sources
this._helpers.bind.make([{ to: "operator.source", trait: "source" }]);
if (this.bind.source == null) {
return;
}
// Prepare uniforms for remapping to absolute coords on the fly
const resampleUniforms = {
remapUVScale: this._attributes.make(this._types.vec2()),
};
this.remapUVScale = resampleUniforms.remapUVScale.value;
// Build fragment shader
let fragment = this._shaders.shader();
const { alpha } = this.props;
if (this.bind.source.is("image")) {
// Sample image directly in 2D UV
fragment.pipe("screen.pass.uv", resampleUniforms);
fragment = this.bind.source.imageShader(fragment);
} else {
// Sample data source in 4D
fragment.pipe("screen.map.xy", resampleUniforms);
fragment = this.bind.source.sourceShader(fragment);
}
// Force pixels to solid if requested
if (!alpha) {
fragment.pipe("color.opaque");
}
// Make screen renderable
const composeUniforms = this._helpers.style.uniforms();
this.compose = this._renderables.make("screen", {
map: fragment,
uniforms: composeUniforms,
linear: true,
});
this._helpers.visible.make();
return this._helpers.object.make([this.compose]);
}
made() {
return this.resize();
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
return this._helpers.object.unmake();
}
change(changed, _touched, _init) {
if (changed["operator.source"] || changed["compose.alpha"]) {
return this.rebuild();
}
}
}
Compose.initClass();
| cchudzicki/mathbox | src/primitives/types/rtt/compose.js | JavaScript | mit | 2,813 |
export * from "./rtt.js";
export * from "./compose.js";
| cchudzicki/mathbox | src/primitives/types/rtt/index.js | JavaScript | mit | 56 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class RTT extends Parent {
static initClass() {
this.traits = [
"node",
"root",
"scene",
"vertex",
"texture",
"rtt",
"source",
"index",
"image",
];
this.defaults = {
minFilter: "linear",
magFilter: "linear",
type: "unsignedByte",
};
}
init() {
return (this.rtt =
this.scene =
this.camera =
this.width =
this.height =
this.history =
this.rootSize =
this.size =
null);
}
indexShader(shader) {
return shader;
}
imageShader(shader) {
return this.rtt.shaderRelative(shader);
}
sourceShader(shader) {
return this.rtt.shaderAbsolute(shader, this.history);
}
getDimensions() {
return {
items: 1,
width: this.width,
height: this.height,
depth: this.history,
};
}
getActiveDimensions() {
return this.getDimensions();
}
make() {
let aspect;
this.parentRoot = this._inherit("root");
this.rootSize = this.parentRoot.getSize();
this._listen(this.parentRoot, "root.pre", this.pre);
this._listen(this.parentRoot, "root.update", this.update);
this._listen(this.parentRoot, "root.render", this.render);
this._listen(this.parentRoot, "root.post", this.post);
this._listen(this.parentRoot, "root.camera", this.setCamera);
this._listen(this.parentRoot, "root.resize", function (event) {
return this.resize(event.size);
});
if (this.rootSize == null) {
return;
}
const { minFilter, magFilter, type } = this.props;
const { width, height, history, size } = this.props;
const relativeSize =
size === this.node.attributes["rtt.size"].enum.relative;
const widthFactor = relativeSize ? this.rootSize.renderWidth : 1;
const heightFactor = relativeSize ? this.rootSize.renderHeight : 1;
this.width = Math.round(
width != null ? width * widthFactor : this.rootSize.renderWidth
);
this.height = Math.round(
height != null ? height * heightFactor : this.rootSize.renderHeight
);
this.history = history;
this.aspect = aspect = this.width / this.height;
if (this.scene == null) {
this.scene = this._renderables.make("scene");
}
this.rtt = this._renderables.make("renderToTexture", {
scene: this.scene,
camera: this._context.defaultCamera,
width: this.width,
height: this.height,
frames: this.history,
minFilter,
magFilter,
type,
});
aspect = width || height ? aspect : this.rootSize.aspect;
const viewWidth = width != null ? width : this.rootSize.viewWidth;
const viewHeight = height != null ? height : this.rootSize.viewHeight;
return (this.size = {
renderWidth: this.width,
renderHeight: this.height,
aspect,
viewWidth,
viewHeight,
pixelRatio: this.height / viewHeight,
});
}
made() {
// Notify of buffer reallocation
this.trigger({
type: "source.rebuild",
});
if (this.size) {
return this.trigger({
type: "root.resize",
size: this.size,
});
}
}
unmake(rebuild) {
if (this.rtt == null) {
return;
}
this.rtt.dispose();
if (!rebuild) {
this.scene.dispose();
}
return (this.rtt = this.width = this.height = this.history = null);
}
change(changed, touched, init) {
if (touched["texture"] || changed["rtt.width"] || changed["rtt.height"]) {
return this.rebuild();
}
if (changed["root.camera"] || init) {
this._unattach();
this._attach(
this.props.camera,
"camera",
this.setCamera,
this,
this,
true
);
return this.setCamera();
}
}
adopt(renderable) {
return Array.from(renderable.renders).map((object) =>
this.scene.add(object)
);
}
unadopt(renderable) {
return Array.from(renderable.renders).map((object) =>
this.scene.remove(object)
);
}
resize(size) {
let height, width;
this.rootSize = size;
({ width, height, size } = this.props);
const relativeSize =
size === this.node.attributes["rtt.size"].enum.relative;
if (!this.rtt || width == null || height == null || relativeSize) {
return this.rebuild();
}
}
select(selector) {
return this._root.node.model.select(selector, [this.node]);
}
watch(selector, handler) {
return this._root.node.model.watch(selector, handler);
}
unwatch(handler) {
return this._root.node.model.unwatch(handler);
}
pre(e) {
return this.trigger(e);
}
update(e) {
let camera;
if ((camera = this.getOwnCamera()) != null) {
camera.aspect = this.aspect || 1;
camera.updateProjectionMatrix();
}
return this.trigger(e);
}
render(e) {
this.trigger(e);
return this.rtt != null ? this.rtt.render(this.getCamera()) : undefined;
}
post(e) {
return this.trigger(e);
}
setCamera() {
const camera = __guard__(
this.select(this.props.camera)[0],
(x) => x.controller
);
if (this.camera !== camera) {
this.camera = camera;
this.rtt.camera = this.getCamera();
return this.trigger({ type: "root.camera" });
} else if (!this.camera) {
return this.trigger({ type: "root.camera" });
}
}
getOwnCamera() {
return this.camera != null ? this.camera.getCamera() : undefined;
}
getCamera() {
let left;
return (left = this.getOwnCamera()) != null
? left
: this._inherit("root").getCamera();
}
// End transform chain here
vertex(shader, pass) {
if (pass === 2) {
return shader.pipe("view.position");
}
if (pass === 3) {
return shader.pipe("root.position");
}
return shader;
}
}
RTT.initClass();
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/rtt/rtt.js | JavaScript | mit | 6,621 |
export * from "./shader.js";
| cchudzicki/mathbox | src/primitives/types/shader/index.js | JavaScript | mit | 29 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Primitive } from "../../primitive.js";
export class Shader extends Primitive {
static initClass() {
this.traits = ["node", "bind", "shader"];
this.freeform = true;
}
init() {
return (this.shader = null);
}
make() {
const { language, code } = this.props;
if (language !== "glsl") {
throw new Error("GLSL required");
}
// Bind to attached data sources
this._helpers.bind.make([
{ to: "shader.sources", trait: "source", multiple: true },
]);
// Parse snippet w/ shadergraph (will do implicit DOM script tag by ID
// lookup if simple selector or ID given)
const snippet = this._shaders.fetch(code);
// Convert uniforms to attributes
const types = this._types;
const uniforms = {};
const make = (type) => {
let t;
switch (type) {
case "i":
return types.int();
case "f":
return types.number();
case "v2":
return types.vec2();
case "v3":
return types.vec3();
case "v4":
return types.vec4();
case "m3":
return types.mat3();
case "m4":
return types.mat4();
case "t":
return types.object();
default:
t = type.split("");
if (t.pop() === "v") {
return types.array(make(t.join("")));
} else {
return null;
}
}
};
for (const def of Array.from(snippet._signatures.uniform)) {
let type;
if ((type = make(def.type))) {
uniforms[def.name] = type;
}
}
// Reconfigure node model
return this.reconfigure({ props: { uniform: uniforms } });
}
made() {
// Notify of shader reallocation
return this.trigger({
type: "source.rebuild",
});
}
unmake() {
return (this.shader = null);
}
change(changed, _touched, _init) {
if (
changed["shader.uniforms"] ||
changed["shader.code"] ||
changed["shader.language"]
) {
return this.rebuild();
}
}
shaderBind(uniforms) {
let k, u, v;
if (uniforms == null) {
uniforms = {};
}
const { code } = this.props;
// Merge in prop attributes as uniforms
for (k in this.node.attributes) {
v = this.node.attributes[k];
if (v.type != null && v.short != null && v.ns === "uniform") {
if (uniforms[v.short] == null) {
uniforms[v.short] = v;
}
}
}
// Merge in explicit uniform object if set
if ((u = this.props.uniforms) != null) {
for (k in u) {
v = u[k];
uniforms[k] = v;
}
}
// New shader
const s = this._shaders.shader();
// Require sources
if (this.bind.sources != null) {
for (const source of Array.from(this.bind.sources)) {
s.require(source.sourceShader(this._shaders.shader()));
}
}
// Build bound shader
return s.pipe(code, uniforms);
}
}
Shader.initClass();
| cchudzicki/mathbox | src/primitives/types/shader/shader.js | JavaScript | mit | 3,461 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { FloatType, NearestFilter } from "three/src/constants.js";
import { Operator } from "../operator/operator.js";
export class Format extends Operator {
static initClass() {
this.traits = [
"node",
"bind",
"operator",
"texture",
"text",
"format",
"font",
];
this.defaults = {
minFilter: "linear",
magFilter: "linear",
};
}
init() {
super.init();
this.atlas = this.buffer = this.used = this.time = null;
return (this.filled = false);
}
sourceShader(shader) {
return this.buffer.shader(shader);
}
textShader(shader) {
return this.atlas.shader(shader);
}
textIsSDF() {
return this.props.sdf > 0;
}
textHeight() {
return this.props.detail;
}
make() {
// Bind to attached data sources # super()
this._helpers.bind.make([{ to: "operator.source", trait: "raw" }]);
// Read sampling parameters
let { minFilter, magFilter, type } = this.props;
// Read font parameters
const { font, style, variant, weight, detail, sdf } = this.props;
// Prepare text atlas
this.atlas = this._renderables.make("textAtlas", {
font,
size: detail,
style,
variant,
weight,
outline: sdf,
minFilter,
magFilter,
type,
});
// Underlying data buffer needs no filtering
minFilter = NearestFilter;
magFilter = NearestFilter;
type = FloatType;
// Fetch geometry dimensions
const dims = this.bind.source.getDimensions();
const { items, width, height, depth } = dims;
// Create voxel buffer for text atlas coords
this.buffer = this._renderables.make("voxelBuffer", {
width,
height,
depth,
channels: 4,
items,
minFilter,
magFilter,
type,
});
// Hook buffer emitter to map atlas text
const { atlas } = this;
const { emit } = this.buffer.streamer;
this.buffer.streamer.emit = (t) => atlas.map(t, emit);
// Grab parent clock
this.clockParent = this._inherit("clock");
return this._listen("root", "root.update", this.update);
}
made() {
super.made();
return this.resize();
}
unmake() {
super.unmake();
if (this.buffer) {
this.buffer.dispose();
this.buffer = null;
}
if (this.atlas) {
this.atlas.dispose();
return (this.atlas = null);
}
}
update() {
if ((this.filled && !this.props.live) || !this.through) {
return;
}
this.time = this.clockParent.getTime();
const { used } = this;
this.atlas.begin();
this.used = this.through();
this.buffer.write(this.used);
this.atlas.end();
this.filled = true;
if (used !== this.used) {
return this.trigger({
type: "source.resize",
});
}
}
change(changed, touched, init) {
if (touched["font"]) {
return this.rebuild();
}
if (
changed["format.expr"] ||
changed["format.digits"] ||
changed["format.data"] ||
init
) {
let map;
let { expr } = this.props;
const { digits, data } = this.props;
if (expr == null) {
if (data != null) {
expr = (x, y, z, w, i) => data[i];
} else {
expr = (x) => x;
}
}
const { length } = expr;
if (digits != null) {
expr = (
(expr) => (x, y, z, w, i, j, k, l, t, d) =>
+expr(x, y, z, w, i, j, k, l, t, d).toPrecision(digits)
)(expr);
}
// Stream raw source data and format it with expression
if (length > 8) {
map = (emit, x, y, z, w, i, j, k, l, _t, _d) => {
return emit(
expr(x, y, z, w, i, j, k, l, this.time.clock, this.time.step)
);
};
} else {
map = (emit, x, y, z, w, i, j, k, l) => {
return emit(expr(x, y, z, w, i, j, k, l));
};
}
return (this.through = this.bind.source
.rawBuffer()
.through(map, this.buffer));
}
}
}
Format.initClass();
| cchudzicki/mathbox | src/primitives/types/text/format.js | JavaScript | mit | 4,486 |
export * from "./text.js";
export * from "./format.js";
export * from "./label.js";
export * from "./retext.js";
| cchudzicki/mathbox | src/primitives/types/text/index.js | JavaScript | mit | 113 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UJS from "../../../util/js.js";
import { Primitive } from "../../primitive.js";
export class Label extends Primitive {
static initClass() {
this.traits = [
"node",
"bind",
"object",
"visible",
"style",
"label",
"attach",
"geometry",
"position",
];
}
make() {
let color;
super.make();
// Bind to attached objects
this._helpers.bind.make([
{ to: "label.text", trait: "text" },
{ to: "geometry.points", trait: "source" },
{ to: "geometry.colors", trait: "source" },
]);
if (this.bind.points == null) {
return;
}
if (this.bind.text == null) {
return;
}
// Fetch geometry/text dimensions
const pointDims = this.bind.points.getDimensions();
const textDims = this.bind.text.getDimensions();
const textIsSDF = this.bind.text.textIsSDF();
const items = Math.min(pointDims.items, textDims.items);
const width = Math.min(pointDims.width, textDims.width);
const height = Math.min(pointDims.height, textDims.height);
const depth = Math.min(pointDims.depth, textDims.depth);
// Build shader to sample position data
// and transform into screen space
let position = this.bind.points.sourceShader(this._shaders.shader());
position = this._helpers.position.pipeline(position);
// Build shader to sample text geometry data
const sprite = this.bind.text.sourceShader(this._shaders.shader());
// Build shader to sample text image data
const map = this._shaders.shader().pipe("label.map");
map.pipe(this.bind.text.textShader(this._shaders.shader()));
// Build shader to resolve text data
const labelUniforms = {
spriteDepth: this.node.attributes["attach.depth"],
spriteOffset: this.node.attributes["attach.offset"],
spriteSnap: this.node.attributes["attach.snap"],
spriteScale: this._attributes.make(this._types.number()),
outlineStep: this._attributes.make(this._types.number()),
outlineExpand: this._attributes.make(this._types.number()),
outlineColor: this.node.attributes["label.background"],
};
this.spriteScale = labelUniforms.spriteScale;
this.outlineStep = labelUniforms.outlineStep;
this.outlineExpand = labelUniforms.outlineExpand;
const snippet = textIsSDF ? "label.outline" : "label.alpha";
const combine = this._shaders.shader().pipe(snippet, labelUniforms);
// Build color lookup
if (this.bind.colors) {
color = this._shaders.shader();
this.bind.colors.sourceShader(color);
}
// Build transition mask lookup
const mask = this._helpers.object.mask();
// Prepare bound uniforms
const styleUniforms = this._helpers.style.uniforms();
const unitUniforms = this._inherit("unit").getUnitUniforms();
// Make sprite renderable
const uniforms = UJS.merge(unitUniforms, styleUniforms, labelUniforms);
this.sprite = this._renderables.make("sprite", {
uniforms,
width,
height,
depth,
items,
position,
sprite,
map,
combine,
color,
mask,
linear: true,
});
this._helpers.visible.make();
return this._helpers.object.make([this.sprite]);
}
unmake() {
this._helpers.bind.unmake();
this._helpers.visible.unmake();
this._helpers.object.unmake();
return (this.sprite = null);
}
resize() {
// Fetch geometry/text dimensions
const pointDims = this.bind.points.getActiveDimensions();
const textDims = this.bind.text.getActiveDimensions();
const items = Math.min(pointDims.items, textDims.items);
const width = Math.min(pointDims.width, textDims.width);
const height = Math.min(pointDims.height, textDims.height);
const depth = Math.min(pointDims.depth, textDims.depth);
return this.sprite.geometry.clip(width, height, depth, items);
}
change(changed, touched, _init) {
if (touched["geometry"] || changed["label.text"]) {
return this.rebuild();
}
if (this.bind.points == null) {
return;
}
const { size } = this.props;
const { outline } = this.props;
const { expand } = this.props;
const height = this.bind.text.textHeight();
const scale = size / height;
this.outlineExpand.value = ((expand / scale) * 16) / 255;
this.outlineStep.value = ((outline / scale) * 16) / 255;
return (this.spriteScale.value = scale);
}
}
Label.initClass();
| cchudzicki/mathbox | src/primitives/types/text/label.js | JavaScript | mit | 4,892 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Resample } from "../operator/resample.js";
export class Retext extends Resample {
static initClass() {
this.traits = [
"node",
"bind",
"operator",
"resample",
"sampler:x",
"sampler:y",
"sampler:z",
"sampler:w",
"include",
"text",
];
}
init() {
return (this.sourceSpec = [{ to: "operator.source", trait: "text" }]);
}
textShader(shader) {
return this.bind.source.textShader(shader);
}
textIsSDF() {
return (
(this.bind.source != null ? this.bind.source.props.sdf : undefined) > 0
);
}
textHeight() {
return this.bind.source != null ? this.bind.source.props.detail : undefined;
}
}
Retext.initClass();
| cchudzicki/mathbox | src/primitives/types/text/retext.js | JavaScript | mit | 1,142 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../../util/data.js";
import { FloatType, NearestFilter } from "three/src/constants.js";
import { Buffer } from "../data/buffer.js";
import { Voxel } from "../data/voxel.js";
export class Text extends Voxel {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"texture",
"voxel",
"text",
"font",
];
this.defaults = {
minFilter: "linear",
magFilter: "linear",
};
this.finals = { channels: 1 };
}
init() {
super.init();
return (this.atlas = null);
}
textShader(shader) {
return this.atlas.shader(shader);
}
textIsSDF() {
return this.props.sdf > 0;
}
textHeight() {
return this.props.detail;
}
make() {
// Read sampling parameters
let { minFilter, magFilter, type } = this.props;
// Read font parameters
const { font, style, variant, weight, detail, sdf } = this.props;
// Prepare text atlas
this.atlas = this._renderables.make("textAtlas", {
font,
size: detail,
style,
variant,
weight,
outline: sdf,
minFilter,
magFilter,
type,
});
// Underlying data buffer needs no filtering
this.minFilter = NearestFilter;
this.magFilter = NearestFilter;
this.type = FloatType;
// Skip voxel::make(), as we need 4 channels internally in our buffer to store sprite x/y/w/h per string
Buffer.prototype.make.call(this);
// Read sampling parameters
minFilter = this.minFilter != null ? this.minFilter : this.props.minFilter;
magFilter = this.magFilter != null ? this.magFilter : this.props.magFilter;
type = this.type != null ? this.type : this.props.type;
// Read given dimensions
const { width } = this.props;
const { height } = this.props;
const { depth } = this.props;
const reserveX = this.props.bufferWidth;
const reserveY = this.props.bufferHeight;
const reserveZ = this.props.bufferDepth;
const { channels } = this.props;
const { items } = this.props;
let dims = (this.spec = { channels, items, width, height, depth });
this.items = dims.items;
this.channels = dims.channels;
// Init to right size if data supplied
const { data } = this.props;
dims = UData.getDimensions(data, dims);
const { space } = this;
space.width = Math.max(reserveX, dims.width || 1);
space.height = Math.max(reserveY, dims.height || 1);
space.depth = Math.max(reserveZ, dims.depth || 1);
// Create text voxel buffer
this.buffer = this._renderables.make(this.storage, {
width: space.width,
height: space.height,
depth: space.depth,
channels: 4,
items,
minFilter,
magFilter,
type,
});
// Hook buffer emitter to map atlas text
const { atlas } = this;
const { emit } = this.buffer.streamer;
return (this.buffer.streamer.emit = (text) => atlas.map(text, emit));
}
unmake() {
super.unmake();
if (this.atlas) {
this.atlas.dispose();
return (this.atlas = null);
}
}
update() {
this.atlas.begin();
super.update();
return this.atlas.end();
}
change(changed, touched, init) {
if (touched["font"]) {
return this.rebuild();
}
return super.change(changed, touched, init);
}
}
Text.initClass();
| cchudzicki/mathbox | src/primitives/types/text/text.js | JavaScript | mit | 3,792 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class Clock extends Parent {
static initClass() {
this.traits = ["node", "clock", "seek", "play"];
}
init() {
this.skew = 0;
this.last = 0;
return (this.time = {
now: +new Date() / 1000,
time: 0,
delta: 0,
clock: 0,
step: 0,
});
}
make() {
// Listen to parent clock
return this._listen("clock", "clock.tick", this.tick);
}
reset() {
return (this.skew = 0);
}
tick(e) {
const { from, to, speed, seek, pace, delay, realtime } = this.props;
const parent = this._inherit("clock").getTime();
const time = realtime ? parent.time : parent.clock;
const delta = realtime ? parent.delta : parent.step;
const ratio = speed / pace;
this.skew += delta * (ratio - 1);
if (this.last > time) {
this.skew = 0;
}
this.time.now = parent.now + this.skew;
this.time.time = parent.time;
this.time.delta = parent.delta;
const clock = seek != null ? seek : parent.clock + this.skew;
this.time.clock = Math.min(to, from + Math.max(0, clock - delay * ratio));
this.time.step = delta * ratio;
this.last = time;
return this.trigger(e);
}
getTime() {
return this.time;
}
}
Clock.initClass();
| cchudzicki/mathbox | src/primitives/types/time/clock.js | JavaScript | mit | 1,703 |
export * from "./clock.js";
export * from "./now.js";
| cchudzicki/mathbox | src/primitives/types/time/index.js | JavaScript | mit | 54 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class Now extends Parent {
static initClass() {
this.traits = ["node", "clock", "now"];
}
init() {
let now;
this.now = now = +new Date() / 1000;
this.skew = 0;
return (this.time = {
now,
time: 0,
delta: 0,
clock: 0,
step: 0,
});
}
make() {
// Listen to parent clock
this.clockParent = this._inherit("clock");
return this._listen("clock", "clock.tick", this.tick);
}
unmake() {
return (this.clockParent = null);
}
change(changed, _touched, _init) {
if (changed["date.now"]) {
return (this.skew = 0);
}
}
tick(e) {
const { seek, pace, speed } = this.props;
const parent = this.clockParent.getTime();
this.skew += (parent.step * pace) / speed;
if (seek != null) {
this.skew = seek;
}
this.time.now =
this.time.time =
this.time.clock =
(this.props.now != null ? this.props.now : this.now) + this.skew;
this.time.delta = this.time.step = parent.delta;
return this.trigger(e);
}
getTime() {
return this.time;
}
}
Now.initClass();
| cchudzicki/mathbox | src/primitives/types/time/now.js | JavaScript | mit | 1,575 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
import { Types } from "./types_typed";
export const Traits = {
node: {
id: Types.nullable(Types.string()),
classes: Types.classes(),
},
entity: {
active: Types.bool(true),
},
object: {
visible: Types.bool(true),
},
unit: {
scale: Types.nullable(Types.number()),
fov: Types.nullable(Types.number()),
focus: Types.nullable(Types.number(1), true),
},
span: {
range: Types.nullable(Types.vec2(-1, 1)),
},
view: {
range: Types.array(Types.vec2(-1, 1), 4),
},
view3: {
position: Types.vec3(),
quaternion: Types.quat(),
rotation: Types.vec3(),
scale: Types.vec3(1, 1, 1),
eulerOrder: Types.swizzle("xyz"),
},
view4: {
position: Types.vec4(),
scale: Types.vec4(1, 1, 1, 1),
},
layer: {
depth: Types.number(1),
fit: Types.fit("y"),
},
vertex: {
pass: Types.vertexPass(),
},
fragment: {
pass: Types.fragmentPass(),
gamma: Types.bool(false),
},
transform3: {
position: Types.vec3(),
quaternion: Types.quat(),
rotation: Types.vec3(),
eulerOrder: Types.swizzle("xyz"),
scale: Types.vec3(1, 1, 1),
matrix: Types.mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
},
transform4: {
position: Types.vec4(),
scale: Types.vec4(1, 1, 1, 1),
matrix: Types.mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
},
camera: {
proxy: Types.bool(false),
position: Types.nullable(Types.vec3()),
quaternion: Types.nullable(Types.quat()),
rotation: Types.nullable(Types.vec3()),
lookAt: Types.nullable(Types.vec3()),
up: Types.nullable(Types.vec3()),
eulerOrder: Types.swizzle("xyz"),
fov: Types.nullable(Types.number(1)),
},
//ortho: Types.nullable(Types.number(0))
polar: {
bend: Types.number(1),
helix: Types.number(0),
},
spherical: {
bend: Types.number(1),
},
stereographic: {
bend: Types.number(1),
},
interval: {
axis: Types.axis(),
},
area: {
axes: Types.swizzle([1, 2], 2),
},
volume: {
axes: Types.swizzle([1, 2, 3], 3),
},
origin: {
origin: Types.vec4(),
},
scale: {
divide: Types.number(10),
unit: Types.number(1),
base: Types.number(10),
mode: Types.scale(),
start: Types.bool(true),
end: Types.bool(true),
zero: Types.bool(true),
factor: Types.positive(Types.number(1)),
nice: Types.bool(true),
},
grid: {
lineX: Types.bool(true),
lineY: Types.bool(true),
crossed: Types.bool(false),
closedX: Types.bool(false),
closedY: Types.bool(false),
},
axis: {
detail: Types.int(1),
crossed: Types.bool(false),
},
data: {
data: Types.nullable(Types.data()),
expr: Types.nullable(Types.emitter()),
bind: Types.nullable(Types.func()),
live: Types.bool(true),
},
buffer: {
channels: Types.enum<1 | 2 | 3 | 4>(4, [1, 2, 3, 4]),
items: Types.int(1),
fps: Types.nullable(Types.int(60)),
hurry: Types.int(5),
limit: Types.int(60),
realtime: Types.bool(false),
observe: Types.bool(false),
aligned: Types.bool(false),
},
sampler: {
centered: Types.bool(false),
padding: Types.number(0),
},
array: {
width: Types.nullable(Types.positive(Types.int(1), true)),
bufferWidth: Types.int(1),
history: Types.int(1),
},
matrix: {
width: Types.nullable(Types.positive(Types.int(1), true)),
height: Types.nullable(Types.positive(Types.int(1), true)),
history: Types.int(1),
bufferWidth: Types.int(1),
bufferHeight: Types.int(1),
},
voxel: {
width: Types.nullable(Types.positive(Types.int(1), true)),
height: Types.nullable(Types.positive(Types.int(1), true)),
depth: Types.nullable(Types.positive(Types.int(1), true)),
bufferWidth: Types.int(1),
bufferHeight: Types.int(1),
bufferDepth: Types.int(1),
},
resolve: {
expr: Types.nullable(Types.func()),
items: Types.int(1),
},
style: {
opacity: Types.positive(Types.number(1)),
color: Types.color(),
blending: Types.blending(),
zWrite: Types.bool(true),
zTest: Types.bool(true),
zIndex: Types.positive(Types.round()),
zBias: Types.number(0),
zOrder: Types.nullable(Types.int()),
},
geometry: {
points: Types.select(),
colors: Types.nullable(Types.select()),
},
point: {
size: Types.positive(Types.number(4)),
sizes: Types.nullable(Types.select()),
shape: Types.shape(),
optical: Types.bool(true),
fill: Types.bool(true),
depth: Types.number(1),
},
line: {
width: Types.positive(Types.number(2)),
depth: Types.positive(Types.number(1)),
join: Types.join(),
stroke: Types.stroke(),
proximity: Types.nullable(Types.number(Infinity)),
closed: Types.bool(false),
},
mesh: {
fill: Types.bool(true),
shaded: Types.bool(false),
map: Types.nullable(Types.select()),
lineBias: Types.number(5),
},
strip: {
line: Types.bool(false),
},
face: {
line: Types.bool(false),
},
arrow: {
size: Types.number(3),
start: Types.bool(false),
end: Types.bool(false),
},
ticks: {
normal: Types.vec3(0, 0, 1),
size: Types.positive(Types.number(10)),
epsilon: Types.positive(Types.number(0.001)),
},
attach: {
offset: Types.vec2(0, -20),
snap: Types.bool(false),
depth: Types.number(0),
},
format: {
digits: Types.nullable(Types.positive(Types.number(3))),
data: Types.nullable(Types.data()),
expr: Types.nullable(Types.func()),
live: Types.bool(true),
},
font: {
font: Types.font("sans-serif"),
style: Types.string(),
variant: Types.string(),
weight: Types.string(),
detail: Types.number(24),
sdf: Types.number(5),
},
label: {
text: Types.select(),
size: Types.number(16),
outline: Types.number(2),
expand: Types.number(0),
background: Types.color(1, 1, 1),
},
overlay: {
opacity: Types.number(1),
zIndex: Types.positive(Types.round(0)),
},
dom: {
points: Types.select(),
html: Types.select(),
size: Types.number(16),
outline: Types.number(2),
zoom: Types.number(1),
color: Types.nullable(Types.color()),
attributes: Types.nullable(Types.object()),
pointerEvents: Types.bool(false),
},
texture: {
minFilter: Types.filter("nearest"),
magFilter: Types.filter("nearest"),
type: Types.type("float"),
},
shader: {
sources: Types.nullable(Types.select()),
language: Types.string("glsl"),
code: Types.string(),
uniforms: Types.nullable(Types.object()),
},
include: {
shader: Types.select(),
},
operator: {
source: Types.select(),
},
spread: {
unit: Types.mapping(),
items: Types.nullable(Types.vec4()),
width: Types.nullable(Types.vec4()),
height: Types.nullable(Types.vec4()),
depth: Types.nullable(Types.vec4()),
alignItems: Types.anchor(),
alignWidth: Types.anchor(),
alignHeight: Types.anchor(),
alignDepth: Types.anchor(),
},
grow: {
scale: Types.number(1),
items: Types.nullable(Types.anchor()),
width: Types.nullable(Types.anchor()),
height: Types.nullable(Types.anchor()),
depth: Types.nullable(Types.anchor()),
},
split: {
order: Types.transpose("wxyz"),
axis: Types.nullable(Types.axis()),
length: Types.int(1),
overlap: Types.int(0),
},
join: {
order: Types.transpose("wxyz"),
axis: Types.nullable(Types.axis()),
overlap: Types.int(0),
},
swizzle: {
order: Types.swizzle(),
},
transpose: {
order: Types.transpose(),
},
repeat: {
items: Types.number(1),
width: Types.number(1),
height: Types.number(1),
depth: Types.number(1),
},
slice: {
items: Types.nullable(Types.vec2()),
width: Types.nullable(Types.vec2()),
height: Types.nullable(Types.vec2()),
depth: Types.nullable(Types.vec2()),
},
lerp: {
size: Types.mapping("absolute"),
items: Types.nullable(Types.number()),
width: Types.nullable(Types.number()),
height: Types.nullable(Types.number()),
depth: Types.nullable(Types.number()),
},
subdivide: {
items: Types.nullable(Types.positive(Types.int(), true)),
width: Types.nullable(Types.positive(Types.int(), true)),
height: Types.nullable(Types.positive(Types.int(), true)),
depth: Types.nullable(Types.positive(Types.int(), true)),
bevel: Types.number(1),
lerp: Types.bool(true),
},
resample: {
indices: Types.number(4),
channels: Types.number(4),
sample: Types.mapping(),
size: Types.mapping("absolute"),
items: Types.nullable(Types.number()),
width: Types.nullable(Types.number()),
height: Types.nullable(Types.number()),
depth: Types.nullable(Types.number()),
},
readback: {
type: Types.type("float"),
expr: Types.nullable(Types.func()),
data: Types.data(),
channels: Types.enum<1 | 2 | 3 | 4>(4, [1, 2, 3, 4]),
items: Types.nullable(Types.int()),
width: Types.nullable(Types.int()),
height: Types.nullable(Types.int()),
depth: Types.nullable(Types.int()),
},
root: {
speed: Types.number(1),
camera: Types.select("[camera]"),
},
inherit: {
source: Types.select(),
traits: Types.array(Types.string()),
},
rtt: {
size: Types.mapping("absolute"),
width: Types.nullable(Types.number()),
height: Types.nullable(Types.number()),
history: Types.int(1),
},
compose: {
alpha: Types.bool(false),
},
present: {
index: Types.int(1),
directed: Types.bool(true),
length: Types.number(0),
},
slide: {
order: Types.nullable(Types.int(0)),
steps: Types.number(1),
early: Types.int(0),
late: Types.int(0),
from: Types.nullable(Types.int(0)),
to: Types.nullable(Types.int(1)),
},
transition: {
stagger: Types.vec4(),
enter: Types.nullable(Types.number(1)),
exit: Types.nullable(Types.number(1)),
delay: Types.number(0),
delayEnter: Types.nullable(Types.number(0)),
delayExit: Types.nullable(Types.number(0)),
duration: Types.number(0.3),
durationEnter: Types.nullable(Types.number(0)),
durationExit: Types.nullable(Types.number(0)),
},
move: {
from: Types.vec4(),
to: Types.vec4(),
},
seek: {
seek: Types.nullable(Types.number(0)),
},
track: {
target: Types.select(),
script: Types.object({}),
ease: Types.ease("cosine"),
},
trigger: {
trigger: Types.nullable(Types.int(1), true),
},
step: {
playback: Types.ease("linear"),
stops: Types.nullable(Types.array(Types.number())),
delay: Types.number(0),
duration: Types.number(0.3),
pace: Types.number(0),
speed: Types.number(1),
rewind: Types.number(2),
skip: Types.bool(true),
realtime: Types.bool(false),
},
play: {
delay: Types.number(0),
pace: Types.number(1),
speed: Types.number(1),
from: Types.number(0),
to: Types.number(Infinity),
realtime: Types.bool(false),
loop: Types.bool(false),
},
now: {
now: Types.nullable(Types.timestamp()),
seek: Types.nullable(Types.number(0)),
pace: Types.number(1),
speed: Types.number(1),
},
};
| cchudzicki/mathbox | src/primitives/types/traits.ts | TypeScript | mit | 11,310 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Transform } from "./transform.js";
export class Fragment extends Transform {
static initClass() {
this.traits = ["node", "include", "fragment", "bind"];
}
make() {
// Bind to attached shader
return this._helpers.bind.make([
{ to: "include.shader", trait: "shader", optional: true },
]);
}
unmake() {
return this._helpers.bind.unmake();
}
change(changed, touched, _init) {
if (touched["include"] || changed["fragment.gamma"]) {
return this.rebuild();
}
}
fragment(shader, pass) {
if (this.bind.shader != null) {
if (pass === this.props.pass) {
if (this.props.gamma) {
shader.pipe("mesh.gamma.out");
}
shader.pipe(this.bind.shader.shaderBind());
shader.split();
if (this.props.gamma) {
shader.pipe("mesh.gamma.in");
}
shader.pass();
}
}
return super.fragment(shader, pass);
}
}
Fragment.initClass();
| cchudzicki/mathbox | src/primitives/types/transform/fragment.js | JavaScript | mit | 1,387 |
export * from "./transform.js";
export * from "./transform3.js";
export * from "./transform4.js";
export * from "./vertex.js";
export * from "./fragment.js";
export * from "./layer.js";
export * from "./mask.js";
| cchudzicki/mathbox | src/primitives/types/transform/index.js | JavaScript | mit | 213 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Transform } from "./transform.js";
export class Layer extends Transform {
static initClass() {
this.traits = ["node", "vertex", "layer"];
}
make() {
this._listen("root", "root.resize", this.update);
return (this.uniforms = {
layerScale: this._attributes.make(this._types.vec4()),
layerBias: this._attributes.make(this._types.vec4()),
});
}
update() {
const camera = this._inherit("root").getCamera();
const aspect = camera.aspect != null ? camera.aspect : 1;
const fov = camera.fov != null ? camera.fov : 1;
const pitch = Math.tan((fov * Math.PI) / 360);
const _enum = this.node.attributes["layer.fit"].enum;
let { fit } = this.props;
const { depth } = this.props;
// Convert contain/cover into x/y
switch (fit) {
case _enum.contain:
fit = aspect > 1 ? _enum.y : _enum.x;
break;
case _enum.cover:
fit = aspect > 1 ? _enum.x : _enum.y;
break;
}
// Fit x/y
switch (fit) {
case _enum.x:
this.uniforms.layerScale.value.set(pitch * aspect, pitch * aspect);
break;
case _enum.y:
this.uniforms.layerScale.value.set(pitch, pitch);
break;
}
return this.uniforms.layerBias.value.set(0, 0, -depth, 0);
}
change(changed, touched, init) {
if (changed["layer.fit"] || changed["layer.depth"] || init) {
return this.update();
}
}
// End transform chain here without applying camera view
vertex(shader, pass) {
if (pass === 2) {
return shader.pipe("layer.position", this.uniforms);
}
if (pass === 3) {
return shader.pipe("root.position");
}
return shader;
}
}
Layer.initClass();
| cchudzicki/mathbox | src/primitives/types/transform/layer.js | JavaScript | mit | 2,139 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UGLSL from "../../../util/glsl.js";
import { Parent } from "../base/parent.js";
export class Mask extends Parent {
static initClass() {
this.traits = ["node", "include", "mask", "bind"];
}
make() {
// Bind to attached shader
return this._helpers.bind.make([
{ to: "include.shader", trait: "shader", optional: true },
]);
}
unmake() {
return this._helpers.bind.unmake();
}
change(changed, touched, _init) {
if (touched["include"]) {
return this.rebuild();
}
}
mask(shader) {
let left, s;
if (this.bind.shader != null) {
if (shader) {
s = this._shaders.shader();
s.pipe(UGLSL.identity("vec4"));
s.fan();
s.pipe(shader);
s.next();
s.pipe(this.bind.shader.shaderBind());
s.end();
s.pipe("float combine(float a, float b) { return min(a, b); }");
} else {
s = this._shaders.shader();
s.pipe(this.bind.shader.shaderBind());
}
} else {
s = shader;
}
return (left = __guard__(this._inherit("mask"), (x) => x.mask(s))) != null
? left
: s;
}
}
Mask.initClass();
function __guard__(value, transform) {
return typeof value !== "undefined" && value !== null
? transform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/transform/mask.js | JavaScript | mit | 1,848 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Parent } from "../base/parent.js";
export class Transform extends Parent {
static initClass() {
this.traits = ["node", "vertex", "fragment"];
}
vertex(shader, pass) {
let left;
return (left = __guard__(this._inherit("vertex"), (x) =>
x.vertex(shader, pass)
)) != null
? left
: shader;
}
fragment(shader, pass) {
let left;
return (left = __guard__(this._inherit("fragment"), (x) =>
x.fragment(shader, pass)
)) != null
? left
: shader;
}
}
Transform.initClass();
function __guard__(value, xform) {
return typeof value !== "undefined" && value !== null
? xform(value)
: undefined;
}
| cchudzicki/mathbox | src/primitives/types/transform/transform.js | JavaScript | mit | 1,223 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UThree from "../../../util/three.js";
import { Transform } from "./transform.js";
export class Transform3 extends Transform {
static initClass() {
this.traits = ["node", "vertex", "transform3"];
}
make() {
this.uniforms = {
transformMatrix: this._attributes.make(this._types.mat4()),
};
return (this.composer = UThree.transformComposer());
}
unmake() {
return delete this.uniforms;
}
change(changed, touched, init) {
if (changed["transform3.pass"]) {
return this.rebuild();
}
if (!touched["transform3"] && !init) {
return;
}
const p = this.props.position;
const q = this.props.quaternion;
const r = this.props.rotation;
const s = this.props.scale;
const m = this.props.matrix;
const e = this.props.eulerOrder;
return (this.uniforms.transformMatrix.value = this.composer(
p,
r,
q,
s,
m,
e
));
}
vertex(shader, pass) {
if (pass === this.props.pass) {
shader.pipe("transform3.position", this.uniforms);
}
return super.vertex(shader, pass);
}
}
Transform3.initClass();
| cchudzicki/mathbox | src/primitives/types/transform/transform3.js | JavaScript | mit | 1,508 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Transform } from "./transform.js";
export class Transform4 extends Transform {
static initClass() {
this.traits = ["node", "vertex", "transform4"];
}
make() {
this.uniforms = {
transformMatrix: this._attributes.make(this._types.mat4()),
transformOffset: this.node.attributes["transform4.position"],
};
return (this.transformMatrix = this.uniforms.transformMatrix.value);
}
unmake() {
return delete this.uniforms;
}
change(changed, touched, init) {
if (changed["transform4.pass"]) {
return this.rebuild();
}
if (!touched["transform4"] && !init) {
return;
}
const s = this.props.scale;
const m = this.props.matrix;
const t = this.transformMatrix;
t.copy(m);
return t.scale(s);
}
vertex(shader, pass) {
if (pass === this.props.pass) {
shader.pipe("transform4.position", this.uniforms);
}
return super.vertex(shader, pass);
}
}
Transform4.initClass();
| cchudzicki/mathbox | src/primitives/types/transform/transform4.js | JavaScript | mit | 1,345 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Transform } from "./transform.js";
export class Vertex extends Transform {
static initClass() {
this.traits = ["node", "include", "vertex", "bind"];
}
make() {
// Bind to attached shader
return this._helpers.bind.make([
{ to: "include.shader", trait: "shader", optional: true },
]);
}
unmake() {
return this._helpers.bind.unmake();
}
change(changed, touched, _init) {
if (touched["include"]) {
return this.rebuild();
}
}
vertex(shader, pass) {
if (this.bind.shader != null) {
if (pass === this.props.pass) {
shader.pipe(this.bind.shader.shaderBind());
}
}
return super.vertex(shader, pass);
}
}
Vertex.initClass();
| cchudzicki/mathbox | src/primitives/types/transform/vertex.js | JavaScript | mit | 1,136 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS104: Avoid inline assignments
* DS202: Simplify dynamic range loops
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UData from "../../util/data.js";
import * as UJS from "../../util/js.js";
import {
ByteType,
FloatType,
IntType,
LinearFilter,
LinearMipMapLinearFilter,
LinearMipMapNearestFilter,
NearestFilter,
NearestMipMapLinearFilter,
NearestMipMapNearestFilter,
ShortType,
UnsignedByteType,
UnsignedIntType,
UnsignedShortType,
} from "three/src/constants.js";
import { Color } from "three/src/math/Color.js";
import { Matrix3 } from "three/src/math/Matrix3.js";
import { Matrix4 } from "three/src/math/Matrix4.js";
import { Quaternion } from "three/src/math/Quaternion.js";
import { Vector2 } from "three/src/math/Vector2.js";
import { Vector3 } from "three/src/math/Vector3.js";
import { Vector4 } from "three/src/math/Vector4.js";
// Property types
//
// The weird calling convention is for double-buffering the values
// while validating compound types like arrays and nullables.
//
// validate: (value, target, invalid) ->
//
// # Option 1: Call invalid() to reject
// return invalid() if value < 0
//
// # Option 2: Change target in-place
// target.set(value)
// return target
//
// # Option 3: Return new value
// return +value
//
const _Types = {
array(type, size, value = null) {
const lerp = type.lerp
? function (a, b, target, f) {
const l = Math.min(a.length, b.length);
for (
let i = 0, end = l, asc = 0 <= end;
asc ? i < end : i > end;
asc ? i++ : i--
) {
target[i] = type.lerp(a[i], b[i], target[i], f);
}
return target;
}
: undefined;
const op = type.op
? function (a, b, target, op) {
const l = Math.min(a.length, b.length);
for (
let i = 0, end = l, asc = 0 <= end;
asc ? i < end : i > end;
asc ? i++ : i--
) {
target[i] = type.op(a[i], b[i], target[i], op);
}
return target;
}
: undefined;
if (value != null && !(value instanceof Array)) {
value = [value];
}
return {
uniform() {
if (type.uniform) {
return type.uniform() + "v";
} else {
return undefined;
}
},
make() {
if (value != null) {
return value.slice();
}
if (!size) {
return [];
}
return __range__(0, size, false).map((_i) => type.make());
},
validate(value, target, invalid) {
if (!(value instanceof Array)) {
value = [value];
}
const l = (target.length = size ? size : value.length);
for (
let i = 0, end = l, asc = 0 <= end;
asc ? i < end : i > end;
asc ? i++ : i--
) {
const input = value[i] != null ? value[i] : type.make();
target[i] = type.validate(input, target[i], invalid);
}
return target;
},
equals(a, b) {
const al = a.length;
const bl = b.length;
if (al !== bl) {
return false;
}
const l = Math.min(al, bl);
for (
let i = 0, end = l, asc = 0 <= end;
asc ? i < end : i > end;
asc ? i++ : i--
) {
if (
!(typeof type.equals === "function"
? type.equals(a[i], b[i])
: undefined)
) {
return false;
}
}
return true;
},
lerp,
op,
clone(v) {
return Array.from(v).map((x) => type.clone(x));
},
};
},
letters(type, size, value = null) {
if (value != null) {
if (value === "" + value) {
value = value.split("");
}
for (let i = 0; i < value.length; i++) {
const v = value[i];
value[i] = type.validate(v, v);
}
}
const array = Types.array(type, size, value);
return {
uniform() {
return array.uniform();
},
make() {
return array.make();
},
validate(value, target, invalid) {
if (value === "" + value) {
value = value.split("");
}
return array.validate(value, target, invalid);
},
equals(a, b) {
return array.equals(a, b);
},
clone: array.clone,
};
},
nullable(type, make) {
if (make == null) {
make = false;
}
let value = make ? type.make() : null;
const emitter = type.emitter
? function (expr1, expr2) {
if (expr2 == null) {
return expr1;
}
if (expr1 == null) {
return expr2;
}
return type.emitter(expr1, expr2);
}
: undefined;
const lerp = type.lerp
? function (a, b, target, f) {
if (a === null || b === null) {
if (f < 0.5) {
return a;
} else {
return b;
}
}
if (target == null) {
target = type.make();
}
value = type.lerp(a, b, target, f);
return target;
}
: undefined;
const op = type.op
? function (a, b, target, op) {
if (a === null || b === null) {
return null;
}
if (target == null) {
target = type.make();
}
value = type.op(a, b, target, op);
return value;
}
: undefined;
return {
make() {
return value;
},
validate(value, target, invalid) {
if (value === null) {
return value;
}
if (target === null) {
target = type.make();
}
return type.validate(value, target, invalid);
},
uniform() {
return typeof type.uniform === "function" ? type.uniform() : undefined;
},
equals(a, b) {
let left;
const an = a === null;
const bn = b === null;
if (an && bn) {
return true;
}
if (an ^ bn) {
return false;
}
return (left =
typeof type.equals === "function" ? type.equals(a, b) : undefined) !=
null
? left
: a === b;
},
lerp,
op,
emitter,
};
},
enum(value, keys, map) {
let key;
if (keys == null) {
keys = [];
}
if (map == null) {
map = {};
}
let i = 0;
const values = {};
for (key of Array.from(keys)) {
if (key !== +key) {
if (map[key] == null) {
map[key] = i++;
}
}
}
for (key of Array.from(keys)) {
if (key === +key) {
values[key] = key;
}
}
for (key in map) {
i = map[key];
values[i] = true;
}
if (values[value] == null) {
value = map[value];
}
return {
enum() {
return map;
},
make() {
return value;
},
validate(value, target, invalid) {
const v = values[value] ? value : map[value];
if (v != null) {
return v;
}
return invalid();
},
};
},
enumber(value, keys, map) {
if (map == null) {
map = {};
}
const _enum = Types.enum(value, keys, map);
return {
enum: _enum.enum,
uniform() {
return "f";
},
make() {
let left;
return (left = _enum.make()) != null ? left : +value;
},
validate(value, target, invalid) {
if (value === +value) {
return value;
}
return _enum.validate(value, target, invalid);
},
op(a, b, target, op) {
return op(a, b);
},
};
},
select(value) {
if (value == null) {
value = "<";
}
value;
return {
make() {
return value;
},
validate(value, target, invalid) {
if (typeof value === "string") {
return value;
}
if (typeof value === "object") {
return value;
}
return invalid();
},
};
},
bool(value) {
value = !!value;
return {
uniform() {
return "f";
},
make() {
return value;
},
validate(value, _target, _invalid) {
return !!value;
},
};
},
int(value) {
if (value == null) {
value = 0;
}
value = +Math.round(value);
return {
uniform() {
return "i";
},
make() {
return value;
},
validate(value, target, invalid) {
let x;
if (value !== (x = +value)) {
return invalid();
}
return Math.round(x) || 0;
},
op(a, b, target, op) {
return op(a, b);
},
};
},
round(value) {
if (value == null) {
value = 0;
}
value = +Math.round(value);
return {
uniform() {
return "f";
},
make() {
return value;
},
validate(value, target, invalid) {
let x;
if (value !== (x = +value)) {
return invalid();
}
return Math.round(x) || 0;
},
op(a, b, target, op) {
return op(a, b);
},
};
},
number(value) {
if (value == null) {
value = 0;
}
return {
uniform() {
return "f";
},
make() {
return +value;
},
validate(value, target, invalid) {
let x;
if (value !== (x = +value)) {
return invalid();
}
return x || 0;
},
op(a, b, target, op) {
return op(a, b);
},
};
},
positive(type, strict) {
if (strict == null) {
strict = false;
}
return {
uniform: type.uniform,
make: type.make,
validate(value, target, invalid) {
value = type.validate(value, target, invalid);
if (value < 0 || (strict && value <= 0)) {
return invalid();
}
return value;
},
op(a, b, target, op) {
return op(a, b);
},
};
},
string(value) {
if (value == null) {
value = "";
}
return {
make() {
return "" + value;
},
validate(value, target, invalid) {
let x;
if (value !== (x = "" + value)) {
return invalid();
}
return x;
},
};
},
func() {
return {
make() {
return function () {};
},
validate(value, target, invalid) {
if (typeof value === "function") {
return value;
}
return invalid();
},
};
},
emitter() {
return {
make() {
return (emit) => emit(1, 1, 1, 1);
},
validate(value, target, invalid) {
if (typeof value === "function") {
return value;
}
return invalid();
},
emitter(a, b) {
return UData.getLerpEmitter(a, b);
},
};
},
object(value) {
return {
make() {
return value != null ? value : {};
},
validate(value, target, invalid) {
if (typeof value === "object") {
return value;
}
return invalid();
},
clone(v) {
return JSON.parse(JSON.stringify(v));
},
};
},
timestamp(value = null) {
if (typeof value === "string") {
value = Date.parse(value);
}
return {
uniform() {
return "f";
},
make() {
return value != null ? value : +new Date();
},
validate(value, target, invalid) {
value = Date.parse(value);
if (value !== +value) {
return invalid();
}
return value;
},
op(a, b, target, op) {
return op(a, b);
},
};
},
vec2(x, y) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
const defaults = [x, y];
return {
uniform() {
return "v2";
},
make() {
return new Vector2(x, y);
},
validate(value, target, invalid) {
if (value === +value) {
value = [value];
}
if (value instanceof Vector2) {
target.copy(value);
} else if (value instanceof Array) {
value = value.concat(defaults.slice(value.length));
target.set.apply(target, value);
} else if (value != null) {
const xx = value.x != null ? value.x : x;
const yy = value.y != null ? value.y : y;
target.set(xx, yy);
} else {
return invalid();
}
return target;
},
equals(a, b) {
return a.x === b.x && a.y === b.y;
},
op(a, b, target, op) {
target.x = op(a.x, b.x);
target.y = op(a.y, b.y);
return target;
},
};
},
ivec2(x, y) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
const vec2 = Types.vec2(x, y);
const { validate } = vec2;
vec2.validate = function (value, target, invalid) {
validate(value, target, invalid);
target.x = Math.round(target.x);
target.y = Math.round(target.y);
return target;
};
return vec2;
},
vec3(x, y, z) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
if (z == null) {
z = 0;
}
const defaults = [x, y, z];
return {
uniform() {
return "v3";
},
make() {
return new Vector3(x, y, z);
},
validate(value, target, invalid) {
if (value === +value) {
value = [value];
}
if (value instanceof Vector3) {
target.copy(value);
} else if (value instanceof Array) {
value = value.concat(defaults.slice(value.length));
target.set.apply(target, value);
} else if (value != null) {
const xx = value.x != null ? value.x : x;
const yy = value.y != null ? value.y : y;
const zz = value.z != null ? value.z : z;
target.set(xx, yy, zz);
} else {
return invalid();
}
return target;
},
equals(a, b) {
return a.x === b.x && a.y === b.y && a.z === b.z;
},
op(a, b, target, op) {
target.x = op(a.x, b.x);
target.y = op(a.y, b.y);
target.z = op(a.z, b.z);
return target;
},
};
},
ivec3(x, y, z) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
if (z == null) {
z = 0;
}
const vec3 = Types.vec3(x, y, z);
const { validate } = vec3;
vec3.validate = function (value, target, invalid) {
validate(value, target, invalid);
target.x = Math.round(target.x);
target.y = Math.round(target.y);
target.z = Math.round(target.z);
return target;
};
return vec3;
},
vec4(x, y, z, w) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
if (z == null) {
z = 0;
}
if (w == null) {
w = 0;
}
const defaults = [x, y, z, w];
return {
uniform() {
return "v4";
},
make() {
return new Vector4(x, y, z, w);
},
validate(value, target, invalid) {
if (value === +value) {
value = [value];
}
if (value instanceof Vector4) {
target.copy(value);
} else if (value instanceof Array) {
value = value.concat(defaults.slice(value.length));
target.set.apply(target, value);
} else if (value != null) {
const xx = value.x != null ? value.x : x;
const yy = value.y != null ? value.y : y;
const zz = value.z != null ? value.z : z;
const ww = value.w != null ? value.w : w;
target.set(xx, yy, zz, ww);
} else {
return invalid();
}
return target;
},
equals(a, b) {
return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
},
op(a, b, target, op) {
target.x = op(a.x, b.x);
target.y = op(a.y, b.y);
target.z = op(a.z, b.z);
target.w = op(a.w, b.w);
return target;
},
};
},
ivec4(x, y, z, w) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
if (z == null) {
z = 0;
}
if (w == null) {
w = 0;
}
const vec4 = Types.vec4(x, y, z, w);
const { validate } = vec4;
vec4.validate = function (value, target, invalid) {
validate(value, target, invalid);
target.x = Math.round(target.x);
target.y = Math.round(target.y);
target.z = Math.round(target.z);
target.w = Math.round(target.w);
return target;
};
return vec4;
},
mat3(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
if (n11 == null) {
n11 = 1;
}
if (n12 == null) {
n12 = 0;
}
if (n13 == null) {
n13 = 0;
}
if (n21 == null) {
n21 = 0;
}
if (n22 == null) {
n22 = 1;
}
if (n23 == null) {
n23 = 0;
}
if (n31 == null) {
n31 = 0;
}
if (n32 == null) {
n32 = 0;
}
if (n33 == null) {
n33 = 1;
}
const defaults = [n11, n12, n13, n21, n22, n23, n31, n32, n33];
return {
uniform() {
return "m4";
},
make() {
const m = new Matrix3();
m.set(n11, n12, n13, n21, n22, n23, n31, n32, n33);
return m;
},
validate(value, target, invalid) {
if (value instanceof Matrix3) {
target.copy(value);
} else if (value instanceof Array) {
value = value.concat(defaults.slice(value.length));
target.set.apply(target, value);
} else {
return invalid();
}
return target;
},
};
},
mat4(
n11,
n12,
n13,
n14,
n21,
n22,
n23,
n24,
n31,
n32,
n33,
n34,
n41,
n42,
n43,
n44
) {
if (n11 == null) {
n11 = 1;
}
if (n12 == null) {
n12 = 0;
}
if (n13 == null) {
n13 = 0;
}
if (n14 == null) {
n14 = 0;
}
if (n21 == null) {
n21 = 0;
}
if (n22 == null) {
n22 = 1;
}
if (n23 == null) {
n23 = 0;
}
if (n24 == null) {
n24 = 0;
}
if (n31 == null) {
n31 = 0;
}
if (n32 == null) {
n32 = 0;
}
if (n33 == null) {
n33 = 1;
}
if (n34 == null) {
n34 = 0;
}
if (n41 == null) {
n41 = 0;
}
if (n42 == null) {
n42 = 0;
}
if (n43 == null) {
n43 = 0;
}
if (n44 == null) {
n44 = 1;
}
const defaults = [
n11,
n12,
n13,
n14,
n21,
n22,
n23,
n24,
n31,
n32,
n33,
n34,
n41,
n42,
n43,
n44,
];
return {
uniform() {
return "m4";
},
make() {
const m = new Matrix4();
m.set(
n11,
n12,
n13,
n14,
n21,
n22,
n23,
n24,
n31,
n32,
n33,
n34,
n41,
n42,
n43,
n44
);
return m;
},
validate(value, target, invalid) {
if (value instanceof Matrix4) {
target.copy(value);
} else if (value instanceof Array) {
value = value.concat(defaults.slice(value.length));
target.set.apply(target, value);
} else {
return invalid();
}
return target;
},
};
},
quat(x, y, z, w) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
if (z == null) {
z = 0;
}
if (w == null) {
w = 1;
}
const vec4 = Types.vec4(x, y, z, w);
return {
uniform() {
return "v4";
},
make() {
return new Quaternion();
},
validate(value, target, invalid) {
if (value instanceof Quaternion) {
target.copy(value);
} else {
target = vec4.validate(value, target, invalid);
}
target.normalize();
return target;
},
equals(a, b) {
return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
},
op(a, b, target, op) {
target.x = op(a.x, b.x);
target.y = op(a.y, b.y);
target.z = op(a.z, b.z);
target.w = op(a.w, b.w);
target.normalize();
return target;
},
lerp(a, b, target, f) {
if (target.slerpQuaternions) {
// NOTE: slerpQuaternions replaced the static slerp method in three.js
// r127. This switch removes the deprecation warning and keeps the
// project three.js compatible across this version.
target.slerpQuaternions(a, b, f);
} else {
Quaternion.slerp(a, b, target, f);
}
return target;
},
};
},
color(r, g, b) {
if (r == null) {
r = 0.5;
}
if (g == null) {
g = 0.5;
}
if (b == null) {
b = 0.5;
}
const defaults = [r, g, b];
return {
uniform() {
return "c";
},
make() {
return new Color(r, g, b);
},
validate(value, target, invalid) {
if (value === "" + value) {
value = new Color().setStyle(value);
} else if (value === +value) {
value = new Color(value);
}
if (value instanceof Color) {
target.copy(value);
} else if (value instanceof Array) {
value = value.concat(defaults.slice(value.length));
target.setRGB.apply(target, value);
} else if (value != null) {
const rr = value.r != null ? value.r : r;
const gg = value.g != null ? value.g : g;
const bb = value.b != null ? value.b : b;
target.set(rr, gg, bb);
} else {
return invalid();
}
return target;
},
equals(a, b) {
return a.r === b.r && a.g === b.g && a.b === b.b;
},
op(a, b, target, op) {
target.r = op(a.r, b.r);
target.g = op(a.g, b.g);
target.b = op(a.b, b.b);
return target;
},
};
},
axis(value, allowZero) {
let v;
if (value == null) {
value = 1;
}
if (allowZero == null) {
allowZero = false;
}
const map = {
x: 1,
y: 2,
z: 3,
w: 4,
W: 1,
H: 2,
D: 3,
I: 4,
zero: 0,
null: 0,
width: 1,
height: 2,
depth: 3,
items: 4,
};
const range = allowZero ? [0, 1, 2, 3, 4] : [1, 2, 3, 4];
if ((v = map[value]) != null) {
value = v;
}
return {
make() {
return value;
},
validate(value, target, invalid) {
let left;
if ((v = map[value]) != null) {
value = v;
}
value = (left = Math.round(value)) != null ? left : 0;
if (Array.from(range).includes(value)) {
return value;
}
return invalid();
},
};
},
transpose(order) {
if (order == null) {
order = [1, 2, 3, 4];
}
const looseArray = Types.letters(Types.axis(null, false), 0, order);
const axesArray = Types.letters(Types.axis(null, false), 4, order);
return {
make() {
return axesArray.make();
},
validate(value, target, invalid) {
let temp = [1, 2, 3, 4];
looseArray.validate(value, temp, invalid);
if (temp.length < 4) {
const missing = [1, 2, 3, 4].filter((x) => temp.indexOf(x) === -1);
temp = temp.concat(missing);
}
const unique = Array.from(temp).map(
(letter, i) => temp.indexOf(letter) === i
);
if (unique.indexOf(false) < 0) {
return axesArray.validate(temp, target, invalid);
}
return invalid();
},
equals: axesArray.equals,
clone: axesArray.clone,
};
},
swizzle(order, size = null) {
if (order == null) {
order = [1, 2, 3, 4];
}
if (size == null) {
size = order.length;
}
order = order.slice(0, size);
const looseArray = Types.letters(Types.axis(null, false), 0, order);
const axesArray = Types.letters(Types.axis(null, true), size, order);
return {
make() {
return axesArray.make();
},
validate(value, target, invalid) {
let temp = order.slice();
looseArray.validate(value, temp, invalid);
if (temp.length < size) {
temp = temp.concat([0, 0, 0, 0]).slice(0, size);
}
return axesArray.validate(temp, target, invalid);
},
equals: axesArray.equals,
clone: axesArray.clone,
};
},
classes() {
const stringArray = Types.array(Types.string());
return {
make() {
return stringArray.make();
},
validate(value, target, invalid) {
if (value === "" + value) {
value = value.split(" ");
}
value = value.filter((x) => !!x.length);
return stringArray.validate(value, target, invalid);
},
equals: stringArray.equals,
clone: stringArray.clone,
};
},
blending(value) {
if (value == null) {
value = "normal";
}
const keys = ["no", "normal", "add", "subtract", "multiply", "custom"];
return Types.enum(value, keys);
},
filter(value) {
if (value == null) {
value = "nearest";
}
const map = {
nearest: NearestFilter,
nearestMipMapNearest: NearestMipMapNearestFilter,
nearestMipMapLinear: NearestMipMapLinearFilter,
linear: LinearFilter,
linearMipMapNearest: LinearMipMapNearestFilter,
linearMipmapLinear: LinearMipMapLinearFilter,
};
return Types.enum(value, [], map);
},
type(value) {
if (value == null) {
value = "unsignedByte";
}
const map = {
unsignedByte: UnsignedByteType,
byte: ByteType,
short: ShortType,
unsignedShort: UnsignedShortType,
int: IntType,
unsignedInt: UnsignedIntType,
float: FloatType,
};
return Types.enum(value, [], map);
},
scale(value) {
if (value == null) {
value = "linear";
}
const keys = ["linear", "log"];
return Types.enum(value, keys);
},
mapping(value) {
if (value == null) {
value = "relative";
}
const keys = ["relative", "absolute"];
return Types.enum(value, keys);
},
indexing(value) {
if (value == null) {
value = "original";
}
const keys = ["original", "final"];
return Types.enum(value, keys);
},
shape(value) {
if (value == null) {
value = "circle";
}
const keys = ["circle", "square", "diamond", "up", "down", "left", "right"];
return Types.enum(value, keys);
},
join(value) {
if (value == null) {
value = "miter";
}
const keys = ["miter", "round", "bevel"];
return Types.enum(value, keys);
},
stroke(value) {
if (value == null) {
value = "solid";
}
const keys = ["solid", "dotted", "dashed"];
return Types.enum(value, keys);
},
vertexPass(value) {
if (value == null) {
value = "view";
}
const keys = ["data", "view", "world", "eye"];
return Types.enum(value, keys);
},
fragmentPass(value) {
if (value == null) {
value = "light";
}
const keys = ["color", "light", "rgba"];
return Types.enum(value, keys);
},
ease(value) {
if (value == null) {
value = "linear";
}
const keys = ["linear", "cosine", "binary", "hold"];
return Types.enum(value, keys);
},
fit(value) {
if (value == null) {
value = "contain";
}
const keys = ["x", "y", "contain", "cover"];
return Types.enum(value, keys);
},
anchor(value) {
if (value == null) {
value = "middle";
}
const map = {
first: 1,
middle: 0,
last: -1,
};
return Types.enumber(value, [], map);
},
transitionState(value) {
if (value == null) {
value = "enter";
}
const map = {
enter: -1,
visible: 0,
exit: 1,
};
return Types.enumber(value, [], map);
},
font(value) {
if (value == null) {
value = "sans-serif";
}
const parse = UJS.parseQuoted;
if (!(value instanceof Array)) {
value = parse(value);
}
const stringArray = Types.array(Types.string(), 0, value);
return {
make() {
return stringArray.make();
},
validate(value, target, invalid) {
try {
if (!(value instanceof Array)) {
value = parse(value);
}
} catch (error) {
return invalid();
}
value = value.filter((x) => !!x.length);
return stringArray.validate(value, target, invalid);
},
equals: stringArray.equals,
clone: stringArray.clone,
};
},
data(value) {
if (value == null) {
value = [];
}
return {
make() {
return [];
},
validate(value, target, invalid) {
if (value instanceof Array) {
return value;
} else if ((value != null ? value.length : undefined) != null) {
return value;
} else {
return invalid();
}
},
emitter(a, b) {
return UData.getLerpThunk(a, b);
},
};
},
};
const decorate = function (types) {
for (const k in types) {
const type = types[k];
types[k] = ((type) =>
function () {
const t = type.apply(type, arguments);
if (t.validate == null) {
t.validate = (v) => v != null;
}
if (t.equals == null) {
t.equals = (a, b) => a === b;
}
if (t.clone == null) {
t.clone = function (v) {
let left;
return (left = __guardMethod__(v, "clone", (o) => o.clone())) !=
null
? left
: v;
};
}
return t;
})(type);
}
return types;
};
export const Types = decorate(_Types);
function __range__(left, right, inclusive) {
const range = [];
const ascending = left < right;
const end = !inclusive ? right : ascending ? right + 1 : right - 1;
for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
range.push(i);
}
return range;
}
function __guardMethod__(obj, methodName, transform) {
if (
typeof obj !== "undefined" &&
obj !== null &&
typeof obj[methodName] === "function"
) {
return transform(obj, methodName);
} else {
return undefined;
}
}
| cchudzicki/mathbox | src/primitives/types/types.js | JavaScript | mit | 31,405 |
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Manual typings for types.js.
*
* Why not name this types.d.ts? Because then it won't be included in the build,
* see https://stackoverflow.com/a/56440335/2747370. dts files are good for
* specifying types that are only consumed in our source code, but no good for
* specifying types that should be included in the output.
*/
import type { MathboxNode } from "../../types";
import { Types as TypesUntyped } from "./types";
type OnInvalid = () => void;
type Validate<In, Out> = (
value: In,
target: unknown,
invalid: OnInvalid
) => Out;
export interface Type<In, Out> {
validate: Validate<In, Out>;
make(): Out;
}
export type Optional<T> = T | null | undefined;
export type BlendingModes =
| "no"
| "normal"
| "add"
| "subtract"
| "multiply"
| "custom";
export type Axes =
| "x"
| "y"
| "z"
| "w"
| "W"
| "H"
| "D"
| "I"
| "width"
| "height"
| "depth"
| "items"
| 1
| 2
| 3
| 4;
export type AxesWithZero = Axes | 0 | "zero" | "null";
/**
* Values 'left' and 'right' correspond to -1 and +1, respectively.
*/
export type Alignments = "left" | "middle" | "right" | number;
/**
* If specified as a number, should range between -1 ("enter") to +1 ("exit").
*/
export type TransitionStates = "enter" | "visible" | "exiit" | number;
export type TypeGenerators = {
// Helpers
nullable<I, O>(type: Type<I, O>): Type<null | I, null | O>;
nullable<I, O>(type: Type<I, O>, make: true): Type<null | I, O>;
array<I, O>(type: Type<I, O>, size?: number, value?: O): Type<I[], O[]>;
// Primitives
string(defaultValue?: string): Type<Optional<string>, string>;
bool(defaultValue?: boolean): Type<Optional<boolean>, boolean>;
number(defaultValue?: number): Type<Optional<number>, number>;
// collection-esque
enum<E extends string | number>(
value: E,
keys: E[],
map?: Record<E, number>
): Type<Optional<E>, E>;
enumber<E extends string | number>(
value: E | number,
keys: E[],
map?: Record<E, number>
): Type<Optional<E | number>, E | number>;
// Others
classes(): Type<Optional<string | string[]>, string[]>;
blending(
defaultValue?: BlendingModes
): Type<Optional<BlendingModes>, BlendingModes>;
anchor(defaultValue?: Alignments): Type<Optional<Alignments>, Alignments>;
transitionState(
defaultValue?: TransitionStates
): Type<Optional<TransitionStates>, TransitionStates>;
// Internally, this axis type is not quite correct. When allowZero is true, the Axes enum should have an extra member.
axis(value?: Axes, allowZero?: false): Type<Optional<Axes>, number>;
axis(
value: AxesWithZero,
allowZero: true
): Type<Optional<AxesWithZero>, number>;
select(
defaultValue?: string
): Type<Optional<string | MathboxNode>, string | MathboxNode>;
letters<I, O>(
type: Type<I, O>,
size?: number,
value?: string
): Type<Optional<string | I[]>, O[]>;
int(value?: number): Type<Optional<number>, number>;
round(value?: number): Type<Optional<number>, number>;
positive<I, O extends number>(type: Type<I, O>, strict?: boolean): Type<I, O>;
func: any;
emitter: any;
object: any;
timestamp: any;
vec2: any;
ivec2: any;
vec3: any;
ivec3: any;
vec4: any;
ivec4: any;
mat3: any;
mat4: any;
quat: any;
color: any;
transpose(order?: string | Axes[]): Type<Optional<string | Axes[]>, number[]>;
swizzle(
order?: string | Axes[],
size?: number
): Type<Optional<string | Axes[]>, number[]>;
filter: any;
type: any;
scale: any;
mapping: any;
indexing: any;
shape: any;
join: any;
stroke: any;
vertexPass: any;
fragmentPass: any;
ease: any;
fit: any;
font: any;
data: any;
};
export const Types: TypeGenerators = TypesUntyped;
| cchudzicki/mathbox | src/primitives/types/types_typed.ts | TypeScript | mit | 3,822 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UThree from "../../../util/three.js";
import { View } from "./view.js";
export class Cartesian extends View {
static initClass() {
this.traits = ["node", "object", "visible", "view", "view3", "vertex"];
}
make() {
super.make();
this.uniforms = { viewMatrix: this._attributes.make(this._types.mat4()) };
this.viewMatrix = this.uniforms.viewMatrix.value;
this.composer = UThree.transformComposer();
}
unmake() {
super.unmake();
delete this.viewMatrix;
delete this.objectMatrix;
delete this.uniforms;
}
change(changed, touched, init) {
if (!touched["view"] && !touched["view3"] && !init) {
return;
}
const p = this.props.position;
const s = this.props.scale;
const q = this.props.quaternion;
const r = this.props.rotation;
const g = this.props.range;
const e = this.props.eulerOrder;
const { x } = g[0];
const y = g[1].x;
const z = g[2].x;
const dx = g[0].y - x || 1;
const dy = g[1].y - y || 1;
const dz = g[2].y - z || 1;
// Forward transform
this.viewMatrix.set(
2 / dx,
0,
0,
-(2 * x + dx) / dx,
0,
2 / dy,
0,
-(2 * y + dy) / dy,
0,
0,
2 / dz,
-(2 * z + dz) / dz,
0,
0,
0,
1
);
const transformMatrix = this.composer(p, r, q, s, null, e);
this.viewMatrix.multiplyMatrices(transformMatrix, this.viewMatrix);
if (changed["view.range"]) {
this.trigger({
type: "view.range",
});
}
}
vertex(shader, pass) {
if (pass === 1) {
shader.pipe("cartesian.position", this.uniforms);
}
return super.vertex(shader, pass);
}
}
Cartesian.initClass();
| cchudzicki/mathbox | src/primitives/types/view/cartesian.js | JavaScript | mit | 2,102 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { View } from "./view.js";
export class Cartesian4 extends View {
static initClass() {
this.traits = ["node", "object", "visible", "view", "view4", "vertex"];
}
make() {
super.make();
this.uniforms = {
basisOffset: this._attributes.make(this._types.vec4()),
basisScale: this._attributes.make(this._types.vec4()),
};
this.basisScale = this.uniforms.basisScale.value;
return (this.basisOffset = this.uniforms.basisOffset.value);
}
unmake() {
super.unmake();
delete this.basisScale;
delete this.basisOffset;
return delete this.uniforms;
}
change(changed, touched, init) {
if (!touched["view"] && !touched["view4"] && !init) {
return;
}
const p = this.props.position;
const s = this.props.scale;
const g = this.props.range;
const { x } = g[0];
const y = g[1].x;
const z = g[2].x;
const w = g[3].x;
const dx = g[0].y - x || 1;
const dy = g[1].y - y || 1;
const dz = g[2].y - z || 1;
const dw = g[3].y - w || 1;
const mult = function (a, b) {
a.x *= b.x;
a.y *= b.y;
a.z *= b.z;
return (a.w *= b.w);
};
// 4D axis adjustment
this.basisScale.set(2 / dx, 2 / dy, 2 / dz, 2 / dw);
this.basisOffset.set(
-(2 * x + dx) / dx,
-(2 * y + dy) / dy,
-(2 * z + dz) / dz,
-(2 * w + dw) / dw
);
// 4D scale
mult(this.basisScale, s);
mult(this.basisOffset, s);
// 4D position
this.basisOffset.add(p);
if (changed["view.range"]) {
return this.trigger({
type: "view.range",
});
}
}
vertex(shader, pass) {
if (pass === 1) {
shader.pipe("cartesian4.position", this.uniforms);
}
return super.vertex(shader, pass);
}
}
Cartesian4.initClass();
| cchudzicki/mathbox | src/primitives/types/view/cartesian4.js | JavaScript | mit | 2,168 |
export * from "./view.js";
export * from "./cartesian.js";
export * from "./cartesian4.js";
export * from "./polar.js";
export * from "./spherical.js";
export * from "./stereographic.js";
export * from "./stereographic4.js";
| cchudzicki/mathbox | src/primitives/types/view/index.js | JavaScript | mit | 225 |
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import * as UAxis from "../../../util/axis.js";
import * as UThree from "../../../util/three.js";
import { Vector2 } from "three/src/math/Vector2.js";
import { View } from "./view.js";
export class Polar extends View {
static initClass() {
this.traits = [
"node",
"object",
"visible",
"view",
"view3",
"polar",
"vertex",
];
}
make() {
super.make();
const { types } = this._attributes;
this.uniforms = {
polarBend: this.node.attributes["polar.bend"],
polarHelix: this.node.attributes["polar.helix"],
polarFocus: this._attributes.make(types.number()),
polarAspect: this._attributes.make(types.number()),
viewMatrix: this._attributes.make(types.mat4()),
};
this.viewMatrix = this.uniforms.viewMatrix.value;
this.composer = UThree.transformComposer();
return (this.aspect = 1);
}
unmake() {
super.unmake();
delete this.viewMatrix;
delete this.objectMatrix;
delete this.aspect;
return delete this.uniforms;
}
change(changed, touched, init) {
let aspect, bend, focus;
if (!touched["view"] && !touched["view3"] && !touched["polar"] && !init) {
return;
}
this.helix = this.props.helix;
this.bend = bend = this.props.bend;
this.focus = focus = bend > 0 ? 1 / bend - 1 : 0;
const p = this.props.position;
const s = this.props.scale;
const q = this.props.quaternion;
const r = this.props.rotation;
const g = this.props.range;
const e = this.props.eulerOrder;
const { x } = g[0];
let y = g[1].x;
const z = g[2].x;
const dx = g[0].y - x || 1;
let dy = g[1].y - y || 1;
const dz = g[2].y - z || 1;
const sx = s.x;
const sy = s.y;
// Watch for negative scales.
const idx = dx > 0 ? 1 : -1;
// Recenter viewport on origin the more it's bent
[y, dy] = Array.from(UAxis.recenterAxis(y, dy, bend));
// Adjust viewport range for polar transform.
// As the viewport goes polar, the X-range is interpolated to the Y-range instead,
// creating a square/circular viewport.
const ady = Math.abs(dy);
const fdx = dx + (ady * idx - dx) * bend;
const sdx = fdx / sx;
const sdy = dy / sy;
this.aspect = aspect = Math.abs(sdx / sdy);
this.uniforms.polarFocus.value = focus;
this.uniforms.polarAspect.value = aspect;
// Forward transform
this.viewMatrix.set(
2 / fdx,
0,
0,
-(2 * x + dx) / dx,
0,
2 / dy,
0,
-(2 * y + dy) / dy,
0,
0,
2 / dz,
-(2 * z + dz) / dz,
0,
0,
0,
1 //,
);
const transformMatrix = this.composer(p, r, q, s, null, e);
this.viewMatrix.multiplyMatrices(transformMatrix, this.viewMatrix);
if (changed["view.range"] || touched["polar"]) {
this.trigger({
type: "view.range",
});
}
}
vertex(shader, pass) {
if (pass === 1) {
shader.pipe("polar.position", this.uniforms);
}
return super.vertex(shader, pass);
}
axis(dimension) {
const range = this.props.range[dimension - 1];
let min = range.x;
let max = range.y;
// Correct Y extents during polar warp.
if (dimension === 2 && this.bend > 0) {
max = Math.max(Math.abs(max), Math.abs(min));
min = Math.max(-this.focus / this.aspect, min);
}
return new Vector2(min, max);
}
}
Polar.initClass();
| cchudzicki/mathbox | src/primitives/types/view/polar.js | JavaScript | mit | 3,857 |