diff --git a/apps/desktop/package.json b/apps/desktop/package.json index ff620fb..0540ec2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -41,6 +41,8 @@ "es-toolkit": "^1.53.0", "fast-json-patch": "^3.1.1", "html-react-parser": "^6.1.9", + "jsonc-parser": "^3.3.1", + "konva": "^10.9.1", "kysely": "^0.29.7", "lucide-react": "^1.62.0", "mdast-util-from-markdown": "^2.1.0", @@ -52,11 +54,13 @@ "quickjs-emscripten": "^0.32.0", "react": "^19.3.1", "react-dom": "^19.3.1", + "react-konva": "^19.3.2", "react-markdown": "^10.1.0", "react-photo-view": "1.2.7", "remark-gfm": "^4.0.1", "ses": "^2.3.0", "streamdown": "^2.7.1", + "toml-eslint-parser": "^1.0.3", "tw-animate-css": "^1.4.0", "typebox": "1.3.7", "zod": "^4.6.7" diff --git a/apps/desktop/src/main/modules/map-editor.test.ts b/apps/desktop/src/main/modules/map-editor.test.ts new file mode 100644 index 0000000..830c1fc --- /dev/null +++ b/apps/desktop/src/main/modules/map-editor.test.ts @@ -0,0 +1,180 @@ +import { expect, test } from "bun:test"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { openMapEdit, saveMapEdit } from "./map-editor"; +for (const ext of ["json", "toml"]) + test(ext + " 地图只改指定坐标并拒绝覆盖外部修改", async () => { + const root = await mkdtemp(join(tmpdir(), "map-edit-")); + try { + const path = "maps/test." + ext, + file = join(root, path); + const source = + ext === "json" + ? '{"name":"测试","width":100,"height":100,"image":"a.png","grid":{"type":"none","unit":"米","pixelsPerUnit":1},"walls":[{"points":[[1,2], [3, 4], [5,6]]}],"doors":[{"id":"门","from":[1,2],"to":[3, 4]}]}' + : 'name="测试"\nwidth=100\nheight=100\nimage="a.png"\ngrid={type="none",unit="米",pixelsPerUnit=1}\n[[walls]]\npoints=[[1,2], [3, 4], [5,6]] # 墙\n[[doors]]\nid="门"\nfrom=[1,2]\nto=[3, 4] # 门\n'; + await mkdir(join(root, "maps")); + await writeFile(file, source); + const { revision } = openMapEdit(root, path); + saveMapEdit(root, path, revision, [ + { layer: "walls", index: 0, vertex: 1, at: [8, 9] }, + { layer: "doors", index: 0, vertex: 1, at: [8, 9] }, + ]); + expect(await readFile(file, "utf8")).toBe(source.replaceAll("3, 4", "8, 9")); + const reopened = openMapEdit(root, path); + expect(reopened.config.doors[0].to).toEqual([8, 9]); + await writeFile(file, source + "\n"); + expect(() => saveMapEdit(root, path, reopened.revision, [])).toThrow("外部修改"); + expect(await readFile(file, "utf8")).toBe(source + "\n"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + +import { firstBlocked, pointInPolygon, wallSegments } from "@jointarp/module/map-geometry"; + +import { previewSight } from "../../renderer/src/features/modules/map-inspector-sight"; +for (const ext of ["toml", "json"]) + test(ext + " 空地图建两室,切门保存后开门通行并恢复视线", async () => { + const root = await mkdtemp(join(tmpdir(), "map-room-")); + try { + const path = "maps/test." + ext, + file = join(root, path); + await mkdir(join(root, "maps")); + await writeFile( + file, + ext === "toml" + ? 'name="两室"\nwidth=100\nheight=100\nimage="a.png"\ngrid={type="none",unit="米",pixelsPerUnit=1}\n# 保留说明\n' + : JSON.stringify({ + name: "两室", + width: 100, + height: 100, + image: "a.png", + grid: { type: "none", unit: "米", pixelsPerUnit: 1 }, + }), + ); + saveMapEdit(root, path, openMapEdit(root, path).revision, [ + { + kind: "wall", + points: [ + [0, 0], + [100, 0], + [100, 100], + [0, 100], + [0, 0], + ], + }, + { + kind: "wall", + points: [ + [50, 0], + [50, 100], + ], + }, + { kind: "door", wall: 1, segment: 0, start: 0.4, end: 0.6 }, + ]); + const { config, revision } = openMapEdit(root, path); + const door = config.doors[0]; + expect(config.walls.length).toBe(3); + const route = [ + [25, 50], + [75, 50], + ] as const; + for (const open of [false, true]) { + door.open = open; + const blockers = wallSegments(config); + if (!open) blockers.push({ a: door.from, b: door.to }); + expect(!!firstBlocked(route, blockers)).toBe(!open); + expect(pointInPolygon(route[1], previewSight(config, [25, 50]))).toBe(open); + } + saveMapEdit(root, path, revision, [ + { kind: "delete", layer: "doors", index: 0 }, + { kind: "delete", layer: "walls", index: 2 }, + ]); + expect(openMapEdit(root, path).config.doors).toHaveLength(0); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + +for (const ext of ["json", "toml"]) + test(ext + " 设置及移除上级,拒绝保存循环", async () => { + const root = await mkdtemp(join(tmpdir(), "map-parent-")); + try { + const path = "maps/旅馆." + ext; + const town = "maps/城镇.JSON"; + const config = { + name: "旅馆", + width: 100, + height: 100, + image: "a.png", + grid: { type: "none", unit: "米", pixelsPerUnit: 1 }, + }; + await mkdir(join(root, "maps")); + await writeFile(join(root, town), JSON.stringify(config)); + await writeFile( + join(root, path), + ext === "json" + ? JSON.stringify(config) + : 'name="旅馆"\nwidth=100\nheight=100\nimage="a.png"\n[grid]\ntype="none"\nunit="米"\npixelsPerUnit=1\n', + ); + const parent = (file: string, value: string | null) => + saveMapEdit(root, file, openMapEdit(root, file).revision, [ + { kind: "parent", parent: value }, + ]); + parent(path, "城镇"); + expect(openMapEdit(root, path).config.parent).toBe("城镇"); + expect(() => parent(town, "旅馆")).toThrow("循环"); + expect(() => parent(path, "缺失")).toThrow("不存在"); + parent(path, null); + expect(openMapEdit(root, path).config.parent).toBeUndefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + +for (const ext of ["json", "toml"]) + test(ext + " 画布新增起点并配对,重新加载、取消配对和目标缺失", async () => { + const root = await mkdtemp(join(tmpdir(), "map-links-")); + try { + await mkdir(join(root, "maps")); + const file = "maps/楼上." + ext; + const base = { + name: "测试", + image: "a.png", + width: 100, + height: 100, + grid: { type: "none", pixelsPerUnit: 1, unit: "米" }, + }; + const target = "maps/楼下.json"; + await writeFile( + join(root, file), + ext === "toml" + ? 'name="测试"\nimage="a.png"\nwidth=100\nheight=100\n[grid]\ntype="none"\npixelsPerUnit=1\nunit="米"\n' + : JSON.stringify(base), + ); + await writeFile( + join(root, target), + JSON.stringify({ ...base, starts: [{ id: "楼梯", name: "楼梯", at: [10, 20] }] }), + ); + const link = { from: "东楼梯", map: "楼下", to: "楼梯", oneWay: false }; + saveMapEdit(root, file, openMapEdit(root, file).revision, [ + { kind: "start", start: { id: "东楼梯", name: "东楼梯", at: [30, 40] } }, + { kind: "connect", link }, + ]); + const saved = openMapEdit(root, file); + expect(saved.config.connections).toEqual([link]); + expect(() => + saveMapEdit(root, file, saved.revision, [ + { kind: "connect", link: { ...link, to: "不存在" } }, + ]), + ).toThrow("目标地图或起点"); + expect(openMapEdit(root, file).revision).toBe(saved.revision); + saveMapEdit(root, file, saved.revision, [{ kind: "disconnect", index: 0 }]); + expect(openMapEdit(root, file).config.connections).toEqual([]); + expect(openMapEdit(root, file).config.starts[0].at).toEqual([30, 40]); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); diff --git a/apps/desktop/src/main/modules/map-editor.ts b/apps/desktop/src/main/modules/map-editor.ts new file mode 100644 index 0000000..78e0bc8 --- /dev/null +++ b/apps/desktop/src/main/modules/map-editor.ts @@ -0,0 +1,238 @@ +import { createHash } from "node:crypto"; +import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; +import { basename, dirname, resolve } from "node:path"; +import { isDeepStrictEqual } from "node:util"; + +import { writeFileAtomicSync } from "@jointarp/core/node/storage/write-file-atomic"; +import { + mapConfigSchema, + mapLineage, + validateMapDestination, + type MapConfig, +} from "@jointarp/module/map"; +import { parseConfig } from "@jointarp/module/node/config-file"; +import { findNodeAtLocation, parseTree, modify, applyEdits } from "jsonc-parser/lib/esm/main.js"; +import { parseTOML, type AST } from "toml-eslint-parser"; + +import { applyMapEdit, editPoint, type VertexEdit, type MapEdit } from "../../shared/map-vertex"; + +function mapFile(root: string, path: string) { + if ( + !/^maps\/(?:[^/\\]+\/)*[^/\\]+\.(toml|json)$/iu.test(path) || + path.split("/").some((p) => p.startsWith(".")) + ) + throw new Error("无效地图路径"); + const file = resolve(realpathSync(root), path); + if (realpathSync(file) !== file || !statSync(file).isFile()) + throw new Error("地图必须是模组内的普通文件"); + return file; +} +const revision = (text: string) => createHash("sha256").update(text).digest("hex"); + +export function openMapEdit(root: string, path: string) { + const text = readFileSync(mapFile(root, path), "utf8"); + return { config: mapConfigSchema.parse(parseConfig(text, path)), revision: revision(text) }; +} + +function tomlNumbers(source: string) { + const ranges = new Map(); + function visit( + node: AST.TOMLTable | AST.TOMLKeyValue | AST.TOMLContentNode, + path: (string | number)[], + ) { + if (node.type === "TOMLTable") node.body.forEach((child) => visit(child, node.resolvedKey)); + else if (node.type === "TOMLKeyValue") + visit(node.value, [ + ...path, + ...node.key.keys.map((k) => (k.type === "TOMLBare" ? k.name : k.value)), + ]); + else if (node.type === "TOMLArray") + node.elements.forEach((child, i) => visit(child, [...path, i])); + else if (node.type === "TOMLInlineTable") node.body.forEach((child) => visit(child, path)); + else if (typeof node.value === "number") ranges.set(JSON.stringify(path), node.range); + } + parseTOML(source, { tomlVersion: "1.1" }).body[0].body.forEach((node) => visit(node, [])); + return ranges; +} + +function patchVertices(source: string, path: string, config: MapConfig, edits: VertexEdit[]) { + const toml = /\.toml$/iu.test(path) ? tomlNumbers(source) : undefined; + const tree = toml ? undefined : parseTree(source); + const changes = new Map(); + for (const edit of edits) { + const point = editPoint(config, edit); + const key = + edit.layer === "walls" + ? ["walls", edit.index, "points", edit.vertex] + : ["doors", edit.index, edit.vertex === 0 ? "from" : "to"]; + for (const axis of [0, 1] as const) { + if (point[axis] === edit.at[axis]) continue; + const loc = [...key, axis]; + const json = tree && findNodeAtLocation(tree, loc); + const range = json + ? [json.offset, json.offset + json.length] + : toml?.get(JSON.stringify(loc)); + if (!range) throw new Error("无法定位坐标在源文件中的位置"); + changes.set(range[0], { end: range[1], value: edit.at[axis] }); + point[axis] = edit.at[axis]; + } + } + for (const [start, { end, value }] of [...changes].sort(([a], [b]) => b - a)) + source = source.slice(0, start) + value + source.slice(end); + return source; +} + +function patchStructure( + source: string, + path: string, + previous: MapConfig, + next: MapConfig, + layer: "walls" | "doors" | "starts" | "connections", +) { + const old = previous[layer], + items = next[layer]; + let start = 0; + while (start < old.length && old[start] === items[start]) start++; + let end = old.length, + tail = items.length; + while (end > start && tail > start && old[end - 1] === items[tail - 1]) { + end--; + tail--; + } + if (start === end && start === tail) return source; + const insert = items.slice(start, tail); + if (/\.json$/iu.test(path)) { + const opts = { + formattingOptions: { + insertSpaces: true, + tabSize: 2, + eol: source.includes("\r\n") ? "\r\n" : "\n", + }, + }; + if (!findNodeAtLocation(parseTree(source)!, [layer])) + return applyEdits(source, modify(source, [layer], insert, opts)); + for (let i = end - 1; i >= start; i--) + source = applyEdits(source, modify(source, [layer, i], undefined, opts)); + insert.forEach((item, i) => { + source = applyEdits( + source, + modify(source, [layer, start + i], item, { ...opts, isArrayInsertion: true }), + ); + }); + return source; + } + const ast = parseTOML(source, { tomlVersion: "1.1" }); + const nodes = ast.body[0].body; + const tables = nodes.filter( + (n): n is AST.TOMLTable => n.type === "TOMLTable" && n.resolvedKey[0] === layer, + ); + const fields = (obj: (typeof insert)[number]) => + Object.entries(obj).map(([k, v]) => k + " = " + JSON.stringify(v)); + const inline = nodes.find( + (n) => + n.type === "TOMLKeyValue" && + n.key.keys.length === 1 && + (n.key.keys[0].type === "TOMLBare" ? n.key.keys[0].name : n.key.keys[0].value) === layer, + ); + if (inline?.type === "TOMLKeyValue" && inline.value.type === "TOMLArray") { + const arr = inline.value; + const text = insert.map((o) => "{ " + fields(o).join(", ") + " }").join(", "); + if (start === end) { + const last = arr.elements.at(-1), + offset = last?.range[1] ?? arr.range[0] + 1; + return source.slice(0, offset) + (last ? ", " : "") + text + source.slice(offset); + } + const [a, b] = arr.elements[start].range; + if (text) return source.slice(0, a) + text + source.slice(b); + const comma = ast.tokens.find( + (t) => + t.range[0] >= b && + t.range[0] < (arr.elements[end]?.range[0] ?? arr.range[1]) && + t.value === ",", + ); + if (comma) source = source.slice(0, comma.range[0]) + source.slice(comma.range[1]); + return source.slice(0, a) + source.slice(b); + } + const nl = source.includes("\r\n") ? "\r\n" : "\n"; + const text = insert.map((o) => ["[[" + layer + "]]", ...fields(o)].join(nl)).join(nl + nl); + const offset = tables[start]?.range[0] ?? source.length; + for (let i = end - 1; i >= start; i--) { + const [a, b] = tables[i].range; + source = source.slice(0, a) + source.slice(b); + } + return source.slice(0, offset) + (text ? nl + text + nl : "") + source.slice(offset); +} +function patchParent(source: string, path: string, parent?: string) { + if (/\.json$/iu.test(path)) return applyEdits(source, modify(source, ["parent"], parent, {})); + const entry = parseTOML(source, { tomlVersion: "1.1" }).body[0].body.find( + (node) => + node.type === "TOMLKeyValue" && + node.key.keys.length === 1 && + (node.key.keys[0].type === "TOMLBare" ? node.key.keys[0].name : node.key.keys[0].value) === + "parent", + ); + if (entry?.type === "TOMLKeyValue") { + const [start, end] = parent ? entry.value.range : entry.range; + return source.slice(0, start) + (parent ? JSON.stringify(parent) : "") + source.slice(end); + } + return parent + ? `parent = ${JSON.stringify(parent)}${source.includes("\r\n") ? "\r\n" : "\n"}${source}` + : source; +} + +function referencedMap(root: string, id: string) { + if (id.split("/").some((part) => !part || part.startsWith(".") || part.includes("\\"))) + throw new Error("引用地图路径无效"); + const directory = dirname(`maps/${id}`); + const location = resolve(realpathSync(root), directory); + if (realpathSync(location) !== location) throw new Error("引用地图路径无效"); + const files = readdirSync(location) + .filter( + (name) => + /\.(json|toml)$/iu.test(name) && name.replace(/\.(json|toml)$/iu, "") === basename(id), + ) + .map((name) => `${directory}/${name}`); + if (files.length !== 1) throw new Error(`引用地图不存在或重名:${id}`); + return openMapEdit(root, files[0]).config; +} + +export function saveMapEdit(root: string, path: string, expected: string, edits: MapEdit[]) { + const file = mapFile(root, path); + let source = readFileSync(file, "utf8"); + const conflict = () => { + throw new Error("地图文件已在外部修改。请保留需要的坐标,退出编辑并重新加载后再修改。"); + }; + if (revision(source) !== expected) conflict(); + let config = mapConfigSchema.parse(parseConfig(source, path)); + for (let i = 0; i < edits.length;) { + const edit = edits[i++]; + if ("kind" in edit) { + const next = applyMapEdit(config, edit); + if (edit.kind === "parent") source = patchParent(source, path, next.parent); + else + for (const layer of ["walls", "doors", "starts", "connections"] as const) + source = patchStructure(source, path, config, next, layer); + config = next; + } else { + const batch = [edit]; + while (i < edits.length && !("kind" in edits[i])) batch.push(edits[i++] as VertexEdit); + source = patchVertices(source, path, config, batch); + } + } + if (edits.some((edit) => "kind" in edit && edit.kind === "parent")) { + const current = path.slice(5).replace(/\.(json|toml)$/iu, ""); + mapLineage(current, (id) => { + if (id === current) return config.parent; + return referencedMap(root, id).parent; + }); + } + if (edits.some((edit) => "kind" in edit && edit.kind === "connect")) { + const id = path.slice(5).replace(/\.(json|toml)$/iu, ""); + for (const link of config.connections) + validateMapDestination(id, link, referencedMap(root, link.map)); + } + if (!isDeepStrictEqual(config, mapConfigSchema.parse(parseConfig(source, path)))) + throw new Error("写入校验失败"); + if (revision(readFileSync(mapFile(root, path), "utf8")) !== expected) conflict(); + writeFileAtomicSync(file, source, { mode: statSync(file).mode }); +} diff --git a/apps/desktop/src/main/modules/module-router.ts b/apps/desktop/src/main/modules/module-router.ts index c28328b..69ad9b6 100644 --- a/apps/desktop/src/main/modules/module-router.ts +++ b/apps/desktop/src/main/modules/module-router.ts @@ -2,12 +2,14 @@ import { mkdir } from "node:fs/promises"; import { loadDocumentTypes } from "@jointarp/module/node/document-types"; import { loadModuleLibraryDocuments } from "@jointarp/module/node/module-documents"; +import { loadModuleMapEntries } from "@jointarp/module/node/module-maps"; import { loadModuleMetadata } from "@jointarp/module/node/module-metadata"; import { loadModulePages } from "@jointarp/module/node/module-pages"; import { ORPCError } from "@orpc/server"; import type { ModulesDirectory, OpenModuleLibraryResult } from "@shared/desktop-api"; import { z } from "zod"; +import { mapEditSchema } from "../../shared/map-vertex"; import { assertAbsolutePath, readAppConfig, @@ -20,6 +22,7 @@ import { allowDocumentMediaRoots } from "../media-path"; import { documentsPath, showPathPicker } from "../native-dialog"; import { importLocalModule } from "./import-local-module"; import { listModules } from "./list-modules"; +import { openMapEdit, saveMapEdit } from "./map-editor"; export async function readModulesDirectory(configFilePath: string): Promise { const documentsDir = documentsPath(); @@ -53,7 +56,30 @@ async function loadLibraryFromPath(path: string): Promise openMapEdit(assertAbsolutePath(input.path), input.file)), + saveMapEdit: procedure + .input( + editFile.extend({ + revision: z.string().length(64), + edits: z.array(mapEditSchema).min(1).max(10000), + }), + ) + .handler(({ input }) => { + try { + saveMapEdit(assertAbsolutePath(input.path), input.file, input.revision, input.edits); + } catch (error) { + throw new ORPCError("BAD_REQUEST", { + message: error instanceof Error ? error.message : "地图保存失败", + }); + } + }), + maps: procedure + .input(z.object({ path: z.string().min(1) })) + .handler(({ input }) => loadModuleMapEntries(assertAbsolutePath(input.path))), importState: procedure.handler(({ context }) => context.moduleImports.get()), confirmImport: procedure .input(z.object({ id: z.number().int(), replace: z.boolean() })) diff --git a/apps/desktop/src/renderer/src/features/maps/MapCanvas.tsx b/apps/desktop/src/renderer/src/features/maps/MapCanvas.tsx new file mode 100644 index 0000000..e3d4abf --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/MapCanvas.tsx @@ -0,0 +1,470 @@ +import type { MapTokenView } from "@jointarp/core/shared/map"; +import type { MapPoint } from "@jointarp/module/map"; +import { firstBlocked, footprintPixels, snapToGrid } from "@jointarp/module/map-geometry"; +import type Konva from "konva"; +import { LocateFixed, Maximize2, Minus, Plus } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { Circle, Group, Image as KonvaImage, Layer, Line, Stage, Text } from "react-konva"; + +import { Button } from "../../components/ui/button"; +import { useDocumentImage } from "../modules/document-image"; +import { cameraFromTransform, cameraTransform, zoomCamera } from "./map-camera"; +import { + distanceText, + knownWalls, + summarizePlan, + type RoomMap, + type TokenPortrait, +} from "./map-model"; +import { mapUi, useMapUi, type MovementPlan, type PendingRoute } from "./map-ui"; +import { MapTerrain } from "./MapTerrain"; + +function useLoadedImage(src: string | undefined, onError?: (src: string) => void) { + const [image, setImage] = useState(); + const report = useRef(onError); + report.current = onError; + useEffect(() => { + setImage(undefined); + if (!src) return; + const element = new window.Image(); + element.onload = () => setImage(element); + element.onerror = () => report.current?.(src); + element.src = src; + return () => { + element.onload = null; + element.onerror = null; + }; + }, [src]); + return image; +} + +/** 圆形标记里按 cover 取图,并靠上对齐,避免头像只剩衣服。 */ +function portraitCrop(image: HTMLImageElement, size: number) { + const scale = Math.max(size / image.width, size / image.height); + const width = Math.min(image.width, size / scale); + const height = Math.min(image.height, size / scale); + return { x: Math.max(0, (image.width - width) / 2), y: 0, width, height }; +} + +function useSize(element: HTMLDivElement | null) { + const [size, setSize] = useState({ width: 0, height: 0 }); + useEffect(() => { + if (!element) return; + const observer = new ResizeObserver(([entry]) => { + if (!entry) return; + setSize({ width: entry.contentRect.width, height: entry.contentRect.height }); + }); + observer.observe(element); + return () => observer.disconnect(); + }, [element]); + return size; +} + +const tokenColors = { + own: { fill: "#2563eb", stroke: "#dbeafe" }, + party: { fill: "#0f766e", stroke: "#ccfbf1" }, + other: { fill: "#b45309", stroke: "#fef3c7" }, +}; + +const flatten = (points: readonly MapPoint[]) => points.flatMap(([x, y]) => [x, y]); + +function TokenMarker({ + roomId, + token, + name, + portrait, + radius, + screen, + fill, + stroke, + interactive, + onHover, +}: { + roomId: string; + token: MapTokenView; + name: string; + portrait?: TokenPortrait; + radius: number; + screen: number; + fill: string; + stroke: string; + interactive: boolean; + onHover: (point: { x: number; y: number } | undefined) => void; +}) { + const scope = `room-module:${roomId}`; + const preferred = useDocumentImage(portrait?.path, portrait?.avatar ?? portrait?.image, scope); + const fallback = useDocumentImage( + portrait?.path, + portrait?.avatar && portrait.image ? portrait.image : undefined, + scope, + ); + const [broken, setBroken] = useState>(() => new Set()); + const src = [preferred, fallback].find((url) => url && !broken.has(url)); + const photo = useLoadedImage(src, (failed) => + setBroken((current) => new Set([...current, failed])), + ); + const size = radius * 2; + const hoverAt = (event: Konva.KonvaEventObject) => { + const point = event.target.getStage()?.getPointerPosition(); + if (point) onHover(point); + }; + return ( + onHover(undefined)} + onMouseDown={(event) => { + if (interactive) event.target.getStage()?.startDrag(); + }} + > + + {photo ? ( + { + context.beginPath(); + context.arc(0, 0, radius, 0, Math.PI * 2); + context.closePath(); + }} + > + + + ) : ( + + )} + + ); +} + +export function MapCanvas({ + roomId, + map, + tokenName, + tokenPortrait, + ownToken, + routes = [], + plan, + planning = false, + interactive = false, + onAddWaypoint, + className, +}: { + roomId: string; + map: RoomMap; + tokenName: (token: MapTokenView) => string; + tokenPortrait?: (token: MapTokenView) => TokenPortrait | undefined; + ownToken?: string; + routes?: readonly PendingRoute[]; + plan?: MovementPlan; + planning?: boolean; + interactive?: boolean; + onAddWaypoint?: (point: MapPoint) => void; + className?: string; +}) { + const { resource, view } = map; + const [container, setContainer] = useState(null); + const [hover, setHover] = useState<{ name: string; x: number; y: number }>(); + const size = useSize(container); + const image = useLoadedImage( + useDocumentImage(resource.path, resource.image, `room-module:${roomId}`), + ); + const fit = useMemo(() => { + const scale = Math.min(size.width / resource.width, size.height / resource.height) || 1; + return { + scale, + x: (size.width - resource.width * scale) / 2, + y: (size.height - resource.height * scale) / 2, + }; + }, [size.width, size.height, resource.width, resource.height]); + const ui = useMapUi(roomId); + const saved = ui.cameras[resource.id]; + const camera = saved ? cameraTransform(saved, size) : fit; + const setCamera = (next: { scale: number; x: number; y: number }) => { + setPointer(undefined); + setHover(undefined); + mapUi.update(roomId, (state) => ({ + ...state, + cameras: { + ...state.cameras, + [resource.id]: cameraFromTransform(next, size), + }, + })); + }; + const transform = interactive ? camera : fit; + const screen = 1 / transform.scale; + const ownTokenView = view.tokens.find((token) => token.id === ownToken); + const [pointer, setPointer] = useState(); + const [dragging, setDragging] = useState(false); + const previewPoint = planning && !dragging ? pointer : undefined; + const last = plan?.waypoints.at(-1) ?? ownTokenView?.at; + const blocked = Boolean( + last && previewPoint && firstBlocked([last, previewPoint], knownWalls(resource, view)), + ); + const preview = + previewPoint && ownTokenView + ? summarizePlan(map, { + map: resource.id, + token: ownTokenView.id, + waypoints: [...(plan?.waypoints ?? []), previewPoint], + }) + : undefined; + const pointAtPointer = (stage: Konva.Stage | null): MapPoint | undefined => { + const position = stage?.getPointerPosition(); + if (!position) return; + const point: MapPoint = [ + (position.x - transform.x) / transform.scale, + (position.y - transform.y) / transform.scale, + ]; + if (point[0] < 0 || point[1] < 0 || point[0] > resource.width || point[1] > resource.height) + return; + const snapped = snapToGrid(resource.grid, point, ownTokenView?.size ?? 1); + if ( + snapped[0] >= 0 && + snapped[1] >= 0 && + snapped[0] <= resource.width && + snapped[1] <= resource.height + ) + return snapped; + }; + const zoom = (factor: number, anchor = { x: size.width / 2, y: size.height / 2 }) => { + setCamera(zoomCamera(camera, factor, fit.scale, anchor)); + }; + + const handleWheel = (event: Konva.KonvaEventObject) => { + if (!interactive) return; + event.evt.preventDefault(); + const stage = event.target.getStage(); + const pointer = stage?.getPointerPosition(); + if (!pointer) return; + if (event.evt.deltaY !== 0) zoom(event.evt.deltaY > 0 ? 1 / 1.15 : 1.15, pointer); + }; + const handleClick = (event: Konva.KonvaEventObject) => { + if (!planning || !onAddWaypoint || event.evt.button !== 0 || dragging) return; + const point = pointAtPointer(event.target.getStage()); + if (point) onAddWaypoint(point); + }; + + return ( +
+ {size.width > 0 && size.height > 0 ? ( + { + if (planning && !dragging) setPointer(pointAtPointer(event.target.getStage())); + }} + onMouseLeave={() => { + setPointer(undefined); + setHover(undefined); + }} + onDragStart={() => { + setDragging(true); + setPointer(undefined); + setHover(undefined); + }} + onDragEnd={(event) => { + setDragging(false); + if (event.target === event.target.getStage()) + setCamera({ ...camera, x: event.target.x(), y: event.target.y() }); + }} + onWheel={handleWheel} + onClick={handleClick} + > + + + {last && previewPoint ? ( + <> + + + + ) : null} + {routes.map((route) => ( + + ))} + {plan && ownTokenView ? ( + <> + + {plan.waypoints.map(([x, y], index) => ( + + ))} + + ) : null} + + + {view.tokens + .filter((token) => token.document) + .map((token) => { + const colors = + token.id === ownToken + ? tokenColors.own + : token.party + ? tokenColors.party + : tokenColors.other; + const name = tokenName(token); + return ( + setHover(point ? { name, ...point } : undefined)} + /> + ); + })} + + + ) : null} + {interactive ? ( + <> +
+ + + + +
+
+ {planning + ? blocked + ? "路线不能穿过墙" + : preview + ? distanceText(preview.length, resource.grid.unit, preview.explore) + : "点击添加路点 · 拖动平移 · 滚轮缩放" + : "拖动平移 · 滚轮缩放"} +
+ + ) : null} + {hover && !dragging ? ( +
+ {hover.name} +
+ ) : null} +
+ ); +} diff --git a/apps/desktop/src/renderer/src/features/maps/MapPanel.tsx b/apps/desktop/src/renderer/src/features/maps/MapPanel.tsx new file mode 100644 index 0000000..b1bf244 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/MapPanel.tsx @@ -0,0 +1,251 @@ +import { mapLineage } from "@jointarp/module/map"; +import { firstBlocked } from "@jointarp/module/map-geometry"; +import { Footprints, Maximize2, Undo2, X } from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; + +import { Button } from "../../components/ui/button"; +import { GameToolDialog } from "../sessions/GameToolDialog"; +import { distanceText, knownWalls, summarizePlan, useRoomMaps, type RoomMap } from "./map-model"; +import { mapUi, useMapUi, type PendingRoute } from "./map-ui"; +import { MapCanvas } from "./MapCanvas"; + +function useSelectedMap(roomId: string) { + const model = useRoomMaps(roomId); + const ui = useMapUi(roomId); + const selected = + model.maps.find((item) => item.resource.id === ui.mapId) ?? + model.maps.find((item) => item.resource.id === model.own?.map) ?? + model.maps[0]; + return { model, ui, selected }; +} + +/** 同一标记只显示最近一次仍从当前位置出发的意图。 */ +function activeRoutes(map: RoomMap, routes: Readonly>) { + const latest = new Map(); + for (const route of Object.values(routes)) { + if (route.map !== map.resource.id) continue; + const token = map.view.tokens.find((item) => item.id === route.token); + if (!token || token.at[0] !== route.from[0] || token.at[1] !== route.from[1]) continue; + const current = latest.get(route.token); + if (!current || current.sequence < route.sequence) latest.set(route.token, route); + } + return [...latest.values()]; +} + +function MapSwitcher({ + roomId, + maps, + selected, +}: { + roomId: string; + maps: readonly RoomMap[]; + selected: RoomMap; +}) { + if (maps.length < 2) return {selected.resource.name}; + const byId = new Map(maps.map((item) => [item.resource.id, item])); + const paths = maps + .map(({ resource }) => ({ + id: resource.id, + label: mapLineage(resource.id, (id) => { + const parent = byId.get(id)?.view.parent; + return parent && byId.has(parent) ? parent : undefined; + }) + .map((id) => byId.get(id)!.resource.name) + .join(" › "), + })) + .sort((a, b) => a.label.localeCompare(b.label, "zh")); + return ( + + ); +} + +/** 左侧栏的小地图;点击放大查看或规划移动。 */ +export function MapPanel({ roomId }: { roomId: string }) { + const { model, ui, selected } = useSelectedMap(roomId); + if (!selected) return null; + const routes = activeRoutes(selected, ui.routes); + return ( +
+
+ + +
+ +
+ ); +} + +/** 大图:平移缩放,规划本人角色的移动路线。 */ +export function MapDialog({ roomId }: { roomId: string }) { + const { model, ui, selected } = useSelectedMap(roomId); + const returnToComposer = useRef(false); + const [warning, setWarning] = useState(""); + const own = model.own; + useEffect(() => { + if (own) mapUi.trackCharacter(roomId, own.token.id, own.map, own.token.at); + }, [roomId, own]); + const plan = ui.plan?.map === selected?.resource.id ? ui.plan : undefined; + const planMap = useMemo( + () => model.maps.find((item) => item.resource.id === plan?.map), + [model.maps, plan?.map], + ); + const summary = plan && planMap ? summarizePlan(planMap, plan) : undefined; + const canPlan = Boolean(own && selected && own.map === selected.resource.id); + const planning = ui.planning && canPlan; + if (!selected) return null; + const unit = selected.resource.grid.unit; + + const addWaypoint = (point: [number, number]) => { + if (!own) return; + const current = + plan && plan.token === own.token.id && plan.map === own.map + ? plan + : { token: own.token.id, map: own.map, waypoints: [] }; + const last = current.waypoints.at(-1) ?? own.token.at; + if (current.waypoints.length >= 50) return setWarning("路点最多 50 个"); + if (firstBlocked([last, point], knownWalls(selected.resource, selected.view))) + return setWarning("路线不能穿过墙"); + setWarning(""); + mapUi.setPlan(roomId, { ...current, waypoints: [...current.waypoints, point] }); + }; + + return ( + { + if (!open) mapUi.close(roomId); + }} + finalFocus={() => { + if (!returnToComposer.current) return; + returnToComposer.current = false; + return document.querySelector( + `[data-room-composer="${CSS.escape(roomId)}"] [contenteditable="true"]`, + ); + }} + title={} + description="查看队伍已探索的地图,规划本人角色的移动。" + wide + headerActions={ +
+ {planning ? ( + <> + + {warning || + (summary + ? `${plan!.waypoints.length} 个路点 · ${distanceText(summary.length, unit, summary.explore)}` + : "点击地图添加路点")} + + + + + + ) : canPlan ? ( + + ) : null} +
+ } + > + {planning ? ( +

+ 路线随行动发送,由主持裁定;规划不会立即移动角色。 +

+ ) : null} + +
+ ); +} diff --git a/apps/desktop/src/renderer/src/features/maps/MapTerrain.tsx b/apps/desktop/src/renderer/src/features/maps/MapTerrain.tsx new file mode 100644 index 0000000..1fcf35a --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/MapTerrain.tsx @@ -0,0 +1,60 @@ +import type Konva from "konva"; +import { useReducedMotion } from "motion/react"; +import { useLayoutEffect, useMemo, useRef } from "react"; +import { Image as KonvaImage } from "react-konva"; + +import { clipPreviousFog, createFogLayers, fogCanvas, paintFogFrame } from "./map-fog"; +import type { RoomMap } from "./map-model"; + +/** 小图、大图共用地形记忆;仅对主机已确认的新视野做淡入。 */ +export function MapTerrain({ + map: { resource, view }, + image, +}: { + map: RoomMap; + image?: HTMLImageElement; +}) { + const node = useRef(null); + const previous = useRef< + { canvas: HTMLCanvasElement; image?: HTMLImageElement; id: string } | undefined + >(undefined); + const reducedMotion = useReducedMotion(); + const layers = useMemo( + () => createFogLayers(resource, view, image), + [resource, view.explored, view.visible, image], + ); + + useLayoutEffect(() => { + const canvas = fogCanvas(layers.memory.width, layers.memory.height); + const old = previous.current; + const animate = + !reducedMotion && + old && + old.id === resource.id && + old.image === image && + old.canvas.width === canvas.width && + old.canvas.height === canvas.height; + const clipped = animate ? clipPreviousFog(old.canvas, layers.visible) : undefined; + previous.current = { canvas, image, id: resource.id }; + node.current?.image(canvas); + const draw = (progress: number) => { + paintFogFrame(canvas, layers, clipped, progress); + node.current?.getLayer()?.batchDraw(); + }; + draw(animate ? 0 : 1); + if (!animate) return; + const start = performance.now(); + let frame: number; + const tick = (now: number) => { + const progress = Math.min(1, (now - start) / 180); + draw(1 - (1 - progress) ** 3); + if (progress < 1) frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + return () => cancelAnimationFrame(frame); + }, [layers, image, resource.id, reducedMotion]); + + return ( + + ); +} diff --git a/apps/desktop/src/renderer/src/features/maps/MovementCard.tsx b/apps/desktop/src/renderer/src/features/maps/MovementCard.tsx new file mode 100644 index 0000000..f7f38da --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/MovementCard.tsx @@ -0,0 +1,70 @@ +import type { MovementIntent } from "@jointarp/core/shared/map"; +import { Footprints } from "lucide-react"; +import { useEffect } from "react"; + +import { distanceText, useRoomMaps } from "./map-model"; +import { mapUi } from "./map-ui"; + +/** 行动消息下方的移动意图卡;实际结果以地图和主持叙述为准。 */ +export function MovementCard({ + roomId, + messageId, + sequence, + intent, + submitted, +}: { + roomId: string; + messageId: string; + sequence: number; + intent: MovementIntent; + submitted: boolean; +}) { + const model = useRoomMaps(roomId); + const progress = model.intents[messageId]; + const pending = submitted && progress === undefined; + useEffect(() => { + if (!pending) return; + mapUi.showRoute(roomId, { + messageId, + sequence, + token: intent.token, + map: intent.map, + from: intent.from, + waypoints: intent.waypoints, + }); + return () => mapUi.hideRoute(roomId, messageId); + }, [pending, roomId, messageId, sequence, intent]); + const map = model.maps.find((item) => item.resource.id === intent.map); + const currentMap = model.maps.find((item) => item.view.tokens.some((t) => t.id === intent.token)); + const token = currentMap?.view.tokens.find((item) => item.id === intent.token); + const name = token ? model.tokenName(token) : intent.token.split("/").at(-1); + const status = !submitted + ? "已改为聊天,未提交" + : progress === undefined + ? "等待主持裁定" + : intent.length === null + ? `已走 ${progress} ${intent.unit}` + : `已走 ${progress} / ${intent.length} ${intent.unit}`; + return ( + + ); +} diff --git a/apps/desktop/src/renderer/src/features/maps/map-camera.test.ts b/apps/desktop/src/renderer/src/features/maps/map-camera.test.ts new file mode 100644 index 0000000..0a31e4c --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/map-camera.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from "bun:test"; + +import { cameraFromTransform, cameraTransform, zoomCamera } from "./map-camera"; +import { mapUi } from "./map-ui"; + +test("缩放保持指针下的位置不动,并限制最小和最大缩放", () => { + const camera = { x: -100, y: 30, scale: 2 }; + const anchor = { x: 240, y: 160 }; + for (const factor of [1.15, 0.001, 1000]) { + const next = zoomCamera(camera, factor, 1, anchor); + expect((anchor.x - next.x) / next.scale).toBeCloseTo((anchor.x - camera.x) / camera.scale); + expect((anchor.y - next.y) / next.scale).toBeCloseTo((anchor.y - camera.y) / camera.scale); + expect(next.scale).toBeGreaterThanOrEqual(0.6); + expect(next.scale).toBeLessThanOrEqual(12); + } +}); + +test("切图和关闭后保留各自视角与行动草稿,窗口变化保留观察中心", () => { + const room = "map-camera-test"; + const first = cameraFromTransform({ x: -120, y: 40, scale: 2 }, { width: 800, height: 600 }); + const second = { center: [40, 80] as [number, number], scale: 1 }; + const plan = { map: "first", token: "hero", waypoints: [[100, 100] as [number, number]] }; + mapUi.update(room, (state) => ({ ...state, cameras: { first, second } })); + mapUi.setPlan(room, plan); + mapUi.open(room, { mapId: "second", planning: true }); + mapUi.close(room); + mapUi.open(room, { mapId: "first" }); + expect(mapUi.get(room).plan).toEqual(plan); + expect(mapUi.get(room).cameras.second).toEqual(second); + mapUi.open(room, { mapId: "second", center: [70, 90] }); + expect(mapUi.get(room).cameras.second).toEqual({ ...second, center: [70, 90] }); + const size = { width: 1000, height: 500 }; + const restored = cameraTransform(mapUi.get(room).cameras.first!, size); + expect(cameraFromTransform(restored, size)).toEqual(first); + expect(restored).toEqual({ x: -20, y: -10, scale: 2 }); +}); + +test("浏览其他地图时仅本人跨图触发跟随,清除旧路线并定位落点", () => { + const room = "follow-stairs"; + mapUi.trackCharacter(room, "旅人", "城市", [10, 20]); + mapUi.open(room, { mapId: "宅邸", planning: true }); + mapUi.setPlan(room, { token: "旅人", map: "城市", waypoints: [[2, 3]] }); + mapUi.trackCharacter(room, "旅人", "城市", [20, 30]); + expect(mapUi.get(room).mapId).toBe("宅邸"); + mapUi.trackCharacter(room, "旅人", "地窖", [100, 50]); + expect(mapUi.get(room)).toMatchObject({ + mapId: "地窖", + planning: false, + cameras: { 地窖: { center: [100, 50] } }, + }); + expect(mapUi.get(room).plan).toBeUndefined(); +}); diff --git a/apps/desktop/src/renderer/src/features/maps/map-camera.ts b/apps/desktop/src/renderer/src/features/maps/map-camera.ts new file mode 100644 index 0000000..abae459 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/map-camera.ts @@ -0,0 +1,36 @@ +import type { MapCamera } from "./map-ui"; + +type Size = { width: number; height: number }; +type Transform = { x: number; y: number; scale: number }; + +export function cameraTransform(camera: MapCamera, size: Size): Transform { + return { + scale: camera.scale, + x: size.width / 2 - camera.center[0] * camera.scale, + y: size.height / 2 - camera.center[1] * camera.scale, + }; +} + +export function cameraFromTransform(transform: Transform, size: Size): MapCamera { + return { + scale: transform.scale, + center: [ + (size.width / 2 - transform.x) / transform.scale, + (size.height / 2 - transform.y) / transform.scale, + ], + }; +} + +export function zoomCamera( + camera: Transform, + factor: number, + fitScale: number, + anchor: { x: number; y: number }, +): Transform { + const scale = Math.min(fitScale * 12, Math.max(fitScale * 0.6, camera.scale * factor)); + return { + scale, + x: anchor.x - ((anchor.x - camera.x) / camera.scale) * scale, + y: anchor.y - ((anchor.y - camera.y) / camera.scale) * scale, + }; +} diff --git a/apps/desktop/src/renderer/src/features/maps/map-fog.test.ts b/apps/desktop/src/renderer/src/features/maps/map-fog.test.ts new file mode 100644 index 0000000..b7223ec --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/map-fog.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "bun:test"; + +import { createExploration, explorationGrid, markExplored } from "@jointarp/module/map-geometry"; + +import { paintExploration } from "./map-fog"; + +test("探索遮罩不覆盖相邻未知格,并裁掉底图之外的末行末列", () => { + const bounds = { width: 105, height: 65 }; + const grid = explorationGrid({ + ...bounds, + grid: { type: "square", size: 40, distance: 1, unit: "米", diagonal: "equal", offset: [0, 0] }, + }); + const bits = createExploration(grid); + markExplored(bits, grid, [ + [0, 0], + [40, 0], + [40, 40], + [0, 40], + ]); + markExplored(bits, grid, [ + [80, 40], + [120, 40], + [120, 80], + [80, 80], + ]); + const rectangles: number[][] = []; + paintExploration( + { + fillRect: (...args) => { + rectangles.push(args); + }, + }, + bits, + grid, + bounds, + ); + const painted = (x: number, y: number) => + rectangles.some( + ([left, top, width, height]) => + x >= left! && x < left! + width! && y >= top! && y < top! + height!, + ); + expect(painted(39.99, 10)).toBe(true); + expect(painted(40.01, 10)).toBe(false); + expect(painted(79.99, 50)).toBe(false); + expect(painted(104.99, 64.99)).toBe(true); + expect(painted(105.01, 50)).toBe(false); + expect(painted(90, 65.01)).toBe(false); +}); diff --git a/apps/desktop/src/renderer/src/features/maps/map-fog.ts b/apps/desktop/src/renderer/src/features/maps/map-fog.ts new file mode 100644 index 0000000..5bf3359 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/map-fog.ts @@ -0,0 +1,116 @@ +import type { MapResource, MapView } from "@jointarp/core/shared/map"; +import { + decodeExploration, + explorationGrid, + type ExplorationGrid, +} from "@jointarp/module/map-geometry"; + +const fogResolution = 2048; +export const fogColor = "rgb(14, 14, 17)"; + +/** 直接绘制探索格,避免缩放低分辨率遮罩时把亮边插值到未知格。 */ +export function paintExploration( + context: Pick, + bits: Uint8Array, + grid: ExplorationGrid, + bounds: { width: number; height: number }, +) { + for (let row = 0; row < grid.rows; row++) { + let start = -1; + for (let column = 0; column <= grid.columns; column++) { + const index = row * grid.columns + column; + const explored = + column < grid.columns && ((bits[index >> 3] ?? 0) & (1 << (index & 7))) !== 0; + if (explored && start < 0) start = column; + if (!explored && start >= 0) { + const x = start * grid.cell; + const y = row * grid.cell; + context.fillRect( + x, + y, + Math.min(column * grid.cell, bounds.width) - x, + Math.min(grid.cell, bounds.height - y), + ); + start = -1; + } + } + } +} + +export function fogCanvas(width: number, height: number) { + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; +} + +export function createFogLayers(resource: MapResource, view: MapView, image?: HTMLImageElement) { + const scale = Math.min(1, fogResolution / Math.max(resource.width, resource.height)); + const width = Math.ceil(resource.width * scale); + const height = Math.ceil(resource.height * scale); + const memory = fogCanvas(width, height); + const visible = fogCanvas(width, height); + const memoryContext = memory.getContext("2d"); + const visibleContext = visible.getContext("2d"); + if (!memoryContext || !visibleContext) return { memory, visible }; + + memoryContext.scale(scale, scale); + memoryContext.fillStyle = "white"; + const grid = explorationGrid(resource); + paintExploration(memoryContext, decodeExploration(view.explored, grid), grid, resource); + memoryContext.globalCompositeOperation = "source-in"; + if (image) { + memoryContext.filter = "grayscale(0.9) brightness(0.45)"; + memoryContext.drawImage(image, 0, 0, resource.width, resource.height); + memoryContext.filter = "none"; + } else { + memoryContext.fillStyle = fogColor; + memoryContext.fillRect(0, 0, resource.width, resource.height); + } + memoryContext.globalCompositeOperation = "destination-over"; + memoryContext.fillStyle = fogColor; + memoryContext.fillRect(0, 0, resource.width, resource.height); + + visibleContext.scale(scale, scale); + visibleContext.fillStyle = "white"; + for (const polygon of view.visible) { + if (polygon.length < 3) continue; + visibleContext.beginPath(); + visibleContext.moveTo(polygon[0]![0], polygon[0]![1]); + for (const [x, y] of polygon.slice(1)) visibleContext.lineTo(x, y); + visibleContext.closePath(); + visibleContext.fill(); + } + visibleContext.globalCompositeOperation = "source-in"; + if (image) visibleContext.drawImage(image, 0, 0, resource.width, resource.height); + else visibleContext.clearRect(0, 0, resource.width, resource.height); + return { memory, visible }; +} + +/** 旧画面只允许留在新视野内,关门、撤回探索时立即遮住失去的视野。 */ +export function clipPreviousFog(previous: HTMLCanvasElement, visible: HTMLCanvasElement) { + const clipped = fogCanvas(visible.width, visible.height); + const context = clipped.getContext("2d"); + if (context) { + context.drawImage(previous, 0, 0); + context.globalCompositeOperation = "destination-in"; + context.drawImage(visible, 0, 0); + } + return clipped; +} + +export function paintFogFrame( + canvas: HTMLCanvasElement, + layers: { memory: HTMLCanvasElement; visible: HTMLCanvasElement }, + previous?: HTMLCanvasElement, + progress = 1, +) { + const context = canvas.getContext("2d"); + if (!context) return; + context.clearRect(0, 0, canvas.width, canvas.height); + context.drawImage(layers.memory, 0, 0); + if (previous && progress < 1) context.drawImage(previous, 0, 0); + context.globalAlpha = progress; + context.drawImage(layers.visible, 0, 0); + context.globalAlpha = 1; +} diff --git a/apps/desktop/src/renderer/src/features/maps/map-model.ts b/apps/desktop/src/renderer/src/features/maps/map-model.ts new file mode 100644 index 0000000..8983189 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/map-model.ts @@ -0,0 +1,120 @@ +import type { MapResource, MapTokenView, MapView } from "@jointarp/core/shared/map"; +import { documentIdentity } from "@jointarp/module/document-path"; +import type { MapPoint } from "@jointarp/module/map"; +import { + decodeExploration, + explorationGrid, + firstBlocked, + isExplored, + measurePath, + polylineSegments, + round, + type Segment, +} from "@jointarp/module/map-geometry"; +import { useMemo, useSyncExternalStore } from "react"; + +import { desktopRpc } from "../../desktop-rpc"; +import { localRoomModuleLoader } from "../sessions/local-room-module"; +import { roomConnection } from "../sessions/room-connection"; +import { roomDocuments, useRoomReplica } from "../sessions/use-room-state"; +import type { MovementPlan } from "./map-ui"; + +export interface RoomMap { + readonly resource: MapResource; + readonly view: MapView; +} + +/** 标记关联资料上的头像;没有头像时用封面。 */ +export interface TokenPortrait { + readonly path: string; + readonly avatar?: string; + readonly image?: string; +} + +/** 队伍已知的地图与当前投影;静态资料来自冻结模组,动态部分来自房间同步。 */ +export function useRoomMaps(roomId: string) { + const connection = roomConnection(desktopRpc.game, roomId, localRoomModuleLoader); + const resources = useSyncExternalStore( + connection.subscribe, + () => connection.getSnapshot().resources, + )?.maps; + const replica = useRoomReplica(roomId); + const section = replica?.sections.map; + const viewerId = replica?.sections.viewerId; + const documents = replica ? roomDocuments(replica) : undefined; + return useMemo(() => { + const maps: RoomMap[] = []; + for (const view of section?.maps ?? []) { + const resource = resources?.find((item) => item.id === view.id); + if (resource) maps.push({ resource, view }); + } + const names = new Map( + (documents ?? []).map((document) => [documentIdentity(document.path), document.title]), + ); + const portraits = new Map( + Object.values(replica?.entities ?? {}).map((entity) => [ + documentIdentity(entity.document.path), + { + path: entity.document.path, + avatar: entity.document.avatar, + image: entity.document.image, + }, + ]), + ); + const own = maps.flatMap(({ resource, view }) => + view.tokens + .filter((token) => token.party && token.playerId === viewerId) + .map((token) => ({ map: resource.id, token })), + )[0]; + return { + maps, + intents: section?.intents ?? {}, + viewerId, + own, + tokenName: (token: MapTokenView): string => + token.label ?? + (token.document + ? (names.get(token.document) ?? token.document.split("/").at(-1) ?? token.document) + : token.id), + tokenPortrait: (token: MapTokenView) => + token.document ? portraits.get(token.document) : undefined, + }; + }, [resources, section, viewerId, documents, replica]); +} + +/** 玩家可知的阻挡:配置的墙与尚未揭示的秘门。 */ +export function knownWalls(resource: MapResource, view: MapView): Segment[] { + return [ + ...resource.walls.flatMap((points) => polylineSegments(points)), + ...view.barriers.map(([a, b]) => ({ a, b })), + ]; +} + +export function unitLabel(resource: MapResource) { + return resource.grid.unit; +} + +export interface PlanSummary { + readonly path: MapPoint[]; + readonly length: number | null; + readonly explore: boolean; + readonly blocked: boolean; +} + +export function summarizePlan(map: RoomMap, plan: MovementPlan): PlanSummary | undefined { + const token = map.view.tokens.find((item) => item.id === plan.token); + if (!token) return undefined; + const path: MapPoint[] = [token.at, ...plan.waypoints]; + const grid = explorationGrid(map.resource); + const explore = !isExplored(decodeExploration(map.view.explored, grid), grid, path.at(-1)!); + return { + path, + length: explore ? null : round(measurePath(map.resource.grid, path).total), + explore, + blocked: Boolean(firstBlocked(path, knownWalls(map.resource, map.view))), + }; +} + +export function distanceText(length: number | null, unit: string, explore: boolean) { + return explore || length === null ? "前往未探索区域" : `约 ${length} ${unit}`; +} diff --git a/apps/desktop/src/renderer/src/features/maps/map-ui.ts b/apps/desktop/src/renderer/src/features/maps/map-ui.ts new file mode 100644 index 0000000..f13bfab --- /dev/null +++ b/apps/desktop/src/renderer/src/features/maps/map-ui.ts @@ -0,0 +1,111 @@ +import type { MovementIntentInput } from "@jointarp/core/shared/map"; +import type { MapPoint } from "@jointarp/module/map"; +import { useSyncExternalStore } from "react"; + +export type MovementPlan = MovementIntentInput; + +/** 已发送且主持尚未执行的意图,用于在地图上画出虚线路线。 */ +export interface PendingRoute { + readonly messageId: string; + readonly sequence: number; + readonly token: string; + readonly map: string; + readonly from: MapPoint; + readonly waypoints: readonly MapPoint[]; +} + +export interface MapCamera { + readonly center: MapPoint; + readonly scale: number; +} + +interface RoomMapUi { + readonly character?: { token: string; map: string }; + readonly cameras: Readonly>; + readonly open: boolean; + readonly planning: boolean; + readonly mapId?: string; + readonly plan?: MovementPlan; + readonly routes: Readonly>; +} + +const initial: RoomMapUi = { open: false, planning: false, routes: {}, cameras: {} }; +const rooms = new Map(); +const listeners = new Set<() => void>(); + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** 地图面板、大图与输入框共用的房间内界面状态,不写入存档。 */ +export const mapUi = { + get(roomId: string): RoomMapUi { + return rooms.get(roomId) ?? initial; + }, + update(roomId: string, change: (state: RoomMapUi) => RoomMapUi) { + const current = mapUi.get(roomId); + const next = change(current); + if (next === current) return; + rooms.set(roomId, next); + for (const listener of listeners) listener(); + }, + trackCharacter(roomId: string, token: string, map: string, center: MapPoint) { + mapUi.update(roomId, (state) => { + const previous = state.character; + if (previous?.token === token && previous.map === map) return state; + const character = { token, map }; + if (previous?.token !== token) return { ...state, character }; + return { + ...state, + character, + mapId: map, + planning: false, + plan: undefined, + cameras: { ...state.cameras, [map]: { center, scale: state.cameras[map]?.scale ?? 1 } }, + }; + }); + }, + open(roomId: string, options: { mapId?: string; planning?: boolean; center?: MapPoint } = {}) { + mapUi.update(roomId, (state) => ({ + ...state, + open: true, + cameras: + options.mapId && options.center + ? { + ...state.cameras, + [options.mapId]: { + center: options.center, + scale: state.cameras[options.mapId]?.scale ?? 1, + }, + } + : state.cameras, + planning: options.planning ?? state.planning, + mapId: options.mapId ?? state.mapId, + })); + }, + close(roomId: string) { + mapUi.update(roomId, (state) => ({ ...state, open: false, planning: false })); + }, + setPlan(roomId: string, plan: MovementPlan | undefined) { + mapUi.update(roomId, (state) => (state.plan === plan ? state : { ...state, plan })); + }, + showRoute(roomId: string, route: PendingRoute) { + mapUi.update(roomId, (state) => + state.routes[route.messageId] + ? state + : { ...state, routes: { ...state.routes, [route.messageId]: route } }, + ); + }, + hideRoute(roomId: string, messageId: string) { + mapUi.update(roomId, (state) => { + if (!state.routes[messageId]) return state; + const { [messageId]: _removed, ...routes } = state.routes; + return { ...state, routes }; + }); + }, +}; + +export function useMapUi(roomId: string): RoomMapUi { + return useSyncExternalStore(subscribe, () => mapUi.get(roomId)); +} diff --git a/apps/desktop/src/renderer/src/features/modules/MapConnections.tsx b/apps/desktop/src/renderer/src/features/modules/MapConnections.tsx new file mode 100644 index 0000000..d7df9ae --- /dev/null +++ b/apps/desktop/src/renderer/src/features/modules/MapConnections.tsx @@ -0,0 +1,166 @@ +import { + mapStartSchema, + type MapConfig, + type MapPoint, + type ModuleMap, +} from "@jointarp/module/map"; +import type { MapEdit } from "@shared/map-vertex"; +import { useState } from "react"; + +import { Button } from "../../components/ui/button"; + +export function MapConnections({ + map, + maps, + config, + point, + commit, +}: { + map: ModuleMap; + maps: readonly ModuleMap[]; + config: MapConfig; + point?: MapPoint; + commit: (edit: MapEdit) => void; +}) { + const [name, setName] = useState(""); + const [sourceId, setSourceId] = useState(""); + const [targetId, setTargetId] = useState(""); + const [arrivalId, setArrivalId] = useState(""); + const [oneWay, setOneWay] = useState(false); + const targets = maps.filter((item) => item.id !== map.id && item.config.starts.length); + const target = targets.find((item) => item.id === targetId) ?? targets[0]; + const from = config.starts.find((item) => item.id === sourceId) ?? config.starts[0]; + const to = + target?.config.starts.find((item) => item.id === arrivalId) ?? target?.config.starts[0]; + const id = name.trim(); + const start = mapStartSchema.safeParse({ id, name: id, at: point }); + const used = [...config.starts, ...config.regions, ...config.tokens, ...config.doors].some( + (item) => item.id === id, + ); + const paired = + target && + from && + to && + (config.connections.some( + (link) => link.from === from.id && link.map === target.id && link.to === to.id, + ) || + target.config.connections.some( + (link) => !link.oneWay && link.from === to.id && link.map === map.id && link.to === from.id, + )); + return ( +
+

跨图出入口

+

+ {point ? `选点 (${point.join(", ")}) · 可添加为起点` : "点击底图,选择新起点的位置。"} +

+
+ setName(e.target.value)} + className="bg-background w-full rounded-md border p-1.5" + /> + + {used && 名称已被使用} + {point && id && !used && !start.success && ( + 名称不能包含空白、斜杠、# 或 ?。 + )} +
+ {(!from || !target) && ( +

+ {!from + ? "先为本图添加起点,再与其他地图配对。" + : "在另一张地图添加并保存起点后,即可配对。"} +

+ )} + {from && target && to && ( +
+ + + + + +
+ )} + {config.connections.map((link, index) => ( +
+ {link.from} {link.oneWay ? "→" : "↔"} {link.map} / {link.to} + +
+ ))} + {maps.flatMap((owner) => + owner.config.connections + .filter((link) => link.map === map.id) + .map((link) => ( +

+ {owner.id} / {link.from} {link.oneWay ? "→" : "↔"} {link.to}(在「{owner.id}」编辑) +

+ )), + )} +
+ ); +} diff --git a/apps/desktop/src/renderer/src/features/modules/MapInspector.tsx b/apps/desktop/src/renderer/src/features/modules/MapInspector.tsx new file mode 100644 index 0000000..83dc7ba --- /dev/null +++ b/apps/desktop/src/renderer/src/features/modules/MapInspector.tsx @@ -0,0 +1,965 @@ +import { mapLineage } from "@jointarp/module/map"; +import type { MapConfig, MapPoint, ModuleMap } from "@jointarp/module/map"; +import { applyMapEdit, type MapEdit, type VertexEdit } from "@shared/map-vertex"; +import { useQuery } from "@tanstack/react-query"; +import { useBlocker } from "@tanstack/react-router"; +import { + Check, + DoorOpen, + Layers, + Link2, + MousePointer2, + Pencil, + Save, + Scan, + Spline, + Undo2, + X, +} from "lucide-react"; +import { useEffect, useMemo, useRef, useState } from "react"; + +import { PageToolbarHeader } from "../../components/StickyPageToolbar"; +import { Button } from "../../components/ui/button"; +import { desktopOrpc, desktopRpc } from "../../desktop-rpc"; +import { useDocumentImage } from "./document-image"; +import { previewSight } from "./map-inspector-sight"; +import { MapConnections } from "./MapConnections"; + +const emptyMaps: readonly ModuleMap[] = []; + +export function MapInspector({ path }: { path: string }) { + const query = useQuery(desktopOrpc.modules.maps.queryOptions({ input: { path } })); + const [lastMap, setLastMap] = useState(); + const maps = query.data?.maps ?? emptyMaps; + const hierarchy = useMemo(() => { + const byId = new Map(maps.map((map) => [map.id, map])); + return maps + .map((map) => { + let chain: string[] = []; + try { + chain = mapLineage(map.id, (id) => { + const entry = byId.get(id); + if (!entry) throw new Error("上级地图缺失"); + return entry.config.parent; + }); + } catch { + /* 配置错误由查询结果展示,仍可选中地图修复。 */ + } + const label = chain.length + ? chain.map((id) => byId.get(id)!.config.name).join(" › ") + : map.config.name; + return { id: map.id, chain, label }; + }) + .sort((a, b) => a.label.localeCompare(b.label, "zh")); + }, [maps]); + const current = maps.find((map) => map.id === lastMap?.id); + const stale = + !!lastMap && !current && !!query.data?.issues.some((issue) => issue.path === lastMap.path); + const [pinned, setPinned] = useState(); + const selected = pinned ?? current ?? (stale ? lastMap : maps[0]); + useEffect(() => { + if (selected) setLastMap(selected); + }, [selected]); + return ( + <> + +
+
+ {selected && ( + + )} + +
+ {query.error &&

{query.error.message}

} + {query.data?.issues.map((issue) => ( +

+ {issue.path} · {issue.message} +

+ ))} + {(stale || (query.error && selected)) && ( +

读取失败,画布保留上次有效配置。修正文件后可重新加载。

+ )} + {query.data && !selected &&

模组的 maps 目录中没有可预览的地图。

} + {selected && ( + query.refetch()} + /> + )} +
+ + ); +} + +const layers = { walls: "墙线", doors: "门", regions: "区域", starts: "起点", sight: "视野" }; +type Layer = keyof typeof layers; + +function MapSheet({ + map, + hierarchy, + maps, + version, + root, + canEdit, + pin, + reload, +}: { + map: ModuleMap; + maps: readonly ModuleMap[]; + hierarchy: readonly { id: string; chain: string[]; label: string }[]; + version: number; + root: string; + canEdit: boolean; + pin: (map: ModuleMap | undefined) => void; + reload: () => Promise; +}) { + const { path } = map; + const [session, setSession] = useState<{ config: MapConfig; revision: string }>(); + const [edits, setEdits] = useState([]); + const [moving, setMoving] = useState(); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(""); + const [discard, setDiscard] = useState(false); + const [tool, setTool] = useState<"select" | "wall" | "door">("select"); + const [relationships, setRelationships] = useState(false); + const [hover, setHover] = useState(); + const [line, setLine] = useState([]); + const [first, setFirst] = useState<{ + wall: number; + segment: number; + t: number; + point: MapPoint; + }>(); + useBlocker({ + disabled: !edits.length && !busy && !line.length && !first, + enableBeforeUnload: true, + shouldBlockFn: () => { + setMessage("请先保存或放弃当前编辑。"); + return true; + }, + }); + const m = useMemo(() => { + if (!session) return map.config; + return (moving ? [...edits, moving] : edits).reduce(applyMapEdit, session.config); + }, [map.config, session, edits, moving]); + function selectTool(value: typeof tool) { + setTool(value); + setHover(undefined); + setLine([]); + setFirst(undefined); + setMessage(""); + setDiscard(false); + } + function commit(edit: MapEdit) { + setEdits((prev) => [...prev, edit]); + setDiscard(false); + setObjectKey(""); + selectTool("select"); + } + const finish = () => { + setRelationships(false); + selectTool("select"); + setSession(undefined); + setEdits([]); + setMoving(undefined); + setDiscard(false); + pin(undefined); + }; + const file = { path: root, file: path }; + async function begin() { + setBusy(true); + pin(map); + setMessage(""); + try { + setSession(await desktopRpc.modules.openMapEdit(file)); + } catch (error) { + setMessage(String(error)); + pin(undefined); + } finally { + setBusy(false); + } + } + async function save() { + if (!session) return; + setBusy(true); + try { + await desktopRpc.modules.saveMapEdit({ ...file, revision: session.revision, edits }); + await reload(); + finish(); + setMessage("地图已保存"); + } catch (error) { + setMessage(error instanceof Error ? error.message : String(error)); + } finally { + setBusy(false); + } + } + const [visible, setVisible] = useState>({ + walls: true, + doors: true, + regions: true, + starts: true, + sight: true, + }); + const [at, setAt] = useState(); + const svgRef = useRef(null); + const [camera, setCamera] = useState({ x: 0, y: 0, scale: 1 }); + const drag = useRef<{ + x: number; + y: number; + camera: typeof camera; + moved: boolean; + id: number; + handle?: VertexEdit; + } | null>(null); + const [objectKey, setObjectKey] = useState(""); + const zoomAt = (scale: number, anchor: MapPoint) => + setCamera((prev) => { + const next = Math.max(1, Math.min(12, scale)); + return { + scale: next, + x: anchor[0] - ((anchor[0] - prev.x) * prev.scale) / next, + y: anchor[1] - ((anchor[1] - prev.y) * prev.scale) / next, + }; + }); + useEffect(() => { + const svg = svgRef.current; + if (!svg) return; + const wheel = (e: WheelEvent) => { + const matrix = svg.getScreenCTM(); + if (!matrix) return; + e.preventDefault(); + const pt = new DOMPoint(e.clientX, e.clientY).matrixTransform(matrix.inverse()); + zoomAt(camera.scale * (e.deltaY < 0 ? 1.2 : 1 / 1.2), [pt.x, pt.y]); + }; + svg.addEventListener("wheel", wheel, { passive: false }); + return () => svg.removeEventListener("wheel", wheel); + }, [camera.scale]); + const objects = useMemo( + () => [ + ...m.walls.map((w, i) => ({ + key: `walls[${i}]`, + name: `墙线 ${i + 1}`, + points: w.points, + layer: "walls" as const, + })), + ...m.doors.map((d, i) => ({ + key: `doors[${i}]`, + name: d.id, + points: [d.from, d.to], + layer: "doors" as const, + })), + ...m.starts.map((s, i) => ({ + key: `starts[${i}]`, + name: s.name, + points: [s.at], + layer: "starts" as const, + })), + ...m.regions.map((r, i) => ({ + key: `regions[${i}]`, + name: r.name ?? r.id, + points: r.points, + layer: "regions" as const, + })), + ], + [m], + ); + const object = objects.find((o) => o.key === objectKey && visible[o.layer]); + const [copy, setCopy] = useState(""); + const [failed, setFailed] = useState(""); + const localImage = !/^(?:[a-z]+:|[/\\])/i.test(m.image) && !m.image.split(/[/\\]/).includes(".."); + const src = useDocumentImage("", localImage ? m.image : undefined); + const href = src && src + "&revision=" + version; + const point = + at && at[0] >= 0 && at[1] >= 0 && at[0] <= m.width && at[1] <= m.height ? at : undefined; + const sight = useMemo( + () => (point && visible.sight ? previewSight(m, point) : []), + [m, point, visible.sight], + ); + const draft = line.length > 0 || !!first; + const dirty = edits.length > 0 || draft; + const canSave = !!session && !!edits.length && !draft && !moving && !busy; + function undo() { + if (line.length) return setLine(line.slice(0, -1)); + if (first) return setFirst(undefined); + if (!edits.length) return; + selectTool("select"); + setObjectKey(""); + setEdits(edits.slice(0, -1)); + } + function chooseTool(value: typeof tool) { + setRelationships(false); + selectTool(value); + if (value === "wall") setVisible((v) => ({ ...v, walls: true })); + if (value === "door") setVisible((v) => ({ ...v, walls: true, doors: true })); + svgRef.current?.focus({ preventScroll: true }); + } + const hint = + tool === "wall" + ? line.length + ? `已标记 ${line.length} 个墙角,再点下一处墙角或完成墙线。` + : "点击第一个墙角开始绘制。" + : tool === "door" + ? first + ? "在同一墙段点另一端,确定门洞宽度。" + : "在已有墙线上点击门洞的第一端。" + : relationships + ? "点击底图选取起点位置,已有起点可直接配对。" + : session + ? "点击墙线或门可选中,拖动白色顶点调整形状。" + : "点击底图查看坐标与视野,拖动画布平移。"; + return ( +
{ + if (!session || busy || e.nativeEvent.isComposing) return; + const target = e.target as HTMLElement; + if (target.closest("input, select, textarea, [contenteditable=true]")) return; + const mod = e.ctrlKey || e.metaKey; + if (mod && !e.shiftKey && e.key.toLowerCase() === "s") { + e.preventDefault(); + if (canSave) void save(); + } else if (mod && !e.shiftKey && e.key.toLowerCase() === "z") { + e.preventDefault(); + undo(); + } else if (e.key === "Escape" && tool !== "select") { + e.preventDefault(); + chooseTool("select"); + } else if ( + e.key === "Enter" && + e.target === svgRef.current && + tool === "wall" && + line.length >= 2 + ) { + e.preventDefault(); + commit({ kind: "wall", points: line }); + } + }} + > +
+ {m.name} + {session ? ( + <> + + {busy ? "正在保存…" : dirty ? "有未保存更改" : "已保存"} + + + + + {discard && ( + + )} + + ) : ( + + )} +
+ {session && ( +
+ {( + [ + { value: "select", label: "选择", Icon: MousePointer2 }, + { value: "wall", label: "画墙", Icon: Spline }, + { value: "door", label: "开门洞", Icon: DoorOpen }, + ] as const + ).map(({ value, label, Icon }) => ( + + ))} + + {tool === "wall" && ( + + )} + {tool !== "select" && ( + + )} +
+ )} +
+

+ {message || hint} +

+
+ + + {Math.round(camera.scale * 100)}% + + + +
+
+
+
+ {(!href || failed === href) &&

无法载入底图 · {m.image}

} +
+ setHover(undefined)} + viewBox={`${camera.x} ${camera.y} ${m.width / camera.scale} ${m.height / camera.scale}`} + aria-label="地图校对画布" + className="block h-[55vh] w-full cursor-crosshair touch-none" + onPointerDown={(e) => { + if (e.button !== 0 || !e.isPrimary) return; + e.currentTarget.focus({ preventScroll: true }); + const vertex = (e.target as Element).getAttribute("data-vertex"); + const handle = + session && + !busy && + tool === "select" && + vertex !== null && + object && + (object.layer === "walls" || object.layer === "doors") + ? { + layer: object.layer, + index: Number(object.key.match(/\d+/)![0]), + vertex: Number(vertex), + at: object.points[Number(vertex)], + } + : undefined; + drag.current = { + handle, + x: e.clientX, + y: e.clientY, + camera, + moved: false, + id: e.pointerId, + }; + e.currentTarget.setPointerCapture(e.pointerId); + }} + onPointerMove={(e) => { + const start = drag.current, + matrix = e.currentTarget.getScreenCTM(); + if (!start && tool === "wall" && line.length && matrix) { + const p = new DOMPoint(e.clientX, e.clientY).matrixTransform(matrix.inverse()); + setHover( + p.x >= 0 && p.y >= 0 && p.x <= m.width && p.y <= m.height + ? [p.x, p.y] + : undefined, + ); + } + if (!start || start.id !== e.pointerId || !matrix) return; + const dx = e.clientX - start.x, + dy = e.clientY - start.y; + if (!start.moved && Math.hypot(dx, dy) < 4) return; + start.moved = true; + if (start.handle) { + const pt = new DOMPoint(e.clientX, e.clientY).matrixTransform(matrix.inverse()); + setMoving({ + ...start.handle, + at: [ + Math.max(0, Math.min(m.width, Math.round(pt.x))), + Math.max(0, Math.min(m.height, Math.round(pt.y))), + ], + }); + return; + } + setCamera({ + ...start.camera, + x: start.camera.x - dx / matrix.a, + y: start.camera.y - dy / matrix.d, + }); + }} + onLostPointerCapture={() => { + drag.current = null; + setMoving(undefined); + }} + onPointerUp={(e) => { + const start = drag.current, + matrix = e.currentTarget.getScreenCTM(); + if (!start || start.id !== e.pointerId || !matrix) return; + if (start.handle) { + if (start.moved) { + const pt = new DOMPoint(e.clientX, e.clientY).matrixTransform(matrix.inverse()); + const at: MapPoint = [ + Math.max(0, Math.min(m.width, Math.round(pt.x))), + Math.max(0, Math.min(m.height, Math.round(pt.y))), + ]; + if (at.some((v, i) => v !== start.handle!.at[i])) + setEdits((prev) => [...prev, { ...start.handle!, at }]); + setDiscard(false); + } + setMoving(undefined); + return; + } + if (start.moved) return; + const pos = new DOMPoint(e.clientX, e.clientY).matrixTransform(matrix.inverse()); + if (pos.x < 0 || pos.y < 0 || pos.x > m.width || pos.y > m.height) return; + if (busy) return; + if (tool === "wall") { + const p: MapPoint = [Math.round(pos.x), Math.round(pos.y)]; + if (!line.length || line.at(-1)!.some((v, i) => v !== p[i])) + setLine([...line, p]); + return; + } + if (tool === "door") { + let best: typeof first, + nearest = 12 / matrix.a; + for (const [wall, w] of m.walls.entries()) + for (let segment = 0; segment < w.points.length - 1; segment++) { + if (first && (wall !== first.wall || segment !== first.segment)) continue; + const [a, b] = w.points.slice(segment, segment + 2), + dx = b[0] - a[0], + dy = b[1] - a[1]; + if (!dx && !dy) continue; + const t = Math.min( + 1, + Math.max( + 0, + ((pos.x - a[0]) * dx + (pos.y - a[1]) * dy) / (dx * dx + dy * dy), + ), + ); + const point: MapPoint = [a[0] + t * dx, a[1] + t * dy], + d = Math.hypot(pos.x - point[0], pos.y - point[1]); + if (d <= nearest) { + nearest = d; + best = { wall, segment, t, point }; + } + } + if (!best) { + setMessage("请点击同一墙段上的位置"); + return; + } + if (!first) { + setFirst(best); + setMessage(""); + return; + } + if ( + Math.hypot(best.point[0] - first.point[0], best.point[1] - first.point[1]) < 1 + ) { + setMessage("门洞两端至少相距一个像素"); + return; + } + commit({ + kind: "door", + wall: first.wall, + segment: first.segment, + start: Math.min(first.t, best.t), + end: Math.max(first.t, best.t), + }); + return; + } + setObjectKey( + document + .elementFromPoint(e.clientX, e.clientY) + ?.closest("[data-object]") + ?.getAttribute("data-object") ?? "", + ); + setAt([Math.round(pos.x), Math.round(pos.y)]); + setCopy(""); + }} + > + {href && ( + setFailed(href)} + /> + )} + {sight.length > 0 && ( + + )} + {visible.regions && + m.regions.map((r, i) => ( + + {r.name ?? r.id} + + ))} + {visible.walls && + m.walls.map((w, i) => ( + + + + + ))} + {visible.doors && + m.doors.map((d, i) => ( + + + {d.id} · {d.open ? "开启" : "关闭"} + {d.secret ? " · 秘门" : ""} + + + ))} + {visible.starts && + m.starts.map((s, i) => ( + + {s.name} + + ))} + {object && + object.points.map(([x, y], i) => ( + + ))} + {hover && line.length > 0 && ( + + )} + {line.length > 0 && ( + + )} + {(first ? [first.point] : line).map(([x, y], i) => ( + + ))} + {point && ( + + )} + +
+
+ + {tool === "wall" ? "Enter 完成墙线 · Esc 取消" : "滚轮缩放 · 拖动平移"} + + {point ? ( + <> + [{point.join(", ")}] + + {copy} + + ) : ( + 点击底图拾取像素坐标并预览视野 + )} +
+
+ +
+
+ ); +} diff --git a/apps/desktop/src/renderer/src/features/modules/ModuleNavigation.tsx b/apps/desktop/src/renderer/src/features/modules/ModuleNavigation.tsx index b633380..a415443 100644 --- a/apps/desktop/src/renderer/src/features/modules/ModuleNavigation.tsx +++ b/apps/desktop/src/renderer/src/features/modules/ModuleNavigation.tsx @@ -25,7 +25,7 @@ export const typesPageId = "types"; export const preludePageId = "prelude"; export const startsPageId = "starts"; export const creationPageId = "creation"; -export type ModuleMetaPage = "types" | "prelude" | "starts" | "creation"; +export type ModuleMetaPage = "types" | "prelude" | "starts" | "creation" | "maps"; export interface ModuleNavItem { readonly icon: LucideIcon; diff --git a/apps/desktop/src/renderer/src/features/modules/ModulePage.tsx b/apps/desktop/src/renderer/src/features/modules/ModulePage.tsx index e14f02b..79ebd41 100644 --- a/apps/desktop/src/renderer/src/features/modules/ModulePage.tsx +++ b/apps/desktop/src/renderer/src/features/modules/ModulePage.tsx @@ -2,7 +2,7 @@ import { typeFormatLabel } from "@jointarp/module/document-path"; import { searchItems } from "@shared/query"; import { useQuery } from "@tanstack/react-query"; import { useSearch } from "@tanstack/react-router"; -import { BookOpenText, FileCode2, FileText, TriangleAlert } from "lucide-react"; +import { BookOpenText, FileCode2, FileText, MapIcon, TriangleAlert } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { PageToolbarHeader } from "../../components/StickyPageToolbar"; @@ -12,6 +12,7 @@ import { DocumentLibraryScope } from "./document-library-context"; import { DocumentReferences } from "./DocumentReferences"; import { DocumentTypesPage } from "./DocumentTypesPage"; import { LaunchOverviewPage } from "./LaunchOverviewPage"; +import { MapInspector } from "./MapInspector"; import { ModuleDocuments } from "./ModuleDocuments"; import { creationPageIcon, @@ -82,6 +83,7 @@ export function ModulePage() { : documentItems; const metaItems: ModuleNavItem[] = [ typesItem, + { id: "maps", label: "地图校对", icon: MapIcon, page: "maps" }, { id: preludePageId, label: "开场文案", icon: preludePageIcon, page: "prelude" }, { id: startsPageId, label: "开局方案", icon: startsPageIcon, page: "starts" }, { id: creationPageId, label: "角色创建", icon: creationPageIcon, page: "creation" }, @@ -170,6 +172,9 @@ export function ModulePage() { ) : null} + {opened?.status === "success" && page === "maps" && !reading ? ( + + ) : null} {opened?.status === "success" && onTypesPage ? ( { + const map = mapConfigSchema.parse({ + name: "校对测试", + image: "test.png", + width: 100, + height: 100, + grid: { type: "none", pixelsPerUnit: 1, unit: "米" }, + doors: [{ id: "门", from: [50, 0], to: [50, 100] }], + }); + expect(pointInPolygon([75, 50], previewSight(map, [25, 50]))).toBe(false); + map.doors[0]!.open = true; + expect(pointInPolygon([75, 50], previewSight(map, [25, 50]))).toBe(true); +}); diff --git a/apps/desktop/src/renderer/src/features/modules/map-inspector-sight.ts b/apps/desktop/src/renderer/src/features/modules/map-inspector-sight.ts new file mode 100644 index 0000000..a8dd0bf --- /dev/null +++ b/apps/desktop/src/renderer/src/features/modules/map-inspector-sight.ts @@ -0,0 +1,24 @@ +import type { MapConfig, MapPoint } from "@jointarp/module/map"; +import { + footprintPixels, + pixelsPerUnit, + squareSegments, + visibilityPolygon, + wallSegments, +} from "@jointarp/module/map-geometry"; + +export function previewSight(map: MapConfig, at: MapPoint) { + const blockers = [ + ...wallSegments(map), + ...map.doors.filter((d) => !d.open).map((d) => ({ a: d.from, b: d.to })), + ...map.tokens + .filter((t) => t.blocksVision) + .flatMap((t) => squareSegments(t.at, footprintPixels(map.grid, t.size))), + ]; + return visibilityPolygon( + at, + blockers, + map, + map.vision === undefined ? undefined : map.vision * pixelsPerUnit(map.grid), + ); +} diff --git a/apps/desktop/src/renderer/src/features/sessions/ChatComposer.tsx b/apps/desktop/src/renderer/src/features/sessions/ChatComposer.tsx index 27c8d3a..3203c4a 100644 --- a/apps/desktop/src/renderer/src/features/sessions/ChatComposer.tsx +++ b/apps/desktop/src/renderer/src/features/sessions/ChatComposer.tsx @@ -1,4 +1,4 @@ -import { ArrowLeftRight, ArrowUp, CornerUpLeft, Play, Square, X } from "lucide-react"; +import { ArrowLeftRight, ArrowUp, CornerUpLeft, Footprints, Play, Square, X } from "lucide-react"; import type { MouseEvent } from "react"; import { Button } from "../../components/ui/button"; @@ -10,6 +10,8 @@ import { SelectLabel, SelectTrigger, } from "../../components/ui/select"; +import { distanceText, summarizePlan, useRoomMaps } from "../maps/map-model"; +import { mapUi } from "../maps/map-ui"; import { SpeechControls } from "../tts/SpeechControls"; import type { useSpeech } from "../tts/use-speech"; import type { MentionCandidate } from "./mention"; @@ -85,6 +87,10 @@ export function ChatComposer({ submissionDisabled, sendDisabled, } = composer; + const maps = useRoomMaps(roomId); + const plan = composer.plan; + const planMap = maps.maps.find((item) => item.resource.id === plan?.map); + const planSummary = plan && planMap ? summarizePlan(planMap, plan) : undefined; function focusComposer() { mentionField.current?.focus(); } @@ -120,7 +126,7 @@ export function ChatComposer({ if (messageId) void actOnRun(messageId); } return ( -
+
+ {ready ? : null} void; - title: string; + title: ReactNode; description: string; + headerActions?: ReactNode; + finalFocus?: React.ComponentProps["finalFocus"]; wide?: boolean; preserveState?: boolean; children: ReactNode; @@ -32,11 +36,15 @@ export function GameToolDialog({ return ( - - {title} + + {title} + {headerActions} {description} {children} diff --git a/apps/desktop/src/renderer/src/features/sessions/room-connection.test.ts b/apps/desktop/src/renderer/src/features/sessions/room-connection.test.ts index 1cfcf27..004ecd5 100644 --- a/apps/desktop/src/renderer/src/features/sessions/room-connection.test.ts +++ b/apps/desktop/src/renderer/src/features/sessions/room-connection.test.ts @@ -39,6 +39,7 @@ function fixture() { module: { name: "测试" }, documentTypes: [], documents: [], + maps: [], pages: [], }; }, diff --git a/apps/desktop/src/renderer/src/features/sessions/room-state-store.ts b/apps/desktop/src/renderer/src/features/sessions/room-state-store.ts index c268eb3..059a6d7 100644 --- a/apps/desktop/src/renderer/src/features/sessions/room-state-store.ts +++ b/apps/desktop/src/renderer/src/features/sessions/room-state-store.ts @@ -95,6 +95,7 @@ export class RoomStateStore { "metrics", "chatActivity", "companionVersion", + "map", ] as const) { const json = decoder.state.sections.get(key); if (json === undefined) throw new Error("房间状态缺少必要字段"); diff --git a/apps/desktop/src/renderer/src/features/sessions/use-chat-composer.ts b/apps/desktop/src/renderer/src/features/sessions/use-chat-composer.ts index 7960dfc..d8334b0 100644 --- a/apps/desktop/src/renderer/src/features/sessions/use-chat-composer.ts +++ b/apps/desktop/src/renderer/src/features/sessions/use-chat-composer.ts @@ -9,6 +9,7 @@ import { parseMentionRefs } from "@jointarp/core/shared/mentions"; import type { ChatActivitySnapshot } from "@jointarp/core/shared/room-state"; import { useCallback, useEffect, useRef, useState } from "react"; +import { mapUi, useMapUi } from "../maps/map-ui"; import { errorMessage, type GameClient } from "./game-client"; import { draftText, @@ -71,8 +72,12 @@ export function useChatComposer({ const [convertingMessageId, setConvertingMessageId] = useState(null); const convertLock = useRef(false); const [failedSends, setFailedSends] = useState([]); + const plan = useMapUi(roomId).plan; const draftRetryPayload = failedSends.find( - (item) => item.text === currentText.trim() && item.chatOnly === chatOnly, + (item) => + item.text === currentText.trim() && + item.chatOnly === chatOnly && + JSON.stringify(item.movement) === JSON.stringify(plan), ); const retryingDraft = Boolean(draftRetryPayload); const [pendingRun, setPendingRun] = useState(null); @@ -91,7 +96,7 @@ export function useChatComposer({ const busy = Boolean(activeMessage); const canSteer = steering.enabled && busy && !activeMessage?.companionId && !activeMessage?.chatOnly; - const steeringMode = canSteer && !effectiveChatOnly && !retryingDraft; + const steeringMode = canSteer && !effectiveChatOnly && !retryingDraft && !plan; useEffect(() => { const request = continueRequest.current; if (request && ![...request.pendingIds].some((id) => pendingIds.has(id))) @@ -150,13 +155,18 @@ export function useChatComposer({ async function send(retry?: SendInput) { if (sendingLock.current || continuing || modeChanging || !player || !ready) return; const text = (retry?.text ?? currentText).trim(); - if (!text) return; + const movement = retry ? retry.movement : plan; + if (!text && !movement) return; const refs = parseMentionRefs(text); const only = retry?.chatOnly ?? chatOnly; const submittedDraft = currentText === text && chatOnly === only ? draft : undefined; const directed = refs.some((part) => mentions.some((target) => target.id === part.id)); const effectiveOnly = only || directed; const retryPayload = retry ?? draftRetryPayload; + if (movement && effectiveOnly) { + reportError("移动意图只能随行动提交,请切换到「行动」或移除移动。"); + return; + } if (!effectiveOnly && pendingInput) { reportError("有尚未送达主持的行动,请房主先重试或放弃;期间可以仅聊天。"); return; @@ -167,7 +177,12 @@ export function useChatComposer({ ); return; } - if (!retryPayload && !effectiveOnly && (canSteer || steeringRequest.current?.text === text)) { + if ( + !retryPayload && + !effectiveOnly && + !movement && + (canSteer || steeringRequest.current?.text === text) + ) { sendingLock.current = true; setSending(true); reportError(""); @@ -236,12 +251,17 @@ export function useChatComposer({ text, chatOnly: only, clientMessageId: crypto.randomUUID(), + ...(movement ? { movement } : {}), }; if (submittedDraft !== undefined) setDraft((current) => (current === submittedDraft ? [] : current)); const sent = await client.chat.send(payload, { signal }); if (signal?.aborted) return; actions.acceptMessage(sent); + if (payload.movement) + mapUi.update(roomId, (state) => + state.plan === payload!.movement ? { ...state, plan: undefined } : state, + ); const sentId = payload.clientMessageId; setFailedSends((current) => current.filter((item) => item.clientMessageId !== sentId)); scrollToBottom(); @@ -438,6 +458,7 @@ export function useChatComposer({ submitSteering, draft, draftText: visibleDraft, + plan, setDraft, mentionField, quickMention, @@ -486,7 +507,7 @@ export function useChatComposer({ modeChanging || !player || !ready || - !visibleDraft.trim() || + (!visibleDraft.trim() && !plan) || (!effectiveChatOnly && Boolean(pendingInput)) || (!retryingDraft && !effectiveChatOnly && busy && !activeMessage?.companionId && !canSteer), }; diff --git a/apps/desktop/src/renderer/src/features/sessions/use-room-state.ts b/apps/desktop/src/renderer/src/features/sessions/use-room-state.ts index d3365bc..ff05693 100644 --- a/apps/desktop/src/renderer/src/features/sessions/use-room-state.ts +++ b/apps/desktop/src/renderer/src/features/sessions/use-room-state.ts @@ -30,7 +30,7 @@ const characterCache = new WeakMap< { document?: ModuleDocument; character: Character } >(); const documentsCache = new WeakMap(); -function roomDocuments(replica: RoomReplica): ModuleDocument[] { +export function roomDocuments(replica: RoomReplica): ModuleDocument[] { const cached = documentsCache.get(replica.entities); if (cached) return cached; const documents = Object.values(replica.entities).map((entity) => { diff --git a/apps/desktop/src/renderer/src/router.tsx b/apps/desktop/src/renderer/src/router.tsx index 93d2a3f..810e0e4 100644 --- a/apps/desktop/src/renderer/src/router.tsx +++ b/apps/desktop/src/renderer/src/router.tsx @@ -74,7 +74,7 @@ const historyRoute = createRoute({ interface ModuleSearch { readonly path: string; readonly type?: string; - readonly page?: "types" | "prelude" | "starts" | "creation"; + readonly page?: "types" | "prelude" | "starts" | "creation" | "maps"; readonly define?: string; readonly reading?: string; } @@ -93,7 +93,8 @@ const moduleRoute = createRoute({ search.page === "types" || search.page === "prelude" || search.page === "starts" || - search.page === "creation" + search.page === "creation" || + search.page === "maps" ? search.page : undefined, define: diff --git a/apps/desktop/src/shared/map-vertex.ts b/apps/desktop/src/shared/map-vertex.ts new file mode 100644 index 0000000..1fb33b5 --- /dev/null +++ b/apps/desktop/src/shared/map-vertex.ts @@ -0,0 +1,108 @@ +import { + mapConnectionSchema, + mapStartSchema, + mapPointSchema, + type MapConfig, +} from "@jointarp/module/map"; +import { z } from "zod"; + +export const vertexEditSchema = z.strictObject({ + layer: z.enum(["walls", "doors"]), + index: z.number().int().nonnegative(), + vertex: z.number().int().nonnegative(), + at: mapPointSchema, +}); +export type VertexEdit = z.infer; + +export function editPoint(map: MapConfig, edit: VertexEdit) { + const point = + edit.layer === "walls" + ? map.walls[edit.index]?.points[edit.vertex] + : edit.vertex === 0 + ? map.doors[edit.index]?.from + : edit.vertex === 1 + ? map.doors[edit.index]?.to + : undefined; + if (!point) throw new Error("找不到所选顶点"); + return point; +} + +export const mapEditSchema = z.union([ + vertexEditSchema, + z.strictObject({ kind: z.literal("start"), start: mapStartSchema }), + z.strictObject({ kind: z.literal("connect"), link: mapConnectionSchema }), + z.strictObject({ kind: z.literal("disconnect"), index: z.number().int().nonnegative() }), + z.strictObject({ kind: z.literal("parent"), parent: z.string().min(1).nullable() }), + z.strictObject({ kind: z.literal("wall"), points: z.array(mapPointSchema).min(2) }), + z.strictObject({ + kind: z.literal("delete"), + layer: z.enum(["walls", "doors"]), + index: z.number().int().nonnegative(), + }), + z.strictObject({ + kind: z.literal("door"), + wall: z.number().int().nonnegative(), + segment: z.number().int().nonnegative(), + start: z.number().min(0).max(1), + end: z.number().min(0).max(1), + }), +]); +export type MapEdit = z.infer; + +export function applyMapEdit(map: MapConfig, edit: MapEdit): MapConfig { + if ("kind" in edit && edit.kind === "parent") { + const next = { ...map }; + if (edit.parent === null) delete next.parent; + else next.parent = edit.parent; + return next; + } + if ("kind" in edit) { + if (edit.kind === "start") return { ...map, starts: [...map.starts, edit.start] }; + if (edit.kind === "connect") return { ...map, connections: [...map.connections, edit.link] }; + if (edit.kind === "disconnect") + return { ...map, connections: map.connections.filter((_, i) => i !== edit.index) }; + } + const walls = [...map.walls], + doors = [...map.doors]; + if (!("kind" in edit)) { + editPoint(map, edit); + if (edit.layer === "walls") { + const points = [...walls[edit.index].points]; + points[edit.vertex] = edit.at; + walls[edit.index] = { points }; + } else + doors[edit.index] = { ...doors[edit.index], [edit.vertex === 0 ? "from" : "to"]: edit.at }; + } else if (edit.kind === "wall") { + walls.push({ points: edit.points }); + } else if (edit.kind === "delete") { + const items = edit.layer === "walls" ? walls : doors; + if (!items[edit.index]) throw Error("找不到要删除的对象"); + items.splice(edit.index, 1); + } else { + const points = walls[edit.wall]?.points; + const a = points?.[edit.segment], + b = points?.[edit.segment + 1]; + if (!a || !b || edit.end <= edit.start || (a[0] === b[0] && a[1] === b[1])) + throw Error("门洞需要同一墙段上两个不同的位置"); + const along = (t: number): [number, number] => [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + ]; + const from = along(edit.start), + to = along(edit.end); + const before = points.slice(0, edit.segment + 1), + after = points.slice(edit.segment + 1); + if (edit.start > 0) before.push(from); + if (edit.end < 1) after.unshift(to); + walls.splice( + edit.wall, + 1, + ...[before, after].filter((p) => p.length >= 2).map((points) => ({ points })), + ); + const ids = new Set([...doors, ...map.regions, ...map.tokens, ...map.starts].map((o) => o.id)); + let n = 1; + while (ids.has("门-" + n)) n++; + doors.push({ id: "门-" + n, from, to, open: false, secret: false }); + } + return { ...map, walls, doors }; +} diff --git a/bun.lock b/bun.lock index 8e5a27c..6e11f8c 100644 --- a/bun.lock +++ b/bun.lock @@ -39,6 +39,8 @@ "es-toolkit": "^1.53.0", "fast-json-patch": "^3.1.1", "html-react-parser": "^6.1.9", + "jsonc-parser": "^3.3.1", + "konva": "^10.9.1", "kysely": "^0.29.7", "lucide-react": "^1.62.0", "mdast-util-from-markdown": "^2.1.0", @@ -50,11 +52,13 @@ "quickjs-emscripten": "^0.32.0", "react": "^19.3.1", "react-dom": "^19.3.1", + "react-konva": "^19.3.2", "react-markdown": "^10.1.0", "react-photo-view": "1.2.7", "remark-gfm": "^4.0.1", "ses": "^2.3.0", "streamdown": "^2.7.1", + "toml-eslint-parser": "^1.0.3", "tw-animate-css": "^1.4.0", "typebox": "1.3.7", "zod": "^4.6.7", @@ -477,6 +481,8 @@ "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], + "@types/react-reconciler": ["@types/react-reconciler@0.34.0", "", { "peerDependencies": { "@types/react": "*" } }, "sha512-zVDzX0Fk1XgDP2IutTpSrxd57jwOHlX3rlPrFz68Sc+06tpgOFRlqSUK2ZiqQeQXqnIfUb2cfJQUupXBKy498w=="], + "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], @@ -647,6 +653,8 @@ "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], + "eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], + "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], @@ -779,6 +787,8 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + "its-fine": ["its-fine@2.1.1", "", { "dependencies": { "@types/react-reconciler": "^0.28.9" }, "peerDependencies": { "react": "^19.0.0" } }, "sha512-C5ZoVkeqSt0Aje0tzESO+iT/EQpNFNL39GkP7mCACtoZUFD6GcyerFCr6kp0ZtiII4W9HoYkY48Soy5xE/uHKw=="], + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], "jose": ["jose@6.2.13", "", {}, "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="], @@ -791,10 +801,14 @@ "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], + "jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="], + "jwa": ["jwa@2.0.1", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="], "jws": ["jws@4.0.1", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="], + "konva": ["konva@10.9.1", "", { "peerDependencies": { "canvas": "^3.0.0", "skia-canvas": "^3.0.0" }, "optionalPeers": ["canvas", "skia-canvas"] }, "sha512-m49x+GatSxEUSvqahYhxpTjgKbtrLtw4P4o4B4iux953ZFpceaK52Ea+CFsAsd7W4I0Y5u6mMoRUsY/eltNZmw=="], + "kysely": ["kysely@0.29.7", "", {}, "sha512-fmIq+7kv4WbFm2tcfznRzikqB4cuNpgZ40PSU2fAJ2/OO5XhojqnTPrmgrCjYSRJVwBln03XcRXJGnw9H099IQ=="], "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], @@ -1027,12 +1041,16 @@ "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], + "react-konva": ["react-konva@19.3.2", "", { "dependencies": { "@types/react-reconciler": "0.34.0", "its-fine": "^2.1.1", "react-reconciler": "0.34.0", "scheduler": "0.28.0" }, "peerDependencies": { "konva": "^8.0.1 || ^7.2.5 || ^9.0.0 || ^10.0.0", "react": "^19.3.0", "react-dom": "^19.3.0" } }, "sha512-Uv0xlWoRSCByHinqs/03SFL8E28fYbe59sQ+2EJpwa1O4Zlz0+T+8DaKwlma9C2rkYwYj6j8eHD41F5oJafagg=="], + "react-markdown": ["react-markdown@10.1.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "html-url-attributes": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "unified": "^11.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="], "react-photo-view": ["react-photo-view@1.2.7", "", { "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-MfOWVPxuibncRLaycZUNxqYU8D9IA+rbGDDaq6GM8RIoGJal592hEJoRAyRSI7ZxyyJNJTLMUWWL3UIXHJJOpw=="], "react-property": ["react-property@2.0.2", "", {}, "sha512-+PbtI3VuDV0l6CleQMsx2gtK0JZbZKbpdu5ynr+lbsuvtmgbNcS3VM0tuY2QjFNOcWxvXeHjDpy42RO+4U2rug=="], + "react-reconciler": ["react-reconciler@0.34.0", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.0" } }, "sha512-eVibvB1fc9j5Qf1KRkiM3GzRPBdjg2P6G6QV2f3P6Eb3OGMxRBhdg2rrUwjbV5JrQaJj8nOa8uajmmJA5tJWjQ=="], + "rehype-harden": ["rehype-harden@1.1.8", "", { "dependencies": { "unist-util-visit": "^5.0.0" } }, "sha512-Qn7vR1xrf6fZCrkm9TDWi/AB4ylrHy+jqsNm1EHOAmbARYA6gsnVJBq/sdBh6kmT4NEZxH5vgIjrscefJAOXcw=="], "rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="], @@ -1135,6 +1153,8 @@ "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + "toml-eslint-parser": ["toml-eslint-parser@1.0.3", "", { "dependencies": { "eslint-visitor-keys": "^5.0.0" } }, "sha512-A5F0cM6+mDleacLIEUkmfpkBbnHJFV1d2rprHU2MXNk7mlxHq2zGojA+SRvQD1RoMo9gqjZPWEaKG4v1BQ48lw=="], + "trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="], "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], @@ -1255,6 +1275,8 @@ "hast-util-to-jsx-runtime/style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="], + "its-fine/@types/react-reconciler": ["@types/react-reconciler@0.28.9", "", { "peerDependencies": { "@types/react": "*" } }, "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg=="], + "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], "p-retry/retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 95e9858..4004e74 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -19,6 +19,26 @@ _避免_:将文件扩展名视为文档身份的一部分。 **冒险基础模组**:创建冒险时固定下来的模组资料,是本局变化所继承的基础。 _避免_:与模组库中仍可编辑的作者资料混用。 +## 地图与探索 + +**概览地图**:通过固定地图点表达地点及其关系的地图,角色只能以这些地点为移动目的地,不在图上任意选择坐标。世界、区域或城镇地图都可采用这种形式。 +_避免_:将其等同于层级最上方的地图,或与允许坐标移动的场景地图混用。 + +**场景地图**:展示局部环境、角色位置及空间关系的地图,可以位于另一张地图所表达的地点内部。 +_避免_:用“小地图”同时指代局部场景与导航缩略图。 + +**子地图**:与父地图中某个地点关联的更细致地图;查看子地图不代表角色已进入该地点。 +_避免_:将地图浏览切换等同于角色移动。 + +**移动意图**:角色希望前往某个位置的行动声明,实际抵达位置、耗时与途中事件尚待主持裁定。 +_避免_:将目标预览视为已完成移动。 + +**当前可见范围**:角色此刻能够观察到的空间范围,区别于曾经探索过但此刻无法观察的区域。 +_避免_:将已探索等同于持续掌握区域内的实时情况。 + +**探索记录**:队伍已经获知的地图空间信息,不代表队伍当前身处或能看见这些区域。 +_避免_:与当前视野混用。 + ## 状态与结束 **模组状态**:模组自行定义并随冒险变化的事实,包括位置、时间、资源、效果和剧情进展,其结构与含义由模组规则决定。 diff --git a/docs/README.md b/docs/README.md index fdb49b1..21fdbda 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ - [角色与开局实现](角色与开局实现.md):进度、角色占用、建卡求值与保密、开场消息及恢复。 - [游戏聊天与 AI 实现](游戏聊天与AI实现.md):正文协议、输入接收、主持插话、队友调度、会话上下文、事件恢复与凭据。 - [MCP 预演实现](MCP预演实现.md):临时测试局、前置数据初始化、AI 队友逐步驱动、本地 MCP 接入及清理边界。 +- [地图实现](地图实现.md):场景地图加载、空间状态、共享视野、主持工具、移动意图与界面边界。 - [游戏状态实现](游戏状态实现.md):模组自定状态、公开展示、主持上下文和明确结束操作。 - [语音朗读实现](语音朗读实现.md):提供商适配、消息解析、共享任务、流式播放、锁与验证。 - [模组共享包](../packages/module/README.md)与[CLI 开发](../packages/module-cli/README.md):包边界、构建、打包和发布。 @@ -35,6 +36,8 @@ - [ADR-0003:统一主持输入接收确认](adr/0003-统一主持输入接收确认.md):真人与队友共享提交批次、接收回执和失败恢复。 - [ADR-0004:模组解释玩法状态](adr/0004-模组解释玩法状态.md):通用数据能力与模组玩法的职责边界。 - [ADR-0005:类型目录与嵌套资料分组](adr/0005-类型目录与嵌套资料分组.md):一级目录决定文档类型,子目录承载嵌套分类的边界。 +- [ADR-0006:地图移动由主持统一裁定](adr/0006-地图移动由主持统一裁定.md):移动意图预览与主持确认的边界。 +- [ADR-0007:平台保存地图空间状态](adr/0007-平台保存地图空间状态.md):地图配置、空间位置与模组地点字段的职责划分。 ## 文档维护 diff --git "a/docs/adr/0004-\346\250\241\347\273\204\350\247\243\351\207\212\347\216\251\346\263\225\347\212\266\346\200\201.md" "b/docs/adr/0004-\346\250\241\347\273\204\350\247\243\351\207\212\347\216\251\346\263\225\347\212\266\346\200\201.md" index d82d8f2..a1bbc40 100644 --- "a/docs/adr/0004-\346\250\241\347\273\204\350\247\243\351\207\212\347\216\251\346\263\225\347\212\266\346\200\201.md" +++ "b/docs/adr/0004-\346\250\241\347\273\204\350\247\243\351\207\212\347\216\251\346\263\225\347\212\266\346\200\201.md" @@ -2,4 +2,4 @@ 位置、场景、参与者、时间、回合、效果和胜负由模组自行建模与解释,平台通过通用文档、计算、布局和明确操作支持游戏。移除固定状态绑定、自动入场和玩法状态投影,避免某套场景模型成为所有模组的隐含前提;世界卡与引用文档使用作者配置的完整布局。房间生命周期、角色控制、数据权限和存储校验仍由平台负责,主持按模组规则明确调用结束冒险操作。 -这一选择放弃平台统一检查唯一场景归属、行动顺序等玩法一致性,由模组规则、主持和模组验收承担;不以另一套通用规则配置语言重新引入相同耦合。当前版本移除地图功能,后续设计应遵循同一边界。 +这一选择放弃平台统一检查唯一场景归属、行动顺序等玩法一致性,由模组规则、主持和模组验收承担;不以另一套通用规则配置语言重新引入相同耦合。此前的地图实现已移除;新的地图空间位置由平台保存,边界见 [ADR 0007](0007-平台保存地图空间状态.md),地点含义、耗时与规则效果仍由模组解释。 diff --git "a/docs/adr/0006-\345\234\260\345\233\276\347\247\273\345\212\250\347\224\261\344\270\273\346\214\201\347\273\237\344\270\200\350\243\201\345\256\232.md" "b/docs/adr/0006-\345\234\260\345\233\276\347\247\273\345\212\250\347\224\261\344\270\273\346\214\201\347\273\237\344\270\200\350\243\201\345\256\232.md" new file mode 100644 index 0000000..a2aabd0 --- /dev/null +++ "b/docs/adr/0006-\345\234\260\345\233\276\347\247\273\345\212\250\347\224\261\344\270\273\346\214\201\347\273\237\344\270\200\350\243\201\345\256\232.md" @@ -0,0 +1,7 @@ +# 地图移动由主持统一裁定 + +地图交互提交移动意图,由主持按模组规则统一结算实际位置、游戏耗时和途中事件,随后地图更新位置与探索表现;等待期间的目标和路线仅为预览,不改变真实位置或提前揭雾。多人行动共同结算,避免把同时发生的行动耗时简单累加。 + +这一边界牺牲直接拖动即时生效的体验,以避免 AI 处理延迟导致角色先越过事件点、随后回退并泄露未知区域。即便路线已经探索,移动仍可能消耗时间和资源并触发事件,因此首版不采用“已知路段自动结算、遇事再交主持”的方案。 + +本决策是后续地图功能的设计约束,尚未实现;延续 [ADR 0004](0004-模组解释玩法状态.md) 的模组解释规则边界,具体空间契约与首版规则覆盖范围仍在[设计讨论](../地图功能设计讨论.md)中澄清。 diff --git "a/docs/adr/0007-\345\271\263\345\217\260\344\277\235\345\255\230\345\234\260\345\233\276\347\251\272\351\227\264\347\212\266\346\200\201.md" "b/docs/adr/0007-\345\271\263\345\217\260\344\277\235\345\255\230\345\234\260\345\233\276\347\251\272\351\227\264\347\212\266\346\200\201.md" new file mode 100644 index 0000000..93a6ea7 --- /dev/null +++ "b/docs/adr/0007-\345\271\263\345\217\260\344\277\235\345\255\230\345\234\260\345\233\276\347\251\272\351\227\264\347\212\266\346\200\201.md" @@ -0,0 +1,7 @@ +# 平台保存地图空间状态 + +地图配置放在模组的 `maps/` 目录,使用平台固定格式,不进入作者自定义的文档类型系统。房间内角色所在地图与坐标、门状态和队伍探索记录由平台保存在独立的房间地图状态中,主持通过专用地图工具更新;模组自有的地点、时间与资源字段保持不变,由主持按模组规则同时维护。 + +这一选择修订 [ADR 0004](0004-模组解释玩法状态.md) 关于“位置由模组解释”的边界:平台只拥有几何意义上的空间位置、视野和遮挡,不解释地点归属、耗时、通行合法性或规则效果,也不自动安排入场。平台空间位置与模组地点字段可能短暂不一致,由主持裁定并修正,不建立自动双向同步。 + +地图状态按查看者投影后同步:主机按全队视野过滤,只下发当前可见的标记与探索记录,不把原始地图状态放入共享文档实体。底图、墙体和门等静态配置与现有 `public/gm` 字段处于同一本机信任边界,云端权限上线前统一处理。移动仍遵循 [ADR 0006](0006-地图移动由主持统一裁定.md):玩家提交的移动意图只是预览,主持确认后才改变位置并揭示。 diff --git "a/docs/\345\234\260\345\233\276\345\212\237\350\203\275\350\256\276\350\256\241\350\256\250\350\256\272.md" "b/docs/\345\234\260\345\233\276\345\212\237\350\203\275\350\256\276\350\256\241\350\256\250\350\256\272.md" new file mode 100644 index 0000000..a842d4c --- /dev/null +++ "b/docs/\345\234\260\345\233\276\345\212\237\350\203\275\350\256\276\350\256\241\350\256\250\350\256\272.md" @@ -0,0 +1,135 @@ +# 地图功能设计讨论 + +状态:已确认分期实现,第一期进行中;未列入第一期的内容仍按本文讨论结论推进,不作为已实现能力或公开配置规范。记录日期:2026-11-02。 + +## 实现分期与第一期决策 + +已确认分四期: + +1. 场景地图、墙门视野与迷雾、移动意图与主持确认、房间地图面板;地图配置先手写。 +2. 概览地图、可选单一上级的嵌套浏览与跨图连接。 +3. 战斗模式、移动预算、困难地形、多格占地与分段移动。 +4. 简单可视化编辑器。 + +第一期已确认的实现决策: + +- 地图配置放在模组 `maps/` 目录,使用平台固定格式;角色位置、门状态和探索记录保存在平台房间地图状态,主持通过专用工具更新,边界见 [ADR 0007](adr/0007-平台保存地图空间状态.md)。 +- 主机按全队视野投影后同步,渲染端只收到可见标记与探索记录;底图、墙体和门等静态配置与现有 `public/gm` 字段处于同一本机信任边界。 +- 门只分开和关;可选秘门在主持揭示前对玩家按墙处理。上锁由主持在规则层面处理,地图上仍为关门。 +- 作者配置命名起点,主持按剧情把角色放到起点,平台不自动入场。 +- 移动意图卡附在行动消息下方随消息发送,不能附在聊天消息上;允许只有卡片没有文字,每条消息最多一张,只能为自己控制的角色提交。卡片只记录目标、途经点与预估距离,实际结果看地图和主持叙述;等待裁定期间地图显示虚线路线。 +- AI 队友第一期不提交移动意图卡,用文字描述移动,由主持移动标记。 +- 主持模型以语义理解地图,米坐标兜底:作者可划命名区域,区域可关联地点资料或标为幕后;平台把位置、意图路线与视野翻译为区域、门、标记和距离,并标出穿过阻挡物件、终点重叠、通道窄于标记和进入未探索区域。主持确认移动时引用意图路线,指定走完、走到第几米或停在进入某区域、穿过某门之前;直接放置支持起点、区域方位、标记旁侧和米坐标。 +- 带意图卡的行动自动附上仅主持可见的路线描述,玩家卡片只显示目标、途经点和预估距离;每轮附一行队伍位置摘要,完整状态按需读取。`map_read` 可选返回带标注的地图图片,供支持读图的模型参考。 +- 物件标记可选阻挡通行,只用于规划提示与主持提醒,不强制拒绝移动。同行 NPC 由主持按叙述移动。 +- 以上表示方式经过一轮对照实验:纯坐标需要模型自行拼出房间,纯语义缺少精确落点,混合方案保留两者优点。实现完成后用实际配置的主持模型通过 MCP 预演验收。 +- 渲染使用 Konva;真实验收使用「石冢-后山古墓」,平台测试使用独立测试夹具。 + +## 已确认的方向 + +- 首要目标是定位与探索,参考 FVTT 的场景地图体验,使用底图与热点。 +- 支持全局地图与场景地图嵌套;多层嵌套、面包屑、各地图独立比例尺与探索方式的建议已获认可。查看已知子地图与角色进入子地图分开,父地图揭示不自动揭示内部。 +- 地点与移动规则由模组定义,主持负责裁定;需灵活支持 CoC、D&D 常用玩法,已确认以 CoC 第七版与 D&D 2024 为验收基线;首版玩法范围见下文。 +- 点击或拖动提交移动意图,主持统一结算位置、耗时及途中事件。确认前显示目标与虚线路线,角色保留原位,不提前揭雾;确认后表现实际移动,途中事件可使移动提前结束。 +- 多人意图集中处理,共同推进游戏时间,不把同时行动的各人耗时简单相加。这里的行动收集批次不等同于规则中的战斗回合。 +- 场景地图首版支持角色标记、视距、墙体遮挡、门,以及未探索、已探索但当前不可见、当前可见三种表现;全队共享视野和探索记录。复杂光照暂不纳入。 +- 首版加入简单可视化编辑器:底图、比例尺、墙线、门、角色初始位置,以及选择、移动、删除、撤销;位于模组编辑入口,保存回模组。游戏中改变门、位置和探索状态,暂不编辑墙体布局。 +- 验收最初约定以一个真实模组跑通;后来提出的独立测试模组建议尚未确认,二者不可混为已决事项。 + +## 已确认的地图交互边界 + +地图保持少量交互,以空间查看与移动意图为主。开门、关门等通过正常行动描述交给主持处理,地图不提供对应的专用操作按钮;主持更新状态后,地图反映新的遮挡与通行情况。作者使用的可视化编辑器仍保留。 + +困难地形由作者绘制并添加说明,地图只展示已知信息,移动消耗由主持结算,首版不自动预览地形费用。角色占地由作者配置并在地图显示;窄道通行与挤压交主持判断,不提供额外通行提示。 + +## 已确认的移动交互 + +- 主持可以只结算到途中中断点;需要玩家选择时暂停,剩余路径保持为未执行的意图。 +- 已探索区域允许规划路线与途经点;未知区域只能指定探索方向或入口,不提供穿越未知区域的精确路径和耗时预览。 +- 探索时集中处理多人意图;战斗时当前角色可以分次提交移动、动作与剩余移动,其他角色的反应可插入处理,不等整轮结束才询问。 +- 路径分段表达实际位置变化及相关时间、资源变化;后续尚未决定的路段不计入实际执行结果。 + +## 已确认的主持权限与动态信息 + +- 主持可直接调整角色所在地图与位置、门状态和揭示范围,用于传送、剧情变化或纠正错误;不受普通移动路径约束。 +- 已探索但当前不可见的区域保留地形,不显示 NPC、敌人及其移动,也不显示最后位置残影。 + +## 已确认的全局地图探索 + +全局地图可配置为整张公开,或按作者划定的区域由主持逐步揭示;场景地图继续使用角色视野揭雾。地图采用可选单一上级组织浏览,跨图连接独立表达通路。 + +## 已确认的跨图移动 + +- 作者配置跨图连接两端的入口,默认双向,也可设为单向;是否通过由主持按行动、事件与耗时裁定,不设置玩家直接传送按钮。 +- 首版一次地图移动意图最多通过一个跨图连接。到达目标入口后,原地图剩余路线结束,玩家查看新环境后重新选择后续路线。 +- 跨图时主持确认前保留原位置;确认后更新实际通过的角色所在地图与位置,按抵达视野揭示,原地图探索记录保留。 +- 自己控制的角色跨图时界面自动跟随;队友跨图不强制切换自己的画面。允许查看队友所在地图及全队已探索地图,浏览不改变角色位置。 +- 已确认角色在当前场景内移动,上层地图只表达所在地点,不同步局部坐标;离开地点后由主持更新归属。概览地图仅允许前往固定地图点,场景地图才支持坐标与路径移动;地图类型不由层级决定。 +- 已确认首版采用可选单一上级组织嵌套浏览,实际通路由跨图连接表达,不受浏览层级限制。 + +## 取舍与被替代的建议 + +- 单纯地点节点与连线被底图及热点取代。 +- 仅手工揭示区域,以及未知/传闻/已探索的三层情报方案,未被采纳为首版设计;后续转向 FVTT 式空间视野。 +- 玩家直接移动,或已知路段自动移动、遇事再停下的方案,被统一提交主持裁定取代:已知路线仍消耗游戏时间,并可能触发巡逻、资源消耗或途中事件;AI 延迟可能造成先移动、后追溯裁定和信息泄露。 +- 仅配置文件、不做编辑器的建议被简单可视化编辑器取代。 + +## 已确认的规则适配范围 + +用户已确认以下四项;细化验收仍需确认: + +1. 平台提供通用空间能力,模组定义移动速度、行动消耗、检定和特殊感官;具体平台契约需进一步设计,不能据此推定固定场景归属。 +2. 同一地图可切换探索与战斗模式;战斗按先攻处理,并辅助显示移动预算。 +3. 首版支持无网格、方格及可选斜向计距方式;六角格后续加入。 +4. 首版验收覆盖 CoC 调查探索、耗时行动与基础战斗,以及 D&D 探索、先攻和移动距离;追逐、完整法术范围与特殊感官自动化延后。 + +已确认首版纳入困难地形标注、多格角色占地、同回合分段移动、途中暂停裁定。全队共享视野仍保留,各角色实际感知差异由主持处理,不精确模拟独立视觉。 + +具体场景、验收结果和待决边界见 [CoC 与 D&D 地图验收草案](地图规则验收草案.md)。 + +## 后续需要继续追问的分支 + +- 具体真实验收模组,以及独立测试数据的范围。 +- 路线长度的计算职责与已知区域的规划细节;已确认支持途经点,未知区域不提供精确穿越路线。 +- 现有行动收集机制的接入、多人不同行动时长、分队和跨地图行动的时间推进。 +- 全局地图的区域揭示编辑方式、地图出口与子地图入口关系、角色跨图定位。 +- 门的开关与交互、视距来源、已探索区域中的动态实体可见性,以及主持额外揭示或重置探索的权限。 +- 地图配置与房间状态的数据边界、保存恢复、同步及隐藏数据权限;需结合现有实现调查后再问决策。 + +## 架构依据与文档边界 + +- [ADR 0004](adr/0004-模组解释玩法状态.md) 明确当前实现已移除地图,位置与时间由模组解释。新设计不能被描述为现成功能,也不能默默引入统一玩法规则。 +- [地图移动裁定决策](adr/0006-地图移动由主持统一裁定.md) 记录已确认的移动边界;[术语表](GLOSSARY.md) 记录相关领域用语。 +- 本文只保存内部设计讨论;公开行为与最终模组配置格式确定后,应同步官网正文,不在本文复制公开参数规范。 +- 每轮访谈后更新已确认项与待决项;各期开始前确认该期范围内的待决项。 + +## 范围收敛:避免过度设计 + +用户明确担心地图层级过度设计。首版已确认收敛为简单地图列表与可选单一上级,提供嵌套浏览;跨图连接独立表达实际通路。暂不加入多上级引用、独立位置归属模型或移动载具地图,不由风险举例推导额外需求。 + +## 地图类型与移动方式 + +- 已确认简化层级:每张地图可选一个上级;跨图连接可连接任意地图入口,不增加多上级或独立归属系统。 +- 用户提出将地图明确分为概览地图与场景地图。概览地图只允许移动到作者配置的固定地图点,不允许任意坐标移动;场景地图允许提交坐标目标与路径。类型与嵌套深度无关。 +- 两种移动均遵循已有主持裁定边界:选择目标不直接更新位置,主持处理时间与事件后确认实际结果。 +- 已确认:概览地点不强制连线;玩家选择已知地点提交前往意图,由主持根据模组裁定可达性、路线、时间与途中事件,编辑器不要求维护路网。 +- 已确认:抵达概览地点不自动进入关联场景;主持根据行动裁定是否进入及实际入口,地图据结果切换。 +- 已确认:概览地点可以没有场景图,抵达后通过文字行动交互,不要求创建空场景。 +- 已确认:概览旅行途中被事件打断时,显示“前往某地途中”,不虚构自由坐标或提前标记抵达。有遭遇场景图时由主持切入,没有时通过文字处理,后续继续或返回由主持裁定;首版不增加旅行进度条或自动计时系统。 + +## 已确认的角色标记 + +玩家角色与 NPC 标记关联已有角色资料,复用名称与头像;地图配置位置、占地和可见状态,不新增独立角色编辑器。环境物件方案已确认:普通装饰画入底图;需要移动或改变状态的重要物件以简单标记表示,由主持移动、修改或移除。不增加玩家专用操作菜单、物理模拟或自动掩护计算。 + +## 已确认的基础视野与遮挡 + +- 基础视野由角色视距与墙、门遮挡决定;同图内队伍角色的可见范围取并集,全队共享。不同地图各自计算,不混合坐标。 +- 光源、黑暗视觉等特殊规则由主持调整视距或揭示范围处理,首版不自动模拟。 +- 普通物件标记默认不遮挡视野;需要挡住视线的物件由作者或主持明确设置遮挡。提供掩护不等于完全阻断视线,规则效果仍由主持裁定。 + +## 已确认的房间地图入口 + +- 地图面板放在世界状态下面,世界状态可折叠,地图保留稳定的可用高度并支持收起和展开大图;具体高度在实际布局中验证。两种视图使用同一份地图状态,不额外开发导航小地图。 +- 首版不增加拖拽停靠、自定义地图位置或独立地图侧栏,先在实际布局中验证空间是否足够。 +- 基础操作保留缩放、平移、回到自己角色、切换已知地图,以及移动目标与路径选择。概览地图只选择固定地点,场景地图可选择坐标与路径。 +- 展开或收起、平移缩放与地图浏览均不改变角色真实位置。具体接入需检查现有世界状态布局后设计,不新增一套世界状态模型。 diff --git "a/docs/\345\234\260\345\233\276\345\256\236\347\216\260.md" "b/docs/\345\234\260\345\233\276\345\256\236\347\216\260.md" new file mode 100644 index 0000000..91f137d --- /dev/null +++ "b/docs/\345\234\260\345\233\276\345\256\236\347\216\260.md" @@ -0,0 +1,43 @@ +# 地图实现 + +当前实现覆盖手写场景地图、墙门遮挡与探索记录、主持地图工具、行动移动意图及房间地图面板。模组工作区支持绘制折线墙、切出门洞、删除对象与拖动顶点。每张地图可选一个上级。读取模组和编辑器保存层级时检查引用与循环;玩家投影仅在直接上级也已知时携带层级关系。房间地图选择器显示已知路径,浏览不改变角色位置,各图独立计算比例和探索。概览地图仍属后续阶段。 + +跨图连接引用两图的具名起点,默认双向,同一条连接只需保存一端。主持通过 `map_read` 读取当前地图的可用方向,调用 `map_update traverse` 确认一批标记通行。执行在房间状态锁内检查路线,整组成功后写入位置与探索记录。玩家跟随自己角色的地图变化,清除之前地图的移动草稿。 + +## 模组加载与坐标 + +`packages/module/src/schema/map.ts` 定义地图结构,`node/module-maps.ts` 扫描 `maps/` 中的 JSON/TOML;地图标识是去掉目录前缀和格式扩展名的相对路径。同名两种格式报冲突,地图不是游戏文档类型。完整校验同时检查底图与文档引用;创建冒险时地图配置随基础模组编译成 JSON。 + +底图、墙、门、区域、起点与初始标记使用像素坐标,原点在左上角,y 向下。`schema/map-geometry.ts` 统一距离换算、路径测量、遮挡、视野和探索位图;支持方格与无网格。主持工具的坐标和距离换算成地图距离单位,不能直接混用像素。命名区域提供空间语义,不决定规则效果;凹形区域的默认锚点必须位于多边形内部。 + +编辑会话从当前源文件读取配置和内容摘要。保存时主进程检查摘要,按语法树定位坐标或墙门结构变更,重新解析并校验完整结果后原子替换源文件。地图编辑作用于模组工作区,房间继续使用创建冒险时冻结的副本。 + +## 权威状态与投影 + +`packages/core/src/node/sessions/map-state.ts` 保存房间地图事实,文件与恢复职责见[存档格式](游戏房间存档格式.md#地图状态)。地图位置、门状态和探索记录由平台维护;模组自定义位置与时间字段仍由主持维护,两者互不同步。 + +`map-space.ts` 按同图队伍角色的视野取并集,墙、关闭的门及显式遮挡标记影响可见范围。探索记录累计保留地形;视野外的非队伍标记不显示,也不保存最后位置残影。`map-projection.ts` 只投影已知地图;隐藏标记不显示,未揭示秘门以无标识墙段出现。静态资源不包含初始标记、区域与起点,但包含底图和墙线,不能把视觉迷雾当成原始素材的传输权限隔离。 + +## 主持裁定与行动意图 + +`agent/map-tools.ts` 提供 `map_read`、`map_move` 和 `map_update`,通过 `sessions/map-commands.ts` 执行。读取包含幕后区域和隐藏标记,主持必须按角色实际感知叙述。移动可引用玩家消息意图,或以起点、区域方位、标记旁侧和距离单位坐标指定目标;目标寻路绕开墙与关闭的门,沿意图执行时遇阻停止。`until` 限制本次距离,工具返回实际移动、剩余距离、阻挡与新见标记;规则裁定先于移动,到达叙述以成功返回为准。 + +`map_update` 处理放置、跨图修正、移除、标记属性、门及秘门揭示和地图已知状态。普通移动服从空间阻挡,直接放置用于主持合法修正;物件阻挡通行是提示,不替代主持裁定。地图不自动结算检定、移动预算、地形费用或行动耗时。只有一张地图且只有一个起点时,玩家确认角色、队友入队后自动放在该起点,地图随之对玩家可见;多人依次站在旁边。多张地图或多个起点仍由主持放置。 + +`map-intent.ts` 在主机接收行动时验证地图、本人控制权、范围与墙线,并记录当前位置为起点。每条行动最多附一张意图卡,可不附文字;聊天不能附卡。关闭的已知门允许规划经过,由主持裁定。终点未探索时记录探索方向,预估距离为 `null`。提交、接收及保存意图均不直接移动标记;主持执行后另存意图进度。 + +`map-description.ts` 把路线、区域、门、重叠、窄道与未探索区域转换为主持语义上下文。幕后路线描述不直接放进玩家意图卡;距离与风险提醒不等于规则裁定。 + +## 房间界面 + +`apps/desktop/src/renderer/src/features/maps/` 通过 `map-model.ts` 消费地图资源与房间投影。`MapPanel` 位于世界状态下方,`MapDialog` 提供大图浏览、平移缩放与本人角色的路点规划,两者共用投影和 `map-ui.ts` 的本地草稿。视角按房间和地图保存在 `map-ui.ts` 的内存状态中,以地图中心坐标和缩放值记录,关闭大图、切图及调整窗口后保留观察中心;重启应用不保留。视角工具提供本人定位、全图适配与缩放。规划预览复用 `summarizePlan` 与已知墙线,点击时仍独立校验;添加到行动后由弹窗关闭焦点回到输入框,随行动发送,不直接修改权威位置。没有关联资料的物件标记不在地图上绘制,以底图表现为准。关联了资料的角色和生物显示标记,优先用资料头像,没有头像时用封面,都没有时用名字首字。名称不常驻,指针悬停时显示。 + +`MapTerrain` 与 `map-fog.ts` 为小图、大图统一绘制三层地形:未知区域保持实色遮罩,已探索区域以低饱和、低亮度底图保留地形记忆,当前视野显示原色。历史探索格按连续行段直接绘制到地形画布,不再平滑放大低分辨率探索遮罩;探索位图的格心判定与存档精度不变,墙边仍可能存在一个探索格量级的近似误差。当前视野继续使用主机下发的多边形,不对墙边做模糊。 + +视野变化只对已确认地形做 180 毫秒淡入:旧画面先与新视野相交,失去视野的区域立即退回地形记忆,清空探索时立即遮黑。动态标记继续直接消费最新投影,不保留旧标记参与淡入。快速连续更新会取消上一段动画,从当前画面重新过渡;首次载入、切图与系统偏好减少动态效果时直接显示目标画面。本轮不插值角色位置或推算沿途视野,也不引入光照或个人迷雾。 + +`ChatComposer` 将草稿随行动提交,`MovementCard` 展示路线摘要;待裁定路线以虚线呈现,同一标记只显示最近且仍从当前位置出发的意图。实际位置以房间状态为准,本地草稿不承担存档恢复职责。 + +## 验证边界 + +共享几何、模组加载、地图状态、主持命令及行动接入的测试使用独立平台数据。改动空间状态、消息或同步链路后执行根级全量测试、类型检查和桌面构建。CLI 校验只能证明配置与资源符合约束;真实模型需通过 MCP 临时局验证初始化、工具调用、遮挡、分段移动及叙述保密。当前 MCP 的步骤快照只保存文档,地图变更还需对照临时局 `map-state.json` 与真实模型工具记录;不能把文档快照当作地图状态快照。缩放、点选、明暗主题和底图对齐仍需实际界面验收。 diff --git "a/docs/\345\234\260\345\233\276\350\247\204\345\210\231\351\252\214\346\224\266\350\215\211\346\241\210.md" "b/docs/\345\234\260\345\233\276\350\247\204\345\210\231\351\252\214\346\224\266\350\215\211\346\241\210.md" new file mode 100644 index 0000000..95b4688 --- /dev/null +++ "b/docs/\345\234\260\345\233\276\350\247\204\345\210\231\351\252\214\346\224\266\350\215\211\346\241\210.md" @@ -0,0 +1,145 @@ +# CoC 与 D&D 地图验收草案 + +状态:内部需求细化,尚待整体确认。上层范围见[地图功能设计讨论](地图功能设计讨论.md)。以下均为拟议验收场景,不表示功能已经实现,也不是规则教程。文中保留部分早期讨论过程;地图层级以“已确认的层级收敛与地图类型细化”为准,角色与物件以“环境物件:规则核对与已确认方案”为准,早期对应的待确认标记已被后续结论替代。 + +## 规则基线与职责 + +已确认用 CoC 第七版与 D&D 2024 基础规则作为首版验收基线。不能将 D&D 的固定战斗时长与移动预算套给 CoC,也不能将玩家一起提交行动视为角色同时执行战斗行动。 + +程序负责几何测量、预览与已裁定状态的展示,主持依据模组规则决定耗时、行动顺序、合法性、检定与中断。确认的结果决定位置与揭雾。移动预算是规则数据,不是所有模组必填的统一属性。 + +## CoC:调查与基础战斗 + +| 编号 | 具体操作或情境 | 拟议验收结果 | +| ---- | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| C1 | 从城镇地图查看宅邸,再提交进入宅邸 | 查看不移动角色;主持确认后进入宅邸指定入口,未探索房间不暴露;返回父地图不等于离开宅邸 | +| C2 | 调查员站在走廊,提交前往关闭的门并尝试开门 | 可停在门前;锁住或事件中断时不穿门,不揭示门后;门获准打开后按视野与墙体揭示 | +| C3 | 点击书桌提交搜索,另一名调查员守门 | 可提交包含目标地点或物件的文字行动;主持结算搜索、守望和共同时间,不把搜索视为移动,不按点击次数计时 | +| C4 | 主持判定搜索需十分钟,第五分钟有人敲门 | 只推进到事件发生时,保留搜索未完成的事实;此处分钟数是测试剧情设定,不是 CoC 固定搜索规则 | +| C5 | 两名调查员分在楼上与楼下 | 独立位置与嵌套地图保持正确,全队共享地图信息;角色能否利用队友信息仍由主持判断,不把共享地图等同于角色感知 | +| C6 | 调查转入战斗,参与者按模组给出的敏捷顺序行动 | 地图展示当前行动者与顺序,可接受主持修正;不默认套用 D&D 的六秒一轮或固定格数移动额度 | +| C7 | 调查员选择目标射击,或声明退到桌后 | 能测量距离、引用目标与掩体位置;射程、掩护效果与动作结果交主持,几何可见不等于必然能命中 | + +首版不自动执行 CoC 追逐流程;若发生逃跑,可交主持叙事裁定,但不得宣称已有追逐规则自动化。 + +## D&D:探索与战术移动 + +| 编号 | 具体操作或情境 | 拟议验收结果 | +| ---- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| D1 | 配置每格五英尺,角色速度三十英尺,在无遮挡普通地面规划六格 | 显示路径距离三十英尺及预算;提交前不移动,主持确认后更新位置和本回合剩余额度 | +| D2 | 同一角色先移动十英尺,攻击后再申请移动 | 保留本回合已用移动量;不得因第二次提交恢复完整预算;是否允许后续移动由主持裁定 | +| D3 | 路径含十英尺普通地形与十英尺困难地形 | 主持结算后区分几何距离二十英尺与移动消耗三十英尺;地形由作者标注,地图只展示已知信息,不自动预览地形费用 | +| D4 | 本回合移动需求超出预算,玩家声明疾走 | 提示需要额外行动支持,主持确认后更新预算与行动消耗;不能默认为玩家自动消耗动作 | +| D5 | 角色斜走或试图斜穿墙角 | 按所选计距方式显示距离,不能斜穿阻挡墙角;替代斜向计距是模组选项,不混称默认规则 | +| D6 | 角色规划路径离开敌人附近,途中可能触发反应 | 主持可在途中停止,处理反应后继续或结束;不直接落到终点再补述结果,不从路径提示泄露隐藏敌人 | +| D7 | 大型生物占据多格,经过狭窄通道 | 显示占地范围;主持能据此处理挤压、阻挡与通行例外,不仅按标记中心判断能否通过 | +| D8 | 切入战斗后,多个玩家同时提交意图 | 按主持确定的先攻顺序执行,后执行者依据先前结果重评;整轮时间不按参与人数重复累加 | +| D9 | 玩家测量远程目标,或描述施法目标区域 | 提供距离和目标引用;完整法术模板、范围命中与特殊感官自动化不作为首版通过条件,效果仍交主持裁定 | + +已确认首版纳入困难地形标注、多格角色占地、同回合分段移动与途中暂停裁定;编辑器及交互需覆盖这些能力。 + +## 共同的可靠性验收 + +- AI 等待、失败或重试时,预览不得提交为真实位置;恢复后的移动不能重复扣时间或重复推进事件。 +- 移动途中实际看见的范围可以成为探索记录;不能仅用终点视野遗漏沿途,也不能把尚未实际抵达的后半段揭开。 +- 已探索但当前不可见的区域保留地形,不持续显示敌人实时位置;隐藏位置不能通过客户端数据或测距结果泄露。 +- 多人客户端与重新载入后的角色位置、门状态、当前视野和探索记录一致。 + +## 本轮确认与下一轮待决 + +已确认规则基线、新增地图能力,以及全队共享视野的取舍。不同角色实际掌握的信息由主持裁定,首版不精确模拟各角色独立视觉与秘密情报。上述验收表仍是细化草案,未讨论的具体交互不能推定为已确认。 + +已确认的移动交互: + +1. 移动结果按实际路径分段表达,每段包含实际位置变化及相关时间/资源变化;遇到需要玩家选择或反应时暂停,不能把尚未决定的后续路径当成已执行。 +2. 已知区域允许规划路径与途经点;未知区域只提交探索方向或入口,不提供穿过未知区域的自动寻路与精确耗时预览。 +3. 战斗中同一角色可以分次提交移动与动作,主持确认后更新剩余预算;需要玩家反应时保留当前行动上下文,不等到整轮所有动作都执行完才询问。 + +## 已确认的交互简化 + +地图以查看空间与表达移动意图为主,不提供开门、关门、解锁等专用按钮。相关行动通过正常行动描述交给主持,主持更新门状态,地图据此表现遮挡与通行。此决定不取消门的空间数据,也不取消已确认的作者编辑器。 + +## 已确认的空间编辑与裁定边界 + +- 作者可绘制困难地形区域并添加说明。地图展示已知区域,移动消耗由主持结算,首版不自动预览地形费用;此项替代此前地形消耗预览的建议。 +- 作者配置角色标记占地大小,地图据此显示。狭窄通道能否通过、是否挤压由主持判断,不增加自动通行提示。 +- 门由主持处理与更新;地图不提供开关门或解锁按钮。具体门状态分类尚未确认。 + +## 已确认的跨图连接约束 + +作者配置连接两端入口,默认双向,允许设为单向;主持决定是否通过。一次地图移动意图最多通过一个连接,到达后重新选路。尚未确认的移动不改变角色所在地图或揭示目标地图;无需玩家专用传送按钮。 + +拟议验收:配置地下室到下水道的连接,玩家提交穿过通道;受阻时停在原图,获准后到达目标入口,原路线终止。单向连接反向不可作为普通返回路线,分队仅移动实际通过的角色。已确认自己控制的角色跨图时自动跟随,队友跨图不强制切屏;上层仅展示角色所在地点,局部坐标变化不引起上层标记漂移。允许浏览队友所在地图与全队已探索地图,浏览不移动角色。 + +## 待确认:地图连接与层级 + +1. 父地图地点可以关联子地图,子地图允许多个具名入口;跨地图行动由主持选择实际抵达入口,不默认传送至中心。 +2. 已确认:全局地图支持整张公开,或按作者划定区域由主持逐步揭示;场景地图使用角色视野揭雾。父地图揭示不自动揭示内部。 +3. 初次制作地图时,作者设置父子关系、入口和比例尺;游戏中由主持更新角色所在地图与位置,浏览地图不改变角色位置。 + +## 核对来源 + +- [Chaosium CoC 战斗规则](https://callofcthulhuwiki.chaosium.com/rules/combat.html):敏捷顺序、主持掌握战斗轮节奏等;此来源为简化规则,不足以覆盖所有第七版可选规则。 +- [Chaosium 第七版快速入门](https://www.chaosium.com/cthulhu-quickstart/):版本与基础规则入口。 +- [D&D 2024 Playing the Game](https://www.dndbeyond.com/sources/dnd/br-2024/playing-the-game):移动、困难地形、战斗顺序及方格移动依据。 + +规则来源用于核对玩法差异,表中界面行为、可靠性要求与测试情境均是本项目的设计建议。 + +## 地图层级的参考与待决建议 + +核对日期:2026-11-02。D&D 与 CoC 的不同尺度地图是冒险资料与使用方式,不应据此推导出强制父子地图数据规则。Chaosium 的 Arkham 官方资源同时提供州、城郊、城市地图及玩家/主持版本;D&D 官方资源同样提供区域与城市地图。 + +FVTT 以独立 Scene 为核心,每张场景有独立空间配置,通过目录组织及导航查看/激活;场景区域还支持跨场景传送。目录层级不等于角色必须依次穿越的空间层级。 + +据此建议:地图保持独立,以可选层级表达浏览归属,以入口/出口关联表达实际空间连接。玩家查看另一张地图与主持确认角色跨图移动保持分离。“每张子地图只有一个父级地点”仍是待决建议,不能将其当作 D&D、CoC 或 FVTT 的既定要求。 + +来源: + +- [FVTT Scenes](https://foundryvtt.com/article/scenes/) +- [FVTT Scene Regions](https://foundryvtt.com/article/scene-regions/) +- [Chaosium Arkham 地图资源](https://www.chaosium.com/blogdownload-free-call-of-cthulhu-arkham-keeper-resources-including-maps-and-the-complete-arkham-advertiser-newspaper/) +- [D&D 2024 DMG 区域与城市地图](https://dndstore.wizards.com/eu/en/product/1001666/2024-dungeon-master-s-guide-digital-plus-physical-bundle) + +## 当前讨论焦点:地图归属 + +用户要求继续讨论每张地图是否有唯一上级。暂不确立单父级树结构。需区分浏览返回路径、地图在世界中的位置归属、实际入口出口连接;以跨多个建筑的下水道和移动中的船舱检验模型,避免强行给独立地图指定错误的固定地理归属。 + +## 收敛建议 + +用户提出避免过度设计。下水道多个入口已由跨图连接覆盖,不构成多上级模型的必要理由。首版建议仅保留地图可选单一上级与已确认的跨图连接;不为不同尺度重复引用、移动船舱等尚未请求的情境增加模型。此前这些例子只作讨论,不作为验收要求。此收敛建议待确认。 + +## 已确认的层级收敛与地图类型细化 + +用户已同意可选单一上级用于嵌套浏览,跨图连接独立表达通路。多上级引用与独立归属模型不进入首版。用户进一步提出:概览地图只允许前往固定地图点,不能自由移动坐标;场景地图允许坐标目标与路径。 + +拟议验收:城镇概览上存在酒馆与教堂,玩家只能选择这些地点提交移动意图,不能把角色拖到空白处作为目的地;场景地图允许指定具体空间位置。选择目的地仍不直接生效,主持统一裁定耗时与事件。已确认概览地点不强制连线,主持裁定可达性、路线与耗时;已确认抵达不自动进入场景,是否进入及实际入口由主持裁定。 + +已确认:概览地点关联场景时,抵达后是否进入及实际入口由主持裁定;只到门口与进入室内可以是不同结果。没有场景地图的地点可直接进行文字行动,不要求创建空场景。 + +已确认:概览旅行途中被事件打断时,显示“前往某地途中”,不虚构概览坐标或提前标记抵达;事件有场景图则由主持切入,没有则用文字继续。该决定仅定义位置表现,不引入旅行进度条或自动计时系统。 + +已确认:主持可直接修正角色所在地图与位置、门状态和揭示范围,用于传送、剧情变化或纠正裁定;地图几何不能成为阻止这些合法修正的硬规则。已探索但当前不可见的区域保留地形,不显示 NPC/敌人及其移动,也不显示最后位置残影。具体工具契约需在调查现有文档更新与权限机制后设计。 + +下一轮待确认:地图保存恢复需保留角色位置、门状态和探索记录;首版以地图关联现有角色资料来放置角色及 NPC 标记,不新增独立角色编辑系统。技术契约与权限设计须结合仓库现状调查,不能仅凭访谈默认实现。 + +## 环境物件:规则核对与已确认方案 + +已确认角色与 NPC 标记关联现有资料,复用名称与头像,不新增角色编辑器。 + +规则核对:D&D 2024 包含物件交互、物件损坏与掩护;CoC 基础战斗包含寻找掩护的反应。因此不提供玩家专用物件按钮不妨碍主持裁定,但把全部物件永久烘焙到底图会限制搬动或破坏后的准确展示,不能声称完整覆盖动态环境。 + +已确认:装饰画入底图;对位置或状态变化有意义的物件,可用简单标记与已有资料或文字说明表达,由主持调整位置、状态或移除;不增加专用玩家操作菜单、自动物理或自动掩护计算。墙体视野遮挡与规则上的掩护不能直接等同。 + +来源:[D&D 2024 游戏规则](https://www.dndbeyond.com/sources/dnd/br-2024/playing-the-game)、[D&D 规则术语](https://www.dndbeyond.com/sources/dnd/br-2024/rules-glossary)、[CoC 战斗规则](https://callofcthulhuwiki.chaosium.com/rules/combat.html)。 + +## 已确认的视野验收边界 + +同一场景按队伍角色视距与墙、门计算各自视野并取并集;跨图不混合坐标。首版不自动模拟复杂光源或黑暗视觉,主持可调整视距或揭示范围。物件标记默认不遮挡视野,作者或主持可明确设置遮挡;掩护数值与完全阻断视线分别裁定。 + +拟议验收:两名角色分别观察走廊两端时共享可见范围;关门后不能看见门后的实时敌人,历史地形仍保留。普通箱子标记不会无意产生黑墙,明确设置的遮挡才影响视野。 + +## 已确认的房间界面验收 + +地图面板位于世界状态下面,世界状态可折叠,地图保留稳定的可用高度,可以收起或展开大图;两种视图共用地图状态。支持缩放、平移、回到自己角色、切换已知地图和已确认的移动意图操作;概览图不能选择任意坐标。视图变化不触发角色移动,不另建导航小地图。 + +已确认布局收敛:首版不增加拖拽停靠、自定义位置或独立地图侧栏;具体尺寸以实际布局验证为准。 diff --git "a/docs/\346\210\277\351\227\264\345\242\236\351\207\217\345\220\214\346\255\245\345\256\236\347\216\260.md" "b/docs/\346\210\277\351\227\264\345\242\236\351\207\217\345\220\214\346\255\245\345\256\236\347\216\260.md" index fc77499..56ae6a8 100644 --- "a/docs/\346\210\277\351\227\264\345\242\236\351\207\217\345\220\214\346\255\245\345\256\236\347\216\260.md" +++ "b/docs/\346\210\277\351\227\264\345\242\236\351\207\217\345\220\214\346\255\245\345\256\236\347\216\260.md" @@ -2,6 +2,8 @@ 同步结构标识是 `game-document-overlay-v1`,协议版本为 `1`。文档版本用数字 `revision` 表示,客户端会检查它是否为正的安全整数。开发版本的兼容策略见[存档格式](游戏房间存档格式.md)。 +地图以房间地图区段同步全队已知地图、探索位图、当前共享视野、可见标记及意图执行进度;静态地图资源与运行投影分离。未揭示秘门投影为无标识墙段,幕后区域和初始标记不进入静态资源。具体边界见[地图实现](地图实现.md#权威状态与投影)。 + ## 数据与计算边界 文档是游戏状态的来源。各客户端从本地 `session/module/` 读取同一份冻结模组,主机同步本局原始文档相对模组的累计覆盖。JSON、TOML 和 Markdown 归一化为结构化文档;不传目录、原文件文本或图片字节。 diff --git "a/docs/\346\270\270\346\210\217\346\210\277\351\227\264\345\255\230\346\241\243\346\240\274\345\274\217.md" "b/docs/\346\270\270\346\210\217\346\210\277\351\227\264\345\255\230\346\241\243\346\240\274\345\274\217.md" index f82b7a7..1f1c0f2 100644 --- "a/docs/\346\270\270\346\210\217\346\210\277\351\227\264\345\255\230\346\241\243\346\240\274\345\274\217.md" +++ "b/docs/\346\270\270\346\210\217\346\210\277\351\227\264\345\255\230\346\241\243\346\240\274\345\274\217.md" @@ -9,6 +9,7 @@ | 文件或目录 | 职责 | | ------------------------------------ | ------------------------------------------------ | | `adventure.json` | 房间资料、玩家笔记、开局进度与队伍状态 | +| `map-state.json` | 地图、门、标记、探索记录与意图执行进度 | | `settings.json` | 创建时复制的游戏配置,及冒险内独立调整 | | `module/` | 编译的完整基础模组,游戏工具只读,可手动同步替换 | | `module-source.json` | 本机模组来源目录,可首次绑定,不进入玩家同步 | @@ -48,6 +49,12 @@ 两份文件独立读写:设置缺失或损坏只阻止依赖设置的操作,不妨碍读取冒险列表、资料和笔记;状态损坏也不阻止修正设置。已有文件损坏时保留原文,并拒绝保存补丁,不自动重置。创建房间在 staging 目录分别初始化两份文件后整体发布。设置空值规则见[配置存储](模组加载与文档实现.md#应用配置与房间设置)。 +## 地图状态 + +房间根级 `map-state.json` 保存地图可浏览状态、探索位图、门的开关与揭示状态、标记位置及属性、按玩家消息标识记录的移动意图进度。`sessions/map-state.ts` 在 staging 中从基础地图初始化,读取要求文件存在且为普通文件;写入使用结构化文件替换并推进房间状态版本。文件与 SQLite、冒险文档之间不构成跨文件事务。 + +基础 `module/maps/` 只保存作者配置,运行变化不写回基础副本或文档覆盖。同步模组时保留仍存在地图与门的状态,新地图按初始配置加入;探索位图不适配新尺寸时清空,旧标记坐标收敛到底图边界。仍有地图标记引用的文档不能删除。空间投影与裁定边界见[地图实现](地图实现.md)。 + ## SQLite 连接与迁移 `SessionDatabase` 使用内置 `bun:sqlite` 持有同步连接,Kysely 提供类型化查询构建与迁移管理。业务查询通过编译后的 SQL 和绑定参数同步执行,保持聊天事务内原有的提交顺序;事务成功后才发布通知。JSON 字段查询使用固定路径,以匹配表达式索引。 diff --git "a/docs/\346\270\270\346\210\217\347\212\266\346\200\201\345\256\236\347\216\260.md" "b/docs/\346\270\270\346\210\217\347\212\266\346\200\201\345\256\236\347\216\260.md" index 17ba74b..632e4b8 100644 --- "a/docs/\346\270\270\346\210\217\347\212\266\346\200\201\345\256\236\347\216\260.md" +++ "b/docs/\346\270\270\346\210\217\347\212\266\346\200\201\345\256\236\347\216\260.md" @@ -2,6 +2,8 @@ 状态建模和展示配置维护在官网的状态与布局文档。本文说明状态的权威来源、通用提交与展示、主持上下文,以及房间生命周期的约束。 +平台另行维护地图空间位置、门状态与探索记录,见[地图实现](地图实现.md);它们与模组自定义位置、时间字段互不同步。 + ## 模组状态与平台职责 游戏事实来自房间 `module/` 与 `game/` 的合并视图。`module/` 是基础模组,`game/` 保存本局字段差异;聊天记录和开局背景不能替代当前文档值。 diff --git "a/docs/\346\270\270\346\210\217\350\201\212\345\244\251\344\270\216AI\345\256\236\347\216\260.md" "b/docs/\346\270\270\346\210\217\350\201\212\345\244\251\344\270\216AI\345\256\236\347\216\260.md" index d526e32..8813f97 100644 --- "a/docs/\346\270\270\346\210\217\350\201\212\345\244\251\344\270\216AI\345\256\236\347\216\260.md" +++ "b/docs/\346\270\270\346\210\217\350\201\212\345\244\251\344\270\216AI\345\256\236\347\216\260.md" @@ -2,6 +2,8 @@ 模型连接、行动提交、队友、掷骰和笔记的玩家说明统一维护在官网文档。本文维护业务协议、生成调度、恢复、凭据及进程通信边界。 +行动消息可携带移动意图,主机校验控制权并记录起点,主持接收语义路线后通过地图工具结算;提交意图不改变实际位置。相关工具、坐标和投影边界见[地图实现](地图实现.md)。 + ## 代码职责 ### 服务入口与模块依赖 diff --git a/packages/core/src/node/agent/game-tools.ts b/packages/core/src/node/agent/game-tools.ts index b7d4e85..db68eac 100644 --- a/packages/core/src/node/agent/game-tools.ts +++ b/packages/core/src/node/agent/game-tools.ts @@ -8,6 +8,7 @@ import { z } from "zod"; import { endAdventure } from "../sessions/adventure-status"; import { storedTypes } from "../sessions/character-db"; +import { frozenModule } from "../sessions/frozen-module"; import { gameDocumentPatchSchema } from "../sessions/game-document-patch"; import { gameReadableFiles } from "../sessions/game-file-access"; import { readOverlayDocument } from "../sessions/game-overlay"; @@ -19,6 +20,7 @@ import { writeGameDocument, } from "../sessions/game-state"; import { openSessionDatabase } from "../sessions/session-store"; +import { createMapTools } from "./map-tools"; import { createModuleTools } from "./tools"; const documentPath = z.string().min(1).max(1000); @@ -216,5 +218,7 @@ export async function createGameTools( return output({ ended: true }); }, }); + if (await withDatabase(room, async (db) => frozenModule(db).maps.length > 0)) + tools.push(...createMapTools((fn) => withDatabase(room, fn), signal)); return tools; } diff --git a/packages/core/src/node/agent/map-tools.ts b/packages/core/src/node/agent/map-tools.ts new file mode 100644 index 0000000..de8c6f8 --- /dev/null +++ b/packages/core/src/node/agent/map-tools.ts @@ -0,0 +1,121 @@ +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +import { moveToken, readMap, updateMap } from "../sessions/map-commands"; +import { mapSides } from "../sessions/map-space"; +import type { SessionDatabase } from "../storage/session-database"; + +type WithDatabase = (fn: (db: SessionDatabase) => Promise) => Promise; + +function output(value: unknown) { + return { content: [{ type: "text" as const, text: JSON.stringify(value) }], details: {} }; +} + +const side = Type.Union( + mapSides.map((item) => Type.Literal(item)), + { description: "区域或标记的方位,默认 center(区域)或自动选择空位(标记)" }, +); +const anchor = Type.Union( + [ + Type.Object({ start: Type.String({ description: "起点 id 或名称" }) }), + Type.Object({ + region: Type.String({ description: "区域 id 或名称" }), + side: Type.Optional(side), + }), + Type.Object({ near: Type.String({ description: "相邻的标记 id" }), side: Type.Optional(side) }), + Type.Object({ x: Type.Number(), y: Type.Number() }), + ], + { description: "位置:起点、区域方位、标记旁边,或距离单位坐标(原点在左上角,y 向下)" }, +); +const flags = { + label: Type.Optional(Type.String({ description: "显示名称" })), + size: Type.Optional(Type.Number({ description: "占地边长:方格地图按格,无网格按距离单位" })), + hidden: Type.Optional(Type.Boolean({ description: "对玩家隐藏,即使在视野内也不显示" })), + blocksVision: Type.Optional(Type.Boolean({ description: "遮挡视线" })), + blocksMovement: Type.Optional(Type.Boolean({ description: "阻挡通行的提示,平台不强制" })), + vision: Type.Optional( + Type.Union([Type.Number(), Type.Null()], { + description: "覆盖地图默认视距(距离单位),null 表示不限距离", + }), + ), +}; + +/** 主持维护平台地图:位置、门与探索记录。与模组位置字段相互独立。 */ +export function createMapTools( + withDatabase: WithDatabase, + signal: AbortSignal, +): ToolDefinition[] { + return [ + { + name: "map_read", + label: "读取地图", + executionMode: "sequential", + description: + "读取平台地图。省略 map 列出全部地图、是否对玩家可见及队伍所在;指定 map 返回区域(含秘密区域、备注与已探索比例)、门(位置、两侧区域、开关与秘门揭示状态)、起点、当前可通行方向的跨图连接 exits(from、map、to)和全部标记(区域、是否在队伍视野内、隐藏与遮挡)。坐标与距离使用地图的距离单位,原点在左上角,y 向下。结果含玩家不可见的信息,叙述时只描述角色能感知的部分。", + parameters: Type.Object({ + map: Type.Optional(Type.String({ description: "地图 id 或名称" })), + }), + execute: async (_id, params: { map?: string }) => { + signal.throwIfAborted(); + return output(await withDatabase(async (db) => readMap(db, params.map))); + }, + }, + { + name: "map_move", + label: "移动地图标记", + executionMode: "sequential", + description: + "在同一张地图上移动标记。intent 填携带移动意图的玩家消息 id,沿玩家计划路线执行;to 指定目的地,由平台绕开墙与关闭的门寻路。两者只能提供一个。until 限制本次移动的距离,用于受阻、被打断或分段移动。路线遇到墙或关闭的门时停在阻挡前并返回 stoppedBy;需要通过时先用 map_update 开门。返回新位置、所在区域、实际移动与剩余距离、新进入队伍视野的标记。先按规则裁定行动结果再移动,成功后才叙述到达;沿已配对出入口换图使用 map_update traverse;主持修正位置使用 place。", + parameters: Type.Object({ + token: Type.Optional(Type.String({ description: "标记 id;使用 intent 时可省略" })), + intent: Type.Optional(Type.String({ description: "携带移动意图的消息 id" })), + to: Type.Optional(anchor), + until: Type.Optional(Type.Number({ description: "本次最多移动的距离" })), + }), + execute: async (_id, params) => { + signal.throwIfAborted(); + return output(await withDatabase((db) => moveToken(db, params, signal))); + }, + }, + { + name: "map_update", + label: "更新地图", + executionMode: "sequential", + description: + "维护地图状态。traverse 用于主持确认一批标记通过一个出入口。先 map_read 查看 exits,再传当前 map、出发起点 from、目标地图 target、抵达起点 to 和实际通过的 tokens。平台检查到出发口的路线,任一标记无法通过则整组留在原图。place 放置或瞬移标记(可跨地图):document 为角色或其他游戏文档,同一文档未指定 token 时移动已有标记,需要多个副本时指定新的 token;纯物件用 label。队伍角色放入地图后玩家即可看到该地图。remove 移除标记;set 修改标记属性;door 开关门,打开秘门同时揭示;reveal/conceal 揭示或重新隐藏秘门;known 设置地图是否对玩家可见。玩家看到的地图只包含队伍视野、已探索区域和视野内未隐藏的标记。地图与模组位置字段互不同步,需要时另行更新文档。", + parameters: Type.Union([ + Type.Object({ + action: Type.Literal("place"), + map: Type.String(), + at: anchor, + token: Type.Optional(Type.String()), + document: Type.Optional(Type.String({ description: "游戏文档路径" })), + ...flags, + }), + Type.Object({ + action: Type.Literal("traverse"), + map: Type.String(), + from: Type.String(), + target: Type.String(), + to: Type.String(), + tokens: Type.Array(Type.String(), { minItems: 1, maxItems: 100 }), + }), + Type.Object({ action: Type.Literal("remove"), token: Type.String() }), + Type.Object({ action: Type.Literal("set"), token: Type.String(), ...flags }), + Type.Object({ + action: Type.Literal("door"), + map: Type.String(), + door: Type.String(), + open: Type.Boolean(), + }), + Type.Object({ action: Type.Literal("reveal"), map: Type.String(), door: Type.String() }), + Type.Object({ action: Type.Literal("conceal"), map: Type.String(), door: Type.String() }), + Type.Object({ action: Type.Literal("known"), map: Type.String(), known: Type.Boolean() }), + ]), + execute: async (_id, params) => { + signal.throwIfAborted(); + return output(await withDatabase((db) => updateMap(db, params, signal))); + }, + }, + ]; +} diff --git a/packages/core/src/node/game/chat/companions.ts b/packages/core/src/node/game/chat/companions.ts index 6288df5..c1065b7 100644 --- a/packages/core/src/node/game/chat/companions.ts +++ b/packages/core/src/node/game/chat/companions.ts @@ -30,6 +30,7 @@ import { saveLaunchProgress, saveLaunchRoom, } from "../../sessions/launch-db"; +import { seatPartyAtStart } from "../../sessions/map-commands"; import { readRoomSettings } from "../../sessions/room-settings"; import type { CompanionSeat } from "../../sessions/room-storage"; import { roomDirectoryForDatabase } from "../../sessions/session-paths"; @@ -234,6 +235,7 @@ export class ChatCompanions { }); markStateChanged(state.db); }); + if (companion && !before) await seatPartyAtStart(state.db); }); } diff --git a/packages/core/src/node/game/chat/submissions.ts b/packages/core/src/node/game/chat/submissions.ts index 4d8f287..7ee29d4 100644 --- a/packages/core/src/node/game/chat/submissions.ts +++ b/packages/core/src/node/game/chat/submissions.ts @@ -3,8 +3,11 @@ import { createHash, randomUUID } from "node:crypto"; import { ORPCError } from "@orpc/server"; import type { ChatMessage, Player, SendInput } from "../../../shared/game"; +import type { MovementIntent } from "../../../shared/map"; import { parseMentionRefs, resolveMentionRefs } from "../../../shared/mentions"; import { assertPlayerReady, readCharacters } from "../../sessions/character-db"; +import { movementPrompt } from "../../sessions/map-description"; +import { prepareMovement } from "../../sessions/map-intent"; import { assertSessionActive } from "../../sessions/session-store"; import type { ChatInputBatches } from "./input-batches"; import type { ChatMentionQueue } from "./mention-queue"; @@ -171,7 +174,7 @@ export class ChatSubmissions { playerId: player.id, requestId: input.clientMessageId, fingerprint: createHash("sha256") - .update(JSON.stringify([input.text, input.chatOnly])) + .update(JSON.stringify([input.text, input.chatOnly, input.movement ?? null])) .digest("hex"), }; return this.request(state, request, () => this.sendOnce(state, input, player, request)); @@ -201,10 +204,14 @@ export class ChatSubmissions { const targets = await this.context.mentions.targets(state, player); this.assertAvailable(state); const text = input.text.trim(); - if (!text || text.length > 4000) + if ((!text && !input.movement) || text.length > 4000) throw new ORPCError("BAD_REQUEST", { message: "消息应为 1 至 4000 个字符" }); const mentioned = resolveMentionRefs(parseMentionRefs(text), targets); const only = input.chatOnly || mentioned.length > 0; + if (input.movement && only) + throw new ORPCError("BAD_REQUEST", { + message: "移动意图只能随行动消息提交,不能用于聊天或点名", + }); // 接收时由稳定身份计算用途;失效引用仍按原手动模式处理。 if (!only) { if (!this.context.activity.running(state)) this.context.inputs.assertResolved(state); @@ -268,6 +275,16 @@ export class ChatSubmissions { } const saved = this.context.store.submissionResult(state, request); if (saved) return saved; + let movement: MovementIntent | undefined; + if (input.movement) + try { + movement = prepareMovement(state.db, player.id, input.movement); + } catch (error) { + throw new ORPCError("BAD_REQUEST", { + message: error instanceof Error ? error.message : "移动意图无效", + }); + } + const messageId = randomUUID(); const manual = this.context.queue.mode(state) === "manual"; const willRun = !only && !manual; if (!only && this.context.activity.running(state)) @@ -291,7 +308,12 @@ export class ChatSubmissions { const turns = hostRun ? [ ...this.context.queue.pendingTurns(state, pending), - { text, playerId: player.id, characterName: character?.name }, + { + text, + playerId: player.id, + characterName: character?.name, + ...(movement ? { movement: movementPrompt(state.db, messageId, movement) } : {}), + }, ] : []; const prompt = hostRun ? this.context.queue.hostPrompt(state, turns, pending) : ""; @@ -306,7 +328,7 @@ export class ChatSubmissions { if (!only) this.context.queue.replacePending(state, player.id); if (hostRun) this.context.queue.consumePending(state, pending); const message = this.context.store.save(state, { - id: randomUUID(), + id: messageId, sequence: 0, revision: 0, roomId: input.roomId, @@ -317,6 +339,7 @@ export class ChatSubmissions { text, ...(mentioned.length ? { mentions: mentioned } : {}), chatOnly: only, + ...(movement ? { movement } : {}), ...(!only && (manual || companions.length) ? { pendingAgent: true } : {}), status: "complete", }); diff --git a/packages/core/src/node/game/chat/sync.ts b/packages/core/src/node/game/chat/sync.ts index 9f15ae4..0018476 100644 --- a/packages/core/src/node/game/chat/sync.ts +++ b/packages/core/src/node/game/chat/sync.ts @@ -6,8 +6,12 @@ import type { ChatMessage, Player } from "../../../shared/game"; import type { ChatActivitySnapshot, RoomBaseline, RoomReplica } from "../../../shared/room-state"; import type { RoomProjection } from "../../../shared/room-state"; import { readAdventureState } from "../../sessions/adventure-state"; +import { frozenModule } from "../../sessions/frozen-module"; import { stateRevision } from "../../sessions/game-state"; import { launchState } from "../../sessions/launch-store"; +import { projectMapSection } from "../../sessions/map-projection"; +import { partyIndex } from "../../sessions/map-space"; +import { readMapState } from "../../sessions/map-state"; import { roomGeneration } from "../../sessions/room-changes"; import { readRoomFileSync } from "../../sessions/room-file"; import { gameDirectoryForDatabase, roomDirectoryForDatabase } from "../../sessions/session-paths"; @@ -41,6 +45,7 @@ export class ChatSync { launch: RoomReplica["sections"]["launch"]; } >; + map?: { revision: number; section: RoomReplica["sections"]["map"] }; } >(); private projection(state: RoomState) { @@ -123,6 +128,16 @@ export class ChatSync { if (state.closed) throw new ORPCError("UNAVAILABLE"); if (generation !== roomGeneration(directory)) return; const selection = readAdventureState(state.db); + let map = this.projection(state).map; + if (map?.revision !== revision) + this.projection(state).map = map = { + revision, + section: projectMapSection( + frozenModule(state.db).maps, + readMapState(state.db), + partyIndex(state.db), + ), + }; return { entities, documentRevision, @@ -149,6 +164,7 @@ export class ChatSync { }), ) .digest("hex"), + map: map.section, }, }; }); diff --git a/packages/core/src/node/game/chat/turn-queue.ts b/packages/core/src/node/game/chat/turn-queue.ts index 3c6fbf4..11b88d8 100644 --- a/packages/core/src/node/game/chat/turn-queue.ts +++ b/packages/core/src/node/game/chat/turn-queue.ts @@ -4,6 +4,7 @@ import { chatText } from "../../../shared/agent-message"; import { messageSchema } from "../../../shared/game"; import type { ChatMessage, SubmissionMode, SubmissionModeSnapshot } from "../../../shared/game"; import { readCharacters } from "../../sessions/character-db"; +import { movementPrompt } from "../../sessions/map-description"; import { readRoomSettings, updateRoomSettings } from "../../sessions/room-settings"; import { roomDirectoryForDatabase } from "../../sessions/session-paths"; import { chatField } from "../../storage/session-database"; @@ -60,6 +61,9 @@ export class ChatTurnQueue { playerId: message.senderId, characterName: names.get(message.senderId), text: chatText(message), + ...(message.movement + ? { movement: movementPrompt(state.db, message.id, message.movement) } + : {}), }, ]; if (message.kind === "assistant" && message.companionId && message.pendingAction) diff --git a/packages/core/src/node/game/map-chat.test.ts b/packages/core/src/node/game/map-chat.test.ts new file mode 100644 index 0000000..6fdf068 --- /dev/null +++ b/packages/core/src/node/game/map-chat.test.ts @@ -0,0 +1,98 @@ +import { test, onTestFinished } from "bun:test"; +import { strict as assert } from "node:assert"; +import { randomUUID } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { waitFor } from "@jointarp/module/testing/async"; +import { writeTestFile as writeFile } from "@jointarp/module/testing/files"; +import { createTestModule } from "@jointarp/module/testing/test-module"; + +import { updateMap } from "../sessions/map-commands"; +import { updateAdventure } from "../sessions/room-storage"; +import { createSession, openSessionDatabase } from "../sessions/session-store"; +import { ChatService } from "./chat-service"; + +test("行动消息可只携带移动意图卡,主持输入附带幕后路线说明,聊天消息不能携带意图", async () => { + const data = await createTestModule(); + const path = join(data.modulePath, "module.json"); + const { + gameStarts: _starts, + preludeFlow: _prelude, + ...module + } = JSON.parse(await readFile(path, "utf8")); + await writeFile(path, JSON.stringify(module)); + const room = await createSession(data.sessions, data.modulePath, "地图行动"); + const player = { id: randomUUID(), nickname: "玩家" }; + updateAdventure(join(data.sessions, room.id), (adventure) => { + adventure.party.characters.find( + (character) => character.sourcePath === "角色/旅人.json", + )!.playerId = player.id; + return adventure; + }); + const db = await openSessionDatabase(data.sessions, room.id); + await updateMap(db, { + action: "place", + map: "测试场景", + document: "角色/旅人", + at: { start: "入口" }, + }); + const prompts: string[] = []; + const chat = new ChatService( + data.sessions, + { run: async (args) => void prompts.push(args.text) }, + async () => ({ config: { provider: "test", model: "test" } }), + ); + onTestFinished(async () => { + await chat.close(); + db.close(); + await data.cleanup(); + }); + const movement = { + token: "角色/旅人", + map: "测试场景", + waypoints: [[350, 250]] as [number, number][], + }; + + await assert.rejects( + chat.send( + { + roomId: room.id, + clientMessageId: randomUUID(), + text: "随便聊聊", + chatOnly: true, + movement, + }, + player, + ), + /只能随行动消息提交/, + ); + await assert.rejects( + chat.send( + { + roomId: room.id, + clientMessageId: randomUUID(), + text: "", + chatOnly: false, + movement: { ...movement, token: "守望者" }, + }, + player, + ), + /自己的角色/, + ); + const sent = await chat.send( + { roomId: room.id, clientMessageId: randomUUID(), text: "", chatOnly: false, movement }, + player, + ); + assert.equal(sent.kind === "player" && sent.movement?.length, 10); + await waitFor(() => assert.equal(prompts.length, 1)); + assert.match(prompts[0]!, /移动意图(旅人\[角色\/旅人\]/); + assert.match(prompts[0]!, new RegExp(`intent: "${sent.id}"`)); + assert.match(prompts[0]!, /地图位置(幕后/); + + const projection = await chat.roomProjection(room.id, player); + const [view] = projection.sections.map.maps; + assert.equal(view?.id, "测试场景"); + assert.ok(view.tokens.some((token) => token.id === "角色/旅人" && token.playerId === player.id)); + assert.ok(!view.tokens.some((token) => token.id === "守望者")); +}); diff --git a/packages/core/src/node/game/player-turn.ts b/packages/core/src/node/game/player-turn.ts index e83926d..d2a5ebb 100644 --- a/packages/core/src/node/game/player-turn.ts +++ b/packages/core/src/node/game/player-turn.ts @@ -6,12 +6,15 @@ export interface PlayerTurn { text: string; playerId: string; characterName?: string; + /** 主持专用的移动意图说明,在生成主持输入时按当时的地图状态计算。 */ + movement?: string; } /** 一条玩家发言。多人时按顺序拼成多块,正文保持原样。 */ function playerTurnMessage(input: PlayerTurn) { const character = input.characterName ? ` character="${attr(input.characterName)}"` : ""; - return `\n${input.text}\n`; + const movement = input.movement ? `\n${input.movement}` : ""; + return `\n${input.text}${movement}\n`; } export function playerTurnPrompt(turns: readonly PlayerTurn[]) { diff --git a/packages/core/src/node/sessions/compile-module.ts b/packages/core/src/node/sessions/compile-module.ts index 6857aab..12c935d 100644 --- a/packages/core/src/node/sessions/compile-module.ts +++ b/packages/core/src/node/sessions/compile-module.ts @@ -6,6 +6,7 @@ import { configFilePath, parseConfig } from "@jointarp/module/node/config-file"; import { parseDocumentContent } from "@jointarp/module/node/document-codec"; import { loadDocumentTypes } from "@jointarp/module/node/document-types"; import { loadModuleDocuments } from "@jointarp/module/node/module-documents"; +import { loadModuleMaps } from "@jointarp/module/node/module-maps"; import { loadModuleMetadata } from "@jointarp/module/node/module-metadata"; /** 只编译 staging 副本;保留作者原值、公式及引用,阅读页和附件不转换。 */ @@ -29,6 +30,7 @@ export async function compileModule(directory: string): Promise { for (const entry of await readdir(join(directory, ".types"), { withFileTypes: true })) if (entry.isFile() && /\.(fields|layout)\.toml$/u.test(entry.name)) await config(`.types/${entry.name}`); + for (const map of await loadModuleMaps(directory)) await config(map.path); for (const document of documents) { if (/\.json$/iu.test(document.path)) continue; conversions.push({ diff --git a/packages/core/src/node/sessions/frozen-module.ts b/packages/core/src/node/sessions/frozen-module.ts index d8456ae..c65daea 100644 --- a/packages/core/src/node/sessions/frozen-module.ts +++ b/packages/core/src/node/sessions/frozen-module.ts @@ -1,10 +1,13 @@ import { join } from "node:path"; +import { documentIdentity } from "@jointarp/module/document-path"; import type { DocumentType } from "@jointarp/module/document-type"; import { launchConfigSchema, validateLaunch, type LaunchConfig } from "@jointarp/module/flow"; +import type { ModuleMap } from "@jointarp/module/map"; import type { RawModuleDocument } from "@jointarp/module/module-document"; import { loadDocumentTypes } from "@jointarp/module/node/document-types"; import { loadModuleDocuments } from "@jointarp/module/node/module-documents"; +import { loadModuleMaps, validateModuleMapReferences } from "@jointarp/module/node/module-maps"; import { loadModuleMetadata } from "@jointarp/module/node/module-metadata"; import type { SessionDatabase } from "../storage/session-database"; @@ -13,9 +16,26 @@ import { roomDirectoryForDatabase } from "./session-paths"; export interface FrozenModule { readonly types: readonly DocumentType[]; readonly documents: readonly RawModuleDocument[]; + readonly maps: readonly ModuleMap[]; readonly launch?: LaunchConfig; } +/** 地图配置与关联资料须同时有效,避免房间运行时引用缺失的标记资料。 */ +export async function loadValidatedMaps( + directory: string, + documents: readonly RawModuleDocument[], +): Promise { + const maps = await loadModuleMaps(directory); + const identities = new Set( + documents + .filter((document) => document.valid) + .map((document) => documentIdentity(document.path)), + ); + const issue = (await validateModuleMapReferences(directory, maps, identities))[0]; + if (issue) throw new Error(`地图 ${issue.path} 无效:${issue.message}`); + return maps; +} + const modules = new WeakMap(); const cached = new Map>(); const connections = new Map>(); @@ -65,7 +85,8 @@ export function loadFrozenModule(directory: string): Promise { }) : undefined; if (launch) validateLaunch(launch, types, documents); - return { types, documents, launch }; + const maps = await loadValidatedMaps(directory, documents); + return { types, documents, maps, launch }; })(); cached.set(directory, pending); void pending.catch(() => { diff --git a/packages/core/src/node/sessions/game-context.ts b/packages/core/src/node/sessions/game-context.ts index f404072..2421a4a 100644 --- a/packages/core/src/node/sessions/game-context.ts +++ b/packages/core/src/node/sessions/game-context.ts @@ -1,6 +1,7 @@ import type { SessionDatabase } from "../storage/session-database"; import { storedTypes, readCharacters } from "./character-db"; import { listGameFileRecords } from "./game-file-index"; +import { mapPositionPrompt } from "./map-description"; /** 仅提供本局资料入口;状态结构与玩法含义由模组规则解释。 */ export async function gameStatePrompt(db: SessionDatabase): Promise { @@ -19,5 +20,6 @@ export async function gameStatePrompt(db: SessionDatabase): Promise { path: character.sourcePath, playerId: character.playerId, })); - return `本局资料入口(幕后索引,不向玩家公开路径):${JSON.stringify({ worlds, characters })}。位置、场景、时间、回合、效果与结局均按模组字段和规则解释;不得由开局背景或旧聊天推定当前值。`; + const map = mapPositionPrompt(db); + return `本局资料入口(幕后索引,不向玩家公开路径):${JSON.stringify({ worlds, characters })}。位置、场景、时间、回合、效果与结局均按模组字段和规则解释;不得由开局背景或旧聊天推定当前值。${map ? `\n${map}` : ""}`; } diff --git a/packages/core/src/node/sessions/launch-store.ts b/packages/core/src/node/sessions/launch-store.ts index 1688b50..8440c34 100644 --- a/packages/core/src/node/sessions/launch-store.ts +++ b/packages/core/src/node/sessions/launch-store.ts @@ -42,6 +42,7 @@ import { saveLaunchRoom, } from "./launch-db"; import { allLaunchProgress } from "./launch-db"; +import { seatPartyAtStart } from "./map-commands"; import { assertSessionActive } from "./session-store"; function canSelectCharacter( @@ -494,6 +495,7 @@ export async function advanceLaunch(root: string, input: LaunchAction, playerId: if (db.sqlite.inTransaction) db.sqlite.exec("ROLLBACK"); throw error; } + if (a.action === "confirm") await seatPartyAtStart(db); }); return launchState(root, a.roomId, playerId); } diff --git a/packages/core/src/node/sessions/map-commands.test.ts b/packages/core/src/node/sessions/map-commands.test.ts new file mode 100644 index 0000000..ede84cf --- /dev/null +++ b/packages/core/src/node/sessions/map-commands.test.ts @@ -0,0 +1,238 @@ +import { test, onTestFinished } from "bun:test"; +import { strict as assert } from "node:assert"; +import { randomUUID } from "node:crypto"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { loadModuleMaps } from "@jointarp/module/node/module-maps"; +import { createTestModule } from "@jointarp/module/testing/test-module"; + +import type { ChatMessage } from "../../shared/game"; +import { moveToken, readMap, seatPartyAtStart, updateMap } from "./map-commands"; +import { mapPositionPrompt, movementPrompt } from "./map-description"; +import { prepareMovement } from "./map-intent"; +import { projectMapSection } from "./map-projection"; +import { initialMapState, readMapState } from "./map-state"; +import { updateAdventure } from "./room-storage"; +import { createSession, openSessionDatabase } from "./session-store"; + +const player = "8d03c680-4f8d-4d9e-ae52-6f95eaee7232"; + +async function room(prepare?: (root: string) => Promise) { + const f = await createTestModule(); + onTestFinished(f.cleanup); + await prepare?.(f.modulePath); + const created = await createSession(f.sessions, f.modulePath, "地图命令"); + updateAdventure(join(f.sessions, created.id), (adventure) => { + adventure.party.characters.find( + (character) => character.sourcePath === "角色/旅人.json", + )!.playerId = player; + return adventure; + }); + const db = await openSessionDatabase(f.sessions, created.id); + onTestFinished(() => db.close()); + return { db, roomId: created.id }; +} + +test("单起点地图在入队时把队伍角色放到起点", async () => { + const { db } = await room(); + await seatPartyAtStart(db); + const state = readMapState(db); + assert.equal(state.maps["测试场景"]!.known, true); + assert.deepEqual(state.tokens["角色/旅人"]?.at, [150, 250]); + const at = state.tokens["角色/旅人"]!.at; + await seatPartyAtStart(db); + assert.deepEqual(readMapState(db).tokens["角色/旅人"]?.at, at); +}); + +test("主持放置队伍角色后地图对玩家可见,读取结果包含区域、门、标记与探索比例", async () => { + const { db } = await room(); + const placed = await updateMap(db, { + action: "place", + map: "测试场景", + document: "角色/旅人.json", + at: { start: "入口" }, + }); + assert.deepEqual(placed, { + token: "角色/旅人", + map: "测试场景", + at: [7.5, 12.5], + regions: ["西室"], + }); + assert.equal(readMapState(db).maps["测试场景"]!.known, true); + await assert.rejects( + updateMap(db, { + action: "place", + map: "测试场景", + document: "不存在/文档", + at: { x: 1, y: 1 }, + }), + /文档不存在/, + ); + + const map = readMap(db, "测试场景") as ReturnType & Record; + assert.deepEqual(map.scale, { grid: "square", cell: 5, unit: "尺", diagonal: "equal" }); + assert.equal(map.regions.find((region: any) => region.id === "西室").explored, 1); + assert.equal(map.regions.find((region: any) => region.id === "东室").explored, 0); + assert.deepEqual(map.doors.find((door: any) => door.id === "中门").between.sort(), [ + "东室", + "西室", + ]); + assert.deepEqual(map.doors.find((door: any) => door.id === "暗门").revealed, false); + assert.equal(map.tokens.find((token: any) => token.id === "守望者").visible, false); + assert.equal(map.tokens.find((token: any) => token.id === "角色/旅人").party, true); + + const line = mapPositionPrompt(db); + assert.match(line, /旅人\[角色\/旅人\] 西室 \(7\.5, 12\.5\)/); + assert.match(line, /守望者\[守望者\] 东室 \(32\.5, 12\.5\) 视野外/); + + await assert.rejects( + updateMap(db, { action: "reveal", map: "测试场景", door: "中门" }), + /不是秘门/, + ); + await updateMap(db, { action: "door", map: "测试场景", door: "暗门", open: true }); + assert.deepEqual(readMapState(db).maps["测试场景"]!.doors["暗门"], { + open: true, + revealed: true, + }); +}); + +test("移动意图只允许本人角色且不能穿墙,主持说明标注区域、门与终点重叠,执行时停在关闭的门前", async () => { + const { db, roomId } = await room(); + await updateMap(db, { + action: "place", + map: "测试场景", + document: "角色/旅人", + at: { start: "入口" }, + }); + const input = { + token: "角色/旅人", + map: "测试场景", + waypoints: [[650, 250]] as [number, number][], + }; + assert.throws(() => prepareMovement(db, randomUUID(), input), /自己的角色/); + assert.throws( + () => prepareMovement(db, player, { ...input, waypoints: [[650, 450]] }), + /不能穿过墙/, + ); + assert.throws( + () => prepareMovement(db, player, { ...input, waypoints: [[900, 450]] }), + /不能穿过墙/, + ); + const intent = prepareMovement(db, player, input); + assert.deepEqual( + { from: intent.from, length: intent.length, explore: intent.explore, unit: intent.unit }, + { from: [150, 250], length: null, explore: true, unit: "尺" }, + ); + + const messageId = randomUUID(); + const message: ChatMessage = { + id: messageId, + sequence: 1, + roomId, + senderId: player, + nickname: "玩家", + createdAt: new Date().toISOString(), + status: "complete", + revision: 0, + kind: "player", + text: "去看看守望者", + chatOnly: false, + movement: intent, + }; + db.run( + db.query.insertInto("chat_messages").values({ id: messageId, data: JSON.stringify(message) }), + ); + const prompt = movementPrompt(db, messageId, intent); + assert.match(prompt, /经过门 中门(关)/); + assert.match(prompt, /进入东室/); + assert.match(prompt, /终点与 守望者\[守望者\] 重叠/); + assert.match(prompt, /终点在未探索区域/); + assert.match(prompt, new RegExp(`intent: "${messageId}"`)); + + const stopped = await moveToken(db, { intent: messageId }); + assert.equal(stopped.stoppedBy, "门 中门 关闭"); + assert.deepEqual(stopped.at, [22.5, 12.5]); + assert.equal(readMapState(db).intents[messageId]?.progress, stopped.moved); + + await updateMap(db, { action: "door", map: "测试场景", door: "中门", open: true }); + const moved = await moveToken(db, { token: "角色/旅人", to: { near: "守望者", side: "west" } }); + assert.deepEqual(moved.at, [27.5, 12.5]); + assert.deepEqual(moved.regions, ["东室"]); + await assert.rejects(moveToken(db, { token: "角色/旅人", to: { region: "暗室" } }), /无法到达/); +}); + +test("父子地图仅在两图均已知时公开关系,保持各自探索状态", async () => { + const f = await createTestModule(); + onTestFinished(f.cleanup); + const [base] = await loadModuleMaps(f.modulePath); + const maps = [base!, { ...base!, id: "地下室", config: { ...base!.config, parent: base!.id } }]; + const state = initialMapState(maps); + const views = () => + projectMapSection(maps, state, new Map()).maps.map(({ id, parent }) => [id, parent]); + state.maps[base!.id]!.known = true; + assert.deepEqual(views(), [[base!.id, undefined]]); + state.maps[base!.id]!.known = false; + state.maps["地下室"]!.known = true; + assert.deepEqual(views(), [["地下室", undefined]]); + state.maps[base!.id]!.known = true; + assert.deepEqual(views(), [ + [base!.id, undefined], + ["地下室", base!.id], + ]); +}); + +test("主持通过配对楼梯,受阻整组回滚,分队保留位置,单向禁止返回", async () => { + const { db } = await room(async (root) => { + const [base] = await loadModuleMaps(root); + const config = { + ...base!.config, + name: "二楼", + tokens: [], + starts: [ + { id: "楼梯", name: "楼梯", at: [150, 250] }, + { id: "滑道", name: "滑道", at: [250, 250] }, + ], + connections: [ + { from: "楼梯", map: base!.id, to: "入口" }, + { from: "滑道", map: base!.id, to: "入口", oneWay: true }, + ], + }; + await writeFile(join(root, "maps/二楼.json"), JSON.stringify(config)); + }); + const map = "测试场景", + hero = "角色/旅人"; + await updateMap(db, { action: "place", map, at: { start: "入口" }, document: hero }); + await updateMap(db, { action: "place", map, at: { start: "入口" }, label: "同伴" }); + const go = { + action: "traverse", + map, + from: "入口", + target: "二楼", + to: "楼梯", + tokens: [hero, "同伴"], + }; + const before = readMapState(db); + await assert.rejects(updateMap(db, { ...go, tokens: [hero, "守望者"] }), /无法到达/); + assert.deepEqual(readMapState(db), before); + await assert.rejects(updateMap(db, { ...go, to: "滑道" }), /该方向/); + await updateMap(db, { ...go, tokens: [hero] }); + const arrived = readMapState(db); + assert.deepEqual(arrived.tokens[hero]!.at, [150, 250]); + assert.equal(arrived.tokens["同伴"]!.map, map); + assert.equal(arrived.maps["二楼"]!.known, true); + assert.ok(arrived.maps["二楼"]!.explored); + const back = { + action: "traverse", + map: "二楼", + from: "楼梯", + target: map, + to: "入口", + tokens: [hero], + }; + await updateMap(db, back); + await updateMap(db, go); + const group = readMapState(db); + assert.equal(group.tokens["同伴"]!.map, "二楼"); + assert.notDeepEqual(group.tokens["同伴"]!.at, group.tokens[hero]!.at); +}); diff --git a/packages/core/src/node/sessions/map-commands.ts b/packages/core/src/node/sessions/map-commands.ts new file mode 100644 index 0000000..e49b5c2 --- /dev/null +++ b/packages/core/src/node/sessions/map-commands.ts @@ -0,0 +1,553 @@ +import { documentIdentity } from "@jointarp/module/document-path"; +import { exitsFrom, type MapPoint, type ModuleMap } from "@jointarp/module/map"; +import { + explorationGrid, + firstBlocked, + footprintPixels, + isExplored, + measurePath, + pointAtDistance, + pointInPolygon, + round, + snapToGrid, + toUnits, + wallSegments, + type Point, +} from "@jointarp/module/map-geometry"; +import { z } from "zod"; + +import { messageSchema } from "../../shared/game"; +import type { SessionDatabase } from "../storage/session-database"; +import { assertGameWritable } from "./adventure-status"; +import { frozenModule } from "./frozen-module"; +import { listGameFileRecords } from "./game-file-index"; +import { tokenNames } from "./map-description"; +import { + analyzeRoute, + explorationBits, + exploreAlong, + exploreCurrentVision, + findPath, + isParty, + mapSides, + movementBlockers, + overlapping, + partyIndex, + partyVision, + regionLabel, + regionsAt, + resolveAnchor, + tokensOn, + visibleTokens, + type MapAnchor, +} from "./map-space"; +import { readMapState, writeMapState, type MapState, type MapTokenState } from "./map-state"; +import { gameDirectoryForDatabase } from "./session-paths"; +import { withStateLock } from "./state-lock"; + +const id = z.string().trim().min(1).max(200); +const side = z.enum(mapSides as [string, ...string[]]); +export const mapAnchorSchema = z.union([ + z.strictObject({ start: id }), + z.strictObject({ region: id, side: side.optional() }), + z.strictObject({ near: id, side: side.optional() }), + z.strictObject({ x: z.number().finite(), y: z.number().finite() }), +]); +type AnchorInput = z.infer; + +export const mapMoveSchema = z + .strictObject({ + token: id.optional(), + intent: z.string().uuid().optional(), + to: mapAnchorSchema.optional(), + until: z.number().nonnegative().optional(), + }) + .refine((input) => Boolean(input.intent) !== Boolean(input.to), { + message: "intent 与 to 必须且只能提供一个", + }) + .refine((input) => input.intent || input.token, { message: "使用 to 时必须提供 token" }); + +const flags = { + hidden: z.boolean().optional(), + blocksVision: z.boolean().optional(), + blocksMovement: z.boolean().optional(), + vision: z.number().positive().nullable().optional(), + size: z.number().positive().max(20).optional(), + label: z.string().trim().min(1).max(100).optional(), +}; +export const mapUpdateSchema = z.discriminatedUnion("action", [ + z.strictObject({ + action: z.literal("place"), + map: id, + at: mapAnchorSchema, + token: id.optional(), + document: z.string().trim().min(1).max(1000).optional(), + ...flags, + }), + z.strictObject({ + action: z.literal("traverse"), + map: id, + from: id, + target: id, + to: id, + tokens: z.array(id).min(1).max(100), + }), + z.strictObject({ action: z.literal("remove"), token: id }), + z.strictObject({ action: z.literal("set"), token: id, ...flags }), + z.strictObject({ action: z.literal("door"), map: id, door: id, open: z.boolean() }), + z.strictObject({ action: z.literal("reveal"), map: id, door: id }), + z.strictObject({ action: z.literal("conceal"), map: id, door: id }), + z.strictObject({ action: z.literal("known"), map: id, known: z.boolean() }), +]); + +function findMap(db: SessionDatabase, mapId: string): ModuleMap { + const maps = frozenModule(db).maps; + const map = + maps.find((item) => item.id === mapId) ?? maps.find((item) => item.config.name === mapId); + if (!map) throw new Error(`地图不存在:${mapId}`); + return map; +} + +function anchor(input: AnchorInput): MapAnchor { + return "x" in input ? { point: [input.x, input.y] } : (input as MapAnchor); +} + +function units(map: ModuleMap, point: Point) { + return toUnits(map.config.grid, point); +} + +function explorationShare(map: ModuleMap, state: MapState, points: readonly Point[]): number { + const room = state.maps[map.id]!; + const grid = explorationGrid(map.config); + const bits = explorationBits(map, room); + let total = 0; + let explored = 0; + for (let row = 0; row < grid.rows; row++) + for (let column = 0; column < grid.columns; column++) { + const center: Point = [(column + 0.5) * grid.cell, (row + 0.5) * grid.cell]; + if (!pointInPolygon(center, points)) continue; + total++; + if (isExplored(bits, grid, center)) explored++; + } + return total ? round(explored / total, 2) : 0; +} + +/** 主持读取地图:区域、门、起点、全部标记与队伍视野,坐标使用距离单位。 */ +export function readMap(db: SessionDatabase, mapId?: string) { + const maps = frozenModule(db).maps; + const state = readMapState(db); + const party = partyIndex(db); + if (!mapId) + return { + maps: maps.map((map) => ({ + id: map.id, + name: map.config.name, + ...(map.config.parent ? { parent: map.config.parent } : {}), + known: state.maps[map.id]?.known ?? false, + party: tokensOn(state, map.id) + .filter(([, token]) => isParty(token, party)) + .map(([id]) => id), + })), + }; + const map = findMap(db, mapId); + const room = state.maps[map.id]!; + const names = tokenNames(db, state); + const visible = visibleTokens( + map, + state, + party, + partyVision(map, room, state, party).map(({ polygon }) => polygon), + ); + const regionNames = (point: Point) => regionsAt(map, point).map(regionLabel); + const grid = map.config.grid; + return { + id: map.id, + name: map.config.name, + ...(map.config.parent ? { parent: map.config.parent } : {}), + ...(map.config.description ? { description: map.config.description } : {}), + known: room.known, + scale: + grid.type === "square" + ? { grid: "square", cell: grid.distance, unit: grid.unit, diagonal: grid.diagonal } + : { grid: "none", unit: grid.unit }, + size: units(map, [map.config.width, map.config.height]), + regions: map.config.regions.map((region) => ({ + id: region.id, + ...(region.name ? { name: region.name } : {}), + ...(region.document ? { document: region.document } : {}), + ...(region.secret ? { secret: true } : {}), + ...(region.note ? { note: region.note } : {}), + points: region.points.map((point) => units(map, point)), + explored: explorationShare(map, state, region.points), + })), + doors: map.config.doors.map((door) => { + const middle: Point = [(door.from[0] + door.to[0]) / 2, (door.from[1] + door.to[1]) / 2]; + const normal = [door.to[1] - door.from[1], door.from[0] - door.to[0]]; + const length = Math.hypot(normal[0]!, normal[1]!) || 1; + const offset = footprintPixels(grid, 0.5); + const sides = [1, -1].map((sign) => + regionNames([ + middle[0] + (sign * normal[0]! * offset) / length, + middle[1] + (sign * normal[1]! * offset) / length, + ]).join("/"), + ); + const doorState = room.doors[door.id]!; + return { + id: door.id, + at: units(map, middle), + between: sides.map((item) => item || "区域外"), + open: doorState.open, + ...(door.secret ? { secret: true, revealed: doorState.revealed } : {}), + }; + }), + exits: exitsFrom(maps, map.id), + starts: map.config.starts.map((start) => ({ + id: start.id, + name: start.name, + at: units(map, start.at), + regions: regionNames(start.at), + })), + tokens: tokensOn(state, map.id).map(([id, token]) => ({ + id, + name: names.get(id), + ...(token.document ? { document: token.document } : {}), + at: units(map, token.at), + regions: regionNames(token.at), + size: token.size, + ...(isParty(token, party) ? { party: true } : { visible: visible.has(id) }), + ...(token.hidden ? { hidden: true } : {}), + ...(token.blocksVision ? { blocksVision: true } : {}), + ...(token.blocksMovement ? { blocksMovement: true } : {}), + ...(token.vision !== undefined ? { vision: token.vision } : {}), + })), + }; +} + +async function mutate( + db: SessionDatabase, + signal: AbortSignal | undefined, + change: (state: MapState, party: ReadonlyMap) => T, +): Promise { + return withStateLock(gameDirectoryForDatabase(db), async () => { + signal?.throwIfAborted(); + assertGameWritable(db); + const state = readMapState(db); + const result = change(state, partyIndex(db)); + writeMapState(db, state); + return result; + }); +} + +function visibleSet(map: ModuleMap, state: MapState, party: ReadonlyMap) { + const room = state.maps[map.id]!; + return visibleTokens( + map, + state, + party, + partyVision(map, room, state, party).map(({ polygon }) => polygon), + ); +} + +function intentOf(db: SessionDatabase, messageId: string) { + const row = db.get( + db.query.selectFrom("chat_messages").select("data").where("id", "=", messageId), + ); + const message = row ? messageSchema.parse(JSON.parse(String(row.data))) : undefined; + if (message?.kind !== "player" || !message.movement) throw new Error("该消息没有移动意图"); + return message.movement; +} + +/** 按意图路线或寻路移动标记;路线遇到墙或关闭的门时停在阻挡前。 */ +export async function moveToken(db: SessionDatabase, raw: unknown, signal?: AbortSignal) { + const input = mapMoveSchema.parse(raw); + const intent = input.intent ? intentOf(db, input.intent) : undefined; + const tokenId = intent?.token ?? input.token!; + if (intent && input.token && input.token !== intent.token) + throw new Error(`该意图属于标记 ${intent.token}`); + return mutate(db, signal, (state, party) => { + const token = state.tokens[tokenId]; + if (!token) throw new Error(`标记不存在:${tokenId}`); + if (intent && token.map !== intent.map) throw new Error("标记已不在意图所在的地图上"); + const map = findMap(db, token.map); + const room = state.maps[map.id]!; + let path: MapPoint[]; + if (intent) path = [token.at, ...intent.waypoints]; + else { + const target = resolveAnchor(map, room, state, anchor(input.to!), token.size, tokenId); + const found = findPath(map, room, token.at, target); + if (!found) throw new Error("无法到达:路线被墙或关闭的门隔断"); + path = found; + } + const grid = map.config.grid; + const measure = measurePath(grid, path); + let stop = input.until !== undefined ? Math.min(input.until, measure.total) : measure.total; + let stoppedBy: string | undefined; + const distanceAt = (hit: { segment: number; t: number }) => + measure.cumulative[hit.segment]! + + hit.t * (measure.cumulative[hit.segment + 1]! - measure.cumulative[hit.segment]!); + const half = (grid.type === "square" ? token.size * grid.distance : token.size) / 2; + const blockers = [ + ...map.config.doors + .filter((door) => !room.doors[door.id]?.open) + .map((door) => ({ label: `门 ${door.id} 关闭`, segment: { a: door.from, b: door.to } })), + ...wallSegments(map.config).map((segment) => ({ label: "墙", segment })), + ]; + for (const blocker of blockers) { + const hit = firstBlocked(path, [blocker.segment]); + if (!hit) continue; + const before = Math.max(0, distanceAt(hit) - half); + if (before < stop) { + stop = before; + stoppedBy = blocker.label; + } + } + const end = pointAtDistance(path, measure, stop); + const walked: MapPoint[] = [...path.slice(0, end.segment + 1), end.point]; + if (stop < measure.total) { + const snapped = snapToGrid(grid, end.point, token.size); + if (!firstBlocked([end.point, snapped], movementBlockers(map, room))) walked.push(snapped); + } + const destination = path.at(-1)!; + const route = analyzeRoute(map, state, tokenId, walked); + const before = visibleSet(map, state, party); + const final = walked.at(-1)!; + token.at = [round(final[0], 2), round(final[1], 2)]; + exploreAlong(map, state, party, tokenId, walked); + if (input.intent) + state.intents[input.intent] = { + progress: round((state.intents[input.intent]?.progress ?? 0) + stop), + }; + const after = visibleSet(map, state, party); + const names = tokenNames(db, state); + return { + token: tokenId, + at: units(map, token.at), + regions: regionsAt(map, token.at).map(regionLabel), + moved: round(stop), + remaining: round(measure.total - stop), + ...(stoppedBy ? { stoppedBy } : {}), + ...(stop < measure.total ? { destination: units(map, destination) } : {}), + entered: route.events + .filter((event) => event.kind === "enter") + .map((event) => (event.kind === "enter" ? regionLabel(event.region) : "")), + ...(route.endOverlap.length + ? { overlapping: route.endOverlap.map((id) => `${names.get(id)}[${id}]`) } + : {}), + newlyVisible: [...after] + .filter((id) => !before.has(id) && !isParty(state.tokens[id]!, party)) + .map((id) => `${names.get(id)}[${id}]`), + }; + }); +} + +function newTokenId(state: MapState, base: string) { + if (!state.tokens[base]) return base; + for (let index = 2; ; index++) if (!state.tokens[`${base}-${index}`]) return `${base}-${index}`; +} + +/** + * 只有一张地图且只有一个起点时,把尚未入图的队伍角色放到该起点。 + * 多人时第一个在起点,其余依次站在旁边。多张地图或多个起点仍由主持放置。 + */ +export async function seatPartyAtStart(db: SessionDatabase): Promise { + const maps = frozenModule(db).maps; + const map = maps.length === 1 ? maps[0] : undefined; + const start = map?.config.starts.length === 1 ? map.config.starts[0] : undefined; + if (!map || !start) return; + await withStateLock(gameDirectoryForDatabase(db), async () => { + assertGameWritable(db); + const state = readMapState(db); + const party = partyIndex(db); + const missing = [...party.keys()].filter( + (document) => !Object.values(state.tokens).some((token) => token.document === document), + ); + if (!missing.length) return; + let previous: string | undefined; + for (const document of missing) { + const tokenId = state.tokens[document] ? newTokenId(state, document) : document; + const token: MapTokenState = { + map: map.id, + at: [0, 0], + size: 1, + hidden: false, + blocksVision: false, + blocksMovement: false, + document, + }; + token.at = resolveAnchor( + map, + state.maps[map.id]!, + state, + previous ? { near: previous } : { start: start.id }, + token.size, + tokenId, + ); + state.tokens[tokenId] = token; + previous = tokenId; + } + state.maps[map.id]!.known = true; + exploreCurrentVision(map, state, party); + writeMapState(db, state); + }); +} + +/** 主持维护标记、门与地图可见性;队伍角色放入地图后该地图对玩家可见。 */ +export async function updateMap(db: SessionDatabase, raw: unknown, signal?: AbortSignal) { + const input = mapUpdateSchema.parse(raw); + return mutate(db, signal, (state, party) => { + const refresh = (map: ModuleMap) => exploreCurrentVision(map, state, party); + switch (input.action) { + case "traverse": { + const map = findMap(db, input.map); + const link = exitsFrom(frozenModule(db).maps, map.id).find( + (exit) => exit.from === input.from && exit.map === input.target && exit.to === input.to, + ); + if (!link) throw new Error("该方向没有此出入口连接"); + const target = findMap(db, link.map); + const room = state.maps[map.id]!; + const arrival = state.maps[target.id]!; + const tokens = [...new Set(input.tokens)]; + for (const id of tokens) { + const token = state.tokens[id]; + if (!token || token.map !== map.id) throw new Error(`标记不在出发地图:${id}`); + const entrance = resolveAnchor(map, room, state, { start: link.from }, token.size, id); + const route = findPath(map, room, token.at, entrance); + if (!route) throw new Error(`标记无法到达出入口:${id}`); + exploreAlong(map, state, party, id, route); + const landing = resolveAnchor(target, arrival, state, { start: link.to }, token.size, id); + const [occupied] = overlapping(target, state, landing, token.size, id); + token.at = landing; + if (occupied) { + const beside = resolveAnchor( + target, + arrival, + state, + { near: occupied }, + token.size, + id, + ); + if ( + beside[0] >= 0 && + beside[1] >= 0 && + beside[0] <= target.config.width && + beside[1] <= target.config.height && + !overlapping(target, state, beside, token.size, id).length && + !firstBlocked([landing, beside], movementBlockers(target, arrival)) + ) + token.at = beside; + } + token.map = target.id; + if (isParty(token, party)) arrival.known = true; + } + refresh(map); + refresh(target); + return { tokens, map: target.id, start: link.to }; + } + case "place": { + const map = findMap(db, input.map); + const document = input.document + ? documentIdentity(input.document.replace(/^\//u, "")) + : undefined; + if ( + document && + !listGameFileRecords(db).some((record) => documentIdentity(record.path) === document) + ) + throw new Error(`文档不存在:${input.document}`); + // 未指定标识时,同一文档的标记直接移动;需要多个副本时显式指定新的 token。 + const tokenId = + input.token ?? document ?? (input.label ? newTokenId(state, input.label) : undefined); + if (!tokenId) throw new Error("新标记需要 token、document 或 label"); + const existing = state.tokens[tokenId]; + if (!existing && !document && !input.label) throw new Error("新标记需要 document 或 label"); + const base: MapTokenState = existing ?? { + map: map.id, + at: [0, 0], + size: 1, + hidden: false, + blocksVision: false, + blocksMovement: false, + ...(document ? { document } : {}), + }; + const previousMap = existing?.map; + const token: MapTokenState = { + ...base, + map: map.id, + ...(document ? { document } : {}), + ...pickFlags(input), + }; + if (input.label) token.label = input.label; + token.at = resolveAnchor( + map, + state.maps[map.id]!, + state, + anchor(input.at), + token.size, + tokenId, + ); + state.tokens[tokenId] = token; + if (isParty(token, party)) state.maps[map.id]!.known = true; + refresh(map); + if (previousMap && previousMap !== map.id) refresh(findMap(db, previousMap)); + return { + token: tokenId, + map: map.id, + at: units(map, token.at), + regions: regionsAt(map, token.at).map(regionLabel), + }; + } + case "remove": { + if (!state.tokens[input.token]) throw new Error(`标记不存在:${input.token}`); + delete state.tokens[input.token]; + return { removed: input.token }; + } + case "set": { + const token = state.tokens[input.token]; + if (!token) throw new Error(`标记不存在:${input.token}`); + Object.assign(token, pickFlags(input)); + if (input.label) token.label = input.label; + refresh(findMap(db, token.map)); + return { token: input.token }; + } + case "door": + case "reveal": + case "conceal": { + const map = findMap(db, input.map); + const door = state.maps[map.id]!.doors[input.door]; + const config = map.config.doors.find((item) => item.id === input.door); + if (!door || !config) throw new Error(`地图「${map.config.name}」没有门 ${input.door}`); + if (input.action === "door") { + door.open = input.open; + if (input.open) door.revealed = true; + } else if (!config.secret) throw new Error(`门 ${input.door} 不是秘门`); + else if (input.action === "reveal") door.revealed = true; + else { + door.revealed = false; + door.open = false; + } + refresh(map); + return { door: input.door, open: door.open, revealed: door.revealed }; + } + case "known": { + const map = findMap(db, input.map); + state.maps[map.id]!.known = input.known; + return { map: map.id, known: input.known }; + } + } + }); +} + +function pickFlags(input: { + hidden?: boolean; + blocksVision?: boolean; + blocksMovement?: boolean; + vision?: number | null; + size?: number; +}): Partial { + const flags: Partial = {}; + if (input.hidden !== undefined) flags.hidden = input.hidden; + if (input.blocksVision !== undefined) flags.blocksVision = input.blocksVision; + if (input.blocksMovement !== undefined) flags.blocksMovement = input.blocksMovement; + if (input.vision !== undefined) flags.vision = input.vision; + if (input.size !== undefined) flags.size = input.size; + return flags; +} diff --git a/packages/core/src/node/sessions/map-description.ts b/packages/core/src/node/sessions/map-description.ts new file mode 100644 index 0000000..ca7bfa8 --- /dev/null +++ b/packages/core/src/node/sessions/map-description.ts @@ -0,0 +1,156 @@ +import { basename } from "node:path"; + +import { documentIdentity } from "@jointarp/module/document-path"; +import type { ModuleMap } from "@jointarp/module/map"; +import { distance, measurePath, round, toUnits, type Point } from "@jointarp/module/map-geometry"; + +import type { MovementIntent } from "../../shared/map"; +import type { SessionDatabase } from "../storage/session-database"; +import { readCharacters } from "./character-db"; +import { frozenModule } from "./frozen-module"; +import { + analyzeRoute, + isParty, + partyIndex, + partyVision, + regionLabel, + regionsAt, + tokensOn, + visibleTokens, +} from "./map-space"; +import { readMapState, type MapState, type MapTokenState } from "./map-state"; + +/** 标记的显示名:自定义标签、角色或文档名称,最后回退到标识。 */ +export function tokenNames(db: SessionDatabase, state: MapState): Map { + const titles = new Map(); + for (const document of frozenModule(db).documents) + if (document.title) titles.set(documentIdentity(document.path), document.title); + for (const character of readCharacters(db)) + if (character.sourcePath) titles.set(documentIdentity(character.sourcePath), character.name); + return new Map( + Object.entries(state.tokens).map(([id, token]) => [ + id, + token.label ?? + (token.document ? (titles.get(token.document) ?? basename(token.document)) : id), + ]), + ); +} + +function place(map: ModuleMap, point: Point): string { + const [x, y] = toUnits(map.config.grid, point); + const regions = regionsAt(map, point).map(regionLabel); + return `${regions.length ? regions.join("/") : "区域外"} (${x}, ${y})`; +} + +function scale(map: ModuleMap): string { + const grid = map.config.grid; + return grid.type === "square" + ? `方格 ${grid.distance} ${grid.unit}/格,坐标单位${grid.unit}` + : `无网格,坐标单位${grid.unit}`; +} + +const maxListedTokens = 30; + +/** 每轮附带的地图位置:队伍所在地图上的标记、区域与是否在队伍视野内。 */ +export function mapPositionPrompt(db: SessionDatabase): string { + const maps = frozenModule(db).maps; + if (!maps.length) return ""; + const state = readMapState(db); + const party = partyIndex(db); + const names = tokenNames(db, state); + const lines: string[] = []; + for (const map of maps) { + const tokens = tokensOn(state, map.id); + const members = tokens.filter(([, token]) => isParty(token, party)); + if (!members.length) continue; + const room = state.maps[map.id]!; + const visible = visibleTokens( + map, + state, + party, + partyVision(map, room, state, party).map(({ polygon }) => polygon), + ); + const nearest = (token: MapTokenState) => + Math.min(...members.map(([, member]) => distance(member.at, token.at))); + const others = tokens + .filter(([, token]) => !isParty(token, party)) + .sort(([, a], [, b]) => nearest(a) - nearest(b)); + const describe = ([id, token]: [string, MapTokenState]) => + `${names.get(id)}[${id}] ${place(map, token.at)}${isParty(token, party) ? "" : visible.has(id) ? "" : token.hidden ? " 隐藏" : " 视野外"}`; + lines.push( + `「${map.config.name}」[${map.id}](${scale(map)})队伍:${members.map(describe).join(";")}${others.length ? `。其他:${others.slice(0, maxListedTokens).map(describe).join(";")}${others.length > maxListedTokens ? `;另有 ${others.length - maxListedTokens} 个较远标记` : ""}` : ""}`, + ); + } + return lines.length + ? `地图位置(幕后,平台按坐标计算;与模组位置字段相互独立,需要时由你同步更新):\n${lines.join("\n")}` + : ""; +} + +/** 主持专用的移动意图说明;包含玩家不可见的区域、秘门与隐藏标记。 */ +export function movementPrompt( + db: SessionDatabase, + messageId: string, + intent: MovementIntent, +): string { + const map = frozenModule(db).maps.find((item) => item.id === intent.map); + const state = readMapState(db); + const token = state.tokens[intent.token]; + if (!map || !token) + return `移动意图:标记 ${intent.token} 或地图 ${intent.map} 已不存在,按文字行动裁定。`; + const names = tokenNames(db, state); + const path = [intent.from, ...intent.waypoints]; + const route = analyzeRoute( + map, + { ...state, tokens: { ...state.tokens, [intent.token]: { ...token, at: intent.from } } }, + intent.token, + path, + ); + const unit = map.config.grid.unit; + const at = (value: number) => `${round(value)}${unit}处`; + const events = route.events.map((event) => { + switch (event.kind) { + case "enter": + return `${at(event.at)}进入${regionLabel(event.region)}${event.region.secret ? "(秘密区域)" : ""}`; + case "leave": + return `${at(event.at)}离开${regionLabel(event.region)}`; + case "door": { + const door = map.config.doors.find((item) => item.id === event.door)!; + const revealed = state.maps[map.id]?.doors[event.door]?.revealed; + return `${at(event.at)}经过门 ${event.door}(${event.open ? "开" : "关"}${door.secret ? (revealed ? ",已揭示的秘门" : ",玩家未知的秘门,对玩家等同墙") : ""}${event.narrow ? ",门宽窄于占地" : ""})`; + } + case "unexplored": + return `${at(event.at)}进入未探索区域`; + case "blocked": + return `${at(event.at)}被墙阻挡`; + case "obstacle": + return `${at(event.at)}${event.blocking ? "穿过阻挡物" : "经过"} ${names.get(event.token)}[${event.token}]${state.tokens[event.token]?.hidden ? "(隐藏)" : ""}`; + } + }); + const problems = [ + ...(route.events.some((event) => event.kind === "blocked") ? ["路线穿墙"] : []), + ...(route.events.some((event) => event.kind === "obstacle" && event.blocking) + ? ["穿过阻挡物"] + : []), + ...(route.events.some((event) => event.kind === "door" && event.narrow) + ? ["通道窄于占地"] + : []), + ...(route.endOverlap.length + ? [`终点与 ${route.endOverlap.map((id) => `${names.get(id)}[${id}]`).join("、")} 重叠`] + : []), + ...(intent.explore ? ["终点在未探索区域,只表示方向"] : []), + ]; + const moved = !samePoint(token.at, intent.from) && token.map === intent.map; + return [ + `移动意图(${names.get(intent.token)}[${intent.token}],地图「${map.config.name}」[${map.id}]):从 ${place(map, intent.from)} 经 ${intent.waypoints.length} 个路点到 ${place(map, path.at(-1)!)},路线全长 ${round(measurePath(map.config.grid, path).total)}${unit}。`, + events.length ? `途经:${events.join(";")}。` : "", + problems.length ? `需注意:${problems.join(";")}。` : "", + moved ? `该标记提交后已移动到 ${place(map, token.at)}。` : "", + `意图只是计划,按规则与情境裁定实际结果;确认后用 map_move(intent: "${messageId}")沿路线执行,或改为指定位置。`, + ] + .filter(Boolean) + .join(""); +} + +function samePoint(a: Point, b: Point) { + return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6; +} diff --git a/packages/core/src/node/sessions/map-intent.ts b/packages/core/src/node/sessions/map-intent.ts new file mode 100644 index 0000000..4fafaf4 --- /dev/null +++ b/packages/core/src/node/sessions/map-intent.ts @@ -0,0 +1,54 @@ +import { + explorationGrid, + firstBlocked, + isExplored, + measurePath, + round, + wallSegments, +} from "@jointarp/module/map-geometry"; + +import type { MovementIntent, MovementIntentInput } from "../../shared/map"; +import type { SessionDatabase } from "../storage/session-database"; +import { frozenModule } from "./frozen-module"; +import { explorationBits, partyIndex } from "./map-space"; +import { readMapState } from "./map-state"; + +/** 校验玩家为本人角色提交的移动意图,并按当前标记位置记录起点与预估距离。 */ +export function prepareMovement( + db: SessionDatabase, + playerId: string, + input: MovementIntentInput, +): MovementIntent { + const map = frozenModule(db).maps.find((item) => item.id === input.map); + const state = readMapState(db); + const room = map && state.maps[map.id]; + if (!map || !room?.known) throw new Error("地图不存在或队伍尚未到达"); + const token = state.tokens[input.token]; + if (!token || token.map !== map.id) throw new Error("该标记不在这张地图上"); + if (!token.document || partyIndex(db).get(token.document) !== playerId) + throw new Error("只能为自己的角色提交移动意图"); + for (const [x, y] of input.waypoints) + if (x < 0 || y < 0 || x > map.config.width || y > map.config.height) + throw new Error("路点超出地图范围"); + const path = [token.at, ...input.waypoints]; + // 玩家只知道已揭示的门;未揭示的秘门与墙一样不能穿过,关闭的门交给主持裁定。 + const walls = [ + ...wallSegments(map.config), + ...map.config.doors + .filter((door) => !room.doors[door.id]?.revealed) + .map((door) => ({ a: door.from, b: door.to })), + ]; + if (firstBlocked(path, walls)) throw new Error("移动路线不能穿过墙"); + const explore = !isExplored( + explorationBits(map, room), + explorationGrid(map.config), + path.at(-1)!, + ); + return { + ...input, + from: token.at, + length: explore ? null : round(measurePath(map.config.grid, path).total), + unit: map.config.grid.unit, + explore, + }; +} diff --git a/packages/core/src/node/sessions/map-projection.ts b/packages/core/src/node/sessions/map-projection.ts new file mode 100644 index 0000000..567a0f1 --- /dev/null +++ b/packages/core/src/node/sessions/map-projection.ts @@ -0,0 +1,81 @@ +import type { MapPoint, ModuleMap } from "@jointarp/module/map"; +import { round } from "@jointarp/module/map-geometry"; + +import type { MapResource, MapSection, MapView } from "../../shared/map"; +import { isParty, partyVision, tokensOn, visibleTokens } from "./map-space"; +import type { MapState } from "./map-state"; + +export function mapResources(maps: readonly ModuleMap[]): MapResource[] { + return maps.map(({ id, path, config }) => ({ + id, + path, + name: config.name, + ...(config.description ? { description: config.description } : {}), + image: config.image, + width: config.width, + height: config.height, + grid: config.grid, + walls: config.walls.map((wall) => wall.points), + })); +} + +const roundPoint = (point: readonly [number, number]): MapPoint => [ + round(point[0]), + round(point[1]), +]; + +/** 按全队视野投影队伍已知的地图;视野外的标记与未揭示的秘门不进入投影。 */ +export function projectMapSection( + maps: readonly ModuleMap[], + state: MapState, + party: ReadonlyMap, +): MapSection { + const views: MapView[] = []; + for (const map of maps) { + const room = state.maps[map.id]; + if (!room?.known) continue; + const polygons = partyVision(map, room, state, party).map(({ polygon }) => + polygon.map(roundPoint), + ); + const visible = visibleTokens(map, state, party, polygons); + views.push({ + id: map.id, + ...(map.config.parent && state.maps[map.config.parent]?.known + ? { parent: map.config.parent } + : {}), + explored: room.explored, + visible: polygons, + doors: map.config.doors + .filter((door) => room.doors[door.id]?.revealed) + .map((door) => ({ + id: door.id, + from: door.from, + to: door.to, + open: Boolean(room.doors[door.id]?.open), + })), + barriers: map.config.doors + .filter((door) => !room.doors[door.id]?.revealed) + .map((door) => [door.from, door.to] as const), + tokens: tokensOn(state, map.id) + .filter(([id]) => visible.has(id)) + .map(([id, token]) => { + const playerId = token.document ? party.get(token.document) : undefined; + return { + id, + ...(token.document ? { document: token.document } : {}), + ...(token.label ? { label: token.label } : {}), + at: token.at, + size: token.size, + party: isParty(token, party), + ...(playerId ? { playerId } : {}), + }; + }), + }); + } + return { + maps: views, + intents: Object.fromEntries( + Object.entries(state.intents).map(([id, intent]) => [id, intent.progress]), + ), + }; +} diff --git a/packages/core/src/node/sessions/map-space.test.ts b/packages/core/src/node/sessions/map-space.test.ts new file mode 100644 index 0000000..bb6b6a1 --- /dev/null +++ b/packages/core/src/node/sessions/map-space.test.ts @@ -0,0 +1,212 @@ +import { test, onTestFinished } from "bun:test"; +import { strict as assert } from "node:assert"; +import { join } from "node:path"; + +import { + explorationGrid, + isExplored, + decodeExploration, + pointInPolygon, +} from "@jointarp/module/map-geometry"; +import { loadModuleMaps } from "@jointarp/module/node/module-maps"; +import { createTestModule } from "@jointarp/module/testing/test-module"; + +import { mapResources, projectMapSection } from "./map-projection"; +import { analyzeRoute, exploreAlong, findPath, resolveAnchor } from "./map-space"; +import { initialMapState, readMapState, reconcileMapState, type MapState } from "./map-state"; +import { createSession, openSessionDatabase } from "./session-store"; + +const party = new Map([["角色/旅人", "玩家甲"]]); + +async function scene() { + const f = await createTestModule(); + onTestFinished(f.cleanup); + const [map] = await loadModuleMaps(f.modulePath); + assert.equal(map!.id, "测试场景"); + const state = initialMapState([map!]); + state.tokens["旅人"] = { + map: map!.id, + at: [150, 250], + size: 1, + document: "角色/旅人", + hidden: false, + blocksVision: false, + blocksMovement: false, + }; + return { f, map: map!, state, room: state.maps[map!.id]! }; +} + +test("创建冒险时按模组地图初始化房间地图状态,玩家资源不含区域、起点与标记", async () => { + const f = await createTestModule(); + onTestFinished(f.cleanup); + const room = await createSession(f.sessions, f.modulePath, "地图状态"); + const db = await openSessionDatabase(f.sessions, room.id); + onTestFinished(() => db.close()); + const state = readMapState(db); + assert.deepEqual(state.maps["测试场景"], { + known: false, + explored: "", + doors: { 中门: { open: false, revealed: true }, 暗门: { open: false, revealed: false } }, + }); + assert.equal(state.tokens["守望者"]?.document, "人物/守望者"); + const [resource] = mapResources(await loadModuleMaps(join(f.sessions, room.id, "module"))); + assert.deepEqual(Object.keys(resource!).sort(), [ + "description", + "grid", + "height", + "id", + "image", + "name", + "path", + "walls", + "width", + ]); +}); + +test("投影只包含已知地图、全队视野内的标记,并把未揭示的秘门当作墙", async () => { + const { map, state, room } = await scene(); + assert.deepEqual(projectMapSection([map], state, party).maps, []); + room.known = true; + let [view] = projectMapSection([map], state, party).maps; + assert.deepEqual(view!.tokens.map((token) => token.id).sort(), ["旅人", "木箱"]); + assert.equal(view!.tokens.find((token) => token.id === "旅人")?.playerId, "玩家甲"); + assert.deepEqual( + view!.doors.map((door) => door.id), + ["中门"], + ); + assert.deepEqual(view!.barriers, [ + [ + [800, 400], + [800, 500], + ], + ]); + + room.doors["中门"]!.open = true; + [view] = projectMapSection([map], state, party).maps; + assert.ok(view!.tokens.some((token) => token.id === "守望者")); + state.tokens["守望者"]!.hidden = true; + [view] = projectMapSection([map], state, party).maps; + assert.ok(!view!.tokens.some((token) => token.id === "守望者")); + + // 遮挡视线的物件挡住其后方标记。 + state.tokens["木箱"]!.blocksVision = true; + state.tokens["旅人"]!.at = [50, 150]; + state.tokens["哨兵"] = { + ...state.tokens["木箱"]!, + at: [450, 150], + label: "哨兵", + blocksVision: false, + }; + [view] = projectMapSection([map], state, party).maps; + assert.ok(!view!.tokens.some((token) => token.id === "哨兵")); + assert.ok(view!.tokens.some((token) => token.id === "木箱")); +}); + +test("寻路绕开墙与关闭的门,路线分析给出区域、门、未探索区域与经过的标记", async () => { + const { map, state, room } = await scene(); + assert.equal(findPath(map, room, [150, 250], [650, 250]), undefined); + room.doors["中门"]!.open = true; + const path = findPath(map, room, [150, 100], [650, 500])!; + assert.ok(path.length >= 3); + assert.deepEqual(path.at(-1), [650, 500]); + + room.doors["中门"]!.open = false; + exploreAlong(map, state, party, "旅人", [[150, 250]]); + const route = analyzeRoute(map, state, "旅人", [ + [150, 250], + [650, 250], + ]); + assert.equal(route.length, 25); + assert.deepEqual(route.events.map((event) => event.kind).sort(), [ + "door", + "enter", + "leave", + "unexplored", + ]); + const door = route.events.find((event) => event.kind === "door"); + assert.equal(door?.kind === "door" && door.open, false); + assert.deepEqual( + route.endRegions.map((region) => region.id), + ["东室"], + ); + assert.deepEqual(route.endOverlap, ["守望者"]); + + const throughWall = analyzeRoute(map, state, "旅人", [ + [150, 100], + [650, 100], + ]); + assert.deepEqual(throughWall.events.map((event) => event.kind).sort(), [ + "blocked", + "enter", + "leave", + "obstacle", + "unexplored", + ]); +}); + +test("模组同步保留已有地图状态,新地图按初始配置加入,拒绝删除仍有标记的文档", async () => { + const { map, state, room } = await scene(); + room.known = true; + room.doors["中门"]!.open = true; + exploreAlong(map, state, party, "旅人", [[150, 250]]); + delete state.tokens["木箱"]; + const changed = { + ...map, + config: { + ...map.config, + width: 900, + doors: map.config.doors.filter((door) => door.id !== "暗门"), + }, + }; + const added = { ...map, id: "新场景", config: { ...map.config, tokens: [] } }; + const documents = new Set(["角色/旅人", "人物/守望者"]); + const next = reconcileMapState(state, [changed, added], documents); + assert.equal(next.maps["测试场景"]!.known, true); + assert.deepEqual(next.maps["测试场景"]!.doors, { 中门: { open: true, revealed: true } }); + // 底图尺寸改变后旧探索记录失效。 + assert.equal(next.maps["测试场景"]!.explored, ""); + assert.deepEqual(next.maps["新场景"]!.known, false); + assert.ok(!next.tokens["木箱"]); + assert.ok(next.tokens["旅人"]); + assert.throws(() => reconcileMapState(state, [changed], new Set(["角色/旅人"])), /人物\/守望者/); +}); + +test("位置锚点解析为格心,沿路线揭示探索记录", async () => { + const { map, state, room } = await scene(); + assert.deepEqual(resolveAnchor(map, room, state, { start: "西侧入口" }, 1), [150, 250]); + assert.deepEqual( + resolveAnchor(map, room, state, { region: "东室", side: "north" }, 1), + [650, 50], + ); + assert.deepEqual( + resolveAnchor(map, room, state, { near: "守望者", side: "west" }, 1), + [550, 250], + ); + assert.deepEqual(resolveAnchor(map, room, state, { point: [12, 3] }, 1), [250, 50]); + assert.throws(() => resolveAnchor(map, room, state, { region: "不存在" }, 1), /没有区域/); + const bent = structuredClone(map); + bent.config.regions.push({ + id: "拐角", + secret: false, + points: [ + [0, 0], + [1000, 0], + [1000, 100], + [100, 100], + [100, 600], + [0, 600], + ], + }); + const corner = resolveAnchor(bent, room, state, { region: "拐角" }, 1); + assert.ok(pointInPolygon(corner, bent.config.regions.at(-1)!.points)); + + const before: MapState = structuredClone(state); + exploreAlong(map, state, party, "旅人", [ + [150, 250], + [350, 250], + ]); + assert.notEqual(state.maps[map.id]!.explored, before.maps[map.id]!.explored); + const bits = decodeExploration(state.maps[map.id]!.explored, explorationGrid(map.config)); + assert.ok(isExplored(bits, explorationGrid(map.config), [450, 550])); + assert.ok(!isExplored(bits, explorationGrid(map.config), [650, 250])); +}); diff --git a/packages/core/src/node/sessions/map-space.ts b/packages/core/src/node/sessions/map-space.ts new file mode 100644 index 0000000..086e95e --- /dev/null +++ b/packages/core/src/node/sessions/map-space.ts @@ -0,0 +1,611 @@ +import { documentIdentity } from "@jointarp/module/document-path"; +import type { MapPoint, MapRegionConfig, ModuleMap } from "@jointarp/module/map"; +import { + decodeExploration, + distance, + encodeExploration, + explorationGrid, + firstBlocked, + footprintPixels, + fromUnits, + isExplored, + markExplored, + measurePath, + pixelsPerUnit, + pointInPolygon, + pointSegmentDistance, + polylineSegments, + segmentIntersection, + snapToGrid, + squareSegments, + visibilityPolygon, + wallSegments, + type Point, + type Segment, +} from "@jointarp/module/map-geometry"; + +import type { SessionDatabase } from "../storage/session-database"; +import { readAdventureState } from "./adventure-state"; +import type { MapRoomState, MapState, MapTokenState } from "./map-state"; + +/** 队伍角色:文档标识到控制者身份。 */ +export function partyIndex(db: SessionDatabase): Map { + const party = new Map(); + for (const character of readAdventureState(db).party.characters) + if (character.playerId && !character.retired && character.sourcePath) + party.set(documentIdentity(character.sourcePath), character.playerId); + return party; +} + +export function isParty(token: MapTokenState, party: ReadonlyMap): boolean { + return Boolean(token.document && party.has(token.document)); +} + +export function tokensOn(state: MapState, mapId: string): [string, MapTokenState][] { + return Object.entries(state.tokens).filter(([, token]) => token.map === mapId); +} + +export function regionLabel(region: MapRegionConfig): string { + return region.name ?? region.id; +} + +export function regionsAt(map: ModuleMap, point: Point): MapRegionConfig[] { + return map.config.regions.filter((region) => pointInPolygon(point, region.points)); +} + +export function footprint(map: ModuleMap, token: Pick): number { + return footprintPixels(map.config.grid, token.size); +} + +export function movementBlockers(map: ModuleMap, room: MapRoomState): Segment[] { + return [ + ...wallSegments(map.config), + ...map.config.doors + .filter((door) => !room.doors[door.id]?.open) + .map((door) => ({ a: door.from, b: door.to })), + ]; +} + +function visionBlockers( + map: ModuleMap, + room: MapRoomState, + state: MapState, + party: ReadonlyMap, +): Segment[] { + return [ + ...movementBlockers(map, room), + ...tokensOn(state, map.id) + .filter(([, token]) => token.blocksVision && !isParty(token, party)) + .flatMap(([, token]) => squareSegments(token.at, footprint(map, token))), + ]; +} + +export function visionRadius(map: ModuleMap, token: MapTokenState): number | undefined { + const units = token.vision === undefined ? map.config.vision : (token.vision ?? undefined); + return units === undefined ? undefined : units * pixelsPerUnit(map.config.grid); +} + +/** 同图队伍角色各自的可见范围,全队共享。 */ +export function partyVision( + map: ModuleMap, + room: MapRoomState, + state: MapState, + party: ReadonlyMap, +): { readonly token: string; readonly polygon: MapPoint[] }[] { + const blockers = visionBlockers(map, room, state, party); + return tokensOn(state, map.id) + .filter(([, token]) => isParty(token, party)) + .map(([id, token]) => ({ + token: id, + polygon: visibilityPolygon(token.at, blockers, map.config, visionRadius(map, token)), + })); +} + +function samplePoints(map: ModuleMap, token: MapTokenState): Point[] { + const [x, y] = token.at; + // 遮挡视线的物件自身挡住中心,改为检查各边外侧。 + const half = token.blocksVision ? footprint(map, token) / 2 + 2 : footprint(map, token) / 2.5; + return [ + ...(token.blocksVision ? [] : [[x, y] as Point]), + [x - half, y], + [x + half, y], + [x, y - half], + [x, y + half], + ]; +} + +export function visibleTokens( + map: ModuleMap, + state: MapState, + party: ReadonlyMap, + polygons: readonly (readonly Point[])[], +): Set { + const visible = new Set(); + for (const [id, token] of tokensOn(state, map.id)) { + if (isParty(token, party)) visible.add(id); + else if ( + !token.hidden && + samplePoints(map, token).some((point) => + polygons.some((polygon) => pointInPolygon(point, polygon)), + ) + ) + visible.add(id); + } + return visible; +} + +export function explorationBits(map: ModuleMap, room: MapRoomState): Uint8Array { + return decodeExploration(room.explored, explorationGrid(map.config)); +} + +/** 按队伍角色当前视野补充探索记录。 */ +export function exploreCurrentVision( + map: ModuleMap, + state: MapState, + party: ReadonlyMap, +): void { + const room = state.maps[map.id]!; + const grid = explorationGrid(map.config); + const bits = explorationBits(map, room); + let changed = false; + for (const { polygon } of partyVision(map, room, state, party)) + changed = markExplored(bits, grid, polygon) || changed; + if (changed) room.explored = encodeExploration(bits); +} + +/** 沿实际走过的路线揭示沿途视野,不揭示尚未抵达的部分。 */ +export function exploreAlong( + map: ModuleMap, + state: MapState, + party: ReadonlyMap, + tokenId: string, + path: readonly Point[], +): void { + const token = state.tokens[tokenId]!; + if (!isParty(token, party)) return; + const room = state.maps[map.id]!; + const grid = explorationGrid(map.config); + const bits = explorationBits(map, room); + const blockers = visionBlockers(map, room, state, party); + const radius = visionRadius(map, token); + const step = Math.max(grid.cell * 2, footprint(map, token) / 2); + const points = path.length === 1 ? [path[0]!, path[0]!] : path; + let changed = false; + for (let index = 1; index < points.length; index++) { + const a = points[index - 1]!; + const b = points[index]!; + const count = Math.max(1, Math.ceil(distance(a, b) / step)); + for (let sample = 0; sample <= count; sample++) { + const t = sample / count; + const origin: Point = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; + changed = + markExplored(bits, grid, visibilityPolygon(origin, blockers, map.config, radius)) || + changed; + } + } + if (changed) room.explored = encodeExploration(bits); +} + +export type MapSide = + | "center" + | "north" + | "south" + | "east" + | "west" + | "northeast" + | "northwest" + | "southeast" + | "southwest"; + +const sideVectors: Record = { + center: [0, 0], + north: [0, -1], + south: [0, 1], + east: [1, 0], + west: [-1, 0], + northeast: [1, -1], + northwest: [-1, -1], + southeast: [1, 1], + southwest: [-1, 1], +}; +export const mapSides = Object.keys(sideVectors) as MapSide[]; + +export type MapAnchor = + | { readonly start: string } + | { readonly region: string; readonly side?: MapSide } + | { readonly near: string; readonly side?: MapSide } + | { readonly point: Point }; + +function findRegion(map: ModuleMap, name: string): MapRegionConfig { + const region = map.config.regions.find((item) => item.id === name || item.name === name); + if (!region) throw new Error(`地图「${map.config.name}」没有区域「${name}」`); + return region; +} + +export { findRegion }; + +function regionPoint(map: ModuleMap, region: MapRegionConfig, side: MapSide, size: number): Point { + const xs = region.points.map((point) => point[0]); + const ys = region.points.map((point) => point[1]); + const [minX, maxX, minY, maxY] = [ + Math.min(...xs), + Math.max(...xs), + Math.min(...ys), + Math.max(...ys), + ]; + const center: Point = [(minX + maxX) / 2, (minY + maxY) / 2]; + const inset = footprintPixels(map.config.grid, size) / 2; + const vector = sideVectors[side]; + const target: Point = [ + center[0] + vector[0] * Math.max(0, (maxX - minX) / 2 - inset), + center[1] + vector[1] * Math.max(0, (maxY - minY) / 2 - inset), + ]; + // 凹多边形的方位点可能落在区域外,沿中心连线收回到区域内。 + for (let step = 0; step <= 20; step++) { + const t = 1 - step / 20; + const point: Point = [ + center[0] + t * (target[0] - center[0]), + center[1] + t * (target[1] - center[1]), + ]; + if (pointInPolygon(point, region.points)) return point; + } + // 中心也在区域外(如 L 形),取区域内离目标最近、能容下占地的采样点。 + const step = Math.max((maxX - minX) / 64, (maxY - minY) / 64, 1); + const edges = regionSegments(region); + let best: { point: Point; roomy: boolean; gap: number } | undefined; + for (let x = minX + step / 2; x < maxX; x += step) + for (let y = minY + step / 2; y < maxY; y += step) { + const point: Point = [x, y]; + if (!pointInPolygon(point, region.points)) continue; + const roomy = edges.every((edge) => pointSegmentDistance(point, edge) >= inset); + const gap = distance(point, target); + if (!best || (roomy && !best.roomy) || (roomy === best.roomy && gap < best.gap)) + best = { point, roomy, gap }; + } + return best?.point ?? region.points[0]!; +} + +/** 把主持指定的位置解析为像素坐标,方格地图对齐格心。 */ +export function resolveAnchor( + map: ModuleMap, + room: MapRoomState, + state: MapState, + anchor: MapAnchor, + size: number, + self?: string, +): MapPoint { + const grid = map.config.grid; + const snapInside = (point: Point, polygon?: readonly Point[]) => { + const snapped = snapToGrid(grid, point, size); + return !polygon || pointInPolygon(snapped, polygon) + ? snapped + : ([point[0], point[1]] as MapPoint); + }; + if ("start" in anchor) { + const start = map.config.starts.find((item) => item.id === anchor.start); + const entry = start ?? map.config.starts.find((item) => item.name === anchor.start); + if (!entry) throw new Error(`地图「${map.config.name}」没有起点「${anchor.start}」`); + const at = snapInside(entry.at); + return at[0] >= 0 && + at[1] >= 0 && + at[0] <= map.config.width && + at[1] <= map.config.height && + !firstBlocked([entry.at, at], movementBlockers(map, room)) + ? at + : [...entry.at]; + } + if ("point" in anchor) return snapInside(fromUnits(grid, anchor.point)); + if ("region" in anchor) { + const region = findRegion(map, anchor.region); + return snapInside(regionPoint(map, region, anchor.side ?? "center", size), region.points); + } + const target = state.tokens[anchor.near]; + if (!target || target.map !== map.id) + throw new Error(`地图「${map.config.name}」上没有标记「${anchor.near}」`); + const gap = (footprint(map, target) + footprintPixels(grid, size)) / 2; + const blockers = movementBlockers(map, room); + const candidates = ( + anchor.side + ? [anchor.side] + : ([ + "east", + "west", + "south", + "north", + "southeast", + "southwest", + "northeast", + "northwest", + ] as const) + ).map((side) => { + const vector = sideVectors[side]; + const length = Math.hypot(vector[0], vector[1]) || 1; + return snapInside([ + target.at[0] + (vector[0] / length) * gap * (side.length > 5 ? Math.SQRT2 : 1), + target.at[1] + (vector[1] / length) * gap * (side.length > 5 ? Math.SQRT2 : 1), + ]); + }); + const free = candidates.find( + (point) => + !firstBlocked([target.at, point], blockers) && + point[0] >= 0 && + point[1] >= 0 && + point[0] <= map.config.width && + point[1] <= map.config.height && + !overlapping(map, state, point, size, self).length, + ); + return free ?? candidates[0]!; +} + +/** 占地与给定位置重叠的其他标记。 */ +export function overlapping( + map: ModuleMap, + state: MapState, + point: Point, + size: number, + self?: string, +): string[] { + const own = footprintPixels(map.config.grid, size); + return tokensOn(state, map.id) + .filter( + ([id, token]) => + id !== self && distance(token.at, point) < ((footprint(map, token) + own) / 2) * 0.9, + ) + .map(([id]) => id); +} + +class SegmentIndex { + private readonly buckets = new Map(); + constructor( + segments: readonly Segment[], + private readonly size: number, + ) { + for (const segment of segments) + for (const key of this.keys(segment.a, segment.b)) { + let bucket = this.buckets.get(key); + if (!bucket) this.buckets.set(key, (bucket = [])); + bucket.push(segment); + } + } + private keys(a: Point, b: Point): string[] { + const keys: string[] = []; + const [x0, x1] = [ + Math.floor(Math.min(a[0], b[0]) / this.size), + Math.floor(Math.max(a[0], b[0]) / this.size), + ]; + const [y0, y1] = [ + Math.floor(Math.min(a[1], b[1]) / this.size), + Math.floor(Math.max(a[1], b[1]) / this.size), + ]; + for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) keys.push(`${x},${y}`); + return keys; + } + blocked(a: Point, b: Point): boolean { + const seen = new Set(); + const candidates: Segment[] = []; + for (const key of this.keys(a, b)) + for (const segment of this.buckets.get(key) ?? []) + if (!seen.has(segment)) { + seen.add(segment); + candidates.push(segment); + } + return Boolean(firstBlocked([a, b], candidates)); + } +} + +const maxExpansions = 200_000; + +/** 在不穿墙与关闭门的前提下寻找路线,并拉直为尽量少的转折点。 */ +export function findPath( + map: ModuleMap, + room: MapRoomState, + from: Point, + to: Point, +): MapPoint[] | undefined { + const blockers = movementBlockers(map, room); + const grid = explorationGrid(map.config); + const index = new SegmentIndex(blockers, grid.cell * 4); + if (!index.blocked(from, to)) + return [ + [from[0], from[1]], + [to[0], to[1]], + ]; + const cellOf = (point: Point) => + [ + Math.min(grid.columns - 1, Math.max(0, Math.floor(point[0] / grid.cell))), + Math.min(grid.rows - 1, Math.max(0, Math.floor(point[1] / grid.cell))), + ] as const; + const centerOf = (column: number, row: number): Point => [ + (column + 0.5) * grid.cell, + (row + 0.5) * grid.cell, + ]; + const [startColumn, startRow] = cellOf(from); + const [goalColumn, goalRow] = cellOf(to); + const key = (column: number, row: number) => row * grid.columns + column; + const goal = key(goalColumn, goalRow); + const cost = new Map([[key(startColumn, startRow), 0]]); + const parent = new Map(); + const open: { key: number; score: number }[] = [{ key: key(startColumn, startRow), score: 0 }]; + const closed = new Set(); + const position = (value: number): Point => + value === key(startColumn, startRow) + ? from + : centerOf(value % grid.columns, Math.floor(value / grid.columns)); + let expansions = 0; + while (open.length && expansions++ < maxExpansions) { + let best = 0; + for (let item = 1; item < open.length; item++) + if (open[item]!.score < open[best]!.score) best = item; + const current = open.splice(best, 1)[0]!.key; + if (closed.has(current)) continue; + closed.add(current); + if (current === goal) break; + const column = current % grid.columns; + const row = Math.floor(current / grid.columns); + for (let dx = -1; dx <= 1; dx++) + for (let dy = -1; dy <= 1; dy++) { + if (!dx && !dy) continue; + const nextColumn = column + dx; + const nextRow = row + dy; + if (nextColumn < 0 || nextRow < 0 || nextColumn >= grid.columns || nextRow >= grid.rows) + continue; + const next = key(nextColumn, nextRow); + if (closed.has(next)) continue; + const a = position(current); + const b = next === goal ? to : centerOf(nextColumn, nextRow); + if (index.blocked(a, b)) continue; + const tentative = cost.get(current)! + distance(a, b); + if (tentative >= (cost.get(next) ?? Number.POSITIVE_INFINITY)) continue; + cost.set(next, tentative); + parent.set(next, current); + open.push({ key: next, score: tentative + distance(b, to) }); + } + } + if (!closed.has(goal)) return undefined; + const raw: Point[] = [to]; + for (let current = goal; parent.has(current);) { + current = parent.get(current)!; + raw.unshift(position(current)); + } + if (raw[0] !== from) raw.unshift(from); + const smooth: MapPoint[] = [[from[0], from[1]]]; + let anchor = 0; + while (anchor < raw.length - 1) { + let next = raw.length - 1; + while (next > anchor + 1 && index.blocked(raw[anchor]!, raw[next]!)) next--; + smooth.push([raw[next]![0], raw[next]![1]]); + anchor = next; + } + return smooth; +} + +export type RouteEvent = + | { readonly kind: "enter" | "leave"; readonly at: number; readonly region: MapRegionConfig } + | { + readonly kind: "door"; + readonly at: number; + readonly door: string; + readonly open: boolean; + readonly narrow: boolean; + } + | { readonly kind: "unexplored"; readonly at: number } + | { readonly kind: "blocked"; readonly at: number } + | { + readonly kind: "obstacle"; + readonly at: number; + readonly token: string; + readonly blocking: boolean; + }; + +export interface RouteAnalysis { + readonly length: number; + readonly cumulative: readonly number[]; + readonly events: readonly RouteEvent[]; + readonly startRegions: readonly MapRegionConfig[]; + readonly endRegions: readonly MapRegionConfig[]; + readonly endOverlap: readonly string[]; +} + +/** 把路线翻译为区域进出、门、未探索区域与经过的标记,距离按地图单位计。 */ +export function analyzeRoute( + map: ModuleMap, + state: MapState, + tokenId: string, + path: readonly Point[], +): RouteAnalysis { + const room = state.maps[map.id]!; + const token = state.tokens[tokenId]!; + const grid = map.config.grid; + const { cumulative, total } = measurePath(grid, path); + const own = footprint(map, token); + const bits = explorationBits(map, room); + const exploration = explorationGrid(map.config); + const events: RouteEvent[] = []; + const at = (segment: number, t: number) => + cumulative[segment]! + t * (cumulative[segment + 1]! - cumulative[segment]!); + const blocked = firstBlocked(path, wallSegments(map.config)); + if (blocked) events.push({ kind: "blocked", at: at(blocked.segment, blocked.t) }); + const others = tokensOn(state, map.id).filter(([id]) => id !== tokenId); + const reported = new Set(); + for (let index = 1; index < path.length; index++) { + const move: Segment = { a: path[index - 1]!, b: path[index]! }; + for (const door of map.config.doors) { + const t = segmentIntersection(move, { a: door.from, b: door.to }); + if (t === undefined) continue; + events.push({ + kind: "door", + at: at(index - 1, t), + door: door.id, + open: Boolean(room.doors[door.id]?.open), + narrow: distance(door.from, door.to) < own * 0.95, + }); + } + for (const [id, other] of others) { + if (reported.has(id)) continue; + if (pointSegmentDistance(other.at, move) >= ((footprint(map, other) + own) / 2) * 0.9) + continue; + if (distance(other.at, path[path.length - 1]!) < ((footprint(map, other) + own) / 2) * 0.9) + continue; + reported.add(id); + const length = distance(move.a, move.b) || 1; + const t = Math.max( + 0, + Math.min( + 1, + ((other.at[0] - move.a[0]) * (move.b[0] - move.a[0]) + + (other.at[1] - move.a[1]) * (move.b[1] - move.a[1])) / + length ** 2, + ), + ); + events.push({ + kind: "obstacle", + at: at(index - 1, t), + token: id, + blocking: other.blocksMovement, + }); + } + } + const step = pixelsPerUnit(grid) * 0.1; + let inside = new Set(regionsAt(map, path[0]!).map((region) => region.id)); + let unknown = !isExplored(bits, exploration, path[0]!); + for (let index = 1; index < path.length; index++) { + const a = path[index - 1]!; + const b = path[index]!; + const count = Math.max(1, Math.ceil(distance(a, b) / step)); + for (let sample = 1; sample <= count; sample++) { + const t = sample / count; + const point: Point = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; + const here = regionsAt(map, point); + const ids = new Set(here.map((region) => region.id)); + for (const region of map.config.regions) { + if (ids.has(region.id) && !inside.has(region.id)) + events.push({ kind: "enter", at: at(index - 1, t), region }); + if (!ids.has(region.id) && inside.has(region.id)) + events.push({ kind: "leave", at: at(index - 1, t), region }); + } + inside = ids; + if (!unknown && !isExplored(bits, exploration, point)) { + unknown = true; + events.push({ kind: "unexplored", at: at(index - 1, t) }); + } + } + } + events.sort((a, b) => a.at - b.at); + const end = path[path.length - 1]!; + return { + length: total, + cumulative, + events, + startRegions: regionsAt(map, path[0]!), + endRegions: regionsAt(map, end), + endOverlap: overlapping(map, state, end, token.size, tokenId), + }; +} + +export function doorSegments(map: ModuleMap): Segment[] { + return map.config.doors.map((door) => ({ a: door.from, b: door.to })); +} + +export function regionSegments(region: MapRegionConfig): Segment[] { + return polylineSegments([...region.points, region.points[0]!]); +} diff --git a/packages/core/src/node/sessions/map-state.ts b/packages/core/src/node/sessions/map-state.ts new file mode 100644 index 0000000..e6cf701 --- /dev/null +++ b/packages/core/src/node/sessions/map-state.ts @@ -0,0 +1,147 @@ +import { join } from "node:path"; + +import type { ModuleMap } from "@jointarp/module/map"; +import { mapPointSchema } from "@jointarp/module/map"; +import { decodeExploration, explorationGrid } from "@jointarp/module/map-geometry"; +import { z } from "zod"; + +import { assertRegularFile } from "../storage/regular-file"; +import type { SessionDatabase } from "../storage/session-database"; +import { structuredFile } from "../storage/structured-file"; +import { roomDirectoryForDatabase } from "./session-paths"; +import { bumpStateRevision } from "./state-version"; + +const tokenStateSchema = z.strictObject({ + map: z.string().min(1), + at: mapPointSchema, + size: z.number().positive(), + document: z.string().min(1).optional(), + label: z.string().min(1).optional(), + hidden: z.boolean(), + blocksVision: z.boolean(), + blocksMovement: z.boolean(), + /** 覆盖地图默认视距;null 表示不限距离。 */ + vision: z.number().positive().nullable().optional(), +}); +export type MapTokenState = z.infer; + +const mapRoomStateSchema = z.strictObject({ + /** 队伍可以浏览该地图;放入队伍角色或主持揭示后成立。 */ + known: z.boolean(), + explored: z.string(), + doors: z.record(z.string(), z.strictObject({ open: z.boolean(), revealed: z.boolean() })), +}); +export type MapRoomState = z.infer; + +export const mapStateSchema = z.strictObject({ + maps: z.record(z.string(), mapRoomStateSchema), + tokens: z.record(z.string(), tokenStateSchema), + /** 主持已确认的意图路线进度,按距离单位计。 */ + intents: z.record(z.string(), z.strictObject({ progress: z.number().nonnegative() })), +}); +export type MapState = z.infer; + +function mapStateFile(directory: string) { + return structuredFile(join(directory, "map-state.json"), { + validate: (value) => mapStateSchema.parse(value), + fileMode: 0o600, + }); +} + +export function initialMapState(maps: readonly ModuleMap[]): MapState { + const state: MapState = { maps: {}, tokens: {}, intents: {} }; + for (const map of maps) { + state.maps[map.id] = { + known: false, + explored: "", + doors: Object.fromEntries( + map.config.doors.map((door) => [door.id, { open: door.open, revealed: !door.secret }]), + ), + }; + for (const token of map.config.tokens) + state.tokens[token.id] = { + map: map.id, + at: token.at, + size: token.size, + ...(token.document ? { document: token.document } : {}), + ...(token.label ? { label: token.label } : {}), + hidden: token.hidden, + blocksVision: token.blocksVision, + blocksMovement: token.blocksMovement, + }; + } + return state; +} + +/** 模组同步后保留仍然存在的地图、门与标记状态,新地图按初始配置加入。 */ +export function reconcileMapState( + previous: MapState, + maps: readonly ModuleMap[], + documents: ReadonlySet, +): MapState { + const initial = initialMapState(maps); + const next: MapState = { maps: {}, tokens: {}, intents: previous.intents }; + for (const map of maps) { + const before = previous.maps[map.id]; + const fresh = initial.maps[map.id]!; + if (!before) { + next.maps[map.id] = fresh; + for (const [id, token] of Object.entries(initial.tokens)) + if (token.map === map.id && !previous.tokens[id]) next.tokens[id] = token; + continue; + } + let explored = before.explored; + try { + decodeExploration(explored, explorationGrid(map.config)); + } catch { + explored = ""; + } + next.maps[map.id] = { + known: before.known, + explored, + doors: Object.fromEntries( + Object.entries(fresh.doors).map(([id, door]) => [id, before.doors[id] ?? door]), + ), + }; + } + for (const [id, token] of Object.entries(previous.tokens)) { + const map = maps.find((item) => item.id === token.map); + if (!map) continue; + if (token.document && !documents.has(token.document)) + throw new Error(`不能删除地图上仍有标记的文档:${token.document}`); + next.tokens[id] = { + ...token, + at: [ + Math.min(map.config.width, Math.max(0, token.at[0])), + Math.min(map.config.height, Math.max(0, token.at[1])), + ], + }; + } + return next; +} + +export function readMapStateFile(directory: string): MapState { + assertRegularFile(join(directory, "map-state.json")); + return mapStateFile(directory).readSync(); +} + +export function writeMapStateFile(directory: string, state: MapState): void { + mapStateFile(directory).writeSync(state); +} + +/** 仅在尚未发布的冒险 staging 目录初始化。 */ +export function initializeMapState(directory: string, maps: readonly ModuleMap[]): void { + mapStateFile(directory).writeSync(initialMapState(maps)); +} + +export function readMapState(db: SessionDatabase): MapState { + return readMapStateFile(roomDirectoryForDatabase(db)); +} + +/** 调用方持有房间状态锁;提交后推进房间版本以刷新投影。 */ +export function writeMapState(db: SessionDatabase, state: MapState): void { + const directory = roomDirectoryForDatabase(db); + assertRegularFile(join(directory, "map-state.json")); + mapStateFile(directory).writeSync(state); + bumpStateRevision(db); +} diff --git a/packages/core/src/node/sessions/module-sync-recovery.ts b/packages/core/src/node/sessions/module-sync-recovery.ts index f4414c8..beb3723 100644 --- a/packages/core/src/node/sessions/module-sync-recovery.ts +++ b/packages/core/src/node/sessions/module-sync-recovery.ts @@ -33,7 +33,7 @@ export async function recoverModuleSync(directory: string): Promise { rmSync(current, { recursive: true, force: true }); renameSync(previousModule, current); } - for (const name of ["adventure.json", "document-references.json"]) { + for (const name of ["adventure.json", "map-state.json", "document-references.json"]) { const backup = join(transaction, `previous-${name}`); if (existsSync(backup)) { assertRegularFile(backup); diff --git a/packages/core/src/node/sessions/module-sync.ts b/packages/core/src/node/sessions/module-sync.ts index f0ad149..abf4702 100644 --- a/packages/core/src/node/sessions/module-sync.ts +++ b/packages/core/src/node/sessions/module-sync.ts @@ -35,6 +35,7 @@ import { readGameDocuments } from "./game-document-source"; import { forgetGameDocumentViews, readGameDocumentSnapshot } from "./game-document-views"; import { listGameFileRecords } from "./game-file-index"; import { layerPath, readOverlayDocument } from "./game-overlay"; +import { readMapStateFile, reconcileMapState, writeMapStateFile } from "./map-state"; import { copyModule, directoryExists } from "./module-copy"; import { moduleSyncDirectory, moduleSyncJournal, recoverModuleSync } from "./module-sync-recovery"; import { readAdventure } from "./room-storage"; @@ -201,6 +202,7 @@ async function validateCandidate( ): Promise<{ module: FrozenModule; characters: ReturnType["party"]["characters"]; + identities: Set; }> { const module = await loadFrozenModule(join(candidate, "module")); if (!module.types.length || !module.documents.length) throw new Error("模组没有可用于游戏的文档"); @@ -313,7 +315,11 @@ async function validateCandidate( initializeCharacters(db); await readGameDocumentSnapshot(db, game); await projectEntities(db); - return { module, characters: readAdventure(candidate).party.characters }; + return { + module, + characters: readAdventure(candidate).party.characters, + identities: new Set(documents.map((document) => documentIdentity(document.path))), + }; } finally { db.close(); forgetFrozenModule(join(candidate, "module")); @@ -351,6 +357,11 @@ export async function syncModule(root: string, roomId: string) { { flag: "wx", mode: 0o600 }, ); const validated = await validateCandidate(candidate, previous); + const nextMapState = reconcileMapState( + readMapStateFile(directory), + validated.module.maps, + validated.identities, + ); const metadata = await loadModuleMetadata(join(candidate, "module")); // 发布阶段同步执行,房间笔记与设置的同步保存不会插入备份和提交之间。 const adventure = readAdventure(directory); @@ -368,6 +379,11 @@ export async function syncModule(root: string, roomId: string) { readFileSync(join(directory, "adventure.json")), { flag: "wx", mode: 0o600 }, ); + writeFileSync( + join(transaction, "previous-map-state.json"), + readFileSync(join(directory, "map-state.json")), + { flag: "wx", mode: 0o600 }, + ); if (hadIndex) writeFileSync(join(transaction, "previous-document-references.json"), readFileSync(index), { flag: "wx", @@ -377,6 +393,7 @@ export async function syncModule(root: string, roomId: string) { flag: "wx", mode: 0o600, }); + writeMapStateFile(candidate, nextMapState); const journal = moduleSyncJournal(directory); writeFileAtomicSync(journal, JSON.stringify({ phase: "prepared", hadIndex }), { mode: 0o600, @@ -385,6 +402,7 @@ export async function syncModule(root: string, roomId: string) { renameSync(join(directory, "module"), join(transaction, "previous-module")); renameSync(join(candidate, "module"), join(directory, "module")); renameSync(join(candidate, "next-adventure.json"), join(directory, "adventure.json")); + renameSync(join(candidate, "map-state.json"), join(directory, "map-state.json")); renameSync(join(candidate, "document-references.json"), index); writeFileAtomicSync(journal, JSON.stringify({ phase: "committed", hadIndex }), { mode: 0o600, diff --git a/packages/core/src/node/sessions/session-store.ts b/packages/core/src/node/sessions/session-store.ts index f3ee3b5..4077e8a 100644 --- a/packages/core/src/node/sessions/session-store.ts +++ b/packages/core/src/node/sessions/session-store.ts @@ -36,11 +36,14 @@ import { forgetFrozenModule, frozenModule, loadFrozenModule, + loadValidatedMaps, setFrozenModule, } from "./frozen-module"; import { resolveGameDocumentPath } from "./game-document-path"; import { gameDocumentViews, readGameDocumentSnapshot } from "./game-state"; import { initializeLaunch } from "./launch-db"; +import { mapResources } from "./map-projection"; +import { initializeMapState } from "./map-state"; import { copyModule, directoryExists } from "./module-copy"; import { saveModuleSource } from "./module-sync"; import { recoverModuleSync, hasModuleSyncJournal } from "./module-sync-recovery"; @@ -166,6 +169,7 @@ export async function createSession( if (!documentTypes.length || !documents.length) throw new Error("模组没有可用于开局的文档"); const invalid = documents.find((document) => !document.valid); if (invalid) throw new Error(`请先修复模组文档 ${invalid.path}:${invalid.error}`); + const maps = await loadValidatedMaps(moduleCopy, documents); const room: GameRoom = { id, name, @@ -176,13 +180,14 @@ export async function createSession( }; initializeAdventure(staging, room); initializeRoomSettings(staging, defaults); + initializeMapState(staging, maps); await saveModuleSource(staging, resolve(modulePath)); const db = new SessionDatabase(join(staging, "session.sqlite")); try { await db.migrate(); associateSessionDirectory(db, staging); retainRoomResources(db, staging); - setFrozenModule(db, { types: documentTypes, documents, launch }); + setFrozenModule(db, { types: documentTypes, documents, maps, launch }); db.sqlite.exec("BEGIN"); beginAdventureEdit(db); initializeCharacters(db); @@ -371,6 +376,7 @@ export async function loadSessionModuleResources( ...session, documentTypes: frozenModule(db).types, launchConfig, + maps: mapResources(frozenModule(db).maps), baseline: await projectRoomBaseline(db), }; } finally { diff --git a/packages/core/src/shared/game.ts b/packages/core/src/shared/game.ts index 689ae7c..ff66fb6 100644 --- a/packages/core/src/shared/game.ts +++ b/packages/core/src/shared/game.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import { diceDataSchema } from "./dice"; import { identityIdSchema } from "./identity"; import { launchActionSchema } from "./launch"; +import { movementIntentInputSchema, movementIntentSchema } from "./map"; import { mentionTargetSchema, mentionReplyLimitSchema, mentionsSchema } from "./mentions"; import { ROOM_PROTOCOL_VERSION, roomStateFrameSchema, type RoomLaunchState } from "./room-state"; @@ -128,6 +129,7 @@ export const hostInputBatchSchema = z.object({ playerId: identityIdSchema, characterName: z.string().optional(), text: z.string(), + movement: z.string().optional(), }), ) .min(1), @@ -140,6 +142,8 @@ export const messageSchema = z.discriminatedUnion("kind", [ text: z.string(), /** 仅聊天,不作为行动裁定;合法点名主持时可唤起主持场外回应。 */ chatOnly: z.boolean(), + /** 随行动提交的移动意图卡;实际结果由主持确认后体现在地图上。 */ + movement: movementIntentSchema.optional(), }), messageBase.extend({ kind: z.literal("card"), card: cardDataSchema }), messageBase.extend({ @@ -279,11 +283,14 @@ const roomNotificationSchema = z.discriminatedUnion("type", [ ]); export type RoomNotification = z.infer; const room = z.object({ roomId: z.string().uuid() }); -const sendSchema = room.extend({ - clientMessageId: z.string().uuid(), - text: z.string().trim().min(1).max(4000), - chatOnly: z.boolean(), -}); +const sendSchema = room + .extend({ + clientMessageId: z.string().uuid(), + text: z.string().trim().max(4000), + chatOnly: z.boolean(), + movement: movementIntentInputSchema.optional(), + }) + .refine((input) => input.text || input.movement, { message: "消息不能为空", path: ["text"] }); export type SendInput = z.infer; export const gameContract = { room: { diff --git a/packages/core/src/shared/map.ts b/packages/core/src/shared/map.ts new file mode 100644 index 0000000..eadc5be --- /dev/null +++ b/packages/core/src/shared/map.ts @@ -0,0 +1,71 @@ +import type { MapGrid, MapPoint } from "@jointarp/module/map"; +import { mapPointSchema } from "@jointarp/module/map"; +import { z } from "zod"; + +/** 玩家随行动消息提交的移动意图;起点由主机在接收时按标记当前位置记录。 */ +export const movementIntentInputSchema = z.strictObject({ + token: z.string().trim().min(1).max(200), + map: z.string().trim().min(1).max(200), + waypoints: z.array(mapPointSchema).min(1).max(50), +}); +export type MovementIntentInput = z.infer; + +export const movementIntentSchema = movementIntentInputSchema.extend({ + from: mapPointSchema, + /** 已知区域内的预估距离;终点位于未探索区域时只表示方向,不给距离。 */ + length: z.number().nonnegative().nullable(), + unit: z.string().min(1), + explore: z.boolean(), +}); +export type MovementIntent = z.infer; + +/** 玩家可见的地图静态资料;不含标记初始位置、起点、区域及未揭示的秘门。 */ +export interface MapResource { + readonly id: string; + readonly name: string; + readonly description?: string; + readonly image: string; + readonly path: string; + readonly width: number; + readonly height: number; + readonly grid: MapGrid; + readonly walls: readonly (readonly MapPoint[])[]; +} + +export interface MapTokenView { + readonly id: string; + readonly document?: string; + readonly label?: string; + readonly at: MapPoint; + readonly size: number; + readonly party: boolean; + /** 控制该角色的玩家或队友身份。 */ + readonly playerId?: string; +} + +export interface MapDoorView { + readonly id: string; + readonly from: MapPoint; + readonly to: MapPoint; + readonly open: boolean; +} + +export interface MapView { + readonly parent?: string; + readonly id: string; + /** 已探索格子的位图,按 explorationGrid 排列并以 Base64 编码。 */ + readonly explored: string; + /** 队伍当前可见范围,每名队伍角色一个多边形。 */ + readonly visible: readonly (readonly MapPoint[])[]; + readonly doors: readonly MapDoorView[]; + /** 尚未揭示的秘门,以不带标识的墙段出现。 */ + readonly barriers: readonly (readonly [MapPoint, MapPoint])[]; + readonly tokens: readonly MapTokenView[]; +} + +/** 按全队视野投影的地图区段;只包含队伍已知的地图。 */ +export interface MapSection { + readonly maps: readonly MapView[]; + /** 主持已按意图执行的距离,键为携带意图的消息。 */ + readonly intents: Readonly>; +} diff --git a/packages/core/src/shared/room-state.ts b/packages/core/src/shared/room-state.ts index 4d42037..f434405 100644 --- a/packages/core/src/shared/room-state.ts +++ b/packages/core/src/shared/room-state.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import { identityIdSchema } from "./identity"; import type { LaunchState } from "./launch"; +import type { MapResource, MapSection } from "./map"; import type { GameRoom, GameSession } from "./session"; import type { SessionMetrics } from "./session-metrics"; @@ -45,6 +46,7 @@ export interface RoomBaseline { } export interface SessionModuleResources extends GameSession { launchConfig?: LaunchConfig; + maps: MapResource[]; baseline: RoomBaseline; } /** 相对模组基线的累计覆盖;Map 项删除表示恢复基线。 */ @@ -89,6 +91,7 @@ export interface RoomSections { metrics: SessionMetrics; chatActivity: ChatActivitySnapshot; companionVersion: string; + map: MapSection; } export interface RoomReplica { sections: RoomSections; diff --git a/packages/core/src/testing/room-replica.ts b/packages/core/src/testing/room-replica.ts index edf8d01..ce7e73d 100644 --- a/packages/core/src/testing/room-replica.ts +++ b/packages/core/src/testing/room-replica.ts @@ -33,6 +33,7 @@ export function createRoomReplica(): RoomReplica { }, launch: null, companionVersion: "initial", + map: { maps: [], intents: {} }, chatActivity: { running: null, queued: null }, metrics: { host: { diff --git a/packages/module-cli/src/commands.ts b/packages/module-cli/src/commands.ts index 8003a69..506805c 100644 --- a/packages/module-cli/src/commands.ts +++ b/packages/module-cli/src/commands.ts @@ -21,7 +21,7 @@ export const cliHelp = `TARP 模组开发工具 tarp --version tarp --help -validate 校验配置、文档、引用、计算字段、阅读页及开局,不修改模组。 +validate 校验配置、文档、引用、计算字段、阅读页、地图及开局,不修改模组。 preview 在桌面应用中打开模组,可直接预览 Git 工作区。 --json 输出结构化校验结果,供开发 Agent 使用。 @@ -115,7 +115,7 @@ export async function runModuleCommand( }; return { exitCode: result.status === "success" ? 0 : 1, - stdout: `${result.status === "success" ? "校验通过" : "校验失败"}:${result.name ?? result.path}\n${result.documentTypeCount} 种文档类型 · ${result.documentCount} 份文档 · ${result.pageCount} 个阅读页\n${result.issues.map((issue) => `[${issue.kind}] ${issue.path}:${issue.message}\n`).join("")}`, + stdout: `${result.status === "success" ? "校验通过" : "校验失败"}:${result.name ?? result.path}\n${result.documentTypeCount} 种文档类型 · ${result.documentCount} 份文档 · ${result.pageCount} 个阅读页 · ${result.mapCount} 张地图\n${result.issues.map((issue) => `[${issue.kind}] ${issue.path}:${issue.message}\n`).join("")}`, stderr: "", }; } diff --git a/packages/module/src/node/document-types.ts b/packages/module/src/node/document-types.ts index 89b21b4..eeac2b9 100644 --- a/packages/module/src/node/document-types.ts +++ b/packages/module/src/node/document-types.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import type { DocumentField, DocumentType } from "../schema/document-type"; import { validateDocumentLayout, validateDocumentType } from "../schema/document-type"; +import { mapDirectory } from "../schema/map"; import { parseConfig } from "./config-file"; import { loadLayoutTemplates } from "./layout-templates"; @@ -58,6 +59,8 @@ export async function loadDocumentTypes(libraryPath: string): Promise entry.name.startsWith(`${mapDirectory}.fields.`)); + if (reserved) throw new Error(`.types/${reserved.name}:${mapDirectory} 目录保留给地图配置`); const seen = new Set(); for (const entry of [...files, ...layoutFiles]) { const stem = entry.name.replace(/\.(json|toml)$/, ""); diff --git a/packages/module/src/node/module-documents.ts b/packages/module/src/node/module-documents.ts index e97236d..cdb2bf1 100644 --- a/packages/module/src/node/module-documents.ts +++ b/packages/module/src/node/module-documents.ts @@ -5,6 +5,7 @@ import { resolveModuleDocuments, type ParsedModuleDocument } from "../schema/doc import { documentFormat, documentIdentity, documentTypeId } from "../schema/document-path"; import type { DocumentContentType, DocumentType } from "../schema/document-type"; import { documentMetadataSchema, validateDocumentValues } from "../schema/document-type"; +import { mapDirectory } from "../schema/map"; import type { ModuleDocument, RawModuleDocument } from "../schema/module-document"; import { parseDocumentContent } from "./document-codec"; import { loadModuleMetadata } from "./module-metadata"; @@ -13,13 +14,14 @@ import { modulePagePath } from "./module-pages"; const ignoredDirectories = new Set(["node_modules"]); const ignoredFiles = new Set(["AGENTS.md", "module.json", "module.toml"]); -async function findContentFiles(directory: string): Promise { +async function findContentFiles(directory: string, root = true): Promise { const files: string[] = []; for (const entry of await readdir(directory, { withFileTypes: true })) { if (entry.name.startsWith(".") || ignoredFiles.has(entry.name)) continue; const path = join(directory, entry.name); + if (root && entry.name === mapDirectory) continue; if (entry.isDirectory() && !ignoredDirectories.has(entry.name)) { - files.push(...(await findContentFiles(path))); + files.push(...(await findContentFiles(path, false))); } else if (entry.isFile() && /\.(json|toml|md)$/iu.test(entry.name)) { files.push(path); } diff --git a/packages/module/src/node/module-maps.test.ts b/packages/module/src/node/module-maps.test.ts new file mode 100644 index 0000000..c4d0839 --- /dev/null +++ b/packages/module/src/node/module-maps.test.ts @@ -0,0 +1,99 @@ +import { onTestFinished, test } from "bun:test"; +import { strict as assert } from "node:assert"; +import { rm } from "node:fs/promises"; +import { join } from "node:path"; + +import { writeTestFile as writeFile } from "@jointarp/module/testing/files"; +import { createTestModule } from "@jointarp/module/testing/test-module"; + +import { loadDocumentTypes } from "./document-types"; +import { loadModuleDocuments } from "./module-documents"; +import { loadModuleMaps } from "./module-maps"; +import { validateModule } from "./validate-module"; + +test("maps 目录作为地图配置读取,不被当作游戏文档,配置错误按地图报告", async () => { + const fixture = await createTestModule(); + onTestFinished(fixture.cleanup); + const root = fixture.modulePath; + const [map] = await loadModuleMaps(root); + assert.equal(map?.id, "测试场景"); + assert.equal(map?.config.grid.type === "square" && map.config.grid.diagonal, "equal"); + assert.deepEqual( + map?.config.doors.map((door) => [door.id, door.open, door.secret]), + [ + ["中门", false, false], + ["暗门", false, true], + ], + ); + assert.deepEqual( + map?.config.regions.map((region) => [region.id, region.secret]), + [ + ["西室", false], + ["东室", false], + ["暗室", true], + ], + ); + const documents = await loadModuleDocuments(root, await loadDocumentTypes(root)); + assert.ok(documents.every((document) => !document.path.startsWith("maps/"))); + const valid = await validateModule(root); + assert.equal(valid.status, "success", JSON.stringify(valid.issues)); + assert.equal(valid.mapCount, 1); + + await writeFile( + join(root, "maps/坏图.json"), + JSON.stringify({ + name: "坏图", + image: "maps/图片/不存在.png", + width: 100, + height: 100, + grid: { type: "none", pixelsPerUnit: 10, unit: "米" }, + tokens: [{ id: "幽灵", document: "人物/不存在", at: [10, 10] }], + }), + ); + await writeFile( + join(root, "maps/越界.json"), + JSON.stringify({ + name: "越界", + image: "maps/图片/测试场景.svg", + width: 100, + height: 100, + grid: { type: "none", pixelsPerUnit: 10, unit: "米" }, + walls: [ + { + points: [ + [0, 0], + [200, 0], + ], + }, + ], + }), + ); + const invalid = await validateModule(root); + const messages = invalid.issues + .filter((issue) => issue.kind === "map") + .map((issue) => issue.message); + assert.ok(messages.some((message) => /人物\/不存在/u.test(message))); + assert.ok(messages.some((message) => /找不到底图/u.test(message))); + assert.ok(messages.some((message) => /超出底图范围/u.test(message))); + await assert.rejects(loadModuleMaps(root), /越界/u); + + await rm(join(root, "maps"), { recursive: true }); + await writeFile(join(root, ".types/maps.fields.json"), JSON.stringify({ fields: {} })); + await assert.rejects(loadDocumentTypes(root), /保留给地图配置/u); +}); + +test("父子地图支持多级目录引用,拒绝缺失上级和循环", async () => { + const fixture = await createTestModule(); + onTestFinished(fixture.cleanup); + const root = fixture.modulePath; + const [base] = await loadModuleMaps(root); + const put = (id: string, parent: string) => + writeFile(join(root, "maps", id + ".json"), JSON.stringify({ ...base!.config, parent })); + await put("城/宅邸", base!.id); + await put("地下室", "城/宅邸"); + assert.equal((await loadModuleMaps(root)).length, 3); + await put("城/宅邸", "地下室"); + await assert.rejects(loadModuleMaps(root), /循环/); + await put("城/宅邸", "失踪"); + await assert.rejects(loadModuleMaps(root), /上级地图不存在/); +}); diff --git a/packages/module/src/node/module-maps.ts b/packages/module/src/node/module-maps.ts new file mode 100644 index 0000000..5bfd4d9 --- /dev/null +++ b/packages/module/src/node/module-maps.ts @@ -0,0 +1,123 @@ +import { lstat, readFile, readdir } from "node:fs/promises"; +import { join } from "node:path"; + +import { + mapConfigSchema, + mapDirectory, + mapLineage, + validateMapDestination, + type ModuleMap, +} from "../schema/map"; +import { parseConfig } from "./config-file"; + +export interface ModuleMapIssue { + readonly path: string; + readonly message: string; +} + +async function findMapFiles(root: string, directory: string): Promise { + const files: string[] = []; + for (const entry of await readdir(join(root, directory), { withFileTypes: true })) { + if (entry.name.startsWith(".")) continue; + const path = `${directory}/${entry.name}`; + if (entry.isDirectory()) files.push(...(await findMapFiles(root, path))); + else if (entry.isFile() && /\.(json|toml)$/iu.test(entry.name)) files.push(path); + } + return files; +} + +async function hasMapDirectory(root: string): Promise { + try { + const stat = await lstat(join(root, mapDirectory)); + if (!stat.isDirectory()) throw new Error(`${mapDirectory} 必须是目录`); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +/** 读取 maps/ 中的地图配置;单张地图错误不影响其他地图的结果。 */ +export async function loadModuleMapEntries( + root: string, +): Promise<{ maps: ModuleMap[]; issues: ModuleMapIssue[] }> { + const maps: ModuleMap[] = []; + const issues: ModuleMapIssue[] = []; + if (!(await hasMapDirectory(root))) return { maps, issues }; + const files = (await findMapFiles(root, mapDirectory)).sort(); + const counts = new Map(); + const idOf = (path: string) => + path.slice(mapDirectory.length + 1).replace(/\.(json|toml)$/iu, ""); + for (const path of files) counts.set(idOf(path), (counts.get(idOf(path)) ?? 0) + 1); + for (const path of files) { + const id = idOf(path); + try { + if ((counts.get(id) ?? 0) > 1) throw new Error("同名 JSON 与 TOML 地图不能同时存在"); + const parsed = mapConfigSchema.safeParse( + parseConfig(await readFile(join(root, path), "utf8"), path), + ); + if (!parsed.success) { + const issue = parsed.error.issues[0]; + throw new Error(`${issue?.path.join(".") || "地图"}:${issue?.message ?? "格式无效"}`); + } + maps.push({ id, path, config: parsed.data }); + } catch (error) { + issues.push({ path, message: error instanceof Error ? error.message : String(error) }); + } + } + const byId = new Map(maps.map((map) => [map.id, map])); + for (const map of maps) { + try { + for (const link of map.config.connections) + validateMapDestination(map.id, link, byId.get(link.map)?.config); + mapLineage(map.id, (id) => { + const entry = byId.get(id); + if (!entry) throw new Error(`上级地图不存在或无效:${id}`); + return entry.config.parent; + }); + } catch (error) { + issues.push({ + path: map.path, + message: String(error instanceof Error ? error.message : error), + }); + } + } + return { maps, issues }; +} + +/** 运行时加载要求全部地图有效。 */ +export async function loadModuleMaps(root: string): Promise { + const { maps, issues } = await loadModuleMapEntries(root); + const issue = issues[0]; + if (issue) throw new Error(`地图 ${issue.path} 无效:${issue.message}`); + return maps; +} + +/** 地图引用的资料须存在;底图须是模组内图片。 */ +export async function validateModuleMapReferences( + root: string, + maps: readonly ModuleMap[], + documentIdentities: ReadonlySet, +): Promise { + const issues: ModuleMapIssue[] = []; + for (const map of maps) { + for (const item of [...map.config.tokens, ...map.config.regions]) + if (item.document && !documentIdentities.has(item.document)) + issues.push({ path: map.path, message: `${item.id} 关联的资料不存在:${item.document}` }); + const image = map.config.image.replaceAll("\\", "/"); + if (!/\.(avif|gif|jpe?g|png|svg|webp)$/iu.test(image)) { + issues.push({ path: map.path, message: `底图不是支持的图片格式:${map.config.image}` }); + continue; + } + if (image.startsWith("/") || image.split("/").includes("..")) { + issues.push({ path: map.path, message: `底图必须位于模组目录内:${map.config.image}` }); + continue; + } + try { + if (!(await lstat(join(root, image))).isFile()) throw new Error(); + } catch { + issues.push({ path: map.path, message: `找不到底图:${map.config.image}` }); + } + } + return issues; +} diff --git a/packages/module/src/node/validate-module.ts b/packages/module/src/node/validate-module.ts index 55f16ea..7b5d252 100644 --- a/packages/module/src/node/validate-module.ts +++ b/packages/module/src/node/validate-module.ts @@ -11,11 +11,20 @@ import { parseDocumentContent } from "./document-codec"; import { loadDocumentTypes } from "./document-types"; import { validateInitialGameState } from "./game-state-validation"; import { loadModuleDocuments } from "./module-documents"; +import { loadModuleMapEntries, validateModuleMapReferences } from "./module-maps"; import { loadModuleMetadata } from "./module-metadata"; import { loadModulePages } from "./module-pages"; export interface ModuleValidationIssue { - readonly kind: "metadata" | "types" | "document" | "reference" | "page" | "launch" | "empty"; + readonly kind: + | "metadata" + | "types" + | "document" + | "reference" + | "page" + | "launch" + | "map" + | "empty"; readonly path: string; readonly message: string; } @@ -27,6 +36,7 @@ export interface ModuleValidationResult { readonly documentTypeCount: number; readonly documentCount: number; readonly pageCount: number; + readonly mapCount: number; readonly issues: readonly ModuleValidationIssue[]; } @@ -50,10 +60,27 @@ export async function validateModule(directory: string): Promise document.valid) + .map((document) => documentIdentity(document.path)), + ); + for (const issue of [ + ...mapIssues, + ...(await validateModuleMapReferences(path, maps, identities)), + ]) + add("map", issue.path, issue.message); + } catch (error) { + add("map", "maps", error); + } const byIdentity = new Map( documents.map((document) => [documentIdentity(document.path), document]), ); @@ -128,6 +155,7 @@ export async function validateModule(directory: string): Promise ({ + type: "square", + size: 100, + distance: 5, + unit: "尺", + diagonal, + offset: [0, 0], +}); + +test("地图几何按计距规则测量、对齐格心并判断墙体阻挡与视野", () => { + const diagonal = [ + [50, 50], + [250, 250], + [350, 350], + ] as const; + assert.equal(measurePath(square("equal"), diagonal).total, 15); + // 交替斜向在整条路线上连续计数:第二格斜向记两格。 + assert.equal(measurePath(square("alternate"), diagonal).total, 20); + assert.ok( + Math.abs( + measurePath(square("euclidean"), [ + [0, 0], + [300, 400], + ]).total - 25, + ) < 1e-9, + ); + assert.equal( + measurePath({ type: "none", pixelsPerUnit: 50, unit: "米" }, [ + [0, 0], + [100, 0], + ]).total, + 2, + ); + const line = [ + [0, 0], + [200, 0], + [200, 200], + ] as const; + assert.deepEqual(pointAtDistance(line, measurePath(square("equal"), line), 15).point, [200, 100]); + + assert.deepEqual(snapToGrid(square("equal"), [130, 270]), [150, 250]); + assert.deepEqual(snapToGrid(square("equal"), [130, 270], 2), [100, 300]); + + const wall = { a: [500, 0] as const, b: [500, 600] as const }; + assert.deepEqual( + firstBlocked( + [ + [100, 300], + [900, 300], + ], + [wall], + ), + { segment: 0, t: 0.5 }, + ); + assert.equal( + firstBlocked( + [ + [100, 300], + [400, 300], + ], + [wall], + ), + undefined, + ); + // 紧贴墙体出发不算阻挡,擦过墙端点算阻挡。 + assert.equal( + firstBlocked( + [ + [500, 300], + [100, 300], + ], + [wall], + ), + undefined, + ); + assert.ok( + firstBlocked( + [ + [400, -100], + [600, 100], + ], + [wall], + ), + ); + + const bounds = { width: 1000, height: 600 }; + const visible = visibilityPolygon([100, 300], [wall], bounds); + assert.ok(pointInPolygon([450, 100], visible)); + assert.ok(!pointInPolygon([700, 300], visible)); + const limited = visibilityPolygon([100, 300], [], bounds, 200); + assert.ok(pointInPolygon([250, 300], limited)); + assert.ok(!pointInPolygon([350, 300], limited)); +}); + +test("探索记录按格心标记并可编码往返", () => { + const config = { grid: square("equal"), width: 1000, height: 600 }; + const grid = explorationGrid(config); + assert.deepEqual(grid, { cell: 50, columns: 20, rows: 12 }); + const bits = createExploration(grid); + const room = [ + [0, 0], + [500, 0], + [500, 600], + [0, 600], + ] as const; + assert.equal(markExplored(bits, grid, room), true); + assert.equal(markExplored(bits, grid, room), false); + const decoded = decodeExploration(encodeExploration(bits), grid); + assert.ok(isExplored(decoded, grid, [480, 580])); + assert.ok(!isExplored(decoded, grid, [520, 20])); + assert.throws(() => decodeExploration(btoa("x"), grid), /尺寸不一致/); + // 超大底图限制总格数。 + const huge = explorationGrid({ grid: square("equal"), width: 20000, height: 20000 }); + assert.ok(huge.columns * huge.rows <= 512 * 512 + 2 * 512 + 1); +}); diff --git a/packages/module/src/schema/map-geometry.ts b/packages/module/src/schema/map-geometry.ts new file mode 100644 index 0000000..92f7a45 --- /dev/null +++ b/packages/module/src/schema/map-geometry.ts @@ -0,0 +1,346 @@ +import type { MapConfig, MapGrid, MapPoint } from "./map"; + +export type Point = readonly [number, number]; +export interface Segment { + readonly a: Point; + readonly b: Point; +} + +const epsilon = 1e-6; + +/** 每个距离单位对应的底图像素数。 */ +export function pixelsPerUnit(grid: MapGrid): number { + return grid.type === "square" ? grid.size / grid.distance : grid.pixelsPerUnit; +} + +/** 占地边长(格数或距离单位)对应的像素边长。 */ +export function footprintPixels(grid: MapGrid, size: number): number { + return grid.type === "square" ? grid.size * size : grid.pixelsPerUnit * size; +} + +export function toUnits(grid: MapGrid, point: Point): [number, number] { + const scale = pixelsPerUnit(grid); + return [round(point[0] / scale), round(point[1] / scale)]; +} + +export function fromUnits(grid: MapGrid, point: Point): MapPoint { + const scale = pixelsPerUnit(grid); + return [point[0] * scale, point[1] * scale]; +} + +export function round(value: number, digits = 1): number { + const factor = 10 ** digits; + return Math.round(value * factor) / factor; +} + +/** 方格地图把标记中心对齐到格心;占地为偶数格时对齐到格线交点。 */ +export function snapToGrid(grid: MapGrid, point: Point, size = 1): MapPoint { + if (grid.type !== "square") return [point[0], point[1]]; + const even = Math.round(size) % 2 === 0; + const snap = (value: number, offset: number) => { + const cell = (value - offset) / grid.size; + return (even ? Math.round(cell) : Math.floor(cell) + 0.5) * grid.size + offset; + }; + return [snap(point[0], grid.offset[0]), snap(point[1], grid.offset[1])]; +} + +export function polylineSegments(points: readonly Point[]): Segment[] { + const segments: Segment[] = []; + for (let index = 1; index < points.length; index++) + segments.push({ a: points[index - 1]!, b: points[index]! }); + return segments; +} + +export function wallSegments(config: Pick): Segment[] { + return config.walls.flatMap((wall) => polylineSegments(wall.points)); +} + +/** 正方形占地的四条边,用于明确设置遮挡的物件。 */ +export function squareSegments(center: Point, side: number): Segment[] { + const half = side / 2; + const [x, y] = center; + const corners: Point[] = [ + [x - half, y - half], + [x + half, y - half], + [x + half, y + half], + [x - half, y + half], + [x - half, y - half], + ]; + return polylineSegments(corners); +} + +function cross(o: Point, a: Point, b: Point): number { + return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); +} + +export function distance(a: Point, b: Point): number { + return Math.hypot(a[0] - b[0], a[1] - b[1]); +} + +export function pointSegmentDistance(point: Point, segment: Segment): number { + const { a, b } = segment; + const length = (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2; + if (length < epsilon) return distance(point, a); + const t = Math.max( + 0, + Math.min(1, ((point[0] - a[0]) * (b[0] - a[0]) + (point[1] - a[1]) * (b[1] - a[1])) / length), + ); + return distance(point, [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]); +} + +/** 两条线段相交时返回第一条线段上的参数 t。 */ +export function segmentIntersection(first: Segment, second: Segment): number | undefined { + const r = [first.b[0] - first.a[0], first.b[1] - first.a[1]]; + const s = [second.b[0] - second.a[0], second.b[1] - second.a[1]]; + const denominator = r[0]! * s[1]! - r[1]! * s[0]!; + const qp = [second.a[0] - first.a[0], second.a[1] - first.a[1]]; + if (Math.abs(denominator) < epsilon) { + if (Math.abs(cross(first.a, first.b, second.a)) > epsilon) return undefined; + // 共线时按重叠区间的起点处理。 + const length = r[0]! ** 2 + r[1]! ** 2; + if (length < epsilon) return undefined; + const t0 = (qp[0]! * r[0]! + qp[1]! * r[1]!) / length; + const t1 = t0 + (s[0]! * r[0]! + s[1]! * r[1]!) / length; + const start = Math.max(0, Math.min(t0, t1)); + return start <= Math.min(1, Math.max(t0, t1)) ? start : undefined; + } + const t = (qp[0]! * s[1]! - qp[1]! * s[0]!) / denominator; + const u = (qp[0]! * r[1]! - qp[1]! * r[0]!) / denominator; + return t >= -epsilon && t <= 1 + epsilon && u >= -epsilon && u <= 1 + epsilon + ? Math.max(0, Math.min(1, t)) + : undefined; +} + +/** 路线中第一处碰到阻挡线段的位置;擦过墙角同样视为阻挡。 */ +export function firstBlocked( + path: readonly Point[], + blockers: readonly Segment[], +): { readonly segment: number; readonly t: number } | undefined { + for (let index = 1; index < path.length; index++) { + const move = { a: path[index - 1]!, b: path[index]! }; + let hit: number | undefined; + for (const blocker of blockers) { + const t = segmentIntersection(move, blocker); + if (t === undefined || (index === 1 && t < epsilon)) continue; + if (hit === undefined || t < hit) hit = t; + } + if (hit !== undefined) return { segment: index - 1, t: hit }; + } + return undefined; +} + +export interface PathMeasure { + /** 各路线点处的累计距离,按距离单位计。 */ + readonly cumulative: readonly number[]; + readonly total: number; +} + +/** 按地图计距方式测量路线;交替斜向计距在整条路线上连续计数。 */ +export function measurePath(grid: MapGrid, path: readonly Point[]): PathMeasure { + const cumulative = [0]; + let total = 0; + let diagonals = 0; + for (let index = 1; index < path.length; index++) { + const a = path[index - 1]!; + const b = path[index]!; + let cost: number; + if (grid.type === "none") { + cost = distance(a, b) / grid.pixelsPerUnit; + } else { + const dx = Math.abs(b[0] - a[0]) / grid.size; + const dy = Math.abs(b[1] - a[1]) / grid.size; + const diagonal = Math.min(dx, dy); + const straight = Math.max(dx, dy) - diagonal; + if (grid.diagonal === "euclidean") cost = Math.hypot(dx, dy); + else if (grid.diagonal === "equal") cost = straight + diagonal; + else { + const extra = Math.floor((diagonals + diagonal) / 2) - Math.floor(diagonals / 2); + diagonals += diagonal; + cost = straight + diagonal + extra; + } + cost *= grid.distance; + } + total += cost; + cumulative.push(total); + } + return { cumulative, total }; +} + +/** 路线上累计距离达到指定值的位置。 */ +export function pointAtDistance( + path: readonly Point[], + measure: PathMeasure, + target: number, +): { readonly point: MapPoint; readonly segment: number } { + const clamped = Math.max(0, Math.min(measure.total, target)); + for (let index = 1; index < path.length; index++) { + const start = measure.cumulative[index - 1]!; + const end = measure.cumulative[index]!; + if (clamped <= end + epsilon || index === path.length - 1) { + const t = end - start < epsilon ? 1 : Math.min(1, (clamped - start) / (end - start)); + const a = path[index - 1]!; + const b = path[index]!; + return { point: [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])], segment: index - 1 }; + } + } + const first = path[0]!; + return { point: [first[0], first[1]], segment: 0 }; +} + +export function pointInPolygon(point: Point, polygon: readonly Point[]): boolean { + let inside = false; + for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index++) { + const a = polygon[index]!; + const b = polygon[previous]!; + if ( + a[1] > point[1] !== b[1] > point[1] && + point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0] + ) + inside = !inside; + } + return inside; +} + +const circleRays = 72; + +/** 从视点出发、被线段遮挡的可见多边形;radius 省略时只受底图边界限制。 */ +export function visibilityPolygon( + origin: Point, + blockers: readonly Segment[], + bounds: { readonly width: number; readonly height: number }, + radius?: number, +): MapPoint[] { + const { width, height } = bounds; + const edges = polylineSegments([ + [0, 0], + [width, 0], + [width, height], + [0, height], + [0, 0], + ]); + const segments = [ + ...(radius === undefined + ? blockers + : blockers.filter((segment) => pointSegmentDistance(origin, segment) <= radius)), + ...edges, + ]; + const angles: number[] = []; + for (const segment of segments) + for (const point of [segment.a, segment.b]) { + const angle = Math.atan2(point[1] - origin[1], point[0] - origin[0]); + angles.push(angle - 1e-4, angle, angle + 1e-4); + } + if (radius !== undefined) + for (let index = 0; index < circleRays; index++) + angles.push(-Math.PI + (index * 2 * Math.PI) / circleRays); + angles.sort((a, b) => a - b); + const polygon: MapPoint[] = []; + let previous = Number.NaN; + for (const angle of angles) { + if (Math.abs(angle - previous) < 1e-9) continue; + previous = angle; + const direction: Point = [Math.cos(angle), Math.sin(angle)]; + let nearest = Number.POSITIVE_INFINITY; + for (const segment of segments) { + const hit = rayHit(origin, direction, segment); + if (hit !== undefined && hit < nearest) nearest = hit; + } + if (radius !== undefined) nearest = Math.min(nearest, radius); + if (!Number.isFinite(nearest)) continue; + polygon.push([origin[0] + direction[0] * nearest, origin[1] + direction[1] * nearest]); + } + return polygon; +} + +function rayHit(origin: Point, direction: Point, segment: Segment): number | undefined { + const s = [segment.b[0] - segment.a[0], segment.b[1] - segment.a[1]] as const; + const denominator = direction[0] * s[1] - direction[1] * s[0]; + if (Math.abs(denominator) < epsilon) return undefined; + const qp = [segment.a[0] - origin[0], segment.a[1] - origin[1]] as const; + const t = (qp[0] * s[1] - qp[1] * s[0]) / denominator; + const u = (qp[0] * direction[1] - qp[1] * direction[0]) / denominator; + return t >= 0 && u >= -epsilon && u <= 1 + epsilon ? t : undefined; +} + +/** 探索记录的栅格;格边长随底图比例尺变化,并限制总格数。 */ +export interface ExplorationGrid { + readonly cell: number; + readonly columns: number; + readonly rows: number; +} + +const maxExplorationCells = 512 * 512; + +export function explorationGrid( + config: Pick, +): ExplorationGrid { + let cell = config.grid.type === "square" ? config.grid.size / 2 : config.grid.pixelsPerUnit / 2; + cell = Math.max(cell, Math.sqrt((config.width * config.height) / maxExplorationCells)); + return { + cell, + columns: Math.ceil(config.width / cell), + rows: Math.ceil(config.height / cell), + }; +} + +export function createExploration(grid: ExplorationGrid): Uint8Array { + return new Uint8Array(Math.ceil((grid.columns * grid.rows) / 8)); +} + +export function isExplored(bits: Uint8Array, grid: ExplorationGrid, point: Point): boolean { + const column = Math.floor(point[0] / grid.cell); + const row = Math.floor(point[1] / grid.cell); + if (column < 0 || row < 0 || column >= grid.columns || row >= grid.rows) return false; + const index = row * grid.columns + column; + return ((bits[index >> 3] ?? 0) & (1 << (index & 7))) !== 0; +} + +/** 把格心落在多边形内的格子记为已探索;返回是否有新格子。 */ +export function markExplored( + bits: Uint8Array, + grid: ExplorationGrid, + polygon: readonly Point[], +): boolean { + if (polygon.length < 3) return false; + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + for (const [x, y] of polygon) { + minX = Math.min(minX, x); + minY = Math.min(minY, y); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + } + let changed = false; + const firstColumn = Math.max(0, Math.floor(minX / grid.cell)); + const lastColumn = Math.min(grid.columns - 1, Math.floor(maxX / grid.cell)); + const firstRow = Math.max(0, Math.floor(minY / grid.cell)); + const lastRow = Math.min(grid.rows - 1, Math.floor(maxY / grid.cell)); + for (let row = firstRow; row <= lastRow; row++) + for (let column = firstColumn; column <= lastColumn; column++) { + const index = row * grid.columns + column; + const mask = 1 << (index & 7); + if ((bits[index >> 3]! & mask) !== 0) continue; + if (!pointInPolygon([(column + 0.5) * grid.cell, (row + 0.5) * grid.cell], polygon)) continue; + bits[index >> 3]! |= mask; + changed = true; + } + return changed; +} + +export function encodeExploration(bits: Uint8Array): string { + let binary = ""; + for (let index = 0; index < bits.length; index += 0x8000) + binary += String.fromCharCode(...bits.subarray(index, index + 0x8000)); + return btoa(binary); +} + +export function decodeExploration(value: string, grid: ExplorationGrid): Uint8Array { + const bits = createExploration(grid); + if (!value) return bits; + const binary = atob(value); + if (binary.length !== bits.length) throw new Error("探索记录与地图尺寸不一致"); + for (let index = 0; index < binary.length; index++) bits[index] = binary.charCodeAt(index); + return bits; +} diff --git a/packages/module/src/schema/map.ts b/packages/module/src/schema/map.ts new file mode 100644 index 0000000..1a54055 --- /dev/null +++ b/packages/module/src/schema/map.ts @@ -0,0 +1,221 @@ +import { z } from "zod"; + +import { documentIdentity } from "./document-path"; + +/** 地图坐标使用底图像素,原点在左上角。 */ +export const mapPointSchema = z.tuple([z.number().finite(), z.number().finite()]); +export type MapPoint = z.infer; + +const mapIdSchema = z + .string() + .trim() + .min(1) + .max(64) + .regex(/^[^\s/\\#?]+$/u, "标识不能包含空白、斜杠、# 或 ?"); + +const squareGridSchema = z + .object({ + type: z.literal("square"), + /** 每格的像素边长。 */ + size: z.number().positive(), + /** 每格代表的距离。 */ + distance: z.number().positive(), + unit: z.string().trim().min(1).max(16), + /** equal:斜向一格按一格计;alternate:斜向交替按一格、两格计;euclidean:按直线距离。 */ + diagonal: z.enum(["equal", "alternate", "euclidean"]).default("equal"), + offset: mapPointSchema.default([0, 0]), + }) + .strict(); + +const gridlessSchema = z + .object({ + type: z.literal("none"), + /** 每个距离单位的像素数。 */ + pixelsPerUnit: z.number().positive(), + unit: z.string().trim().min(1).max(16), + }) + .strict(); + +export const mapGridSchema = z.discriminatedUnion("type", [squareGridSchema, gridlessSchema]); +export type MapGrid = z.infer; + +const wallSchema = z + .object({ + points: z.array(mapPointSchema).min(2), + }) + .strict(); + +const doorSchema = z + .object({ + id: mapIdSchema, + from: mapPointSchema, + to: mapPointSchema, + open: z.boolean().default(false), + /** 秘门在主持揭示前对玩家按墙处理。 */ + secret: z.boolean().default(false), + }) + .strict(); + +/** 命名区域为主持提供空间语义;幕后区域只向主持描述。 */ +const regionSchema = z + .object({ + id: mapIdSchema, + name: z.string().trim().min(1).max(40).optional(), + points: z.array(mapPointSchema).min(3), + document: z.string().trim().min(1).transform(documentIdentity).optional(), + secret: z.boolean().default(false), + note: z.string().trim().min(1).max(500).optional(), + }) + .strict(); + +export const mapStartSchema = z + .object({ + id: mapIdSchema, + name: z.string().trim().min(1).max(40), + at: mapPointSchema, + }) + .strict(); + +export const mapConnectionSchema = z.strictObject({ + from: mapIdSchema, + map: z.string().min(1), + to: mapIdSchema, + oneWay: z.boolean().default(false), +}); +export type MapConnection = z.infer; + +const tokenSchema = z + .object({ + id: mapIdSchema, + /** 关联已有资料时复用名称与头像;不关联时为简单物件标记。 */ + document: z.string().trim().min(1).transform(documentIdentity).optional(), + label: z.string().trim().min(1).max(40).optional(), + at: mapPointSchema, + /** 占地边长,按格数(无网格时按距离单位)计。 */ + size: z.number().positive().max(20).default(1), + hidden: z.boolean().default(false), + /** 明确设置后才遮挡视线。 */ + blocksVision: z.boolean().default(false), + /** 只用于规划提示与主持提醒,不强制拒绝移动。 */ + blocksMovement: z.boolean().default(false), + }) + .strict() + .refine((token) => Boolean(token.document || token.label), { + message: "标记需要关联资料 document 或填写 label", + }); + +export const mapConfigSchema = z + .object({ + name: z.string().trim().min(1).max(80), + description: z.string().trim().min(1).max(1000).optional(), + parent: z.string().min(1).optional(), + /** 模组内图片路径。 */ + image: z.string().trim().min(1), + width: z.number().int().positive().max(20000), + height: z.number().int().positive().max(20000), + grid: mapGridSchema, + /** 角色默认视距,按距离单位计;省略时不限距离,只受墙和门遮挡。 */ + vision: z.number().positive().optional(), + walls: z.array(wallSchema).max(5000).default([]), + doors: z.array(doorSchema).max(1000).default([]), + regions: z.array(regionSchema).max(500).default([]), + connections: z.array(mapConnectionSchema).max(500).default([]), + starts: z.array(mapStartSchema).max(100).default([]), + tokens: z.array(tokenSchema).max(1000).default([]), + }) + .strict() + .superRefine((map, context) => { + const inside = (point: MapPoint, path: (string | number)[]) => { + if (point[0] < 0 || point[1] < 0 || point[0] > map.width || point[1] > map.height) + context.addIssue({ code: "custom", path, message: "坐标超出底图范围" }); + }; + map.walls.forEach((wall, index) => + wall.points.forEach((point, pointIndex) => + inside(point, ["walls", index, "points", pointIndex]), + ), + ); + const ids = new Set(); + const unique = (id: string, path: (string | number)[]) => { + if (ids.has(id)) context.addIssue({ code: "custom", path, message: `标识重复:${id}` }); + ids.add(id); + }; + map.doors.forEach((door, index) => { + unique(door.id, ["doors", index, "id"]); + inside(door.from, ["doors", index, "from"]); + inside(door.to, ["doors", index, "to"]); + }); + map.regions.forEach((region, index) => { + unique(region.id, ["regions", index, "id"]); + region.points.forEach((point, pointIndex) => + inside(point, ["regions", index, "points", pointIndex]), + ); + }); + map.starts.forEach((start, index) => { + unique(start.id, ["starts", index, "id"]); + inside(start.at, ["starts", index, "at"]); + }); + const routes = new Set(); + map.connections.forEach((link, index) => { + const key = JSON.stringify([link.from, link.map, link.to]); + if (routes.has(key)) + context.addIssue({ + code: "custom", + path: ["connections", index], + message: "出入口连接重复", + }); + routes.add(key); + if (!map.starts.some((start) => start.id === link.from)) + context.addIssue({ + code: "custom", + path: ["connections", index, "from"], + message: "出发起点不存在", + }); + }); + map.tokens.forEach((token, index) => { + unique(token.id, ["tokens", index, "id"]); + inside(token.at, ["tokens", index, "at"]); + }); + }); + +export type MapConfig = z.infer; +export type MapDoorConfig = MapConfig["doors"][number]; +export type MapTokenConfig = MapConfig["tokens"][number]; +export type MapRegionConfig = MapConfig["regions"][number]; + +/** 模组 maps/ 目录中的一张地图;id 为去掉 maps/ 前缀与扩展名的相对路径。 */ +export interface ModuleMap { + readonly id: string; + readonly path: string; + readonly config: MapConfig; +} + +export const mapDirectory = "maps"; + +/** 从当前地图向上遍历到根;查找函数对不存在的地图报错。 */ +export function mapLineage(id: string, parentOf: (id: string) => string | undefined) { + const chain = new Set(); + let current: string | undefined = id; + while (current !== undefined) { + if (chain.has(current)) throw new Error(`上级地图形成循环:${[...chain, current].join(" → ")}`); + chain.add(current); + current = parentOf(current); + } + return [...chain].reverse(); +} + +export function validateMapDestination(source: string, link: MapConnection, target?: MapConfig) { + if (source === link.map) throw new Error("跨图连接的两端必须在不同地图"); + if (!target?.starts.some((start) => start.id === link.to)) + throw new Error(`找不到目标地图或起点:${link.map} / ${link.to}`); +} + +/** 双向连接只需在一端配置。 */ +export function exitsFrom(maps: readonly ModuleMap[], id: string) { + return maps.flatMap((owner) => + (owner.config.connections ?? []).flatMap((link) => { + if (owner.id === id) return [{ from: link.from, map: link.map, to: link.to }]; + if (link.map === id && !link.oneWay) return [{ from: link.to, map: owner.id, to: link.from }]; + return []; + }), + ); +} diff --git "a/packages/module/test-fixtures/platform/maps/\345\233\276\347\211\207/\346\265\213\350\257\225\345\234\272\346\231\257.svg" "b/packages/module/test-fixtures/platform/maps/\345\233\276\347\211\207/\346\265\213\350\257\225\345\234\272\346\231\257.svg" new file mode 100644 index 0000000..9e53e5c --- /dev/null +++ "b/packages/module/test-fixtures/platform/maps/\345\233\276\347\211\207/\346\265\213\350\257\225\345\234\272\346\231\257.svg" @@ -0,0 +1 @@ + diff --git "a/packages/module/test-fixtures/platform/maps/\346\265\213\350\257\225\345\234\272\346\231\257.toml" "b/packages/module/test-fixtures/platform/maps/\346\265\213\350\257\225\345\234\272\346\231\257.toml" new file mode 100644 index 0000000..903c73b --- /dev/null +++ "b/packages/module/test-fixtures/platform/maps/\346\265\213\350\257\225\345\234\272\346\231\257.toml" @@ -0,0 +1,68 @@ +name = "测试场景" +description = "两间相邻房间,用于视野、门与秘门测试。" +image = "maps/图片/测试场景.svg" +width = 1000 +height = 600 +vision = 60 + +[grid] +type = "square" +size = 100 +distance = 5 +unit = "尺" + +[[walls]] +points = [[0, 0], [1000, 0], [1000, 600], [0, 600], [0, 0]] + +[[walls]] +points = [[500, 0], [500, 200]] + +[[walls]] +points = [[500, 300], [500, 600]] + +[[walls]] +points = [[800, 0], [800, 400]] + +[[walls]] +points = [[800, 500], [800, 600]] + +[[doors]] +id = "中门" +from = [500, 200] +to = [500, 300] + +[[doors]] +id = "暗门" +from = [800, 400] +to = [800, 500] +secret = true + +[[starts]] +id = "入口" +name = "西侧入口" +at = [150, 250] + +[[tokens]] +id = "守望者" +document = "人物/守望者" +at = [650, 250] + +[[tokens]] +id = "木箱" +label = "木箱" +at = [250, 150] + +[[regions]] +id = "西室" +points = [[0, 0], [500, 0], [500, 600], [0, 600]] +document = "地点/集合点" + +[[regions]] +id = "东室" +points = [[500, 0], [800, 0], [800, 600], [500, 600]] + +[[regions]] +id = "暗室" +points = [[800, 0], [1000, 0], [1000, 600], [800, 600]] +secret = true +note = "秘门后的隐藏房间"