Compare commits

..
Author SHA1 Message Date
Sameh Khamis 39f2d0b165 Merge remote-tracking branch 'origin/main' into fix/models-black
# Conflicts:
#	docs/CURRENT-STATE.md
2026-11-17 16:54:43 -08:00
Sameh Khamis db27ac6b55 Add the changelog entry for models keeping their paint 2026-11-17 16:51:20 -08:00
Sameh Khamis e83c1672dd fix(models): tracked and emergency tints mix into aircraft paint instead of multiplying it
Aircraft models multiplied their tint into the shaded paint (HIGHLIGHT).
A saturated tint zeroes every channel it lacks: the tracked cyan (no red)
drew a red helicopter solid black, day or night, and a white Cessna one
flat cyan. Tinted models now mix the colour in at 30%
(AIRCRAFT_MODEL_TINT_MIX), so the paint stays readable and the colour
still marks them; untinted models still draw their own colours, and the
IR boost stays flat white.

Neither the multi-part models nor the part shader were involved: old and
new GLBs, with and without the shader, render the same pixels, and an
untinted model at night is lit by the default ambient term.

The new conformance check draw.models.paint draws a model painted with
COLOR_0 under a fixed sun and reads its colour by day, at night, and
under a tint mixed in. The parts test model can now carry vertex paint.
2026-11-17 16:50:52 -08:00
10 changed files with 224 additions and 12 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
- Keep a tracked or emergency aircraft model's paint visible: its tint now
mixes in instead of multiplying, which drew red models black under the
cyan tracked colour (samehkhamis, #1794).
+1 -1
View File
@@ -8042,7 +8042,7 @@ pins and share links already supply complete boxes.
normal four-samples-per-250-ms budget. Retry timestamps more than the maximum
30-second backoff ahead of the current clock are ignored. A smaller rollback
can retain a bounded retry delay of up to 30 seconds.
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the tracked colour (cyan, or amber in Military Flights) and the emergency red multiply into the mesh, so its paint still shows. IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
- Commercial and military aircraft use the same high-level FLEET model regime: an aircraft draws as its glTF model only within 3 km of the camera (eye to aircraft: `MODEL_ADD_M` = 3,000 m, kept to `MODEL_KEEP_M` = 3,600 m so a contact on the edge does not flicker) and as its icon farther away, controlled by the DISPLAY rail `3D` toggle and `Proximity` / `All` modes. Both modes use the same radius and differ by their caps (`MODEL_MAX` 150, `MODEL_MAX_ALL` 350). Models are drawn at their true size, with no minimum pixel size. The fleet ceiling (`MODEL_ALT_CEIL_M`, 33,600 m) is the highest contact the layers draw (`MODEL_HIGHEST_CONTACT_M`, 30 km) plus the keep radius: above it no contact can be within range, so the eligibility pass is skipped; below it only the distance decides. Every model is one of the project's procedural fleet models (`public/models/fleet/`, MIT, 122 GLBs, about 2 MB in all; `public/models/README.md`), chosen per aircraft by `aircraftModelSpec` (`src/data/fleetModels.js`): the first of its ICAO type's callsign rules in `types.json` (`aircraft_callsign`) its callsign matches, else its type's entry, else the model of its `classifyAircraft` class for a type the map lacks, else its ADS-B emitter category's, else the default airliner. It is drawn LIFE SIZE: the type's published length over the model's built length (`src/layers/flights/modelSpec.js`, shared by Flights, Military Flights and Local ADS-B), and a grounded aircraft stands the model's scaled clearance above the ground. An airport ground vehicle (feed type `ZVEH`) is a fire truck (`FIRE…`), pushback tug (`PUSH…`, `TUG…`), van (`DEICER…`, `SQUID…`, `SQB…`) or else a car by its callsign, and a ground station (`GRND`) is an 11.8 m radio mast; these models (catalog category `other`) are drawn at their built size, and such a contact with no altitude stands on the ground instead of at the airborne default (`src/layers/flights/records.js`). `classifyAircraft` still picks the 2D icons (see the map sprites entry below). The whole set loads once, up front, when a layer that draws it starts (`loadFleetModelSet`, which logs `[Fleet] N/122 models (X MB) loaded in N ms`); models are built from those bytes, never fetched mid-session, and an aircraft stays its billboard until the set has loaded. Every aircraft model draws its mesh's own colours (`aircraftModelBlend`, `src/data/aircraftModelLighting.js`): Cesium's `ColorBlendMode.HIGHLIGHT` with white, in Flights, Military Flights and Local ADS-B alike; the tracked colour (cyan, or amber in Military Flights) and the emergency red are mixed in at 30% (`AIRCRAFT_MODEL_TINT_MIX`, `MIX`), so the paint still shows: multiplying by a saturated tint zeroed the channels it lacks, and drew a red helicopter followed in cyan black and a white Cessna flat cyan. IR boost draws them flat white (`MIX` at `1.0`). Under NVG/FLIR (map preset or Cockpit vision) models render unlit flat-white at full alpha and scene fog is disabled (fog otherwise blacks out distant models with the globe hidden); state restores on exit.
- **Map sprites.** Every far-away contact is a white sprite on the 96-unit, nose-up frame of `src/data/aircraftIcons.js`, tinted when it is drawn, so one icon-atlas slot serves every colour and selection state. Sprites are the far level of detail: the handoff to 3D models is unchanged, and no sprite is sized by the contact's length (each layer keeps its own size rules: aircraft ×0.8 on the ground and larger when tracked, vessels by speed). **Aircraft** keep their class glyphs, and every class draws at one size: there is no per-class scale in Flights, Military Flights or Local ADS-B, and each glyph is fitted so its farthest edge sits 44 units from the centre of the 96-unit frame (`BODY_HALF_EXTENT`, re-measured from the rasters by `src/data/aircraftIcons.test.mjs`), so a light aircraft is as big as a quadjet and is told apart by shape. `classifyAircraft` (`src/data/aircraftClass.js`) has two classes that are not aircraft, each with a label: `vehicle` (Airport vehicle: feed type `ZVEH`, ADS-B emitter category `C1` or `C2`, OpenSky category 16 or 17), one van-shaped sprite for every kind, tinted orange amber (`VEHICLE_TINT_CSS`, `#FF8F1F`, apart from the military `#FFB800`), and `station` (Ground station / obstacle: type `GRND`, or the point, cluster and line obstacles of emitter `C3` to `C5` and OpenSky 18 to 20), a radio mast drawn upright, also when tracked. Both are known from a contact's first fix: Flights classes it by the feed's own ground type before any airframe lookup (the early ground-type rule in `src/layers/flights/records.js`) and keeps a feed's emitter category string (`"C1"`) as well as OpenSky's integer one; Local ADS-B classes it by its emitter category. The **helicopter** is a top-down body under a four-blade rotor drawn in three frames 30° apart (`aircraftIcon('helicopter', px, frame)`); four blades repeat every 90°, so the loop is seamless. `rotorFrame` (`src/data/rotorFrames.js`) steps the frames at 10 a second from a phase hashed from the contact's id, so helicopters flying together do not change in step, and holds the middle frame (blades as an X) on the ground. The Flights and Military Flights layers keep the airborne helicopters drawn as their glyph in a map and, on each fleet pass (about 12 a second), write new images only for those in the camera's view, above the horizon and shown, whose frame changed (`_turnRotors`, `src/data/aircraftIconLayer.js`); one judged out of view is not judged again until its frame steps on. The tracked one's billboard is given its new images, and the still frame as soon as it lands. With no airborne helicopter on the map the pass does nothing. Local ADS-B redraws its markers each frame and picks the frame as it does. **Vessels** are drawn as the white hull of their kind (`vesselKind`, `src/data/vesselTypes.js`, by AIS type code or text family: cargo 70–79, tanker 80–89, passenger and ferry 60–69, high-speed 40–49, fishing 30, tug, pilot and service 31, 32, 50, 52–54, sailing 36, pleasure 37, military, law enforcement and rescue 35, 55, 51, and other), bow up and turned with course (`src/data/vesselSprites.js`), tinted by the kind's colour (`VESSEL_KIND_STYLES`, shared with the vessel card's accent; sailing `#b49cff`, pleasure `#ff6f61`, military and law `#a9bccb` and high-speed `#c6ff3d` are their own), white while selected. **Aids to navigation** are one buoy sprite, upright, never turned and with no halo.
- Fleet models with moving parts are posed live (`ModelItem.parts`, capability `modelParts`), by the rules in `src/data/modelPartDrivers.js`, read from each model's part table (`fleetPartTable`, `src/data/fleetModels.js`). Aircraft and helicopters (Flights, Military Flights, Local ADS-B): fans, propellers and rotors turn while airborne or taxiing faster than 1 m/s; the landing gear is down on the ground, comes down between 750 and 600 m above the ground when descending faster than 1 m/s, and otherwise is down below 100 m and up above 300 m; gear doors open over the first quarter of the gear's travel; flaps follow the gear in the air and are up on the ground. Height above the ground is the render altitude over the cached ground floor; where no ground height is known (always for Local ADS-B), the gear is down while the aircraft descends faster than 1 m/s, slower than 85 m/s, below 5,000 m, and up otherwise. Vessels: the radar sweeps while under way (over 0.5 m/s). Transit and rail: wheels roll at the speed drawn, and doors open while stopped at a stop. A model without parts, or a renderer without `modelParts`, draws the model whole, at rest. The bundled fleet set (`public/models/fleet/`) has no part tables yet, so it draws as before.
- Vessels, Transit and Rail draw fleet models under the same DISPLAY rail `3D` toggle, at the same altitude ceiling, caps and 3 km add/keep radii as the aircraft, at true size (`FLEET_MODEL_POLICY`, `src/layers/flights/policy.js`; `createFleetModelLayer`, `src/data/fleetModelInstances.js`). A vessel's model follows its AIS ship type and is drawn at its reported length and beam (AIS static dimensions A+B and C+D, now carried on vessel rows as `length` and `beam`), standing at the sea surface, heading by true heading then course. An aid to navigation is not a hull: a vessel record whose type names a buoy, beacon, mark, RACON or light, or whose MMSI is an aid-to-navigation station's (`99MIDxxxx`), is `isAidToNavigation` (`src/data/vesselTypes.js`) and is drawn as the set's `buoys` model of the IALA mark its type names (`aidToNavigationModel`, `src/data/fleetModels.js`: cardinal N/E/S/W, port or starboard hand, preferred channel by its side, safe water, isolated danger, special mark; a beacon, light, light vessel, RACON or reference point with no mark of its own is the special mark), else a red can (`DEFAULT_AID_MODEL`), at its built size and facing north whatever heading it reports. A type is an aid's when it is one of the 32 kinds an aid report names or uses a word for one (buoy, beacon, cardinal, safe water, RACON, lighthouse and so on); a vessel that works on aids (`Buoy Tender`, `Buoy Layer`) is not one. Its icon is the buoy sprite, tinted bone white (`AID_TO_NAVIGATION_STYLE`, `src/data/vesselLabels.js`), upright and never turned, and its card, selected card and HUD readout (`src/layers/vessels/cards.js`) show its kind alone, whole, in that colour: no speed or heading, since a fixed mark has neither. AISStream subscribes to `AidsToNavigationReport` (message 21) by default, and the server names each report's aid type code (0 to 31) as its kind (`aidToNavigationTypeName`: `20` is `Cardinal Mark N`) rather than reading it as a ship type, and its name runs on into the report's `NameExtension`. A virtual aid (the report's `VirtualAtoN` flag: a mark broadcast where nothing physical stands) carries `virtual: true` on its row, and on its vessel source record (the live-source contract's `virtual`, `src/sources/live/contract.js`, false unless a source says true; any source may set it). It keeps its buoy sprite but never gets a model (`vesselModelSpec` returns null for it, and the vessel layer gathers no model item for it), and its card and readout add `VIRTUAL` after its kind. `aisStreamRows` (`server/providers/vessels/ais-store.js`) puts every vessel ahead of every aid, so a capped request (the layer asks for 12,000 rows) never gives up a ship for a buoy. The `vessels_in_area` tool (and the brief built on it) counts ships only: it leaves aids out of its rows, counts, breakdowns and speed stats. A transit vehicle's model follows its route's GTFS `route_type` when its record carries one and that type is a kind of the vehicle's mode (`types.json` `transit.route_types`: 200 a coach, 101 a high-speed set, 106 a regional DMU, 710 a double-decker), else its layer mode (`transit.modes`: bus, trolleybus, tram, cable car, subway, monorail, rail, funicular, gondola or ferry; a vehicle of `unknown` mode keeps its icon); a fleet hint that overrules the route (a bus on a tram route) leaves the type unused. A monorail and a gondola are raised by their `transit.elevation` lifts. A train's model follows its rail category and mode (rail, metro or tram). The bundled GTFS-Realtime proxy carries no route type, so its vehicles draw their mode's model; a source that adds `routeType` reaches the finer ones. Both stand on the road or rail top they are drawn on, without the 1.5 m `GROUND_FLOOR_LIFT_M` their icons carry, and are painted in their mode or category colour where the model's `_TINT` attribute marks it. A vessel model is clipped at its waterline (one clipping plane per model, at the model origin's horizontal plane), so its hull below the water never shows through a plain globe, which Cesium does not depth-test models against. Under the NVG/FLIR styles (the Flights `irBoost` parameter) these models render unlit flat white, as aircraft models do. Each vehicle's icon stays the visual until its model is loaded, ready and placed; a model is picked as its icon is, and a vehicle drawn as its model keeps its selection card and its place in the detection overlay.
+3
View File
@@ -318,6 +318,9 @@ opaque command and before the translucent pass, which blends
order-independently and would undo the addition; ground commands keep their
pass and stencil and only blend differently. The checks `draw.sets.blend`
(points, icons, lines, shapes) and `draw.models.blend` read the pixels.
`draw.models.paint` reads a lit model's vertex paint (`COLOR_0`) at a fixed
sun: its colour by day, still its colour (not black) with the sun below the
horizon, and its paint kept under a tint mixed in.
A model item may bring its glTF bytes (`gltf`): the renderer builds it from
them and never fetches its `url`, which stays the model's identity, so a
+1 -1
View File
@@ -402,7 +402,7 @@ export function createAircraftModels({
tint: record.tint ?? WHITE,
// The mesh's own colours, tinted while tracked or in an emergency;
// the IR boost draws it flat white.
colorBlend: aircraftModelBlend(state._irBoost === true),
colorBlend: aircraftModelBlend(state._irBoost === true, record.tint),
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
...(record.parts ? { parts: record.parts } : {}),
show: record.show,
+21 -6
View File
@@ -17,15 +17,30 @@ export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
const HIGHLIGHT = Object.freeze({ mode: 'highlight' });
const FLAT = Object.freeze({ mode: 'mix', amount: 1 });
/**
* How much of a tracked or emergency colour a model takes over its paint.
* Multiplying by a saturated tint zeroes every channel the tint lacks: the
* tracked cyan (no red) draws a red helicopter black and a white Cessna flat
* cyan. Mixed in at this share, the paint stays readable and the colour still
* marks the model.
*/
export const AIRCRAFT_MODEL_TINT_MIX = 0.3;
const TINTED = Object.freeze({ mode: 'mix', amount: AIRCRAFT_MODEL_TINT_MIX });
/**
* How an aircraft model's colour meets its mesh, as a draw item's
* `colorBlend`. `highlight` multiplies, so white draws the mesh's own
* colours as built, and the tracked or emergency colour tints the mesh
* without hiding its paint. The IR boost draws the model flat white instead
* (`mix` at 1, unlit).
* `colorBlend`. White (no tint) multiplies (`highlight`), which draws the
* mesh's own colours as built. A tracked or emergency colour is mixed in at
* `AIRCRAFT_MODEL_TINT_MIX`, so it tints the mesh without hiding its paint.
* The IR boost draws the model flat white instead (`mix` at 1, unlit).
* @param {boolean} irBoost
* @param {ArrayLike<number>|null} [tint] The model's RGBA tint, 0..1; white
* or none draws the mesh's own colours.
* @returns {{mode: 'highlight'|'mix', amount?: number}}
*/
export function aircraftModelBlend(irBoost) {
return irBoost ? FLAT : HIGHLIGHT;
export function aircraftModelBlend(irBoost, tint = null) {
if (irBoost) return FLAT;
const white = !tint || (tint[0] >= 1 && tint[1] >= 1 && tint[2] >= 1);
return white ? HIGHLIGHT : TINTED;
}
+66 -1
View File
@@ -2,7 +2,12 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
aircraftModelBlend,
} from './aircraftModelLighting.js';
import * as flightsPolicy from '../layers/flights/policy.js';
import * as militaryPolicy from '../layers/military/policy.js';
/**
* Every aircraft model drawn in the scene skips the renderer's dynamic
@@ -48,3 +53,63 @@ test('localAdsb: its draw-port models skip the dynamic environment map', () => {
/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/,
);
});
/**
* The colour a model draws in, as the renderer blends its tint over the
* shaded paint (`ModelItem.colorBlend`, Cesium's model colour stage): `mix`
* moves the paint toward the tint by `amount`; `highlight` multiplies.
*/
function blended(paint, tint, blend) {
if (blend.mode === 'mix')
return paint.map((c, i) => c + (tint[i] - c) * blend.amount);
if (blend.mode === 'highlight') return paint.map((c, i) => c * tint[i]);
return tint.slice(0, 3);
}
/** Paints the fleet models carry: a red helicopter, a white airliner, a dark blue tail. */
const PAINTS = {
red: [0.8, 0.05, 0.05],
white: [0.9, 0.9, 0.9],
blue: [0.05, 0.1, 0.5],
};
test('an untinted model draws its mesh in its own colours', () => {
for (const tint of [null, [1, 1, 1, 1], flightsPolicy.MODEL_WHITE]) {
const blend = aircraftModelBlend(false, tint);
for (const paint of Object.values(PAINTS))
assert.deepEqual(blended(paint, [1, 1, 1], blend), paint);
}
});
test('the tracked and emergency tints keep every paint, never black or one flat colour', () => {
const tints = {
'tracked cyan': flightsPolicy.TRACKED_CYAN,
emergency: flightsPolicy.EMERGENCY_TINT,
'military tracked': militaryPolicy.TRACKED_ICON_COLOR,
'military emergency': militaryPolicy.EMERGENCY_ICON_COLOR,
};
for (const [tintName, tint] of Object.entries(tints)) {
const blend = aircraftModelBlend(false, tint);
const drawn = {};
for (const [paintName, paint] of Object.entries(PAINTS)) {
const out = blended(paint, tint, blend);
drawn[paintName] = out;
// Multiplying by the tracked cyan (no red) drew a red helicopter black.
paint.forEach((c, i) =>
assert.ok(
out[i] >= c * 0.6,
`${tintName} over ${paintName}: channel ${i} ${out[i].toFixed(2)} keeps most of ${c}`,
),
);
}
// Paints that differ still differ: the tint is not one flat colour.
const spread = (a, b) => Math.max(...a.map((c, i) => Math.abs(c - b[i])));
assert.ok(spread(drawn.red, drawn.white) > 0.4, `${tintName}: red and white apart`);
assert.ok(spread(drawn.blue, drawn.white) > 0.4, `${tintName}: blue and white apart`);
}
});
test('the IR boost draws every model flat white whatever its tint', () => {
for (const tint of [null, flightsPolicy.TRACKED_CYAN])
assert.deepEqual(aircraftModelBlend(true, tint), { mode: 'mix', amount: 1 });
});
+1
View File
@@ -84,6 +84,7 @@ export const CESIUM_CHECKS = new Set([
'draw.models.loadFailed',
'draw.models.tint',
'draw.models.blend',
'draw.models.paint',
'draw.models.update',
'draw.models.parts',
'draw.motion',
+87
View File
@@ -4049,6 +4049,93 @@ export function portChecks() {
},
{ capability: 'models', bareSky: true },
),
check(
'draw.models.paint',
'a lit model draws its vertex paint (`COLOR_0`) under the sun, stays readable with the sun below the horizon, and a tint mixed in keeps the paint',
async (h, r) => {
if (h.pixels === false)
return { skip: 'this harness reads no drawn pixels' };
// Austin at 13:00 local (sun about 80° up) and at 03:00 (about 32° below).
const DAY = Date.parse('2026-06-21T18:00:00Z');
const NIGHT = Date.parse('2026-06-21T08:00:00Z');
r.frame.setTime(DAY);
await overAustin(h, r, 200);
const set = r.draw.models({ id: 'conf:models.paint' });
const ready = [];
set.on('ready', (id) => ready.push(id));
const pos = h.toEcef({ ...AUSTIN, height: 0 });
const model = (extra = {}) => ({
id: 'm',
pos,
url: 'conformance:painted-model.glb',
// Red paint, as a fleet model's livery: a white material, its
// colour per vertex.
gltf: partsModelGlb({ paint: [0.8, 0.05, 0.05] }),
orientation: { heading: 0, pitch: 0, roll: 0 },
environmentMap: false,
tint: '#ffffff',
colorBlend: { mode: 'highlight' },
...extra,
});
try {
set.set([model()]);
for (let i = 0; i < 600 && !ready.length; i++) await drawn(h, r, 1);
deepEqual(ready, ['m'], 'ready');
const s = r.query.project(pos);
ok(s, 'the model projects');
// The mean colour of a patch on the model's top, seen from above.
const mean = async (time) => {
r.frame.setTime(time);
await drawn(h, r, 3);
await settled(r);
r.frame.setTime(time);
r.frame.renderNow();
const image = r.readPixels({
crop: {
x: Math.round(s.x) - 4,
y: Math.round(s.y) - 4,
width: 9,
height: 9,
},
});
const sum = [0, 0, 0];
for (let i = 0; i < image.data.length; i += 4)
for (let c = 0; c < 3; c++) sum[c] += image.data[i + c];
return sum.map((v) => Math.round(v / (image.data.length / 4)));
};
const day = await mean(DAY);
ok(
day[0] > 100 && day[0] > 2 * day[1] && day[0] > 2 * day[2],
`in daylight, its red paint: ${day}`,
);
const night = await mean(NIGHT);
ok(
night[0] >= 30 && night[0] > 2 * night[1],
`with the sun below the horizon, still its paint, not black: ${night}`,
);
ok(
night[0] < day[0],
`darker at night than by day: ${night}, ${day}`,
);
// A tint with no red, as a tracked cyan: mixed in, the paint shows.
set.upsert([
model({
tint: '#00ffff',
colorBlend: { mode: 'mix', amount: 0.3 },
}),
]);
const tinted = await mean(DAY);
ok(
tinted[0] > 60 && tinted[1] > day[1] + 30,
`a cyan tint mixed in at 0.3 keeps the red paint and adds its colour: ${tinted}`,
);
deepEqual(ready, ['m'], 'never loaded again');
} finally {
set.dispose();
}
},
{ capability: 'models', bareSky: true },
),
check(
'draw.models.bytes',
'a model given its bytes is drawn from them, its url never fetched',
+40 -3
View File
@@ -108,15 +108,19 @@ const CUBES = [
* The model's GLB bytes. Its mesh node is scaled by `scale`, turned
* `turnDeg` about its vertical and moved by `translation`; the mesh is
* built in that node's own frame, so the model it draws is the same
* whatever the node's transform.
* whatever the node's transform. `paint` (RGB, 0..1) is every vertex's
* colour (`COLOR_0`) over a white material, as the fleet models carry
* their paint; without it the model has no vertex colours.
* @param {{scale?: number, turnDeg?: number,
* translation?: [number, number, number]}} [node]
* translation?: [number, number, number],
* paint?: [number, number, number]}} [node]
* @returns {Uint8Array}
*/
export function partsModelGlb({
scale = 10,
turnDeg = 0,
translation = [0, 0, 0],
paint,
} = {}) {
const a = (turnDeg * Math.PI) / 180;
const c = Math.cos(a);
@@ -139,7 +143,13 @@ export function partsModelGlb({
const parts = new Uint8Array(count * 4);
mesh.parts.forEach((part, i) => (parts[i * 4] = part));
const indices = new Uint16Array(mesh.indices);
// Normalised bytes, RGBA: four to a vertex, on its 4-byte boundary.
const colors = paint ? new Uint8Array(count * 4) : null;
if (colors)
for (let i = 0; i < count; i++)
colors.set([...paint.map((c) => Math.round(c * 255)), 255], i * 4);
const chunks = [positions, normals, parts, indices];
if (colors) chunks.push(colors);
const offsets = [];
let length = 0;
for (const chunk of chunks) {
@@ -177,7 +187,12 @@ export function partsModelGlb({
{
primitives: [
{
attributes: { POSITION: 0, NORMAL: 1, _PART: 2 },
attributes: {
POSITION: 0,
NORMAL: 1,
_PART: 2,
...(colors ? { COLOR_0: 4 } : {}),
},
indices: 3,
material: 0,
},
@@ -220,6 +235,17 @@ export function partsModelGlb({
byteLength: indices.byteLength,
target: 34963,
},
...(colors
? [
{
buffer: 0,
byteOffset: offsets[4],
byteLength: colors.byteLength,
byteStride: 4,
target: 34962,
},
]
: []),
],
accessors: [
{
@@ -238,6 +264,17 @@ export function partsModelGlb({
count: indices.length,
type: 'SCALAR',
},
...(colors
? [
{
bufferView: 4,
componentType: 5121,
normalized: true,
count,
type: 'VEC4',
},
]
: []),
],
};
let text = new TextEncoder().encode(JSON.stringify(json));
+1
View File
@@ -30,6 +30,7 @@ test('the stub passes the conformance suite', async () => {
'draw.lines.split',
'draw.lines.outlineDraped',
'draw.models.blend',
'draw.models.paint',
'globe.imagery.video',
'globe.weather.drawn',
'globe.weather.sceneTime',