@wildshard/shard-format 0.82.4 → 0.82.8

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.4",
3
+ "version": "0.82.8",
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": {
@@ -39,8 +39,9 @@ const ENGINE_PINS =
39
39
  'https://raw.githubusercontent.com/project-wildshard/engine/main/test/pins'
40
40
  /** ZS3 (J507): the next releases, production's and staging's, as engine pins them. */
41
41
  const LIVE_PINS = `${ENGINE_PINS}/shardfiles.json,${ENGINE_PINS}/staging.json`
42
- /** The signed release and placement files api-server's prune reads, public. */
43
- const PACKS = 'https://packs.wildshard.io'
42
+ /** The signed release and placement files api-server's prune reads, public: R2 layout RL10 moved them from
43
+ * `packs.wildshard.io/releases/` to the root of `wildshard-releases` and removed the old keys. */
44
+ const RELEASES = 'https://releases.wildshard.io'
44
45
 
45
46
  interface LiveSet {
46
47
  readonly pins: readonly Pin[]
@@ -57,7 +58,7 @@ async function liveSet(args: MarkedArgs): Promise<LiveSet> {
57
58
  validator: '',
58
59
  fetch: args.get,
59
60
  })
60
- const live = await liveHashes({ packs: PACKS, listed, pins }, args.get)
61
+ const live = await liveHashes({ releases: RELEASES, listed, pins }, args.get)
61
62
  return { pins, listed, live }
62
63
  }
63
64
 
@@ -4,7 +4,7 @@ import type { Pin } from './corpus-pins.ts'
4
4
  import type { StoredRecord } from './corpus.ts'
5
5
 
6
6
  // ZONE-SNAPSHOTS ZS3 (J507): the corpus counts only what players load. Live is what the signed release files name and
7
- // the signed placements place (public at packs.wildshard.io/releases/, the files api-server's prune reads), plus
7
+ // the signed placements place (public at releases.wildshard.io since RL10, the files api-server's prune reads), plus
8
8
  // engine's pins (the next release's). The API keeps more: each live revision's 3 earlier revisions as rollback copies
9
9
  // (api-server ZS2), which roll back with their engine release and never count as users, and whatever a channel's own
10
10
  // pointer still names (`/api/catalogue.json`). A listed original that is none of these is store drift: the prune
