@linxin666/dsh-pet 0.4.6 → 0.4.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/README.i18n.yaml +2 -2
- package/README.md +3 -1
- package/README.zh.md +3 -1
- package/lib/client.js +223 -79
- package/lib/client.js.map +1 -1
- package/lib/index.js +454 -1
- package/lib/live2d-vendor.js +129 -95
- package/lib/live2d-vendor.js.map +1 -1
- package/lib/types/client/PetSprite.d.ts +6 -4
- package/lib/types/client/PetSprite.d.ts.map +1 -1
- package/lib/types/client/PetSprite.js +100 -50
- package/lib/types/client/index.js +1 -1
- package/lib/types/client/renderers/frames2d.d.ts +5 -3
- package/lib/types/client/renderers/frames2d.d.ts.map +1 -1
- package/lib/types/client/renderers/frames2d.js +139 -33
- package/lib/types/client/sequences.d.ts +9 -2
- package/lib/types/client/sequences.d.ts.map +1 -1
- package/lib/types/client/sequences.js +25 -14
- package/lib/types/client/spritesheet.d.ts +22 -1
- package/lib/types/client/spritesheet.d.ts.map +1 -1
- package/lib/types/client/spritesheet.js +26 -2
- package/package.json +26 -30
- package/src/client/PetSprite.test.tsx +262 -26
- package/src/client/PetSprite.tsx +99 -50
- package/src/client/index.ts +1 -1
- package/src/client/pet-css.test.ts +12 -0
- package/src/client/pet.module.css +9 -3
- package/src/client/renderers/frames2d.test.ts +103 -1
- package/src/client/renderers/frames2d.ts +143 -30
- package/src/client/sequences.test.ts +37 -1
- package/src/client/sequences.ts +42 -16
- package/src/client/spritesheet.test.ts +81 -0
- package/src/client/spritesheet.ts +27 -2
- package/src/registry.test.ts +4 -2
- package/lib/invariant.js +0 -34
- package/lib/state-NvDEoCln.js +0 -455
- package/lib/types/invariant.d.ts +0 -10
- package/lib/types/invariant.d.ts.map +0 -1
- package/lib/types/invariant.js +0 -27
- package/src/invariant.ts +0 -40
|
@@ -14,9 +14,11 @@
|
|
|
14
14
|
* - Canvas bitmap buffer (default where createImageBitmap/fetch/2D context
|
|
15
15
|
* exist): frames are decoded once into an ImageBitmap on demand, with a
|
|
16
16
|
* bounded look-ahead window over the playing track, and drawn onto one
|
|
17
|
-
* <canvas
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* <canvas>. Steady-state playback issues zero DOM mutations and re-decodes
|
|
18
|
+
* only what the retention budget evicted: decoded frames are held under
|
|
19
|
+
* MAX_RETAINED_BYTES, so a long-lived pet that plays every track of every
|
|
20
|
+
* skin cannot pin every bitmap for the life of the page (measured hotspot:
|
|
21
|
+
* swapping <img>.src per frame drove image decode + invalidation every tick).
|
|
20
22
|
* - Classic <img> fallback (jsdom/tests or missing APIs): identical to the
|
|
21
23
|
* historical behavior - cache-warm Image elements plus guarded src swaps,
|
|
22
24
|
* so environments without modern decoding keep working unchanged.
|
|
@@ -78,6 +80,20 @@ export interface Frames2dRendererHandle extends PetRendererHandle {
|
|
|
78
80
|
/** Stall watchdog period: a looping track stuck longer re-kicks its chain. */
|
|
79
81
|
const WATCHDOG_MS = 1200
|
|
80
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Retention budget for decoded frame bitmaps, in bytes.
|
|
85
|
+
*
|
|
86
|
+
* The budget is expressed in bytes rather than in frames because a frame's
|
|
87
|
+
* decoded footprint is `width * height * 4` and published pets differ by more
|
|
88
|
+
* than an order of magnitude (a 512x683 frame is 1.33 MB, a 128x128 frame is
|
|
89
|
+
* 64 KB): a frame count would be either useless for small atlases or too tight
|
|
90
|
+
* for large ones. 128 MiB holds this repository's longest shipped track (78
|
|
91
|
+
* frames, 104 MB) in full, so a running loop still re-decodes nothing, while
|
|
92
|
+
* capping a pet that played every track of every skin at roughly a tenth of
|
|
93
|
+
* the ~1.7 GB the unbounded memo reached.
|
|
94
|
+
*/
|
|
95
|
+
const MAX_RETAINED_BYTES = 128 * 1024 * 1024
|
|
96
|
+
|
|
81
97
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
82
98
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
83
99
|
}
|
|
@@ -160,6 +176,32 @@ interface DecodedFrame {
|
|
|
160
176
|
height: number
|
|
161
177
|
}
|
|
162
178
|
|
|
179
|
+
/**
|
|
180
|
+
* One memoized decode job. `frame` and `bytes` appear only once the job
|
|
181
|
+
* resolved with a frame — exactly the set the retention budget may release;
|
|
182
|
+
* pending and failed jobs carry neither. The owning map's insertion order is
|
|
183
|
+
* the LRU order (re-inserting an entry marks it most recently used).
|
|
184
|
+
*/
|
|
185
|
+
interface DecodeEntry {
|
|
186
|
+
job: Promise<DecodedFrame | undefined>
|
|
187
|
+
frame?: DecodedFrame
|
|
188
|
+
bytes?: number
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Release one decoded frame. `close()` is browser-only and idempotent, so the
|
|
193
|
+
* call is guarded for exotic hosts and for frames that were already released;
|
|
194
|
+
* the `<img>` fallback has no close, where dropping the reference is the
|
|
195
|
+
* release.
|
|
196
|
+
*/
|
|
197
|
+
function releaseFrame(frame: DecodedFrame | undefined): void {
|
|
198
|
+
if (frame === undefined) return
|
|
199
|
+
try {
|
|
200
|
+
const maybeClose = (frame.source as { close?: () => void }).close
|
|
201
|
+
if (typeof maybeClose === 'function') maybeClose.call(frame.source)
|
|
202
|
+
} catch { /* already released */ }
|
|
203
|
+
}
|
|
204
|
+
|
|
163
205
|
export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
164
206
|
id: 'frames2d',
|
|
165
207
|
apiVersion: PET_RENDERER_API_VERSION,
|
|
@@ -209,11 +251,18 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
|
209
251
|
ctx.container.appendChild(img)
|
|
210
252
|
}
|
|
211
253
|
|
|
212
|
-
// Decode cache: one concurrent decode per URL,
|
|
213
|
-
//
|
|
214
|
-
//
|
|
215
|
-
|
|
216
|
-
|
|
254
|
+
// Decode cache: one concurrent decode per URL, retained under a decoded
|
|
255
|
+
// byte budget. The historical map memoized every decoded frame forever, so
|
|
256
|
+
// a pet that had played all of its tracks (every skin) kept every bitmap
|
|
257
|
+
// alive for the life of the page: a shipped three-skin pet measures 1276
|
|
258
|
+
// frames at 512x683 RGBA, about 1.7 GB, growing monotonically. Entries now
|
|
259
|
+
// carry their decoded footprint, sit in Map insertion order (delete + set
|
|
260
|
+
// is an LRU touch) and the least recently used ones outside the playing
|
|
261
|
+
// window are closed once MAX_RETAINED_BYTES is crossed. A failed decode
|
|
262
|
+
// still resolves undefined and leaves the memo, so a transient fetch error
|
|
263
|
+
// retries instead of sticking.
|
|
264
|
+
const decoding = new Map<string, DecodeEntry>()
|
|
265
|
+
let retainedBytes = 0
|
|
217
266
|
// All frame fetches funnel through a small pool. Full-library warm passes
|
|
218
267
|
// on large pets fire 1100+ requests at once, which trips the browser's
|
|
219
268
|
// in-flight request limit (net::ERR_INSUFFICIENT_RESOURCES) and fails
|
|
@@ -263,27 +312,93 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
|
263
312
|
if (index > 0) frameQueue.unshift(frameQueue.splice(index, 1)[0]!)
|
|
264
313
|
}
|
|
265
314
|
const cached = decoding.get(url)
|
|
266
|
-
if (cached !== undefined)
|
|
315
|
+
if (cached !== undefined) {
|
|
316
|
+
// LRU touch: a hit means playback just asked for this frame, so it must
|
|
317
|
+
// not be the next victim. Re-inserting the same entry only reorders.
|
|
318
|
+
decoding.delete(url)
|
|
319
|
+
decoding.set(url, cached)
|
|
320
|
+
return cached.job
|
|
321
|
+
}
|
|
267
322
|
let release!: () => void
|
|
268
323
|
const gate = new Promise<void>((resolve) => { release = resolve })
|
|
269
324
|
const job: Promise<DecodedFrame | undefined> = gate.then(() => (disposed ? undefined : decodeFrame(url)))
|
|
325
|
+
const entry: DecodeEntry = { job }
|
|
270
326
|
job.then(
|
|
271
|
-
(frame) => {
|
|
327
|
+
(frame) => {
|
|
328
|
+
if (frame === undefined) {
|
|
329
|
+
decoding.delete(url)
|
|
330
|
+
return
|
|
331
|
+
}
|
|
332
|
+
// A decode that lands after dispose is closed here: nothing can close
|
|
333
|
+
// it later, and the map was already drained.
|
|
334
|
+
if (disposed) {
|
|
335
|
+
releaseFrame(frame)
|
|
336
|
+
decoding.delete(url)
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
entry.frame = frame
|
|
340
|
+
entry.bytes = frame.width * frame.height * 4
|
|
341
|
+
retainedBytes += entry.bytes
|
|
342
|
+
// Only a resolved frame is evictable, and its decoded size is known
|
|
343
|
+
// only now, so the budget is enforced here.
|
|
344
|
+
enforceRetentionBudget()
|
|
345
|
+
},
|
|
272
346
|
() => decoding.delete(url),
|
|
273
347
|
)
|
|
274
348
|
void job.finally(() => {
|
|
275
349
|
activeFrames -= 1
|
|
276
350
|
pumpFrames()
|
|
277
351
|
})
|
|
278
|
-
decoding.set(url,
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
else frameQueue.push(entry)
|
|
352
|
+
decoding.set(url, entry)
|
|
353
|
+
const queued = { url, release }
|
|
354
|
+
if (jump) frameQueue.unshift(queued)
|
|
355
|
+
else frameQueue.push(queued)
|
|
283
356
|
pumpFrames()
|
|
284
357
|
return job
|
|
285
358
|
}
|
|
286
359
|
|
|
360
|
+
/**
|
|
361
|
+
* Release decoded bitmaps until the retained footprint is back under
|
|
362
|
+
* MAX_RETAINED_BYTES. Two properties keep this from breaking playback:
|
|
363
|
+
*
|
|
364
|
+
* - The playing track's look-ahead window, plus the frame a draw is waiting
|
|
365
|
+
* on, are never released. Releasing one would hand a closed bitmap to
|
|
366
|
+
* `drawImage`, and re-decoding it would stall the next tick.
|
|
367
|
+
* - Frames of any other track go first. That is what keeps a running loop
|
|
368
|
+
* warm under a budget smaller than two whole tracks: eviction reclaims the
|
|
369
|
+
* track the pet left instead of eating the cycle it is playing.
|
|
370
|
+
*
|
|
371
|
+
* When the protected window alone exceeds the budget nothing is released —
|
|
372
|
+
* a pet whose frames are that large cannot be bounded further without
|
|
373
|
+
* breaking playback, and the overshoot is then exactly one window.
|
|
374
|
+
*/
|
|
375
|
+
function enforceRetentionBudget(): void {
|
|
376
|
+
if (retainedBytes <= MAX_RETAINED_BYTES) return
|
|
377
|
+
const def = config.tracks[track]
|
|
378
|
+
const playing = new Set<string>(def === undefined ? [] : def.frames)
|
|
379
|
+
const protectedUrls = new Set<string>()
|
|
380
|
+
if (pinned !== undefined) protectedUrls.add(pinned)
|
|
381
|
+
if (def !== undefined) {
|
|
382
|
+
const end = Math.min(def.frames.length, frameIndex + 1 + PREFETCH_AHEAD)
|
|
383
|
+
for (let index = frameIndex; index < end; index += 1) {
|
|
384
|
+
const url = def.frames[index]
|
|
385
|
+
if (url !== undefined) protectedUrls.add(url)
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
// Pass 1 reclaims frames of tracks the pet is not playing; pass 2 is the
|
|
389
|
+
// backstop for a single track larger than the whole budget.
|
|
390
|
+
for (const foreignOnly of [true, false]) {
|
|
391
|
+
for (const [url, entry] of decoding) {
|
|
392
|
+
if (retainedBytes <= MAX_RETAINED_BYTES) return
|
|
393
|
+
if (entry.bytes === undefined || protectedUrls.has(url)) continue
|
|
394
|
+
if (foreignOnly && playing.has(url)) continue
|
|
395
|
+
releaseFrame(entry.frame)
|
|
396
|
+
retainedBytes -= entry.bytes
|
|
397
|
+
decoding.delete(url)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
287
402
|
/**
|
|
288
403
|
* Bounded look-ahead window: decode only the frames playback is about to
|
|
289
404
|
* need. The historical warm pass decoded every frame of every track up
|
|
@@ -318,6 +433,9 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
|
318
433
|
let baseIdle: string = config.phases.idle
|
|
319
434
|
let drawToken = 0
|
|
320
435
|
let lastDrawnUrl: string | undefined
|
|
436
|
+
// The frame a draw is currently awaiting. Eviction must not release it:
|
|
437
|
+
// the callback below holds the bitmap and would draw a closed one.
|
|
438
|
+
let pinned: string | undefined
|
|
321
439
|
|
|
322
440
|
const trackForPhase = (phase: ActivityPhase): string => {
|
|
323
441
|
const mapped = config.phases[phase]
|
|
@@ -330,7 +448,9 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
|
330
448
|
const paintCanvas = (url: string): void => {
|
|
331
449
|
if (context2d === null || canvas === null) return
|
|
332
450
|
const myToken = ++drawToken
|
|
451
|
+
pinned = url
|
|
333
452
|
void loadFrame(url, true).then((frame) => {
|
|
453
|
+
if (pinned === url) pinned = undefined
|
|
334
454
|
if (disposed || frame === undefined || myToken !== drawToken) return
|
|
335
455
|
if (lastDrawnUrl === url) return
|
|
336
456
|
lastDrawnUrl = url
|
|
@@ -342,7 +462,7 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
|
342
462
|
context2d.clearRect(0, 0, canvas.width, canvas.height)
|
|
343
463
|
}
|
|
344
464
|
context2d.drawImage(frame.source as CanvasImageSource, 0, 0)
|
|
345
|
-
}).catch(() => { /* keep last frame */ })
|
|
465
|
+
}).catch(() => { if (pinned === url) pinned = undefined /* keep last frame */ })
|
|
346
466
|
}
|
|
347
467
|
|
|
348
468
|
const show = (trackId: string, index: number): void => {
|
|
@@ -433,21 +553,14 @@ export const frames2dRenderer: PetRenderer<PetFrames2dConfig> = {
|
|
|
433
553
|
unsubscribe()
|
|
434
554
|
if (timer !== undefined) clearTimeout(timer)
|
|
435
555
|
if (watchdog !== undefined) clearInterval(watchdog)
|
|
436
|
-
// Release
|
|
437
|
-
//
|
|
438
|
-
//
|
|
556
|
+
// Release every retained bitmap and drain the pool. Queued-but-unstarted
|
|
557
|
+
// frames resolve as no-ops (the gate skips decodeFrame once disposed), and
|
|
558
|
+
// a decode that lands after this loop is closed by the resolution guard
|
|
559
|
+
// above, so teardown leaves nothing pending and nothing retained.
|
|
439
560
|
for (const queued of frameQueue.splice(0)) queued.release()
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
try {
|
|
444
|
-
const maybeClose = (frame?.source as { close?: () => void } | undefined)?.close
|
|
445
|
-
if (typeof maybeClose === 'function' && frame !== undefined) maybeClose.call(frame.source)
|
|
446
|
-
} catch { /* already released */ }
|
|
447
|
-
}).catch(() => { /* never rejects anyway */ })
|
|
448
|
-
}
|
|
449
|
-
decoding.clear()
|
|
450
|
-
})
|
|
561
|
+
for (const entry of decoding.values()) releaseFrame(entry.frame)
|
|
562
|
+
decoding.clear()
|
|
563
|
+
retainedBytes = 0
|
|
451
564
|
canvas?.remove()
|
|
452
565
|
img?.remove()
|
|
453
566
|
}
|
|
@@ -36,7 +36,7 @@ describe('createSequenceTimeline', () => {
|
|
|
36
36
|
const sequence: PetAnimation[] = ['running', 'waiting']
|
|
37
37
|
|
|
38
38
|
it('resolves identically to the per-call helper at animation-sample elapsed values', () => {
|
|
39
|
-
// The sprite frame loop asks once per
|
|
39
|
+
// The sprite frame loop asks once per frame tick with accumulated
|
|
40
40
|
// millisecond offsets; the precomputed table must agree everywhere.
|
|
41
41
|
const timeline = createSequenceTimeline(sequence, tracks)
|
|
42
42
|
for (let elapsed = 0; elapsed <= 1_500; elapsed += 7) {
|
|
@@ -51,3 +51,39 @@ describe('createSequenceTimeline', () => {
|
|
|
51
51
|
expect(timeline.frameAt(1_420)).toEqual({ animation: 'running', frameIndex: 0 })
|
|
52
52
|
})
|
|
53
53
|
})
|
|
54
|
+
|
|
55
|
+
describe('SequenceTimeline.remainingAt (issue #17)', () => {
|
|
56
|
+
const sequence: PetAnimation[] = ['running', 'waiting']
|
|
57
|
+
|
|
58
|
+
it('reports the time left in the frame the query lands on', () => {
|
|
59
|
+
const timeline = createSequenceTimeline(sequence, tracks)
|
|
60
|
+
// running frames are 100ms then 200ms, waiting 300ms then 100ms.
|
|
61
|
+
expect(timeline.remainingAt(0)).toBe(100)
|
|
62
|
+
expect(timeline.remainingAt(40)).toBe(60)
|
|
63
|
+
expect(timeline.remainingAt(100)).toBe(200)
|
|
64
|
+
expect(timeline.remainingAt(299)).toBe(1)
|
|
65
|
+
// The second item's first frame, measured from the item boundary.
|
|
66
|
+
expect(timeline.remainingAt(300)).toBe(300)
|
|
67
|
+
expect(timeline.remainingAt(600)).toBe(100)
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it('accounts for a loop wrap without overshooting', () => {
|
|
71
|
+
const timeline = createSequenceTimeline(sequence, tracks)
|
|
72
|
+
// 700ms is one full sequence: the wrap lands on running frame 0 again.
|
|
73
|
+
expect(timeline.frameAt(700)).toEqual({ animation: 'running', frameIndex: 0 })
|
|
74
|
+
expect(timeline.remainingAt(700)).toBe(100)
|
|
75
|
+
expect(timeline.remainingAt(750)).toBe(50)
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('steps over a zero-length frame instead of reporting a zero delay', () => {
|
|
79
|
+
const zeroTracks = {
|
|
80
|
+
running: track([0, 200]),
|
|
81
|
+
waiting: track([100]),
|
|
82
|
+
} as Record<PetAnimation, PetTrackDef>
|
|
83
|
+
const timeline = createSequenceTimeline(sequence, zeroTracks)
|
|
84
|
+
// The loop schedules its next wake from this value, so a zero-duration
|
|
85
|
+
// frame must resolve to the next real frame rather than to a 0ms timer.
|
|
86
|
+
expect(timeline.remainingAt(0)).toBe(200)
|
|
87
|
+
expect(timeline.remainingAt(200)).toBe(100)
|
|
88
|
+
})
|
|
89
|
+
})
|
package/src/client/sequences.ts
CHANGED
|
@@ -10,11 +10,26 @@ export interface SequenceFrame {
|
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Precomputed timeline for one looping sequence: the per-item duration table
|
|
13
|
-
* is built once instead of per query. The sprite frame loop asks
|
|
14
|
-
*
|
|
13
|
+
* is built once instead of per query. The sprite frame loop asks once per
|
|
14
|
+
* frame change, where the per-call map/reduce is pure waste.
|
|
15
15
|
*/
|
|
16
16
|
export interface SequenceTimeline {
|
|
17
17
|
frameAt(elapsedMs: number): SequenceFrame
|
|
18
|
+
/**
|
|
19
|
+
* Milliseconds from `elapsedMs` until the frame it lands on ends. The sprite
|
|
20
|
+
* loop sleeps for exactly this long instead of polling at the screen refresh
|
|
21
|
+
* rate (issue #17); the floor of 1 ms keeps a zero-length frame from turning
|
|
22
|
+
* into a busy timer.
|
|
23
|
+
*/
|
|
24
|
+
remainingAt(elapsedMs: number): number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** One sequence position, with the residual offset inside its own frame. */
|
|
28
|
+
interface SequencePoint {
|
|
29
|
+
animation: PetAnimation
|
|
30
|
+
track: PetTrackDef
|
|
31
|
+
frameIndex: number
|
|
32
|
+
offsetInFrame: number
|
|
18
33
|
}
|
|
19
34
|
|
|
20
35
|
/** Build a {@link SequenceTimeline} over one manifest sequence. */
|
|
@@ -24,22 +39,33 @@ export function createSequenceTimeline(
|
|
|
24
39
|
): SequenceTimeline {
|
|
25
40
|
const itemDurations = sequence.map(animation => tracks[animation].durations.reduce((sum, value) => sum + value, 0))
|
|
26
41
|
const sequenceDuration = itemDurations.reduce((sum, value) => sum + value, 0)
|
|
42
|
+
// One traversal serves both queries: frameAt needs the index it lands on and
|
|
43
|
+
// remainingAt needs how far into that frame it is, so resolving them
|
|
44
|
+
// separately would walk the same tables twice for one loop tick.
|
|
45
|
+
const locate = (elapsedMs: number): SequencePoint => {
|
|
46
|
+
let offset = sequenceDuration > 0 ? Math.max(0, elapsedMs) % sequenceDuration : 0
|
|
47
|
+
let itemIndex = 0
|
|
48
|
+
while (itemIndex < sequence.length - 1 && offset >= itemDurations[itemIndex]!) {
|
|
49
|
+
offset -= itemDurations[itemIndex]!
|
|
50
|
+
itemIndex += 1
|
|
51
|
+
}
|
|
52
|
+
const animation = sequence[itemIndex]!
|
|
53
|
+
const track = tracks[animation]
|
|
54
|
+
let frameIndex = 0
|
|
55
|
+
while (frameIndex < track.frames.length - 1 && offset >= track.durations[frameIndex]!) {
|
|
56
|
+
offset -= track.durations[frameIndex]!
|
|
57
|
+
frameIndex += 1
|
|
58
|
+
}
|
|
59
|
+
return { animation, track, frameIndex, offsetInFrame: offset }
|
|
60
|
+
}
|
|
27
61
|
return {
|
|
28
62
|
frameAt(elapsedMs: number): SequenceFrame {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const animation = sequence[itemIndex]!
|
|
36
|
-
const track = tracks[animation]
|
|
37
|
-
let frameIndex = 0
|
|
38
|
-
while (frameIndex < track.frames.length - 1 && offset >= track.durations[frameIndex]!) {
|
|
39
|
-
offset -= track.durations[frameIndex]!
|
|
40
|
-
frameIndex += 1
|
|
41
|
-
}
|
|
42
|
-
return { animation, frameIndex }
|
|
63
|
+
const point = locate(elapsedMs)
|
|
64
|
+
return { animation: point.animation, frameIndex: point.frameIndex }
|
|
65
|
+
},
|
|
66
|
+
remainingAt(elapsedMs: number): number {
|
|
67
|
+
const point = locate(elapsedMs)
|
|
68
|
+
return Math.max(1, (point.track.durations[point.frameIndex] ?? 0) - point.offsetInFrame)
|
|
43
69
|
},
|
|
44
70
|
}
|
|
45
71
|
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import type { PetCell } from '../registry.ts'
|
|
3
|
+
import { framePosition, scaledCellSize, trimTrack } from './spritesheet.ts'
|
|
4
|
+
|
|
5
|
+
/** The built-in hatch-pet cell (192 x 208). */
|
|
6
|
+
const CELL: PetCell = { width: 192, height: 208 }
|
|
7
|
+
|
|
8
|
+
/** The whale-girl display: `display.size` 160 over a 208px-tall cell. */
|
|
9
|
+
const SCALE = 160 / CELL.height
|
|
10
|
+
|
|
11
|
+
describe('scaledCellSize (issue #17)', () => {
|
|
12
|
+
it('rounds the scaled cell so a fractional sprite scale stays on whole pixels', () => {
|
|
13
|
+
// 192 * 160/208 = 147.69px and 208 * 160/208 = 160px before rounding.
|
|
14
|
+
expect(scaledCellSize(CELL, SCALE)).toEqual({ width: 148, height: 160 })
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('agrees with the sprite box the component renders for the same scale', () => {
|
|
18
|
+
// The element is sized from the same helper, so a cell of the scaled atlas
|
|
19
|
+
// and the box that shows it are the same rectangle instead of drifting by
|
|
20
|
+
// a fraction of a pixel per frame.
|
|
21
|
+
const scaled = scaledCellSize(CELL, SCALE)
|
|
22
|
+
expect(Math.round(CELL.width * SCALE)).toBe(scaled.width)
|
|
23
|
+
expect(Math.round(CELL.height * SCALE)).toBe(scaled.height)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('floors a collapsed cell at one pixel instead of rendering nothing', () => {
|
|
27
|
+
expect(scaledCellSize(CELL, 0.001)).toEqual({ width: 1, height: 1 })
|
|
28
|
+
})
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
describe('framePosition (issue #17)', () => {
|
|
32
|
+
it('places every column on an exact multiple of the scaled cell width', () => {
|
|
33
|
+
const scaled = scaledCellSize(CELL, SCALE)
|
|
34
|
+
for (let col = 0; col < 8; col += 1) {
|
|
35
|
+
const pos = framePosition(CELL, 0, col, SCALE)
|
|
36
|
+
expect(pos.x).toBe(-col * scaled.width)
|
|
37
|
+
expect(Number.isInteger(pos.x)).toBe(true)
|
|
38
|
+
// Row 0 is the top of the atlas; the offset is -0, which is still whole.
|
|
39
|
+
expect(Math.abs(pos.y)).toBe(0)
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('places every row on an exact multiple of the scaled cell height', () => {
|
|
44
|
+
const scaled = scaledCellSize(CELL, SCALE)
|
|
45
|
+
for (let row = 0; row < 9; row += 1) {
|
|
46
|
+
const pos = framePosition(CELL, row, 0, SCALE)
|
|
47
|
+
expect(pos.y).toBe(-row * scaled.height)
|
|
48
|
+
expect(Number.isInteger(pos.y)).toBe(true)
|
|
49
|
+
expect(Math.abs(pos.x)).toBe(0)
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('never returns a fractional offset at a scale that does not divide the cell', () => {
|
|
54
|
+
// 120/208 leaves 110.77px cells: the old formula returned -110.77px per
|
|
55
|
+
// column, which is what forced the compositor to resample the atlas.
|
|
56
|
+
const scale = 120 / CELL.height
|
|
57
|
+
const scaled = scaledCellSize(CELL, scale)
|
|
58
|
+
expect(scaled).toEqual({ width: 111, height: 120 })
|
|
59
|
+
expect(framePosition(CELL, 5, 7, scale)).toEqual({ x: -7 * 111, y: -5 * 120 })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('keeps the raw atlas grid when no scale is applied', () => {
|
|
63
|
+
expect(framePosition(CELL, 3, 5)).toEqual({ x: -5 * CELL.width, y: -3 * CELL.height })
|
|
64
|
+
})
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
describe('trimTrack', () => {
|
|
68
|
+
it('trims to the smaller of the track table and the row frame count', () => {
|
|
69
|
+
const track = { frames: [0, 1, 2, 3, 4, 5], durations: [1, 2, 3, 4, 5, 6], loop: true }
|
|
70
|
+
expect(trimTrack(track, 4)).toEqual({
|
|
71
|
+
frames: [0, 1, 2, 3],
|
|
72
|
+
durations: [1, 2, 3, 4],
|
|
73
|
+
loop: true,
|
|
74
|
+
})
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('degrades a row with no detected frames to the first frame', () => {
|
|
78
|
+
const track = { frames: [0, 1], durations: [10, 20], loop: false, fallback: 'idle' as const }
|
|
79
|
+
expect(trimTrack(track, 0)).toEqual({ frames: [0], durations: [10], loop: false, fallback: 'idle' })
|
|
80
|
+
})
|
|
81
|
+
})
|
|
@@ -19,15 +19,40 @@ export function rowOfTrack(animation: PetAnimation): number {
|
|
|
19
19
|
return rowOf(animation)
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Integer size of one cell after `scale`, in device-independent px.
|
|
24
|
+
*
|
|
25
|
+
* Rounding happens here, once, so the rendered atlas grid is integral end to
|
|
26
|
+
* end (issue #17): `background-size` is this size times the column/row count
|
|
27
|
+
* and every frame offset is an exact multiple of it. A fractional cell size
|
|
28
|
+
* leaves each frame on a sub-pixel boundary — 192px cells at `display.size`
|
|
29
|
+
* 160 scale to 147.69px — and the compositor then has to resample the whole
|
|
30
|
+
* scaled atlas on every frame change instead of translating an already-scaled
|
|
31
|
+
* bitmap by whole pixels. The pet advances a frame every 300-700 ms, so that
|
|
32
|
+
* resample was running continuously for a background surface the size of the
|
|
33
|
+
* sprite. A floor of 1px keeps a legally tiny display.size from collapsing the
|
|
34
|
+
* cell to zero and rendering nothing.
|
|
35
|
+
*/
|
|
36
|
+
export function scaledCellSize(cell: PetCell, scale: number): { width: number; height: number } {
|
|
37
|
+
return {
|
|
38
|
+
width: Math.max(1, Math.round(cell.width * scale)),
|
|
39
|
+
height: Math.max(1, Math.round(cell.height * scale)),
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
22
43
|
/**
|
|
23
44
|
* Background-position (px) of one frame cell within the scaled atlas.
|
|
24
45
|
* The background image is scaled by `scale` (element size ÷ cell size), and
|
|
25
46
|
* background-position offsets are applied in SCALED coordinates — using raw
|
|
26
47
|
* atlas coordinates here would drift each frame by the scale factor and
|
|
27
|
-
* render torn/overlapping frames.
|
|
48
|
+
* render torn/overlapping frames. The scaled cell is quantized by
|
|
49
|
+
* {@link scaledCellSize}, so the offset of frame N is exactly N whole cells:
|
|
50
|
+
* the atlas is snapped to the pixel grid and a frame change is a plain
|
|
51
|
+
* translate of the scaled bitmap.
|
|
28
52
|
*/
|
|
29
53
|
export function framePosition(cell: PetCell, row: number, col: number, scale = 1): { x: number; y: number } {
|
|
30
|
-
|
|
54
|
+
const scaled = scaledCellSize(cell, scale)
|
|
55
|
+
return { x: -col * scaled.width, y: -row * scaled.height }
|
|
31
56
|
}
|
|
32
57
|
|
|
33
58
|
/**
|
package/src/registry.test.ts
CHANGED
|
@@ -315,17 +315,19 @@ describe('loadPetRegistry', () => {
|
|
|
315
315
|
})
|
|
316
316
|
|
|
317
317
|
// The repo checkout also resolves doro and miku (frames2d gameplay pets),
|
|
318
|
-
// jyn and jyn-
|
|
319
|
-
//
|
|
318
|
+
// jyn, jyn-foxtail and jyn-loli (frames2d gameplay pets), long-niang
|
|
319
|
+
// (sprite2d pet), starry-doll and deep-chan (community sprite2d pets) from
|
|
320
320
|
// assets/; the npm files whitelist excludes them (Workshop delivery), so
|
|
321
321
|
// npm installs see the atlas pets until a Workshop install lands them
|
|
322
322
|
// under $DSH_HOME/pets. blue-throated-bee-eater ships bundled alongside
|
|
323
323
|
// the other atlas pets.
|
|
324
324
|
expect(registry.entries.map(entry => entry.id)).toEqual([
|
|
325
325
|
'blue-throated-bee-eater',
|
|
326
|
+
'deep-chan',
|
|
326
327
|
'doro',
|
|
327
328
|
'jyn',
|
|
328
329
|
'jyn-foxtail',
|
|
330
|
+
'jyn-loli',
|
|
329
331
|
'long-niang',
|
|
330
332
|
'miku',
|
|
331
333
|
'ouo-neko',
|
package/lib/invariant.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { a as AFFINITY_MAX, n as animationForPhase, o as AFFINITY_RANKS, u as defaultAffinityConfig } from "./state-NvDEoCln.js";
|
|
2
|
-
//#region src/invariant.ts
|
|
3
|
-
/**
|
|
4
|
-
* Package invariants — cheap structural checks run at import time on the
|
|
5
|
-
* host side. Mirrors the pattern used by other dsh plugin packages.
|
|
6
|
-
* @module @linxin666/dsh-pet/invariant
|
|
7
|
-
*/
|
|
8
|
-
/** Assert a condition; throws a descriptive Error when violated. */
|
|
9
|
-
function invariant(condition, message) {
|
|
10
|
-
if (!condition) throw new Error(`[dsh-pet] ${message}`);
|
|
11
|
-
}
|
|
12
|
-
/** Run every package invariant once; throws on the first violation. */
|
|
13
|
-
function runPetInvariants() {
|
|
14
|
-
invariant(AFFINITY_MAX > 0, "AFFINITY_MAX must be positive");
|
|
15
|
-
invariant(AFFINITY_RANKS.length > 0 && AFFINITY_RANKS[0].min === 0, "AFFINITY_RANKS must start at 0");
|
|
16
|
-
invariant(defaultAffinityConfig.turnReward > 0, "turnReward must be positive");
|
|
17
|
-
invariant(defaultAffinityConfig.feedCooldownMs > defaultAffinityConfig.petCooldownMs, "feed cooldown must exceed pet cooldown");
|
|
18
|
-
for (const phase of [
|
|
19
|
-
"idle",
|
|
20
|
-
"waiting",
|
|
21
|
-
"thinking",
|
|
22
|
-
"tool",
|
|
23
|
-
"done"
|
|
24
|
-
]) invariant([
|
|
25
|
-
"idle",
|
|
26
|
-
"running",
|
|
27
|
-
"running-right",
|
|
28
|
-
"waiting",
|
|
29
|
-
"jumping"
|
|
30
|
-
].includes(animationForPhase(phase)), `phase ${phase} maps outside the animation contract`);
|
|
31
|
-
}
|
|
32
|
-
runPetInvariants();
|
|
33
|
-
//#endregion
|
|
34
|
-
export { invariant, runPetInvariants };
|