repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
supersplat | github_2023 | playcanvas | typescript | Camera.rebuildRenderTargets | rebuildRenderTargets() {
const device = this.scene.graphicsDevice;
const { width, height } = this.scene.targetSize;
const rt = this.entity.camera.renderTarget;
if (rt && rt.width === width && rt.height === height) {
return;
}
// out with the old
if (rt) {
rt.destroyTextureBuffers();
rt.destroy();
this.workRenderTarget.destroy();
this.workRenderTarget = null;
}
const createTexture = (name: string, width: number, height: number, format: number) => {
return new Texture(device, {
name,
width,
height,
format,
mipmaps: false,
minFilter: FILTER_NEAREST,
magFilter: FILTER_NEAREST,
addressU: ADDRESS_CLAMP_TO_EDGE,
addressV: ADDRESS_CLAMP_TO_EDGE
});
};
// in with the new
const colorBuffer = createTexture('cameraColor', width, height, PIXELFORMAT_RGBA8);
const depthBuffer = createTexture('cameraDepth', width, height, PIXELFORMAT_DEPTH);
const renderTarget = new RenderTarget({
colorBuffer,
depthBuffer,
flipY: false,
autoResolve: false
});
this.entity.camera.renderTarget = renderTarget;
this.entity.camera.horizontalFov = width > height;
const workColorBuffer = createTexture('workColor', width, height, PIXELFORMAT_RGBA8);
// create pick mode render target (reuse color buffer)
this.workRenderTarget = new RenderTarget({
colorBuffer: workColorBuffer,
depth: false,
autoResolve: false
});
// set picker render target
this.picker.renderTarget = this.workRenderTarget;
this.scene.events.fire('camera.resize', { width, height });
} | // handle the viewer canvas resizing | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/camera.ts#L356-L413 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Camera.pickFocalPoint | pickFocalPoint(screenX: number, screenY: number) {
const scene = this.scene;
const cameraPos = this.entity.getPosition();
const target = scene.canvas;
const sx = screenX / target.clientWidth * scene.targetSize.width;
const sy = screenY / target.clientHeight * scene.targetSize.height;
const splats = scene.getElementsByType(ElementType.splat);
let closestD = 0;
const closestP = new Vec3();
let closestSplat = null;
for (let i = 0; i < splats.length; ++i) {
const splat = splats[i] as Splat;
this.pickPrep(splat, 'set');
const pickId = this.pick(sx, sy);
if (pickId !== -1) {
splat.calcSplatWorldPosition(pickId, vec);
// create a plane at the world position facing perpendicular to the camera
plane.setFromPointNormal(vec, this.entity.forward);
// create the pick ray in world space
if (this.ortho) {
this.entity.camera.screenToWorld(screenX, screenY, -1.0, vec);
this.entity.camera.screenToWorld(screenX, screenY, 1.0, vecb);
vecb.sub(vec).normalize();
ray.set(vec, vecb);
} else {
this.entity.camera.screenToWorld(screenX, screenY, 1.0, vec);
vec.sub(cameraPos).normalize();
ray.set(cameraPos, vec);
}
// find intersection
if (plane.intersectsRay(ray, vec)) {
const distance = vecb.sub2(vec, ray.origin).length();
if (!closestSplat || distance < closestD) {
closestD = distance;
closestP.copy(vec);
closestSplat = splat;
}
}
}
}
if (closestSplat) {
this.setFocalPoint(closestP);
this.setDistance(closestD / this.sceneRadius * this.fovFactor);
scene.events.fire('camera.focalPointPicked', {
camera: this,
splat: closestSplat,
position: closestP
});
}
} | // intersect the scene at the given screen coordinate and focus the camera on this location | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/camera.ts#L509-L568 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Camera.pickPrep | pickPrep(splat: Splat, op: 'add'|'remove'|'set') {
const { width, height } = this.scene.targetSize;
const worldLayer = this.scene.app.scene.layers.getLayerByName('World');
const device = this.scene.graphicsDevice;
const events = this.scene.events;
const alpha = events.invoke('camera.mode') === 'rings' ? 0.0 : 0.2;
// hide non-selected elements
const splats = this.scene.getElementsByType(ElementType.splat);
splats.forEach((s: Splat) => {
s.entity.enabled = s === splat;
});
device.scope.resolve('pickerAlpha').setValue(alpha);
device.scope.resolve('pickMode').setValue(['add', 'remove', 'set'].indexOf(op));
this.picker.resize(width, height);
this.picker.prepare(this.entity.camera, this.scene.app.scene, [worldLayer]);
// re-enable all splats
splats.forEach((splat: Splat) => {
splat.entity.enabled = true;
});
} | // render picker contents | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/camera.ts#L573-L596 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | dist | const dist = (x0: number, y0: number, x1: number, y1: number) => Math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2); | // calculate the distance between two 2d points | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/controllers.ts#L10-L10 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | isMouseEvent | const isMouseEvent = (deltaX: number, deltaY: number) => {
return (Math.abs(deltaX) > 50 && deltaY === 0) ||
(Math.abs(deltaY) > 50 && deltaX === 0) ||
(deltaX === 0 && deltaY !== 0) && !Number.isInteger(deltaY);
}; | // fuzzy detection of mouse wheel events vs trackpad events | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/controllers.ts#L139-L143 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | DataProcessor.intersect | intersect(options: MaskOptions | RectOptions | SphereOptions, splat: Splat) {
const { device } = this;
const { scope } = device;
const numSplats = splat.splatData.numSplats;
const transformA = splat.entity.gsplat.instance.splat.transformATexture;
const splatTransform = splat.transformTexture;
const transformPalette = splat.transformPalette.texture;
// update view projection matrix
const camera = splat.scene.camera.entity.camera;
this.viewProjectionMat.mul2(camera.projectionMatrix, camera.viewMatrix);
// allocate resources
const resources = this.getIntersectResources(transformA.width, numSplats);
resolve(scope, {
transformA,
splatTransform,
transformPalette,
splat_params: [transformA.width, numSplats],
matrix_model: splat.entity.getWorldTransform().data,
matrix_viewProjection: this.viewProjectionMat.data,
output_params: [resources.texture.width, resources.texture.height]
});
const maskOptions = options as MaskOptions;
if (maskOptions.mask) {
resolve(scope, {
mode: 0,
mask: maskOptions.mask,
mask_params: [maskOptions.mask.width, maskOptions.mask.height]
});
} else {
resolve(scope, {
mask: this.dummyTexture,
mask_params: [0, 0]
});
}
const rectOptions = options as RectOptions;
if (rectOptions.rect) {
resolve(scope, {
mode: 1,
rect_params: [
rectOptions.rect.x1 * 2.0 - 1.0,
rectOptions.rect.y1 * 2.0 - 1.0,
rectOptions.rect.x2 * 2.0 - 1.0,
rectOptions.rect.y2 * 2.0 - 1.0
]
});
} else {
resolve(scope, {
rect_params: [0, 0, 0, 0]
});
}
const sphereOptions = options as SphereOptions;
if (sphereOptions.sphere) {
resolve(scope, {
mode: 2,
sphere_params: [
sphereOptions.sphere.x,
sphereOptions.sphere.y,
sphereOptions.sphere.z,
sphereOptions.sphere.radius
]
});
} else {
resolve(scope, {
sphere_params: [0, 0, 0, 0]
});
}
device.setBlendState(BlendState.NOBLEND);
drawQuadWithShader(device, resources.renderTarget, resources.shader);
const glDevice = device as WebglGraphicsDevice;
glDevice.readPixels(0, 0, resources.texture.width, resources.texture.height, resources.data);
return resources.data;
} | // calculate the intersection of a mask canvas with splat centers | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/data-processor.ts#L229-L311 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | DataProcessor.calcBound | calcBound(splat: Splat, boundingBox: BoundingBox, onlySelected: boolean) {
const device = splat.scene.graphicsDevice;
const { scope } = device;
const numSplats = splat.splatData.numSplats;
const transformA = splat.entity.gsplat.instance.splat.transformATexture;
const splatTransform = splat.transformTexture;
const transformPalette = splat.transformPalette.texture;
const splatState = splat.stateTexture;
this.splatParams[0] = transformA.width;
this.splatParams[1] = transformA.height;
this.splatParams[2] = numSplats;
// get resources
const resources = this.getBoundResources(transformA.width);
resolve(scope, {
transformA,
splatTransform,
transformPalette,
splatState,
splat_params: this.splatParams,
mode: onlySelected ? 0 : 1
});
const glDevice = device as WebglGraphicsDevice;
device.setBlendState(BlendState.NOBLEND);
drawQuadWithShader(device, resources.renderTarget, resources.shader);
glDevice.gl.readPixels(0, 0, transformA.width, 1, resources.minTexture.impl._glFormat, resources.minTexture.impl._glPixelType, resources.minData);
glDevice.setRenderTarget(resources.maxRenderTarget);
glDevice.updateBegin();
glDevice.gl.readPixels(0, 0, transformA.width, 1, resources.maxTexture.impl._glFormat, resources.maxTexture.impl._glPixelType, resources.maxData);
glDevice.updateEnd();
// resolve mins/maxs
const { minData, maxData } = resources;
v1.set(minData[0], minData[1], minData[2]);
v2.set(maxData[0], maxData[1], maxData[2]);
for (let i = 1; i < transformA.width; i++) {
v1.x = Math.min(v1.x, minData[i * 4]);
v1.y = Math.min(v1.y, minData[i * 4 + 1]);
v1.z = Math.min(v1.z, minData[i * 4 + 2]);
v2.x = Math.max(v2.x, maxData[i * 4]);
v2.y = Math.max(v2.y, maxData[i * 4 + 1]);
v2.z = Math.max(v2.z, maxData[i * 4 + 2]);
}
boundingBox.setMinMax(v1, v2);
} | // all visible splats | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/data-processor.ts#L315-L368 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | DataProcessor.calcPositions | calcPositions(splat: Splat) {
const { device } = this;
const { scope } = device;
const numSplats = splat.splatData.numSplats;
const transformA = splat.entity.gsplat.instance.splat.transformATexture;
const splatTransform = splat.transformTexture;
const transformPalette = splat.transformPalette.texture;
// allocate resources
const resources = this.getPositionResources(transformA.width, transformA.height, numSplats);
resolve(scope, {
transformA,
splatTransform,
transformPalette,
splat_params: [transformA.width, numSplats]
});
device.setBlendState(BlendState.NOBLEND);
drawQuadWithShader(device, resources.renderTarget, resources.shader);
const glDevice = device as WebglGraphicsDevice;
glDevice.gl.readPixels(
0, 0,
resources.texture.width,
resources.texture.height,
resources.texture.impl._glFormat,
resources.texture.impl._glPixelType,
resources.data
);
return resources.data;
} | // calculate world-space splat positions | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/data-processor.ts#L371-L404 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | getResetConfirmation | const getResetConfirmation = async () => {
const result = await events.invoke('showPopup', {
type: 'yesno',
header: localize('doc.reset'),
message: localize(events.invoke('scene.dirty') ? 'doc.unsaved-message' : 'doc.reset-message')
});
if (result.action !== 'yes') {
return false;
}
return true;
}; | // show the user a reset confirmation popup | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/doc.ts#L60-L72 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | resetScene | const resetScene = () => {
events.fire('scene.clear');
events.fire('camera.reset');
events.fire('doc.setName', null);
documentFileHandle = null;
}; | // reset the scene | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/doc.ts#L75-L80 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | loadDocument | const loadDocument = async (file: File) => {
events.fire('startSpinner');
try {
// reset the scene
resetScene();
// read the document
/* global JSZip */
// @ts-ignore
const zip = new JSZip();
await zip.loadAsync(file);
const document = JSON.parse(await zip.file('document.json').async('text'));
// run through each splat and load it
for (let i = 0; i < document.splats.length; ++i) {
const filename = `splat_${i}.ply`;
const splatSettings = document.splats[i];
// construct the splat asset
const contents = await zip.file(`splat_${i}.ply`).async('blob');
const url = URL.createObjectURL(contents);
const splat = await scene.assetLoader.loadModel({
url,
filename
});
URL.revokeObjectURL(url);
scene.add(splat);
splat.docDeserialize(splatSettings);
}
// FIXME: trigger scene bound calc in a better way
const tmp = scene.bound;
if (tmp === null) {
console.error('this should never fire');
}
events.invoke('docDeserialize.poseSets', document.poseSets);
events.invoke('docDeserialize.view', document.view);
scene.camera.docDeserialize(document.camera);
} catch (error) {
await events.invoke('showPopup', {
type: 'error',
header: localize('doc.load-failed'),
message: `'${error.message ?? error}'`
});
} finally {
events.fire('stopSpinner');
}
}; | // load the document from the given file | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/doc.ts#L83-L133 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | CreateDropHandler | const CreateDropHandler = (target: HTMLElement, dropHandler: DropHandlerFunc) => {
const dragstart = (ev: DragEvent) => {
ev.preventDefault();
ev.stopPropagation();
ev.dataTransfer.effectAllowed = 'all';
};
const dragover = (ev: DragEvent) => {
ev.preventDefault();
ev.stopPropagation();
ev.dataTransfer.effectAllowed = 'all';
};
const drop = async (ev: DragEvent) => {
ev.preventDefault();
const items = Array.from(ev.dataTransfer.items)
.map(item => item.webkitGetAsEntry())
.filter(v => v);
// resolve directories to files
const entries = await resolveDirectories(items);
const files = await Promise.all(
entries.map((entry) => {
return new Promise<DroppedFile>((resolve, reject) => {
entry.file((entryFile: any) => {
resolve(new DroppedFile(entry.fullPath.substring(1), entryFile));
});
});
})
);
if (files.length > 1) {
// if all files share a common filename prefix, remove it
removeCommonPrefix(files);
}
// finally, call the drop handler
dropHandler(files, ev.shiftKey);
};
target.addEventListener('dragstart', dragstart, true);
target.addEventListener('dragover', dragover, true);
target.addEventListener('drop', drop, true);
}; | // configure drag and drop | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/drop-handler.ts#L77-L123 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | buildIndex | const buildIndex = (total: number, pred: (i: number) => boolean) => {
let num = 0;
for (let i = 0; i < total; ++i) {
if (pred(i)) num++;
}
const result = new Uint32Array(num);
let idx = 0;
for (let i = 0; i < total; ++i) {
if (pred(i)) {
result[idx++] = i;
}
}
return result;
}; | // build an index array based on a boolean predicate over indices | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/edit-ops.ts#L17-L32 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | registerEditorEvents | const registerEditorEvents = (events: Events, editHistory: EditHistory, scene: Scene) => {
const vec = new Vec3();
const vec2 = new Vec3();
const vec4 = new Vec4();
const mat = new Mat4();
// get the list of selected splats (currently limited to just a single one)
const selectedSplats = () => {
const selected = events.invoke('selection') as Splat;
return selected?.visible ? [selected] : [];
};
let lastExportCursor = 0;
// add unsaved changes warning message.
window.addEventListener('beforeunload', (e) => {
if (!events.invoke('scene.dirty')) {
// if the undo cursor matches last export, then we have no unsaved changes
return undefined;
}
const msg = 'You have unsaved changes. Are you sure you want to leave?';
e.returnValue = msg;
return msg;
});
events.on('scene.clear', () => {
scene.clear();
editHistory.clear();
lastExportCursor = 0;
});
events.function('scene.dirty', () => {
return editHistory.cursor !== lastExportCursor;
});
events.on('doc.saved', () => {
lastExportCursor = editHistory.cursor;
});
events.on('camera.mode', () => {
scene.forceRender = true;
});
events.on('camera.overlay', () => {
scene.forceRender = true;
});
events.on('camera.splatSize', () => {
scene.forceRender = true;
});
events.on('view.outlineSelection', () => {
scene.forceRender = true;
});
events.on('view.bands', (bands: number) => {
scene.forceRender = true;
});
events.on('camera.bound', () => {
scene.forceRender = true;
});
// grid.visible
const setGridVisible = (visible: boolean) => {
if (visible !== scene.grid.visible) {
scene.grid.visible = visible;
events.fire('grid.visible', visible);
}
};
events.function('grid.visible', () => {
return scene.grid.visible;
});
events.on('grid.setVisible', (visible: boolean) => {
setGridVisible(visible);
});
events.on('grid.toggleVisible', () => {
setGridVisible(!scene.grid.visible);
});
setGridVisible(scene.config.show.grid);
// camera.fov
const setCameraFov = (fov: number) => {
if (fov !== scene.camera.fov) {
scene.camera.fov = fov;
events.fire('camera.fov', scene.camera.fov);
}
};
events.function('camera.fov', () => {
return scene.camera.fov;
});
events.on('camera.setFov', (fov: number) => {
setCameraFov(fov);
});
// camera.tonemapping
events.function('camera.tonemapping', () => {
return scene.camera.tonemapping;
});
events.on('camera.setTonemapping', (value: string) => {
scene.camera.tonemapping = value;
});
// camera.bound
let bound = scene.config.show.bound;
const setBoundVisible = (visible: boolean) => {
if (visible !== bound) {
bound = visible;
events.fire('camera.bound', bound);
}
};
events.function('camera.bound', () => {
return bound;
});
events.on('camera.setBound', (value: boolean) => {
setBoundVisible(value);
});
events.on('camera.toggleBound', () => {
setBoundVisible(!events.invoke('camera.bound'));
});
// camera.focus
events.on('camera.focus', () => {
const splat = selectedSplats()[0];
if (splat) {
const bound = splat.numSelected > 0 ? splat.selectionBound : splat.localBound;
vec.copy(bound.center);
const worldTransform = splat.worldTransform;
worldTransform.transformPoint(vec, vec);
worldTransform.getScale(vec2);
scene.camera.focus({
focalPoint: vec,
radius: bound.halfExtents.length() * vec2.x,
speed: 1
});
}
});
events.on('camera.reset', () => {
const { initialAzim, initialElev, initialZoom } = scene.config.controls;
const x = Math.sin(initialAzim * Math.PI / 180) * Math.cos(initialElev * Math.PI / 180);
const y = -Math.sin(initialElev * Math.PI / 180);
const z = Math.cos(initialAzim * Math.PI / 180) * Math.cos(initialElev * Math.PI / 180);
const zoom = initialZoom;
scene.camera.setPose(new Vec3(x * zoom, y * zoom, z * zoom), new Vec3(0, 0, 0));
});
// handle camera align events
events.on('camera.align', (axis: string) => {
switch (axis) {
case 'px': scene.camera.setAzimElev(90, 0); break;
case 'py': scene.camera.setAzimElev(0, -90); break;
case 'pz': scene.camera.setAzimElev(0, 0); break;
case 'nx': scene.camera.setAzimElev(270, 0); break;
case 'ny': scene.camera.setAzimElev(0, 90); break;
case 'nz': scene.camera.setAzimElev(180, 0); break;
}
// switch to ortho mode
scene.camera.ortho = true;
});
// returns true if the selected splat has selected gaussians
events.function('selection.splats', () => {
const splat = events.invoke('selection') as Splat;
return splat?.numSelected > 0;
});
events.on('select.all', () => {
selectedSplats().forEach((splat) => {
events.fire('edit.add', new SelectAllOp(splat));
});
});
events.on('select.none', () => {
selectedSplats().forEach((splat) => {
events.fire('edit.add', new SelectNoneOp(splat));
});
});
events.on('select.invert', () => {
selectedSplats().forEach((splat) => {
events.fire('edit.add', new SelectInvertOp(splat));
});
});
events.on('select.pred', (op, pred: (i: number) => boolean) => {
selectedSplats().forEach((splat) => {
events.fire('edit.add', new SelectOp(splat, op, pred));
});
});
const intersectCenters = (splat: Splat, op: 'add'|'remove'|'set', options: any) => {
const data = scene.dataProcessor.intersect(options, splat);
const filter = (i: number) => data[i] === 255;
events.fire('edit.add', new SelectOp(splat, op, filter));
};
events.on('select.bySphere', (op: 'add'|'remove'|'set', sphere: number[]) => {
selectedSplats().forEach((splat) => {
intersectCenters(splat, op, {
sphere: { x: sphere[0], y: sphere[1], z: sphere[2], radius: sphere[3] }
});
});
});
events.on('select.rect', (op: 'add'|'remove'|'set', rect: any) => {
const mode = events.invoke('camera.mode');
selectedSplats().forEach((splat) => {
if (mode === 'centers') {
intersectCenters(splat, op, {
rect: { x1: rect.start.x, y1: rect.start.y, x2: rect.end.x, y2: rect.end.y }
});
} else if (mode === 'rings') {
const { width, height } = scene.targetSize;
scene.camera.pickPrep(splat, op);
const pick = scene.camera.pickRect(
Math.floor(rect.start.x * width),
Math.floor(rect.start.y * height),
Math.floor((rect.end.x - rect.start.x) * width),
Math.floor((rect.end.y - rect.start.y) * height)
);
const selected = new Set<number>(pick);
const filter = (i: number) => {
return selected.has(i);
};
events.fire('edit.add', new SelectOp(splat, op, filter));
}
});
});
let maskTexture: Texture = null;
events.on('select.byMask', (op: 'add'|'remove'|'set', canvas: HTMLCanvasElement, context: CanvasRenderingContext2D) => {
const mode = events.invoke('camera.mode');
selectedSplats().forEach((splat) => {
if (mode === 'centers') {
// create mask texture
if (!maskTexture || maskTexture.width !== canvas.width || maskTexture.height !== canvas.height) {
if (maskTexture) {
maskTexture.destroy();
}
maskTexture = new Texture(scene.graphicsDevice);
}
maskTexture.setSource(canvas);
intersectCenters(splat, op, {
mask: maskTexture
});
} else if (mode === 'rings') {
const mask = context.getImageData(0, 0, canvas.width, canvas.height);
// calculate mask bound so we limit pixel operations
let mx0 = mask.width - 1;
let my0 = mask.height - 1;
let mx1 = 0;
let my1 = 0;
for (let y = 0; y < mask.height; ++y) {
for (let x = 0; x < mask.width; ++x) {
if (mask.data[(y * mask.width + x) * 4 + 3] === 255) {
mx0 = Math.min(mx0, x);
my0 = Math.min(my0, y);
mx1 = Math.max(mx1, x);
my1 = Math.max(my1, y);
}
}
}
const { width, height } = scene.targetSize;
const px0 = Math.floor(mx0 / mask.width * width);
const py0 = Math.floor(my0 / mask.height * height);
const px1 = Math.floor(mx1 / mask.width * width);
const py1 = Math.floor(my1 / mask.height * height);
const pw = px1 - px0 + 1;
const ph = py1 - py0 + 1;
scene.camera.pickPrep(splat, op);
const pick = scene.camera.pickRect(px0, py0, pw, ph);
const selected = new Set<number>();
for (let y = 0; y < ph; ++y) {
for (let x = 0; x < pw; ++x) {
const mx = Math.floor((px0 + x) / width * mask.width);
const my = Math.floor((py0 + y) / height * mask.height);
if (mask.data[(my * mask.width + mx) * 4] === 255) {
selected.add(pick[(ph - y) * pw + x]);
}
}
}
const filter = (i: number) => {
return selected.has(i);
};
events.fire('edit.add', new SelectOp(splat, op, filter));
}
});
});
events.on('select.point', (op: 'add'|'remove'|'set', point: { x: number, y: number }) => {
const { width, height } = scene.targetSize;
const mode = events.invoke('camera.mode');
selectedSplats().forEach((splat) => {
const splatData = splat.splatData;
if (mode === 'centers') {
const x = splatData.getProp('x');
const y = splatData.getProp('y');
const z = splatData.getProp('z');
const splatSize = events.invoke('camera.splatSize');
const camera = scene.camera.entity.camera;
const sx = point.x * width;
const sy = point.y * height;
// calculate final matrix
mat.mul2(camera.camera._viewProjMat, splat.worldTransform);
const filter = (i: number) => {
vec4.set(x[i], y[i], z[i], 1.0);
mat.transformVec4(vec4, vec4);
const px = (vec4.x / vec4.w * 0.5 + 0.5) * width;
const py = (-vec4.y / vec4.w * 0.5 + 0.5) * height;
return Math.abs(px - sx) < splatSize && Math.abs(py - sy) < splatSize;
};
events.fire('edit.add', new SelectOp(splat, op, filter));
} else if (mode === 'rings') {
scene.camera.pickPrep(splat, op);
const pickId = scene.camera.pickRect(
Math.floor(point.x * width),
Math.floor(point.y * height),
1, 1
)[0];
const filter = (i: number) => {
return i === pickId;
};
events.fire('edit.add', new SelectOp(splat, op, filter));
}
});
});
events.on('select.hide', () => {
selectedSplats().forEach((splat) => {
events.fire('edit.add', new HideSelectionOp(splat));
});
});
events.on('select.unhide', () => {
selectedSplats().forEach((splat) => {
events.fire('edit.add', new UnhideAllOp(splat));
});
});
events.on('select.delete', () => {
selectedSplats().forEach((splat) => {
editHistory.add(new DeleteSelectionOp(splat));
});
});
const performSelectionFunc = async (func: 'duplicate' | 'separate') => {
const splats = selectedSplats();
const writer = new BufferWriter();
await serializePly(splats, {
maxSHBands: 3,
selected: true
}, writer);
const buffer = writer.close();
if (buffer) {
const splat = splats[0];
// wrap PLY in a blob and load it
const blob = new Blob([buffer], { type: 'octet/stream' });
const url = URL.createObjectURL(blob);
const { filename } = splat;
const copy = await scene.assetLoader.loadPly({ url, filename });
if (func === 'separate') {
editHistory.add(new MultiOp([
new DeleteSelectionOp(splat),
new AddSplatOp(scene, copy)
]));
} else {
editHistory.add(new AddSplatOp(scene, copy));
}
URL.revokeObjectURL(url);
}
};
// duplicate the current selection
events.on('select.duplicate', async () => {
await performSelectionFunc('duplicate');
});
events.on('select.separate', async () => {
await performSelectionFunc('separate');
});
events.on('scene.reset', () => {
selectedSplats().forEach((splat) => {
editHistory.add(new ResetOp(splat));
});
});
const setAllData = (value: boolean) => {
if (value !== scene.assetLoader.loadAllData) {
scene.assetLoader.loadAllData = value;
events.fire('allData', scene.assetLoader.loadAllData);
}
};
events.function('allData', () => {
return scene.assetLoader.loadAllData;
});
events.on('toggleAllData', (value: boolean) => {
setAllData(!events.invoke('allData'));
});
// camera mode
let activeMode = 'centers';
const setCameraMode = (mode: string) => {
if (mode !== activeMode) {
activeMode = mode;
events.fire('camera.mode', activeMode);
}
};
events.function('camera.mode', () => {
return activeMode;
});
events.on('camera.setMode', (mode: string) => {
setCameraMode(mode);
});
events.on('camera.toggleMode', () => {
setCameraMode(events.invoke('camera.mode') === 'centers' ? 'rings' : 'centers');
});
// camera overlay
let cameraOverlay = scene.config.camera.overlay;
const setCameraOverlay = (enabled: boolean) => {
if (enabled !== cameraOverlay) {
cameraOverlay = enabled;
events.fire('camera.overlay', cameraOverlay);
}
};
events.function('camera.overlay', () => {
return cameraOverlay;
});
events.on('camera.setOverlay', (value: boolean) => {
setCameraOverlay(value);
});
events.on('camera.toggleOverlay', () => {
setCameraOverlay(!events.invoke('camera.overlay'));
});
// splat size
let splatSize = 2;
const setSplatSize = (value: number) => {
if (value !== splatSize) {
splatSize = value;
events.fire('camera.splatSize', splatSize);
}
};
events.function('camera.splatSize', () => {
return splatSize;
});
events.on('camera.setSplatSize', (value: number) => {
setSplatSize(value);
});
// camera fly speed
const setFlySpeed = (value: number) => {
if (value !== scene.camera.flySpeed) {
scene.camera.flySpeed = value;
events.fire('camera.flySpeed', value);
}
};
events.function('camera.flySpeed', () => {
return scene.camera.flySpeed;
});
events.on('camera.setFlySpeed', (value: number) => {
setFlySpeed(value);
});
// outline selection
let outlineSelection = false;
const setOutlineSelection = (value: boolean) => {
if (value !== outlineSelection) {
outlineSelection = value;
events.fire('view.outlineSelection', outlineSelection);
}
};
events.function('view.outlineSelection', () => {
return outlineSelection;
});
events.on('view.setOutlineSelection', (value: boolean) => {
setOutlineSelection(value);
});
// view spherical harmonic bands
let viewBands = scene.config.show.shBands;
const setViewBands = (value: number) => {
if (value !== viewBands) {
viewBands = value;
events.fire('view.bands', viewBands);
}
};
events.function('view.bands', () => {
return viewBands;
});
events.on('view.setBands', (value: number) => {
setViewBands(value);
});
events.function('camera.getPose', () => {
const camera = scene.camera;
const position = camera.entity.getPosition();
const focalPoint = camera.focalPoint;
return {
position: { x: position.x, y: position.y, z: position.z },
target: { x: focalPoint.x, y: focalPoint.y, z: focalPoint.z }
};
});
events.on('camera.setPose', (pose: { position: Vec3, target: Vec3 }, speed = 1) => {
scene.camera.setPose(pose.position, pose.target, speed);
});
// hack: fire events to initialize UI
events.fire('camera.fov', scene.camera.fov);
events.fire('camera.overlay', cameraOverlay);
events.fire('view.bands', viewBands);
const replaceExtension = (filename: string, extension: string) => {
const removeExtension = (filename: string) => {
return filename.substring(0, filename.length - path.getExtension(filename).length);
};
return `${removeExtension(filename)}${extension}`;
};
let compressor: PngCompressor;
events.function('scene.saveScreenshot', async () => {
events.fire('startSpinner');
try {
const renderTarget = scene.camera.entity.camera.renderTarget;
const texture = renderTarget.colorBuffer;
const data = new Uint8Array(texture.width * texture.height * 4);
await texture.read(0, 0, texture.width, texture.height, { renderTarget, data });
// construct the png compressor
if (!compressor) {
compressor = new PngCompressor();
}
// @ts-ignore
const pixels = new Uint8ClampedArray(data.buffer);
// the render buffer contains premultiplied alpha. so apply background color.
const { r, g, b } = events.invoke('bgClr');
for (let i = 0; i < pixels.length; i += 4) {
const a = 255 - pixels[i + 3];
pixels[i + 0] += r * a;
pixels[i + 1] += g * a;
pixels[i + 2] += b * a;
pixels[i + 3] = 255;
}
const arrayBuffer = await compressor.compress(
new Uint32Array(pixels.buffer),
texture.width,
texture.height
);
// construct filename
const filename = replaceExtension(selectedSplats()?.[0]?.filename ?? 'SuperSplat', '.png');
// download
const blob = new Blob([arrayBuffer], { type: 'octet/stream' });
const url = window.URL.createObjectURL(blob);
const el = document.createElement('a');
el.download = filename;
el.href = url;
el.click();
window.URL.revokeObjectURL(url);
} finally {
events.fire('stopSpinner');
}
});
// doc serialization
events.function('docSerialize.view', () => {
const packC = (c: Color) => [c.r, c.g, c.b, c.a];
return {
bgColor: packC(events.invoke('bgClr')),
selectedColor: packC(events.invoke('selectedClr')),
unselectedColor: packC(events.invoke('unselectedClr')),
lockedColor: packC(events.invoke('lockedClr')),
shBands: events.invoke('view.bands'),
centersSize: events.invoke('camera.splatSize'),
outlineSelection: events.invoke('view.outlineSelection'),
showGrid: events.invoke('grid.visible'),
showBound: events.invoke('camera.bound'),
flySpeed: events.invoke('camera.flySpeed')
};
});
events.function('docDeserialize.view', (docView: any) => {
events.fire('setBgClr', new Color(docView.bgColor));
events.fire('setSelectedClr', new Color(docView.selectedColor));
events.fire('setUnselectedClr', new Color(docView.unselectedColor));
events.fire('setLockedClr', new Color(docView.lockedColor));
events.fire('view.setBands', docView.shBands);
events.fire('camera.setSplatSize', docView.centersSize);
events.fire('view.setOutlineSelection', docView.outlineSelection);
events.fire('grid.setVisible', docView.showGrid);
events.fire('camera.setBound', docView.showBound);
events.fire('camera.setFlySpeed', docView.flySpeed);
});
}; | // register for editor and scene events | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/editor.ts#L13-L694 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | selectedSplats | const selectedSplats = () => {
const selected = events.invoke('selection') as Splat;
return selected?.visible ? [selected] : [];
}; | // get the list of selected splats (currently limited to just a single one) | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/editor.ts#L20-L23 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | setGridVisible | const setGridVisible = (visible: boolean) => {
if (visible !== scene.grid.visible) {
scene.grid.visible = visible;
events.fire('grid.visible', visible);
}
}; | // grid.visible | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/editor.ts#L79-L84 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | setCameraFov | const setCameraFov = (fov: number) => {
if (fov !== scene.camera.fov) {
scene.camera.fov = fov;
events.fire('camera.fov', scene.camera.fov);
}
}; | // camera.fov | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/editor.ts#L102-L107 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | setFlySpeed | const setFlySpeed = (value: number) => {
if (value !== scene.camera.flySpeed) {
scene.camera.flySpeed = value;
events.fire('camera.flySpeed', value);
}
}; | // camera fly speed | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/editor.ts#L534-L539 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Events.function | function(name: string, fn: FunctionCallback) {
if (this.functions.has(name)) {
throw new Error(`error: function ${name} already exists`);
}
this.functions.set(name, fn);
} | // declare an editor function | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/events.ts#L9-L14 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Events.invoke | invoke(name: string, ...args: any[]) {
const fn = this.functions.get(name);
if (!fn) {
console.log(`error: function not found '${name}'`);
return;
}
return fn(...args);
} | // invoke an editor function | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/events.ts#L17-L24 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | download | const download = (filename: string, data: Uint8Array) => {
const blob = new Blob([data], { type: 'octet/stream' });
const url = window.URL.createObjectURL(blob);
const lnk = document.createElement('a');
lnk.download = filename;
lnk.href = url;
// create a "fake" click-event to trigger the download
if (document.createEvent) {
const e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
lnk.dispatchEvent(e);
} else {
// @ts-ignore
lnk.fireEvent?.('onclick');
}
window.URL.revokeObjectURL(url);
}; | // download the data to the given filename | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/file-handler.ts#L67-L88 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | sorter | const sorter = (a: any, b: any) => {
const avalue = a.img_name?.match(/\d*$/)?.[0];
const bvalue = b.img_name?.match(/\d*$/)?.[0];
return (avalue && bvalue) ? parseInt(avalue, 10) - parseInt(bvalue, 10) : 0;
}; | // sort entries by trailing number if it exists | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/file-handler.ts#L103-L107 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | initFileHandler | const initFileHandler = (scene: Scene, events: Events, dropTarget: HTMLElement, remoteStorageDetails: RemoteStorageDetails) => {
// returns a promise that resolves when the file is loaded
const handleImport = async (url: string, filename?: string, focusCamera = true, animationFrame = false) => {
try {
if (!filename) {
// extract filename from url if one isn't provided
try {
filename = new URL(url, document.baseURI).pathname.split('/').pop();
} catch (e) {
filename = url;
}
}
const lowerFilename = (filename || url).toLowerCase();
if (lowerFilename.endsWith('.json')) {
await loadCameraPoses(url, filename, events);
} else if (lowerFilename.endsWith('.ply') || lowerFilename.endsWith('.splat')) {
const model = await scene.assetLoader.loadModel({ url, filename, animationFrame });
scene.add(model);
if (focusCamera) scene.camera.focus();
return model;
} else {
throw new Error('Unsupported file type');
}
} catch (error) {
await events.invoke('showPopup', {
type: 'error',
header: localize('popup.error-loading'),
message: `${error.message ?? error} while loading '${filename}'`
});
}
};
events.function('import', (url: string, filename?: string, focusCamera = true, animationFrame = false) => {
return handleImport(url, filename, focusCamera, animationFrame);
});
// create a file selector element as fallback when showOpenFilePicker isn't available
let fileSelector: HTMLInputElement;
if (!window.showOpenFilePicker) {
fileSelector = document.createElement('input');
fileSelector.setAttribute('id', 'file-selector');
fileSelector.setAttribute('type', 'file');
fileSelector.setAttribute('accept', '.ply,.splat');
fileSelector.setAttribute('multiple', 'true');
fileSelector.onchange = async () => {
const files = fileSelector.files;
for (let i = 0; i < files.length; i++) {
const file = fileSelector.files[i];
const url = URL.createObjectURL(file);
await handleImport(url, file.name);
URL.revokeObjectURL(url);
}
};
document.body.append(fileSelector);
}
// create the file drag & drop handler
CreateDropHandler(dropTarget, async (entries, shift) => {
// document load, only support a single file drop
if (entries.length === 1 && entries[0].file?.name?.toLowerCase().endsWith('.ssproj')) {
await events.invoke('doc.dropped', entries[0].file);
return;
}
// filter out non supported extensions
entries = entries.filter((entry) => {
const name = entry.file?.name;
if (!name) return false;
const lowerName = name.toLowerCase();
return lowerName.endsWith('.ply') || lowerName.endsWith('.splat') || lowerName.endsWith('.json');
});
if (entries.length === 0) {
await events.invoke('showPopup', {
type: 'error',
header: localize('popup.error-loading'),
message: localize('popup.drop-files')
});
} else {
// determine if all files share a common filename prefix followed by
// a frame number, e.g. "frame0001.ply", "frame0002.ply", etc.
const isSequence = () => {
// eslint-disable-next-line regexp/no-super-linear-backtracking
const regex = /(.*?)(\d+).ply$/;
const baseMatch = entries[0].file.name?.match(regex);
if (!baseMatch) {
return false;
}
for (let i = 1; i < entries.length; i++) {
const thisMatch = entries[i].file.name?.match(regex);
if (!thisMatch || thisMatch[1] !== baseMatch[1]) {
return false;
}
}
return true;
};
if (entries.length > 1 && isSequence()) {
events.fire('animation.setFrames', entries.map(e => e.file));
events.fire('animation.setFrame', 0);
} else {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
const url = URL.createObjectURL(entry.file);
await handleImport(url, entry.filename);
URL.revokeObjectURL(url);
}
}
}
});
// get the list of visible splats containing gaussians
const getSplats = () => {
return (scene.getElementsByType(ElementType.splat) as Splat[])
.filter(splat => splat.visible)
.filter(splat => splat.numSplats > 0);
};
events.function('scene.allSplats', () => {
return (scene.getElementsByType(ElementType.splat) as Splat[]);
});
events.function('scene.splats', () => {
return getSplats();
});
events.function('scene.empty', () => {
return getSplats().length === 0;
});
events.function('scene.import', async () => {
if (fileSelector) {
fileSelector.click();
} else {
try {
const handles = await window.showOpenFilePicker({
id: 'SuperSplatFileOpen',
multiple: true,
types: [filePickerTypes.ply, filePickerTypes.splat]
});
for (let i = 0; i < handles.length; i++) {
const handle = handles[i];
const file = await handle.getFile();
const url = URL.createObjectURL(file);
await handleImport(url, file.name);
URL.revokeObjectURL(url);
if (i === 0) {
fileHandle = handle;
}
}
} catch (error) {
if (error.name !== 'AbortError') {
console.error(error);
}
}
}
});
// open a folder
events.function('scene.openAnimation', async () => {
try {
const handle = await window.showDirectoryPicker({
id: 'SuperSplatFileOpenAnimation',
mode: 'readwrite'
});
if (handle) {
const files = [];
for await (const value of handle.values()) {
if (value.kind === 'file') {
const file = await value.getFile();
if (file.name.toLowerCase().endsWith('.ply')) {
files.push(file);
}
}
}
events.fire('animation.setFrames', files);
events.fire('animation.setFrame', 0);
}
} catch (error) {
if (error.name !== 'AbortError') {
console.error(error);
}
}
});
events.function('scene.export', async (type: ExportType, outputFilename: string = null, exportType: 'export' | 'saveAs' = 'export') => {
const extensions = {
'ply': '.ply',
'compressed-ply': '.compressed.ply',
'splat': '.splat',
'viewer': '-viewer.html'
};
const removeExtension = (filename: string) => {
return filename.substring(0, filename.length - path.getExtension(filename).length);
};
const replaceExtension = (filename: string, extension: string) => {
return `${removeExtension(filename)}${extension}`;
};
const splats = getSplats();
const splat = splats[0];
let filename = outputFilename ?? replaceExtension(splat.filename, extensions[type]);
const hasFilePicker = window.showSaveFilePicker;
let viewerExportSettings;
if (type === 'viewer') {
// show viewer export options
viewerExportSettings = await events.invoke('show.viewerExportPopup', hasFilePicker ? null : filename);
// return if user cancelled
if (!viewerExportSettings) {
return;
}
if (hasFilePicker) {
filename = replaceExtension(filename, viewerExportSettings.type === 'html' ? '.html' : '.zip');
} else {
filename = viewerExportSettings.filename;
}
}
if (hasFilePicker) {
try {
const filePickerType = type === 'viewer' ? (viewerExportSettings.type === 'html' ? filePickerTypes.htmlViewer : filePickerTypes.packageViewer) : filePickerTypes[type];
const fileHandle = await window.showSaveFilePicker({
id: 'SuperSplatFileExport',
types: [filePickerType],
suggestedName: filename
});
await events.invoke('scene.write', {
type,
stream: await fileHandle.createWritable(),
viewerExportSettings
});
} catch (error) {
if (error.name !== 'AbortError') {
console.error(error);
}
}
} else {
await events.invoke('scene.write', { type, filename, viewerExportSettings });
}
});
const writeScene = async (type: ExportType, writer: Writer, viewerExportSettings?: ViewerExportSettings) => {
const splats = getSplats();
const events = splats[0].scene.events;
const serializeSettings = {
maxSHBands: events.invoke('view.bands')
};
switch (type) {
case 'ply':
await serializePly(splats, serializeSettings, writer);
break;
case 'compressed-ply':
await serializePlyCompressed(splats, serializeSettings, writer);
break;
case 'splat':
await serializeSplat(splats, serializeSettings, writer);
break;
case 'viewer':
await serializeViewer(splats, viewerExportSettings, writer);
break;
}
};
events.function('scene.write', async (options: SceneWriteOptions) => {
events.fire('startSpinner');
try {
// setTimeout so spinner has a chance to activate
await new Promise<void>((resolve) => {
setTimeout(resolve);
});
const { stream, filename, type, viewerExportSettings } = options;
const writer = stream ? new FileStreamWriter(stream) : new DownloadWriter(filename);
await writeScene(type, writer, viewerExportSettings);
await writer.close();
} catch (error) {
await events.invoke('showPopup', {
type: 'error',
header: localize('popup.error-loading'),
message: `${error.message ?? error} while saving file`
});
} finally {
events.fire('stopSpinner');
}
});
}; | // initialize file handler events | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/file-handler.ts#L128-L431 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | handleImport | const handleImport = async (url: string, filename?: string, focusCamera = true, animationFrame = false) => {
try {
if (!filename) {
// extract filename from url if one isn't provided
try {
filename = new URL(url, document.baseURI).pathname.split('/').pop();
} catch (e) {
filename = url;
}
}
const lowerFilename = (filename || url).toLowerCase();
if (lowerFilename.endsWith('.json')) {
await loadCameraPoses(url, filename, events);
} else if (lowerFilename.endsWith('.ply') || lowerFilename.endsWith('.splat')) {
const model = await scene.assetLoader.loadModel({ url, filename, animationFrame });
scene.add(model);
if (focusCamera) scene.camera.focus();
return model;
} else {
throw new Error('Unsupported file type');
}
} catch (error) {
await events.invoke('showPopup', {
type: 'error',
header: localize('popup.error-loading'),
message: `${error.message ?? error} while loading '${filename}'`
});
}
}; | // returns a promise that resolves when the file is loaded | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/file-handler.ts#L131-L160 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | isSequence | const isSequence = () => {
// eslint-disable-next-line regexp/no-super-linear-backtracking
const regex = /(.*?)(\d+).ply$/;
const baseMatch = entries[0].file.name?.match(regex);
if (!baseMatch) {
return false;
}
for (let i = 1; i < entries.length; i++) {
const thisMatch = entries[i].file.name?.match(regex);
if (!thisMatch || thisMatch[1] !== baseMatch[1]) {
return false;
}
}
return true;
}; | // determine if all files share a common filename prefix followed by | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/file-handler.ts#L212-L228 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | getSplats | const getSplats = () => {
return (scene.getElementsByType(ElementType.splat) as Splat[])
.filter(splat => splat.visible)
.filter(splat => splat.numSplats > 0);
}; | // get the list of visible splats containing gaussians | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/file-handler.ts#L245-L249 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | toColor | const toColor = (value: { r: number, g: number, b: number, a: number }) => {
return new Color(value.r, value.g, value.b, value.a);
}; | // initialize colors from application config | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/main.ts#L208-L210 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | getUser | const getUser = async () => {
try {
const urlResponse = await fetch(`${origin}/api/id`);
return urlResponse.ok && (await urlResponse.json() as User);
} catch (e) {
return null;
}
}; | // check whether user is logged in | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/publish.ts#L23-L30 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | kebabize | const kebabize = (s: string) => s.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase()); | // https://stackoverflow.com/a/67243723/2405687 | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/scene-config.ts#L76-L76 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | rec | const rec = (obj: any, path: string) => {
for (const child in obj) {
const childPath = `${path}${path.length ? '.' : ''}${child}`;
const childValue = obj[child];
switch (typeof childValue) {
case 'number':
obj[child] = params.getNumber(childPath) ?? childValue;
break;
case 'boolean':
obj[child] = params.getBool(childPath) ?? childValue;
break;
case 'string':
obj[child] = params.get(childPath) ?? childValue;
break;
case 'object': {
const keys = Object.keys(childValue).sort();
if (cmp(keys, ['a', 'b', 'g', 'r'])) {
obj[child] = params.getColor(childPath) ?? childValue;
} else if (cmp(keys, ['x', 'y', 'z'])) {
obj[child] = params.getVec3(childPath) ?? childValue;
} else {
rec(childValue, childPath);
}
break;
}
default:
rec(childValue, childPath);
break;
}
}
}; | // recurse the object and replace concrete leaf values with overrides | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/scene-config.ts#L132-L162 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Scene.add | add(element: Element) {
if (!element.scene) {
// add the new element
element.scene = this;
element.add();
this.elements.push(element);
// notify all elements of scene addition
this.forEachElement(e => e !== element && e.onAdded(element));
// notify listeners
this.events.fire('scene.elementAdded', element);
}
} | // add a scene element | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/scene.ts#L230-L243 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Scene.remove | remove(element: Element) {
if (element.scene === this) {
// remove from list
this.elements.splice(this.elements.indexOf(element), 1);
// notify listeners
this.events.fire('scene.elementRemoved', element);
// notify all elements of scene removal
this.forEachElement(e => e.onRemoved(element));
element.remove();
element.scene = null;
}
} | // remove an element from the scene | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/scene.ts#L246-L260 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Scene.bound | get bound() {
if (this.boundDirty) {
let valid = false;
this.forEachElement((e) => {
const bound = e.worldBound;
if (bound) {
if (!valid) {
valid = true;
this.boundStorage.copy(bound);
} else {
this.boundStorage.add(bound);
}
}
});
this.boundDirty = false;
this.events.fire('scene.boundChanged', this.boundStorage);
}
return this.boundStorage;
} | // get the scene bound | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/scene.ts#L263-L283 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | sigmoid | const sigmoid = (v: number) => 1 / (1 + Math.exp(-v)); | // used for converting PLY opacity | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L74-L74 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | countGaussians | const countGaussians = (splats: Splat[], filter: GaussianFilter) => {
return splats.reduce((accum, splat) => {
filter.set(splat);
for (let i = 0; i < splat.splatData.numSplats; ++i) {
accum += filter.test(i) ? 1 : 0;
}
return accum;
}, 0);
}; | // count the total number of gaussians given a filter | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L117-L125 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | calcSHBands | const calcSHBands = (data: Set<string>) => {
return { '9': 1, '24': 2, '-1': 3 }[shNames.findIndex(v => !data.has(v))] ?? 0;
}; | // determine the number of sh bands present given an object with 'f_rest_*' properties | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L169-L171 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | SingleSplat.constructor | constructor(members: string[], serializeSettings: SerializeSettings) {
const data: any = {};
members.forEach((name) => {
data[name] = 0;
});
const hasPosition = ['x', 'y', 'z'].every(v => data.hasOwnProperty(v));
const hasRotation = ['rot_0', 'rot_1', 'rot_2', 'rot_3'].every(v => data.hasOwnProperty(v));
const hasScale = ['scale_0', 'scale_1', 'scale_2'].every(v => data.hasOwnProperty(v));
const hasColor = ['f_dc_0', 'f_dc_1', 'f_dc_2'].every(v => data.hasOwnProperty(v));
const hasOpacity = data.hasOwnProperty('opacity');
const dstSHBands = calcSHBands(new Set(Object.keys(data)));
const dstSHCoeffs = shBandCoeffs[dstSHBands];
const tmpSHData = dstSHBands ? new Float32Array(dstSHCoeffs) : null;
type CacheEntry = {
splat: Splat;
transformCache: SplatTransformCache;
srcProps: { [name: string]: Float32Array };
hasTint: boolean;
};
const cacheMap = new Map<Splat, CacheEntry>();
let cacheEntry: CacheEntry;
const read = (splat: Splat, i: number) => {
// get the cached data entry for this splat
if (splat !== cacheEntry?.splat) {
if (!cacheMap.has(splat)) {
const transformCache = new SplatTransformCache(splat, serializeSettings.keepWorldTransform);
const srcPropNames = getVertexProperties(splat.splatData);
const srcSHBands = calcSHBands(srcPropNames);
const srcSHCoeffs = shBandCoeffs[srcSHBands];
// cache the props objects
const srcProps: { [name: string]: Float32Array } = {};
members.forEach((name) => {
const shIndex = shNames.indexOf(name);
if (shIndex >= 0) {
const a = Math.floor(shIndex / dstSHCoeffs);
const b = shIndex % dstSHCoeffs;
srcProps[name] = (b < srcSHCoeffs) ? splat.splatData.getProp(shNames[a * srcSHCoeffs + b]) as Float32Array : null;
} else {
srcProps[name] = splat.splatData.getProp(name) as Float32Array;
}
});
const { blackPoint, whitePoint, brightness, tintClr } = splat;
const hasTint = (!tintClr.equals(Color.WHITE) || blackPoint !== 0 || whitePoint !== 1 || brightness !== 1);
cacheEntry = { splat, transformCache, srcProps, hasTint };
cacheMap.set(splat, cacheEntry);
} else {
cacheEntry = cacheMap.get(splat);
}
}
const { transformCache, srcProps, hasTint } = cacheEntry;
// copy members
members.forEach((name) => {
data[name] = srcProps[name]?.[i] ?? 0;
});
// apply transform palette transforms
const mat = transformCache.getMat(i);
if (hasPosition) {
v.set(data.x, data.y, data.z);
mat.transformPoint(v, v);
[data.x, data.y, data.z] = [v.x, v.y, v.z];
}
if (hasRotation) {
const quat = transformCache.getRot(i);
q.set(data.rot_1, data.rot_2, data.rot_3, data.rot_0).mul2(quat, q);
[data.rot_1, data.rot_2, data.rot_3, data.rot_0] = [q.x, q.y, q.z, q.w];
}
if (hasScale) {
const scale = transformCache.getScale(i);
data.scale_0 = Math.log(Math.exp(data.scale_0) * scale.x);
data.scale_1 = Math.log(Math.exp(data.scale_1) * scale.y);
data.scale_2 = Math.log(Math.exp(data.scale_2) * scale.z);
}
if (dstSHBands > 0) {
for (let c = 0; c < 3; ++c) {
for (let d = 0; d < dstSHCoeffs; ++d) {
tmpSHData[d] = data[shNames[c * dstSHCoeffs + d]];
}
transformCache.getSHRot(i).apply(tmpSHData);
for (let d = 0; d < dstSHCoeffs; ++d) {
data[shNames[c * dstSHCoeffs + d]] = tmpSHData[d];
}
}
}
if (!serializeSettings.keepColorTint && hasColor && hasTint) {
const { blackPoint, whitePoint, brightness, tintClr } = splat;
const SH_C0 = 0.28209479177387814;
const to = (value: number) => value * SH_C0 + 0.5;
const from = (value: number) => (value - 0.5) / SH_C0;
const offset = -blackPoint + brightness;
const scale = 1 / (whitePoint - blackPoint);
const tr = tintClr.r * scale;
const tg = tintClr.g * scale;
const tb = tintClr.b * scale;
data.f_dc_0 = from(offset + to(data.f_dc_0) * tr);
data.f_dc_1 = from(offset + to(data.f_dc_1) * tg);
data.f_dc_2 = from(offset + to(data.f_dc_2) * tb);
if (dstSHBands > 0) {
for (let d = 0; d < dstSHCoeffs; ++d) {
data[shNames[d]] *= tr;
data[shNames[d + dstSHCoeffs]] *= tg;
data[shNames[d + dstSHCoeffs * 2]] *= tb;
}
}
}
const { transparency } = splat;
if (!serializeSettings.keepColorTint && hasOpacity && transparency !== 1) {
const invSig = (value: number) => ((value <= 0) ? -400 : ((value >= 1) ? 400 : -Math.log(1 / value - 1)));
data.opacity = invSig(sigmoid(data.opacity) * transparency);
}
};
this.data = data;
this.read = read;
} | // specify the data members required | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L285-L425 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | clamp | const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v)); | // clamp scale because sometimes values are at infinity | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L594-L594 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | packRot | const packRot = (x: number, y: number, z: number, w: number) => {
q.set(x, y, z, w).normalize();
const a = [q.x, q.y, q.z, q.w];
const largest = a.reduce((curr, v, i) => (Math.abs(v) > Math.abs(a[curr]) ? i : curr), 0);
if (a[largest] < 0) {
a[0] = -a[0];
a[1] = -a[1];
a[2] = -a[2];
a[3] = -a[3];
}
const norm = Math.sqrt(2) * 0.5;
let result = largest;
for (let i = 0; i < 4; ++i) {
if (i !== largest) {
result = (result << 10) | packUnorm(a[i] * norm + 0.5, 10);
}
}
return result;
}; | // pack quaternion into 2,10,10,10 | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L633-L654 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | sortSplats | const sortSplats = (splats: Splat[], indices: CompressedIndex[]) => {
// https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
const encodeMorton3 = (x: number, y: number, z: number) : number => {
const Part1By2 = (x: number) => {
x &= 0x000003ff;
x = (x ^ (x << 16)) & 0xff0000ff;
x = (x ^ (x << 8)) & 0x0300f00f;
x = (x ^ (x << 4)) & 0x030c30c3;
x = (x ^ (x << 2)) & 0x09249249;
return x;
};
return (Part1By2(z) << 2) + (Part1By2(y) << 1) + Part1By2(x);
};
let minx: number;
let miny: number;
let minz: number;
let maxx: number;
let maxy: number;
let maxz: number;
// calculate scene extents across all splats (using sort centers, because they're in world space)
for (let i = 0; i < splats.length; ++i) {
const splat = splats[i];
const splatData = splat.splatData;
const state = splatData.getProp('state') as Uint8Array;
const { centers } = splat.entity.gsplat.instance.sorter;
for (let i = 0; i < splatData.numSplats; ++i) {
if ((state[i] & State.deleted) === 0) {
const x = centers[i * 3 + 0];
const y = centers[i * 3 + 1];
const z = centers[i * 3 + 2];
if (minx === undefined) {
minx = maxx = x;
miny = maxy = y;
minz = maxz = z;
} else {
if (x < minx) minx = x; else if (x > maxx) maxx = x;
if (y < miny) miny = y; else if (y > maxy) maxy = y;
if (z < minz) minz = z; else if (z > maxz) maxz = z;
}
}
}
}
const xlen = maxx - minx;
const ylen = maxy - miny;
const zlen = maxz - minz;
const morton = new Uint32Array(indices.length);
let idx = 0;
for (let i = 0; i < splats.length; ++i) {
const splat = splats[i];
const splatData = splat.splatData;
const state = splatData.getProp('state') as Uint8Array;
const { centers } = splat.entity.gsplat.instance.sorter;
for (let i = 0; i < splatData.numSplats; ++i) {
if ((state[i] & State.deleted) === 0) {
const x = centers[i * 3 + 0];
const y = centers[i * 3 + 1];
const z = centers[i * 3 + 2];
const ix = Math.floor(1024 * (x - minx) / xlen);
const iy = Math.floor(1024 * (y - miny) / ylen);
const iz = Math.floor(1024 * (z - minz) / zlen);
morton[idx++] = encodeMorton3(ix, iy, iz);
}
}
}
// order splats by morton code
indices.sort((a, b) => morton[a.globalIndex] - morton[b.globalIndex]);
}; | // sort the compressed indices into morton order | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L685-L762 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | encodeMorton3 | const encodeMorton3 = (x: number, y: number, z: number) : number => {
const Part1By2 = (x: number) => {
x &= 0x000003ff;
x = (x ^ (x << 16)) & 0xff0000ff;
x = (x ^ (x << 8)) & 0x0300f00f;
x = (x ^ (x << 4)) & 0x030c30c3;
x = (x ^ (x << 2)) & 0x09249249;
return x;
};
return (Part1By2(z) << 2) + (Part1By2(y) << 1) + Part1By2(x);
}; | // https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/ | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat-serialize.ts#L687-L698 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | createTexture | const createTexture = (name: string, format: number) => {
return new Texture(splatResource.device, {
name: name,
width: width,
height: height,
format: format,
mipmaps: false,
minFilter: FILTER_NEAREST,
magFilter: FILTER_NEAREST,
addressU: ADDRESS_CLAMP_TO_EDGE,
addressV: ADDRESS_CLAMP_TO_EDGE
});
}; | // pack spherical harmonic data | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat.ts#L137-L149 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Splat.selectionBound | get selectionBound() {
const selectionBound = this.selectionBoundStorage;
if (this.selectionBoundDirty) {
this.scene.dataProcessor.calcBound(this, selectionBound, true);
this.selectionBoundDirty = false;
}
return selectionBound;
} | // get the selection bound | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat.ts#L429-L436 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Splat.localBound | get localBound() {
const localBound = this.localBoundStorage;
if (this.localBoundDirty) {
this.scene.dataProcessor.calcBound(this, localBound, false);
this.localBoundDirty = false;
this.entity.getWorldTransform().transformPoint(localBound.center, vec);
}
return localBound;
} | // get local space bound | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat.ts#L439-L447 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | Splat.worldBound | get worldBound() {
const worldBound = this.worldBoundStorage;
if (this.worldBoundDirty) {
// calculate meshinstance aabb (transformed local bound)
worldBound.setFromTransformedAabb(this.localBound, this.entity.getWorldTransform());
// flag scene bound as dirty
this.worldBoundDirty = false;
}
return worldBound;
} | // get world space bound | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/splat.ts#L450-L460 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | realloc | const realloc = (width: number, height: number) => {
const newTexture = new Texture(device, {
name: 'transformPalette',
width,
height,
format: PIXELFORMAT_RGBA32F,
mipmaps: false,
addressU: ADDRESS_CLAMP_TO_EDGE,
addressV: ADDRESS_CLAMP_TO_EDGE
});
const newData = newTexture.lock() as Float32Array;
newTexture.unlock();
// copy over data if this is a realloc
if (texture) {
newData.set(data);
texture.destroy();
}
texture = newTexture;
data = newData;
}; | // reallocate the storage texture and copy over old data | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/transform-palette.ts#L33-L56 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | CubicSpline.evaluateSegment | evaluateSegment(segment: number, t: number, result: number[]) {
const { knots, dim } = this;
const t2 = t * t;
const twot = t + t;
const omt = 1 - t;
const omt2 = omt * omt;
let idx = segment * 3 * dim;
for (let i = 0; i < dim; ++i) {
const p0 = knots[idx + 1];
const m0 = knots[idx + 2];
const m1 = knots[idx + 3 * dim];
const p1 = knots[idx + 3 * dim + 1];
idx += 3;
result[i] =
p0 * ((1 + twot) * omt2) +
m0 * (t * omt2) +
p1 * (t2 * (3 - twot)) +
m1 * (t2 * (t - 1));
}
} | // evaluate the spline segment at the given normalized time t | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/anim/spline.ts#L43-L65 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | CubicSpline.fromPoints | static fromPoints(times: number[], points: number[], tension = 0) {
const dim = points.length / times.length;
const knots = new Array<number>(times.length * dim * 3);
for (let i = 0; i < times.length; i++) {
const t = times[i];
for (let j = 0; j < dim; j++) {
const idx = i * dim + j;
const p = points[idx];
let tangent;
if (i === 0) {
tangent = (points[idx + dim] - p) / (times[i + 1] - t);
} else if (i === times.length - 1) {
tangent = (p - points[idx - dim]) / (t - times[i - 1]);
} else {
// finite difference tangents
tangent = 0.5 * ((points[idx + dim] - p) / (times[i + 1] - t) + (p - points[idx - dim]) / (t - times[i - 1]));
// cardinal spline tangents
// tangent = (points[idx + dim] - points[idx - dim]) / (times[i + 1] - times[i - 1]);
}
// apply tension
tangent *= (1.0 - tension);
knots[idx * 3] = tangent;
knots[idx * 3 + 1] = p;
knots[idx * 3 + 2] = tangent;
}
}
return new CubicSpline(times, knots);
} | // tension: level of smoothness, 0 = smooth, 1 = linear interpolation | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/anim/spline.ts#L71-L105 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | ZipWriter.file | async file(filename: string, content: string | Uint8Array) {
// start a new file
await this.start(filename);
// write file contents
await this.write(typeof content === 'string' ? new TextEncoder().encode(content) : content);
} | // helper function to start and write file contents | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/serialize/zip-writer.ts#L17-L23 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | ZipWriter.constructor | constructor(writer: Writer) {
const textEncoder = new TextEncoder();
const files: { filename: Uint8Array, crc: Crc, sizeBytes: number }[] = [];
const writeHeader = async (filename: string) => {
const header = new Uint8Array(30 + filename.length);
const view = new DataView(header.buffer);
const filenameBuf = textEncoder.encode(filename);
view.setUint32(0, 0x04034b50, true);
view.setUint16(6, 0x8, true); // indicate crc and size comes after
view.setUint16(26, filename.length, true);
header.set(filenameBuf, 30);
await writer.write(header);
files.push({ filename: filenameBuf, crc: new Crc(), sizeBytes: 0 });
};
const writeFooter = async () => {
const file = files[files.length - 1];
const { crc, sizeBytes } = file;
const data = new Uint8Array(16);
const view = new DataView(data.buffer);
view.setUint32(0, 0x08074b50, true);
view.setUint32(4, crc.value(), true);
view.setUint32(8, sizeBytes, true);
view.setUint32(12, sizeBytes, true);
await writer.write(data);
};
this.start = async (filename: string) => {
// write previous file footer
if (files.length > 0) {
await writeFooter();
}
await writeHeader(filename);
};
this.write = async (data: Uint8Array, finalWrite?: boolean) => {
const file = files[files.length - 1];
file.sizeBytes += data.length;
file.crc.update(data);
await writer.write(data, finalWrite);
};
this.close = async () => {
// write last file's footer
await writeFooter();
// write cd records
let offset = 0;
for (let i = 0; i < files.length; i++) {
const file = files[i];
const { filename, crc, sizeBytes } = file;
const cdr = new Uint8Array(46 + filename.length);
const view = new DataView(cdr.buffer);
view.setUint32(0, 0x02014b50, true);
view.setUint32(16, crc.value(), true);
view.setUint32(20, sizeBytes, true);
view.setUint32(24, sizeBytes, true);
view.setUint16(28, filename.length, true);
view.setUint32(42, offset, true);
cdr.set(filename, 46);
await writer.write(cdr);
offset += 30 + filename.length + sizeBytes + 16;
}
const filenameLength = files.reduce((tot, file) => tot + file.filename.length, 0);
const dataLength = files.reduce((tot, file) => tot + file.sizeBytes, 0);
// write eocd record
const eocd = new Uint8Array(22);
const eocdView = new DataView(eocd.buffer);
eocdView.setUint32(0, 0x06054b50, true);
eocdView.setUint16(8, files.length, true);
eocdView.setUint16(10, files.length, true);
eocdView.setUint32(12, filenameLength + files.length * 46, true);
eocdView.setUint32(16, filenameLength + files.length * (30 + 16) + dataLength, true);
await writer.write(eocd);
};
} | // write uncompressed data to a zip file using the passed-in writer | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/serialize/zip-writer.ts#L26-L113 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | reattach | const reattach = () => {
if (!active || !events.invoke('selection')) {
gizmo.detach();
} else if (!dragging) {
pivot = events.invoke('pivot') as Pivot;
pivotEntity.setLocalPosition(pivot.transform.position);
pivotEntity.setLocalRotation(pivot.transform.rotation);
pivotEntity.setLocalScale(pivot.transform.scale);
gizmo.attach([pivotEntity]);
}
}; | // reattach the gizmo to the pivot | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/tools/transform-tool.ts#L39-L49 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | updateGizmoSize | const updateGizmoSize = () => {
const { camera, canvas } = scene;
if (camera.ortho) {
gizmo.size = 1125 / canvas.clientHeight;
} else {
gizmo.size = 1200 / Math.max(canvas.clientWidth, canvas.clientHeight);
}
}; | // set the gizmo size to remain a constant size in screen space. | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/tools/transform-tool.ts#L62-L69 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | createSvg | const createSvg = (svgString: string) => {
const decodedStr = decodeURIComponent(svgString.substring('data:image/svg+xml,'.length));
return new DOMParser().parseFromString(decodedStr, 'image/svg+xml').documentElement;
}; | // import cropSvg from './svg/crop.svg'; | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/bottom-toolbar.ts#L15-L18 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | stop | const stop = () => {
posePlay.text = '\uE131';
animHandle.off();
animHandle = null;
}; | // stop the playing animation | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/camera-panel.ts#L114-L118 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | play | const play = () => {
posePlay.text = '\uE135';
// construct the spline points to be interpolated
const times = poses.map((p, i) => i);
const points = [];
for (let i = 0; i < poses.length; ++i) {
const p = poses[i].pose;
points.push(p.position.x, p.position.y, p.position.z);
points.push(p.target.x, p.target.y, p.target.z);
}
// interpolate camera positions and camera target positions
const spline = CubicSpline.fromPoints(times, points);
const result: number[] = [];
const pose = { position: new Vec3(), target: new Vec3() };
let time = 0;
// handle application update tick
animHandle = events.on('update', (dt: number) => {
time = (time + dt) % (poses.length - 1);
// evaluate the spline at current time
spline.evaluate(time, result);
// set camera pose
pose.position.set(result[0], result[1], result[2]);
pose.target.set(result[3], result[4], result[5]);
events.fire('camera.setPose', pose, 0);
});
}; | // start playing the current camera poses animation | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/camera-panel.ts#L203-L233 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | setVisible | const setVisible = (visible: boolean) => {
if (visible === this.hidden) {
this.hidden = !visible;
events.fire('cameraPanel.visible', visible);
}
}; | // handle panel visibility | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/camera-panel.ts#L281-L286 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | setVisible | const setVisible = (visible: boolean) => {
if (visible === this.hidden) {
this.hidden = !visible;
events.fire('colorPanel.visible', visible);
}
}; | // handle panel visibility | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/color-panel.ts#L341-L346 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | sepLabel | const sepLabel = (labelText: string) => {
const container = new Container({
class: 'control-parent',
id: 'sep-container'
});
container.class.add('sep-container');
const label = new Label({
class: 'control-element-expand',
text: labelText
});
container.append(label);
return container;
}; | // build a separator label | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/data-panel.ts#L27-L43 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | dataLabel | const dataLabel = (parent: Container, labelText: string) => {
const container = new Container({
class: 'control-parent'
});
const label = new Label({
class: 'control-label',
text: labelText
});
const value = new Label({
class: 'control-element-expand'
});
container.append(label);
container.append(value);
parent.append(container);
return value;
}; | // build a data label | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/data-panel.ts#L46-L66 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | getValueFunc | const getValueFunc = () => {
// @ts-ignore
const dataFunc = dataFuncs[dataSelector.value];
const data = splat.splatData.getProp(dataSelector.value);
let func: (i: number) => number;
if (dataFunc && data) {
func = i => dataFunc(data[i]);
} else {
switch (dataSelector.value) {
case 'volume': {
const sx = splat.splatData.getProp('scale_0');
const sy = splat.splatData.getProp('scale_1');
const sz = splat.splatData.getProp('scale_2');
func = i => scaleFunc(sx[i]) * scaleFunc(sy[i]) * scaleFunc(sz[i]);
break;
}
case 'distance': {
const x = splat.splatData.getProp('x');
const y = splat.splatData.getProp('y');
const z = splat.splatData.getProp('z');
func = i => Math.sqrt(x[i] ** 2 + y[i] ** 2 + z[i] ** 2);
break;
}
case 'surface-area': {
const sx = splat.splatData.getProp('scale_0');
const sy = splat.splatData.getProp('scale_1');
const sz = splat.splatData.getProp('scale_2');
func = i => scaleFunc(sx[i]) ** 2 + scaleFunc(sy[i]) ** 2 + scaleFunc(sz[i]) ** 2;
break;
}
case 'hue': {
const r = splat.splatData.getProp('f_dc_0');
const g = splat.splatData.getProp('f_dc_1');
const b = splat.splatData.getProp('f_dc_2');
func = i => rgb2hsv({ r: colorFunc(r[i]), g: colorFunc(g[i]), b: colorFunc(b[i]) }).h * 360;
break;
}
case 'saturation': {
const r = splat.splatData.getProp('f_dc_0');
const g = splat.splatData.getProp('f_dc_1');
const b = splat.splatData.getProp('f_dc_2');
func = i => rgb2hsv({ r: colorFunc(r[i]), g: colorFunc(g[i]), b: colorFunc(b[i]) }).s;
break;
}
case 'value': {
const r = splat.splatData.getProp('f_dc_0');
const g = splat.splatData.getProp('f_dc_1');
const b = splat.splatData.getProp('f_dc_2');
func = i => rgb2hsv({ r: colorFunc(r[i]), g: colorFunc(g[i]), b: colorFunc(b[i]) }).v;
break;
}
default:
func = i => data[i];
break;
}
}
return func;
}; | // returns a function which will interpret the splat data for purposes of | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/data-panel.ts#L187-L246 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | reset | const reset = () => {
const splats = events.invoke('scene.splats');
const filename = splats[0].filename;
const dot = splats[0].filename.lastIndexOf('.');
const hasPoses = events.invoke('camera.poses').length > 0;
const bgClr = events.invoke('bgClr');
titleInput.value = filename.slice(0, dot > 0 ? dot : undefined);
descInput.value = '';
listBoolean.value = true;
startSelect.value = hasPoses ? 'pose' : 'viewport';
startSelect.disabledOptions = hasPoses ? { } : { pose: startSelect.options[2].t };
animationSelect.value = hasPoses ? 'track' : 'none';
animationSelect.disabledOptions = hasPoses ? { } : { track: animationSelect.options[1].t };
colorPicker.value = [bgClr.r, bgClr.g, bgClr.b];
fovSlider.value = events.invoke('camera.fov');
bandsSlider.value = events.invoke('view.bands');
}; | // reset UI and configure for current state | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/publish-settings-dialog.ts#L196-L214 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | updateUI | const updateUI = (pivot: Pivot) => {
uiUpdating = true;
const transform = pivot.transform;
transform.rotation.getEulerAngles(v);
positionVector.value = toArray(transform.position);
rotationVector.value = toArray(v);
scaleInput.value = transform.scale.x;
uiUpdating = false;
}; | // update UI with pivot | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/transform.ts#L125-L133 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | updatePivot | const updatePivot = (pivot: Pivot) => {
const p = positionVector.value;
const r = rotationVector.value;
const q = new Quat().setFromEulerAngles(r[0], r[1], r[2]);
const s = scaleInput.value;
if (q.w < 0) {
q.mulScalar(-1);
}
pivot.moveTRS(new Vec3(p[0], p[1], p[2]), q, new Vec3(s, s, s));
}; | // update pivot with UI | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/transform.ts#L136-L147 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | change | const change = () => {
if (!uiUpdating) {
const pivot = events.invoke('pivot') as Pivot;
if (mouseUpdating) {
updatePivot(pivot);
} else {
pivot.start();
updatePivot(pivot);
pivot.end();
}
}
}; | // handle a change in the UI state | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/transform.ts#L150-L161 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
supersplat | github_2023 | playcanvas | typescript | setVisible | const setVisible = (visible: boolean) => {
if (visible === this.hidden) {
this.hidden = !visible;
events.fire('viewPanel.visible', visible);
}
}; | // handle panel visibility | https://github.com/playcanvas/supersplat/blob/ae1a7968fa730954a97c67a97678fdddf17c3ef3/src/ui/view-panel.ts#L294-L299 | ae1a7968fa730954a97c67a97678fdddf17c3ef3 |
ChatterUI | github_2023 | Vali-98 | typescript | verifyJSON | const verifyJSON = (source: any, target: any): any => {
const fillFields = (sourceObj: any, targetObj: any): any => {
if (typeof sourceObj !== 'object' || sourceObj === null) {
sourceObj = Array.isArray(targetObj) ? [] : {}
}
for (const key of Object.keys(targetObj)) {
if (key === 'samplerFields') continue
if (!(key in sourceObj)) {
sourceObj[key] = targetObj[key]
} else if (typeof targetObj[key] === 'object' && targetObj[key] !== null) {
sourceObj[key] = fillFields(sourceObj[key], targetObj[key])
}
}
return sourceObj
}
return fillFields(source, target)
} | // recursively fill json in case it is incorrect | https://github.com/Vali-98/ChatterUI/blob/5b2c715cfa57cc9c7ec969408c71def313554bb9/lib/engine/API/APIManagerState.ts#L104-L120 | 5b2c715cfa57cc9c7ec969408c71def313554bb9 |
ChatterUI | github_2023 | Vali-98 | typescript | insertLogs | const insertLogs = (data: Log) => {
const logs = getLogs()
logs.push(data)
if (logs.length > maxloglength) logs.shift()
mmkv.set(Global.Logs, JSON.stringify(logs))
} | // new api | https://github.com/Vali-98/ChatterUI/blob/5b2c715cfa57cc9c7ec969408c71def313554bb9/lib/state/Logger.ts#L62-L67 | 5b2c715cfa57cc9c7ec969408c71def313554bb9 |
ChatterUI | github_2023 | Vali-98 | typescript | useSpacingState | const useSpacingState = () => {
const spacing = {
xs: 2,
s: 4,
sm: 6,
m: 8,
l: 12,
xl: 16,
xl2: 24,
xl3: 32,
}
return spacing
} | // TODO: State-ify | https://github.com/Vali-98/ChatterUI/blob/5b2c715cfa57cc9c7ec969408c71def313554bb9/lib/theme/ThemeManager.ts#L80-L92 | 5b2c715cfa57cc9c7ec969408c71def313554bb9 |
ChatterUI | github_2023 | Vali-98 | typescript | useFontState | const useFontState = () => {
return ''
} | // TODO: Research fonts | https://github.com/Vali-98/ChatterUI/blob/5b2c715cfa57cc9c7ec969408c71def313554bb9/lib/theme/ThemeManager.ts#L114-L116 | 5b2c715cfa57cc9c7ec969408c71def313554bb9 |
ChatterUI | github_2023 | Vali-98 | typescript | extractChunks | function extractChunks(data: Uint8Array) {
if (data[0] !== 0x89 || data[1] !== 0x50 || data[2] !== 0x4e || data[3] !== 0x47)
throw new Error('Invalid .png file header')
if (data[4] !== 0x0d || data[5] !== 0x0a || data[6] !== 0x1a || data[7] !== 0x0a)
throw new Error(
'Invalid .png file header: possibly caused by DOS-Unix line ending conversion?'
)
let idx = 8
let firstiter = true
const uint8 = new Uint8Array(4)
const int32 = new Int32Array(uint8.buffer)
const uint32 = new Uint32Array(uint8.buffer)
while (idx < data.length) {
uint8[3] = data[idx++]
uint8[2] = data[idx++]
uint8[1] = data[idx++]
uint8[0] = data[idx++]
const length = uint32[0] + 4
const chunk = new Uint8Array(length)
chunk[0] = data[idx++]
chunk[1] = data[idx++]
chunk[2] = data[idx++]
chunk[3] = data[idx++]
// Get the name in ASCII for identification.
const name =
String.fromCharCode(chunk[0]) +
String.fromCharCode(chunk[1]) +
String.fromCharCode(chunk[2]) +
String.fromCharCode(chunk[3])
// The IHDR header MUST come first.
if (firstiter && name !== 'IHDR') {
throw new Error('IHDR header missing')
} else {
firstiter = false
}
// for cui, we only want the tEXt chunk
if (name !== 'tEXt') {
idx += length
continue
}
for (let i = 4; i < length; i++) {
chunk[i] = data[idx++]
}
// Read out the CRC value for comparison.
// It's stored as an Int32.
uint8[3] = data[idx++]
uint8[2] = data[idx++]
uint8[1] = data[idx++]
uint8[0] = data[idx++]
const crcActual = int32[0]
const crcExpect = crc32_buf(chunk)
if (crcExpect !== crcActual) {
throw new Error(
'CRC values for ' + name + ' header do not match, PNG file is likely corrupted'
)
}
// skip the rest of the chunks
return new Uint8Array(chunk.buffer.slice(4))
}
throw new Error('No tEXt chunk found!')
} | /// PNG DATA | https://github.com/Vali-98/ChatterUI/blob/5b2c715cfa57cc9c7ec969408c71def313554bb9/lib/utils/PNG.ts#L13-L89 | 5b2c715cfa57cc9c7ec969408c71def313554bb9 |
serwist | github_2023 | serwist | typescript | resolveEntry | const resolveEntry = (entry: string): string | null => {
if (fs.existsSync(entry)) {
const stats = fs.statSync(entry);
if (stats.isDirectory()) {
return resolveEntry(path.join(entry, "index"));
}
return entry;
}
const dir = path.dirname(entry);
if (fs.existsSync(dir)) {
const base = path.basename(entry);
const files = fs.readdirSync(dir);
const found = files.find((file) => file.replace(/\.[^.]+$/, "") === base);
if (found) return path.join(dir, found);
}
return null;
}; | // Source: https://github.com/sveltejs/kit/blob/6419d3eaa7bf1b0a756b28f06a73f71fe042de0a/packages/kit/src/utils/filesystem.js | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/docs/vite.config.ts#L21-L42 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | buildPlugin | const buildPlugin = (ctx: SerwistViteContext, api: SerwistViteApi) => {
return <Plugin>{
name: "@serwist/vite:build",
apply: "build",
enforce: "pre",
closeBundle: {
sequential: true,
order: ctx.userOptions?.integration?.closeBundleOrder,
async handler() {
if (api && !api.disabled && ctx.viteConfig.build.ssr) {
await api.generateSW();
}
},
},
buildEnd(error) {
if (error) throw error;
},
};
}; | // We do not rely on `@serwist/vite`'s built-in `buildPlugin` because | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/docs/vite.config.ts#L53-L71 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | serwist | const serwist = (): Plugin[] => {
let buildAssetsDir = config.kit?.appDir ?? "_app/";
if (buildAssetsDir[0] === "/") {
buildAssetsDir = buildAssetsDir.slice(1);
}
if (buildAssetsDir[buildAssetsDir.length - 1] !== "/") {
buildAssetsDir += "/";
}
// This part is your Serwist configuration.
const options: PluginOptions = {
// We will set these later in `configureOptions`.
swSrc: null!,
swDest: null!,
swUrl: "/service-worker.js",
// We will set this later in `configureOptions`.
globDirectory: null!,
globPatterns: [
// Static assets.
"client/**/*.{js,css,ico,png,svg,webp,json,webmanifest}",
"prerendered/pages/**/*.html",
"prerendered/dependencies/**/__data.json",
],
globIgnores: ["server/*.*", "client/service-worker.js", "client/_redirects", "client/yoga.wasm", "client/noto-sans-mono.ttf"],
injectionPoint: "self.__SW_MANIFEST",
integration: {
closeBundleOrder: "pre",
// These options depend on `viteConfig`, so we have to use `@serwist/vite`'s configuration hook.
configureOptions(viteConfig, options) {
// Since we don't use `devPlugin`, the service worker is not bundled in development.
const clientOutDir = path.resolve(viteConfig.root, viteConfig.build.outDir, "../client");
// Kit fixes the service worker's name to 'service-worker.js'
// This tells Serwist to replace `injectionPoint` with the precache manifest in the bundled service worker.
options.swSrc = path.resolve(clientOutDir, "service-worker.js");
options.swDest = path.resolve(clientOutDir, "service-worker.js");
// `clientOutDir` is '.svelte-kit/output/client'. However, since we also want to precache prerendered
// pages in the '.svelte-kit/output/prerendered' directory, we have to move one directory up.
options.globDirectory = path.resolve(clientOutDir, "..");
options.manifestTransforms = [
// This `manifestTransform` makes the precache manifest valid.
async (entries) => {
const manifest = entries.map((e) => {
// Static assets are in the ".svelte-kit/output/client" directory.
// Prerender pages are in the ".svelte-kit/output/prerendered/pages" directory.
// Remove the prefix, but keep the ending slash.
if (e.url.startsWith("client/")) {
e.url = e.url.slice(6);
} else if (e.url.startsWith("prerendered/pages/")) {
e.url = e.url.slice(17);
} else if (e.url.startsWith("prerendered/dependencies/")) {
e.url = e.url.slice(24);
}
if (e.url.endsWith(".html")) {
// trailingSlash: 'always'
// https://kit.svelte.dev/docs/page-options#trailingslash
// "/abc/index.html" -> "/abc/"
// "/index.html" -> "/"
if (e.url.endsWith("/index.html")) {
e.url = e.url.slice(0, e.url.lastIndexOf("/") + 1);
}
// trailingSlash: 'ignored'
// trailingSlash: 'never'
// https://kit.svelte.dev/docs/page-options#trailingslash
// "/xxx.html" -> "/xxx"
else {
e.url = e.url.substring(0, e.url.lastIndexOf("."));
}
}
// Finally, prepend `viteConfig.base`.
// "/path" -> "/base/path"
// "/" -> "/base/"
e.url = path.posix.join(viteConfig.base, e.url);
return e;
});
return { manifest };
},
];
},
},
// We don't want to version 'client/_app/immutable/**/*' files because they are
// already versioned by Vite via their URLs.
dontCacheBustURLsMatching: new RegExp(`^client/${buildAssetsDir}immutable/`),
};
const ctx = createContext(options, undefined);
const api = createApi(ctx);
return [mainPlugin(ctx, api), buildPlugin(ctx, api)];
}; | // Here is the main logic: it stores your Serwist configuration, creates `@serwist/vite`'s | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/docs/vite.config.ts#L75-L167 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | processor | const processor = async (res: (value: ItemResult<K>[]) => void) => {
const results: ItemResult<K>[] = [];
while (true) {
const next = work.pop();
if (!next) {
return res(results);
}
const result = await func(next.item);
results.push({
result: result,
index: next.index,
});
}
}; | // Process array items | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/$private/utils/src/parallel.ts#L20-L33 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | runBuildCommand | const runBuildCommand = async ({ config, watch }: BuildCommand) => {
const { count, filePaths, size, warnings } = await injectManifest(config);
for (const warning of warnings) {
logger.warn(warning);
}
if (filePaths.length === 1) {
logger.log(`The service worker file was written to ${config.swDest}`);
} else {
const message = filePaths
.sort()
.map((filePath) => ` • ${filePath}`)
.join("\n");
logger.log(`The service worker files were written to:\n${message}`);
}
logger.log(`The service worker will precache ${count} URLs, ` + `totaling ${prettyBytes(size)}.`);
if (watch) {
logger.log("\nWatching for changes...");
}
}; | /**
* Runs the specified build command with the provided configuration.
*
* @param options
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/cli/src/app.ts#L33-L55 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | getSubdirectories | const getSubdirectories = async (): Promise<string[]> => {
return await glob("*/", {
ignore: constants.ignoredDirectories.map((directory) => `${directory}/`),
});
}; | /**
* @returns The subdirectories of the current
* working directory, with hidden and ignored ones filtered out.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/cli/src/lib/ask-questions.ts#L15-L19 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | getAllFileExtensions | const getAllFileExtensions = async (globDirectory: string) => {
// Use a pattern to match any file that contains a '.', since that signifies
// the presence of a file extension.
const files: string[] = await glob("**/*.*", {
cwd: globDirectory,
nodir: true,
ignore: [
...constants.ignoredDirectories.map((directory) => `**/${directory}/**`),
...constants.ignoredFileExtensions.map((extension) => `**/*.${extension}`),
],
});
const extensions: Set<string> = new Set();
for (const file of files) {
const extension = path.extname(file);
if (extension) {
// Get rid of the leading . character.
extensions.add(extension.replace(/^\./, ""));
}
}
return [...extensions];
}; | /**
* @param globDirectory The directory used for the root of globbing.
* @returns The unique file extensions corresponding
* to all of the files under globDirectory.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/cli/src/lib/ask-questions.ts#L61-L83 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | NavigationRoute.constructor | constructor(handler: RouteHandler, { allowlist = [/./], denylist = [] }: NavigationRouteMatchOptions = {}) {
if (process.env.NODE_ENV !== "production") {
assert!.isArrayOfClass(allowlist, RegExp, {
moduleName: "serwist",
className: "NavigationRoute",
funcName: "constructor",
paramName: "options.allowlist",
});
assert!.isArrayOfClass(denylist, RegExp, {
moduleName: "serwist",
className: "NavigationRoute",
funcName: "constructor",
paramName: "options.denylist",
});
}
super((options: RouteMatchCallbackOptions) => this._match(options), handler);
this._allowlist = allowlist;
this._denylist = denylist;
} | /**
* If both `denylist` and `allowlist` are provided, `denylist` will
* take precedence.
*
* The regular expressions in `allowlist` and `denylist`
* are matched against the concatenated
* [`pathname`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname)
* and [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search)
* portions of the requested URL.
*
* *Note*: These RegExps may be evaluated against every destination URL during
* a navigation. Avoid using
* [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
* or else your users may see delays when navigating your site.
*
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
* @param options
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/NavigationRoute.ts#L59-L79 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | NavigationRoute._match | private _match({ url, request }: RouteMatchCallbackOptions): boolean {
if (request && request.mode !== "navigate") {
return false;
}
const pathnameAndSearch = url.pathname + url.search;
for (const regExp of this._denylist) {
if (regExp.test(pathnameAndSearch)) {
if (process.env.NODE_ENV !== "production") {
logger.log(
`The navigation route ${pathnameAndSearch} is not being used, since the URL matches this denylist pattern: ${regExp.toString()}`,
);
}
return false;
}
}
if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) {
if (process.env.NODE_ENV !== "production") {
logger.debug(`The navigation route ${pathnameAndSearch} is being used.`);
}
return true;
}
if (process.env.NODE_ENV !== "production") {
logger.log(`The navigation route ${pathnameAndSearch} is not being used, since the URL being navigated to doesn't match the allowlist.`);
}
return false;
} | /**
* Routes match handler.
*
* @param options
* @returns
* @private
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/NavigationRoute.ts#L88-L117 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | PrecacheRoute.constructor | constructor(serwist: Serwist, options?: PrecacheRouteOptions) {
const match: RouteMatchCallback = ({ request }: RouteMatchCallbackOptions) => {
const urlsToCacheKeys = serwist.getUrlsToPrecacheKeys();
for (const possibleURL of generateURLVariations(request.url, options)) {
const cacheKey = urlsToCacheKeys.get(possibleURL);
if (cacheKey) {
const integrity = serwist.getIntegrityForPrecacheKey(cacheKey);
return { cacheKey, integrity };
}
}
if (process.env.NODE_ENV !== "production") {
logger.debug(`Precaching did not find a match for ${getFriendlyURL(request.url)}.`);
}
return;
};
super(match, serwist.precacheStrategy);
} | /**
* @param serwist A {@linkcode Serwist} instance.
* @param options Options to control how requests are matched
* against the list of precached URLs.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/PrecacheRoute.ts#L27-L44 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | RegExpRoute.constructor | constructor(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod) {
if (process.env.NODE_ENV !== "production") {
assert!.isInstance(regExp, RegExp, {
moduleName: "serwist",
className: "RegExpRoute",
funcName: "constructor",
paramName: "pattern",
});
}
const match: RouteMatchCallback = ({ url }: RouteMatchCallbackOptions) => {
const result = regExp.exec(url.href);
// Return immediately if there's no match.
if (!result) {
return;
}
// Require that the match start at the first character in the URL string
// if it's a cross-origin request.
// See https://github.com/GoogleChrome/workbox/issues/281 for the context
// behind this behavior.
if (url.origin !== location.origin && result.index !== 0) {
if (process.env.NODE_ENV !== "production") {
logger.debug(
`The regular expression '${regExp.toString()}' only partially matched against the cross-origin URL '${url.toString()}'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.`,
);
}
return;
}
// If the route matches, but there aren't any capture groups defined, then
// this will return [], which is truthy and therefore sufficient to
// indicate a match.
// If there are capture groups, then it will return their values.
return result.slice(1);
};
super(match, handler, method);
} | /**
* If the regular expression contains
* [capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references),
* the captured values will be passed to the `params` argument.
*
* @param regExp The regular expression to match against URLs.
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
* @param method The HTTP method to match the {@linkcode Route} against. Defaults to `GET`.
* against.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/RegExpRoute.ts#L33-L73 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Route.constructor | constructor(match: RouteMatchCallback, handler: RouteHandler, method: HTTPMethod = defaultMethod) {
if (process.env.NODE_ENV !== "production") {
assert!.isType(match, "function", {
moduleName: "serwist",
className: "Route",
funcName: "constructor",
paramName: "match",
});
if (method) {
assert!.isOneOf(method, validMethods, { paramName: "method" });
}
}
// These values are referenced directly by Router so cannot be
// altered by minificaton.
this.handler = normalizeHandler(handler);
this.match = match;
this.method = method;
} | /**
* Constructor for Route class.
*
* @param match A callback function that determines whether the
* route matches a given `fetch` event by returning a truthy value.
* @param handler A callback function that returns a `Promise` resolving
* to a `Response`.
* @param method The HTTP method to match the route against. Defaults
* to `GET`.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Route.ts#L38-L57 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Route.setCatchHandler | setCatchHandler(handler: RouteHandler): void {
this.catchHandler = normalizeHandler(handler);
} | /**
*
* @param handler A callback function that returns a Promise resolving
* to a Response.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Route.ts#L64-L66 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.precacheStrategy | get precacheStrategy(): Strategy {
return this._precacheStrategy;
} | /**
* The strategy used to precache assets and respond to `fetch` events.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L243-L245 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.routes | get routes(): Map<HTTPMethod, Route[]> {
return this._routes;
} | /**
* A `Map` of HTTP method name (`'GET'`, etc.) to an array of all corresponding registered {@linkcode Route}
* instances.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L250-L252 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.addEventListeners | addEventListeners() {
self.addEventListener("install", this.handleInstall);
self.addEventListener("activate", this.handleActivate);
self.addEventListener("fetch", this.handleFetch);
self.addEventListener("message", this.handleCache);
} | /**
* Adds Serwist's event listeners for you. Before calling it, add your own listeners should you need to.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L257-L262 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.addToPrecacheList | addToPrecacheList(entries: (PrecacheEntry | string)[]): void {
if (process.env.NODE_ENV !== "production") {
assert!.isArray(entries, {
moduleName: "serwist",
className: "Serwist",
funcName: "addToCacheList",
paramName: "entries",
});
}
const urlsToWarnAbout: string[] = [];
for (const entry of entries) {
// See https://github.com/GoogleChrome/workbox/issues/2259
if (typeof entry === "string") {
urlsToWarnAbout.push(entry);
} else if (entry && !entry.integrity && entry.revision === undefined) {
urlsToWarnAbout.push(entry.url);
}
const { cacheKey, url } = createCacheKey(entry);
const cacheMode = typeof entry !== "string" && entry.revision ? "reload" : "default";
if (this._urlsToCacheKeys.has(url) && this._urlsToCacheKeys.get(url) !== cacheKey) {
throw new SerwistError("add-to-cache-list-conflicting-entries", {
firstEntry: this._urlsToCacheKeys.get(url),
secondEntry: cacheKey,
});
}
if (typeof entry !== "string" && entry.integrity) {
if (this._cacheKeysToIntegrities.has(cacheKey) && this._cacheKeysToIntegrities.get(cacheKey) !== entry.integrity) {
throw new SerwistError("add-to-cache-list-conflicting-integrities", {
url,
});
}
this._cacheKeysToIntegrities.set(cacheKey, entry.integrity);
}
this._urlsToCacheKeys.set(url, cacheKey);
this._urlsToCacheModes.set(url, cacheMode);
if (urlsToWarnAbout.length > 0) {
const warningMessage = `Serwist is precaching URLs without revision info: ${urlsToWarnAbout.join(
", ",
)}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;
if (process.env.NODE_ENV === "production") {
// Use console directly to display this warning without bloating
// bundle sizes by pulling in all of the logger codebase in prod.
console.warn(warningMessage);
} else {
logger.warn(warningMessage);
}
}
}
} | /**
* Adds items to the precache list, removing duplicates and ensuring the information is valid.
*
* @param entries Array of entries to precache.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L269-L323 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.handleInstall | handleInstall(event: ExtendableEvent): Promise<InstallResult> {
return waitUntil<InstallResult>(event, async () => {
const installReportPlugin = new PrecacheInstallReportPlugin();
this.precacheStrategy.plugins.push(installReportPlugin);
await parallel(this._concurrentPrecaching, Array.from(this._urlsToCacheKeys.entries()), async ([url, cacheKey]): Promise<void> => {
const integrity = this._cacheKeysToIntegrities.get(cacheKey);
const cacheMode = this._urlsToCacheModes.get(url);
const request = new Request(url, {
integrity,
cache: cacheMode,
credentials: "same-origin",
});
await Promise.all(
this.precacheStrategy.handleAll({
event,
request,
url: new URL(request.url),
params: { cacheKey },
}),
);
});
const { updatedURLs, notUpdatedURLs } = installReportPlugin;
if (process.env.NODE_ENV !== "production") {
printInstallDetails(updatedURLs, notUpdatedURLs);
}
return { updatedURLs, notUpdatedURLs };
});
} | /**
* Precaches new and updated assets. Call this method from the service worker's
* `install` event.
*
* Note: this method calls `event.waitUntil()` for you, so you do not need
* to call it yourself in your event handlers.
*
* @param event
* @returns
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L335-L368 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.handleActivate | handleActivate(event: ExtendableEvent): Promise<CleanupResult> {
return waitUntil<CleanupResult>(event, async () => {
const cache = await self.caches.open(this.precacheStrategy.cacheName);
const currentlyCachedRequests = await cache.keys();
const expectedCacheKeys = new Set(this._urlsToCacheKeys.values());
const deletedCacheRequests: string[] = [];
for (const request of currentlyCachedRequests) {
if (!expectedCacheKeys.has(request.url)) {
await cache.delete(request);
deletedCacheRequests.push(request.url);
}
}
if (process.env.NODE_ENV !== "production") {
printCleanupDetails(deletedCacheRequests);
}
return { deletedCacheRequests };
});
} | /**
* Deletes assets that are no longer present in the current precache manifest.
* Call this method from the service worker's `activate` event.
*
* Note: this method calls `event.waitUntil()` for you, so you do not need
* to call it yourself in your event handlers.
*
* @param event
* @returns
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L380-L401 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.handleFetch | handleFetch(event: FetchEvent) {
const { request } = event;
const responsePromise = this.handleRequest({ request, event });
if (responsePromise) {
event.respondWith(responsePromise);
}
} | /**
* Gets a `Response` from an appropriate `Route`'s handler. Call this method
* from the service worker's `fetch` event.
* @param event
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L408-L414 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.handleCache | handleCache(event: ExtendableMessageEvent) {
if (event.data && event.data.type === "CACHE_URLS") {
const { payload }: CacheURLsMessageData = event.data;
if (process.env.NODE_ENV !== "production") {
logger.debug("Caching URLs from the window", payload.urlsToCache);
}
const requestPromises = Promise.all(
payload.urlsToCache.map((entry: string | [string, RequestInit?]) => {
let request: Request;
if (typeof entry === "string") {
request = new Request(entry);
} else {
request = new Request(...entry);
}
return this.handleRequest({ request, event });
}),
);
event.waitUntil(requestPromises);
// If a MessageChannel was used, reply to the message on success.
if (event.ports?.[0]) {
void requestPromises.then(() => event.ports[0].postMessage(true));
}
}
} | /**
* Caches new URLs on demand. Call this method from the service worker's
* `message` event. To trigger the handler, send a message of type `"CACHE_URLS"`
* alongside a list of URLs that should be cached as `urlsToCache`.
* @param event
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L422-L449 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.setDefaultHandler | setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void {
this._defaultHandlerMap.set(method, normalizeHandler(handler));
} | /**
* Define a default handler that's called when no routes explicitly
* match the incoming request.
*
* Each HTTP method (`'GET'`, `'POST'`, etc.) gets its own default handler.
*
* Without a default handler, unmatched requests will go against the
* network as if there were no service worker present.
*
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
* @param method The HTTP method to associate with this default handler. Each method
* has its own default. Defaults to `'GET'`.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L464-L466 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.setCatchHandler | setCatchHandler(handler: RouteHandler): void {
this._catchHandler = normalizeHandler(handler);
} | /**
* If a {@linkcode Route} throws an error while handling a request, this handler
* will be called and given a chance to provide a response.
*
* @param handler A callback function that returns a `Promise` resulting
* in a `Response`.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L475-L477 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.registerCapture | registerCapture<T extends RegExp | string | RouteMatchCallback | Route>(
capture: T,
handler?: T extends Route ? never : RouteHandler,
method?: T extends Route ? never : HTTPMethod,
): Route {
const route = parseRoute(capture, handler, method);
this.registerRoute(route);
return route;
} | /**
* Registers a `RegExp`, string, or function with a caching
* strategy to the router.
*
* @param capture If the capture param is a {@linkcode Route} object, all other arguments will be ignored.
* @param handler A callback function that returns a `Promise` resulting in a `Response`.
* This parameter is required if `capture` is not a {@linkcode Route} object.
* @param method The HTTP method to match the route against. Defaults to `'GET'`.
* @returns The generated {@linkcode Route} object.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L489-L497 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.registerRoute | registerRoute(route: Route): void {
if (process.env.NODE_ENV !== "production") {
assert!.isType(route, "object", {
moduleName: "serwist",
className: "Serwist",
funcName: "registerRoute",
paramName: "route",
});
assert!.hasMethod(route, "match", {
moduleName: "serwist",
className: "Serwist",
funcName: "registerRoute",
paramName: "route",
});
assert!.isType(route.handler, "object", {
moduleName: "serwist",
className: "Serwist",
funcName: "registerRoute",
paramName: "route",
});
assert!.hasMethod(route.handler, "handle", {
moduleName: "serwist",
className: "Serwist",
funcName: "registerRoute",
paramName: "route.handler",
});
assert!.isType(route.method, "string", {
moduleName: "serwist",
className: "Serwist",
funcName: "registerRoute",
paramName: "route.method",
});
}
if (!this._routes.has(route.method)) {
this._routes.set(route.method, []);
}
// Give precedence to all of the earlier routes by adding this additional
// route to the end of the array.
this._routes.get(route.method)!.push(route);
} | /**
* Registers a {@linkcode Route} with the router.
*
* @param route The {@linkcode Route} to register.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L504-L549 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.unregisterRoute | unregisterRoute(route: Route): void {
if (!this._routes.has(route.method)) {
throw new SerwistError("unregister-route-but-not-found-with-method", {
method: route.method,
});
}
const routeIndex = this._routes.get(route.method)!.indexOf(route);
if (routeIndex > -1) {
this._routes.get(route.method)!.splice(routeIndex, 1);
} else {
throw new SerwistError("unregister-route-route-not-registered");
}
} | /**
* Unregisters a route from the router.
*
* @param route The {@linkcode Route} object to unregister.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L556-L569 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.getUrlsToPrecacheKeys | getUrlsToPrecacheKeys(): Map<string, string> {
return this._urlsToCacheKeys;
} | /**
* Returns a mapping of a precached URL to the corresponding cache key, taking
* into account the revision information for the URL.
*
* @returns A URL to cache key mapping.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L577-L579 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.getPrecachedUrls | getPrecachedUrls(): string[] {
return [...this._urlsToCacheKeys.keys()];
} | /**
* Returns a list of all the URLs that have been precached by the current
* service worker.
*
* @returns The precached URLs.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L587-L589 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.getPrecacheKeyForUrl | getPrecacheKeyForUrl(url: string): string | undefined {
const urlObject = new URL(url, location.href);
return this._urlsToCacheKeys.get(urlObject.href);
} | /**
* Returns the cache key used for storing a given URL. If that URL is
* unversioned, like "/index.html", then the cache key will be the original
* URL with a search parameter appended to it.
*
* @param url A URL whose cache key you want to look up.
* @returns The versioned URL that corresponds to a cache key
* for the original URL, or undefined if that URL isn't precached.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L600-L603 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
serwist | github_2023 | serwist | typescript | Serwist.getIntegrityForPrecacheKey | getIntegrityForPrecacheKey(cacheKey: string): string | undefined {
return this._cacheKeysToIntegrities.get(cacheKey);
} | /**
* @param url A cache key whose SRI you want to look up.
* @returns The subresource integrity associated with the cache key,
* or undefined if it's not set.
*/ | https://github.com/serwist/serwist/blob/9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f/packages/core/src/Serwist.ts#L610-L612 | 9dc72e205f8079b7ace12d2d4ea9aad7bc1cb83f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.