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 default /* glsl */ `varying float vPixelSize; float getGenericAlpha(float mask) { return vPixelSize * 2.0 * (1.0 - mask); } `;
cchudzicki/mathbox
src/shaders/glsl/point.alpha.generic.js
JavaScript
mit
136
export default /* glsl */ `varying vec2 vSprite; float getSpriteMask(vec2 xy); float getSpriteAlpha(float mask); void setFragmentColorFill(vec4 color) { float mask = getSpriteMask(vSprite); if (mask > 1.0) { discard; } float alpha = getSpriteAlpha(mask); if (alpha >= 1.0) { discard; } gl_FragColor = vec4(color.rgb, alpha * color.a); } `;
cchudzicki/mathbox
src/shaders/glsl/point.edge.js
JavaScript
mit
363
export default /* glsl */ `varying vec2 vSprite; float getSpriteMask(vec2 xy); float getSpriteAlpha(float mask); void setFragmentColorFill(vec4 color) { float mask = getSpriteMask(vSprite); if (mask > 1.0) { discard; } float alpha = getSpriteAlpha(mask); if (alpha < 1.0) { discard; } gl_FragColor = color; } `;
cchudzicki/mathbox
src/shaders/glsl/point.fill.js
JavaScript
mit
336
export default /* glsl */ `varying float vPixelSize; float getCircleMask(vec2 uv) { return dot(uv, uv); } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.circle.js
JavaScript
mit
111
export default /* glsl */ `varying float vPixelSize; float getDiamondMask(vec2 uv) { vec2 a = abs(uv); return a.x + a.y; } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.diamond.js
JavaScript
mit
130
export default /* glsl */ `varying float vPixelSize; float getTriangleDownMask(vec2 uv) { uv.y += .25; return max(uv.y, abs(uv.x) * .866 - uv.y * .5 + .6); } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.down.js
JavaScript
mit
165
export default /* glsl */ `varying float vPixelSize; float getTriangleLeftMask(vec2 uv) { uv.x += .25; return max(uv.x, abs(uv.y) * .866 - uv.x * .5 + .6); } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.left.js
JavaScript
mit
165
export default /* glsl */ `varying float vPixelSize; float getTriangleRightMask(vec2 uv) { uv.x -= .25; return max(-uv.x, abs(uv.y) * .866 + uv.x * .5 + .6); } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.right.js
JavaScript
mit
167
export default /* glsl */ `varying float vPixelSize; float getSquareMask(vec2 uv) { vec2 a = abs(uv); return max(a.x, a.y); } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.square.js
JavaScript
mit
133
export default /* glsl */ `varying float vPixelSize; float getTriangleUpMask(vec2 uv) { uv.y -= .25; return max(-uv.y, abs(uv.x) * .866 + uv.y * .5 + .6); } `;
cchudzicki/mathbox
src/shaders/glsl/point.mask.up.js
JavaScript
mit
164
export default /* glsl */ `uniform float pointDepth; uniform float pixelUnit; uniform float renderScale; uniform float renderScaleInv; uniform float focusDepth; uniform vec4 geometryClip; attribute vec4 position4; attribute vec2 sprite; varying vec2 vSprite; varying float vPixelSize; const float pointScale = POINT_SHAPE_SCALE; // External float getPointSize(vec4 xyzw); vec3 getPosition(vec4 xyzw, float canonical); vec3 getPointPosition() { vec4 p = min(geometryClip, position4); vec3 center = getPosition(p, 1.0); // Depth blending // TODO: orthographic camera // Workaround: set depth = 0 float z = -center.z; float depth = mix(z, focusDepth, pointDepth); // Match device/unit mapping // Sprite goes from -1..1, width = 2. float pointSize = getPointSize(p); float size = pointScale * pointSize * pixelUnit * .5; float depthSize = depth * size; // Pad sprite by half a pixel to make the anti-aliasing straddle the pixel edge // Note: pixelsize measures radius float pixelSize = .5 * (pointDepth > 0.0 ? depthSize / z : size); float paddedSize = pixelSize + 0.5; float padFactor = paddedSize / pixelSize; vPixelSize = paddedSize; vSprite = sprite; return center + vec3(sprite * depthSize * renderScaleInv * padFactor, 0.0); } `;
cchudzicki/mathbox
src/shaders/glsl/point.position.js
JavaScript
mit
1,290
export default /* glsl */ `uniform float pointSize; float getPointSize(vec4 xyzw) { return pointSize; }`;
cchudzicki/mathbox
src/shaders/glsl/point.size.uniform.js
JavaScript
mit
108
export default /* glsl */ `uniform float pointSize; vec4 getSample(vec4 xyzw); float getPointSize(vec4 xyzw) { return pointSize * getSample(xyzw).x; }`;
cchudzicki/mathbox
src/shaders/glsl/point.size.varying.js
JavaScript
mit
156
export default /* glsl */ `uniform float polarBend; uniform float polarFocus; uniform float polarAspect; uniform float polarHelix; uniform mat4 viewMatrix; vec4 getPolarPosition(vec4 position, inout vec4 stpq) { if (polarBend > 0.0) { if (polarBend < 0.001) { // Factor out large addition/subtraction of polarFocus // to avoid numerical error // sin(x) ~ x // cos(x) ~ 1 - x * x / 2 vec2 pb = position.xy * polarBend; float ppbbx = pb.x * pb.x; return viewMatrix * vec4( position.x * (1.0 - polarBend + (pb.y * polarAspect)), position.y * (1.0 - .5 * ppbbx) - (.5 * ppbbx) * polarFocus / polarAspect, position.z + position.x * polarHelix * polarBend, 1.0 ); } else { vec2 xy = position.xy * vec2(polarBend, polarAspect); float radius = polarFocus + xy.y; return viewMatrix * vec4( sin(xy.x) * radius, (cos(xy.x) * radius - polarFocus) / polarAspect, position.z + position.x * polarHelix * polarBend, 1.0 ); } } else { return viewMatrix * vec4(position.xyz, 1.0); } }`;
cchudzicki/mathbox
src/shaders/glsl/polar.position.js
JavaScript
mit
1,135
export default /* glsl */ `uniform float styleZBias; uniform float styleZIndex; void setPosition(vec3 position) { vec4 pos = projectionMatrix * vec4(position, 1.0); // Apply relative Z bias float bias = (1.0 - styleZBias / 32768.0); pos.z *= bias; // Apply large scale Z index changes if (styleZIndex > 0.0) { float z = pos.z / pos.w; pos.z = ((z + 1.0) / (styleZIndex + 1.0) - 1.0) * pos.w; } gl_Position = pos; }`;
cchudzicki/mathbox
src/shaders/glsl/project.position.js
JavaScript
mit
449
export default /* glsl */ `// This is three.js' global uniform, missing from fragment shaders. uniform mat4 projectionMatrix; vec4 readbackPosition(vec3 position, vec4 stpq) { vec4 pos = projectionMatrix * vec4(position, 1.0); vec3 final = pos.xyz / pos.w; if (final.z < -1.0) { return vec4(0.0, 0.0, 0.0, -1.0); } else { return vec4(final, -position.z); } } `;
cchudzicki/mathbox
src/shaders/glsl/project.readback.js
JavaScript
mit
382
export default /* glsl */ `uniform vec4 geometryScale; attribute vec4 position4; vec4 getRawPositionScale() { return geometryScale * position4; } `;
cchudzicki/mathbox
src/shaders/glsl/raw.position.scale.js
JavaScript
mit
151
export default /* glsl */ `uniform vec4 repeatModulus; vec4 getRepeatXYZW(vec4 xyzw) { return mod(xyzw + .5, repeatModulus) - .5; } `;
cchudzicki/mathbox
src/shaders/glsl/repeat.position.js
JavaScript
mit
137
export default /* glsl */ `uniform vec4 resampleBias; vec4 resamplePadding(vec4 xyzw) { return xyzw + resampleBias; }`;
cchudzicki/mathbox
src/shaders/glsl/resample.padding.js
JavaScript
mit
122
export default /* glsl */ `uniform vec4 resampleFactor; vec4 resampleRelative(vec4 xyzw) { return xyzw * resampleFactor; }`;
cchudzicki/mathbox
src/shaders/glsl/resample.relative.js
JavaScript
mit
127
export default /* glsl */ `uniform float transitionEnter; uniform float transitionExit; uniform vec4 transitionScale; uniform vec4 transitionBias; uniform float transitionSkew; uniform float transitionActive; float getTransitionSDFMask(vec4 stpq) { if (transitionActive < 0.5) return 1.0; float enter = transitionEnter; float exit = transitionExit; float skew = transitionSkew; vec4 scale = transitionScale; vec4 bias = transitionBias; float factor = 1.0 + skew; float offset = dot(vec4(1.0), stpq * scale + bias); vec2 d = vec2(enter, exit) * factor + vec2(-offset, offset - skew); if (exit == 1.0) return d.x; if (enter == 1.0) return d.y; return min(d.x, d.y); }`;
cchudzicki/mathbox
src/shaders/glsl/reveal.mask.js
JavaScript
mit
715
export default /* glsl */ `vec3 getRootPosition(vec4 position, in vec4 stpqIn, out vec4 stpqOut) { stpqOut = stpqIn; // avoid inout confusion return position.xyz; }`;
cchudzicki/mathbox
src/shaders/glsl/root.position.js
JavaScript
mit
170
export default /* glsl */ `uniform sampler2D dataTexture; vec4 sample2D(vec2 uv) { return texture2D(dataTexture, uv); } `;
cchudzicki/mathbox
src/shaders/glsl/sample.2d.js
JavaScript
mit
125
export default /* glsl */ `uniform vec4 scaleAxis; uniform vec4 scaleOffset; vec4 sampleData(float x); vec4 getScalePosition(vec4 xyzw) { return scaleAxis * sampleData(xyzw.x).x + scaleOffset; } `;
cchudzicki/mathbox
src/shaders/glsl/scale.position.js
JavaScript
mit
201
export default /* glsl */ `uniform vec4 remapSTPQScale; vec4 screenMapSTPQ(vec4 xyzw, out vec4 stpq) { stpq = xyzw * remapSTPQScale; return xyzw; } `;
cchudzicki/mathbox
src/shaders/glsl/screen.map.stpq.js
JavaScript
mit
155
export default /* glsl */ `uniform vec2 remapUVScale; vec4 screenMapXY(vec4 uvwo, vec4 stpq) { return vec4(floor(remapUVScale * uvwo.xy), 0.0, 0.0); } `;
cchudzicki/mathbox
src/shaders/glsl/screen.map.xy.js
JavaScript
mit
156
export default /* glsl */ `uniform vec2 remapUVScale; uniform vec2 remapModulus; uniform vec2 remapModulusInv; vec4 screenMapXYZW(vec4 uvwo, vec4 stpq) { vec2 st = floor(remapUVScale * uvwo.xy); vec2 xy = st * remapModulusInv; vec2 ixy = floor(xy); vec2 fxy = xy - ixy; vec2 zw = fxy * remapModulus; return vec4(ixy.x, zw.y, ixy.y, zw.x); } `;
cchudzicki/mathbox
src/shaders/glsl/screen.map.xyzw.js
JavaScript
mit
356
export default /* glsl */ `vec2 screenPassUV(vec4 uvwo, vec4 stpq) { return uvwo.xy; } `;
cchudzicki/mathbox
src/shaders/glsl/screen.pass.uv.js
JavaScript
mit
91
export default /* glsl */ `void setScreenPosition(vec4 position) { gl_Position = vec4(position.xy * 2.0 - 1.0, 0.5, 1.0); } `;
cchudzicki/mathbox
src/shaders/glsl/screen.position.js
JavaScript
mit
128
export default /* glsl */ `uniform vec4 sliceOffset; vec4 getSliceOffset(vec4 xyzw) { return xyzw + sliceOffset; } `;
cchudzicki/mathbox
src/shaders/glsl/slice.position.js
JavaScript
mit
120
export default /* glsl */ `uniform float sphericalBend; uniform float sphericalFocus; uniform float sphericalAspectX; uniform float sphericalAspectY; uniform float sphericalScaleY; uniform mat4 viewMatrix; vec4 getSphericalPosition(vec4 position, inout vec4 stpq) { if (sphericalBend > 0.0001) { vec3 xyz = position.xyz * vec3(sphericalBend, sphericalBend / sphericalAspectY * sphericalScaleY, sphericalAspectX); float radius = sphericalFocus + xyz.z; float cosine = cos(xyz.y) * radius; return viewMatrix * vec4( sin(xyz.x) * cosine, sin(xyz.y) * radius * sphericalAspectY, (cos(xyz.x) * cosine - sphericalFocus) / sphericalAspectX, 1.0 ); } else { return viewMatrix * vec4(position.xyz, 1.0); } }`;
cchudzicki/mathbox
src/shaders/glsl/spherical.position.js
JavaScript
mit
760
export default /* glsl */ `uniform float splitStride; vec2 getIndices(vec4 xyzw); vec4 getRest(vec4 xyzw); vec4 injectIndex(float v); vec4 getSplitXYZW(vec4 xyzw) { vec2 uv = getIndices(xyzw); float offset = uv.x + uv.y * splitStride; return injectIndex(offset) + getRest(xyzw); } `;
cchudzicki/mathbox
src/shaders/glsl/split.position.js
JavaScript
mit
291
export default /* glsl */ `uniform vec4 spreadOffset; uniform mat4 spreadMatrix; // External vec4 getSample(vec4 xyzw); vec4 getSpreadSample(vec4 xyzw) { vec4 sample = getSample(xyzw); return sample + spreadMatrix * (spreadOffset + xyzw); } `;
cchudzicki/mathbox
src/shaders/glsl/spread.position.js
JavaScript
mit
249
export default /* glsl */ `varying vec2 vSprite; vec4 getSample(vec2 xy); vec4 getSpriteColor() { return getSample(vSprite); }`;
cchudzicki/mathbox
src/shaders/glsl/sprite.fragment.js
JavaScript
mit
132
export default /* glsl */ `uniform vec2 spriteOffset; uniform float spriteScale; uniform float spriteDepth; uniform float spriteSnap; uniform vec2 renderOdd; uniform float renderScale; uniform float renderScaleInv; uniform float pixelUnit; uniform float focusDepth; uniform vec4 geometryClip; attribute vec4 position4; attribute vec2 sprite; varying float vPixelSize; // External vec3 getPosition(vec4 xyzw, float canonical); vec4 getSprite(vec4 xyzw); vec3 getSpritePosition() { // Clip points vec4 p = min(geometryClip, position4); float diff = length(position4 - p); if (diff > 0.0) { return vec3(0.0, 0.0, 1000.0); } // Make sprites vec3 center = getPosition(p, 1.0); vec4 atlas = getSprite(p); // Sprite goes from -1..1, width = 2. // -1..1 -> -0.5..0.5 vec2 halfSprite = sprite * .5; vec2 halfFlipSprite = vec2(halfSprite.x, -halfSprite.y); #ifdef POSITION_UV // Assign UVs vUV = atlas.xy + atlas.zw * (halfFlipSprite + .5); #endif // Depth blending // TODO: orthographic camera // Workaround: set depth = 0 float depth = focusDepth, z; z = -center.z; if (spriteDepth < 1.0) { depth = mix(z, focusDepth, spriteDepth); } // Match device/unit mapping float size = pixelUnit * spriteScale; float depthSize = depth * size; // Calculate pixelSize for anti-aliasing float pixelSize = (spriteDepth > 0.0 ? depthSize / z : size); vPixelSize = pixelSize; // Position sprite vec2 atlasOdd = fract(atlas.zw / 2.0); vec2 offset = (spriteOffset + halfSprite * atlas.zw) * depthSize; if (spriteSnap > 0.5) { // Snap to pixel (w/ epsilon shift to avoid jitter) return vec3(((floor(center.xy / center.z * renderScale + 0.001) + renderOdd + atlasOdd) * center.z + offset) * renderScaleInv, center.z); } else { // Place directly return center + vec3(offset * renderScaleInv, 0.0); } } `;
cchudzicki/mathbox
src/shaders/glsl/sprite.position.js
JavaScript
mit
1,883
export default /* glsl */ `uniform float stereoBend; uniform mat4 viewMatrix; vec4 getStereoPosition(vec4 position, inout vec4 stpq) { if (stereoBend > 0.0001) { vec3 pos = position.xyz; float r = length(pos); float z = r + pos.z; vec3 project = vec3(pos.xy / z, r); vec3 lerped = mix(pos, project, stereoBend); return viewMatrix * vec4(lerped, 1.0); } else { return viewMatrix * vec4(position.xyz, 1.0); } }`;
cchudzicki/mathbox
src/shaders/glsl/stereographic.position.js
JavaScript
mit
455
export default /* glsl */ `uniform float stereoBend; uniform vec4 basisScale; uniform vec4 basisOffset; uniform mat4 viewMatrix; uniform vec2 view4D; vec4 getStereographic4Position(vec4 position, inout vec4 stpq) { vec4 transformed; if (stereoBend > 0.0001) { float r = length(position); float w = r + position.w; vec4 project = vec4(position.xyz / w, r); transformed = mix(position, project, stereoBend); } else { transformed = position; } vec4 pos4 = transformed * basisScale - basisOffset; vec3 xyz = (viewMatrix * vec4(pos4.xyz, 1.0)).xyz; return vec4(xyz, pos4.w * view4D.y + view4D.x); } `;
cchudzicki/mathbox
src/shaders/glsl/stereographic4.position.js
JavaScript
mit
643
export default /* glsl */ `varying vec2 vST; vec4 getSample(vec2 st); vec4 getSTSample() { return getSample(vST); } `;
cchudzicki/mathbox
src/shaders/glsl/stpq.sample.2d.js
JavaScript
mit
122
export default /* glsl */ `varying vec2 vUV; void setRawUV(vec4 xyzw) { vUV = xyzw.xy; } `;
cchudzicki/mathbox
src/shaders/glsl/stpq.xyzw.2d.js
JavaScript
mit
94
export default /* glsl */ `uniform vec4 geometryClip; attribute vec4 position4; attribute vec3 strip; // External vec3 getPosition(vec4 xyzw, float canonical); varying vec3 vNormal; varying vec3 vLight; varying vec3 vPosition; void getStripGeometry(vec4 xyzw, vec3 strip, out vec3 pos, out vec3 normal) { vec3 a, b, c; a = getPosition(xyzw, 1.0); b = getPosition(vec4(xyzw.xyz, strip.x), 0.0); c = getPosition(vec4(xyzw.xyz, strip.y), 0.0); normal = normalize(cross(c - a, b - a)) * strip.z; pos = a; } vec3 getStripPositionNormal() { vec3 center, normal; vec4 p = min(geometryClip, position4); getStripGeometry(p, strip, center, normal); vNormal = normal; vLight = normalize((viewMatrix * vec4(1.0, 2.0, 2.0, 0.0)).xyz); vPosition = -center; return center; } `;
cchudzicki/mathbox
src/shaders/glsl/strip.position.normal.js
JavaScript
mit
811
export default /* glsl */ `uniform vec3 styleColor; uniform float styleOpacity; vec4 getStyleColor() { return vec4(styleColor, styleOpacity); } `;
cchudzicki/mathbox
src/shaders/glsl/style.color.js
JavaScript
mit
149
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideDepth(vec4 xyzw) { float x = xyzw.z; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; return sampleData(vec4(xyzw.xy, i + g, xyzw.w)); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.depth.js
JavaScript
mit
360
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideDepthLerp(vec4 xyzw) { float x = xyzw.z; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; vec4 xyzw1 = vec4(xyzw.xy, i, xyzw.w); vec4 xyzw2 = vec4(xyzw.xy, i + 1.0, xyzw.w); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, g); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.depth.lerp.js
JavaScript
mit
488
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideHeight(vec4 xyzw) { float x = xyzw.y; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; return sampleData(vec4(xyzw.x, i + g, xyzw.zw)); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.height.js
JavaScript
mit
361
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideHeightLerp(vec4 xyzw) { float x = xyzw.y; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; vec4 xyzw1 = vec4(xyzw.x, i, xyzw.zw); vec4 xyzw2 = vec4(xyzw.x, i + 1.0, xyzw.zw); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, g); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.height.lerp.js
JavaScript
mit
489
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideItems(vec4 xyzw) { float x = xyzw.w; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; return sampleData(vec4(xyzw.xyz, i + g)); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.items.js
JavaScript
mit
353
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideItemsLerp(vec4 xyzw) { float x = xyzw.w; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; vec4 xyzw1 = vec4(xyzw.xyz, i); vec4 xyzw2 = vec4(xyzw.xyz, i + 1.0); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, g); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.items.lerp.js
JavaScript
mit
474
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideWidth(vec4 xyzw) { float x = xyzw.x; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; return sampleData(vec4(i + g, xyzw.yzw)); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.width.js
JavaScript
mit
353
export default /* glsl */ `uniform float subdivideBevel; // External vec4 sampleData(vec4 xyzw); vec4 subdivideWidthLerp(vec4 xyzw) { float x = xyzw.x; float i = floor(x); float f = x - i; float minf = subdivideBevel * min(f, 1.0 - f); float g = (f > 0.5) ? 1.0 - minf : (f < 0.5) ? minf : 0.5; vec4 xyzw1 = vec4(i, xyzw.yzw); vec4 xyzw2 = vec4(i + 1.0, xyzw.yzw); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, g); } `;
cchudzicki/mathbox
src/shaders/glsl/subdivide.width.lerp.js
JavaScript
mit
474
export default /* glsl */ `attribute vec4 position4; float getSurfaceHollowMask(vec4 xyzw) { vec4 df = abs(fract(position4) - .5); vec2 df2 = min(df.xy, df.zw); float df3 = min(df2.x, df2.y); return df3; }`;
cchudzicki/mathbox
src/shaders/glsl/surface.mask.hollow.js
JavaScript
mit
216
export default /* glsl */ `uniform vec4 geometryClip; uniform vec4 geometryResolution; uniform vec4 mapSize; attribute vec4 position4; // External vec3 getPosition(vec4 xyzw, float canonical); vec3 getSurfacePosition() { vec4 p = min(geometryClip, position4); vec3 xyz = getPosition(p, 1.0); // Overwrite UVs #ifdef POSITION_UV #ifdef POSITION_UV_INT vUV = -.5 + (position4.xy * geometryResolution.xy) * mapSize.xy; #else vUV = position4.xy * geometryResolution.xy; #endif #endif return xyz; } `;
cchudzicki/mathbox
src/shaders/glsl/surface.position.js
JavaScript
mit
513
export default /* glsl */ `uniform vec4 mapSize; uniform vec4 geometryResolution; uniform vec4 geometryClip; attribute vec4 position4; attribute vec2 surface; // External vec3 getPosition(vec4 xyzw, float canonical); void getSurfaceGeometry(vec4 xyzw, float edgeX, float edgeY, out vec3 left, out vec3 center, out vec3 right, out vec3 up, out vec3 down) { vec4 deltaX = vec4(1.0, 0.0, 0.0, 0.0); vec4 deltaY = vec4(0.0, 1.0, 0.0, 0.0); /* // high quality, 5 tap center = getPosition(xyzw, 1.0); left = (edgeX > -0.5) ? getPosition(xyzw - deltaX, 0.0) : center; right = (edgeX < 0.5) ? getPosition(xyzw + deltaX, 0.0) : center; down = (edgeY > -0.5) ? getPosition(xyzw - deltaY, 0.0) : center; up = (edgeY < 0.5) ? getPosition(xyzw + deltaY, 0.0) : center; */ // low quality, 3 tap center = getPosition(xyzw, 1.0); left = center; down = center; right = (edgeX < 0.5) ? getPosition(xyzw + deltaX, 0.0) : (2.0 * center - getPosition(xyzw - deltaX, 0.0)); up = (edgeY < 0.5) ? getPosition(xyzw + deltaY, 0.0) : (2.0 * center - getPosition(xyzw - deltaY, 0.0)); } vec3 getSurfaceNormal(vec3 left, vec3 center, vec3 right, vec3 up, vec3 down) { vec3 dx = right - left; vec3 dy = up - down; vec3 n = cross(dy, dx); if (length(n) > 0.0) { return normalize(n); } return vec3(0.0, 1.0, 0.0); } varying vec3 vNormal; varying vec3 vLight; varying vec3 vPosition; vec3 getSurfacePositionNormal() { vec3 left, center, right, up, down; vec4 p = min(geometryClip, position4); getSurfaceGeometry(p, surface.x, surface.y, left, center, right, up, down); vNormal = getSurfaceNormal(left, center, right, up, down); vLight = normalize((viewMatrix * vec4(1.0, 2.0, 2.0, 0.0)).xyz); // hardcoded directional light vPosition = -center; #ifdef POSITION_UV #ifdef POSITION_UV_INT vUV = -.5 + (position4.xy * geometryResolution.xy) * mapSize.xy; #else vUV = position4.xy * geometryResolution.xy; #endif #endif return center; } `;
cchudzicki/mathbox
src/shaders/glsl/surface.position.normal.js
JavaScript
mit
2,081
export default /* glsl */ `uniform float worldUnit; uniform float focusDepth; uniform float tickSize; uniform float tickEpsilon; uniform vec3 tickNormal; uniform vec2 tickStrip; vec4 getSample(vec4 xyzw); vec3 transformPosition(vec4 position, in vec4 stpqIn, out vec4 stpqOut); vec3 getTickPosition(vec4 xyzw, in vec4 stpqIn, out vec4 stpqOut) { float epsilon = tickEpsilon; // determine tick direction float leftX = max(tickStrip.x, xyzw.y - 1.0); float rightX = min(tickStrip.y, xyzw.y + 1.0); vec4 left = getSample(vec4(leftX, xyzw.zw, 0.0)); vec4 right = getSample(vec4(rightX, xyzw.zw, 0.0)); vec4 diff = right - left; vec3 normal = cross(normalize(diff.xyz + vec3(diff.w)), tickNormal); float bias = max(0.0, 1.0 - length(normal) * 2.0); normal = mix(normal, tickNormal.yzx, bias * bias); // transform (point) and (point + delta) vec4 center = getSample(vec4(xyzw.yzw, 0.0)); vec4 delta = vec4(normal, 0.0) * epsilon; vec4 a = center; vec4 b = center + delta; vec4 _; vec3 c = transformPosition(a, stpqIn, stpqOut); vec3 d = transformPosition(b, stpqIn, _); // sample on either side to create line float line = xyzw.x - .5; vec3 mid = c; vec3 side = normalize(d - c); return mid + side * line * tickSize * worldUnit * focusDepth; } `;
cchudzicki/mathbox
src/shaders/glsl/ticks.position.js
JavaScript
mit
1,330
export default /* glsl */ `uniform mat4 transformMatrix; vec4 transformPosition(vec4 position, inout vec4 stpq) { return transformMatrix * vec4(position.xyz, 1.0); } `;
cchudzicki/mathbox
src/shaders/glsl/transform3.position.js
JavaScript
mit
171
export default /* glsl */ `uniform mat4 transformMatrix; uniform vec4 transformOffset; vec4 transformPosition(vec4 position, inout vec4 stpq) { return transformMatrix * position + transformOffset; } `;
cchudzicki/mathbox
src/shaders/glsl/transform4.position.js
JavaScript
mit
204
export default /* glsl */ `// Implicit three.js uniform // uniform mat4 viewMatrix; vec4 getViewPosition(vec4 position, inout vec4 stpq) { return (viewMatrix * vec4(position.xyz, 1.0)); } `;
cchudzicki/mathbox
src/shaders/glsl/view.position.js
JavaScript
mit
193
import arrowposition from "./glsl/arrow.position"; import axisposition from "./glsl/axis.position"; import cartesian4position from "./glsl/cartesian4.position"; import cartesianposition from "./glsl/cartesian.position"; import clampposition from "./glsl/clamp.position"; import coloropaque from "./glsl/color.opaque"; import faceposition from "./glsl/face.position"; import facepositionnormal from "./glsl/face.position.normal"; import floatencode from "./glsl/float.encode"; import floatindexpack from "./glsl/float.index.pack"; import floatstretch from "./glsl/float.stretch"; import fragmentclipdashed from "./glsl/fragment.clip.dashed"; import fragmentclipdotted from "./glsl/fragment.clip.dotted"; import fragmentclipends from "./glsl/fragment.clip.ends"; import fragmentclipproximity from "./glsl/fragment.clip.proximity"; import fragmentcolor from "./glsl/fragment.color"; import fragmentmaprgba from "./glsl/fragment.map.rgba"; import fragmentsolid from "./glsl/fragment.solid"; import fragmenttransparent from "./glsl/fragment.transparent"; import gridposition from "./glsl/grid.position"; import growposition from "./glsl/grow.position"; import joinposition from "./glsl/join.position"; import labelalpha from "./glsl/label.alpha"; import labelmap from "./glsl/label.map"; import labeloutline from "./glsl/label.outline"; import layerposition from "./glsl/layer.position"; import lerpdepth from "./glsl/lerp.depth"; import lerpheight from "./glsl/lerp.height"; import lerpitems from "./glsl/lerp.items"; import lerpwidth from "./glsl/lerp.width"; import lineposition from "./glsl/line.position"; import map2ddata from "./glsl/map.2d.data"; import map2ddatawrap from "./glsl/map.2d.data.wrap"; import mapxyzw2dv from "./glsl/map.xyzw.2dv"; import mapxyzwalign from "./glsl/map.xyzw.align"; import mapxyzwtexture from "./glsl/map.xyzw.texture"; import meshfragmentcolor from "./glsl/mesh.fragment.color"; import meshfragmentmap from "./glsl/mesh.fragment.map"; import meshfragmentmask from "./glsl/mesh.fragment.mask"; import meshfragmentmaterial from "./glsl/mesh.fragment.material"; import meshfragmentshaded from "./glsl/mesh.fragment.shaded"; import meshfragmenttexture from "./glsl/mesh.fragment.texture"; import meshgammain from "./glsl/mesh.gamma.in"; import meshgammaout from "./glsl/mesh.gamma.out"; import meshmapuvwo from "./glsl/mesh.map.uvwo"; import meshposition from "./glsl/mesh.position"; import meshvertexcolor from "./glsl/mesh.vertex.color"; import meshvertexmask from "./glsl/mesh.vertex.mask"; import meshvertexposition from "./glsl/mesh.vertex.position"; import moveposition from "./glsl/move.position"; import objectmaskdefault from "./glsl/object.mask.default"; import pointalphacircle from "./glsl/point.alpha.circle"; import pointalphacirclehollow from "./glsl/point.alpha.circle.hollow"; import pointalphageneric from "./glsl/point.alpha.generic"; import pointalphagenerichollow from "./glsl/point.alpha.generic.hollow"; import pointedge from "./glsl/point.edge"; import pointfill from "./glsl/point.fill"; import pointmaskcircle from "./glsl/point.mask.circle"; import pointmaskdiamond from "./glsl/point.mask.diamond"; import pointmaskdown from "./glsl/point.mask.down"; import pointmaskleft from "./glsl/point.mask.left"; import pointmaskright from "./glsl/point.mask.right"; import pointmasksquare from "./glsl/point.mask.square"; import pointmaskup from "./glsl/point.mask.up"; import pointposition from "./glsl/point.position"; import pointsizeuniform from "./glsl/point.size.uniform"; import pointsizevarying from "./glsl/point.size.varying"; import polarposition from "./glsl/polar.position"; import projectposition from "./glsl/project.position"; import projectreadback from "./glsl/project.readback"; import rawpositionscale from "./glsl/raw.position.scale"; import repeatposition from "./glsl/repeat.position"; import resamplepadding from "./glsl/resample.padding"; import resamplerelative from "./glsl/resample.relative"; import revealmask from "./glsl/reveal.mask"; import rootposition from "./glsl/root.position"; import sample2d from "./glsl/sample.2d"; import scaleposition from "./glsl/scale.position"; import screenmapstpq from "./glsl/screen.map.stpq"; import screenmapxy from "./glsl/screen.map.xy"; import screenmapxyzw from "./glsl/screen.map.xyzw"; import screenpassuv from "./glsl/screen.pass.uv"; import screenposition from "./glsl/screen.position"; import sliceposition from "./glsl/slice.position"; import sphericalposition from "./glsl/spherical.position"; import splitposition from "./glsl/split.position"; import spreadposition from "./glsl/spread.position"; import spritefragment from "./glsl/sprite.fragment"; import spriteposition from "./glsl/sprite.position"; import stereographic4position from "./glsl/stereographic4.position"; import stereographicposition from "./glsl/stereographic.position"; import stpqsample2d from "./glsl/stpq.sample.2d"; import stpqxyzw2d from "./glsl/stpq.xyzw.2d"; import strippositionnormal from "./glsl/strip.position.normal"; import stylecolor from "./glsl/style.color"; import subdividedepth from "./glsl/subdivide.depth"; import subdividedepthlerp from "./glsl/subdivide.depth.lerp"; import subdivideheight from "./glsl/subdivide.height"; import subdivideheightlerp from "./glsl/subdivide.height.lerp"; import subdivideitems from "./glsl/subdivide.items"; import subdivideitemslerp from "./glsl/subdivide.items.lerp"; import subdividewidth from "./glsl/subdivide.width"; import subdividewidthlerp from "./glsl/subdivide.width.lerp"; import surfacemaskhollow from "./glsl/surface.mask.hollow"; import surfaceposition from "./glsl/surface.position"; import surfacepositionnormal from "./glsl/surface.position.normal"; import ticksposition from "./glsl/ticks.position"; import transform3position from "./glsl/transform3.position"; import transform4position from "./glsl/transform4.position"; import viewposition from "./glsl/view.position"; export const Snippets = { "arrow.position": arrowposition, "axis.position": axisposition, "cartesian.position": cartesianposition, "cartesian4.position": cartesian4position, "clamp.position": clampposition, "color.opaque": coloropaque, "face.position": faceposition, "face.position.normal": facepositionnormal, "float.encode": floatencode, "float.index.pack": floatindexpack, "float.stretch": floatstretch, "fragment.clip.dashed": fragmentclipdashed, "fragment.clip.dotted": fragmentclipdotted, "fragment.clip.ends": fragmentclipends, "fragment.clip.proximity": fragmentclipproximity, "fragment.color": fragmentcolor, "fragment.map.rgba": fragmentmaprgba, "fragment.solid": fragmentsolid, "fragment.transparent": fragmenttransparent, "grid.position": gridposition, "grow.position": growposition, "join.position": joinposition, "label.alpha": labelalpha, "label.map": labelmap, "label.outline": labeloutline, "layer.position": layerposition, "lerp.depth": lerpdepth, "lerp.height": lerpheight, "lerp.items": lerpitems, "lerp.width": lerpwidth, "line.position": lineposition, "map.2d.data": map2ddata, "map.2d.data.wrap": map2ddatawrap, "map.xyzw.2dv": mapxyzw2dv, "map.xyzw.align": mapxyzwalign, "map.xyzw.texture": mapxyzwtexture, "mesh.fragment.color": meshfragmentcolor, "mesh.fragment.map": meshfragmentmap, "mesh.fragment.mask": meshfragmentmask, "mesh.fragment.material": meshfragmentmaterial, "mesh.fragment.shaded": meshfragmentshaded, "mesh.fragment.texture": meshfragmenttexture, "mesh.gamma.in": meshgammain, "mesh.gamma.out": meshgammaout, "mesh.map.uvwo": meshmapuvwo, "mesh.position": meshposition, "mesh.vertex.color": meshvertexcolor, "mesh.vertex.mask": meshvertexmask, "mesh.vertex.position": meshvertexposition, "move.position": moveposition, "object.mask.default": objectmaskdefault, "point.alpha.circle": pointalphacircle, "point.alpha.circle.hollow": pointalphacirclehollow, "point.alpha.generic": pointalphageneric, "point.alpha.generic.hollow": pointalphagenerichollow, "point.edge": pointedge, "point.fill": pointfill, "point.mask.circle": pointmaskcircle, "point.mask.diamond": pointmaskdiamond, "point.mask.down": pointmaskdown, "point.mask.left": pointmaskleft, "point.mask.right": pointmaskright, "point.mask.square": pointmasksquare, "point.mask.up": pointmaskup, "point.position": pointposition, "point.size.uniform": pointsizeuniform, "point.size.varying": pointsizevarying, "polar.position": polarposition, "project.position": projectposition, "project.readback": projectreadback, "raw.position.scale": rawpositionscale, "repeat.position": repeatposition, "resample.padding": resamplepadding, "resample.relative": resamplerelative, "reveal.mask": revealmask, "root.position": rootposition, "sample.2d": sample2d, "scale.position": scaleposition, "screen.map.stpq": screenmapstpq, "screen.map.xy": screenmapxy, "screen.map.xyzw": screenmapxyzw, "screen.pass.uv": screenpassuv, "screen.position": screenposition, "slice.position": sliceposition, "spherical.position": sphericalposition, "split.position": splitposition, "spread.position": spreadposition, "sprite.fragment": spritefragment, "sprite.position": spriteposition, "stereographic.position": stereographicposition, "stereographic4.position": stereographic4position, "stpq.sample.2d": stpqsample2d, "stpq.xyzw.2d": stpqxyzw2d, "strip.position.normal": strippositionnormal, "style.color": stylecolor, "subdivide.depth": subdividedepth, "subdivide.depth.lerp": subdividedepthlerp, "subdivide.height": subdivideheight, "subdivide.height.lerp": subdivideheightlerp, "subdivide.items": subdivideitems, "subdivide.items.lerp": subdivideitemslerp, "subdivide.width": subdividewidth, "subdivide.width.lerp": subdividewidthlerp, "surface.mask.hollow": surfacemaskhollow, "surface.position": surfaceposition, "surface.position.normal": surfacepositionnormal, "ticks.position": ticksposition, "transform3.position": transform3position, "transform4.position": transform4position, "view.position": viewposition, }; export * from "./factory.js";
cchudzicki/mathbox
src/shaders/index.js
JavaScript
mit
10,183
.mathbox-loader { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); padding: 10px; border-radius: 50%; background: #fff; } .mathbox-loader.mathbox-exit { opacity: 0; -webkit-transition: opacity 0.15s ease-in-out; transition: opacity 0.15s ease-in-out; } .mathbox-progress { height: 10px; border-radius: 5px; width: 80px; margin: 0 auto 20px; box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.2), 1px -1px 1px rgba(255, 255, 255, 0.2), -1px 1px 1px rgba(255, 255, 255, 0.2), -1px -1px 1px rgba(255, 255, 255, 0.2); background: #ccc; overflow: hidden; } .mathbox-progress > div { display: block; width: 0px; height: 10px; background: #888; } .mathbox-logo { position: relative; width: 140px; height: 100px; margin: 0 auto 10px; -webkit-perspective: 200px; perspective: 200px; } .mathbox-logo > div { position: absolute; left: 0; top: 0; bottom: 0; right: 0; -webkit-transform-style: preserve-3d; transform-style: preserve-3d; } .mathbox-logo > :nth-child(1) { -webkit-transform: rotateZ(22deg) rotateX(24deg) rotateY(30deg); transform: rotateZ(22deg) rotateX(24deg) rotateY(30deg); } .mathbox-logo > :nth-child(2) { -webkit-transform: rotateZ(11deg) rotateX(12deg) rotateY(15deg) scale3d(0.6, 0.6, 0.6); transform: rotateZ(11deg) rotateX(12deg) rotateY(15deg) scale3d(0.6, 0.6, 0.6); } .mathbox-logo > div > div { position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; width: 200px; height: 200px; box-sizing: border-box; border-radius: 50%; } .mathbox-logo > div > :nth-child(1) { -webkit-transform: scale(0.5, 0.5); transform: rotateX(30deg) scale(0.5, 0.5); } .mathbox-logo > div > :nth-child(2) { -webkit-transform: rotateX(90deg) scale(0.42, 0.42); transform: rotateX(90deg) scale(0.42, 0.42); } .mathbox-logo > div > :nth-child(3) { -webkit-transform: rotateY(90deg) scale(0.35, 0.35); transform: rotateY(90deg) scale(0.35, 0.35); } .mathbox-logo > :nth-child(1) > :nth-child(1) { border: 16px solid #808080; } .mathbox-logo > :nth-child(1) > :nth-child(2) { border: 19px solid #a0a0a0; } .mathbox-logo > :nth-child(1) > :nth-child(3) { border: 23px solid #c0c0c0; } .mathbox-logo > :nth-child(2) > :nth-child(1) { border: 27px solid #808080; } .mathbox-logo > :nth-child(2) > :nth-child(2) { border: 32px solid #a0a0a0; } .mathbox-logo > :nth-child(2) > :nth-child(3) { border: 38px solid #c0c0c0; } .mathbox-splash-blue .mathbox-progress { background: #def; } .mathbox-splash-blue .mathbox-progress > div { background: #1979e7; } .mathbox-splash-blue .mathbox-logo > :nth-child(1) > :nth-child(1) { border-color: #1979e7; } .mathbox-splash-blue .mathbox-logo > :nth-child(1) > :nth-child(2) { border-color: #33b0ff; } .mathbox-splash-blue .mathbox-logo > :nth-child(1) > :nth-child(3) { border-color: #75eaff; } .mathbox-splash-blue .mathbox-logo > :nth-child(2) > :nth-child(1) { border-color: #18487f; } .mathbox-splash-blue .mathbox-logo > :nth-child(2) > :nth-child(2) { border-color: #33b0ff; } .mathbox-splash-blue .mathbox-logo > :nth-child(2) > :nth-child(3) { border-color: #75eaff; }
cchudzicki/mathbox
src/splash.css
CSS
mit
3,251
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // Threestrap plugin import { Bootstrap } from "threestrap/src/bootstrap.js"; Bootstrap.registerPlugin("splash", { defaults: { color: "mono", fancy: true, }, listen: [ "ready", "mathbox/init:init", "mathbox/progress:progress", "mathbox/destroy:destroy", ], uninstall() { return this.destroy(); }, ready(event, three) { if (three.MathBox && !this.div) { // TODO woah seems wrong!!! return this.init(event, three); } }, init(event, three) { let div; this.destroy(); const { color } = this.options; const html = `\ <div class="mathbox-loader mathbox-splash-${color}"> <div class="mathbox-logo"> <div> <div></div><div></div><div></div> </div> <div> <div></div><div></div><div></div> </div> </div> <div class="mathbox-progress"><div></div></div> </div>\ `; this.div = div = document.createElement("div"); div.innerHTML = html; three.element.appendChild(div); const x = Math.random() * 2 - 1; const y = Math.random() * 2 - 1; const z = Math.random() * 2 - 1; const l = 1 / Math.sqrt(x * x + y * y + z * z); this.loader = div.querySelector(".mathbox-loader"); this.bar = div.querySelector(".mathbox-progress > div"); this.gyro = div.querySelectorAll(".mathbox-logo > div"); this.transforms = [ "rotateZ(22deg) rotateX(24deg) rotateY(30deg)", "rotateZ(11deg) rotateX(12deg) rotateY(15deg) scale3d(.6, .6, .6)", ]; this.random = [x * l, y * l, z * l]; this.start = three.Time.now; return (this.timer = null); }, // Update splash screen state and animation progress(event, three) { if (!this.div) { return; } const { current, total } = event; // Display splash screen const visible = current < total; clearTimeout(this.timer); if (visible) { this.loader.classList.remove("mathbox-exit"); this.loader.style.display = "block"; } else { this.loader.classList.add("mathbox-exit"); this.timer = setTimeout(() => { return (this.loader.style.display = "none"); }, 150); } // Update splash progress const width = current < total ? Math.round((1000 * current) / total) * 0.1 + "%" : "100%"; this.bar.style.width = width; if (this.options.fancy) { // Spinny gyros const weights = this.random; // Lerp clock speed const f = Math.max(0, Math.min(1, three.Time.now - this.start)); const increment = function (transform, j) { if (j == null) { j = 0; } return transform.replace( /(-?[0-9.e]+)deg/g, (_, n) => +n + weights[j++] * f * three.Time.step * 60 + "deg" ); }; return (() => { const result = []; for (let i = 0; i < this.gyro.length; i++) { let t; const el = this.gyro[i]; this.transforms[i] = t = increment(this.transforms[i]); result.push((el.style.transform = el.style.WebkitTransform = t)); } return result; })(); } }, destroy() { if (this.div != null) { this.div.remove(); } return (this.div = null); }, });
cchudzicki/mathbox
src/splash.js
JavaScript
mit
3,631
// 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 * 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"; export class Animator { constructor(context) { this.context = context; this.anims = []; } make(type, options) { const anim = new Animation(this, this.context.time, type, options); this.anims.push(anim); return anim; } unmake(anim) { return (this.anims = Array.from(this.anims).filter((a) => a !== anim)); } update() { const { time } = this.context; return (this.anims = (() => { const result = []; for (const anim of Array.from(this.anims)) { if (anim.update(time) !== false) { result.push(anim); } } return result; })()); } lerp(type, from, to, f, value) { if (value == null) { value = type.make(); } // Use the most appropriate interpolation method for the type // Direct lerp operator if (type.lerp) { value = type.lerp(from, to, value, f); // Substitute emitter } else if (type.emitter) { const fromE = from.emitterFrom; const toE = to.emitterTo; if (fromE != null && toE != null && fromE === toE) { fromE.lerp(f); return fromE; } else { const emitter = type.emitter(from, to); from.emitterFrom = emitter; to.emitterTo = emitter; emitter.lerp(f); return emitter; } // Generic binary operator } else if (type.op) { const lerp = function (a, b) { if (a === +a && b === +b) { // Lerp numbers return a + (b - a) * f; } else { // No lerp if (f > 0.5) { return b; } else { return a; } } }; value = type.op(from, to, value, lerp); // No lerp } else { value = f > 0.5 ? to : from; } return value; } } class Animation { constructor(animator, time, type, options) { this.animator = animator; this.time = time; this.type = type; this.options = options; this.value = this.type.make(); this.target = this.type.make(); this.queue = []; } dispose() { return this.animator.unmake(this); } set() { let { target } = this; let value = arguments.length > 1 ? [].slice.call(arguments) : arguments[0]; let invalid = false; value = this.type.validate(value, target, () => (invalid = true)); if (!invalid) { target = value; } this.cancel(); this.target = this.value; this.value = target; return this.notify(); } getTime() { const { clock } = this.options; const time = clock ? clock.getTime() : this.time; if (this.options.realtime) { return time.time; } else { return time.clock; } } cancel(from) { let stage; if (from == null) { from = this.getTime(); } const { queue } = this; const cancelled = (() => { const result = []; for (stage of Array.from(queue)) { if (stage.end >= from) { result.push(stage); } } return result; })(); this.queue = (() => { const result1 = []; for (stage of Array.from(queue)) { if (stage.end < from) { result1.push(stage); } } return result1; })(); for (stage of Array.from(cancelled)) { if (typeof stage.complete === "function") { stage.complete(false); } } if (typeof this.options.complete === "function") { this.options.complete(false); } } notify() { return typeof this.options.step === "function" ? this.options.step(this.value) : undefined; } immediate(value, options) { const { duration, delay, ease, step, complete } = options; const time = this.getTime(); const start = time + delay; const end = start + duration; let invalid = false; let target = this.type.make(); value = this.type.validate(value, target, function () { invalid = true; return null; }); if (value !== undefined && !invalid) { target = value; } this.cancel(start); return this.queue.push({ from: null, to: target, start, end, ease, step, complete, }); } update(time) { this.time = time; if (this.queue.length === 0) { return true; } const clock = this.getTime(); let { value } = this; const { queue } = this; let active = false; while (!active) { const stage = queue[0]; let { from } = stage; const { to, start, end, step, complete, ease } = stage; if (from == null) { from = stage.from = this.type.clone(this.value); } let f = Ease.clamp( (clock - start) / Math.max(0.00001, end - start) || 0, 0, 1 ); if (f === 0) { return; } // delayed animation not yet active const method = (() => { switch (ease) { case "linear": case 0: return null; 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; } })(); if (method != null) { f = method(f); } active = f < 1; value = active ? this.animator.lerp(this.type, from, to, f, value) : to; //console.log 'animation step', f, from, to, value if (typeof step === "function") { step(value); } if (!active) { if (typeof complete === "function") { complete(true); } if (typeof this.options.complete === "function") { this.options.complete(true); } queue.shift(); if (queue.length === 0) { break; } // end of queue } } this.value = value; return this.notify(); } }
cchudzicki/mathbox
src/stage/animator.js
JavaScript
mit
6,450
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as Pretty from "../util/pretty.js"; import * as ShaderGraph from "shadergraph"; export class API { v2() { return this; } constructor(_context, _up, _targets) { this._context = _context; this._up = _up; this._targets = _targets; const root = this._context.controller.getRoot(); if (this._targets == null) { this._targets = [root]; } this.isRoot = this._targets.length === 1 && this._targets[0] === root; this.isLeaf = this._targets.length === 1 && this._targets[0].children == null; // Look like an array for (let i = 0; i < this._targets.length; i++) { const t = this._targets[i]; this[i] = t; } this.length = this._targets.length; // Primitive factory. This is where all API methods are assigned. for (const type of Array.from(this._context.controller.getTypes())) { if (!["root"].includes(type)) { this[type] = (options, binds) => this.add(type, options, binds); } } } select(selector) { const targets = this._context.model.select( selector, !this.isRoot ? this._targets : null ); return this._push(targets); } eq(index) { if (this._targets.length > index) { return this._push([this._targets[index]]); } return this._push([]); } filter(callback) { if (typeof callback === "string") { const matcher = this._context.model._matcher(callback); callback = (x) => matcher(x); } return this._push(this._targets.filter(callback)); } map(callback) { return __range__(0, this.length, false).map((i) => callback(this[i], i, this) ); } each(callback) { for ( let i = 0, end = this.length, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { callback(this[i], i, this); } return this; } add(type, options, binds) { // Make node/primitive const { controller } = this._context; // Auto-pop if targeting leaf if (this.isLeaf) { return this._pop().add(type, options, binds); } // Add to target const nodes = []; for (const target of this._targets) { const node = controller.make(type, options, binds); controller.add(node, target); nodes.push(node); } // Return changed selection return this._push(nodes); } remove(selector) { if (selector) { return this.select(selector).remove(); } for (const target of Array.from(this._targets.slice().reverse())) { this._context.controller.remove(target); } return this._pop(); } set(key, value) { for (const target of Array.from(this._targets)) { this._context.controller.set(target, key, value); } return this; } getAll(key) { return Array.from(this._targets).map((target) => this._context.controller.get(target, key) ); } get(key) { return this._targets[0] != null ? this._targets[0].get(key) : undefined; } evaluate(key, time) { return this._targets[0] != null ? this._targets[0].evaluate(key, time) : undefined; } bind(key, value) { for (const target of Array.from(this._targets)) { this._context.controller.bind(target, key, value); } return this; } unbind(key) { for (const target of Array.from(this._targets)) { this._context.controller.unbind(target, key); } return this; } end() { return (this.isLeaf ? this._pop() : this)._pop(); } _push(targets) { return new API(this._context, this, targets); } _pop() { return this._up != null ? this._up : this; } _reset() { let left; return (left = this._up != null ? this._up.reset() : undefined) != null ? left : this; } // TODO is this okay?? // eslint-disable-next-line no-dupe-class-members map(callback) { return this._targets.map(callback); } on() { const args = arguments; this._targets.map((x) => x.on.apply(x, args)); return this; } off() { const args = arguments; this._targets.map((x) => x.off.apply(x, args)); return this; } toString() { const tags = this._targets.map((x) => x.toString()); if (this._targets.length > 1) { return `[${tags.join(", ")}]`; } else { return tags[0]; } } toMarkup() { const tags = this._targets.map((x) => x.toMarkup()); return tags.join("\n\n"); } print() { Pretty.print(this._targets.map((x) => x.toMarkup()).join("\n\n")); return this; } debug() { const info = this.inspect(); console.log("Renderables: ", info.renderables); console.log("Renders: ", info.renders); console.log("Shaders: ", info.shaders); const getName = (owner) => owner.constructor.toString().match("function +([^(]*)")[1]; const shaders = []; for (const shader of Array.from(info.shaders)) { const name = getName(shader.owner); shaders.push(`${name} - Vertex`); shaders.push(shader.vertex); shaders.push(`${name} - Fragment`); shaders.push(shader.fragment); } return ShaderGraph.inspect(shaders); } inspect(selector, trait, print) { let self; if (typeof trait === "boolean") { print = trait; trait = null; } if (print == null) { print = true; } // Recurse tree and extract all inserted renderables const map = (node) => (node.controller != null ? node.controller.objects : undefined) != null ? node.controller != null ? node.controller.objects : undefined : []; const recurse = (self = function (node, list) { if (list == null) { list = []; } if (!trait || node.traits.hash[trait]) { list.push(map(node)); } if (node.children != null) { for (const child of Array.from(node.children)) { self(child, list); } } return list; }); // Flatten arrays const flatten = function (list) { list = list.reduce((a, b) => a.concat(b), []); return (list = list.filter((x, i) => x != null && list.indexOf(x) === i)); }; // Render descriptor const make = function (renderable, render) { const d = {}; d.owner = renderable; d.geometry = render.geometry; d.material = render.material; d.vertex = render.userData.vertexGraph; d.fragment = render.userData.fragmentGraph; return d; }; const info = { nodes: this._targets.slice(), renderables: [], renders: [], shaders: [], }; // Inspect all targets for (const target of Array.from(this._targets)) { let renderables; if (print) { target.print(selector, "info"); } const _info = { renderables: (renderables = flatten(recurse(target))), renders: flatten(renderables.map((x) => x.renders)), shaders: flatten( renderables.map((x) => x.renders != null ? x.renders.map((r) => make(x, r)) : undefined ) ), }; for (const k in _info) { info[k] = info[k].concat(_info[k]); } } return info; } } 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/stage/api.js
JavaScript
mit
7,954
// 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 Controller { constructor(model, primitives) { this.model = model; this.primitives = primitives; } getRoot() { return this.model.getRoot(); } getTypes() { return this.primitives.getTypes(); } make(type, options, binds) { return this.primitives.make(type, options, binds); } get(node, key) { return node.get(key); } set(node, key, value) { try { return node.set(key, value); } catch (e) { node.print(null, "warn"); return console.error(e); } } bind(node, key, expr) { try { return node.bind(key, expr); } catch (e) { node.print(null, "warn"); return console.error(e); } } unbind(node, key) { try { return node.unbind(key); } catch (e) { node.print(null, "warn"); return console.error(e); } } add(node, target) { if (target == null) { target = this.model.getRoot(); } return target.add(node); } remove(node) { const target = node.parent; if (target) { return target.remove(node); } } }
cchudzicki/mathbox
src/stage/controller.js
JavaScript
mit
1,455
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. export * from "./animator.js"; export * from "./api.js"; export * from "./controller.js";
cchudzicki/mathbox
src/stage/index.js
JavaScript
mit
199
import type * as TT from "./node_types"; import type { Alignments, Axes, AxesWithZero, BlendingModes, Optional, } from "./primitives/types/types_typed"; export * from "./node_types"; export type { Alignments, Axes, AxesWithZero, BlendingModes, Optional }; export type Props = { area: TT.AreaProps; array: TT.ArrayProps; axis: TT.AxisProps; camera: TT.CameraProps; cartesian: TT.CartesianProps; cartesian4: TT.Cartesian4Props; clamp: TT.ClampProps; clock: TT.ClockProps; compose: TT.ComposeProps; dom: TT.DomProps; face: TT.FaceProps; format: TT.FormatProps; fragment: TT.FragmentProps; grid: TT.GridProps; group: TT.GroupProps; grow: TT.GrowProps; html: TT.HtmlProps; inherit: TT.InheritProps; interval: TT.IntervalProps; join: TT.JoinProps; label: TT.LabelProps; layer: TT.LayerProps; lerp: TT.LerpProps; line: TT.LineProps; mask: TT.MaskProps; matrix: TT.MatrixProps; memo: TT.MemoProps; move: TT.MoveProps; now: TT.NowProps; play: TT.PlayProps; point: TT.PointProps; polar: TT.PolarProps; present: TT.PresentProps; readback: TT.ReadbackProps; repeat: TT.RepeatProps; resample: TT.ResampleProps; retext: TT.RetextProps; reveal: TT.RevealProps; root: TT.RootProps; rtt: TT.RttProps; scale: TT.ScaleProps; shader: TT.ShaderProps; slice: TT.SliceProps; slide: TT.SlideProps; spherical: TT.SphericalProps; split: TT.SplitProps; spread: TT.SpreadProps; step: TT.StepProps; stereographic: TT.StereographicProps; stereographic4: TT.Stereographic4Props; strip: TT.StripProps; subdivide: TT.SubdivideProps; surface: TT.SurfaceProps; swizzle: TT.SwizzleProps; text: TT.TextProps; ticks: TT.TicksProps; transform: TT.TransformProps; transform4: TT.Transform4Props; transpose: TT.TransposeProps; unit: TT.UnitProps; vector: TT.VectorProps; vertex: TT.VertexProps; view: TT.ViewProps; volume: TT.VolumeProps; voxel: TT.VoxelProps; }; export type PropsNoramlized = { area: TT.AreaPropsNormalized; array: TT.ArrayPropsNormalized; axis: TT.AxisPropsNormalized; camera: TT.CameraPropsNormalized; cartesian: TT.CartesianPropsNormalized; cartesian4: TT.Cartesian4PropsNormalized; clamp: TT.ClampPropsNormalized; clock: TT.ClockPropsNormalized; compose: TT.ComposePropsNormalized; dom: TT.DomPropsNormalized; face: TT.FacePropsNormalized; format: TT.FormatPropsNormalized; fragment: TT.FragmentPropsNormalized; grid: TT.GridPropsNormalized; group: TT.GroupPropsNormalized; grow: TT.GrowPropsNormalized; html: TT.HtmlPropsNormalized; inherit: TT.InheritPropsNormalized; interval: TT.IntervalPropsNormalized; join: TT.JoinPropsNormalized; label: TT.LabelPropsNormalized; layer: TT.LayerPropsNormalized; lerp: TT.LerpPropsNormalized; line: TT.LinePropsNormalized; mask: TT.MaskPropsNormalized; matrix: TT.MatrixPropsNormalized; memo: TT.MemoPropsNormalized; move: TT.MovePropsNormalized; now: TT.NowPropsNormalized; play: TT.PlayPropsNormalized; point: TT.PointPropsNormalized; polar: TT.PolarPropsNormalized; present: TT.PresentPropsNormalized; readback: TT.ReadbackPropsNormalized; repeat: TT.RepeatPropsNormalized; resample: TT.ResamplePropsNormalized; retext: TT.RetextPropsNormalized; reveal: TT.RevealPropsNormalized; root: TT.RootPropsNormalized; rtt: TT.RttPropsNormalized; scale: TT.ScalePropsNormalized; shader: TT.ShaderPropsNormalized; slice: TT.SlicePropsNormalized; slide: TT.SlidePropsNormalized; spherical: TT.SphericalPropsNormalized; split: TT.SplitPropsNormalized; spread: TT.SpreadPropsNormalized; step: TT.StepPropsNormalized; stereographic: TT.StereographicPropsNormalized; stereographic4: TT.Stereographic4PropsNormalized; strip: TT.StripPropsNormalized; subdivide: TT.SubdividePropsNormalized; surface: TT.SurfacePropsNormalized; swizzle: TT.SwizzlePropsNormalized; text: TT.TextPropsNormalized; ticks: TT.TicksPropsNormalized; transform: TT.TransformPropsNormalized; transform4: TT.Transform4PropsNormalized; transpose: TT.TransposePropsNormalized; unit: TT.UnitPropsNormalized; vector: TT.VectorPropsNormalized; vertex: TT.VertexPropsNormalized; view: TT.ViewPropsNormalized; volume: TT.VolumePropsNormalized; voxel: TT.VoxelPropsNormalized; }; export type NodeType = keyof Props; /** * MathBox (virtual)-DOM Nodes. * * Usually one interacts with these via a selection. */ export interface MathboxNode<T extends NodeType = NodeType> { type: string; props: PropsNoramlized[T]; } /** * @typeParam Type The type(s) of MathBox nodes in this selection. */ export interface MathboxSelection<Type extends NodeType> { /** * Set properties on all nodes in this selection. */ set(props: Props[Type]): MathboxSelection<Type>; /** * Set a single property on all nodes in this selection */ set<P extends keyof Props[Type]>( prop: P, value: Props[Type][P] ): MathboxSelection<Type>; /** * Return all props for the first node in this node. */ get(): PropsNoramlized[Type]; /** * Retrieve a specific property value for the first node in this selection. */ get<P extends keyof PropsNoramlized[Type]>(prop: P): PropsNoramlized[Type][P]; /** * Return an array of props for all nodes in this node. */ getAll(): PropsNoramlized[Type][]; remove: () => void; print: () => MathboxSelection<Type>; select: (query: string) => MathboxSelection<NodeType>; /** * Print (in the console) the DOM nodes in this selection. * Called automatically on first load. */ inspect(): void; /** Display a visual representation of all shader snippets, how they are wired, with the GLSL available on mouseover. */ debug(): void; [index: number]: MathboxNode<Type>; /** * The number of nodes contained in this selection. */ length: number; /** * Iterate over a selection's nodes in document order and discard the return * values. Returns the original selection. */ each( cb: ( node: MathboxNode<Type>, i?: number, selection?: MathboxSelection<Type> ) => void ): MathboxSelection<Type>; /** * Iterate over a selection's nodes in document order and return the resulting * values as an array. * */ map<S>( cb: ( node: MathboxNode<Type>, i?: number, selection?: MathboxSelection<Type> ) => S ): S[]; /** * Return the ith node in this selection, indexed from 0. */ eq(i: number): MathboxSelection<Type>; // creation methods /** * Create new `area` node. * * See also {@link AreaProps} and {@link AreaPropsNormalized}. * * @category data */ area(props?: TT.AreaProps): MathboxSelection<"area">; /** * Create new `array` node. * * See also {@link ArrayProps} and {@link ArrayPropsNormalized}. * * @category data */ array(props?: TT.ArrayProps): MathboxSelection<"array">; /** * Create new `axis` node. * * See also {@link AxisProps} and {@link AxisPropsNormalized}. * * @category draw */ axis(props?: TT.AxisProps): MathboxSelection<"axis">; /** * Create new `camera` node. * * See also {@link CameraProps} and {@link CameraPropsNormalized}. * * @category camera */ camera(props?: TT.CameraProps): MathboxSelection<"camera">; /** * Create new `cartesian` node. * * See also {@link CartesianProps} and {@link CartesianPropsNormalized}. * * @category view */ cartesian(props?: TT.CartesianProps): MathboxSelection<"cartesian">; /** * Create new `cartesian4` node. * * See also {@link Cartesian4Props} and {@link Cartesian4PropsNormalized}. * * @category view */ cartesian4(props?: TT.Cartesian4Props): MathboxSelection<"cartesian4">; /** * Create new `clamp` node. * * See also {@link ClampProps} and {@link ClampPropsNormalized}. * * @category operator */ clamp(props?: TT.ClampProps): MathboxSelection<"clamp">; /** * Create new `clock` node. * * See also {@link ClockProps} and {@link ClockPropsNormalized}. * * @category time */ clock(props?: TT.ClockProps): MathboxSelection<"clock">; /** * Create new `compose` node. * * See also {@link ComposeProps} and {@link ComposePropsNormalized}. * * @category rtt */ compose(props?: TT.ComposeProps): MathboxSelection<"compose">; /** * Create new `dom` node. * * See also {@link DomProps} and {@link DomPropsNormalized}. * * @category overlay */ dom(props?: TT.DomProps): MathboxSelection<"dom">; /** * Create new `face` node. * * See also {@link FaceProps} and {@link FacePropsNormalized}. * * @category draw */ face(props?: TT.FaceProps): MathboxSelection<"face">; /** * Create new `format` node. * * See also {@link FormatProps} and {@link FormatPropsNormalized}. * * @category text */ format(props?: TT.FormatProps): MathboxSelection<"format">; /** * Create new `fragment` node. * * See also {@link FragmentProps} and {@link FragmentPropsNormalized}. * * @category transform */ fragment(props?: TT.FragmentProps): MathboxSelection<"fragment">; /** * Create new `grid` node. * * See also {@link GridProps} and {@link GridPropsNormalized}. * * @category draw */ grid(props?: TT.GridProps): MathboxSelection<"grid">; /** * Create new `group` node. * * See also {@link GroupProps} and {@link GroupPropsNormalized}. * * @category base */ group(props?: TT.GroupProps): MathboxSelection<"group">; /** * Create new `grow` node. * * See also {@link GrowProps} and {@link GrowPropsNormalized}. * * @category operator */ grow(props?: TT.GrowProps): MathboxSelection<"grow">; /** * Create new `html` node. * * See also {@link HtmlProps} and {@link HtmlPropsNormalized}. * * @category overlay */ html(props?: TT.HtmlProps): MathboxSelection<"html">; /** * Create new `inherit` node. * * See also {@link InheritProps} and {@link InheritPropsNormalized}. * * @category base */ inherit(props?: TT.InheritProps): MathboxSelection<"inherit">; /** * Create new `interval` node. * * See also {@link IntervalProps} and {@link IntervalPropsNormalized}. * * @category data */ interval(props?: TT.IntervalProps): MathboxSelection<"interval">; /** * Create new `join` node. * * See also {@link JoinProps} and {@link JoinPropsNormalized}. * * @category operator */ join(props?: TT.JoinProps): MathboxSelection<"join">; /** * Create new `label` node. * * See also {@link LabelProps} and {@link LabelPropsNormalized}. * * @category text */ label(props?: TT.LabelProps): MathboxSelection<"label">; /** * Create new `layer` node. * * See also {@link LayerProps} and {@link LayerPropsNormalized}. * * @category transform */ layer(props?: TT.LayerProps): MathboxSelection<"layer">; /** * Create new `lerp` node. * * See also {@link LerpProps} and {@link LerpPropsNormalized}. * * @category operator */ lerp(props?: TT.LerpProps): MathboxSelection<"lerp">; /** * Create new `line` node. * * See also {@link LineProps} and {@link LinePropsNormalized}. * * @category draw */ line(props?: TT.LineProps): MathboxSelection<"line">; /** * Create new `mask` node. * * See also {@link MaskProps} and {@link MaskPropsNormalized}. * * @category transform */ mask(props?: TT.MaskProps): MathboxSelection<"mask">; /** * Create new `matrix` node. * * See also {@link MatrixProps} and {@link MatrixPropsNormalized}. * * @category data */ matrix(props?: TT.MatrixProps): MathboxSelection<"matrix">; /** * Create new `memo` node. * * See also {@link MemoProps} and {@link MemoPropsNormalized}. * * @category operator */ memo(props?: TT.MemoProps): MathboxSelection<"memo">; /** * Create new `move` node. * * See also {@link MoveProps} and {@link MovePropsNormalized}. * * @category present */ move(props?: TT.MoveProps): MathboxSelection<"move">; /** * Create new `now` node. * * See also {@link NowProps} and {@link NowPropsNormalized}. * * @category time */ now(props?: TT.NowProps): MathboxSelection<"now">; /** * Create new `play` node. * * See also {@link PlayProps} and {@link PlayPropsNormalized}. * * @category present */ play(props?: TT.PlayProps): MathboxSelection<"play">; /** * Create new `point` node. * * See also {@link PointProps} and {@link PointPropsNormalized}. * * @category draw */ point(props?: TT.PointProps): MathboxSelection<"point">; /** * Create new `polar` node. * * See also {@link PolarProps} and {@link PolarPropsNormalized}. * * @category view */ polar(props?: TT.PolarProps): MathboxSelection<"polar">; /** * Create new `present` node. * * See also {@link PresentProps} and {@link PresentPropsNormalized}. * * @category present */ present(props?: TT.PresentProps): MathboxSelection<"present">; /** * Create new `readback` node. * * See also {@link ReadbackProps} and {@link ReadbackPropsNormalized}. * * @category operator */ readback(props?: TT.ReadbackProps): MathboxSelection<"readback">; /** * Create new `repeat` node. * * See also {@link RepeatProps} and {@link RepeatPropsNormalized}. * * @category operator */ repeat(props?: TT.RepeatProps): MathboxSelection<"repeat">; /** * Create new `resample` node. * * See also {@link ResampleProps} and {@link ResamplePropsNormalized}. * * @category operator */ resample(props?: TT.ResampleProps): MathboxSelection<"resample">; /** * Create new `retext` node. * * See also {@link RetextProps} and {@link RetextPropsNormalized}. * * @category text */ retext(props?: TT.RetextProps): MathboxSelection<"retext">; /** * Create new `reveal` node. * * See also {@link RevealProps} and {@link RevealPropsNormalized}. * * @category present */ reveal(props?: TT.RevealProps): MathboxSelection<"reveal">; /** * Create new `root` node. * * See also {@link RootProps} and {@link RootPropsNormalized}. * * @category base */ root(props?: TT.RootProps): MathboxSelection<"root">; /** * Create new `rtt` node. * * See also {@link RttProps} and {@link RttPropsNormalized}. * * @category rtt */ rtt(props?: TT.RttProps): MathboxSelection<"rtt">; /** * Create new `scale` node. * * See also {@link ScaleProps} and {@link ScalePropsNormalized}. * * @category data */ scale(props?: TT.ScaleProps): MathboxSelection<"scale">; /** * Create new `shader` node. * * See also {@link ShaderProps} and {@link ShaderPropsNormalized}. * * @category shader */ shader(props?: TT.ShaderProps): MathboxSelection<"shader">; /** * Create new `slice` node. * * See also {@link SliceProps} and {@link SlicePropsNormalized}. * * @category operator */ slice(props?: TT.SliceProps): MathboxSelection<"slice">; /** * Create new `slide` node. * * See also {@link SlideProps} and {@link SlidePropsNormalized}. * * @category present */ slide(props?: TT.SlideProps): MathboxSelection<"slide">; /** * Create new `spherical` node. * * See also {@link SphericalProps} and {@link SphericalPropsNormalized}. * * @category view */ spherical(props?: TT.SphericalProps): MathboxSelection<"spherical">; /** * Create new `split` node. * * See also {@link SplitProps} and {@link SplitPropsNormalized}. * * @category operator */ split(props?: TT.SplitProps): MathboxSelection<"split">; /** * Create new `spread` node. * * See also {@link SpreadProps} and {@link SpreadPropsNormalized}. * * @category operator */ spread(props?: TT.SpreadProps): MathboxSelection<"spread">; /** * Create new `step` node. * * See also {@link StepProps} and {@link StepPropsNormalized}. * * @category present */ step(props?: TT.StepProps): MathboxSelection<"step">; /** * Create new `stereographic` node. * * See also {@link StereographicProps} and {@link StereographicPropsNormalized}. * * @category view */ stereographic( props?: TT.StereographicProps ): MathboxSelection<"stereographic">; /** * Create new `stereographic4` node. * * See also {@link Stereographic4Props} and {@link Stereographic4PropsNormalized}. * * @category view */ stereographic4( props?: TT.Stereographic4Props ): MathboxSelection<"stereographic4">; /** * Create new `strip` node. * * See also {@link StripProps} and {@link StripPropsNormalized}. * * @category draw */ strip(props?: TT.StripProps): MathboxSelection<"strip">; /** * Create new `subdivide` node. * * See also {@link SubdivideProps} and {@link SubdividePropsNormalized}. * * @category operator */ subdivide(props?: TT.SubdivideProps): MathboxSelection<"subdivide">; /** * Create new `surface` node. * * See also {@link SurfaceProps} and {@link SurfacePropsNormalized}. * * @category draw */ surface(props?: TT.SurfaceProps): MathboxSelection<"surface">; /** * Create new `swizzle` node. * * See also {@link SwizzleProps} and {@link SwizzlePropsNormalized}. * * @category operator */ swizzle(props?: TT.SwizzleProps): MathboxSelection<"swizzle">; /** * Create new `text` node. * * See also {@link TextProps} and {@link TextPropsNormalized}. * * @category text */ text(props?: TT.TextProps): MathboxSelection<"text">; /** * Create new `ticks` node. * * See also {@link TicksProps} and {@link TicksPropsNormalized}. * * @category draw */ ticks(props?: TT.TicksProps): MathboxSelection<"ticks">; /** * Create new `transform` node. * * See also {@link TransformProps} and {@link TransformPropsNormalized}. * * @category transform */ transform(props?: TT.TransformProps): MathboxSelection<"transform">; /** * Create new `transform4` node. * * See also {@link Transform4Props} and {@link Transform4PropsNormalized}. * * @category transform */ transform4(props?: TT.Transform4Props): MathboxSelection<"transform4">; /** * Create new `transpose` node. * * See also {@link TransposeProps} and {@link TransposePropsNormalized}. * * @category operator */ transpose(props?: TT.TransposeProps): MathboxSelection<"transpose">; /** * Create new `unit` node. * * See also {@link UnitProps} and {@link UnitPropsNormalized}. * * @category base */ unit(props?: TT.UnitProps): MathboxSelection<"unit">; /** * Create new `vector` node. * * See also {@link VectorProps} and {@link VectorPropsNormalized}. * * @category draw */ vector(props?: TT.VectorProps): MathboxSelection<"vector">; /** * Create new `vertex` node. * * See also {@link VertexProps} and {@link VertexPropsNormalized}. * * @category transform */ vertex(props?: TT.VertexProps): MathboxSelection<"vertex">; /** * Create new `view` node. * * See also {@link ViewProps} and {@link ViewPropsNormalized}. * * @category view */ view(props?: TT.ViewProps): MathboxSelection<"view">; /** * Create new `volume` node. * * See also {@link VolumeProps} and {@link VolumePropsNormalized}. * * @category data */ volume(props?: TT.VolumeProps): MathboxSelection<"volume">; /** * Create new `voxel` node. * * See also {@link VoxelProps} and {@link VoxelPropsNormalized}. * * @category data */ voxel(props?: TT.VoxelProps): MathboxSelection<"voxel">; } export declare function mathBox(opts?: any): MathboxSelection<"root">; export declare type AreaProps = TT.AreaProps;
cchudzicki/mathbox
src/types.ts
TypeScript
mit
20,015
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Vector4 } from "three/src/math/Vector4.js"; export const setOrigin = function (vec, dimensions, origin) { if (+dimensions === dimensions) { dimensions = [dimensions]; } const x = Array.from(dimensions).includes(1) ? 0 : origin.x; const y = Array.from(dimensions).includes(2) ? 0 : origin.y; const z = Array.from(dimensions).includes(3) ? 0 : origin.z; const w = Array.from(dimensions).includes(4) ? 0 : origin.w; return vec.set(x, y, z, w); }; export const addOrigin = (function () { const v = new Vector4(); return function (vec, dimension, origin) { setOrigin(v, dimension, origin); return vec.add(v); }; })(); export const setDimension = function (vec, dimension) { const x = dimension === 1 ? 1 : 0; const y = dimension === 2 ? 1 : 0; const z = dimension === 3 ? 1 : 0; const w = dimension === 4 ? 1 : 0; return vec.set(x, y, z, w); }; export const setDimensionNormal = function (vec, dimension) { const x = dimension === 1 ? 1 : 0; const y = dimension === 2 ? 1 : 0; const z = dimension === 3 ? 1 : 0; const w = dimension === 4 ? 1 : 0; return vec.set(y, z + x, w, 0); }; export const recenterAxis = (function () { const axis = [0, 0]; return function (x, dx, bend, f) { if (f == null) { f = 0; } if (bend > 0) { const x1 = x; const x2 = x + dx; const abs = Math.max(Math.abs(x1), Math.abs(x2)); const fabs = abs * f; const min = Math.min(x1, x2); const max = Math.max(x1, x2); x = min + (-abs + fabs - min) * bend; dx = max + (abs + fabs - max) * bend - x; } axis[0] = x; axis[1] = dx; return axis; }; })();
cchudzicki/mathbox
src/util/axis.js
JavaScript
mit
2,079
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ export const getSizes = function (data) { const sizes = []; let array = data; while ( typeof array !== "string" && (array != null ? array.length : undefined) != null ) { sizes.push(array.length); array = array[0]; } return sizes; }; export const getDimensions = function (data, spec) { let left; if (spec == null) { spec = {}; } const { items, channels, width, height, depth } = spec; const dims = {}; if (!data || !data.length) { return { items, channels, width: width != null ? width : 0, height: height != null ? height : 0, depth: depth != null ? depth : 0, }; } const sizes = getSizes(data); const nesting = sizes.length; dims.channels = channels !== 1 && sizes.length > 1 ? sizes.pop() : channels; dims.items = items !== 1 && sizes.length > 1 ? sizes.pop() : items; dims.width = width !== 1 && sizes.length > 1 ? sizes.pop() : width; dims.height = height !== 1 && sizes.length > 1 ? sizes.pop() : height; dims.depth = depth !== 1 && sizes.length > 1 ? sizes.pop() : depth; let levels = nesting; if (channels === 1) { levels++; } if (items === 1 && levels > 1) { levels++; } if (width === 1 && levels > 2) { levels++; } if (height === 1 && levels > 3) { levels++; } let n = (left = sizes.pop()) != null ? left : 1; if (levels <= 1) { n /= dims.channels != null ? dims.channels : 1; } if (levels <= 2) { n /= dims.items != null ? dims.items : 1; } if (levels <= 3) { n /= dims.width != null ? dims.width : 1; } if (levels <= 4) { n /= dims.height != null ? dims.height : 1; } n = Math.floor(n); if (dims.width == null) { dims.width = n; n = 1; } if (dims.height == null) { dims.height = n; n = 1; } if (dims.depth == null) { dims.depth = n; n = 1; } return dims; }; export const repeatCall = function (call, times) { switch (times) { case 0: return () => true; case 1: return () => call(); case 2: return function () { call(); return call(); }; case 3: return function () { call(); call(); call(); return call(); }; case 4: return function () { call(); call(); call(); return call(); }; case 6: return function () { call(); call(); call(); call(); call(); return call(); }; case 8: return function () { call(); call(); call(); call(); call(); return call(); }; } }; export const makeEmitter = function (thunk, items, channels) { let outer; const inner = (() => { switch (channels) { case 0: return () => true; case 1: return (emit) => emit(thunk()); case 2: return (emit) => emit(thunk(), thunk()); case 3: return (emit) => emit(thunk(), thunk(), thunk()); case 4: return (emit) => emit(thunk(), thunk(), thunk(), thunk()); case 6: return (emit) => emit(thunk(), thunk(), thunk(), thunk(), thunk(), thunk()); case 8: return (emit) => emit( thunk(), thunk(), thunk(), thunk(), thunk(), thunk(), thunk(), thunk() ); } })(); let next = null; while (items > 0) { const n = Math.min(items, 8); outer = (() => { switch (n) { case 1: return (emit) => inner(emit); case 2: return function (emit) { inner(emit); return inner(emit); }; case 3: return function (emit) { inner(emit); inner(emit); return inner(emit); }; case 4: return function (emit) { inner(emit); inner(emit); inner(emit); return inner(emit); }; case 5: return function (emit) { inner(emit); inner(emit); inner(emit); inner(emit); return inner(emit); }; case 6: return function (emit) { inner(emit); inner(emit); inner(emit); inner(emit); inner(emit); return inner(emit); }; case 7: return function (emit) { inner(emit); inner(emit); inner(emit); inner(emit); inner(emit); inner(emit); return inner(emit); }; case 8: return function (emit) { inner(emit); inner(emit); inner(emit); inner(emit); inner(emit); inner(emit); inner(emit); return inner(emit); }; } })(); if (next != null) { next = ((outer, next) => function (emit) { outer(emit); return next(emit); })(outer, next); } else { next = outer; } items -= n; } outer = next != null ? next : () => true; outer.reset = thunk.reset; outer.rebind = thunk.rebind; return outer; }; export const getThunk = function (data) { let thunk; let j, k, l, m; let sizes = getSizes(data); const nesting = sizes.length; let a = sizes.pop(); let b = sizes.pop(); let c = sizes.pop(); const d = sizes.pop(); let i, first, second, third, fourth; switch (nesting) { case 0: thunk = () => 0; thunk.reset = function () {}; break; case 1: i = 0; thunk = () => data[i++]; thunk.reset = () => (i = 0); break; case 2: i = j = 0; first = data[j] != null ? data[j] : []; thunk = function () { const x = first[i++]; if (i === a) { i = 0; j++; first = data[j] != null ? data[j] : []; } return x; }; thunk.reset = function () { i = j = 0; first = data[j] != null ? data[j] : []; }; break; case 3: i = j = k = 0; second = data[k] != null ? data[k] : []; first = second[j] != null ? second[j] : []; thunk = function () { const x = first[i++]; if (i === a) { i = 0; j++; if (j === b) { j = 0; k++; second = data[k] != null ? data[k] : []; } first = second[j] != null ? second[j] : []; } return x; }; thunk.reset = function () { i = j = k = 0; second = data[k] != null ? data[k] : []; first = second[j] != null ? second[j] : []; }; break; case 4: i = j = k = l = 0; third = data[l] != null ? data[l] : []; second = third[k] != null ? third[k] : []; first = second[j] != null ? second[j] : []; thunk = function () { const x = first[i++]; if (i === a) { i = 0; j++; if (j === b) { j = 0; k++; if (k === c) { k = 0; l++; third = data[l] != null ? data[l] : []; } second = third[k] != null ? third[k] : []; } first = second[j] != null ? second[j] : []; } return x; }; thunk.reset = function () { i = j = k = l = 0; third = data[l] != null ? data[l] : []; second = third[k] != null ? third[k] : []; first = second[j] != null ? second[j] : []; }; break; case 5: i = j = k = l = m = 0; fourth = data[m] != null ? data[m] : []; third = fourth[l] != null ? fourth[l] : []; second = third[k] != null ? third[k] : []; first = second[j] != null ? second[j] : []; thunk = function () { const x = first[i++]; if (i === a) { i = 0; j++; if (j === b) { j = 0; k++; if (k === c) { k = 0; l++; if (l === d) { l = 0; m++; fourth = data[m] != null ? data[m] : []; } third = fourth[l] != null ? fourth[l] : []; } second = third[k] != null ? third[k] : []; } first = second[j] != null ? second[j] : []; } return x; }; thunk.reset = function () { i = j = k = l = m = 0; fourth = data[m] != null ? data[m] : []; third = fourth[l] != null ? fourth[l] : []; second = third[k] != null ? third[k] : []; first = second[j] != null ? second[j] : []; }; break; } thunk.rebind = function (d) { data = d; sizes = getSizes(data); if (sizes.length) { a = sizes.pop(); } if (sizes.length) { b = sizes.pop(); } if (sizes.length) { c = sizes.pop(); } if (sizes.length) { return (d = sizes.pop()); } }; return thunk; }; export const getStreamer = function (array, samples, channels, items) { let i, j; let limit = (i = j = 0); const reset = function () { limit = samples * channels * items; return (i = j = 0); }; const count = () => j; const done = () => limit - i <= 0; const skip = (() => { switch (channels) { case 1: return function (n) { i += n; j += n; }; case 2: return function (n) { i += n * 2; j += n; }; case 3: return function (n) { i += n * 3; j += n; }; case 4: return function (n) { i += n * 4; j += n; }; } })(); const consume = (() => { switch (channels) { case 1: return function (emit) { emit(array[i++]); ++j; }; case 2: return function (emit) { emit(array[i++], array[i++]); ++j; }; case 3: return function (emit) { emit(array[i++], array[i++], array[i++]); ++j; }; case 4: return function (emit) { emit(array[i++], array[i++], array[i++], array[i++]); ++j; }; } })(); const emit = (() => { switch (channels) { case 1: return function (x) { array[i++] = x; ++j; }; case 2: return function (x, y) { array[i++] = x; array[i++] = y; ++j; }; case 3: return function (x, y, z) { array[i++] = x; array[i++] = y; array[i++] = z; ++j; }; case 4: return function (x, y, z, w) { array[i++] = x; array[i++] = y; array[i++] = z; array[i++] = w; ++j; }; } })(); consume.reset = reset; emit.reset = reset; reset(); return { emit, consume, skip, count, done, reset }; }; export const getLerpEmitter = function (expr1, expr2) { let emitter, lerp2, q, r, s; const scratch = new Float32Array(4096); let lerp1 = (lerp2 = 0.5); let p = (q = r = s = 0); const emit1 = function (x, y, z, w) { r++; scratch[p++] = x * lerp1; scratch[p++] = y * lerp1; scratch[p++] = z * lerp1; return (scratch[p++] = w * lerp1); }; const emit2 = function (x, y, z, w) { s++; scratch[q++] += x * lerp2; scratch[q++] += y * lerp2; scratch[q++] += z * lerp2; return (scratch[q++] += w * lerp2); }; const args = Math.max(expr1.length, expr2.length); if (args <= 3) { emitter = function (emit, x, i) { p = q = r = s = 0; expr1(emit1, x, i); expr2(emit2, x, i); const n = Math.min(r, s); let l = 0; return __range__(0, n, false).map((_k) => emit(scratch[l++], scratch[l++], scratch[l++], scratch[l++]) ); }; } else if (args <= 5) { emitter = function (emit, x, y, i, j) { p = q = r = s = 0; expr1(emit1, x, y, i, j); expr2(emit2, x, y, i, j); const n = Math.min(r, s); let l = 0; return __range__(0, n, false).map((_k) => emit(scratch[l++], scratch[l++], scratch[l++], scratch[l++]) ); }; } else if (args <= 7) { emitter = function (emit, x, y, z, i, j, k) { p = q = r = s = 0; expr1(emit1, x, y, z, i, j, k); expr2(emit2, x, y, z, i, j, k); const n = Math.min(r, s); let l = 0; return (() => { let asc, end; const result = []; for ( k = 0, end = n, asc = 0 <= end; asc ? k < end : k > end; asc ? k++ : k-- ) { result.push( emit(scratch[l++], scratch[l++], scratch[l++], scratch[l++]) ); } return result; })(); }; } else if (args <= 9) { emitter = function (emit, x, y, z, w, i, j, k, l) { p = q = r = s = 0; expr1(emit1, x, y, z, w, i, j, k, l); expr2(emit2, x, y, z, w, i, j, k, l); const n = Math.min(r, s); l = 0; return (() => { let asc, end; const result = []; for ( k = 0, end = n, asc = 0 <= end; asc ? k < end : k > end; asc ? k++ : k-- ) { result.push( emit(scratch[l++], scratch[l++], scratch[l++], scratch[l++]) ); } return result; })(); }; } else { emitter = function (emit, x, y, z, w, i, j, k, l, d, t) { p = q = 0; expr1(emit1, x, y, z, w, i, j, k, l, d, t); expr2(emit2, x, y, z, w, i, j, k, l, d, t); const n = Math.min(r, s); l = 0; return (() => { let asc, end; const result = []; for ( k = 0, end = n, asc = 0 <= end; asc ? k < end : k > end; asc ? k++ : k-- ) { result.push( emit(scratch[l++], scratch[l++], scratch[l++], scratch[l++]) ); } return result; })(); }; } emitter.lerp = function (f) { let ref; return ([lerp1, lerp2] = Array.from((ref = [1 - f, f]))), ref; }; return emitter; }; export const getLerpThunk = function (data1, data2) { // Get sizes const n1 = getSizes(data1).reduce((a, b) => a * b); const n2 = getSizes(data2).reduce((a, b) => a * b); const n = Math.min(n1, n2); // Create data thunks to copy (multi-)array const thunk1 = getThunk(data1); const thunk2 = getThunk(data2); // Create scratch array const scratch = new Float32Array(n); scratch.lerp = function (f) { thunk1.reset(); thunk2.reset(); let i = 0; return (() => { const result = []; while (i < n) { const a = thunk1(); const b = thunk2(); result.push((scratch[i++] = a + (b - a) * f)); } return result; })(); }; return scratch; }; 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/util/data.js
JavaScript
mit
15,998
export function clamp(x, a, b) { return Math.max(a, Math.min(b, x)); } export function cosine(x) { return 0.5 - 0.5 * Math.cos(clamp(x, 0, 1) * Math.PI); } export function binary(x) { return +(x >= 0.5); } export function hold(x) { return +(x >= 1); }
cchudzicki/mathbox
src/util/ease.js
JavaScript
mit
263
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const letters = "xyzw".split(""); const index = { 0: -1, x: 0, y: 1, z: 2, w: 3, }; const parseOrder = function (order) { if (order === "" + order) { order = order.split(""); } if (order === +order) { order = [order]; } return order; }; export const toType = function (type) { if (type === +type) { type = "vec" + type; } if (type === "vec1") { type = "float"; } return type; }; const toFloatString = function (value) { value = "" + value; if (value.indexOf(".") < 0) { return (value += ".0"); } }; // Helper for float to byte conversion on the w axis, for readback export const mapByte2FloatOffset = function (stretch) { if (stretch == null) { stretch = 4; } const factor = toFloatString(stretch); return `\ vec4 float2ByteIndex(vec4 xyzw, out float channelIndex) { float relative = xyzw.w / ${factor}; float w = floor(relative); channelIndex = (relative - w) * ${factor}; return vec4(xyzw.xyz, w); }\ `; }; // Sample data texture array export const sample2DArray = function (textures) { const divide = function (a, b) { let out; if (a === b) { out = `\ return texture2D(dataTextures[${a}], uv);\ `; } else { const mid = Math.ceil(a + (b - a) / 2); out = `\ if (z < ${mid - 0.5}) { ${divide(a, mid - 1)} } else { ${divide(mid, b)} }\ `; } return (out = out.replace(/\n/g, "\n ")); }; const body = divide(0, textures - 1); return `\ uniform sampler2D dataTextures[${textures}]; vec4 sample2DArray(vec2 uv, float z) { ${body} }\ `; }; // Binary operator export const binaryOperator = function (type, op, curry) { type = toType(type); if (curry != null) { return `\ ${type} binaryOperator(${type} a) { return a ${op} ${curry}; }\ `; } else { return `\ ${type} binaryOperator(${type} a, ${type} b) { return a ${op} b; }\ `; } }; // Extend to n-vector with zeroes export const extendVec = function (from, to, value) { if (value == null) { value = 0; } if (from > to) { return truncateVec(from, to); } const diff = to - from; from = toType(from); to = toType(to); value = toFloatString(value); const parts = __range__(0, diff, true).map(function (x) { if (x) { return value; } else { return "v"; } }); const ctor = parts.join(","); return `\ ${to} extendVec(${from} v) { return ${to}(${ctor}); }\ `; }; // Truncate n-vector export const truncateVec = function (from, to) { if (from < to) { return extendVec(from, to); } const swizzle = "." + "xyzw".substr(0, to); from = toType(from); to = toType(to); return `\ ${to} truncateVec(${from} v) { return v${swizzle}; }\ `; }; // Inject float into 4-component vector export const injectVec4 = function (order) { const swizzler = ["0.0", "0.0", "0.0", "0.0"]; order = parseOrder(order); order = order.map(function (v) { if (v === "" + v) { return index[v]; } else { return v; } }); for (let i = 0; i < order.length; i++) { const channel = order[i]; swizzler[channel] = ["a", "b", "c", "d"][i]; } const mask = swizzler.slice(0, 4).join(", "); const args = ["float a", "float b", "float c", "float d"].slice( 0, order.length ); return `\ vec4 inject(${args}) { return vec4(${mask}); }\ `; }; // Apply 4-component vector swizzle export const swizzleVec4 = function (order, size = null) { const lookup = ["0.0", "xyzw.x", "xyzw.y", "xyzw.z", "xyzw.w"]; if (size == null) { size = order.length; } order = parseOrder(order); order = order.map(function (v) { if (Array.from([0, 1, 2, 3, 4]).includes(+v)) { v = +v; } if (v === "" + v) { v = index[v] + 1; } return lookup[v]; }); while (order.length < size) { order.push("0.0"); } const mask = order.join(", "); return `\ vec${size} swizzle(vec4 xyzw) { return vec${size}(${mask}); }\ `.replace(/vec1/g, "float"); }; // Invert full or truncated swizzles for pointer lookups export const invertSwizzleVec4 = function (order) { const swizzler = ["0.0", "0.0", "0.0", "0.0"]; order = parseOrder(order); order = order.map(function (v) { if (v === +v) { return letters[v - 1]; } else { return v; } }); for (let i = 0; i < order.length; i++) { const letter = order[i]; const src = letters[i]; const j = index[letter]; swizzler[j] = `xyzw.${src}`; } const mask = swizzler.join(", "); return `\ vec4 invertSwizzle(vec4 xyzw) { return vec4(${mask}); }\ `; }; export const identity = function (type) { let args = [].slice.call(arguments); if (args.length > 1) { args = args.map((t, i) => ["inout", t, String.fromCharCode(97 + i)].join(" ") ); args = args.join(", "); return `\ void identity(${args}) { }\ `; } else { return `\ ${type} identity(${type} x) { return x; }\ `; } }; export const constant = (type, value) => `\ ${type} constant() { return ${value}; }\ `; 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/util/glsl.js
JavaScript
mit
5,709
import * as axis from "./axis.js"; import * as data from "./data.js"; import * as ease from "./ease.js"; import * as glsl from "./glsl.js"; import * as js from "./js.js"; import * as pretty from "./pretty.js"; import * as three from "./three.js"; import * as ticks from "./ticks.js"; import * as vdom from "./vdom.js"; export const Axis = axis; export const Data = data; export const Ease = ease; export const GLSL = glsl; export const JS = js; export const Pretty = pretty; export const Three = three; export const Ticks = ticks; export const VDOM = vdom;
cchudzicki/mathbox
src/util/index.js
JavaScript
mit
558
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // Merge multiple objects export const merge = function () { const x = {}; for (const obj of Array.from(arguments)) { for (const k in obj) { const v = obj[k]; x[k] = v; } } return x; }; export const clone = (o) => JSON.parse(JSON.serialize(o)); export const parseQuoted = function (str) { let accum = ""; const unescape = (str) => (str = str.replace(/\\/g, "")); const munch = function (next) { if (accum.length) { list.push(unescape(accum)); } return (accum = next != null ? next : ""); }; str = str.split(/(?=(?:\\.|["' ,]))/g); let quote = false; const list = []; for (const chunk of Array.from(str)) { const char = chunk[0]; const token = chunk.slice(1); switch (char) { case '"': case "'": if (quote) { if (quote === char) { quote = false; munch(token); } else { accum += chunk; } } else { if (accum !== "") { throw new Error( `ParseError: String \`${str}\` does not contain comma-separated quoted tokens.` ); } quote = char; accum += token; } break; case " ": case ",": if (!quote) { munch(token); } else { accum += chunk; } break; default: accum += chunk; } } munch(); return list; };
cchudzicki/mathbox
src/util/js.js
JavaScript
mit
1,854
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const NUMBER_PRECISION = 5; const NUMBER_THRESHOLD = 0.0001; const checkFactor = (v, f) => Math.abs(v / f - Math.round(v / f)) < NUMBER_THRESHOLD; const checkUnit = (v) => checkFactor(v, 1); const formatMultiple = function (v, f, k, compact) { const d = Math.round(v / f); if (d === 1) { return `${k}`; } if (d === -1) { return `-${k}`; } if (k === "1") { return `${d}`; } if (compact) { return `${d}${k}`; } else { return `${d}*${k}`; } }; const formatFraction = function (v, f, k, compact) { let d = Math.round(v * f); if (Math.abs(d) === 1) { d = d < 0 ? "-" : ""; d += k; } else if (k !== "1") { d += compact ? `${k}` : `*${k}`; } return `${d}/${f}`; }; const formatFactors = [ { 1: 1 }, { 1: 1, τ: Math.PI * 2 }, { 1: 1, π: Math.PI }, { 1: 1, τ: Math.PI * 2, π: Math.PI }, { 1: 1, e: Math.E }, { 1: 1, τ: Math.PI * 2, e: Math.E }, { 1: 1, π: Math.PI, e: Math.E }, { 1: 1, τ: Math.PI * 2, π: Math.PI, e: Math.E }, ]; const formatPrimes = [ // denominators 1-30 + interesting multiples [2 * 2 * 3 * 5 * 7, [2, 3, 5, 7]], // 1-7 [2 * 2 * 2 * 3 * 3 * 5 * 5 * 7 * 7, [2, 3, 5, 7]], // 8-11 [2 * 2 * 3 * 5 * 7 * 11 * 13, [2, 3, 5, 7, 11, 13]], // 12-16 [2 * 2 * 17 * 19 * 23 * 29, [2, 17, 19, 23, 29]], // 17-30 [256 * 256, [2]], // Powers of 2 [1000000, [2, 5]], // Powers of 10 ]; const prettyNumber = function (options) { let cache, compact, e, pi, tau; if (options) { ({ cache, compact, tau, pi, e } = options); } compact = +!!(compact != null ? compact : true); tau = +!!(tau != null ? tau : true); pi = +!!(pi != null ? pi : true); e = +!!(e != null ? e : true); cache = +!!(cache != null ? cache : true); const formatIndex = tau + pi * 2 + e * 4; const numberCache = cache ? {} : null; return function (v) { if (numberCache != null) { let cached; if ((cached = numberCache[v]) != null) { return cached; } if (v === Math.round(v)) { return (numberCache[v] = `${v}`); } } let out = `${v}`; let best = out.length + out.indexOf(".") + 2; const match = function (x) { const d = x.length; if (d <= best) { out = `${x}`; return (best = d); } }; for (const k in formatFactors[formatIndex]) { const f = formatFactors[formatIndex][k]; if (checkUnit(v / f)) { match(`${formatMultiple(v / f, 1, k, compact)}`); } else { // eslint-disable-next-line prefer-const for (let [denom, list] of Array.from(formatPrimes)) { let numer = (v / f) * denom; if (checkUnit(numer)) { for (const p of Array.from(list)) { let d, n; while (checkUnit((n = numer / p)) && checkUnit((d = denom / p))) { numer = n; denom = d; } } match(`${formatFraction(v / f, denom, k, compact)}`); break; } } } } if (`${v}`.length > NUMBER_PRECISION) { match(`${v.toPrecision(NUMBER_PRECISION)}`); } if (numberCache != null) { numberCache[v] = out; } return out; }; }; const prettyPrint = function (markup, level) { if (level == null) { level = "info"; } markup = prettyMarkup(markup); return console[level].apply(console, markup); }; const prettyMarkup = function (markup) { // quick n dirty const tag = "color:rgb(128,0,128)"; const attr = "color:rgb(144,64,0)"; const str = "color:rgb(0,0,192)"; const obj = "color:rgb(0,70,156)"; const txt = "color:inherit"; let quoted = false; let nested = 0; const args = []; markup = markup.replace( /(\\[<={}> "'])|(=>|[<={}> "'])/g, function (_, escape, char) { if (escape != null ? escape.length : undefined) { return escape; } if (quoted && !['"', "'"].includes(char)) { return char; } if (nested && !['"', "'", "{", "}"].includes(char)) { return char; } return (() => { switch (char) { case "<": args.push(tag); return "%c<"; case ">": args.push(tag); args.push(txt); return "%c>%c"; case " ": args.push(attr); return " %c"; case "=": case "=>": args.push(tag); return `%c${char}`; case '"': case "'": quoted = !quoted; if (quoted) { args.push(nested ? attr : str); return `${char}%c`; } else { args.push(nested ? obj : tag); return `%c${char}`; } case "{": if (nested++ === 0) { args.push(obj); return `%c${char}`; } else { return char; } case "}": if (--nested === 0) { args.push(tag); return `${char}%c`; } else { return char; } default: return char; } })(); } ); return [markup].concat(args); }; const prettyJSXProp = (k, v) => prettyJSXPair(k, v, "="); const prettyJSXBind = (k, v) => prettyJSXPair(k, v, "=>"); const prettyJSXPair = (function () { const formatNumber = prettyNumber({ compact: false }); return function (k, v, op) { const key = function (k) { if (k === "" + +k || k.match(/^[A-Za-z_][A-Za-z0-9]*$/)) { return k; } else { return JSON.stringify(k); } }; const wrap = function (v) { if (v.match('\n*"')) { return v; } else { return `{${v}}`; } }; const value = function (v) { if (v instanceof Array) { return `[${v.map(value).join(", ")}]`; } switch (typeof v) { case "string": if (v.match("\n")) { return `"\n${v}"\n`; } else { return `"${v}"`; } case "function": v = `${v}`; if (v.match("\n")) { `\n${v}\n`; } else { `${v}`; } v = v.replace(/^function (\([^)]+\))/, "$1 =>"); return (v = v.replace( /^(\([^)]+\)) =>\s*{\s*return\s*([^}]+)\s*;\s*}/, "$1 => $2" )); case "number": return formatNumber(v); default: if (v != null && v !== !!v) { if (v._up != null) { return value(v.map((v) => v)); } if (v.toMarkup) { return v.toString(); } else { return ( "{" + (() => { const result = []; for (const kk in v) { const vv = v[kk]; if (Object.prototype.hasOwnProperty.call(v, kk)) { result.push(`${key(kk)}: ${value(vv)}`); } } return result; })().join(", ") + "}" ); } } else { return `${JSON.stringify(v)}`; } } }; return [k, op, wrap(value(v))].join(""); }; })(); const escapeHTML = function (str) { str = str.replace(/&/g, "&amp;"); str = str.replace(/</g, "&lt;"); return (str = str.replace(/"/g, "&quot;")); }; const prettyFormat = function (str) { const args = [].slice.call(arguments); args.shift(); let out = "<span>"; str = escapeHTML(str); // eslint-disable-next-line no-unused-vars for (const _arg of Array.from(args)) { str = str.replace(/%([a-z])/, function (_, f) { const v = args.shift(); switch (f) { case "c": return `</span><span style="${escapeHTML(v)}">`; default: return escapeHTML(v); } }); } out += str; return (out += "</span>"); }; export const JSX = { prop: prettyJSXProp, bind: prettyJSXBind }; export { prettyMarkup as markup, prettyNumber as number, prettyPrint as print, prettyFormat as format, }; /* for x in [1, 2, 1/2, 3, 1/3, Math.PI, Math.PI / 2, Math.PI * 2, Math.PI * 3, Math.PI * 4, Math.PI * 3 / 4, Math.E * 100, Math.E / 100] console.log prettyNumber({})(x) */
cchudzicki/mathbox
src/util/pretty.js
JavaScript
mit
8,838
// 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 */ import * as CONST from "three/src/constants.js"; import { Euler } from "three/src/math/Euler.js"; import { Matrix4 } from "three/src/math/Matrix4.js"; import { Quaternion } from "three/src/math/Quaternion.js"; import { Vector3 } from "three/src/math/Vector3.js"; export const paramToGL = function (gl, p) { if (p === CONST.RepeatWrapping) { return gl.REPEAT; } if (p === CONST.ClampToEdgeWrapping) { return gl.CLAMP_TO_EDGE; } if (p === CONST.MirroredRepeatWrapping) { return gl.MIRRORED_REPEAT; } if (p === CONST.NearestFilter) { return gl.NEAREST; } if (p === CONST.NearestMipMapNearestFilter) { return gl.NEAREST_MIPMAP_NEAREST; } if (p === CONST.NearestMipMapLinearFilter) { return gl.NEAREST_MIPMAP_LINEAR; } if (p === CONST.LinearFilter) { return gl.LINEAR; } if (p === CONST.LinearMipMapNearestFilter) { return gl.LINEAR_MIPMAP_NEAREST; } if (p === CONST.LinearMipMapLinearFilter) { return gl.LINEAR_MIPMAP_LINEAR; } if (p === CONST.UnsignedByteType) { return gl.UNSIGNED_BYTE; } if (p === CONST.UnsignedShort4444Type) { return gl.UNSIGNED_SHORT_4_4_4_4; } if (p === CONST.UnsignedShort5551Type) { return gl.UNSIGNED_SHORT_5_5_5_1; } if (p === CONST.ByteType) { return gl.BYTE; } if (p === CONST.ShortType) { return gl.SHORT; } if (p === CONST.UnsignedShortType) { return gl.UNSIGNED_SHORT; } if (p === CONST.IntType) { return gl.INT; } if (p === CONST.UnsignedIntType) { return gl.UNSIGNED_INT; } if (p === CONST.FloatType) { return gl.FLOAT; } if (p === CONST.AlphaFormat) { return gl.ALPHA; } if (p === CONST.RGBAFormat) { return gl.RGBA; } if (p === CONST.LuminanceFormat) { return gl.LUMINANCE; } if (p === CONST.LuminanceAlphaFormat) { return gl.LUMINANCE_ALPHA; } if (p === CONST.AddEquation) { return gl.FUNC_ADD; } if (p === CONST.SubtractEquation) { return gl.FUNC_SUBTRACT; } if (p === CONST.ReverseSubtractEquation) { return gl.FUNC_REVERSE_SUBTRACT; } if (p === CONST.ZeroFactor) { return gl.ZERO; } if (p === CONST.OneFactor) { return gl.ONE; } if (p === CONST.SrcColorFactor) { return gl.SRC_COLOR; } if (p === CONST.OneMinusSrcColorFactor) { return gl.ONE_MINUS_SRC_COLOR; } if (p === CONST.SrcAlphaFactor) { return gl.SRC_ALPHA; } if (p === CONST.OneMinusSrcAlphaFactor) { return gl.ONE_MINUS_SRC_ALPHA; } if (p === CONST.DstAlphaFactor) { return gl.DST_ALPHA; } if (p === CONST.OneMinusDstAlphaFactor) { return gl.ONE_MINUS_DST_ALPHA; } if (p === CONST.DstColorFactor) { return gl.DST_COLOR; } if (p === CONST.OneMinusDstColorFactor) { return gl.ONE_MINUS_DST_COLOR; } if (p === CONST.SrcAlphaSaturateFactor) { return gl.SRC_ALPHA_SATURATE; } return 0; }; export const paramToArrayStorage = function (type) { switch (type) { case CONST.UnsignedByteType: return Uint8Array; case CONST.ByteType: return Int8Array; case CONST.ShortType: return Int16Array; case CONST.UnsignedShortType: return Uint16Array; case CONST.IntType: return Int32Array; case CONST.UnsignedIntType: return Uint32Array; case CONST.FloatType: return Float32Array; } }; export const swizzleToEulerOrder = (swizzle) => swizzle.map((i) => ["", "X", "Y", "Z"][i]).join(""); export const transformComposer = function () { const euler = new Euler(); const quat = new Quaternion(); const pos = new Vector3(); const scl = new Vector3(); const transform = new Matrix4(); return function (position, rotation, quaternion, scale, matrix, eulerOrder) { if (eulerOrder == null) { eulerOrder = "XYZ"; } if (rotation != null) { if (eulerOrder instanceof Array) { eulerOrder = swizzleToEulerOrder(eulerOrder); } euler.setFromVector3(rotation, eulerOrder); quat.setFromEuler(euler); } else { quat.set(0, 0, 0, 1); } if (quaternion != null) { quat.multiply(quaternion); } if (position != null) { pos.copy(position); } else { pos.set(0, 0, 0); } if (scale != null) { scl.copy(scale); } else { scl.set(1, 1, 1); } transform.compose(pos, quat, scl); if (matrix != null) { transform.multiplyMatrices(transform, matrix); } return transform; }; };
cchudzicki/mathbox
src/util/three.js
JavaScript
mit
4,823
// 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 * DS202: Simplify dynamic range loops * 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 */ /* Generate equally spaced ticks in a range at sensible positions. @param min/max - Minimum and maximum of range @param n - Desired number of ticks in range @param unit - Base unit of scale (e.g. 1 or π). @param scale - Division scale (e.g. 2 = binary division, or 10 = decimal division). @param bias - Integer to bias divisions one or more levels up or down (to create nested scales) @param start - Whether to include a tick at the start @param end - Whether to include a tick at the end @param zero - Whether to include zero as a tick @param nice - Whether to round to a more reasonable interval */ export const linear = function ( min, max, n, unit, base, factor, start, end, zero, nice ) { let ticks; let i, f; if (nice == null) { nice = true; } if (!n) { n = 10; } if (!unit) { unit = 1; } if (!base) { base = 10; } if (!factor) { factor = 1; } // Calculate naive tick size. const span = max - min; const ideal = span / n; // Unsnapped division if (!nice) { ticks = (() => { let asc, end1; const result = []; for ( i = 0, end1 = n, asc = 0 <= end1; asc ? i <= end1 : i >= end1; asc ? i++ : i-- ) { result.push(min + i * ideal); } return result; })(); if (!start) { ticks.shift(); } if (!end) { ticks.pop(); } if (!zero) { ticks = ticks.filter((x) => x !== 0); } return ticks; } // Round to the floor'd power of 'scale' if (!unit) { unit = 1; } if (!base) { base = 10; } const ref = unit * Math.pow(base, Math.floor(Math.log(ideal / unit) / Math.log(base))); // Make derived steps at sensible factors. const factors = base % 2 === 0 ? [base / 2, 1, 1 / 2] : base % 3 === 0 ? [base / 3, 1, 1 / 3] : [1]; const steps = (() => { const result1 = []; for (f of Array.from(factors)) { result1.push(ref * f); } return result1; })(); // Find step size closest to ideal. let distance = Infinity; let step = steps.reduce(function (ref, step) { f = step / ideal; const d = Math.max(f, 1 / f); if (d < distance) { distance = d; return step; } else { return ref; } }, ref); // Scale final step step *= factor; // Renormalize min/max onto aligned steps. min = Math.ceil(min / step + +!start) * step; max = (Math.floor(max / step) - +!end) * step; n = Math.ceil((max - min) / step); // Generate equally spaced ticks ticks = (() => { let asc1, end2; const result2 = []; for ( i = 0, end2 = n, asc1 = 0 <= end2; asc1 ? i <= end2 : i >= end2; asc1 ? i++ : i-- ) { result2.push(min + i * step); } return result2; })(); if (!zero) { ticks = ticks.filter((x) => x !== 0); } return ticks; }; /* Generate logarithmically spaced ticks in a range at sensible positions. */ export const log = function ( _min, _max, _n, _unit, _base, _bias, _start, _end, _zero, _nice ) { throw new Error("Log ticks not yet implemented."); }; const LINEAR = 0; const LOG = 1; export const make = function ( type, min, max, n, unit, base, bias, start, end, zero, nice ) { switch (type) { case LINEAR: return linear(min, max, n, unit, base, bias, start, end, zero, nice); case LOG: return log(min, max, n, unit, base, bias, start, end, zero, nice); } };
cchudzicki/mathbox
src/util/ticks.js
JavaScript
mit
4,011
// 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 * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // Quick'n'dirty Virtual DOM diffing // with a poor man's React for components // // This is for rendering HTML with data from a GL readback. See DOM examples. const HEAP = []; let id = 0; // Static render components export const Types = { /* * el('example', props, children); example: MathBox.DOM.createClass({ render: (el, props, children) -> * VDOM node return el('span', { className: "foo" }, "Hello World") }) */ }; const descriptor = () => ({ id: id++, type: null, props: null, children: null, rendered: null, instance: null, }); export const hint = function (n) { n *= 2; n = Math.max(0, HEAP.length - n); return __range__(0, n, false).map((_i) => HEAP.push(descriptor())); }; export const element = function (type, props, children) { const el = HEAP.length ? HEAP.pop() : descriptor(); el.type = type != null ? type : "div"; el.props = props != null ? props : null; el.children = children != null ? children : null; // Can't use `arguments` here to pass children as direct args, it de-optimizes label emitters return el; }; export const recycle = function (el) { if (!el.type) { return; } const { children } = el; el.type = el.props = el.children = el.instance = null; HEAP.push(el); if (children != null) { for (const child of Array.from(children)) { recycle(child); } } }; export const apply = function (el, last, node, parent, index) { if (el != null) { if (last == null) { // New node return mount(el, parent, index); } else { // Literal DOM node let same; if (el instanceof Node) { same = el === last; if (same) { return; } } else { // Check compatibility same = typeof el === typeof last && last !== null && el !== null && el.type === last.type; } if (!same) { // Not compatible: unmount and remount unmount(last.instance, node); node.remove(); return mount(el, parent, index); } else { // Maintain component ref let key, ref, value; el.instance = last.instance; // Check if it's a component const type = (el.type != null ? el.type.isComponentClass : undefined) ? el.type : Types[el.type]; // Prepare to diff props and children const props = last != null ? last.props : undefined; const nextProps = el.props; const children = (last != null ? last.children : undefined) != null ? last != null ? last.children : undefined : null; const nextChildren = el.children; if (nextProps != null) { nextProps.children = nextChildren; } // Component if (type != null) { // See if it changed let dirty = node._COMPONENT_DIRTY; if ((props != null) !== (nextProps != null)) { dirty = true; } if (children !== nextChildren) { dirty = true; } if (props != null && nextProps != null) { if (!dirty) { for (key in props) { if (!Object.prototype.hasOwnProperty.call(nextProps, key)) { dirty = true; } } } if (!dirty) { for (key in nextProps) { value = nextProps[key]; if ((ref = props[key]) !== value) { dirty = true; } } } } if (dirty) { let left; const comp = last.instance; if (el.props == null) { el.props = {}; } for (const k in comp.defaultProps) { const v = comp.defaultProps[k]; if (el.props[k] == null) { el.props[k] = v; } } el.props.children = el.children; if (typeof comp.willReceiveProps === "function") { comp.willReceiveProps(el.props); } const should = node._COMPONENT_FORCE || ((left = typeof comp.shouldUpdate === "function" ? comp.shouldUpdate(el.props) : undefined) != null ? left : true); if (should) { const nextState = comp.getNextState(); if (typeof comp.willUpdate === "function") { comp.willUpdate(el.props, nextState); } } const prevProps = comp.props; const prevState = comp.applyNextState(); comp.props = el.props; comp.children = el.children; if (should) { el = el.rendered = typeof comp.render === "function" ? comp.render(element, el.props, el.children) : undefined; apply(el, last.rendered, node, parent, index); if (typeof comp.didUpdate === "function") { comp.didUpdate(prevProps, prevState); } } } return; } else { // VDOM node if (props != null) { for (key in props) { if (!Object.prototype.hasOwnProperty.call(nextProps, key)) { unset(node, key, props[key]); } } } if (nextProps != null) { for (key in nextProps) { value = nextProps[key]; if ((ref = props[key]) !== value && key !== "children") { set(node, key, value, ref); } } } // Diff children if (nextChildren != null) { if (["string", "number"].includes(typeof nextChildren)) { // Insert text directly if (nextChildren !== children) { node.textContent = nextChildren; } } else { if (nextChildren.type != null) { // Single child apply(nextChildren, children, node.childNodes[0], node, 0); } else { // Diff children let child, i; const { childNodes } = node; if (children != null) { for (i = 0; i < nextChildren.length; i++) { child = nextChildren[i]; apply(child, children[i], childNodes[i], node, i); } } else { for (i = 0; i < nextChildren.length; i++) { child = nextChildren[i]; apply(child, null, childNodes[i], node, i); } } } } } else if (children != null) { // Unmount all child components unmount(null, node); // Remove all children node.innerHTML = ""; } } return; } } } if (last != null) { // Removed node unmount(last.instance, node); return last.node.remove(); } }; const mount = function (el, parent, index) { let node; if (index == null) { index = 0; } const type = (el.type != null ? el.type.isComponentClass : undefined) ? el.type : Types[el.type]; // Literal DOM node if (el instanceof Node) { node = el; } else { if (type != null) { // Component let comp; const ctor = (el.type != null ? el.type.isComponentClass : undefined) ? el.type : Types[el.type]; // No component class found if (!ctor) { el = el.rendered = element("noscript"); node = mount(el, parent, index); return node; } // Construct component class el.instance = comp = new ctor(parent); if (el.props == null) { el.props = {}; } for (const k in comp.defaultProps) { const v = comp.defaultProps[k]; if (el.props[k] == null) { el.props[k] = v; } } el.props.children = el.children; // Do initial state transition comp.props = el.props; comp.children = el.children; comp.setState( typeof comp.getInitialState === "function" ? comp.getInitialState() : undefined ); if (typeof comp.willMount === "function") { comp.willMount(); } // Render el = el.rendered = typeof comp.render === "function" ? comp.render(element, el.props, el.children) : undefined; node = mount(el, parent, index); // Finish mounting and remember component/node association if (typeof comp.didMount === "function") { comp.didMount(el); } node._COMPONENT = comp; return node; } else if (["string", "number"].includes(typeof el)) { // Text node = document.createTextNode(el); } else { // VDOM Node node = document.createElement(el.type); for (const key in el.props) { const value = el.props[key]; set(node, key, value); } } const { children } = el; if (children != null) { if (["string", "number"].includes(typeof children)) { // Insert text directly node.textContent = children; } else { if (children.type != null) { // Single child mount(children, node, 0); } else { // Insert children for (let i = 0; i < children.length; i++) { const child = children[i]; mount(child, node, i); } } } } } parent.insertBefore(node, parent.childNodes[index]); return node; }; const unmount = function (comp, node) { if (comp) { if (typeof comp.willUnmount === "function") { comp.willUnmount(); } for (const k in comp) { delete comp[k]; } } return (() => { const result = []; for (const child of Array.from(node.childNodes)) { unmount(child._COMPONENT, child); result.push(delete child._COMPONENT); } return result; })(); }; const prop = function (key) { if (typeof document === "undefined") { return true; } if (document.documentElement.style[key] != null) { return key; } key = key[0].toUpperCase() + key.slice(1); const prefixes = ["webkit", "moz", "ms", "o"]; for (const prefix of Array.from(prefixes)) { if (document.documentElement.style[prefix + key] != null) { return prefix + key; } } }; const map = {}; for (const key of ["transform"]) { map[key] = prop(key); } const set = function (node, key, value, orig) { if (key === "style") { for (const k in value) { const v = value[k]; if ((orig != null ? orig[k] : undefined) !== v) { node.style[map[k] != null ? map[k] : k] = v; } } return; } if (node[key] != null) { try { node[key] = value; } catch (e1) { console.log("failed setting " + key); } return; } if (node instanceof Node) { node.setAttribute(key, value); return; } }; const unset = function (node, key, orig) { if (key === "style") { for (const k in orig) { node.style[map[k] != null ? map[k] : k] = ""; } return; } if (node[key] != null) { node[key] = undefined; } if (node instanceof Node) { node.removeAttribute(key); return; } }; /** * This needs explicit any -> any typings for ts to emit declarations. * Typescript can't handle class declarations inside functions very well. * * @param {any} prototype * @returns {any} */ export const createClass = function (prototype) { let left; const aliases = { willMount: "componentWillMount", didMount: "componentDidMount", willReceiveProps: "componentWillReceiveProps", shouldUpdate: "shouldComponentUpdate", willUpdate: "componentWillUpdate", didUpdate: "componentDidUpdate", willUnmount: "componentWillUnmount", }; for (const a in aliases) { const b = aliases[a]; if (prototype[a] == null) { prototype[a] = prototype[b]; } } class Component { constructor(node, props, state = null, children = null) { let k, v; if (props == null) { props = {}; } this.props = props; this.state = state; this.children = children; const bind = function (f, self) { if (typeof f === "function") { return f.bind(self); } else { return f; } }; for (k in prototype) { v = prototype[k]; this[k] = bind(v, this); } let nextState = null; this.setState = function (state) { if (nextState == null) { nextState = state ? (nextState != null ? nextState : {}) : null; } for (k in state) { v = state[k]; nextState[k] = v; } node._COMPONENT_DIRTY = true; }; this.forceUpdate = function () { node._COMPONENT_FORCE = node._COMPONENT_DIRTY = true; let el = node; return (() => { const result = []; while ((el = el.parentNode)) { if (el._COMPONENT) { result.push((el._COMPONENT_FORCE = true)); } else { result.push(undefined); } } return result; })(); }; this.getNextState = () => nextState; this.applyNextState = function () { node._COMPONENT_FORCE = node._COMPONENT_DIRTY = false; const prevState = this.state; [nextState, this.state] = Array.from([null, nextState]); return prevState; }; } } Component.isComponentClass = true; Component.prototype.defaultProps = (left = typeof prototype.getDefaultProps === "function" ? prototype.getDefaultProps() : undefined) != null ? left : {}; return Component; }; 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/util/vdom.js
JavaScript
mit
14,909
import * as MathBox from "../src"; import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; describe("examples", () => { it("runs the axis example", () => { const mathbox = MathBox.mathBox({ plugins: ["core", "controls", "cursor"], controls: { klass: OrbitControls, }, camera: { fov: 45, }, }); const three = mathbox.three; three.camera.position.set(-0.15, 0.15, 3.6); three.renderer.setClearColor(new THREE.Color(0xffffff), 1.0); const colors = { x: new THREE.Color(0xff4136), y: new THREE.Color(0x2ecc40), z: new THREE.Color(0x0074d9), }; const view = mathbox .set({ scale: 720, focus: 1, }) .cartesian({ range: [ [-2, 2], [-1, 1], [-1, 1], ], scale: [2, 1, 1], }); view.axis({ color: colors.x, }); view.axis({ axis: 2, // "y" also works color: colors.y, }); view.axis({ axis: 3, color: colors.z, }); mathbox .select("axis") .set("end", true) .set("width", 5) .bind("depth", function (t) { return 0.5 + 0.5 * Math.sin(t * 0.5); }); view.array({ id: "colors", live: false, data: [colors.x, colors.y, colors.z].map(function (color) { return [color.r, color.g, color.b, 1]; }), }); view .array({ data: [ [2, 0, 0], [0, 1.11, 0], [0, 0, 1], ], channels: 3, // necessary live: false, }) .text({ data: ["x", "y", "z"], }) .label({ color: 0xffffff, colors: "#colors", }); }); it("runs the curve example", () => { const mathbox = MathBox.mathBox({ plugins: ["core", "controls", "cursor"], controls: { klass: OrbitControls, }, }); const three = mathbox.three; three.camera.position.set(0, 0, 3); three.renderer.setClearColor(new THREE.Color(0xffffff), 1.0); const view = mathbox .set({ focus: 3, }) .cartesian({ range: [ [-2, 2], [-1, 1], [-1, 1], ], scale: [2, 1, 1], }); view.axis({ detail: 30, }); view.axis({ axis: 2, }); view.scale({ divide: 10, }); view.ticks({ classes: ["foo", "bar"], width: 2, }); view.grid({ divideX: 30, width: 1, opacity: 0.5, zBias: -5, }); view.interval({ id: "sampler", width: 64, expr: function (emit, x, i, t) { const y = Math.sin(x + t) * 0.7; // + (i%2)*Math.sin(x * 400000 + t * 5 + x * x * 10000)*.05; emit(x, y); }, channels: 2, }); view.line({ points: "#sampler", color: 0x3090ff, width: 5, }); view .transform({ position: [0, 0.1, 0], }) .line({ points: "#sampler", color: 0x3090ff, width: 5, stroke: "dotted", }); view .transform({ position: [0, -0.1, 0], }) .line({ points: "#sampler", color: 0x3090ff, width: 5, stroke: "dashed", }); }); });
cchudzicki/mathbox
test/examples.spec.js
JavaScript
mit
3,353
import * as MathBox from "../../../src"; import type { Axes, AxesWithZero } from "../../../src/types"; const { Types } = MathBox.Primitives.Types; describe("primitives.types.types", function () { it("validates axes", () => { const axis = Types.axis("y"); let value = axis.make(); expect(value).toBe(2); for (const i of [1, 2, 3, 4] as const) { const invalid = jasmine.createSpy(); const x = axis.validate(i, value, invalid); expect(invalid).not.toHaveBeenCalled(); if (x !== undefined) { value = x; } expect(value).toBe(i); } const axisMap = new Map<Axes, number>([ ["x", 1], ["y", 2], ["z", 3], ["w", 4], ["W", 1], ["H", 2], ["D", 3], ["I", 4], ["width", 1], ["height", 2], ["depth", 3], ["items", 4], ]); axisMap.forEach((i, key) => { const invalid = jasmine.createSpy(); const x = axis.validate(key, value, invalid); expect(invalid).not.toHaveBeenCalled(); if (x !== undefined) { value = x; } expect(value).toBe(i); }); const invalid = jasmine.createSpy(); value = 3; axis.validate(0 as never, value, invalid); expect(invalid).toHaveBeenCalledTimes(1); invalid.calls.reset(); axis.validate(5 as never, value, invalid); expect(invalid).toHaveBeenCalledTimes(1); invalid.calls.reset(); axis.validate("null" as never, value, invalid); expect(invalid).toHaveBeenCalledTimes(1); }); it("validates zero axes", () => { const axis = Types.axis(3, true); let value = axis.make(); expect(value).toBe(3); for (const i of [0, 1, 2, 3, 4] as const) { const invalid = jasmine.createSpy(); const x = axis.validate(i, value, invalid); if (x !== undefined) { value = x; } expect(value).toBe(i); expect(invalid).not.toHaveBeenCalled(); } const axisMap = new Map<AxesWithZero, number>([ ["x", 1], ["y", 2], ["z", 3], ["w", 4], ["W", 1], ["H", 2], ["D", 3], ["I", 4], ["width", 1], ["height", 2], ["depth", 3], ["items", 4], ["zero", 0], ["null", 0], ]); axisMap.forEach((i, key) => { const invalid = jasmine.createSpy(); const x = axis.validate(key, value, invalid); if (x !== undefined) { value = x; } expect(value).toBe(i); expect(invalid).not.toHaveBeenCalled(); }); const invalid = jasmine.createSpy(); value = 3; axis.validate(-1 as never, value, invalid); expect(invalid).toHaveBeenCalledTimes(1); invalid.calls.reset(); axis.validate(5 as never, value, invalid); expect(invalid).toHaveBeenCalledTimes(1); }); it("validates transpose", () => { const transpose = Types.transpose(); let value = transpose.make(); expect(value).toEqual([1, 2, 3, 4]); const invalid = jasmine.createSpy(); value = [1, 2, 3, 4]; let x = transpose.validate("wxyz", value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([4, 1, 2, 3]); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [2, 3, 4, 1]; x = transpose.validate("yxz", value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([2, 1, 3, 4]); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [3, 4, 1, 2]; x = transpose.validate([2, 4, 1, 3], value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([2, 4, 1, 3]); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [4, 1, 2, 3]; x = transpose.validate([2, 4, 1, 2], value, invalid); if (x !== undefined) { value = x; } expect(invalid).toHaveBeenCalledTimes(1); invalid.calls.reset(); value = [1, 2, 3, 4]; x = transpose.validate([2, 4, 1], value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([2, 4, 1, 3]); expect(invalid).not.toHaveBeenCalled(); }); it("validates swizzle", () => { const swizzle = Types.swizzle(); let value = swizzle.make(); expect(value).toEqual([1, 2, 3, 4]); const invalid = jasmine.createSpy(); value = [1, 2, 3, 4]; let x = swizzle.validate("wxyz", value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([4, 1, 2, 3]); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [2, 3, 4, 1]; x = swizzle.validate("yxz", value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([2, 1, 3, 0]); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [3, 4, 1, 2]; x = swizzle.validate([2, 4, 1, 2], value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([2, 4, 1, 2]); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [4, 1, 2, 3]; x = swizzle.validate([2, 4, 1], value, invalid); if (x !== undefined) { value = x; } expect(value).toEqual([2, 4, 1, 0] as never); expect(invalid).not.toHaveBeenCalled(); invalid.calls.reset(); value = [1, 2, 3, 4]; x = swizzle.validate([7, 8, 5, 6] as never, value, invalid); if (x !== undefined) { value = x; } expect(invalid).toHaveBeenCalledTimes(4); }); });
cchudzicki/mathbox
test/primitives/types/types.spec.ts
TypeScript
mit
5,516
import * as MathBox from "../src"; describe("remove", () => { it("does not throw (from issue #15)", () => { const mathbox = MathBox.mathBox({ plugins: ["core", "mathbox"], }); mathbox .cartesian({ range: [ [-2, 2], [-1, 1], ], scale: [2, 1], }) .array({ width: 4, expr: (emit, i) => { emit(i, 0); }, channels: 2, }) .html({ width: 4, expr: (emit, el, _i) => { emit(el("span", { innerHTML: "hello" })); }, }) .dom({ size: 12, offset: [0, 0], outline: 2, zIndex: 2, }); expect(mathbox.remove("html")).toBe(mathbox); expect(mathbox.remove("dom")).toBe(mathbox); }); });
cchudzicki/mathbox
test/remove.spec.js
JavaScript
mit
800
import * as MathBox from "../src"; const expectSelectionIs = (selection, selections) => { expect(selection.length).toBe(selections.length); selection.each((node, i) => { expect(selections[i].length).toBe(1); expect(node).toBe(selections[i][0]); }); }; describe("select", () => { /** * The goal here is not to exhaustively test the selection API, but rather * to sanity check that we've interfaced correctly with our qeurying library */ it("runs the axis example", () => { const root = MathBox.mathBox(); const [c1, c2, c3] = [ { classes: ["child", "one"] }, { classes: ["child", "two"] }, { classes: ["child", "three"] }, ].map(({ classes }) => root.group({ classes })); // two groups const gc1a = c1.group({ classes: ["grandchild", "a"] }); const gc1b = c1.group({ classes: ["grandchild", "b"] }); // group + area const gc2a = c2.group({ classes: ["grandchild", "a"], id: "group-2a" }); const gc2b = c2.axis({ classes: ["grandchild", "b"], size: 2 }); // group + area const gc3a = c3.group({ classes: ["grandchild", "a"] }); const gc3b = c3.axis({ classes: ["grandchild", "b"], size: 3 }); expectSelectionIs( root.select("group"), [c1, gc1a, gc1b, c2, gc2a, c3, gc3a] // ); expectSelectionIs( root.select(".grandchild.a"), [gc1a, gc2a, gc3a] // ); expectSelectionIs( root.select("root group.child axis"), [gc2b, gc3b] // ); expectSelectionIs( c2.select("root group.child axis"), [gc2b] // ); expectSelectionIs( c2.select("#group-2a"), [gc2a] // ); }); });
cchudzicki/mathbox
test/select.spec.js
JavaScript
mit
1,660
/** * Import all files in a directory matching a pattern, and do it recursively. * * This is webpack specific syntax and the arguments to require.context must be * literals since this is transformed while webpack parses. */ const contextualRequire = require.context("./", true, /\.spec\.[jt]s$/); contextualRequire.keys().forEach(contextualRequire);
cchudzicki/mathbox
test/test_entrypoint.js
JavaScript
mit
355
// 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 * DS202: Simplify dynamic range loops * 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 MathBox from "../../src"; const { Data } = MathBox.Util; describe("util.data", function () { it("passed through null array dimensions", function () { const spec = Data.getDimensions(null, { items: 2, channels: 3, width: 5, height: 7, depth: 11, }); return expect(spec).toEqual({ items: 2, channels: 3, width: 5, height: 7, depth: 11, }); }); it("parses 1D JS array dimensions", function () { let spec = Data.getDimensions([1, 2, 3], { items: 1, channels: 1 }); expect(spec).toEqual({ items: 1, channels: 1, width: 3, height: 1, depth: 1, }); spec = Data.getDimensions(__range__(1, 2 * 3, true), { items: 1, channels: 2, }); expect(spec).toEqual({ items: 1, channels: 2, width: 3, height: 1, depth: 1, }); spec = Data.getDimensions(__range__(1, 2 * 3, true), { items: 2, channels: 1, }); expect(spec).toEqual({ items: 2, channels: 1, width: 3, height: 1, depth: 1, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5, true), { items: 2, channels: 3, }); expect(spec).toEqual({ items: 2, channels: 3, width: 5, height: 1, depth: 1, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5, true), { items: 2, channels: 3, width: 1, }); expect(spec).toEqual({ items: 2, channels: 3, width: 1, height: 5, depth: 1, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5, true), { items: 2, channels: 3, width: 1, height: 1, }); expect(spec).toEqual({ items: 2, channels: 3, width: 1, height: 1, depth: 5, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5 * 7, true), { items: 2, channels: 3, width: 5, }); expect(spec).toEqual({ items: 2, channels: 3, width: 5, height: 7, depth: 1, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5 * 7, true), { items: 2, channels: 3, width: 5, height: 1, }); expect(spec).toEqual({ items: 2, channels: 3, width: 5, height: 1, depth: 7, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5 * 7 * 11, true), { items: 2, channels: 3, width: 5, height: 7, }); expect(spec).toEqual({ items: 2, channels: 3, width: 5, height: 7, depth: 11, }); spec = Data.getDimensions(__range__(1, 2 * 3 * 5 * 7 * 11, true), { items: 2, channels: 3, width: 5, depth: 1, }); return expect(spec).toEqual({ items: 2, channels: 3, width: 5, height: 7 * 11, depth: 1, }); }); it("parses 2D JS array dimensions", function () { const map = (channels) => (_x) => __range__(1, channels, true); let spec = Data.getDimensions([1, 2, 3].map(map(2)), { items: 1, channels: 1, }); expect(spec).toEqual({ items: 1, channels: 1, width: 2, height: 3, depth: 1, }); spec = Data.getDimensions([1, 2, 3].map(map(2)), { items: 1, channels: 1, width: 1, }); expect(spec).toEqual({ items: 1, channels: 1, width: 1, height: 2, depth: 3, }); spec = Data.getDimensions([1, 2, 3].map(map(2)), { items: 1, channels: 1, height: 1, }); expect(spec).toEqual({ items: 1, channels: 1, width: 2, height: 1, depth: 3, }); spec = Data.getDimensions([1, 2, 3].map(map(2)), { items: 1, channels: 2 }); expect(spec).toEqual({ items: 1, channels: 2, width: 3, height: 1, depth: 1, }); spec = Data.getDimensions([1, 2, 3].map(map(2)), { items: 2, channels: 1 }); expect(spec).toEqual({ items: 2, channels: 1, width: 3, height: 1, depth: 1, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 3, channels: 2, }); expect(spec).toEqual({ items: 3, channels: 2, width: 5, height: 1, depth: 1, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 3, channels: 2, width: 1, }); expect(spec).toEqual({ items: 3, channels: 2, width: 1, height: 5, depth: 1, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 3, channels: 2, width: 1, height: 1, }); expect(spec).toEqual({ items: 3, channels: 2, width: 1, height: 1, depth: 5, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 2, channels: 1, width: 3, }); expect(spec).toEqual({ items: 2, channels: 1, width: 3, height: 5, depth: 1, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 2, channels: 1, width: 3, height: 1, }); expect(spec).toEqual({ items: 2, channels: 1, width: 3, height: 1, depth: 5, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 2, channels: 1, width: 1, height: 3, }); expect(spec).toEqual({ items: 2, channels: 1, width: 1, height: 3, depth: 5, }); spec = Data.getDimensions(__range__(1, 3 * 5, true).map(map(2)), { items: 2, channels: 1, width: 1, depth: 1, }); return expect(spec).toEqual({ items: 2, channels: 1, width: 1, height: 3 * 5, depth: 1, }); }); it("parses 3D JS array dimensions", function () { const map = (channels) => (_x) => __range__(1, channels, true); const nest = (f, g) => (x) => f(x).map(g); let spec = Data.getDimensions([1, 2, 3, 4, 5].map(nest(map(3), map(2))), { items: 1, channels: 1, }); expect(spec).toEqual({ items: 1, channels: 1, width: 2, height: 3, depth: 5, }); spec = Data.getDimensions([1, 2, 3, 4, 5].map(nest(map(3), map(2))), { items: 1, channels: 2, }); expect(spec).toEqual({ items: 1, channels: 2, width: 3, height: 5, depth: 1, }); spec = Data.getDimensions([1, 2, 3, 4, 5].map(nest(map(3), map(2))), { items: 2, channels: 1, }); expect(spec).toEqual({ items: 2, channels: 1, width: 3, height: 5, depth: 1, }); spec = Data.getDimensions([1, 2, 3, 4, 5].map(nest(map(3), map(2))), { items: 3, channels: 2, }); expect(spec).toEqual({ items: 3, channels: 2, width: 5, height: 1, depth: 1, }); spec = Data.getDimensions( __range__(1, 5 * 7, true).map(nest(map(3), map(2))), { items: 3, channels: 2, width: 5 } ); expect(spec).toEqual({ items: 3, channels: 2, width: 5, height: 7, depth: 1, }); spec = Data.getDimensions( __range__(1, 5 * 7, true).map(nest(map(3), map(2))), { items: 3, channels: 2, width: 1, height: 7 } ); expect(spec).toEqual({ items: 3, channels: 2, width: 1, height: 7, depth: 5, }); spec = Data.getDimensions( __range__(1, 5 * 7, true).map(nest(map(3), map(2))), { items: 3, channels: 2, height: 1, width: 5 } ); expect(spec).toEqual({ items: 3, channels: 2, width: 5, height: 1, depth: 7, }); spec = Data.getDimensions( __range__(1, 5 * 7, true).map(nest(map(3), map(2))), { items: 3, channels: 2, height: 1, depth: 1 } ); return expect(spec).toEqual({ items: 3, channels: 2, width: 5 * 7, height: 1, depth: 1, }); }); it("thunks a 1D array", function () { const data = [1, 2, 3, 4, 5, 6]; const thunk = Data.getThunk(data); const n = 6; let last = null; for ( let i = 1, end = n, asc = 1 <= end; asc ? i <= end : i >= end; asc ? i++ : i-- ) { const value = thunk(); expect(value).toBeGreaterThan(0); if (last != null) { expect(value).toBeGreaterThan(last); } last = value; } return expect(thunk()).toBeFalsy(); }); it("thunks a 2D array", function () { let index = 1; const map = (channels) => (_x) => __range__(index, (index += channels), false); const data = [1, 2, 3].map(map(2)); const thunk = Data.getThunk(data); const n = 2 * 3; let last = null; for ( let i = 1, end = n, asc = 1 <= end; asc ? i <= end : i >= end; asc ? i++ : i-- ) { const value = thunk(); expect(value).toBeGreaterThan(0); if (last != null) { expect(value).toBeGreaterThan(last); } last = value; } return expect(thunk()).toBeFalsy(); }); it("thunks a 3D array", function () { let index = 1; const map = (channels) => (_x) => __range__(index, (index += channels), false); const nest = (f, g) => (x) => f(x).map(g); const data = [1, 2, 3, 4, 5].map(nest(map(3), map(2))); const thunk = Data.getThunk(data); const n = 2 * 3 * 5; let last = null; for ( let i = 1, end = n, asc = 1 <= end; asc ? i <= end : i >= end; asc ? i++ : i-- ) { const value = thunk(); expect(value).toBeGreaterThan(0); if (last != null) { expect(value).toBeGreaterThan(last); } last = value; } return expect(thunk()).toBeFalsy(); }); it("thunks a 4D array", function () { let index = 1; const map = (channels) => (_x) => __range__(index, (index += channels), false); const nest = (f, g) => (x) => f(x).map(g); const data = [1, 2, 3, 4, 5, 6, 7].map(nest(map(5), nest(map(3), map(2)))); const thunk = Data.getThunk(data); const n = 2 * 3 * 5 * 7; let last = null; for ( let i = 1, end = n, asc = 1 <= end; asc ? i <= end : i >= end; asc ? i++ : i-- ) { const value = thunk(); expect(value).toBeGreaterThan(0); if (last != null) { expect(value).toBeGreaterThan(last); } last = value; } return expect(thunk()).toBeFalsy(); }); it("thunks a 5D array", function () { let index = 1; const map = (channels) => (_x) => __range__(index, (index += channels), false); const nest = (f, g) => (x) => f(x).map(g); const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map( nest(map(7), nest(map(5), nest(map(3), map(2)))) ); const thunk = Data.getThunk(data); const n = 2 * 3 * 5 * 7 * 11; let last = null; for ( let i = 1, end = n, asc = 1 <= end; asc ? i <= end : i >= end; asc ? i++ : i-- ) { const value = thunk(); expect(value).toBeGreaterThan(0); if (last != null) { expect(value).toBeGreaterThan(last); } last = value; } return expect(thunk()).toBeFalsy(); }); it("makes a 1 item, 1 channel emitter", function () { let j; let i = (j = 0); const n = 1; const thunk = () => i++; const out = []; Data.makeEmitter(thunk, 1, 1)((x) => out.push(x)); expect(i).toBe(n); expect(out.length).toBe(n); return Array.from(out).map((v) => expect(v).toBe(j++)); }); it("makes a 2 item, 4 channel emitter", function () { let j, row; const items = 2; const channels = 4; let i = (j = 0); const n = items * channels; const thunk = () => i++; const out = []; Data.makeEmitter( thunk, items, channels )((x, y, z, w) => out.push([x, y, z, w])); expect(i).toBe(n); expect(out.length).toBe(items); for (row of Array.from(out)) { expect(row.length).toBe(channels); } return (() => { const result = []; for (row of Array.from(out)) { result.push(Array.from(row).map((v) => expect(v).toBe(j++))); } return result; })(); }); return it("makes a 14 item, 3 channel emitter", function () { let j, row; const items = 14; const channels = 3; let i = (j = 0); const n = items * channels; const thunk = () => i++; const out = []; Data.makeEmitter(thunk, items, channels)((x, y, z) => out.push([x, y, z])); expect(i).toBe(n); expect(out.length).toBe(items); for (row of Array.from(out)) { expect(row.length).toBe(channels); } return (() => { const result = []; for (row of Array.from(out)) { result.push(Array.from(row).map((v) => expect(v).toBe(j++))); } return result; })(); }); }); 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
test/util/data.spec.js
JavaScript
mit
13,840
// 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 */ import * as MathBox from "../../src"; const { GLSL } = MathBox.Util; describe("util.glsl", function () { it("swizzles vec4", function () { let code = GLSL.swizzleVec4([4, 3, 2, 1]); expect(code).toContain("vec4(xyzw.w, xyzw.z, xyzw.y, xyzw.x)"); code = GLSL.swizzleVec4([4, 0, 2, 1]); expect(code).toContain("vec4(xyzw.w, 0.0, xyzw.y, xyzw.x)"); code = GLSL.swizzleVec4([2, 4, 3], 4); expect(code).toContain("vec4(xyzw.y, xyzw.w, xyzw.z, 0.0)"); code = GLSL.swizzleVec4([2, 4, 3]); expect(code).toContain("vec3(xyzw.y, xyzw.w, xyzw.z)"); code = GLSL.swizzleVec4("yxwz"); expect(code).toContain("vec4(xyzw.y, xyzw.x, xyzw.w, xyzw.z)"); code = GLSL.swizzleVec4("y0wz"); expect(code).toContain("vec4(xyzw.y, 0.0, xyzw.w, xyzw.z)"); code = GLSL.swizzleVec4("ywz", 4); expect(code).toContain("vec4(xyzw.y, xyzw.w, xyzw.z, 0.0)"); code = GLSL.swizzleVec4("ywz"); return expect(code).toContain("vec3(xyzw.y, xyzw.w, xyzw.z)"); }); return it("invert swizzles vec4", function () { let code = GLSL.invertSwizzleVec4([2, 3, 4, 1]); expect(code).toContain("vec4(xyzw.w, xyzw.x, xyzw.y, xyzw.z)"); code = GLSL.invertSwizzleVec4([2, 3, 4, 0]); expect(code).toContain("vec4(0.0, xyzw.x, xyzw.y, xyzw.z)"); code = GLSL.invertSwizzleVec4([2, 3, 4], 4); expect(code).toContain("vec4(0.0, xyzw.x, xyzw.y, xyzw.z)"); code = GLSL.invertSwizzleVec4("yzwx"); expect(code).toContain("vec4(xyzw.w, xyzw.x, xyzw.y, xyzw.z)"); code = GLSL.invertSwizzleVec4("yzw0"); expect(code).toContain("vec4(0.0, xyzw.x, xyzw.y, xyzw.z)"); code = GLSL.invertSwizzleVec4("yzw"); return expect(code).toContain("vec4(0.0, xyzw.x, xyzw.y, xyzw.z)"); }); });
cchudzicki/mathbox
test/util/glsl.spec.js
JavaScript
mit
2,054
{ "compilerOptions": { "outDir": "./build/esm/", "noImplicitAny": true, "module": "es6", "target": "es6", "allowJs": true, "moduleResolution": "node", "strictNullChecks": true, "baseUrl": "./", "declaration": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
cchudzicki/mathbox
tsconfig.json
JSON
mit
316
############################################################################### # Set default behavior to automatically normalize line endings. ############################################################################### * text=auto ############################################################################### # Set default behavior for command prompt diff. # # This is need for earlier builds of msysgit that does not have it on by # default for csharp files. # Note: This is only used by command line ############################################################################### #*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS # the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below ############################################################################### #*.sln merge=binary #*.csproj merge=binary #*.vbproj merge=binary #*.vcxproj merge=binary #*.vcproj merge=binary #*.dbproj merge=binary #*.fsproj merge=binary #*.lsproj merge=binary #*.wixproj merge=binary #*.modelproj merge=binary #*.sqlproj merge=binary #*.wwaproj merge=binary ############################################################################### # behavior for image files # # image files are treated as binary by default. ############################################################################### #*.jpg binary #*.png binary #*.gif binary ############################################################################### # diff behavior for common document formats # # Convert binary document formats to text before diffing them. This feature # is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain #*.DOC diff=astextplain #*.docx diff=astextplain #*.DOCX diff=astextplain #*.dot diff=astextplain #*.DOT diff=astextplain #*.pdf diff=astextplain #*.PDF diff=astextplain #*.rtf diff=astextplain #*.RTF diff=astextplain
lucci/rjw
.gitattributes
Git
unknown
2,518
## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.rsuser *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_h.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *_wpftmp.csproj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !?*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser *- Backup*.rdl # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush personal settings .cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ # BeatPulse healthcheck temp database healthchecksdb
lucci/rjw
.gitignore
Git
unknown
5,745
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef ParentName="BondageBase"> <defName>Armbinder</defName> <label>armbinder</label> <labelNoun>an armbinder</labelNoun> <description>An armbinder. A restraint device that binds the arms behind the body.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>ChastityBelt</defName> <label>chastity belt</label> <labelNoun>a chastity belt</labelNoun> <description>A chastity belt. Restricts access to the vagina and anus from its lover, and its wearer.</description> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>ChastityCage</defName> <label>chastity cage</label> <labelNoun>a chastity cage</labelNoun> <description>A chastity cage. Restricts access to the penis from its lover, and its wearer.</description> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>Yoke</defName> <label>yoke</label> <labelNoun>a yoke</labelNoun> <description>Keeps the arms and head of the wearer locked relative to their body in a raised-arm position.</description> <stages> <li> <capMods> <li> <capacity>Manipulation</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>ClosedGag</defName> <label>closed gag</label> <labelNoun>a closed gag</labelNoun> <description>A closed gag that prevents its wearer from speaking.</description> <stages> <li> <capMods> <li> <capacity>Talking</capacity> <setMax>0.00</setMax> </li> <li> <capacity>Eating</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>OpenGag</defName> <label>open gag</label> <labelNoun>an open gag</labelNoun> <description>An open gag that only allows its wearer to mutter incomprehensibly.</description> <stages> <li> <capMods> <li> <capacity>Talking</capacity> <setMax>0.00</setMax> </li> <li> <capacity>Eating</capacity> <offset>-0.25</offset> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>Legbinder</defName> <label>legbinder</label> <labelNoun>a legbinder</labelNoun> <description>An legbinder. A restraint device that binds the legs restricting movement.</description> <stages> <li> <capMods> <li> <capacity>Moving</capacity> <setMax>0.30</setMax> </li> </capMods> </li> </stages> </HediffDef> <HediffDef ParentName="BondageBase"> <defName>Blindfold</defName> <label>blindfold</label> <labelNoun>a blindfold</labelNoun> <description>A blindfold. A restraint device that blocks the wearer's vision.</description> <stages> <li> <capMods> <li> <capacity>Sight</capacity> <setMax>0.00</setMax> </li> </capMods> </li> </stages> </HediffDef> </Defs>
lucci/rjw
1.1/Defs/HediffDefs/Hediffs_Bondage.xml
XML
unknown
3,167
<?xml version="1.0" encoding="utf-8" ?> <Defs> <HediffDef> <defName>Plugged</defName> <hediffClass>Hediff</hediffClass> <defaultLabelColor>(0.5, 0.5, 0.9)</defaultLabelColor> <label>Plugged</label> <description>Plugged.</description> <makesSickThought>false</makesSickThought> <tendable>false</tendable> <stages> <li> <label>loosely</label> </li> <li> <label>comfortable</label> <minSeverity>0.2</minSeverity> <capMods> <li> <capacity>Moving</capacity> <offset>-0.01</offset> </li> </capMods> <statOffsets> <Vulnerability>0.1</Vulnerability> <SexFrequency>0.5</SexFrequency> </statOffsets> </li> <li> <label>tightly</label> <minSeverity>0.4</minSeverity> <painOffset>0.01</painOffset> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> </capMods> <statOffsets> <Vulnerability>0.15</Vulnerability> <SexFrequency>1</SexFrequency> </statOffsets> </li> <li> <label>very tight</label> <minSeverity>0.6</minSeverity> <painOffset>0.03</painOffset> <capMods> <li> <capacity>Moving</capacity> <offset>-0.05</offset> </li> </capMods> <statOffsets> <Vulnerability>0.2</Vulnerability> <SexFrequency>1.2</SexFrequency> </statOffsets> </li> <li> <label>cracking tight</label> <minSeverity>0.8</minSeverity> <painOffset>0.10</painOffset> <capMods> <li> <capacity>Moving</capacity> <offset>-0.15</offset> </li> </capMods> <statOffsets> <Vulnerability>0.35</Vulnerability> <SexFrequency>1</SexFrequency> </statOffsets> </li> </stages> <scenarioCanAdd>false</scenarioCanAdd> </HediffDef> </Defs>
lucci/rjw
1.1/Defs/HediffDefs/Hediffs_Plugged.xml
XML
unknown
1,806
<?xml version="1.0" encoding="utf-8" ?> <Defs> <JobDef> <defName>UseFM</defName> <driverClass>rjwex.JobDriver_UseFM</driverClass> <reportString>using fuck machine</reportString> <casualInterruptible>false</casualInterruptible> </JobDef> </Defs>
lucci/rjw
1.1/Defs/JobDefs/Job_UseFM.xml
XML
unknown
255
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffArmbinder</defName> <label>force off armbinder</label> <description>Forcibly removes an armbinder without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing armbinder.</jobString> <removes_apparel>Armbinder</removes_apparel> <failure_affects>Torso</failure_affects> <destroys_one_of> <li>Hand</li> </destroys_one_of> <major_burns_on> <li>Hand</li> <li>Arm</li> </major_burns_on> <minor_burns_on> <li>Torso</li> </minor_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffGagBall</defName> <label>force off gag</label> <description>Forcibly removes a gag without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing gag.</jobString> <removes_apparel>GagBall</removes_apparel> <failure_affects>Head</failure_affects> <destroys_one_of> <li>Jaw</li> </destroys_one_of> <major_burns_on> <li>Head</li> <li>Neck</li> </major_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffGagRing</defName> <label>force off gag</label> <description>Forcibly removes a gag without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing gag.</jobString> <removes_apparel>GagRing</removes_apparel> <failure_affects>Head</failure_affects> <destroys_one_of> <li>Jaw</li> </destroys_one_of> <major_burns_on> <li>Head</li> <li>Neck</li> </major_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffChastityBelt</defName> <label>force off chastity belt</label> <description>Forcibly removes a chastity belt without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing chastity belt.</jobString> <removes_apparel>ChastityBelt</removes_apparel> <failure_affects>Torso</failure_affects> <destroys_one_of> <li>Genitals</li> </destroys_one_of> <major_burns_on> <li>Torso</li> </major_burns_on> <minor_burns_on> <li>Leg</li> </minor_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffChastityBeltOpen</defName> <label>force off chastity belt</label> <description>Forcibly removes a chastity belt without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing chastity belt.</jobString> <removes_apparel>ChastityBeltO</removes_apparel> <failure_affects>Torso</failure_affects> <destroys_one_of> <li>Genitals</li> </destroys_one_of> <major_burns_on> <li>Torso</li> </major_burns_on> <minor_burns_on> <li>Leg</li> </minor_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffChastityCage</defName> <label>force off chastity belt</label> <description>Forcibly removes a chastity cage without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing chastity cage.</jobString> <removes_apparel>ChastityCage</removes_apparel> <failure_affects>Torso</failure_affects> <destroys_one_of> <li>Genitals</li> </destroys_one_of> <major_burns_on> <li>Torso</li> </major_burns_on> <minor_burns_on> <li>Leg</li> </minor_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffLegbinder</defName> <label>force off legbinder</label> <description>Forcibly removes a legbinder without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing legbinder.</jobString> <removes_apparel>Legbinder</removes_apparel> <failure_affects>Torso</failure_affects> <major_burns_on> <li>Leg</li> </major_burns_on> <minor_burns_on> <li>Genitals</li> </minor_burns_on> </rjw.force_off_gear_def> <rjw.force_off_gear_def ParentName="ForceOffGenericGear"> <defName>ForceOffBlindfold</defName> <label>force off blindfold</label> <description>Forcibly removes a blindfold without the key at the cost of significant damage to the wearer.</description> <jobString>Forcibly removing blindfold.</jobString> <removes_apparel>Blindfold</removes_apparel> <failure_affects>Head</failure_affects> <major_burns_on> <li>Head</li> </major_burns_on> <minor_burns_on> <li>Neck</li> </minor_burns_on> </rjw.force_off_gear_def> </Defs>
lucci/rjw
1.1/Defs/RecipeDefs/Recipes_ForceRemoveBondage.xml
XML
unknown
4,709
<?xml version="1.0" encoding="utf-8" ?> <Defs> <RecipeDef Abstract="True" Name="RJWEX_MakeBondageGear"> <workSpeedStat>GeneralLaborSpeed</workSpeedStat> <workSkill>Crafting</workSkill> </RecipeDef> <RecipeDef Abstract="True" Name="RJWEX_MakeAdvBondageGear" ParentName="RJWEX_MakeBondageGear"> <soundWorking>Recipe_Tailor</soundWorking> <unfinishedThingDef>UnfinishedApparel</unfinishedThingDef> <recipeUsers> <li>ElectricTailoringBench</li> </recipeUsers> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeArmbinder</defName> <label>make armbinder</label> <description>Make an armbinder.</description> <jobString>Making armbinder.</jobString> <workAmount>5000</workAmount> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>50</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>30</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <!-- <categories> <li>Leathers</li> </categories> --> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <Armbinder>1</Armbinder> </products> <skillRequirements> <Crafting>6</Crafting> </skillRequirements> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeGagBall</defName> <label>make ball gag</label> <description>Make a gag with a ball, prevents talking.</description> <jobString>Making gag.</jobString> <workAmount>1500</workAmount> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>8</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>4</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <GagBall>1</GagBall> </products> <skillRequirements> <Crafting>3</Crafting> </skillRequirements> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeGagRing</defName> <label>make ring gag</label> <description>Make a gag with a ring, prevents talking.</description> <jobString>Making gag.</jobString> <workAmount>1250</workAmount> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>8</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>4</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <GagRing>1</GagRing> </products> <skillRequirements> <Crafting>3</Crafting> </skillRequirements> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeChastityBelt</defName> <label>make chastity belt</label> <description>Make a chastity belt, prevents access to genitals and anus.</description> <jobString>Making chastity belt.</jobString> <workAmount>4000</workAmount> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>10</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>50</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <ChastityBelt>1</ChastityBelt> </products> <skillRequirements> <Crafting>5</Crafting> </skillRequirements> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeChastityBeltO</defName> <label>make chastity belt(open)</label> <description>Make a chastity belt, prevents access to genitals, have a hole for anal sex.</description> <jobString>Making chastity belt.</jobString> <workAmount>4000</workAmount> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>10</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>50</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <ChastityBeltO>1</ChastityBeltO> </products> <skillRequirements> <Crafting>5</Crafting> </skillRequirements> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeChastityCage</defName> <label>make chastity cage</label> <description>Make a chastity cage, prevents erection.</description> <jobString>Making chastity cage.</jobString> <workAmount>2000</workAmount> <ingredients> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>10</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <ChastityCage>1</ChastityCage> </products> <skillRequirements> <Crafting>5</Crafting> </skillRequirements> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeLegbinder</defName> <label>make legbinder</label> <description>Make a legbinder.</description> <jobString>Making legbinder.</jobString> <workSpeedStat>GeneralLaborSpeed</workSpeedStat> <soundWorking>Recipe_Tailor</soundWorking> <workAmount>5000</workAmount> <unfinishedThingDef>UnfinishedApparel</unfinishedThingDef> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>70</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>30</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <Legbinder>1</Legbinder> </products> <skillRequirements> <Crafting>6</Crafting> </skillRequirements> <workSkill>Crafting</workSkill> </RecipeDef> <RecipeDef ParentName="RJWEX_MakeAdvBondageGear"> <defName>MakeBlindfold</defName> <label>make blindfold</label> <description>Make a blindfold.</description> <jobString>Making blindfold.</jobString> <workSpeedStat>GeneralLaborSpeed</workSpeedStat> <soundWorking>Recipe_Tailor</soundWorking> <workAmount>5000</workAmount> <unfinishedThingDef>UnfinishedApparel</unfinishedThingDef> <ingredients> <li> <filter> <categories> <li>Leathers</li> <li>Textiles</li> </categories> </filter> <count>40</count> </li> <li> <filter> <categories> <li>ResourcesRaw</li> </categories> </filter> <count>20</count> </li> <li> <filter> <thingDefs> <li>Hololock</li> </thingDefs> </filter> <count>1</count> </li> </ingredients> <fixedIngredientFilter> <thingDefs> <li>Leather_Human</li> <li>Leather_Light</li> <li>Leather_Plain</li> <li>Synthread</li> <li>Hyperweave</li> <li>DevilstrandCloth</li> <li>Silver</li> <li>Gold</li> <li>Steel</li> <li>Plasteel</li> <li>Hololock</li> </thingDefs> </fixedIngredientFilter> <products> <Blindfold>1</Blindfold> </products> <skillRequirements> <Crafting>6</Crafting> </skillRequirements> <workSkill>Crafting</workSkill> </RecipeDef> </Defs>
lucci/rjw
1.1/Defs/RecipeDefs/Recipes_MakeBondageGear.xml
XML
unknown
10,155
<?xml version="1.0" encoding="utf-8" ?> <Defs> <RecordDef> <defName>TimePluggedAnal</defName> <label>wearing anal plug</label> <description>Total time wearing plug in butthole.</description> <type>Time</type> <workerClass>rjwex.RecordWorker_TimePluggedAnal</workerClass> </RecordDef> <RecordDef> <defName>TimeOnFuckMachine</defName> <label>time on fuck machine</label> <description>Total time spent using fuck machine (or bound to it).</description> <type>Time</type> <measuredTimeJobs> <li>UseFM</li> </measuredTimeJobs> </RecordDef> <!--RecordDef> <defName>TimesDominated</defName> <label>time on fuck machine</label> <description>Total time spent using fuck machine (or bound to it).</description> <type>Int</type> </RecordDef> <RecordDef> <defName>TimesDominatedOthers</defName> <label>time on fuck machine</label> <description>Total time spent using fuck machine (or bound to it).</description> <type>Int</type> </RecordDef--> </Defs>
lucci/rjw
1.1/Defs/RecordDefs/Records.xml
XML
unknown
998
<?xml version="1.0" encoding="utf-8"?> <Defs> <SoundDef> <defName>FMThrust</defName> <context>MapOnly</context> <eventNames /> <maxSimultaneous>1</maxSimultaneous> <subSounds> <li> <grains> <li Class="AudioGrain_Folder"> <clipFolderPath>FM/FMThrust</clipFolderPath> </li> </grains> <volumeRange> <min>15</min> <max>15 </max> </volumeRange> <pitchRange> <min>1</min> <max>1</max> </pitchRange> <distRange> <min>0</min> <max>51.86047</max> </distRange> <sustainLoop>False</sustainLoop> </li> </subSounds> </SoundDef> </Defs>
lucci/rjw
1.1/Defs/SoundDefs/Sounds_FM.xml
XML
unknown
625
<?xml version="1.0" encoding="utf-8" ?> <Defs> <!-- <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>Yoke</defName> <label>yoke</label> <description>A high-tech yoke. It prevents any pawn it's attached to from using their arms.</description> <thingClass>rjw.yoke</thingClass> <graphicData> <texPath>Things\Pawn\Humanlike\Apparel\Bondage\Armbinder\armbinder</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <statBases> <MaxHitPoints>250</MaxHitPoints> <Flammability>0.3</Flammability> <DeteriorationRate>1.0</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>850</MarketValue> <Mass>4</Mass> <ArmorRating_Blunt>0.15</ArmorRating_Blunt> <ArmorRating_Sharp>0.25</ArmorRating_Sharp> <Insulation_Cold>-4</Insulation_Cold> </statBases> <apparel> <bodyPartGroups> <li>Arms</li> <li>LeftHand</li> <li>RightHand</li> </bodyPartGroups> <wornGraphicPath>Things\Pawn\Humanlike\Apparel\Bondage\Armbinder\</wornGraphicPath> <layers> <li>Shell</li> </layers> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <equipped_hediff>Yoke</equipped_hediff> <gives_bound_moodlet>true</gives_bound_moodlet> </rjw.bondage_gear_def> --> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage.xml
XML
unknown
1,253
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>Armbinder</defName> <label>armbinder</label> <description>Armbinder prevents any pawn it's attached to from using their arms.</description> <thingClass>rjw.armbinder</thingClass> <graphicData> <texPath>Items/Armbinder/armbinder</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <stuffCategories> <li>Leathery</li> </stuffCategories> <costStuffCount>80</costStuffCount> <statBases> <MaxHitPoints>250</MaxHitPoints> <Flammability>0.5</Flammability> <DeteriorationRate>1.0</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>550</MarketValue> <Mass>4</Mass> <ArmorRating_Blunt>0.15</ArmorRating_Blunt> <ArmorRating_Sharp>0.25</ArmorRating_Sharp> <Insulation_Cold>-4</Insulation_Cold> </statBases> <apparel> <bodyPartGroups> <li>Arms</li> <li>LeftHand</li> <li>RightHand</li> </bodyPartGroups> <wornGraphicPath>Items/Armbinder/Armbinder</wornGraphicPath> <layers> <li>Shell</li> </layers> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <equipped_hediff>Armbinder</equipped_hediff> <gives_bound_moodlet>true</gives_bound_moodlet> <blocks_hands>true</blocks_hands> <HediffTargetBodyPartDefs> <li>Arm</li> </HediffTargetBodyPartDefs> <BoundBodyPartGroupDefs> <li>LeftHand</li> <li>RightHand</li> </BoundBodyPartGroupDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_Armbinder.xml
XML
unknown
1,505
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>Blindfold</defName> <label>blindfold</label> <description>A blindfold. A restraint device that blocks the wearer's vision.</description> <thingClass>rjw.armbinder</thingClass> <graphicData> <texPath>Items/Blindfold/Blindfold</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <stuffCategories> <li>Leathery</li> </stuffCategories> <costStuffCount>40</costStuffCount> <statBases> <MaxHitPoints>250</MaxHitPoints> <Flammability>0.5</Flammability> <DeteriorationRate>1.0</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>550</MarketValue> <Mass>4</Mass> </statBases> <apparel> <hatRenderedFrontOfFace>true</hatRenderedFrontOfFace> <bodyPartGroups> <li>Eyes</li> </bodyPartGroups> <wornGraphicPath>Items/Blindfold/Blindfold</wornGraphicPath> <layers> <li>Overhead</li> </layers> <!-- <commonality>0</commonality> --> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <equipped_hediff>Blindfold</equipped_hediff> <gives_bound_moodlet>true</gives_bound_moodlet> <blocks_hands>false</blocks_hands> <HediffTargetBodyPartDefs> <li>Eye</li> </HediffTargetBodyPartDefs> <BoundBodyPartGroupDefs> <li>Eyes</li> </BoundBodyPartGroupDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_Blindfold.xml
XML
unknown
1,408
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>ChastityBelt</defName> <label>chastity belt</label> <description>Chastity belt prevents sex and masturbation.</description> <thingClass>rjw.bondage_gear</thingClass> <graphicData> <texPath>Items/ChastityBelt/chastity_belt</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <stuffCategories> <li>Metallic</li> </stuffCategories> <costStuffCount>60</costStuffCount> <statBases> <MaxHitPoints>300</MaxHitPoints> <Flammability>0.1</Flammability> <DeteriorationRate>0.5</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>550</MarketValue> <Mass>3</Mass> </statBases> <apparel> <!-- Use the legs group so it doesn't conflict with shirts --> <bodyPartGroups> <li>Legs</li> </bodyPartGroups> <wornGraphicPath>Items/ChastityBelt/Chastity_Belt</wornGraphicPath> <!-- Use the shell layer so it doesn't conflict with pants --> <layers> <li>Shell</li> </layers> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <gives_bound_moodlet>true</gives_bound_moodlet> <blocks_penis>true</blocks_penis> <blocks_vagina>true</blocks_vagina> <blocks_anus>true</blocks_anus> <equipped_hediff>ChastityBelt</equipped_hediff> <HediffTargetBodyPartDefs> <li>Genitals</li> <li>Anus</li> </HediffTargetBodyPartDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_ChastityBelt.xml
XML
unknown
1,456
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>ChastityBeltO</defName> <label>chastity belt(Open)</label> <description>Chastity belt allows anal sex.</description> <thingClass>rjw.bondage_gear</thingClass> <graphicData> <texPath>Items/ChastityBelt/chastity_belt</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <stuffCategories> <li>Metallic</li> </stuffCategories> <costStuffCount>60</costStuffCount> <statBases> <MaxHitPoints>300</MaxHitPoints> <Flammability>0.1</Flammability> <DeteriorationRate>0.5</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>550</MarketValue> <Mass>3</Mass> </statBases> <apparel> <bodyPartGroups> <li>Legs</li> </bodyPartGroups> <wornGraphicPath>Items/ChastityBelt/Chastity_Belt</wornGraphicPath> <layers> <li>Shell</li> </layers> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <gives_bound_moodlet>true</gives_bound_moodlet> <blocks_penis>true</blocks_penis> <blocks_vagina>true</blocks_vagina> <equipped_hediff>ChastityBelt</equipped_hediff> <HediffTargetBodyPartDefs> <li>Genitals</li> <li>Anus</li> </HediffTargetBodyPartDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_ChastityBeltOpen.xml
XML
unknown
1,283
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>ChastityCage</defName> <label>chastity Cage</label> <description>Chastity cage for males, prevents erection.</description> <thingClass>rjw.bondage_gear</thingClass> <graphicData> <texPath>Items/ChastityBelt/chastity_belt</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <stuffCategories> <li>Metallic</li> </stuffCategories> <costStuffCount>10</costStuffCount> <statBases> <MaxHitPoints>100</MaxHitPoints> <Flammability>0.1</Flammability> <DeteriorationRate>0.5</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>100</MarketValue> <Mass>1</Mass> </statBases> <apparel> <bodyPartGroups> <li>Legs</li> </bodyPartGroups> <wornGraphicPath>Items/ChastityBelt/Chastity_Belt</wornGraphicPath> <layers> <li>Shell</li> </layers> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <gives_bound_moodlet>true</gives_bound_moodlet> <blocks_penis>true</blocks_penis> <equipped_hediff>ChastityCage</equipped_hediff> <HediffTargetBodyPartDefs> <li>Genitals</li> </HediffTargetBodyPartDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_ChastityCage.xml
XML
unknown
1,234
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>GagBall</defName> <label>ball gag</label> <description>Ball gag prevents talking.</description> <thingClass>rjw.bondage_gear</thingClass> <graphicData> <texPath>Items/GagBall/gag_ball</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <statBases> <MaxHitPoints>150</MaxHitPoints> <Flammability>0.5</Flammability> <DeteriorationRate>1.0</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>450</MarketValue> <Mass>1</Mass> </statBases> <apparel> <bodyPartGroups> <li>Teeth</li> <!-- <li>FullHead</li> --> <!-- <li>Mouth</li> Causes bugs with ApparelUtility.HasPartsToWear --> </bodyPartGroups> <wornGraphicPath>Items/GagBall/GagBall</wornGraphicPath> <layers> <li>Overhead</li> <!-- <li>OnSkin</li> --> </layers> <hatRenderedFrontOfFace>true</hatRenderedFrontOfFace> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <equipped_hediff>ClosedGag</equipped_hediff> <gives_gagged_moodlet>true</gives_gagged_moodlet> <blocks_oral>true</blocks_oral> <HediffTargetBodyPartDefs> <li>Jaw</li> <li>AnimalJaw</li> <li>Beak</li> <li>InsectMouth</li> <li>SnakeMouth</li> </HediffTargetBodyPartDefs> <BoundBodyPartGroupDefs> <li>HeadAttackTool</li> <li>Teeth</li> <li>Beak</li> <li>Mouth</li> </BoundBodyPartGroupDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_GagBall.xml
XML
unknown
1,495
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>GagRing</defName> <label>ring gag</label> <description>Ring gag prevents talking, allows oral interaction.</description> <thingClass>rjw.bondage_gear</thingClass> <graphicData> <texPath>Items/GagRing/gag_ring</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <statBases> <MaxHitPoints>150</MaxHitPoints> <Flammability>0.2</Flammability> <DeteriorationRate>1.0</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>550</MarketValue> <Mass>1</Mass> </statBases> <apparel> <bodyPartGroups> <li>Teeth</li> <!-- <li>FullHead</li> --> <!-- <li>Mouth</li> Causes bugs with ApparelUtility.HasPartsToWear --> </bodyPartGroups> <wornGraphicPath>Items/GagRing/GagRing</wornGraphicPath> <layers> <li>Overhead</li> <!-- <li>OnSkin</li> --> </layers> <hatRenderedFrontOfFace>true</hatRenderedFrontOfFace> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <equipped_hediff>OpenGag</equipped_hediff> <gives_gagged_moodlet>true</gives_gagged_moodlet> <HediffTargetBodyPartDefs> <li>Jaw</li> <li>AnimalJaw</li> <li>Beak</li> <li>InsectMouth</li> <li>SnakeMouth</li> </HediffTargetBodyPartDefs> <BoundBodyPartGroupDefs> <li>HeadAttackTool</li> <li>Teeth</li> <li>Beak</li> <li>Mouth</li> </BoundBodyPartGroupDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_GagRing.xml
XML
unknown
1,484
<?xml version="1.0" encoding="utf-8" ?> <Defs> <rjw.bondage_gear_def ParentName="BondageGearBase"> <defName>Legbinder</defName> <label>legbinder</label> <description>legbinder that prevents any pawn it's attached to from using their legs.</description> <thingClass>rjw.armbinder</thingClass> <graphicData> <texPath>Items/Legbinder/Legbinder</texPath> <graphicClass>Graphic_Single</graphicClass> </graphicData> <stuffCategories> <li>Leathery</li> </stuffCategories> <costStuffCount>80</costStuffCount> <statBases> <MaxHitPoints>250</MaxHitPoints> <Flammability>0.5</Flammability> <DeteriorationRate>1.0</DeteriorationRate> <Beauty>-6</Beauty> <MarketValue>550</MarketValue> <Mass>4</Mass> <ArmorRating_Blunt>0.15</ArmorRating_Blunt> <ArmorRating_Sharp>0.25</ArmorRating_Sharp> <Insulation_Cold>-4</Insulation_Cold> </statBases> <apparel> <bodyPartGroups> <li>Waist</li> </bodyPartGroups> <wornGraphicPath>Items/Legbinder/Legbinder</wornGraphicPath> <layers> <li>Middle</li> </layers> <!-- <commonality>0</commonality> --> </apparel> <soul_type>rjw.bondage_gear_soul</soul_type> <equipped_hediff>Legbinder</equipped_hediff> <gives_bound_moodlet>true</gives_bound_moodlet> <blocks_hands>false</blocks_hands> <HediffTargetBodyPartDefs> <li>Leg</li> </HediffTargetBodyPartDefs> <BoundBodyPartGroupDefs> <li>Legs</li> </BoundBodyPartGroupDefs> </rjw.bondage_gear_def> </Defs>
lucci/rjw
1.1/Defs/ThingDefs/Bondage/Items_Bondage_Legbinder.xml
XML
unknown
1,482