@wildshard/shard-format 0.82.3 → 0.82.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.82.3",
3
+ "version": "0.82.6",
4
4
  "description": "The raw shardfile format: the spec, the validator and a validate CLI. The public, versioned contract every other repo builds on.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -5,7 +5,7 @@ import { spawnViewSceneFiles } from './spawnView.ts'
5
5
  import { parseImageAsset } from './stillImage.ts'
6
6
  import { parseWorldScenes, worldScenesForTier } from './worldScenes.ts'
7
7
 
8
- import type { TierIndex } from './phone-files.ts'
8
+ import type { PhoneFiles, TierIndex } from './phone-files.ts'
9
9
  import type { Shardfile } from './shardSchema.ts'
10
10
  import type { WorldScenesSection } from './worldScenes.ts'
11
11
 
@@ -43,6 +43,8 @@ interface PhoneTerms {
43
43
  }
44
44
 
45
45
  const NO_BYTES = 0
46
+ /** No file left out, none left raw. */
47
+ const EVERY_FILE: Readonly<PhoneFiles> = { inactive: new Set() }
46
48
  const TRIANGLE_CORNERS = 3
47
49
  const INDEX_COPIES = 2
48
50
  const FAR_SLAB_INDEX_SHARE = 0.75
@@ -163,7 +165,7 @@ function phoneTerms(
163
165
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
164
166
  shard: Shardfile,
165
167
  mountedImages: number = NO_BYTES,
166
- inactive: ReadonlySet<string> = new Set(),
168
+ files: Readonly<PhoneFiles> = EVERY_FILE,
167
169
  ): PhoneTerms {
168
170
  const cost = shard.runtime?.cost
169
171
  const commonsGpu = Object.values(shard.requires.commonsCosts).reduce(
@@ -174,14 +176,14 @@ function phoneTerms(
174
176
  content: contentBytes(
175
177
  shard,
176
178
  cost === undefined ? mountedImages : NO_BYTES,
177
- inactive,
179
+ files,
178
180
  ),
179
181
  textures:
180
182
  cost === undefined
181
- ? gpuBytes(shard, TEXTURE_KINDS, inactive) + commonsGpu + mountedImages
183
+ ? gpuBytes(shard, TEXTURE_KINDS, files) + commonsGpu + mountedImages
182
184
  : NO_BYTES,
183
185
  gl: cost === undefined ? NO_BYTES : Math.ceil(cost.glMB * MB),
184
- geometry: gpuBytes(shard, GEOMETRY_KINDS, inactive),
186
+ geometry: gpuBytes(shard, GEOMETRY_KINDS, files),
185
187
  sims: Math.max(shard.budgets.sim.resident, shard.serverBudget.memory),
186
188
  runtimeReading:
187
189
  cost === undefined
@@ -250,6 +252,8 @@ function bootMemoryCosts(
250
252
  product: Readonly<{
251
253
  mountedImages?: number
252
254
  index?: TierIndex | undefined
255
+ /** SF25: the image files the cook leaves raw (`cookLeavesImageRaw`), charged decoded and as RGBA. */
256
+ rawImages?: ReadonlySet<string> | undefined
253
257
  }> = {},
254
258
  ): BootMemoryCosts {
255
259
  const rawScene = sections.get('world/scenes')
@@ -257,11 +261,10 @@ function bootMemoryCosts(
257
261
  rawScene === undefined
258
262
  ? undefined
259
263
  : worldScenesForTier(parseWorldScenes(rawScene), 'phone')
260
- const terms = phoneTerms(
261
- shard,
262
- product.mountedImages ?? NO_BYTES,
263
- phoneInactiveFiles(shard, product.index, sections),
264
- )
264
+ const terms = phoneTerms(shard, product.mountedImages ?? NO_BYTES, {
265
+ inactive: phoneInactiveFiles(shard, product.index, sections),
266
+ raw: product.rawImages,
267
+ })
265
268
  const phone = bootPhoneBytes(terms)
266
269
  return {
267
270
  ...spawnMemoryCosts(shard, sections),
@@ -0,0 +1,158 @@
1
+ import type { Shardfile } from './shardSchema.ts'
2
+
3
+ /** STANDALONE-SHARDFILES SF5g (J525): a shardfile carries images only, and the cook encodes each texture image to the
4
+ * KTX2 a page reads in its place (blobKtx2), so the memory estimate charges an image as that KTX2. An image row holds no
5
+ * width or height, only `gpu`, its RGBA texels (`stillImage` envelope); textures are square or 2:1, so the size is read
6
+ * back from it, and any other count is charged as the square that holds it. Pine Hollow 0.0.18 was refused at a 1.67 GB
7
+ * phone peak counted as source RGBA, where its hand-made KTX2 sets (0.0.17) had been 1.31 GB. */
8
+
9
+ const RGBA_BYTES = 4
10
+ const WIDE = 2
11
+ const NO_BYTES = 0
12
+ const BLOCK_BYTES = 16
13
+ const BC_BLOCK = 4
14
+ const ASTC_PHONE_BLOCK = 6
15
+ const TEXEL = 1
16
+
17
+ interface Chain {
18
+ readonly block: number
19
+ readonly bytes: number
20
+ }
21
+ const RGBA_CHAIN: Chain = { block: TEXEL, bytes: RGBA_BYTES }
22
+ const BLOCK_CHAIN: Chain = { block: BC_BLOCK, bytes: BLOCK_BYTES }
23
+ const PHONE_CHAIN: Chain = { block: ASTC_PHONE_BLOCK, bytes: BLOCK_BYTES }
24
+
25
+ /** The width and height of an image whose RGBA texels cost `rgba`. */
26
+ function imageSize(rgba: number): readonly [number, number] {
27
+ const texels = Math.ceil(rgba / RGBA_BYTES)
28
+ const side = Math.round(Math.sqrt(texels))
29
+ const wide = Math.round(Math.sqrt(texels * WIDE))
30
+ if (side * side === texels) {
31
+ return [side, side]
32
+ }
33
+ if (wide % WIDE === NO_BYTES && wide * (wide / WIDE) === texels) {
34
+ return [wide, wide / WIDE]
35
+ }
36
+ const square = Math.ceil(Math.sqrt(texels))
37
+ return [square, square]
38
+ }
39
+
40
+ /** A full mip chain's bytes from `width` by `height` down to 1x1, each level in the chain's blocks. */
41
+ function chainBytes(width: number, height: number, chain: Chain): number {
42
+ let total = NO_BYTES
43
+ let levelWidth = width
44
+ let levelHeight = height
45
+ for (;;) {
46
+ total +=
47
+ Math.ceil(levelWidth / chain.block) *
48
+ Math.ceil(levelHeight / chain.block) *
49
+ chain.bytes
50
+ if (levelWidth === TEXEL && levelHeight === TEXEL) {
51
+ return total
52
+ }
53
+ levelWidth = Math.max(TEXEL, Math.floor(levelWidth / WIDE))
54
+ levelHeight = Math.max(TEXEL, Math.floor(levelHeight / WIDE))
55
+ }
56
+ }
57
+
58
+ /** A full mip chain's bytes, each level in the chain's blocks (a block of one 4-byte texel for RGBA). */
59
+ function mipChainBytes(rgba: number, chain: Chain): number {
60
+ const [width, height] = imageSize(rgba)
61
+ return chainBytes(width, height, chain)
62
+ }
63
+
64
+ /** SF25: the GPU bytes of a phone file the cook encodes ASTC 6x6 at `width` by `height`, with its mip chain. */
65
+ function phoneChainBytes(width: number, height: number): number {
66
+ return chainBytes(width, height, PHONE_CHAIN)
67
+ }
68
+
69
+ /** What a library image no longer charges once charged as the KTX2 the cook makes from it (`parseKtx2`): its decoded
70
+ * copy, and its GPU bytes become a full mip chain, RGBA without a transcode, 4x4 blocks of 16 bytes with one. */
71
+ function cookedImageSaving(
72
+ file: Readonly<{ decoded: number; gpu: number }>,
73
+ transcodes: boolean,
74
+ ): number {
75
+ const cooked = mipChainBytes(file.gpu, transcodes ? BLOCK_CHAIN : RGBA_CHAIN)
76
+ return Math.max(NO_BYTES, file.decoded + file.gpu - cooked)
77
+ }
78
+
79
+ type ShardFile = Shardfile['files'][number]
80
+
81
+ /** The shard's files by hash. */
82
+ function filesByHash(
83
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
84
+ source: Shardfile,
85
+ ): Map<string, ShardFile> {
86
+ const files = new Map<string, ShardFile>()
87
+ for (const file of source.files) {
88
+ files.set(file.hash, file)
89
+ }
90
+ return files
91
+ }
92
+
93
+ /** A file once: the first ask has it, later asks get none. */
94
+ function take(
95
+ files: Map<string, ShardFile>,
96
+ ref: string,
97
+ ): ShardFile | undefined {
98
+ const file = files.get(ref)
99
+ files.delete(ref)
100
+ return file
101
+ }
102
+
103
+ /** The library images the shard reaches, its library and their dependencies, each once. */
104
+ function libraryImages(
105
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
106
+ source: Shardfile,
107
+ ): ShardFile[] {
108
+ const files = filesByHash(source)
109
+ const pending = [...source.library]
110
+ const images: ShardFile[] = []
111
+ for (let ref = pending.pop(); ref !== undefined; ref = pending.pop()) {
112
+ const file = take(files, ref)
113
+ pending.push(...(file?.dependencies ?? []))
114
+ if (file?.kind === 'image') {
115
+ images.push(file)
116
+ }
117
+ }
118
+ return images
119
+ }
120
+
121
+ /** The shard with every library image charged as the KTX2 the cook makes from it (`cookedImageSaving`, no transcode):
122
+ * what the offline memory lines and the validation receipt judge, as admission's `textureLibrarySource` does. SF25: an
123
+ * image the cook leaves raw (`rawImages`, off the 4x4 grid) keeps its decoded and RGBA charge. */
124
+ function cookedImageSource(
125
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
126
+ source: Shardfile,
127
+ rawImages: ReadonlySet<string> = new Set(),
128
+ ): Shardfile {
129
+ let saving = NO_BYTES
130
+ for (const file of libraryImages(source)) {
131
+ if (!rawImages.has(file.hash)) {
132
+ saving += cookedImageSaving(file, false)
133
+ }
134
+ }
135
+ if (saving === NO_BYTES) {
136
+ return source
137
+ }
138
+ const { library } = source.budgets
139
+ return {
140
+ ...source,
141
+ budgets: {
142
+ ...source.budgets,
143
+ library: {
144
+ ...library,
145
+ resident: Math.max(NO_BYTES, library.resident - saving),
146
+ },
147
+ },
148
+ }
149
+ }
150
+
151
+ /** The GPU bytes of the phone file the cook makes from an image whose RGBA texels cost `rgba` (an image row's `gpu`):
152
+ * ASTC 6x6, 16 bytes a 6x6 block, with its mip chain. Charged at the image's own size, though the cook trims most phone
153
+ * rows to 512 (`phoneTierSize`): a ground layer or a sky keeps its size, and a row can't tell them apart. */
154
+ function cookedPhoneGpu(rgba: number): number {
155
+ return mipChainBytes(rgba, PHONE_CHAIN)
156
+ }
157
+
158
+ export { cookedImageSaving, cookedImageSource, cookedPhoneGpu, phoneChainBytes }
@@ -0,0 +1,242 @@
1
+ /* oxlint-disable no-bitwise, no-magic-numbers, unicorn/number-literal-case, unicorn/numeric-separators-style -- the PNG, JPEG and WebP header offsets, signatures and masks engine's imageHead reads, written as it writes them */
2
+ import { phoneChainBytes } from './cooked-image-cost.ts'
3
+
4
+ /** STANDALONE-SHARDFILES SF25 (J525): the cook encodes the images it mounts too, not only a shard's library images (SF5g).
5
+ * Engine's cook (`desktopKtx2`, `cookedKtx2.ts`) makes a KTX2 of every `/assets/` PNG, JPEG or WebP mount on the 4x4
6
+ * block grid, unless its row keeps it an image (`keepImage`) or it is a `.phone`/`-phone` copy, and its phone pass
7
+ * (`phoneTier`, `tierTextures.ts`) cooks the phone's ASTC 6x6 file from that KTX2 at the phone's size; the phone's table
8
+ * points a phone copy's URL at its original's file. So the estimate charges an encoded mount as that phone file, a phone
9
+ * copy of one nothing, and a mount the cook leaves raw as before: decoded and on the GPU as RGBA (`mountedImageBytes`).
10
+ * Nine Dragon 0.0.12 was refused at a 1.84 GB loading peak with its 205 MB of mounted images charged as RGBA. The cook
11
+ * encodes only for a product whose cook names its discovery document, as engine's `shardHalf` does. */
12
+
13
+ /** An image's size from its header (engine `imageHead`): a PNG's IHDR, a WebP's VP8, VP8L or VP8X chunk, or a JPEG's
14
+ * first frame marker. Undefined for anything else. */
15
+ interface ImageHead {
16
+ readonly width: number
17
+ readonly height: number
18
+ }
19
+
20
+ const NO_BYTES = 0
21
+ const BLOCK = 4
22
+ const PNG_HEAD = 24
23
+ const WEBP_HEAD = 31
24
+ const JPEG_START = 2
25
+ const JPEG_FRAME = 9
26
+ const JPEG_MARK = 0xff
27
+ const SOF_FIRST = 0xc0
28
+ const SOF_LAST = 0xcf
29
+ // DHT, JPG and DAC sit inside the frame-marker range but hold no frame.
30
+ const NOT_FRAMES: ReadonlySet<number> = new Set([0xc4, 0xc8, 0xcc])
31
+ const WEBP_LOSSY = 0x56503820
32
+ const WEBP_LOSSLESS = 0x5650384c
33
+ const WEBP_EXTENDED = 0x56503858
34
+ const VP8_START = [0x9d, 0x01, 0x2a] as const
35
+ const VP8L_SIGNATURE = 0x2f
36
+ const BITS_14 = 0x3fff
37
+ const BITS_24 = 0xffffff
38
+ const ONE = 1
39
+ /** Engine `PHONE_TIER_MAX`: the phone's file of a plain row keeps no level above 512. */
40
+ const PHONE_TIER_MAX = 512
41
+ /** Engine `KEPT_ENCODE_MAX`: a row kept at its size (a sky, a horizon, a panorama, a `#layer` twin). */
42
+ const KEPT_MAX = 16_384
43
+ /** Engine `DESKTOP_LAYER_MAX`: a ground layer's `#layer` twin keeps no level above the desktop's array size. */
44
+ const DESKTOP_LAYER_MAX = 1024
45
+ const PHONE_COPY = /[.-]phone\.[a-z0-9]+$/iu
46
+ const IMAGE_FILE = /\.(?:jpe?g|png|webp)$/iu
47
+ const LAYER_FILE =
48
+ /\/tex\/[^/]+\/(?:diffuse|nor_gl|arm)(?:_1k)?\.(?:jpe?g|png)$/iu
49
+ const KEPT_SIZE = /\/(?:horizon|sky)\/|\/panorama[.-][^/]*$/u
50
+ const DISCOVERY = /^\/shardfiles\/[^/]+\/discovery\.json$/u
51
+
52
+ function webpHead(
53
+ bytes: Readonly<Uint8Array>,
54
+ view: DataView,
55
+ ): ImageHead | undefined {
56
+ const chunk = view.getUint32(12)
57
+ if (
58
+ chunk === WEBP_LOSSY &&
59
+ VP8_START.every((byte, at): boolean => bytes[23 + at] === byte)
60
+ ) {
61
+ return {
62
+ width: view.getUint16(26, true) & BITS_14,
63
+ height: view.getUint16(28, true) & BITS_14,
64
+ }
65
+ }
66
+ if (chunk === WEBP_LOSSLESS && bytes[20] === VP8L_SIGNATURE) {
67
+ const bits = view.getUint32(21, true)
68
+ return {
69
+ width: (bits & BITS_14) + ONE,
70
+ height: ((bits >>> 14) & BITS_14) + ONE,
71
+ }
72
+ }
73
+ if (chunk === WEBP_EXTENDED) {
74
+ return {
75
+ width: (view.getUint32(24, true) & BITS_24) + ONE,
76
+ height: (view.getUint32(27, true) & BITS_24) + ONE,
77
+ }
78
+ }
79
+ return undefined
80
+ }
81
+
82
+ function jpegHead(
83
+ bytes: Readonly<Uint8Array>,
84
+ view: DataView,
85
+ ): ImageHead | undefined {
86
+ let at = JPEG_START
87
+ while (at + JPEG_FRAME < bytes.length) {
88
+ if (bytes[at] !== JPEG_MARK) {
89
+ return undefined
90
+ }
91
+ const marker = bytes[at + ONE] ?? NO_BYTES
92
+ if (marker >= SOF_FIRST && marker <= SOF_LAST && !NOT_FRAMES.has(marker)) {
93
+ return { width: view.getUint16(at + 7), height: view.getUint16(at + 5) }
94
+ }
95
+ at += JPEG_START + view.getUint16(at + 2)
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ /** The image's width and height from its header alone, at any wire size, as the cook reads it. */
101
+ function imageHead(bytes: Readonly<Uint8Array>): ImageHead | undefined {
102
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
103
+ if (
104
+ bytes.length >= PNG_HEAD &&
105
+ view.getUint32(0) === 0x89504e47 &&
106
+ view.getUint32(4) === 0x0d0a1a0a
107
+ ) {
108
+ return { width: view.getUint32(16), height: view.getUint32(20) }
109
+ }
110
+ if (
111
+ bytes.length >= WEBP_HEAD &&
112
+ view.getUint32(0) === 0x52494646 &&
113
+ view.getUint32(8) === 0x57454250
114
+ ) {
115
+ return webpHead(bytes, view)
116
+ }
117
+ if (bytes.length < BLOCK || bytes[0] !== JPEG_MARK || bytes[1] !== 0xd8) {
118
+ return undefined
119
+ }
120
+ return jpegHead(bytes, view)
121
+ }
122
+
123
+ /** The size the cook encodes an image at, or undefined when it leaves the image raw: a block format's top level is whole
124
+ * 4x4 blocks, so an image off that grid (or one whose header can't be read) stays an image (`encodedBlob`, `desktopKtx2`). */
125
+ function cookedImageHead(bytes: Readonly<Uint8Array>): ImageHead | undefined {
126
+ const head = imageHead(bytes)
127
+ return head === undefined ||
128
+ head.width % BLOCK !== NO_BYTES ||
129
+ head.height % BLOCK !== NO_BYTES
130
+ ? undefined
131
+ : head
132
+ }
133
+
134
+ /** Whether the cook leaves a product image file as it is (`blobKtx2` encodes every other one, SF16). */
135
+ function cookLeavesImageRaw(bytes: Readonly<Uint8Array>): boolean {
136
+ return cookedImageHead(bytes) === undefined
137
+ }
138
+
139
+ /** A KTX2's top level once engine's `trimKtx2` drops every level whose larger side is over `max`. */
140
+ function trimmed(head: ImageHead, max: number): ImageHead {
141
+ let { width, height } = head
142
+ while (Math.max(width, height) > max && (width > ONE || height > ONE)) {
143
+ width = Math.max(ONE, Math.floor(width / 2))
144
+ height = Math.max(ONE, Math.floor(height / 2))
145
+ }
146
+ return { width, height }
147
+ }
148
+
149
+ /** The bytes of the phone files the cook makes from an encoded mount: its ASTC 6x6 file at the phone's size (`phoneTierSize`:
150
+ * 512, a sky, horizon or panorama at its own), and for a ground layer file also its `#layer` twin's, trimmed to the
151
+ * desktop's array size and kept at it. A phone file's wire is at most its GPU bytes, so both terms charge them. */
152
+ function cookedMountBytes(url: string, head: ImageHead): number {
153
+ const plain = trimmed(head, KEPT_SIZE.test(url) ? KEPT_MAX : PHONE_TIER_MAX)
154
+ let bytes = phoneChainBytes(plain.width, plain.height)
155
+ if (LAYER_FILE.test(url)) {
156
+ const layer = trimmed(head, DESKTOP_LAYER_MAX)
157
+ bytes += phoneChainBytes(layer.width, layer.height)
158
+ }
159
+ return bytes
160
+ }
161
+
162
+ /** One image mount as the estimate reads it: its row, whether a phone reads it (`mountedImageOnPhone`), what it charges
163
+ * raw (`mountedImageBytes`) and the size the cook encodes it at (`cookedImageHead`). */
164
+ interface MountedImage {
165
+ readonly url: string
166
+ readonly keepImage?: true
167
+ readonly onPhone: boolean
168
+ readonly raw: number
169
+ readonly head: ImageHead | undefined
170
+ }
171
+
172
+ /** Whether the product's cook encodes its mounts: engine's cook does when the cook names the discovery document. */
173
+ function cookEncodesMounts(
174
+ mounts: readonly Readonly<{ url: string }>[],
175
+ ): boolean {
176
+ return mounts.some((mount): boolean => DISCOVERY.test(mount.url))
177
+ }
178
+
179
+ function encodes(image: Readonly<MountedImage>): boolean {
180
+ return (
181
+ image.keepImage !== true &&
182
+ image.url.startsWith('/assets/') &&
183
+ !PHONE_COPY.test(image.url) &&
184
+ IMAGE_FILE.test(image.url) &&
185
+ image.head !== undefined
186
+ )
187
+ }
188
+
189
+ /** A phone copy's original, as the cook pairs them (`phoneServed`): the copy's name without its `.phone` or `-phone`
190
+ * mark, with any image extension. */
191
+ function originalOf(
192
+ copy: string,
193
+ encoded: ReadonlyMap<string, MountedImage>,
194
+ ): MountedImage | undefined {
195
+ const stem = copy.replace(PHONE_COPY, '')
196
+ for (const [url, image] of encoded) {
197
+ if (url.slice(0, url.lastIndexOf('.')) === stem) {
198
+ return image
199
+ }
200
+ }
201
+ return undefined
202
+ }
203
+
204
+ /** What a product's mounted images charge the phone estimate: each mount the cook encodes as its phone files, whichever
205
+ * of it or its phone copy the phone asks for; a phone copy of an encoded mount nothing (the phone's table reads the
206
+ * original's file in its place); any other mount its raw charge when a phone reads it. */
207
+ function mountedImagesCharge(
208
+ images: readonly Readonly<MountedImage>[],
209
+ cooks: boolean,
210
+ ): number {
211
+ const encoded = new Map<string, MountedImage>()
212
+ for (const image of cooks ? images : []) {
213
+ if (encodes(image)) {
214
+ encoded.set(image.url, image)
215
+ }
216
+ }
217
+ let bytes = NO_BYTES
218
+ for (const image of images) {
219
+ if (image.head !== undefined && encoded.has(image.url)) {
220
+ bytes += cookedMountBytes(image.url, image.head)
221
+ } else if (
222
+ image.onPhone &&
223
+ !(
224
+ PHONE_COPY.test(image.url) &&
225
+ originalOf(image.url, encoded) !== undefined
226
+ )
227
+ ) {
228
+ bytes += image.raw
229
+ }
230
+ }
231
+ return bytes
232
+ }
233
+
234
+ export {
235
+ cookedImageHead,
236
+ cookedMountBytes,
237
+ cookEncodesMounts,
238
+ cookLeavesImageRaw,
239
+ type ImageHead,
240
+ type MountedImage,
241
+ mountedImagesCharge,
242
+ }
@@ -4,6 +4,7 @@ import { worstContentCostSteps, type worstContentCost } from './budget.ts';
4
4
  import type { Shardfile } from './shardSchema.ts';
5
5
  import type { MemoryAdmission } from './memoryAdmission.ts';
6
6
  import { parseKtx2, ktx2DeviceGpu, type Ktx2DeviceCosts } from './ktx2Cost.ts';
7
+ import { cookedImageSaving } from './cooked-image-cost.ts';
7
8
 
8
9
  /** Apply the existing total-memory policy to declared or measured costs. */
9
10
  export function acceptsShardfileCost(memory: MemoryAdmission | undefined, source: Shardfile, stage: 'declared' | 'actual', cost: ReturnType<typeof worstContentCost>): boolean {
@@ -30,6 +31,11 @@ export function textureLibrarySource(source: Shardfile, assets: ReadonlyMap<stri
30
31
  seen.add(ref);
31
32
  const file = files.get(ref); if (file === undefined) continue;
32
33
  pending.push(...file.dependencies);
34
+ // SF25: an image's bytes are never read here: a streamed admission holds none (v0.82.5's corpus stream-miss). The
35
+ // offline estimate charges the images the cook leaves raw (`rawImages`); this runtime projection keeps SF5g's.
36
+ if (file.kind === 'image') {
37
+ saving += cookedImageSaving(file, transcodes);
38
+ }
33
39
  if (file.kind !== 'ktx2') continue;
34
40
  saving += file.decoded;
35
41
  if (!transcodes) continue;
@@ -2,6 +2,7 @@ import { parse } from 'valibot'
2
2
 
3
3
  import { bootMemoryCosts } from './boot-memory-cost.ts'
4
4
  import { worstContentCost } from './budget.ts'
5
+ import { cookedImageSource } from './cooked-image-cost.ts'
5
6
  import {
6
7
  ARMED_LINES,
7
8
  armedZone,
@@ -103,6 +104,8 @@ type MemoryContext =
103
104
  sections: ReadonlyMap<string, unknown>
104
105
  mountedImages: number
105
106
  index?: TierIndex
107
+ /** SF25: the image files the cook leaves raw, charged decoded and as RGBA. */
108
+ rawImages?: ReadonlySet<string>
106
109
  judged?: 'upload' | 'stored'
107
110
  /** FP27b: the API catalogue's armed state for this shard; absent, the shard is not armed (FP27c). */
108
111
  armed?: boolean | ReadonlySet<string> | undefined
@@ -112,6 +115,7 @@ function memoryContext(context: MemoryContext): Readonly<{
112
115
  sections: ReadonlyMap<string, unknown>
113
116
  mountedImages: number
114
117
  index?: TierIndex
118
+ rawImages?: ReadonlySet<string>
115
119
  judged?: 'upload' | 'stored'
116
120
  armed?: boolean | ReadonlySet<string> | undefined
117
121
  }> {
@@ -122,6 +126,7 @@ function memoryContext(context: MemoryContext): Readonly<{
122
126
  sections: ReadonlyMap<string, unknown>
123
127
  mountedImages: number
124
128
  index?: TierIndex
129
+ rawImages?: ReadonlySet<string>
125
130
  }>)
126
131
  }
127
132
 
@@ -131,7 +136,8 @@ function offlineMemoryIssues(
131
136
  source: Shardfile,
132
137
  context: MemoryContext,
133
138
  ): ReturnType<typeof hardLineIssue>[] {
134
- const { sections, mountedImages, index, armed } = memoryContext(context)
139
+ const { sections, mountedImages, index, rawImages, armed } =
140
+ memoryContext(context)
135
141
  const native = source.runtime?.cost
136
142
  const runtime =
137
143
  native === undefined ? EMPTY_BYTES : runtimeOfflineBytes(native)
@@ -139,9 +145,14 @@ function offlineMemoryIssues(
139
145
  (sum, row): number => sum + row.decoded + row.gpu,
140
146
  EMPTY_BYTES,
141
147
  )
142
- const cost = worstContentCost(source, {
148
+ // SF5g: a library image is charged as the KTX2 the cook makes from it (J525); SF25: one it leaves raw is not.
149
+ const cost = worstContentCost(cookedImageSource(source, rawImages), {
143
150
  commons: runtime + commons,
144
- boot: bootMemoryCosts(source, sections, { mountedImages, index }),
151
+ boot: bootMemoryCosts(source, sections, {
152
+ mountedImages,
153
+ index,
154
+ rawImages,
155
+ }),
145
156
  })
146
157
  return memoryLineIssues(cost, armedZone(source.identity.slug, armed))
147
158
  }
@@ -0,0 +1,18 @@
1
+ import type { CookMount } from './cook-data.ts'
2
+
3
+ /** J525: identify legacy phone copies beside their original mounts. */
4
+ export function phoneCopyWarnings(
5
+ mounts: readonly Readonly<CookMount>[],
6
+ ): string[] {
7
+ const urls = new Set(mounts.map((mount): string => mount.url))
8
+ const warnings: string[] = []
9
+ for (const url of urls) {
10
+ const original = url.replace(/[.-]phone(?=\.[^./]+$)/u, '')
11
+ if (original !== url && urls.has(original)) {
12
+ warnings.push(
13
+ `J525: ${url} is a hand-made phone copy of ${original}. Keep the original and let the cook make tier variants.`,
14
+ )
15
+ }
16
+ }
17
+ return warnings
18
+ }
@@ -1,10 +1,19 @@
1
1
  // MEMORY-GATES MG6 epoch 5 (mini-em11b): the files a phone never fetches, for the offline estimate's terms.
2
+ import { cookedPhoneGpu } from './cooked-image-cost.ts'
2
3
  import { tierLibrarySteps } from './tierSelection.ts'
3
4
 
4
5
  import type { Shardfile } from './shardSchema.ts'
5
6
  import type { TierSelectionSource } from './tierSelection.ts'
6
7
 
7
8
  const NO_BYTES = 0
9
+ const NO_FILES: ReadonlySet<string> = new Set()
10
+
11
+ /** The files the phone terms read differently: those a phone never fetches (`inactive`) and, SF25, the image files the
12
+ * cook leaves raw (`raw`, off the 4x4 grid), which a phone decodes and uploads as RGBA. */
13
+ interface PhoneFiles {
14
+ readonly inactive: ReadonlySet<string>
15
+ readonly raw?: ReadonlySet<string> | undefined
16
+ }
8
17
 
9
18
  /** The output index rows tier selection reads: the assembled Shardfile drops each file's `tier` and `variantOf`. */
10
19
  interface TierIndex {
@@ -46,13 +55,17 @@ function contentBytes(
46
55
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
47
56
  shard: Shardfile,
48
57
  mountedImages: number,
49
- inactive: ReadonlySet<string>,
58
+ { inactive, raw = NO_FILES }: Readonly<PhoneFiles>,
50
59
  ): number {
51
60
  let bytes = mountedImages
52
61
  for (const file of shard.files) {
53
62
  if (!inactive.has(file.hash)) {
63
+ // SF5g (J525): the cook encodes an image to the KTX2 a phone uploads, so the phone never decodes it; SF25: one it
64
+ // leaves raw (`rawImages`, off the 4x4 grid) is decoded.
65
+ const cooked = file.kind === 'image' && !raw.has(file.hash)
54
66
  bytes +=
55
- file.compressed + (file.kind === 'audio' ? NO_BYTES : file.decoded)
67
+ file.compressed +
68
+ (file.kind === 'audio' || cooked ? NO_BYTES : file.decoded)
56
69
  }
57
70
  }
58
71
  for (const wire of Object.values(shard.requires.commonsWire)) {
@@ -69,15 +82,25 @@ function gpuBytes(
69
82
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
70
83
  shard: Shardfile,
71
84
  kinds: ReadonlySet<string>,
72
- inactive: ReadonlySet<string>,
85
+ { inactive, raw = NO_FILES }: Readonly<PhoneFiles>,
73
86
  ): number {
74
87
  let bytes = NO_BYTES
75
88
  for (const file of shard.files) {
76
89
  if (kinds.has(file.kind) && !inactive.has(file.hash)) {
77
- bytes += file.gpu
90
+ // SF5g (J525): an image uploads as the cook's phone ASTC 6x6 file, not as RGBA; SF25: one the cook leaves raw as RGBA.
91
+ bytes +=
92
+ file.kind === 'image' && !raw.has(file.hash)
93
+ ? cookedPhoneGpu(file.gpu)
94
+ : file.gpu
78
95
  }
79
96
  }
80
97
  return bytes
81
98
  }
82
99
 
83
- export { contentBytes, gpuBytes, phoneInactiveFiles, type TierIndex }
100
+ export {
101
+ contentBytes,
102
+ gpuBytes,
103
+ type PhoneFiles,
104
+ phoneInactiveFiles,
105
+ type TierIndex,
106
+ }
@@ -19,6 +19,7 @@ import type { Judged } from './policy-verdict.ts';
19
19
  import { staleRuntimeIssues } from './memory-epoch.ts';
20
20
  import { MEMORY_HARD_BYTES, memoryLineIssues, runtimeOfflineBytes } from './memory-line.ts';
21
21
  import { bootMemoryCosts } from './boot-memory-cost.ts';
22
+ import { cookedImageSource } from './cooked-image-cost.ts';
22
23
  import type { TierIndex } from './phone-files.ts';
23
24
  import { VIEW_DRAWS, viewDraws } from './view-draws.ts';
24
25
  import { DEFAULT_GRAPH_BUDGET } from "./materialGraph.ts";
@@ -29,13 +30,15 @@ import type { IssueCodeOf } from './issue-codes.ts';
29
30
  import { isNavigationData, navigationCost } from './navigationBytes.ts';
30
31
 
31
32
  type PerformancePolicy = 'refuse' | 'warn';
32
- interface PerformanceOptions { readonly policy: PerformancePolicy; readonly sections: ReadonlyMap<string, unknown>; readonly mountedImages?: number; readonly index?: TierIndex; readonly judged?: Judged; readonly armed?: boolean | ReadonlySet<string> | undefined }
33
+ interface PerformanceOptions { readonly policy: PerformancePolicy; readonly sections: ReadonlyMap<string, unknown>; readonly mountedImages?: number; readonly index?: TierIndex; readonly rawImages?: ReadonlySet<string>; readonly judged?: Judged; readonly armed?: boolean | ReadonlySet<string> | undefined }
33
34
 
34
35
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
35
- function reportMemory(source: Shardfile, nativeBytes: number, options: Readonly<{ sections: ReadonlyMap<string, unknown>; mountedImages?: number; index?: TierIndex }>): PerformanceReport['memory'] {
36
+ function reportMemory(source: Shardfile, nativeBytes: number, options: Readonly<{ sections: ReadonlyMap<string, unknown>; mountedImages?: number; index?: TierIndex; rawImages?: ReadonlySet<string> }>): PerformanceReport['memory'] {
36
37
  const commons = nativeBytes + Object.values(source.requires.commonsCosts).reduce((sum, row) => sum + row.decoded + row.gpu, 0);
37
38
  const budget = { commons, boot: bootMemoryCosts(source, options.sections, options) };
38
- return { near: nearbyContentCost(source, source.spawn.x, source.spawn.z, budget), worst: worstContentCost(source, budget), playingLimit: ARMED_LINES.playing, loadingLimit: ARMED_LINES.loading };
39
+ // SF5g: a library image is charged as the KTX2 the cook makes from it (J525); SF25: one it leaves raw is not.
40
+ const cooked = cookedImageSource(source, options.rawImages);
41
+ return { near: nearbyContentCost(cooked, source.spawn.x, source.spawn.z, budget), worst: worstContentCost(cooked, budget), playingLimit: ARMED_LINES.playing, loadingLimit: ARMED_LINES.loading };
39
42
  }
40
43
  /** A performance issue's code and its metric words. */
41
44
  type Named = readonly [code: IssueCodeOf<'performance'>, metric: string];
@@ -15,6 +15,7 @@ import {
15
15
  checkDiscoveryMount,
16
16
  isDiscoveryMount,
17
17
  } from './manifest-deprecations.ts'
18
+ import { phoneCopyWarnings } from './phone-copy-warnings.ts'
18
19
  import { validatePlatformFile } from './platformFileFamilies.ts'
19
20
  import { decisionModuleContracts } from './scriptContract.ts'
20
21
  import { mountSharesBlob } from './shardfile-reads.ts'
@@ -275,8 +276,8 @@ function streamedDeprecations(
275
276
  listed === undefined
276
277
  ? undefined
277
278
  : readCanonicalJson(listedBytes(replay, listed))
279
+ const mounts = cook === undefined ? [] : readCookData(cook).mounts
278
280
  if (replay.judged !== 'stored' && shard.index.shardVersion !== undefined) {
279
- const mounts = cook === undefined ? [] : readCookData(cook).mounts
280
281
  const discovery = mounts
281
282
  .filter((mount): boolean => isDiscoveryMount(mount.path))
282
283
  .map((mount): unknown => readDiscoveryArt(listedBytes(replay, mount)))
@@ -285,7 +286,7 @@ function streamedDeprecations(
285
286
  }
286
287
  return deprecationReport(
287
288
  { index: shard.index, sections: shard.sections, cook },
288
- warnings,
289
+ [...warnings, ...phoneCopyWarnings(mounts)],
289
290
  )
290
291
  }
291
292
 
@@ -24,12 +24,15 @@ import { assertScriptSides } from './script-sides.ts';
24
24
  import { shardfileRecordings } from './shardfile-audio.ts';
25
25
  import type { RecordingMeasure } from './audio-measure.ts';
26
26
  import { issueError, withIssueCode as coded } from './issue-codes.ts';
27
+ import { phoneCopyWarnings } from './phone-copy-warnings.ts';
27
28
  import { staleRuntimeIssues } from './memory-epoch.ts';
28
29
  import { memoryContext, offlineMemoryIssues } from './memory-line.ts';
29
30
  import { armedZone } from './memory-armed.ts';
30
31
  import { runtimeTierIssues } from './runtime-tier.ts';
31
32
  import type { MemoryContext } from './memory-line.ts';
32
- import { mountedImageBytes, mountedImageOnPhone, NO_BYTES } from './boot-memory-cost.ts';
33
+ import { mountedImageBytes, mountedImageOnPhone } from './boot-memory-cost.ts';
34
+ import { cookedImageHead, cookEncodesMounts, cookLeavesImageRaw, mountedImagesCharge } from './cooked-mount-cost.ts';
35
+ import type { MountedImage } from './cooked-mount-cost.ts';
33
36
  import { admittedVerdict, policyVerdict, recordVerdict } from './policy-verdict.ts';
34
37
  import type { Judged, PolicyVerdict } from './policy-verdict.ts';
35
38
  import { deprecationReport } from './deprecations.ts';
@@ -213,23 +216,26 @@ function checkServerAndKtx2(index: OutputIndex, read: ReadListed, assets: Readon
213
216
 
214
217
  type MountInventory = Readonly<{ formatVersion: OutputIndex['formatVersion']; files: readonly Readonly<Pick<OutputFile, 'hash' | 'path' | 'compressed'>>[] }>;
215
218
 
216
- /** C0 (J137): verify every cook mount, even a desktop image the phone never requests. */
217
- function checkedMountImageBytes(index: MountInventory, mount: Readonly<CookMount>, options: Readonly<{ read: ReadListed; onPhone: boolean }>): number {
218
- if (mountSharesBlob(mount, index.files)) { return NO_BYTES; }
219
+ /** C0 (J137): verify every cook mount, even a desktop image the phone never requests. SF25: an image mount's raw charge
220
+ * and the size the cook encodes it at; none for a mount whose bytes are a product file, charged as that file. */
221
+ function checkedMountImage(index: MountInventory, mount: Readonly<CookMount>, options: Readonly<{ read: ReadListed; onPhone: boolean }>): MountedImage | undefined {
222
+ if (mountSharesBlob(mount, index.files)) { return undefined; }
219
223
  if (mount.path !== cookMountPath(mount.url)) { throw new Error(`Mount path differs from its URL: ${mount.url}`); }
220
224
  const bytes = checkDiscoveryMount(index.formatVersion, mount.path, options.read(mount));
221
- return options.onPhone ? mountedImageBytes(mount.path, bytes) : NO_BYTES;
225
+ return { url: mount.url, ...(mount.keepImage === true ? { keepImage: true } : {}), onPhone: options.onPhone, raw: mountedImageBytes(mount.path, bytes), head: cookedImageHead(bytes) };
222
226
  }
223
227
 
228
+ /** SF25 (J525): the mounted images' charge, each the cook encodes as its phone files (`mountedImagesCharge`). */
224
229
  function checkedMountImages(index: MountInventory, read: ReadListed, cook: CookData | undefined): number {
225
230
  const mounts = cook?.mounts ?? [];
226
231
  const urls = new Set(mounts.map((mount): string => mount.url));
227
232
  const phoneFence = isPreparedCook(cook) && cook?.fence !== undefined ? new Set(cook.fence) : undefined;
228
- let mountedImages = NO_BYTES;
233
+ const images: MountedImage[] = [];
229
234
  for (const mount of mounts) {
230
- mountedImages += checkedMountImageBytes(index, mount, { read, onPhone: mountedImageOnPhone(mount, urls, phoneFence) });
235
+ const image = checkedMountImage(index, mount, { read, onPhone: mountedImageOnPhone(mount, urls, phoneFence) });
236
+ if (image !== undefined) { images.push(image); }
231
237
  }
232
- return mountedImages;
238
+ return mountedImagesCharge(images, cookEncodesMounts(mounts));
233
239
  }
234
240
 
235
241
  /** The cook file and the mounted engine images measured alongside its own images. */
@@ -261,9 +267,12 @@ export function validateShardfileFolder(files: ShardfileFiles, ports: ShardfileV
261
267
  const payloads = readSections(index, read), warnings = coded('script-side', (): string[] => assertScriptSides(payloads, index, { ...files, verify }));
262
268
  const scripts = coded('script-admission', (): ScriptAdmissionRows => scriptAdmissionRows(payloads));
263
269
  const contracts = coded('script-admission', (): ReturnType<typeof decisionModuleContracts> => decisionModuleContracts(scripts, index.files));
270
+ // SF25: the image files the cook leaves raw (off the 4x4 grid), which the estimate charges decoded and as RGBA.
271
+ const rawImages = new Set<string>();
264
272
  for (const entry of index.files) {
265
273
  const bytes = read({ path: entry.path, hash: entry.hash, bytes: entry.compressed });
266
274
  coded('blob-invalid', (): void => { inspectBlob(entry, bytes, ports, entry.kind === 'wasm' ? contracts.get(entry.hash) ?? { abi: 0 } : undefined); });
275
+ if (entry.kind === 'image' && cookLeavesImageRaw(bytes)) { rawImages.add(entry.hash); }
267
276
  keep(entry, bytes, index.requires.commons.includes(entry.hash));
268
277
  }
269
278
  checkServerAndKtx2(index, read, assets);
@@ -281,8 +290,8 @@ export function validateShardfileFolder(files: ShardfileFiles, ports: ShardfileV
281
290
  }
282
291
  for (const path of files.paths()) if (!listed.has(path)) throw issueError('unlisted-file', `Unlisted output file: ${path}`);
283
292
  coded('carried-ktx2', (): void => { refuseCarriedKtx2(index, files.paths(), ports.judged); });
284
- const shard = admitShardfileFolder(coded('shard-schema', (): unknown => assembleOutputShardfile(index, payloads)), assets, ports.hash, 'warn', scripts, { sections: payloads, mountedImages, index, judged: ports.judged ?? 'upload', armed: ports.armed });
293
+ const shard = admitShardfileFolder(coded('shard-schema', (): unknown => assembleOutputShardfile(index, payloads)), assets, ports.hash, 'warn', scripts, { sections: payloads, mountedImages, index, rawImages, judged: ports.judged ?? 'upload', armed: ports.armed });
285
294
  checkWorldTargets(shard, payloads.get('world/targets'));
286
295
  if (!declaredSourceMatches(shard, index, ports.hash)) throw issueError('source-hash', 'Output sections differ from the declared source hash');
287
- return { index, shard, assets, sections: payloads, scripts, ...deprecationReport({ index, sections: payloads, cook }, warnings), policy: admittedVerdict(shard), audio: shardfileRecordings({ cook, read: files.read, shard, assets }) };
296
+ return { index, shard, assets, sections: payloads, scripts, ...deprecationReport({ index, sections: payloads, cook }, [...warnings, ...phoneCopyWarnings(cook?.mounts ?? [])]), policy: admittedVerdict(shard), audio: shardfileRecordings({ cook, read: files.read, shard, assets }) };
288
297
  }