Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

21.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  check-gizmo-coverage.mjs — a component that describes a SPACE is drawn.
 *
 * `gizmo-chrome` proves that the gizmos it lists paint something. What it cannot
 * do is notice a new component: its list is written by hand, so a component added
 * with a radius or a box on it is invisible in the editor AND invisible to the
 * gate — which is how a NavVolume shipped with a number nobody could see the
 * extent of.
 *
 * That is why this file does NOT hold a list of spatial field names. It held one
 * for a while, and the list is the same failure one level up: `loadRadius`,
 * `prefetchRadius`, `unloadRadius` and `cellSize` arrived with world streaming,
 * none of them was in the enum, so the newest feature in the engine was never
 * judged at all while this gate reported every component green.
 *
 * So the rule is inverted. DISCOVERY is broad and structural — an authored,
 * numeric field whose name carries a length word. Every pair it finds must then
 * carry a DISPOSITION saying what the number is:
 *
 *   extent     a region of world nothing renders — the viewport must name the
 *              component, which is where a gizmo's geometry is computed
 *   renders    a world length whose own drawing IS the picture (a sprite's size)
 *   no-place   a world length that limits or parameterises something else and
 *              has no region of its own (a step height, a contact skin)
 *   not-world  not measured in world space at all (type metrics, a screen
 *              fraction, a texture's pixel size)
 *   owed       an extent nothing draws. Debt, recorded as debt — never a reason
 *
 * A pair with no disposition FAILS. That is the whole point: the next component
 * with a number in it cannot be quietly skipped because nobody thought to add
 * its field name anywhere. It has to be answered.
 *
 * Granularity note: a disposition is per FIELD, the drawn check is per COMPONENT
 * (textually, the viewport naming it at all). A component that draws one of its
 * extents and forgets another still passes here — that is gizmo-chrome's
 * question. This one is about not forgetting a component entirely.
 */
import { readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const SNAPSHOT = path.join(ROOT, 'docs', 'astro', 'src', 'data', 'components.generated.json');
/** The one file where a gizmo's geometry is computed. */
const VIEWPORT = path.join(ROOT, 'desktop', 'src', 'engine', 'ViewportController.ts');

/** A name that carries any of these could be naming a length. Deliberately loose:
 *  a false positive costs one line of disposition, a false negative costs a
 *  feature nobody can see. */
const LENGTH_WORDS = /(radius|extent|bounds|size|width|height|depth|distance|range)/i;
/** Only a number can be a length; `Dimension`, `enum` and the curve objects cannot. */
const NUMERIC = /^(number|Vec2|Vec3|Vec4)$/;

/**
 * What every discovered field IS. Keyed `Component.field`, because the same name
 * means different things on different components: `cellSize` is a voxel on a
 * NavVolume, a tile on a TilemapLayer, and a streamed cell of world on a
 * StreamedWorld.
 */
const DISPOSITION = {
  // A region of world nothing renders — the viewport has to outline it.
  'BoxCollider2D.halfExtents': 'extent',
  'WaterBody.sizeX': 'extent',
  'WaterBody.sizeZ': 'extent',
  'SpringBoneCollider.radius': 'extent',
  'ContentRect.size': 'extent',
  'SpringBoneCollider.height': 'extent',
  'GripSurface.radius': 'extent',
  'GripSurface.height': 'extent',
  'GripSurface.size': 'extent',
  'Hunter.attackRange': 'extent',
  'Perceiver.range': 'extent',
  'Perceiver.hearingRange': 'extent',
  'ThirdPersonCamera.distance': 'extent',
  'ThirdPersonCamera.obstructionRadius': 'extent',
  'BoxCollider2D.radius': 'extent',
  'BoxCollider3D.halfExtents': 'extent',
  'CapsuleCollider2D.radius': 'extent',
  'CapsuleCollider2D.halfHeight': 'extent',
  'CapsuleCollider3D.radius': 'extent',
  'CapsuleCollider3D.halfHeight': 'extent',
  'CircleCollider2D.radius': 'extent',
  'PolygonCollider2D.radius': 'extent',
  'SphereCollider3D.radius': 'extent',
  'CharacterController3D.radius': 'extent',
  'CharacterController3D.halfHeight': 'extent',
  'Camera.orthoSize': 'extent',
  'Light.radius': 'extent',
  'Light.innerRadius': 'extent',
  'Light.cookieSize': 'extent',
  'LightProbeVolume.halfExtents': 'extent',
  'Occluder.halfExtents': 'extent',
  'ReflectionProbe.halfExtents': 'extent',
  'MeleeAttack.radius': 'extent',
  'AudioSource.minDistance': 'extent',
  'AudioSource.maxDistance': 'extent',
  'NavAgent.radius': 'extent',
  'NavAgent.arriveRadius': 'extent',
  'NavArea.halfExtents': 'extent',
  'NavObstacle.halfExtents': 'extent',
  'NavLink.radius': 'extent',
  'NavVolume.halfExtents': 'extent',
  'ParticleForceField.radius': 'extent',
  'ParticleCollider.radius': 'extent',
  'ParticleCollider.halfExtents': 'extent',
  'ParticleCollider.halfHeight': 'extent',
  'ParticleEmitter.shapeRadius': 'extent',
  'ParticleEmitter.shapeSize': 'extent',
  'PostProcessVolume.size': 'extent',
  'ShadowCaster2D.size': 'extent',
  'TilemapLayer.cellSize': 'extent',
  'StreamedWorld.cellSize': 'extent',
  'WorldStreamingSource.prefetchRadius': 'extent',
  'WorldStreamingSource.loadRadius': 'extent',
  'WorldStreamingSource.unloadRadius': 'extent',

  // The component's own drawing is the picture; an outline round it would trace
  // what is already on screen.
  'MeshInstances.lodDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
  'MeshInstances.minDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
  'MeshInstances.drawDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
  'MeshInstances.shadowDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
  'Planet.radius': ['renders', 'the sphere drawn at the entity is the outline'],
  'BlobShadow.radius': ['renders', 'the disc drawn on the ground is the outline'],
  'SightViewer.radius': ['no-place', 'how far an eye sees round the entity, a limit on what it reports and not a region the editor lays out'],
  'BlobShadow.fadeHeight': ['no-place', 'a height above the ground at which the disc is gone, not a region of the entity'],
  'Planet.collisionDistance': ['no-place', 'how far round each moving body the ground is built for collision, not a region of the entity'],
  'Planet.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],
  'PlacedFoliage.sizeX': ['renders', 'the area the plants are placed over is the outline'],
  'PlacedFoliage.sizeZ': ['renders', 'the area the plants are placed over is the outline'],
  'CompositeBatch.cellSize': ['no-place', 'the side of the chunks a model\'s merged parts are cut into in its root\'s space, which decides what an edit re-merges; not a region of the entity'],
  'PlacedFoliage.cellSize': ['no-place', 'the side of the cells the area is cut into, not a region of the entity'],
  'Terrain.sizeX': ['renders', 'the ground drawn at it is the outline'],
  'Terrain.sizeZ': ['renders', 'the ground drawn at it is the outline'],
  'Terrain.height': ['renders', 'the ground drawn at it is the outline'],
  'Impostor.screenSize': ['not-world', 'a fraction of the view\'s height below which the card replaces the mesh, as LODGroup\'s sizes are'],
  'Terrain.dirtHeight': ['not-world', 'a share of the height of the terrain, 0 to 1'],
  'Terrain.snowHeight': ['not-world', 'a share of the height of the terrain, 0 to 1'],
  'Footsteps.width': ['no-place', 'how far apart the left and right feet land, a spacing between steps and not a region of the walker'],
  'Footsteps.printSize': ['no-place', 'the size of a footprint sprite the engine spawns, not a region of the walker that carries the component'],
  'Footsteps.rippleSize': ['no-place', 'the final size of a ring sprite the engine spawns, not a region of the walker that carries the component'],
  'SwayPusher.radius': ['owed', 'how far from the entity plants lean away is not outlined in the viewport yet'],
  'Text.boxWidth': ['owed', 'the rectangle a world label wraps and aligns in is not outlined in the viewport yet'],
  'Text.boxHeight': ['owed', 'the rectangle a world label wraps and aligns in is not outlined in the viewport yet'],
  'FogOfWar.width': ['owed', 'the rectangle the fog covers is not outlined in the viewport yet'],
  'FogOfWar.height': ['owed', 'the rectangle the fog covers is not outlined in the viewport yet'],
  'FogOfWar.viewRadius': ['no-place', 'how far a viewer with no radius of its own sees, a limit on the field of view and not a region of the fog entity'],
  'Foliage.sizeX': ['owed', 'the area plants grow in is not outlined in the viewport yet'],
  'Foliage.sizeZ': ['owed', 'the area plants grow in is not outlined in the viewport yet'],
  'Terrain.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],
  'Terrain.drawDistance': ['no-place', 'how far from the eye ground without end is drawn, not a region of the entity'],
  'Terrain.collisionDistance': ['no-place', 'how far round each moving body the ground is built for collision, not a region of the entity'],
  'Foliage.cellSize': ['no-place', 'the square the area is cut into for drawing, not a region of the entity'],
  'Foliage.bladeWidth': ['renders', 'the blades drawn at it are the picture'],
  'Foliage.bladeHeight': ['renders', 'the blades drawn at it are the picture'],
  'Foliage.heightMin': ['no-place', 'a band of world heights plants grow in, not a region round the entity'],
  'Foliage.heightMax': ['no-place', 'a band of world heights plants grow in, not a region round the entity'],
  'Foliage.lodDistance': ['no-place', 'a distance from the camera past which the far version is drawn'],
  'Foliage.drawDistance': ['no-place', 'a distance from the camera past which nothing is drawn'],
  'Foliage.waterDepth': ['no-place', 'how deep under the water a plant may stand, not a region of the entity'],
  'WaterBody.shoreWidth': ['no-place', 'a distance in from a body\'s shore over which the waves come to full height, not a region of the entity'],
  'WorldZone.radius': 'extent',
  'WorldZone.sizeX': 'extent',
  'WorldZone.sizeZ': 'extent',
  'WaterZone.sizeX': 'extent',
  'WaterZone.sizeZ': 'extent',
  'WaterZone.cellSize': ['no-place', 'the cell size of the finest ring of the surface\'s mesh, not a region of the entity'],
  'WaterZone.rippleSize': ['no-place', 'the side of a window of ripples that follows the camera, not a region of the entity'],
  'Floating.radius': ['no-place', 'how deep under the surface a point of the body is wholly wet, not a region of the entity'],
  'Waterfall.width': ['renders', 'the sheet of water the component draws is this wide where it leaves the lip'],
  'WaterBody.waveHeight': ['no-place', 'the height of the tallest wave, not a region of the entity'],
  'WaterBody.bedDepth': ['renders', 'a river\'s bed is cut into the terrain, which draws it'],
  'SpringBone.radius': ['no-place', 'the thickness of the strand, kept clear of the colliders; a margin on each bone, not a region of the root'],
  'FirstPersonController.eyeHeight': ['no-place', 'where the camera sits above the character\'s centre; the camera child is the place, and it is selected and drawn as a camera'],
  'FirstPersonController.crouchEyeHeight': ['no-place', 'where the camera sits above the centre when crouched; the camera child is the place'],
  'FirstPersonController.crouchHalfHeight': ['no-place', 'the half height the character\'s capsule is made again at when crouched; the CharacterController3D beside it draws the standing one'],
  'PathFollower.distance': ['no-place', 'how far along the Spline the entity is, a position on a curve the Spline already draws, not a region'],
  'TerrainBand2D.depth': ['renders', 'how far down the filled body goes below the surface; the band drawn at it is the outline'],
  'TerrainBand2D.edgeWidth': ['renders', 'the thickness of the lip along the surface; the lip drawn at it is the outline'],
  'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
  'Sprite.tileSize': ['renders', 'the repeat of a drawn sprite'],
  'ShapeRenderer.size': ['renders', 'the shape drawn at it is the outline'],
  'ShapeRenderer.cornerRadius': ['renders', 'a corner of the shape it draws'],
  'UIVisual.tileSize': ['renders', 'the repeat of a drawn nine-slice'],
  'BitmapText.fontSize': ['renders', 'type metrics — the glyphs are the picture'],
  'Text.fontSize': ['renders', 'type metrics — the glyphs are the picture'],
  'Text.lineHeight': ['renders', 'type metrics — the laid-out lines are the picture'],
  'Text.strokeWidth': ['renders', 'the stroke it draws round its own glyphs'],
  'TextInput.fontSize': ['renders', 'type metrics — the glyphs are the picture'],
  'TrailRenderer.startWidth': ['renders', 'the ribbon drawn at it is the outline'],
  'TrailRenderer.endWidth': ['renders', 'the ribbon drawn at it is the outline'],
  'ParticleEmitter.startSizeMin': ['renders', 'the particles drawn at it are the picture'],
  'ParticleEmitter.startSizeMax': ['renders', 'the particles drawn at it are the picture'],
  'ParticleEmitter.endSizeMin': ['renders', 'the particles drawn at it are the picture'],
  'ParticleEmitter.endSizeMax': ['renders', 'the particles drawn at it are the picture'],
  'ParticleModelUnits.startSizeMin': ['renders', 'scaled into the emitter, whose particles drawn at it are the picture'],
  'ParticleModelUnits.startSizeMax': ['renders', 'scaled into the emitter, whose particles drawn at it are the picture'],
  'ParticleModelUnits.endSizeMin': ['renders', 'scaled into the emitter, whose particles drawn at it are the picture'],
  'ParticleModelUnits.endSizeMax': ['renders', 'scaled into the emitter, whose particles drawn at it are the picture'],
  'ParticleEmitter.trailWidth': ['renders', 'the ribbon drawn at it is the outline'],

  // A world length with no region of its own: it bounds or feeds something else,
  // and a shape drawn for it would claim a place it does not occupy.
  'ParticleEmitter.collisionMaxDistance': ['no-place', 'query culling threshold relative to the nearest active camera, not an emitter extent'],
  'CharacterController2D.skinWidth': ['no-place', 'a contact skin held off the collider; drawn, it is that outline\'s own line width'],
  'CharacterController2D.stepHeight': ['no-place', 'the highest ledge it walks up: a limit on motion, not a volume'],
  'FoliageContact.radius': ['no-place', 'how far plants lean from it, seen on the plants themselves; a ring drawn for it would sit under the grass'],
  'VoxelTerrain.cellSize': ['no-place', 'the side of a cell of the volume, seen in the skin it makes, not a region of the entity'],
  'VoxelTerrain.drawDistance': ['no-place', 'how far from the eye the volume is drawn, not a region of the entity'],
  'VoxelTerrain.collisionDistance': ['no-place', 'how far round each moving body the volume is built for collision, not a region of the entity'],
  'VoxelTerrain.surfaceHeight': ['renders', 'where the stock ground lies: the ground drawn is its picture'],
  'VoxelTerrain.hillHeight': ['renders', 'how far its hills rise and fall: the hills drawn are their picture'],
  'VoxelTerrain.caveWidth': ['renders', 'how wide its tunnels are: the tunnels drawn are their picture'],
  'VoxelTerrain.soilDepth': ['renders', 'how deep its soil goes: seen in the material of the ground drawn'],
  'RoadDecal.widthScale': ['no-place', 'a multiplier on the widths its Spline already draws, and the strip it lays shows the result'],
  'CharacterController3D.stepHeight': ['no-place', 'the tallest step it will climb — a limit on motion, not a volume'],
  'NavVolume.cellSize': ['no-place', 'the voxel the box is diced into; the box is what has a place'],
  'NavVolume.cellHeight': ['no-place', 'the voxel the box is diced into; the box is what has a place'],
  'NavVolume.agentHeight': ['no-place', 'the agent the mesh is baked for, not a region of the volume'],
  'NavVolume.agentRadius': ['no-place', 'the agent the mesh is baked for, not a region of the volume'],
  'NavVolume.stepHeight': ['no-place', 'the agent the mesh is baked for, not a region of the volume'],
  'Light.shadowDistance': ['no-place', 'how far the directional cascade reaches from the CAMERA, so it has no place round this light'],
  'Light.shadowExtent': ['no-place', 'the shadow map\'s coverage, sized on the view rather than on the light\'s own place'],
  'PostProcessVolume.blendDistance': ['no-place', 'a fade band on the volume\'s own edge, which is already drawn'],
  'ParticleEmitter.trailMinDistance': ['no-place', 'how far a particle moves before a trail point is kept — a sampling step'],
  'TrailRenderer.minVertexDistance': ['no-place', 'how far the entity moves before a point is kept — a sampling step'],

  // Not a length in world space at all.
  'BakedLighting.atlasSize': ['not-world', 'the side of a TEXTURE in texels; what it covers in the world is every lightmapped surface at once'],
  'PlanarReflection.maxSize': ['not-world', 'the longest side of the reflection capture in texels; the plane it mirrors is the surface itself'],
  'Canvas.matchWidthOrHeight': ['not-world', 'a 0..1 blend between two fits, not a length'],
  'UIDropdown.optionHeight': ['not-world', 'a row height inside a laid-out box, resolved by layout rather than placed'],
  'UITooltip.maxWidth': ['not-world', 'the maximum text wrap width in layout pixels of a transient screen popup'],
  'UITreeView.rowHeight': ['not-world', 'virtualized row height in local layout pixels'],
  'VirtualJoystick.radius': ['not-world', 'control travel in local UI layout pixels; the authored base and handle draw the control'],
  'SpriteMask.rangeEndOrder': ['not-world', 'the last draw ORDER a mask reaches, not a distance it reaches over'],
  'LODGroup.lod1Size': ['not-world', 'a fraction of SCREEN height — a property of the view, not of the entity'],
  'LODGroup.lod2Size': ['not-world', 'a fraction of SCREEN height — a property of the view, not of the entity'],
  'LODGroup.lod3Size': ['not-world', 'a fraction of SCREEN height — a property of the view, not of the entity'],
  'LODGroup.cullSize': ['not-world', 'a fraction of SCREEN height — a property of the view, not of the entity'],
};

const components = JSON.parse(readFileSync(SNAPSHOT, 'utf8')).components;

// The editor is an optional submodule, and it is where every gizmo lives. Without
// it there is nothing to judge — reported, never rounded down to a pass.
if (!existsSync(VIEWPORT)) {
  console.log('check-gizmo-coverage: no editor checkout — the viewport was not scanned,'
    + ' so no component was judged.');
  process.exit(0);
}
const viewport = readFileSync(VIEWPORT, 'utf8');

/** Every authored field a length word could be hiding in. A transient component
 *  is a runtime reading rather than something authored, and a readonly field is
 *  an output — neither is a number anybody sets, so neither can be drawn wrong. */
function discover() {
  const found = [];
  for (const component of components) {
    if (component.transient) continue;
    for (const field of component.fields ?? []) {
      if (field.readonly) continue;
      if (!NUMERIC.test(field.type ?? '')) continue;
      if (!LENGTH_WORDS.test(field.key)) continue;
      found.push({ component: component.name, field: field.key, key: `${component.name}.${field.key}` });
    }
  }
  return found;
}

const discovered = discover();
const problems = [];
const owed = [];
const counts = { extent: 0, renders: 0, 'no-place': 0, 'not-world': 0, owed: 0 };
const unused = new Set(Object.keys(DISPOSITION));

for (const { component, field, key } of discovered) {
  unused.delete(key);
  const disposition = DISPOSITION[key];
  if (!disposition) {
    problems.push(`${key} has no disposition — say what this number is`
      + ' (extent / renders / no-place / not-world), in tools/check-gizmo-coverage.mjs');
    continue;
  }
  const kind = Array.isArray(disposition) ? disposition[0] : disposition;
  if (!(kind in counts)) {
    problems.push(`${key} declares an unknown disposition "${kind}"`);
    continue;
  }
  counts[kind]++;
  if (kind === 'owed') {
    owed.push(`  ${key} — ${disposition[1]}`);
    // An owed extent that IS now named is debt somebody paid without saying so;
    // left in the list it would go on claiming a hole that has been filled.
    if (new RegExp(`\\b${component}\\b`).test(viewport)) {
      problems.push(`${key} is listed as owed, but the viewport now names ${component}`
        + ' — promote it to "extent"');
    }
    continue;
  }
  if (kind !== 'extent') continue;
  // Named in the viewport at all: every gizmo path starts by asking the world for
  // the component, so the name is there by construction when one exists.
  if (new RegExp(`\\b${component}\\b`).test(viewport)) continue;
  problems.push(`${key} is an extent and the viewport never names ${component}`
    + ' — its extent is a number with nothing on screen to show it');
}

for (const key of unused) {
  problems.push(`DISPOSITION names "${key}", which is no longer an authored numeric field`);
}

if (process.argv.includes('--list')) {
  console.log(`discovered ${discovered.length} authored length-ish field(s): `
    + Object.entries(counts).map(([k, n]) => `${k} ${n}`).join(', '));
  if (owed.length) console.log(`owed — an extent nothing draws:\n${owed.join('\n')}`);
}

if (problems.length) {
  console.error(`check-gizmo-coverage: ${problems.length} problem(s)`);
  for (const p of problems) console.error(`  ${p}`);
  console.error('\n  Draw it in ViewportController and add a case to the editor\'s gizmo-chrome check,');
  console.error('  or give the field a disposition saying what its number actually is.');
  process.exit(1);
}
console.log(`check-gizmo-coverage: ${discovered.length} authored length-ish field(s) judged`
  + ` — ${counts.extent} extent(s) drawn, ${counts.renders} self-drawn, ${counts['no-place']} placeless,`
  + ` ${counts['not-world']} not world-space, ${counts.owed} owed (--list names them).`);