@ferret/perspective
Drawing and animating by size on the screen: a ladder of full model, simpler mesh, baked impostor, dot and nothing, with cross-fades, a budget, a frame-time governor, animated impostors and measured thresholds.
Read the guide: how to use it →
Classes
BabylonBackend class
class BabylonBackend implements PerspectiveBackendconstructor(readonly scene: BABYLON.Scene, private readonly o: BabylonBackendOptions = {}) | |
get pointsPass(): PointsPass | undefined | |
represent(entity: Entity, rung: number | string, what: BABYLON.TransformNode | BABYLON.AbstractMesh[] | Representation): Representation | Gives a rung its representation: a node with its meshes, a list of meshes, or any Representation (the impostor). The rung is an index into the entity's ladder or the name / kind of a level. A full rung with none given is the entity's own meshes that no other rung claims. |
representLazy(entity: Entity, rung: number | string, make: () => BABYLON.TransformNode | BABYLON.AbstractMesh[], keepFrames?: number): LazyMeshRepresentation | A rung whose meshes are made by make when it is first shown and disposed after keepFrames frames unused (see LazyMeshRepresentation). Because the entity may then have no meshes at all, give its size with setBounds (the impostor's addImpostor does this by itself from the atlas). |
setBounds(entity: Entity, centre: Point3, radius: number): void | The entity's bounding sphere in its own node's frame, when it cannot be measured from meshes that may not exist. |
async addImpostor(entity: Entity, rung: number | string, src: ImpostorSource): Promise<ImpostorResult> | Gives the entity an impostor at rung. The atlas is the packed bytes if given; else the cache's for this model and options if it has them and they are of this bake version; else the model is baked now (and the result is written to the cache). Entities with the same modelKey and options share one atlas and one draw call. |
cameras(): CameraView[] | the cameras that render this frame |
sphereOf(entity: Entity): Sphere | the bounding sphere of an entity in world space |
frame(entity: Entity, frame: number): void | show frame frame of an animated impostor of the entity |
upOf(entity: Entity): Point3 | the entity's up axis in the world, for the glint of a point |
apply(entity: Entity, ladder: readonly PerspectiveLevel[], f: Fade): void | show the rungs of fade (from fading out, to fading in) for an entity; mix is 1 when the change is over and only to is drawn |
points(list: readonly PointInstance[]): void | the entities at the point level this frame, in one batch (one draw call) |
frameMs(): number | the real time of the last frame, ms, if the backend can measure it |
debug(on: boolean): void | tint every level a colour (debug) |
dispose(): void |
packages/perspective/src/view.ts:172
CoherenceState class
class CoherenceStateWhat is carried from one frame to the next: the boundaries chosen per kind, and the scratch buffers (grown once, then reused).
readonly splits: Map<string, number[]> | |
px: Float64Array<ArrayBuffer> | |
seen: Uint8Array<ArrayBuffer> | |
level: Int16Array<ArrayBuffer> | |
parent: Int32Array<ArrayBuffer> | |
gidx: Int32Array<ArrayBuffer> | |
readonly cells: Map<number, number[]> | |
readonly byKind: Map<string, number[]> | |
ensure(n: number): void | buffers for n items |
list(): number[] | an empty list from the pool (all given back by reset) |
reset(): void |
packages/perspective/src/coherence.ts:51
FrameGovernor class
class FrameGovernorWatches frame times and scales the thresholds: over budget, less detail at the same size; well under, it comes back.
scale: number | |
constructor(readonly cfg: GovernorConfig) | |
record(ms: number): number | undefined | Records a frame; returns the new scale when it changed. |
packages/perspective/src/select.ts:93
ImpostorSet class
class ImpostorSetAll the objects of one baked model: one mesh, one material, thin instances.
readonly mesh: BABYLON.Mesh | |
readonly material: BABYLON.ShaderMaterial | |
domHit: boolean | a hit by the nearest view alone counts (thin parts survive); on by default after measurement |
coverMin: number | |
surfaceEps: number | how far, in radii of the sphere, the depth a view stored may be from a point of the eye ray for the point to be on the surface that view saw (read when a set is made) |
metalDarken: number | how much of the metalness darkens the diffuse term: 1 is the physical model (a metal has none), which is what Babylon's PBR does (read when a set is made) |
hemiSpecular: number | the strength of the hemispheric light's specular lobe (1: as Babylon's PBR) (read when a set is made) |
fogPower: number | the power the fog factor is raised to (see PointsPass.fogPower) |
lightScale: [number, number] | |
debugTint: [number, number, number] | |
constructor(readonly scene: BABYLON.Scene, readonly meta: AtlasMeta, png: Record<string, Uint8Array>) | |
isReady(): boolean | Is every texture loaded (a mesh that uses them draws nothing before). |
add(node: BABYLON.TransformNode): Representation | |
get active(): number | Instances shown now. |
dispose(): void |
packages/perspective/src/impostor.ts:224
LazyMeshRepresentation class
class LazyMeshRepresentation implements RepresentationA rung whose meshes do not exist until it is first shown, and are disposed again after keepFrames frames off (default 120, so a rung at the edge of a threshold does not churn). The scene then never walks the meshes of rungs nobody sees: a far aircraft has no full model at all.
created: number | how many times the meshes were made (for tests and stats) |
constructor(private readonly make: () => BABYLON.TransformNode | BABYLON.AbstractMesh[], readonly keepFrames = 120) | |
get alive(): boolean | |
setState(state: RepState, mix: number): void | |
tint(color: BABYLON.Color3 | null): void | debug: tint the representation (null: remove the tint) |
packages/perspective/src/view.ts:100
MeshRepresentation class
class MeshRepresentation implements RepresentationA set of meshes that is one rung. Visibility is isVisible (the game's own enabling is untouched); what a mesh was before is restored when it is shown.
constructor(readonly meshes: BABYLON.AbstractMesh[]) | |
setState(state: RepState, mix: number): void | |
tint(color: BABYLON.Color3 | null): void | debug: tint the representation (null: remove the tint) |
packages/perspective/src/view.ts:65
PartCuller class
class PartCullerget count(): number | parts that carry a far level now |
minPx: number | |
constructor(private scene: BABYLON.Scene, private o: PartCullOptions = {}) | |
add(root: BABYLON.Node): number | Give every source mesh under root its far level. A mesh already given one is left as it is. Returns how many parts were added. The bounding sphere is read in the world, so a model's own scale counts; root should be in place (scaled) when this is called. |
refit(force: boolean): void | set the distances again when the field of view or the target's height has moved (called each frame by itself; force for a test) |
qualityKnob(maxPx = 4.5, steps = 3): import('@ferret/core').QualityKnob | The pixel threshold as a knob of the quality regulator: a larger one leaves more small far parts undrawn, fewer draw calls and active meshes (both sides of the frame). The scene is never broken: the threshold never goes above maxPx (default 4.5 pixels), below which a part is not seen as a part; the steps are the shares of the way from the start to it. |
dispose(): void | take the levels off again and stop following the view |
packages/perspective/src/parts.ts:26
Perspective class
class Perspective extends Component<PerspectiveParams>Marks an entity as drawn by size on the screen. The component holds only the declaration and the state the service writes (index, fade); it
has no onFixedUpdate, so nothing here can reach the simulation. The service decides in update, before the components' onUpdate.
index: number | the rung shown now (the one fading in while a fade runs) |
fadeFrom: number | the rung fading out, or -1 when no fade runs |
mix: number | 0..1 while a fade runs |
px: number | the size in pixels, last frame |
forced: number | a rung held by perspective.force, or -1 |
phase: number | frames since the service counted this entity, for poseEvery |
animateNow: boolean | set by the service: true when this frame should pose the bones / refresh the presentation at this entity's rate |
gated: boolean | the service has hooked this entity's Animator |
get level(): PerspectiveLevel | |
onAttach() | |
onDetach() |
packages/perspective/src/component.ts:37
PerspectiveService class
class PerspectiveService implements Servicethe plan to 6. Once per rendered frame, in update (never in the fixed step), it measures every tracked entity on the screen, picks its rung
with hysteresis, applies the budget, runs the cross-fades and tells the backend. The simulation does not read anything it writes.
readonly name: "perspective" | |
coherent: boolean | coherent detail on (the constructor's coherent, ?coherent=0 in a game turns it off) |
constructor(private readonly o: PerspectiveOptions) | |
get backend(): PerspectiveBackend | |
get scale(): number | the multiplier now applied to every threshold: tier times governor |
effectiveLadder(ladder: readonly PerspectiveLevel[]): PerspectiveLevel[] | The thresholds in use for a ladder: the tier scales them all; the quality regulator scales only those of the detailed rungs (full, mesh). The threshold where a baked impostor gives way to a point is the one measured at the bake: no regulator moves it, so far things keep their impostors (that is what impostors are made for) and never turn into dots sooner to save a frame. |
qualityKnobs(): import('@ferret/core').QualityKnob[] | knobs for the quality regulator (QualityService finds them): larger thresholds draw far things simpler sooner (both CPU and GPU) |
setTierScale(s: number): void | |
setBudget(b: BudgetLimits): void | |
init(world: World): void | |
track(p: Perspective): void | |
untrack(p: Perspective): void | |
get count(): number | |
list() | |
stats() | |
animate(entityId: string): boolean | True when this frame should refresh the presentation of entityId at its rung's rate (bones, code-driven parts). Entities not tracked animate. |
levelOf(entityId: string) | |
update(dt: number): void | Called once per rendered frame. |
dispose(): void |
packages/perspective/src/service.ts:29
PointsPass class
class PointsPassreadonly mesh: BABYLON.Mesh | |
readonly material: BABYLON.ShaderMaterial | |
drawn: number | |
fogPower: number | the power the fog factor is raised to: 2.2 for PBR meshes (the library's models), 1 for standard materials |
constructor(private readonly scene: BABYLON.Scene) | |
light(): SceneLight | The light the scene gives a surface, as the point colour needs it. |
update(list: readonly PointInstance[], eye: Point3, viewport: [number, number]): void | Draws these points this frame (an empty list hides the pass). |
dispose(): void |
packages/perspective/src/points.ts:122
RecordingBackend class
class RecordingBackend implements PerspectiveBackendA backend that draws nothing and writes down what it was told. Cameras and spheres are set by the test.
readonly log: Recorded[] | |
cams: CameraView[] | |
spheres: Map<string, Sphere> | |
ms: number | undefined | |
debugOn: boolean | |
last: Map<string, Fade> | |
pointList: PointInstance[] | |
frames: Map<string, number> | |
cameras(): CameraView[] | the cameras that render this frame |
sphereOf(e: Entity): Sphere | the bounding sphere of an entity in world space |
apply(e: Entity, _l: readonly PerspectiveLevel[], f: Fade): void | show the rungs of fade (from fading out, to fading in) for an entity; mix is 1 when the change is over and only to is drawn |
points(list: readonly PointInstance[]): void | the entities at the point level this frame, in one batch (one draw call) |
frame(e: Entity, frame: number): void | show frame frame of an animated impostor of the entity |
frameMs(): number | undefined | the real time of the last frame, ms, if the backend can measure it |
debug(on: boolean): void | tint every level a colour (debug) |
packages/perspective/src/backend.ts:52
Functions
applyBudget function
function applyBudget(cands: readonly Candidate[], lim: BudgetLimits): Map<string, number>The budget of detail: at most maxFull entities at full and maxMesh at mesh rungs. The largest on screen keep their rung (ties by id, so that the order never shuffles); the rest step down to the next rung that is not over a limit. Returns the rung per id.
packages/perspective/src/select.ts:60
atlasSize function
function atlasSize(b: ResolvedBake, frames = 1): { w: number; h: number }packages/perspective/src/bake-spec.ts:57
bakeImpostor function
async function bakeImpostor(scene: BABYLON.Scene, root: BABYLON.TransformNode, options: ImpostorBakeOptions = {}, anim?: BakeAnimation): Promise<BakedAtlas>Bakes the model under root: one render per view per map. The root is moved to the origin, unrotated, for the bake and put back after. Nothing in the
scene but the model's meshes is drawn into the maps. hide nodes are left out and replace nodes are shown in place of the ones named (see ImpostorBakeOptions).
packages/perspective/src/bake.ts:95
bakeKey function
function bakeKey(model: Uint8Array, materials: string, o: ImpostorBakeOptions): stringThe key an atlas is cached by: the model bytes, what the materials give (any string the caller derives), the options and the bake version.
packages/perspective/src/bake-spec.ts:60
blurError function
function blurError(a: Rgb, b: Rgb, sky: readonly [number, number, number] | 'border', r = 2): BlurErrorHow far b is from a, with the sky colour sky (sRGB bytes) as the empty picture. Both go through a box blur of radius r first. err is relative to a and so cannot tell a vanishing object from a big one: contrast can.
packages/perspective/src/compare.ts:56
checkLadder function
function checkLadder(ladder: readonly PerspectiveLevel[]): string[]packages/perspective/src/select.ts:17
chooseLevel function
function chooseLevel(ladder: readonly PerspectiveLevel[], current: number, px: number, scale = 1, margin = 0.1): numberThe level for a size, with hysteresis. current is the rung now (an index into the ladder); scale multiplies every threshold (the quality tier and the governor: above 1, detail is given up at larger sizes); margin is the ratio by which a size must pass a threshold to cross it: richer needs px >= minPx * scale * (1 + margin), poorer needs px < minPx * scale * (1 - margin).
packages/perspective/src/select.ts:36
clipFrame function
function clipFrame(t: number, duration: number, frames: number): numberThe frame of a looping clip baked as frames frames, at clip time t of a clip of duration seconds.
packages/perspective/src/octa.ts:56
coherentLevels function
function coherentLevels(items: readonly CoherentItem[], cams: readonly CameraView[], rule: (kind: string) => KindRule, scale = 1, state = new CoherenceState(), budget: BudgetLimits = {}, fits?: (members: readonly number[], level: number, kind: string) => boolean): CoherentResultLevels for items seen by cams, with every threshold times scale, the budget spent per group. state keeps the boundaries between frames (so they do not jump between two gaps of about the same size) and the buffers. fits(members, level, kind) (members as item indexes) lets a drawer with pools of its own refuse a whole group; it is asked only for levels of full and mesh kind, and reserves what it accepts.
packages/perspective/src/coherence.ts:84
decodePng function
async function decodePng(png: Uint8Array): Promise<{ rgba: Uint8Array; width: number; height: number }>Decodes to RGBA bytes (for tests and for tools; the engine loads PNGs straight into textures and never reads them back).
packages/perspective/src/png.ts:34
dilate function
function dilate(maps: Partial<Record<BakeMap, Uint8Array>>, o: { views: number }, width: number, cell: number, passes: number, frames = 1): voidFills the RGB of the texels no view covers with that of the covered texels beside them, passes texels deep, in every maps' cell. Coverage is the colour map's alpha and is not changed.
packages/perspective/src/bake.ts:250
distance function
function distance: (a: Point3, b: Point3) => numberpackages/perspective/src/projection.ts:59
distanceForPx function
function distanceForPx(r: number, px: number, fovY: number, heightPx: number): numberThe distance at which a sphere of radius r covers px pixels (perspective): the inverse of projectedPx.
packages/perspective/src/projection.ts:81
encodePng function
async function encodePng(rgba: Uint8Array, width: number, height: number): Promise<Uint8Array>A PNG of RGBA bytes written by hand (CompressionStream for the zlib part): a canvas premultiplies, and drops the colour of every texel whose alpha is 0, which is exactly the colour the bake bleeds past the silhouette.
packages/perspective/src/png.ts:12
firstLevel function
function firstLevel(ladder: readonly PerspectiveLevel[], px: number, scale = 1): numberThe rung with no hysteresis, for a first choice.
packages/perspective/src/select.ts:44
inView function
function inView(s: Sphere, cam: CameraView): booleanIs any of the sphere inside the camera's view: within the cone that holds the frame's corners, widened by the sphere's own angle. A camera
without forward sees everything (the answer is then always true).
packages/perspective/src/projection.ts:24
ladderFromThresholds function
function ladderFromThresholds(t: MeasuredThresholds, has: { mesh?: boolean } = {}, names: Partial<Record<'full' | 'mesh' | 'impostor' | 'point', string>> = {}): PerspectiveLevel[]The ladder a model's measured thresholds make. A level that would take over at a size not below the one before it is left out (the impostor is then
as good as the simpler mesh up to a size where the mesh is still needed: the mesh rung is dropped). names gives the backend's name of a rung.
packages/perspective/src/thresholds.ts:29
ladderOfModel function
function ladderOfModel(model: LadderModel, o: ModelLadderOptions = {}): ModelRung[]The ladder of a model. A level other than the last needs its measured threshold (the size below which the next level is within tolerance of it): the packer writes them, they are never made up here, and a model that has not been measured throws, naming the levels that miss it. A rung that would take over at a size not below the one before it is left out. The last rung is used down to 0.
packages/perspective/src/model-ladder.ts:34
largestPx function
function largestPx(s: Sphere, cams: readonly CameraView[]): numberThe size for a scene with several cameras (XR eyes, a scope, a mirror): the largest wins, so nothing is drawn thinner than the best view needs.
packages/perspective/src/projection.ts:74
luminance function
function luminance: (r: number, g: number, b: number) => numberrelative luminance of an sRGB byte triple, as linear light
packages/perspective/src/compare.ts:10
measureThreshold function
function measureThreshold(error: (px: number) => number, tol: number, lo = 0.25, hi = 2048, steps = 14): numberThe threshold of a cheaper level (4.4): the smallest size in pixels at which its image differs from the richer one's by no more than tol.
error(px) renders both at that size and returns the difference; it should shrink as px shrinks, which is what makes a cheaper level possible.
Found by bisection on a log scale between lo and hi. If even hi is within the error the answer is hi; if lo is not, it is lo.
packages/perspective/src/bake-spec.ts:72
measureThresholdAsync function
async function measureThresholdAsync(error: (px: number) => Promise<number>, tol: number, lo = 0.25, hi = 2048, steps = 14): Promise<number>measureThreshold for an error that is measured by rendering, which is asynchronous.
packages/perspective/src/bake-spec.ts:84
measureThresholds function
async function measureThresholds(inp: MeasureInput): Promise<MeasuredThresholds>Measures all the thresholds of a model. The levels the model does not have (no loadMesh) come out absent.
packages/perspective/src/measure.ts:151
octaDecode function
function octaDecode(u: number, v: number, mode: OctaMode): Point3The inverse of octaEncode.
packages/perspective/src/octa.ts:19
octaEncode function
function octaEncode(d: Point3, mode: OctaMode): [number, number]A direction (unit, from the object to the viewer) to a point of the unit square. The hemisphere takes y >= 0 only.
packages/perspective/src/octa.ts:8
openMeasureRig function
async function openMeasureRig(inp: MeasureInput): Promise<MeasureRig>Opens the scene the measurement draws in: the model every way it has, over a sky, under fixed light.
packages/perspective/src/measure.ts:71
orderThresholds function
function orderThresholds(t: MeasuredThresholds): MeasuredThresholdsA cheaper level that takes over at a size not below the one before it adds nothing: the level after it is as good as it from there down. Going from the cheapest up, a level whose threshold does not exceed that of the cheaper level kept is dropped (the point, when the object is already invisible where the point stops being within the tolerance).
packages/perspective/src/thresholds.ts:13
packAtlas function
function packAtlas(a: PackedAtlas): Uint8ArrayWrites: magic, u32 meta length, meta as JSON, then per map in the order of meta.options.maps: u32 length and the PNG bytes.
packages/perspective/src/atlas-file.ts:26
packBaked function
async function packBaked(a: BakedAtlas, note?: string): Promise<Uint8Array>Encodes the maps as PNG and packs them with the meta into the bytes that are cached and shipped (atlas-file.ts).
packages/perspective/src/bake.ts:280
pointColor function
function pointColor(p: PointInstance, light: SceneLight, eye: Point3): Point3The colour of a lit object seen from afar: its albedo times the light that falls on a surface turned at random (the ambient plus half the sun, which is the mean of max(N.L, 0) over the sphere of normals), plus the sun's glint off the object's up axis where it has one. Pure; light is the scene's.
packages/perspective/src/points.ts:107
poseEveryOf function
function poseEveryOf(l: PerspectiveLevel): numberpackages/perspective/src/select.ts:29
projectedPx function
function projectedPx(s: Sphere, cam: CameraView): numberThe size in pixels of a sphere on the render target of cam: the tangent of the half angle it subtends over the tangent of half the field of view,
times the target's height (so a sphere that fills the view is heightPx); for an orthographic camera its diameter over the view's height.
Inside the sphere, or at its surface, it fills the view: Infinity.
packages/perspective/src/projection.ts:66
resolveBake function
function resolveBake(o: ImpostorBakeOptions = {}): ResolvedBakepackages/perspective/src/bake-spec.ts:38
sceneLight function
function sceneLight(scene: BABYLON.Scene): SceneLightSums the enabled lights of the scene by kind. Linear colour times intensity, as Babylon's PBR takes them.
packages/perspective/src/points.ts:72
screenHeightPx function
function screenHeightPx(engine: { getRenderHeight(): number; getRenderingCanvas?(): { clientHeight?: number } | null }): numberThe height of the screen in its own pixels (the canvas's CSS height times the device pixel ratio), not of the render target: a level of detail is chosen by how big a thing looks, and a lower render scale (the quality regulator's) must not turn far things into dots or drop parts sooner. Falls back to the render height where there is no canvas.
packages/perspective/src/projection.ts:38
skyOfBorder function
function skyOfBorder(img: Rgb): [number, number, number]The colour of the picture's border (the median of the border pixels, per channel): the sky, when the object is not at the edge.
packages/perspective/src/compare.ts:32
unpackAtlas function
function unpackAtlas(bytes: Uint8Array): PackedAtlasReads what packAtlas wrote. A file of another bake version, or a damaged one, is an error that says which.
packages/perspective/src/atlas-file.ts:39
viewBlend function
function viewBlend(d: Point3, n: number, mode: OctaMode): ViewBlendThe three views to blend for a viewing direction, and their weights (a triangle of the grid cell that holds the direction).
packages/perspective/src/octa.ts:46
viewDirection function
function viewDirection(i: number, j: number, n: number, mode: OctaMode): Point3The direction a view of the N x N grid was baked from: views sit on the grid points (i/(N-1), j/(N-1)), the edges included.
packages/perspective/src/octa.ts:34
viewRect function
function viewRect(b: ResolvedBake, i: number, j: number, frame = 0): { x: number; y: number; w: number; h: number }Where a view lives in one map's atlas. A still atlas is views x views cells; a clip repeats that block once per frame, side by side.
packages/perspective/src/bake-spec.ts:53
Interfaces
AtlasMeta interface
interface AtlasMetaversion: number | |
options: ResolvedBake | |
radius: number | |
centre: Point3 | |
width: number | |
height: number | |
frames: number | |
look: { color: Point3; fill: number } | |
note?: string | the mean of what the colour map covers per view, for tests and the viewer: nothing reads it at run time |
packages/perspective/src/atlas-file.ts:7
BabylonBackendOptions interface
interface BabylonBackendOptionspoints?: boolean | draw the point level (default true) |
fogPower?: number | the power of the fog factor of the points: 2.2 matches PBR meshes (default), 1 matches standard materials |
packages/perspective/src/view.ts:165
BakeAnimation interface
interface BakeAnimationAn animated bake: pose(f) puts the model in frame f of its loop (0..frames-1) before that frame's views are drawn.
frames: number | |
pose(frame: number): void | Promise<void> |
packages/perspective/src/bake.ts:247
BakedAtlas interface
interface BakedAtlasThree maps of RGBA bytes, width x height, rows from the top. color: unlit base colour (sRGB bytes) + coverage; normal: view-space normal x and y * 0.5 + 0.5, and the depth across the sphere (0 near, 1 far) in blue; orm: occlusion, roughness, metallic.
options: ResolvedBake | |
radius: number | the bounding sphere radius the views were framed with, metres |
centre: Point3 | the bounding sphere's centre in the root's frame |
width: number | |
height: number | |
frames: number | |
maps: Partial<Record<BakeMap, Uint8Array>> | |
look: { color: Point3; fill: number } | mean linear albedo of what the views cover, and the share of the bounding disc they cover (averaged over the views) |
packages/perspective/src/bake.ts:13
BlurError interface
interface BlurErrorerr: number | the sum of the absolute differences of the blurred luminances over the sum of how far the first one is from the sky: 0 the same, 1 as much as a missing object |
massRatio: number | the blurred "mass" (the sum of the distance from the sky) of the second over the first: 1 is the same brightness overall |
shift: number | the distance in pixels between the two centres of mass |
contrast: number | the first image's mass in units of the sky's own luminance: the size of the object's contrast, whatever it looks like (the absolute measure the "none" level is cut by) |
packages/perspective/src/compare.ts:41
BudgetLimits interface
interface BudgetLimitsmaxFull?: number | |
maxMesh?: number |
packages/perspective/src/select.ts:52
CameraView interface
interface CameraViewWhat the rule needs to know about one camera that renders the scene this frame.
position: Point3 | |
fovY: number | vertical field of view, radians (perspective) |
heightPx: number | height of the render target in pixels, render scale included |
orthoHeight?: number | orthographic cameras: the height of the view in world units (then fovY is ignored) |
forward?: Point3 | where the camera looks (a unit vector) and the width over the height of its target: with them inView can tell what is in the frame |
aspect?: number |
packages/perspective/src/projection.ts:7
Candidate interface
interface Candidateid: string | |
px: number | |
ladder: readonly PerspectiveLevel[] | |
want: number |
packages/perspective/src/select.ts:54
CoherentGroup interface
interface CoherentGroupkind: string | |
members: number[] | the members, as indexes into the items given |
px: number | screen size of the largest member, pixels |
level: number |
packages/perspective/src/coherence.ts:41
CoherentItem interface
interface CoherentItemid: string | |
kind: string | what is compared with what: a model id, 'tommy', 'lifeboat'. Items of different kinds never group or snap together |
centre: Point3 | |
radius: number | |
ladder: readonly PerspectiveLevel[] | |
current: number | the level shown now, -1 before the first choice |
packages/perspective/src/coherence.ts:21
CoherentResult interface
interface CoherentResultlevelAt: Int16Array | the level of item i (in the order of items); valid until the next call with the same state |
pxAt: Float64Array | the screen size of item i, pixels; valid until the next call with the same state |
groups: CoherentGroup[] | the groups in the frame (a thing out of the frame stands alone and is not listed) |
packages/perspective/src/coherence.ts:68
Fade interface
interface FadeA cross-fade between two rungs. mix goes 0 to 1: from fades out and to fades in (a dither in screen space).
from: number | |
to: number | |
mix: number |
packages/perspective/src/select.ts:50
GovernorConfig interface
interface GovernorConfigbudgetMs: number | the frame time that is too long, ms |
window?: number | frames in a window (default 60) |
down?: number | windows over budget in a row before the thresholds go up (default 2), windows well under it before they come back (default 4) |
up?: number | |
maxScale?: number | the largest scale (default 4) and the step ratio (default 1.25) |
step?: number |
packages/perspective/src/select.ts:79
ImpostorBakeOptions interface
interface ImpostorBakeOptionsviews?: number | views per side of the octahedral grid (default 12) |
cell?: number | pixels per view side (default 128) |
mode?: OctaMode | a model that stays upright is baked over the upper hemisphere only (default 'sphere') |
hide?: string[] | node names left out of the bake (a spinning propeller) |
replace?: Record<string, string> | node name -> node name of a substitute drawn in its place (the propeller disc) |
radius?: number | bounding sphere radius, metres; default: from the model |
maps?: BakeMap[] | maps baked (default all three) |
clips?: Record<string, number> | frames per looping clip for animated impostors: clip name -> frames. Empty: a still impostor |
flat?: boolean | drawn as flat pictures: the nearest views' pictures blended on the billboard, no depth march (for people and animals, which have no thin parts to find: no holes, a third of the cost) |
packages/perspective/src/bake-spec.ts:11
ImpostorResult interface
interface ImpostorResultset: ImpostorSet | |
meta: AtlasMeta | |
fromCache: boolean | |
key: string | null |
packages/perspective/src/view.ts:163
ImpostorSource interface
interface ImpostorSourceWhere an impostor's atlas comes from: bytes already packed (a library asset, a .ferret package), or the model to bake.
bytes?: Uint8Array | packed atlas bytes (atlas-file.ts): used as they are |
root?: BABYLON.TransformNode | the loaded model to bake when there are no bytes (or the cache has none) |
options?: ImpostorBakeOptions | |
modelKey?: string | a string that names this model and its content (the file's url and hash): with the options it is the cache key, and entities of the same model share one atlas |
cache?: CacheBackend | the persistent cache (@ferret/assets): read before baking, written after |
anim?: BakeAnimation | an animated impostor: the frames of the looping clip and how to pose the model in each (the frame count is part of the cache key) |
node?: BABYLON.TransformNode | the node the impostor follows (default: the entity's): a node placed where the model's own frame is, when the atlas was baked in that frame (a library atlas) and the entity's node holds the model turned or moved |
packages/perspective/src/view.ts:146
KindRule interface
interface KindRulelink?: number | metres: two things of the kind closer than this belong to one group (0: no groups, each thing alone) |
gap?: number | the ratio of screen size around a threshold within which its boundary looks for the largest gap (default 1.4) |
margin?: number | the hysteresis of a lone group's level, as a share of the threshold (default 0.1) |
packages/perspective/src/coherence.ts:32
LadderModel interface
interface LadderModelWhat the ladder needs of a resolved model (ResolvedModel.model of @ferret/assets is one).
id?: string | |
levels?: { file: string; maxTier?: ModelTier; thresholds?: { px: number; tolerance: number } }[] | |
impostors?: Record<string, { thresholds?: { impostor?: number; point?: number; none?: number; tolerance: number } } | null> |
packages/perspective/src/model-ladder.ts:8
MeasuredError interface
interface MeasuredErrorrel: number | blurError.err: relative to the full image |
contrast: number | the full image's contrast, in pixels of sky brightness |
judged: number | what the measurement is judged by: rel weighted by how visible the object is (an object too faint to see cannot be wrong in a way anyone sees); for 'none' the contrast of the full image itself, the size of what is left out |
massRatio: number | the blurred mass of the picture over the full one's, and the distance between the two centres of mass, px (means over the directions) |
shift: number | |
perDirection: number[] | rel of each direction, in the order of the directions |
packages/perspective/src/measure.ts:47
MeasuredThresholds interface
interface MeasuredThresholdsmesh?: number | |
impostor?: number | |
point?: number | |
none?: number | |
tolerance: number |
packages/perspective/src/thresholds.ts:6
MeasureInput interface
interface MeasureInputengine: BABYLON.AbstractEngine | |
loadFull(scene: BABYLON.Scene): Promise<BABYLON.TransformNode> | a fresh copy of the model's full mesh and of its simpler mesh, in the scene given (the simpler may be absent: then there is no mesh level) |
loadMesh?(scene: BABYLON.Scene): Promise<BABYLON.TransformNode> | |
atlas: Uint8Array | the packed atlas of the model (atlas-file.ts) |
tolerance?: number | the error a cheaper level may have against the richer image (default 0.05); the none level takes it as an absolute contrast, in pixels of sky brightness |
directions?: Array<[number, number] | [number, number, number]> | viewing directions: [yaw, pitch] of the model, or [x, y, z] of the direction from the model to the eye in the model's own frame (default eight spread over the sphere) |
lights?: { hemi: number; sun: number } | the strength of the two lights (default hemispheric 0.55, sun 1.0) |
maxPx?: number | the biggest size measured, px (default 300: the object must fit the window) |
onImage?(label: string, dataUrl: string): void | called with each rendered picture (a data URL), for looking at what is compared |
onCurve?(level: 'mesh' | 'impostor' | 'point' | 'none', samples: Array<[number, number]>): void |
packages/perspective/src/measure.ts:14
MeasureRig interface
interface MeasureRighasMesh: boolean | is there a simpler mesh to measure |
shoot(v: Variant, dir: readonly number[], px: number): Promise<Rgb> | |
error(v: Exclude<Variant, 'full'>, px: number): Promise<MeasuredError> | the mean over the directions of how far variant v is from the full model at size px |
dispose(): void |
packages/perspective/src/measure.ts:61
ModelLadderOptions interface
interface ModelLadderOptionstier?: ModelTier | the device tier: which levels may be loaded (default desktop) |
impostor?: string | the impostor the far rungs use (default default); none when the model has none of that name |
packages/perspective/src/model-ladder.ts:22
ModelRung interface
interface ModelRung extends PerspectiveLevelA rung of a model's ladder: which level of the model it draws, or which impostor.
level?: number | the model's level index (the rungs of kind full and mesh) |
impostor?: string | the impostor's name (the rung of kind impostor) |
packages/perspective/src/model-ladder.ts:15
PackedAtlas interface
interface PackedAtlasA packed atlas: the meta and, per map, the PNG bytes.
packages/perspective/src/atlas-file.ts:21
PartCullOptions interface
interface PartCullOptionsSmall parts of a model are not drawn when they are smaller than a few pixels.
A glTF model of a boat or a gun is dozens of primitives (rails, fittings, gear, detail), each its own draw call however many instances of the model there are. At a few hundred metres every one of them is a speck, and Babylon still submits it. Here each source mesh of a model gets Babylon's own level of detail with nothing as its far level (addLODLevel(distance, null)), the distance being where the part's bounding sphere covers minPx pixels: Babylon then drops it before it evaluates the mesh (instances use their source's levels, each by its own distance).
The distance depends on the field of view and the height of the render target, so it is set again when either moves by more than a twentieth. A part that is skinned, has thin instances or is not a plain mesh is left alone.
minPx?: number | a part smaller than this many pixels is not drawn (default 2) |
heightPx?: () => number | the height of the render target in pixels (default: the engine's render height) |
fov?: () => number | the vertical field of view, rad (default: the active camera's) |
packages/perspective/src/parts.ts:15
PerspectiveBackend interface
interface PerspectiveBackendcameras(): CameraView[] | the cameras that render this frame |
sphereOf(entity: Entity): Sphere | the bounding sphere of an entity in world space |
apply(entity: Entity, ladder: readonly PerspectiveLevel[], fade: Fade): void | show the rungs of fade (from fading out, to fading in) for an entity; mix is 1 when the change is over and only to is drawn |
points(list: readonly PointInstance[]): void | the entities at the point level this frame, in one batch (one draw call) |
frame?(entity: Entity, frame: number): void | show frame frame of an animated impostor of the entity |
upOf?(entity: Entity): Point3 | the entity's up axis in the world, for the glint of a point |
frameMs?(): number | undefined | the real time of the last frame, ms, if the backend can measure it |
debug?(on: boolean): void | tint every level a colour (debug) |
dispose?(): void |
packages/perspective/src/backend.ts:26
PerspectiveLevel interface
interface PerspectiveLevelOne rung of an entity's ladder. The ladder is ordered richest first; a rung is used from minPx up.
kind: LevelKind | |
name?: string | a name the backend knows it by: the mesh lod1, the impostor atlas ... |
minPx: number | used when the projected size is at least this many pixels |
poseEvery?: number | the bones are posed every poseEvery frames (1: every frame); 0: never. Default: 1 at full and mesh, 0 below |
packages/perspective/src/select.ts:7
PerspectiveOptions interface
interface PerspectiveOptionsbackend: PerspectiveBackend | |
tierScale?: number | a multiplier of every threshold from the quality tier (default 1); set again with setTierScale |
budget?: BudgetLimits | |
governor?: GovernorConfig | the frame-time governor; without it the thresholds only move with the tier |
coherent?: boolean | coherent detail: groups and peers drawn alike (default true; false chooses each entity alone, as before) |
packages/perspective/src/service.ts:11
PerspectiveParams interface
interface PerspectiveParamsladder: PerspectiveLevel[] | the rungs, richest first (see PerspectiveLevel); the last must have minPx 0 |
fade?: number | seconds of the cross-fade between two rungs (default 0.25); 0 switches at once |
margin?: number | the ratio by which a size must pass a threshold to cross it (default 0.1) |
radius?: number | bounding sphere radius override, metres; default: what the backend measures |
color?: [number, number, number] | the mean albedo drawn for the object at the point level, linear rgb (default a mid grey) |
glint?: number | the sun's glint on the object at the point level, 0..1 (default 0) |
loop?: { duration: number; frames: number } | an animated impostor: the looping clip's length in seconds and the frames baked of it. The frame shown is picked from clock (default: the service's own time) |
clock?: () => number | the time in seconds of the clip's loop for this entity (e.g. its Animator's clock); default the service's time, so objects without one all walk in step |
fill?: number | the share of the bounding sphere's disc that the object's silhouette fills, averaged over the directions (0..1, default 1); the bake measures it. The point level draws a disc of the object's own area, not of its bounding sphere's |
coherence?: { kind?: string; link?: number; gap?: number } | Coherent detail: kind names what this is compared with (things of one kind at about one distance are drawn alike; default:
the things with the same ladder), link the metres within which things of the kind stand together as one group with one level (default 0: alone). |
packages/perspective/src/component.ts:6
PointInstance interface
interface PointInstanceOne thing drawn as a point this frame.
id: string | |
position: Point3 | |
coverage: number | the share of its pixel the object covers, 0..1 (below one pixel: the squared size) |
px: number | the diameter in pixels of the disc that has the object's own area (its size times the root of its fill) |
alpha: number | the fade of the point in or out, 0..1 |
color?: Point3 | the mean albedo of the object, linear rgb 0..1 (default a mid grey) |
glint?: number | how strongly the sun glints off it, 0..1 (0: never); the flash is strongest when the half vector of the sun and the eye lies along up |
up?: Point3 | the object's up axis in the world, for the glint |
packages/perspective/src/backend.ts:9
Representation interface
interface RepresentationSomething a rung draws. Meshes implement it here; the impostor implements it in impostor.ts.
setState(state: RepState, mix: number): void | |
setFrame?(f: number): void | an animated impostor: show frame f of the baked loop (a still atlas ignores it) |
tint?(color: BABYLON.Color3 | null): void | debug: tint the representation (null: remove the tint) |
packages/perspective/src/view.ts:20
ResolvedBake interface
interface ResolvedBakeviews: number | |
cell: number | |
mode: OctaMode | |
hide: string[] | |
replace: Record<string, string> | |
radius?: number | |
maps: BakeMap[] | |
clips: Record<string, number> | |
flat?: boolean |
packages/perspective/src/bake-spec.ts:32
Rgb interface
interface RgbRGB bytes of a w x h image, three per pixel.
data: ArrayLike<number> | |
width: number | |
height: number |
packages/perspective/src/compare.ts:6
SceneLight interface
interface SceneLightThe scene's light as the impostor and point shaders take it: the hemispheric light as an up and a down colour (mixed by the normal), the directional lights summed as one sun.
ambient: Point3 | the mean of up and down: what a surface of any orientation gets |
ambientUp: Point3 | |
ambientDown: Point3 | |
sun: Point3 | |
toSun: Point3 |
packages/perspective/src/points.ts:62
Sphere interface
interface SphereA bounding sphere in world space.
centre: Point3 | |
radius: number |
packages/perspective/src/projection.ts:57
ViewBlend interface
interface ViewBlendviews: [[number, number], [number, number], [number, number]] | three views of the grid, each [i, j] |
weights: [number, number, number] | their weights; they sum to 1 |
packages/perspective/src/octa.ts:38
Types
BakeMap type
type BakeMap = 'color' | 'normal' | 'orm'packages/perspective/src/bake-spec.ts:9
LevelKind type
type LevelKind = 'full' | 'mesh' | 'impostor' | 'point' | 'none'packages/perspective/src/select.ts:4
OctaMode type
type OctaMode = 'sphere' | 'hemisphere'packages/perspective/src/octa.ts:5
Point3 type
type Point3 = [number, number, number]packages/perspective/src/projection.ts:4
Recorded type
type Recorded = | { call: 'apply'; id: string; from: number; to: number; mix: number } | { call: 'points'; ids: string[] }What a backend call was, for tests.
packages/perspective/src/backend.ts:47
RepState type
type RepState = 'off' | 'on' | 'in' | 'out'How a rung is shown: fully (on), fading in, fading out (with the mix 0..1 of the cross-fade), or not at all.
packages/perspective/src/view.ts:17
Variant type
type Variant = 'full' | 'mesh' | 'impostor' | 'point' | 'none'packages/perspective/src/measure.ts:42
Constants
AMBIENT_SCALE const
const AMBIENT_SCALE: 1What a Babylon PBR surface (no environment map) returns of the light it gets, measured on a flat plate of known albedo under each light alone (tools/perspective/check, calibration of 2026-11-10): the hemispheric light comes back whole (albedo x light), the directional light as albedo x light x cos / 3 (the Lambert 1/pi, 0.347 measured); the two add.
packages/perspective/src/points.ts:100
BAKE_VERSION const
const BAKE_VERSION: 2Bumped when the bake or the atlas format changes: older atlases are then baked again.
packages/perspective/src/bake-spec.ts:7
SUN_SCALE const
const SUN_SCALE: 0.347packages/perspective/src/points.ts:101
VISIBLE_CONTRAST const
const VISIBLE_CONTRAST: 4How visible an object has to be for an error in it to count: the object's contrast, in pixels of sky brightness (a black object of 4 px of area has 4).
packages/perspective/src/measure.ts:45