@@ -178,7 +178,7 @@ async function channelHashes(
178
178
  /** The hashes players load: each signed release file's shards and placement's cells, and engine's pins. */
179
179
  async function liveHashes(
180
180
  input: Readonly<{
181
- packs: string
181
+ releases: string
182
182
  listed: readonly StoredRecord[]
183
183
  pins: readonly Readonly<Pin>[]
184
184
  }>,
@@ -193,11 +193,7 @@ async function liveHashes(
193
193
  const channels = await Promise.all(
194
194
  RELEASE_CHANNELS.map(
195
195
  async (channel: string): Promise<readonly string[]> =>
196
- await channelHashes(
197
- `${input.packs}/releases/${channel}`,
198
- byRevision,
199
- get,
200
- ),
196
+ await channelHashes(`${input.releases}/${channel}`, byRevision, get),
201
197
  ),
202
198
  )
203
199
  const pinned = input.pins.map((pin: Readonly<Pin>): string => pin.hash)
@@ -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),
@@ -37,9 +37,8 @@ function imageSize(rgba: number): readonly [number, number] {
37
37
  return [square, square]
38
38
  }
39
39
 
40
- /** A full mip chain's bytes, each level in the chain's blocks (a block of one 4-byte texel for RGBA). */
41
- function mipChainBytes(rgba: number, chain: Chain): number {
42
- const [width, height] = imageSize(rgba)
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 {
43
42
  let total = NO_BYTES
44
43
  let levelWidth = width
45
44
  let levelHeight = height
@@ -56,6 +55,17 @@ function mipChainBytes(rgba: number, chain: Chain): number {
56
55
  }
57
56
  }
58
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
+
59
69
  /** What a library image no longer charges once charged as the KTX2 the cook makes from it (`parseKtx2`): its decoded
60
70
  * copy, and its GPU bytes become a full mip chain, RGBA without a transcode, 4x4 blocks of 16 bytes with one. */
61
71
  function cookedImageSaving(
@@ -109,14 +119,18 @@ function libraryImages(
109
119
  }
110
120
 
111
121
  /** The shard with every library image charged as the KTX2 the cook makes from it (`cookedImageSaving`, no transcode):
112
- * what the offline memory lines and the validation receipt judge, as admission's `textureLibrarySource` does. */
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. */
113
124
  function cookedImageSource(
114
125
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
115
126
  source: Shardfile,
127
+ rawImages: ReadonlySet<string> = new Set(),
116
128
  ): Shardfile {
117
129
  let saving = NO_BYTES
118
130
  for (const file of libraryImages(source)) {
119
- saving += cookedImageSaving(file, false)
131
+ if (!rawImages.has(file.hash)) {
132
+ saving += cookedImageSaving(file, false)
133
+ }
120
134
  }
121
135
  if (saving === NO_BYTES) {
122
136
  return source
@@ -141,4 +155,4 @@ function cookedPhoneGpu(rgba: number): number {
141
155
  return mipChainBytes(rgba, PHONE_CHAIN)
142
156
  }
143
157
 
144
- export { cookedImageSaving, cookedImageSource, cookedPhoneGpu }
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
+ }
@@ -31,6 +31,8 @@ export function textureLibrarySource(source: Shardfile, assets: ReadonlyMap<stri
31
31
  seen.add(ref);
32
32
  const file = files.get(ref); if (file === undefined) continue;
33
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.
34
36
  if (file.kind === 'image') {
35
37
  saving += cookedImageSaving(file, transcodes);
36
38
  }
@@ -104,6 +104,8 @@ type MemoryContext =
104
104
  sections: ReadonlyMap<string, unknown>
105
105
  mountedImages: number
106
106
  index?: TierIndex
107
+ /** SF25: the image files the cook leaves raw, charged decoded and as RGBA. */
108
+ rawImages?: ReadonlySet<string>
107
109
  judged?: 'upload' | 'stored'
108
110
  /** FP27b: the API catalogue's armed state for this shard; absent, the shard is not armed (FP27c). */
109
111
  armed?: boolean | ReadonlySet<string> | undefined
@@ -113,6 +115,7 @@ function memoryContext(context: MemoryContext): Readonly<{
113
115
  sections: ReadonlyMap<string, unknown>
114
116
  mountedImages: number
115
117
  index?: TierIndex
118
+ rawImages?: ReadonlySet<string>
116
119
  judged?: 'upload' | 'stored'
117
120
  armed?: boolean | ReadonlySet<string> | undefined
118
121
  }> {
@@ -123,6 +126,7 @@ function memoryContext(context: MemoryContext): Readonly<{
123
126
  sections: ReadonlyMap<string, unknown>
124
127
  mountedImages: number
125
128
  index?: TierIndex
129
+ rawImages?: ReadonlySet<string>
126
130
  }>)
127
131
  }
128
132
 
@@ -132,7 +136,8 @@ function offlineMemoryIssues(
132
136
  source: Shardfile,
133
137
  context: MemoryContext,
134
138
  ): ReturnType<typeof hardLineIssue>[] {
135
- const { sections, mountedImages, index, armed } = memoryContext(context)
139
+ const { sections, mountedImages, index, rawImages, armed } =
140
+ memoryContext(context)
136
141
  const native = source.runtime?.cost
137
142
  const runtime =
138
143
  native === undefined ? EMPTY_BYTES : runtimeOfflineBytes(native)
@@ -140,10 +145,14 @@ function offlineMemoryIssues(
140
145
  (sum, row): number => sum + row.decoded + row.gpu,
141
146
  EMPTY_BYTES,
142
147
  )
143
- // SF5g: a library image is charged as the KTX2 the cook makes from it (J525).
144
- const cost = worstContentCost(cookedImageSource(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), {
145
150
  commons: runtime + commons,
146
- boot: bootMemoryCosts(source, sections, { mountedImages, index }),
151
+ boot: bootMemoryCosts(source, sections, {
152
+ mountedImages,
153
+ index,
154
+ rawImages,
155
+ }),
147
156
  })
148
157
  return memoryLineIssues(cost, armedZone(source.identity.slug, armed))
149
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
+ }
@@ -6,6 +6,14 @@ import type { Shardfile } from './shardSchema.ts'
6
6
  import type { TierSelectionSource } from './tierSelection.ts'
7
7
 
8
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
+ }
9
17
 
10
18
  /** The output index rows tier selection reads: the assembled Shardfile drops each file's `tier` and `variantOf`. */
11
19
  interface TierIndex {
@@ -47,17 +55,17 @@ function contentBytes(
47
55
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
48
56
  shard: Shardfile,
49
57
  mountedImages: number,
50
- inactive: ReadonlySet<string>,
58
+ { inactive, raw = NO_FILES }: Readonly<PhoneFiles>,
51
59
  ): number {
52
60
  let bytes = mountedImages
53
61
  for (const file of shard.files) {
54
62
  if (!inactive.has(file.hash)) {
55
- // SF5g (J525): the cook encodes an image to the KTX2 a phone uploads, so the phone never decodes it.
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)
56
66
  bytes +=
57
67
  file.compressed +
58
- (file.kind === 'audio' || file.kind === 'image'
59
- ? NO_BYTES
60
- : file.decoded)
68
+ (file.kind === 'audio' || cooked ? NO_BYTES : file.decoded)
61
69
  }
62
70
  }
63
71
  for (const wire of Object.values(shard.requires.commonsWire)) {
@@ -74,16 +82,25 @@ function gpuBytes(
74
82
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
75
83
  shard: Shardfile,
76
84
  kinds: ReadonlySet<string>,
77
- inactive: ReadonlySet<string>,
85
+ { inactive, raw = NO_FILES }: Readonly<PhoneFiles>,
78
86
  ): number {
79
87
  let bytes = NO_BYTES
80
88
  for (const file of shard.files) {
81
89
  if (kinds.has(file.kind) && !inactive.has(file.hash)) {
82
- // SF5g (J525): an image uploads as the cook's phone ASTC 6x6 file, not as RGBA.
83
- bytes += file.kind === 'image' ? cookedPhoneGpu(file.gpu) : 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
84
95
  }
85
96
  }
86
97
  return bytes
87
98
  }
88
99
 
89
- export { contentBytes, gpuBytes, phoneInactiveFiles, type TierIndex }
100
+ export {
101
+ contentBytes,
102
+ gpuBytes,
103
+ type PhoneFiles,
104
+ phoneInactiveFiles,
105
+ type TierIndex,
106
+ }
@@ -30,14 +30,14 @@ import type { IssueCodeOf } from './issue-codes.ts';
30
30
  import { isNavigationData, navigationCost } from './navigationBytes.ts';
31
31
 
32
32
  type PerformancePolicy = 'refuse' | 'warn';
33
- 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 }
34
34
 
35
35
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
36
- 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'] {
37
37
  const commons = nativeBytes + Object.values(source.requires.commonsCosts).reduce((sum, row) => sum + row.decoded + row.gpu, 0);
38
38
  const budget = { commons, boot: bootMemoryCosts(source, options.sections, options) };
39
- // SF5g: a library image is charged as the KTX2 the cook makes from it (J525).
40
- const cooked = cookedImageSource(source);
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
41
  return { near: nearbyContentCost(cooked, source.spawn.x, source.spawn.z, budget), worst: worstContentCost(cooked, budget), playingLimit: ARMED_LINES.playing, loadingLimit: ARMED_LINES.loading };
42
42
  }
43
43
  /** A performance issue's code and its metric words. */
@@ -139,7 +139,7 @@ function namedKeys(
139
139
  * tables), but not its textures (`ktx2`, OF27b): no later check reads a texture's bytes (`validateSkinAssets` reads the
140
140
  * JSON and the GLB, and each texture's own costs were checked as it streamed, by `admitFileBytes`). Holding them put
141
141
  * Nalati r7's declared skin looks (OF30: 18 textures, 15.7 MB) over `PLACED_HOLD_CAP`. */
142
- const UNHELD_DEPENDENCY_KIND = 'ktx2'
142
+ const UNHELD_DEPENDENCY_KINDS: ReadonlySet<string> = new Set(['ktx2', 'image'])
143
143
 
144
144
  /** The placed keys, and the listed dependencies of the JSON among them (a skin file names its GLB; Codex review). */
145
145
  function placedKeys(
@@ -163,7 +163,7 @@ function placedKeys(
163
163
  for (const dependency of row.dependencies) {
164
164
  for (const found of hashKeys(dependency, paths).filter(
165
165
  (held: string): boolean =>
166
- rows.get(held)?.kind !== UNHELD_DEPENDENCY_KIND,
166
+ !UNHELD_DEPENDENCY_KINDS.has(rows.get(held)?.kind ?? ''),
167
167
  )) {
168
168
  keys.add(found)
169
169
  }
@@ -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
  }