## Map import CLI (DESIGN 11.1 "Map import", 3.3 tiles, 13 M4; issue #79, pulled forward from M6). ## ## Offline, no browser: slice one source image into `tile_size` PNG tiles under ## `/tiles//v/` (origin at the world origin, names `_.png`) and ## update the one v1 scene row's `w`, `h`, `tile_size` and `art_version`. The server keeps its ## in-memory scene from startup (4.1), so it must be stopped for an import and restarted after it; ## the state-dir lock of 3.2/11.1 is what makes that non-negotiable (the same lock `gm-key --new` ## honours). A re-import for a scene that already has art grows `art_version` so browsers never ## serve a tile from a stale cache (3.3). ## ## Decoding is delegated to ImageMagick (`magick` from the root devbox, `imagemagick`), the one ## reviewed source of PNG/WebP codecs here: a 16384 px source is far too large for a whole-image ## decoder in this process (Q16-HDRI stores it in ImageMagick's *disk-backed* pixel cache under the ## explicit `-limit memory/-limit map` below, so RSS stays bounded). No Nim or npm image dependency ## is added; the FIXED stack of DESIGN 2 is unchanged, and `tools/` keeps its built-ins-only rule ## (TESTING 10.4). The tile layout the gate parses is produced here, not by the prototype's ## deterministic fixture generator. import std/[math, options, os, osproc, streams, strutils, times] import db_connector/db_sqlite import config, db, instancelock, world const ImportedFormats* = ["PNG", "WEBP"] ## Source formats accepted by the CLI. Output tiles are always PNG (the gate's URL suffix). ImportUsage* = """fff-vtt import --image= [options] Slice a map image into the scene's tile tree and register the scene dimensions. Options: --image= Source image (PNG or WebP). Required. --tile-size= Tile edge in px (default: the scene's current tile_size). Must be a positive multiple of the scene's explored cell (32 px), so 64 is the designed fallback. --scene= Target scene. v1 has exactly one scene, id 1. --state-dir= Directory holding state.db and tiles (default: run). A missing or empty directory is created and migrated through the server's startup path, so an import works before the first serve. The server must be stopped: the state-dir lock is refused (exit 3), like gm-key --new. Tiles land in /tiles//v/_.png, origin at the world origin. A re-import for a scene that already has art grows art_version and writes a new v directory; the server serves the new scene and tiles after a restart. The CLI never touches a status, wall or token; create those through the GM panels/wire after the import. """ type ImportArgs = object cfg: Config image: string scene: int tileSize: int hasTileSize: bool proc failImport(msg: string, code: int): int = stderr.writeLine "fff-vtt import: " & msg code proc parseImportArgs(raw: seq[string], a: var ImportArgs): int = ## Recognise the import-only flags, hand everything else (state-dir, help) to `parseConfig`, so ## the state-dir key behaves exactly as it does for the server and `gm-key`. a.scene = DefaultSceneId var rest: seq[string] var i = 0 while i < raw.len: let arg = raw[i] inc i case arg of "--image": if i >= raw.len: return failImport("--image: missing value", 2) a.image = raw[i]; inc i of "--tile-size": if i >= raw.len: return failImport("--tile-size: missing value", 2) a.hasTileSize = true try: a.tileSize = parseInt(raw[i].strip) except ValueError: return failImport("--tile-size: expected a whole number of px", 2) inc i of "--scene": if i >= raw.len: return failImport("--scene: missing value", 2) try: a.scene = parseInt(raw[i].strip) except ValueError: return failImport("--scene: expected a whole number", 2) inc i else: if arg.startsWith("--image="): a.image = arg["--image=".len .. ^1] elif arg.startsWith("--tile-size="): a.hasTileSize = true try: a.tileSize = parseInt(arg["--tile-size=".len .. ^1].strip) except ValueError: return failImport("--tile-size: expected a whole number of px", 2) elif arg.startsWith("--scene="): try: a.scene = parseInt(arg["--scene=".len .. ^1].strip) except ValueError: return failImport("--scene: expected a whole number", 2) else: rest.add arg try: a.cfg = parseConfig(rest) except ConfigError as e: return failImport(e.msg, 2) 0 proc runMagick(args: seq[string], workingDir = ""): tuple[status: int, output: string] = ## One ImageMagick call, no shell. `poStdErrToStdOut` folds its diagnostics into the message a ## failed import prints; malformed output never reaches a path or a SQL statement. A missing ## `magick` is reported like any other decode failure instead of escaping as a stack trace. try: let p = startProcess("magick", workingDir = workingDir, args = args, options = {poUsePath, poStdErrToStdOut}) try: result.output = p.outputStream.readAll() result.status = p.waitForExit() finally: p.close() except OSError as e: result.status = -1 result.output = "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox" proc lastLine(s: string): string = var lines = s.strip.splitLines if lines.len == 0: "" else: lines[^1] proc removeTemp(dir: string) = ## The slice temp dir holds only files (ImageMagick `+adjoin`); no recursive delete is needed. if not dirExists(dir): return for kind, path in walkDir(dir): if kind in {pcFile, pcLinkToFile}: try: removeFile(path) except OSError: discard try: removeDir(dir) except OSError: discard proc dirHasFiles(dir: string): bool = if not dirExists(dir): return false for kind, path in walkDir(dir): if kind in {pcFile, pcLinkToFile}: return true false proc runImport*(rawArgs: seq[string]): int = var a: ImportArgs let parseRc = parseImportArgs(rawArgs, a) if parseRc != 0: return parseRc if a.cfg.help: stdout.write ImportUsage return 0 if a.image.len == 0: return failImport("--image is required\n\n" & ImportUsage, 2) if a.scene != DefaultSceneId: return failImport("scene " & $a.scene & ": v1 has exactly one scene, id " & $DefaultSceneId, 2) # Validate the source before touching the state dir: an error creates nothing. if not fileExists(a.image): return failImport("source image \"" & a.image & "\" does not exist", 1) let imagePath = expandFilename(a.image) # Identify: dimensions and one format only. Multi-frame input (animated PNG/WebP) would break the # one-tile-per-coordinate tree, so it is refused rather than silently importing frame zero. let ident = runMagick(@["identify", "-ping", "-format", "%w %h %m", imagePath]) if ident.status != 0: return failImport("cannot read image \"" & a.image & "\": " & lastLine(ident.output), 1) let parts = ident.output.splitWhitespace if parts.len != 3: return failImport("multi-frame image \"" & a.image & "\" is not supported; import a single-frame PNG or WebP", 2) if parts[2].toUpperAscii notin ImportedFormats: return failImport("unsupported format " & parts[2] & ": the source must be PNG or WebP (tiles are always PNG)", 2) var imgW, imgH: int try: imgW = parseInt(parts[0]) imgH = parseInt(parts[1]) except ValueError: return failImport("cannot read image dimensions from \"" & a.image & "\"", 1) if imgW <= 0 or imgH <= 0: return failImport("image \"" & a.image & "\" has no pixels", 1) # A fresh or empty state dir is the normal case (#82): create and migrate through the same # startup path as the server, under the same state-dir lock. The lock is taken before the DB is # created, so a running server can never race an import. if not dirExists(a.cfg.stateDir): try: createDir(a.cfg.stateDir) except OSError as e: return failImport("cannot create state dir \"" & a.cfg.stateDir & "\": " & e.msg, 1) var lock = tryAcquire(a.cfg.stateDir) if not lock.held: return failImport("the server is running on \"" & a.cfg.stateDir & "\" (state-dir lock held); stop it first, then restart it after the import", 3) var conn: DbConn var applied: int try: let opened = openMigratedDatabase(a.cfg.dbPath) conn = opened.db applied = opened.applied except CatchableError as e: return failImport("cannot open or migrate " & a.cfg.dbPath & ": " & e.msg, 1) defer: close(conn) if applied > 0: stderr.writeLine "fff-vtt import: created/migrated " & a.cfg.dbPath & " (" & $applied & " schema step" & (if applied == 1: "" else: "s") & ")" let loaded = loadScene(conn) if loaded.isNone: return failImport("state.db has no scene " & $DefaultSceneId & " after migration; the database is inconsistent", 1) let scene = loaded.get var tileSize = if a.hasTileSize: a.tileSize else: scene.tileSize if tileSize <= 0: return failImport("--tile-size must be positive, got " & $tileSize, 2) if tileSize mod scene.cell != 0: return failImport("--tile-size " & $tileSize & " is not a multiple of the scene's explored cell " & $scene.cell & " px; the gate requires tile_size % cell == 0 (64 is the designed fallback)", 2) let cols = int(ceil(float(imgW) / float(tileSize))) let rows = int(ceil(float(imgH) / float(tileSize))) if cols > 99999 or rows > 99999: return failImport("tile grid " & $cols & "x" & $rows & " exceeds the URL's 5-digit coordinates", 2) # A scene that already has tiles for its current version must not answer from a stale cache: # every re-import grows art_version and writes the next v directory (DESIGN 3.3). let tileRoot = a.cfg.stateDir / "tiles" / $scene.id var version = scene.artVersion if dirHasFiles(tileRoot / ("v" & $version)): inc version let finalDir = tileRoot / ("v" & $version) if dirExists(finalDir): if dirHasFiles(finalDir): return failImport("tile directory " & finalDir & " already exists and is not empty", 1) try: removeDir(finalDir) except OSError as e: return failImport("cannot clear empty tile directory " & finalDir & ": " & e.msg, 1) if not dirExists(tileRoot): try: createDir(tileRoot) except OSError as e: return failImport("cannot create " & tileRoot & ": " & e.msg, 1) let tempDir = tileRoot / (".import-" & $getCurrentProcessId() & "-" & $int(epochTime())) removeTemp(tempDir) try: createDir(tempDir) except OSError as e: return failImport("cannot create temporary tile directory " & tempDir & ": " & e.msg, 1) # Memory-sane slicing (DESIGN 11.1): 256 MiB heap and a 512 MiB map cap push ImageMagick's pixel # cache to disk, so a 16384 px source never needs a whole-image buffer in RAM. `-crop` with # `+repage` emits tiles in row-major order; `tile_%d.png` is renamed below to the gate's exact # `_.png` spelling (no leading zeros). let crop = $tileSize & "x" & $tileSize let sliced = runMagick(@["-limit", "memory", "256MiB", "-limit", "map", "512MiB", imagePath, "-crop", crop, "+repage", "+adjoin", "tile_%d.png"], tempDir) if sliced.status != 0: removeTemp(tempDir) return failImport("magick failed to slice \"" & a.image & "\": " & lastLine(sliced.output), 1) for i in 0 ..< cols * rows: let src = tempDir / ("tile_" & $i & ".png") if not fileExists(src): removeTemp(tempDir) return failImport("magick produced no tile " & $i & " of " & $(cols * rows) & " (source " & $imgW & "x" & $imgH & ", tile " & $tileSize & ")", 1) let x = i mod cols let y = i div cols try: moveFile(src, tempDir / ($x & "_" & $y & ".png")) except OSError as e: removeTemp(tempDir) return failImport("cannot name tile " & $x & "_" & $y & ": " & e.msg, 1) for kind, path in walkDir(tempDir): if kind in {pcFile, pcLinkToFile} and path.extractFilename.startsWith("tile_"): removeTemp(tempDir) return failImport("magick produced more than the " & $(cols * rows) & " expected tiles", 1) try: moveDir(tempDir, finalDir) except OSError as e: removeTemp(tempDir) return failImport("cannot publish " & finalDir & ": " & e.msg, 1) # One FULL authoring transaction (Q12), like every other persisted authoring write. If the row # update fails, the freshly published directory is removed so a failed import changes nothing. try: authoringTransaction(conn): conn.exec(sql"""UPDATE scene SET w = ?, h = ?, tile_size = ?, art_version = ? WHERE id = ?""", $imgW, $imgH, $tileSize, $version, scene.id) except CatchableError as e: removeTemp(finalDir) return failImport("cannot update the scene row: " & e.msg, 1) stdout.writeLine "imported " & a.image & ": " & $imgW & "x" & $imgH & " px, tile " & $tileSize & " px, " & $cols & "x" & $rows & " tiles -> " & finalDir & " (art_version " & $version & ")" stdout.flushFile() 0