dsh-game-material-master 0.9.2 → 0.10.0

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.
@@ -0,0 +1,471 @@
1
+ /**
2
+ * 45° 地图编辑器(模块五 · iso)的**绘制计划与光栅化**。
3
+ *
4
+ * 宿主是唯一渲染器:每个计划条目 = 「用哪块图、画在哪个像素、在第几层多深」。
5
+ * 客户端只 `drawImage`,导出 PNG 执行**同一份计划**并按同一个 `z` 排序。
6
+ *
7
+ * 与模块六的三个关键差异(都是等距带来的):
8
+ *
9
+ * 1. 格子是菱形,贴图按**菱形中心**摆放;
10
+ * 2. 绘制顺序不能按 chunk / 行优先,必须按宿主算好的 `z`(前后遮挡);
11
+ * 3. 物件是一张完整图,不是按格切开的图块,可以高出一格。
12
+ */
13
+ import { encodePng } from "./png.js";
14
+ import { cellIndex } from "./isodoc.js";
15
+ import { cellCenter, cellTopLeft, chunkKey, chunkOf, expandBounds, groundBounds, isoDepthZ, layoutOf, objectTopLeft, parseChunkKey, wrapCell } from "./isogeom.js";
16
+ import { corner16Mask, nearestMask } from "./mapauto.js";
17
+ import { applyLoop, flatTiles } from "./maptiles.js";
18
+ /** 单张导出图的最大像素数(超过就明确拒绝,而不是把进程 OOM 掉)。 */
19
+ export const MAX_ISO_RENDER_PIXELS = 64_000_000;
20
+ /** 动画帧率:与模块六一致,1 帧/秒是默认档。 */
21
+ const DEFAULT_FPS = 1;
22
+ function tilesetBaseIndex(tilesets) {
23
+ const out = new Map();
24
+ for (const flat of flatTiles(tilesets)) {
25
+ if (!out.has(flat.tilesetId))
26
+ out.set(flat.tilesetId, flat.index);
27
+ }
28
+ return out;
29
+ }
30
+ export function isoRenderContext(project, doc, tilesets) {
31
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
32
+ return { cell: project.cell, layout, tilesets, lookup: new Map(flatTiles(tilesets).map((flat) => [flat.index, flat])) };
33
+ }
34
+ /** 物件的展示帧尺寸(第 0 帧的 rect;所有帧同尺寸)。 */
35
+ export function objectFrameRect(tileset) {
36
+ const first = tileset.tiles.find((tile) => (tile.frame ?? 0) === 0) ?? tileset.tiles[0];
37
+ return first?.rect;
38
+ }
39
+ /** 计划包围盒:网格脚印 + 每个物件图片向上 / 左右溢出的部分。 */
40
+ export function planBounds(context, doc) {
41
+ const layout = context.layout;
42
+ let bounds = groundBounds(layout);
43
+ const byId = new Map(context.tilesets.map((tileset) => [tileset.id, tileset]));
44
+ for (const object of doc.objects) {
45
+ const tileset = byId.get(object.tilesetId);
46
+ if (tileset === undefined || tileset.kind !== "object" || tileset.footprint === undefined)
47
+ continue;
48
+ const rect = objectFrameRect(tileset);
49
+ if (rect === undefined)
50
+ continue;
51
+ const topLeft = objectTopLeft(layout, object.r, object.c, tileset.footprint, rect.width, rect.height, tileset.anchor);
52
+ bounds = expandBounds(bounds, { x: topLeft.x, y: topLeft.y, width: rect.width, height: rect.height });
53
+ }
54
+ return bounds ?? { originX: 0, originY: 0, width: 1, height: 1 };
55
+ }
56
+ function cellOpsAt(env, layerIndex, layerId, rr, cc) {
57
+ const w = wrapCell(env.layout, rr, cc);
58
+ if (w.r < 0 || w.c < 0 || w.r >= env.doc.rows || w.c >= env.doc.cols)
59
+ return [];
60
+ const data = env.doc.data[layerId];
61
+ const value = data === undefined ? 0 : data[cellIndex(env.doc, w.r, w.c)];
62
+ if (!(value > 0))
63
+ return [];
64
+ const flat = env.context.lookup.get(value);
65
+ if (flat === undefined) {
66
+ env.sink.missing.add(value);
67
+ return [];
68
+ }
69
+ const tileset = env.tilesetById.get(flat.tilesetId);
70
+ const base = env.baseIndex.get(flat.tilesetId);
71
+ if (tileset === undefined || base === undefined || tileset.kind === "object") {
72
+ env.sink.missing.add(value);
73
+ return [];
74
+ }
75
+ const local = value - base;
76
+ if (local < 0 || local >= tileset.tiles.length) {
77
+ env.sink.missing.add(value);
78
+ return [];
79
+ }
80
+ const at = (nr, nc) => {
81
+ const cell = wrapCell(env.layout, nr, nc);
82
+ if (cell.r < 0 || cell.c < 0 || cell.r >= env.doc.rows || cell.c >= env.doc.cols)
83
+ return false;
84
+ const raw = data === undefined ? 0 : data[cellIndex(env.doc, cell.r, cell.c)];
85
+ if (!(raw > 0))
86
+ return false;
87
+ const neighbor = env.context.lookup.get(raw);
88
+ return neighbor !== undefined && neighbor.tilesetId === tileset.id;
89
+ };
90
+ const position = cellTopLeft(env.layout, rr, cc, tileset.cell.width, tileset.cell.height);
91
+ const z = isoDepthZ(layerIndex, rr, cc);
92
+ if (tileset.kind === "autotile") {
93
+ const configured = [];
94
+ for (const tile of tileset.tiles)
95
+ if (typeof tile.mask === "number")
96
+ configured.push(tile.mask);
97
+ let used;
98
+ if (configured.length === 0) {
99
+ env.sink.autotileUnmasked.add(tileset.id);
100
+ used = 0;
101
+ }
102
+ else {
103
+ const wanted = corner16Mask(at, w.r, w.c);
104
+ used = configured.includes(wanted) ? wanted : nearestMask(wanted, configured);
105
+ if (used !== undefined && used !== wanted) {
106
+ const key = `${tileset.id}|${wanted}|${used}`;
107
+ const row = env.sink.autotileFallback.get(key);
108
+ if (row === undefined)
109
+ env.sink.autotileFallback.set(key, { tilesetId: tileset.id, wanted, used, cells: 1 });
110
+ else
111
+ row.cells++;
112
+ }
113
+ }
114
+ if (used === undefined)
115
+ used = 0;
116
+ const found = tileset.tiles.findIndex((tile) => (tile.mask ?? -1) === used);
117
+ if (found < 0) {
118
+ env.sink.autotileUnmasked.add(tileset.id);
119
+ return [];
120
+ }
121
+ return [{ l: layerIndex, r: w.r, c: w.c, t: base + found, x: Math.round(position.x), y: Math.round(position.y), a: 1, z }];
122
+ }
123
+ let cycle;
124
+ if (tileset.animRows === true && tileset.frames > 1 && tileset.columns > 0) {
125
+ const column = local % tileset.columns;
126
+ const frames = [];
127
+ for (let row = 0; row < tileset.frames; row++) {
128
+ const index = row * tileset.columns + column;
129
+ if (index >= tileset.tiles.length)
130
+ break;
131
+ frames.push(base + index);
132
+ }
133
+ if (frames.length > 1)
134
+ cycle = applyLoop(frames, tileset.loop ?? "forward");
135
+ }
136
+ const op = {
137
+ l: layerIndex,
138
+ r: w.r,
139
+ c: w.c,
140
+ t: cycle === undefined ? base + local : cycle[0],
141
+ x: Math.round(position.x),
142
+ y: Math.round(position.y),
143
+ a: 1,
144
+ z
145
+ };
146
+ if (cycle !== undefined) {
147
+ op.cycle = cycle;
148
+ if (tileset.fps !== undefined)
149
+ op.fps = tileset.fps;
150
+ }
151
+ return [op];
152
+ }
153
+ function objectOp(env, layerIndex, object) {
154
+ const tileset = env.tilesetById.get(object.tilesetId);
155
+ if (tileset === undefined || tileset.kind !== "object" || tileset.footprint === undefined) {
156
+ env.sink.objectMissing.add(object.tilesetId);
157
+ return undefined;
158
+ }
159
+ const base = env.baseIndex.get(tileset.id);
160
+ const rect = objectFrameRect(tileset);
161
+ if (base === undefined || rect === undefined) {
162
+ env.sink.objectMissing.add(tileset.id);
163
+ return undefined;
164
+ }
165
+ const first = tileset.tiles.find((tile) => (tile.frame ?? 0) === 0) ?? tileset.tiles[0];
166
+ if (first === undefined) {
167
+ env.sink.objectMissing.add(tileset.id);
168
+ return undefined;
169
+ }
170
+ const firstIndex = base + tileset.tiles.indexOf(first);
171
+ if (firstIndex < base || firstIndex >= base + tileset.tiles.length) {
172
+ env.sink.objectMissing.add(tileset.id);
173
+ return undefined;
174
+ }
175
+ let cycle;
176
+ if (tileset.frames > 1) {
177
+ const frames = [];
178
+ for (let frame = 0; frame < tileset.frames; frame++) {
179
+ const found = tileset.tiles.findIndex((tile) => (tile.frame ?? 0) === frame);
180
+ if (found < 0)
181
+ break;
182
+ frames.push(base + found);
183
+ }
184
+ if (frames.length > 1)
185
+ cycle = applyLoop(frames, tileset.loop ?? "forward");
186
+ }
187
+ const topLeft = objectTopLeft(env.layout, object.r, object.c, tileset.footprint, rect.width, rect.height, tileset.anchor);
188
+ const op = {
189
+ l: layerIndex,
190
+ r: object.r,
191
+ c: object.c,
192
+ t: cycle === undefined ? firstIndex : cycle[0],
193
+ x: Math.round(topLeft.x),
194
+ y: Math.round(topLeft.y),
195
+ a: 1,
196
+ z: isoDepthZ(layerIndex, object.r, object.c, tileset.footprint)
197
+ };
198
+ if (cycle !== undefined) {
199
+ op.cycle = cycle;
200
+ if (tileset.fps !== undefined)
201
+ op.fps = tileset.fps;
202
+ }
203
+ return op;
204
+ }
205
+ function objectIntersectsRange(object, footprint, range) {
206
+ for (let dr = 0; dr < footprint.rows; dr++) {
207
+ for (let dc = 0; dc < footprint.cols; dc++) {
208
+ const r = object.r + dr;
209
+ const c = object.c + dc;
210
+ if (r >= range.r0 && r < range.r1 && c >= range.c0 && c < range.c1)
211
+ return true;
212
+ }
213
+ }
214
+ return false;
215
+ }
216
+ /**
217
+ * 生成绘制计划。
218
+ *
219
+ * - `range` 缺省 = 整张地图(导出走这条,不环绕);
220
+ * - 给了就越界也算(环绕),同一格会在多个像素位置出现;
221
+ * - `layers` 只算这些层号(单层预览);`op.l` 仍是真实层号。
222
+ */
223
+ export function buildIsoPlan(context, doc, opts = {}) {
224
+ const layout = context.layout;
225
+ const range = opts.range ?? { r0: 0, c0: 0, r1: doc.rows, c1: doc.cols };
226
+ const keepLayers = opts.layers === undefined ? undefined : new Set(opts.layers);
227
+ const legend = opts.includeLegend === false
228
+ ? []
229
+ : flatTiles(context.tilesets).map((flat) => {
230
+ const tileset = context.tilesets.find((entry) => entry.id === flat.tilesetId);
231
+ return { index: flat.index, tilesetId: flat.tilesetId, rect: flat.tile.rect, kind: (tileset?.kind ?? "ground") };
232
+ });
233
+ const env = {
234
+ context,
235
+ doc,
236
+ layout,
237
+ baseIndex: tilesetBaseIndex(context.tilesets),
238
+ tilesetById: new Map(context.tilesets.map((tileset) => [tileset.id, tileset])),
239
+ sink: { missing: new Set(), missingTileset: new Set(), autotileFallback: new Map(), autotileUnmasked: new Set(), objectMissing: new Set() }
240
+ };
241
+ const buckets = new Map();
242
+ const push = (op, r, c) => {
243
+ const key = chunkKey(chunkOf(r, c));
244
+ const list = buckets.get(key);
245
+ if (list === undefined)
246
+ buckets.set(key, [op]);
247
+ else
248
+ list.push(op);
249
+ };
250
+ for (let layerIndex = 0; layerIndex < doc.layers.length; layerIndex++) {
251
+ if (keepLayers !== undefined && !keepLayers.has(layerIndex))
252
+ continue;
253
+ const layer = doc.layers[layerIndex];
254
+ if (layer === undefined)
255
+ continue;
256
+ if (layer.kind === "ground") {
257
+ for (let rr = range.r0; rr < range.r1; rr++) {
258
+ for (let cc = range.c0; cc < range.c1; cc++) {
259
+ for (const op of cellOpsAt(env, layerIndex, layer.id, rr, cc))
260
+ push(op, rr, cc);
261
+ }
262
+ }
263
+ }
264
+ else {
265
+ for (const object of doc.objects) {
266
+ if (object.layerId !== layer.id)
267
+ continue;
268
+ const tileset = env.tilesetById.get(object.tilesetId);
269
+ const footprint = tileset?.footprint ?? { cols: 1, rows: 1 };
270
+ if (!objectIntersectsRange(object, footprint, range))
271
+ continue;
272
+ const op = objectOp(env, layerIndex, object);
273
+ if (op !== undefined)
274
+ push(op, object.r, object.c);
275
+ }
276
+ }
277
+ }
278
+ const warnings = [];
279
+ if (context.tilesets.length === 0)
280
+ warnings.push("还没有素材:先导入一张素材图,或者用内置素材。");
281
+ if (env.sink.missing.size > 0)
282
+ warnings.push(`地图里用到了 ${env.sink.missing.size} 个找不到的图块序号(素材被删过或改过切分),这些格子没有画出来。`);
283
+ for (const row of env.sink.autotileFallback.values()) {
284
+ const name = env.tilesetById.get(row.tilesetId)?.name ?? row.tilesetId;
285
+ warnings.push(`素材「${name}」没有第 ${row.wanted} 种接法,${row.cells} 个格子用了最接近的第 ${row.used} 种顶上。`);
286
+ }
287
+ for (const id of env.sink.autotileUnmasked) {
288
+ const name = env.tilesetById.get(id)?.name ?? id;
289
+ warnings.push(`素材「${name}」是自动连接,但没有可用的 16 块接法,画不出来。`);
290
+ }
291
+ for (const id of env.sink.objectMissing) {
292
+ const name = env.tilesetById.get(id)?.name ?? id;
293
+ warnings.push(`地图里引用了「${name}」的物件,但素材不见了或不是物件,这些物件没有画出来。`);
294
+ }
295
+ const chunks = [];
296
+ const cycles = [];
297
+ const seenCycles = new Set();
298
+ let frameCount = 1;
299
+ let fpsMax = DEFAULT_FPS;
300
+ const ordered = [...buckets.entries()].sort((a, b) => {
301
+ const pa = parseChunkKey(a[0]) ?? { cx: 0, cy: 0 };
302
+ const pb = parseChunkKey(b[0]) ?? { cx: 0, cy: 0 };
303
+ return pa.cy - pb.cy || pa.cx - pb.cx;
304
+ });
305
+ for (const [key, list] of ordered) {
306
+ list.sort((a, b) => a.z - b.z || a.r - b.r || a.c - b.c);
307
+ for (const op of list) {
308
+ if (op.cycle === undefined)
309
+ continue;
310
+ if (op.cycle.length > frameCount)
311
+ frameCount = op.cycle.length;
312
+ if (typeof op.fps === "number" && op.fps > fpsMax)
313
+ fpsMax = op.fps;
314
+ const id = op.cycle.join(",");
315
+ if (seenCycles.has(id))
316
+ continue;
317
+ seenCycles.add(id);
318
+ cycles.push(op.cycle);
319
+ }
320
+ chunks.push({ key, ops: list });
321
+ }
322
+ return {
323
+ chunks,
324
+ bounds: planBounds(context, doc),
325
+ legend,
326
+ fps: DEFAULT_FPS,
327
+ fpsMax,
328
+ frameCount,
329
+ cycles,
330
+ markers: buildIsoMarkers(context, doc, range),
331
+ warnings
332
+ };
333
+ }
334
+ /** 落在 range 里的标记(编号 = 数组下标 + 1,每次整份重发)。 */
335
+ export function buildIsoMarkers(context, doc, range) {
336
+ if (doc.markers.length === 0)
337
+ return [];
338
+ const layout = context.layout;
339
+ const byCell = new Map();
340
+ doc.markers.forEach((marker, index) => byCell.set(marker.r * doc.cols + marker.c, { n: index + 1, marker }));
341
+ const radius = Math.max(5, Math.round(layout.cell.width * 0.18));
342
+ const font = Math.max(8, Math.round(radius * 1.2));
343
+ const out = [];
344
+ for (let rr = range.r0; rr < range.r1; rr++) {
345
+ for (let cc = range.c0; cc < range.c1; cc++) {
346
+ const w = wrapCell(layout, rr, cc);
347
+ if (w.r < 0 || w.c < 0 || w.r >= doc.rows || w.c >= doc.cols)
348
+ continue;
349
+ const hit = byCell.get(w.r * doc.cols + w.c);
350
+ if (hit === undefined)
351
+ continue;
352
+ const center = cellCenter(layout, rr, cc);
353
+ out.push({
354
+ id: hit.marker.id,
355
+ n: hit.n,
356
+ name: hit.marker.name,
357
+ r: w.r,
358
+ c: w.c,
359
+ x: Math.round(center.x),
360
+ y: Math.round(center.y),
361
+ radius,
362
+ font
363
+ });
364
+ }
365
+ }
366
+ return out;
367
+ }
368
+ /** 物件占格的通行性(「区域」叠加与导出共用)。 */
369
+ export function passCellsOf(context, doc) {
370
+ const out = new Map();
371
+ const layout = context.layout;
372
+ for (const object of doc.objects) {
373
+ const tileset = context.tilesets.find((entry) => entry.id === object.tilesetId);
374
+ if (tileset === undefined || tileset.kind !== "object" || tileset.footprint === undefined)
375
+ continue;
376
+ const pass = tileset.pass ?? [];
377
+ for (let dr = 0; dr < tileset.footprint.rows; dr++) {
378
+ for (let dc = 0; dc < tileset.footprint.cols; dc++) {
379
+ const wrapped = wrapCell(layout, object.r + dr, object.c + dc);
380
+ if (wrapped.r < 0 || wrapped.c < 0 || wrapped.r >= doc.rows || wrapped.c >= doc.cols)
381
+ continue;
382
+ const kind = pass[dr * tileset.footprint.cols + dc] ?? 1;
383
+ out.set(`${wrapped.r},${wrapped.c}`, { r: wrapped.r, c: wrapped.c, kind });
384
+ }
385
+ }
386
+ }
387
+ return [...out.values()];
388
+ }
389
+ // ── 光栅化 ───────────────────────────────────────────────────────────────
390
+ function blendPixel(dst, index, r, g, b, a) {
391
+ if (a <= 0)
392
+ return;
393
+ const sa = Math.min(1, a);
394
+ const da = dst[index + 3] / 255;
395
+ const outA = sa + da * (1 - sa);
396
+ if (outA <= 0)
397
+ return;
398
+ const mix = (s, d) => Math.round((s * sa + d * da * (1 - sa)) / outA);
399
+ dst[index] = mix(r, dst[index]);
400
+ dst[index + 1] = mix(g, dst[index + 1]);
401
+ dst[index + 2] = mix(b, dst[index + 2]);
402
+ dst[index + 3] = Math.round(outA * 255);
403
+ }
404
+ function blitScaled(dst, source, rect, dx, dy, scale, alpha) {
405
+ const x0 = Math.max(0, -dx);
406
+ const y0 = Math.max(0, -dy);
407
+ const x1 = Math.min(Math.ceil(rect.width * scale), Math.ceil((dst.width - dx) / 1));
408
+ const y1 = Math.min(Math.ceil(rect.height * scale), Math.ceil((dst.height - dy) / 1));
409
+ for (let sy = y0; sy < y1; sy++) {
410
+ const srcY = rect.y + Math.floor(sy / scale);
411
+ if (srcY < 0 || srcY >= source.height)
412
+ continue;
413
+ for (let sx = x0; sx < x1; sx++) {
414
+ const srcX = rect.x + Math.floor(sx / scale);
415
+ if (srcX < 0 || srcX >= source.width)
416
+ continue;
417
+ const si = (srcY * source.width + srcX) * 4;
418
+ const sa = (source.rgba[si + 3] / 255) * alpha;
419
+ if (sa <= 0)
420
+ continue;
421
+ const tx = dx + sx;
422
+ const ty = dy + sy;
423
+ if (tx < 0 || ty < 0 || tx >= dst.width || ty >= dst.height)
424
+ continue;
425
+ blendPixel(dst.rgba, (ty * dst.width + tx) * 4, source.rgba[si], source.rgba[si + 1], source.rgba[si + 2], sa);
426
+ }
427
+ }
428
+ }
429
+ /**
430
+ * 把计划光栅化成位图(导出 `map.png` 用)。
431
+ *
432
+ * **按 `z` 排序后绘制**,与客户端完全同一顺序。只画第 0 帧:
433
+ * PNG 是静帧,动画信息留在 `map.json` 与计划里。
434
+ */
435
+ export function rasterizeIso(context, doc, lookup, options = {}) {
436
+ const scale = Math.max(1, Math.round(options.scale ?? 1));
437
+ const plan = buildIsoPlan(context, doc, { includeLegend: true });
438
+ const width = Math.ceil(plan.bounds.width * scale);
439
+ const height = Math.ceil(plan.bounds.height * scale);
440
+ if (width < 1 || height < 1)
441
+ throw new Error("这张地图还没有任何内容,先画点东西再导出。");
442
+ if (width * height > MAX_ISO_RENDER_PIXELS) {
443
+ throw new Error(`导出图会到 ${width}×${height}(${((width * height) / 1e6).toFixed(1)}M 像素),超过 ${MAX_ISO_RENDER_PIXELS / 1e6}M 上限。请把缩放调小,或把地图拆小。`);
444
+ }
445
+ const bitmap = { width, height, rgba: Buffer.alloc(width * height * 4) };
446
+ const legend = new Map(plan.legend.map((entry) => [entry.index, entry]));
447
+ const warnings = [...plan.warnings];
448
+ const missingBitmaps = new Set();
449
+ const ops = plan.chunks.flatMap((chunk) => chunk.ops).sort((a, b) => a.z - b.z || a.r - b.r || a.c - b.c);
450
+ let drawn = 0;
451
+ for (const op of ops) {
452
+ const entry = legend.get(op.t);
453
+ if (entry === undefined)
454
+ continue;
455
+ const source = lookup.get(entry.tilesetId);
456
+ if (source === undefined) {
457
+ missingBitmaps.add(entry.tilesetId);
458
+ continue;
459
+ }
460
+ blitScaled(bitmap, source, entry.rect, Math.round((op.x - plan.bounds.originX) * scale), Math.round((op.y - plan.bounds.originY) * scale), scale, op.a);
461
+ drawn++;
462
+ }
463
+ for (const id of missingBitmaps) {
464
+ const name = context.tilesets.find((tileset) => tileset.id === id)?.name ?? id;
465
+ warnings.push(`素材「${name}」的图片没有解码出来,它上面的内容没有画进 PNG。`);
466
+ }
467
+ return { bitmap, bounds: plan.bounds, warnings, drawn };
468
+ }
469
+ export function isoBitmapToPng(bitmap) {
470
+ return encodePng(bitmap.rgba, bitmap.width, bitmap.height);
471
+ }