The one-shot `magick -crop 64x64 +adjoin` built an image list of all 65,536 tiles; ImageMagick's
memory/map limits are per image, so the attempt held 4.3 GB of source cache plus every tile cache and
died after minutes with "Too many open files" at 1023 fds, having published nothing.
Slice by streaming instead: one disk-cache-backed decode of the source to raw samples, the CLI reads
it one tile row at a time, and a pool of 8 magick children cuts one row band each. Live caches and
fds are bounded by the worker count, never by the tile count. Progress goes to stderr ("rows 37/256,
tiles 9472/65536") and failures quote the image, row band and magick's own message. Atomicity is
unchanged: temp dir then rename, scene row only on success, same lock and exit codes.
Measured on the owner's 16384x16384 map at 64 px: 19 s, 391 MB peak RSS, 10 fds, 65,536 tiles (was
~5 min then failure). The tile pixels are identical to the old crop (proven tile by tile in
tools/import.test.mjs); PNG bytes can differ because the encoder now sees raw samples.
New gate: devbox run import-scale (16384/64 under ulimit -n 256) writes results/import-scale.log;
devbox run test keeps the fast fixtures and skips it.
467 lines
21 KiB
Nim
467 lines
21 KiB
Nim
## 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
|
|
## `<state>/tiles/<scene>/v<art_version>/` (origin at the world origin, names `<x>_<y>.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. A single `-crop 64x64 +adjoin` over the source materialises all 65,536
|
|
## tiles in one image list, and `-limit memory/-limit map` are *per image*, so that attempt needed
|
|
## 4.3 GB RSS and 65k file descriptors and died with "Too many open files" (#83). Slicing therefore
|
|
## streams: one `magick` decodes the source to raw samples (its own pixel cache is disk-backed under
|
|
## the `-limit` flags below, so RSS stays ~50 MB), this process reads it one tile row at a time and
|
|
## hands that band to a small pool of `magick` children, each of which only ever holds a single row
|
|
## band. Live caches and fds are bounded by the worker count, never by the tile count. 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).
|
|
SliceCacheLimit = "32MiB"
|
|
## Per-image pixel-cache RAM cap for every `magick` of the slice. Large images spill to
|
|
## ImageMagick's disk cache instead of growing RSS (#83).
|
|
MaxSliceWorkers = 8
|
|
## Child `magick` count of the slice: half a 16-core box, and never more than the band count.
|
|
MaxBandBytes = 32 * 1024 * 1024
|
|
## Largest tile row handed to one child. A row band above this (a very large `--tile-size` on a
|
|
## wide source) falls back to the one-shot crop, whose image list is then small by construction.
|
|
ImportUsage* = """fff-vtt import --image=<path> [options]
|
|
|
|
Slice a map image into the scene's tile tree and register the scene dimensions.
|
|
|
|
Options:
|
|
--image=<path> Source image (PNG or WebP). Required.
|
|
--tile-size=<px> 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=<id> Target scene. v1 has exactly one scene, id 1.
|
|
--state-dir=<path> 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 <state-dir>/tiles/<scene>/v<art_version>/<x>_<y>.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]
|
|
|
|
type
|
|
SlicePlan = object
|
|
## How the decoded source is handed to the children as raw samples: the channel set follows
|
|
## the source's own type, so a plain RGB image still produces plain RGB tiles and an image with
|
|
## alpha keeps its alpha channel (pixel-identical tiles to the one-shot crop; PNG bytes can
|
|
## differ because the encoder sees raw samples instead of a decoded image's properties).
|
|
rawSpec: string
|
|
channels: int
|
|
sampleDepth: int
|
|
|
|
proc slicePlan(imgType: string, srcDepth: int): SlicePlan =
|
|
let t = imgType.toLowerAscii
|
|
let alpha = t.endsWith("alpha")
|
|
let gray = t.startsWith("gray") or t.startsWith("bilevel")
|
|
result.sampleDepth = if srcDepth > 8: 16 else: 8
|
|
result.channels = (if gray: 1 else: 3) + (if alpha: 1 else: 0)
|
|
result.rawSpec =
|
|
if gray: (if alpha: "graya:" else: "gray:")
|
|
else: (if alpha: "rgba:" else: "rgb:")
|
|
|
|
proc removeBands(dir: string) =
|
|
## Row bands are one-shot scratch files next to the tile temp dir: files first, then the dir.
|
|
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 sliceRows(imagePath, tempDir: string, imgW, imgH, tileSize, cols, rows: int,
|
|
plan: SlicePlan): tuple[rc: int, message: string] =
|
|
## Stream the source once and cut one tile row (a band) per child `magick`, so live pixel caches
|
|
## stay bounded by the worker count and the fd count does not follow the tile count (#83). The
|
|
## decoder's own cache is disk-backed (`SliceCacheLimit`), a band file is a few MB, and every
|
|
## child only ever holds one band. Tiles are written as `tile_<global index>.png`; the caller
|
|
## renames them to the `<x>_<y>.png` gate grammar.
|
|
let sampleBytes = plan.sampleDepth div 8
|
|
let bandStride = imgW * plan.channels * sampleBytes
|
|
let workers = max(1, min(MaxSliceWorkers, min(countProcessors() div 2, rows)))
|
|
let total = cols * rows
|
|
let progressStep = max(1, rows div 20)
|
|
let bandDir = tempDir & "-bands"
|
|
|
|
stderr.writeLine "fff-vtt import: slicing " & $imgW & "x" & $imgH & " into " & $total &
|
|
" tiles at " & $tileSize & " px (" & $workers & " workers)"
|
|
removeBands(bandDir)
|
|
try: createDir(bandDir)
|
|
except OSError as e:
|
|
return (1, "cannot create scratch directory " & bandDir & ": " & e.msg)
|
|
|
|
let decode = try:
|
|
startProcess("magick", options = {poUsePath}, args = @[
|
|
"-limit", "memory", SliceCacheLimit, "-limit", "map", SliceCacheLimit,
|
|
imagePath, "-depth", $plan.sampleDepth, plan.rawSpec & "-"])
|
|
except OSError as e:
|
|
removeBands(bandDir)
|
|
return (1, "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox")
|
|
|
|
var buf = newString(bandStride * tileSize)
|
|
var busy: seq[tuple[p: Process, row: int]]
|
|
|
|
proc reap(w: var tuple[p: Process, row: int]): int =
|
|
## Reap one child (its stderr already went straight to ours) and drop its band file.
|
|
result = try: w.p.waitForExit() except CatchableError: -1
|
|
w.p.close()
|
|
try: removeFile(bandDir / ("band_" & $w.row & ".raw"))
|
|
except OSError: discard
|
|
|
|
proc abortChildren() =
|
|
for i in 0 ..< busy.len:
|
|
try: busy[i].p.terminate()
|
|
except CatchableError: discard
|
|
discard reap(busy[i])
|
|
busy.setLen(0)
|
|
|
|
var row = 0
|
|
var handed = 0
|
|
var failure = ""
|
|
var gotShort = false
|
|
while row < rows and failure.len == 0:
|
|
let bandH = min(tileSize, imgH - row * tileSize)
|
|
let want = bandStride * bandH
|
|
var got = 0
|
|
while got < want:
|
|
var n = 0
|
|
try:
|
|
n = decode.outputStream.readData(addr buf[got], want - got)
|
|
except CatchableError:
|
|
n = 0
|
|
if n <= 0: break
|
|
got += n
|
|
if got < want:
|
|
gotShort = true
|
|
failure = "the decoder stopped after " & $got & " of " & $want & " bytes of row band " &
|
|
$row & " (source " & $imgW & "x" & $imgH & ")"
|
|
break
|
|
|
|
if busy.len >= workers:
|
|
var w = busy[0]
|
|
busy.delete(0)
|
|
if reap(w) != 0:
|
|
failure = "magick failed on the tiles of row " & $w.row & " (its message is above)"
|
|
break
|
|
|
|
let bandFile = bandDir / ("band_" & $row & ".raw")
|
|
try:
|
|
writeFile(bandFile, buf[0 ..< want])
|
|
except IOError as e:
|
|
failure = "cannot write row band " & $row & ": " & e.msg
|
|
break
|
|
let child = try:
|
|
# poParentStreams: the child needs no pipes at all (it reads the band file and writes tiles),
|
|
# so every magick's stderr lands on ours and no descriptors are inherited per child.
|
|
startProcess("magick", options = {poUsePath, poParentStreams}, args = @[
|
|
"-size", $imgW & "x" & $bandH, "-depth", $plan.sampleDepth, plan.rawSpec & bandFile,
|
|
"-crop", $tileSize & "x" & $tileSize, "+repage", "+adjoin",
|
|
"-scene", $(row * cols), tempDir / "tile_%d.png"])
|
|
except OSError as e:
|
|
failure = "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox"
|
|
break
|
|
busy.add((child, row))
|
|
handed += cols
|
|
if (row + 1) mod progressStep == 0 or row + 1 == rows:
|
|
stderr.writeLine "fff-vtt import: rows " & $(row + 1) & "/" & $rows & ", tiles " &
|
|
$min(handed, total) & "/" & $total
|
|
inc row
|
|
|
|
# Every child must be reaped (and its status checked) before the tile tree is trusted.
|
|
while busy.len > 0 and failure.len == 0:
|
|
var w = busy[0]
|
|
busy.delete(0)
|
|
if reap(w) != 0:
|
|
failure = "magick failed on the tiles of row " & $w.row & " (its message is above)"
|
|
if failure.len > 0:
|
|
abortChildren()
|
|
|
|
# The decoder's own exit status matters even when every band arrived: a corrupt tail is exactly
|
|
# the case where the band loop stops short, and the error text lives on its stderr.
|
|
let decodeErr = try: decode.errorStream.readAll() except CatchableError: ""
|
|
let decodeRc = try: decode.waitForExit() except CatchableError: -1
|
|
decode.close()
|
|
removeBands(bandDir)
|
|
if failure.len == 0 and decodeRc != 0:
|
|
failure = "magick failed to decode \"" & imagePath & "\": " & lastLine(decodeErr)
|
|
elif failure.len > 0 and gotShort and decodeErr.len > 0:
|
|
# A short read is the decoder's failure: quote its own last line, not just our byte count.
|
|
failure.add ": " & lastLine(decodeErr)
|
|
if failure.len > 0: return (1, failure)
|
|
(0, "")
|
|
|
|
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, one format, and the sample layout the streaming slice feeds raw to
|
|
# `magick` (type/depth). 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 %[type] %z", imagePath])
|
|
if ident.status != 0:
|
|
return failImport("cannot read image \"" & a.image & "\": " & lastLine(ident.output), 1)
|
|
let parts = ident.output.splitWhitespace
|
|
if parts.len != 5:
|
|
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, srcDepth: int
|
|
try:
|
|
imgW = parseInt(parts[0])
|
|
imgH = parseInt(parts[1])
|
|
srcDepth = parseInt(parts[4])
|
|
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)
|
|
let plan = slicePlan(parts[3], srcDepth)
|
|
|
|
# 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, #83). A single `-crop tile +adjoin` over a 16384 px source
|
|
# builds one image list of every tile and dies on fds/memory, so the normal path streams: one
|
|
# decode to raw samples, then one row band per child `magick` (bounded caches, bounded fds, and
|
|
# progress on stderr). Only a source whose single tile row is itself huge falls back to the
|
|
# one-shot crop, where the tile list is small by construction. `tile_%d.png` names use the global
|
|
# scene index, so the rename below to `<x>_<y>.png` is the same for both paths.
|
|
let bandBytes = imgW * plan.channels * (plan.sampleDepth div 8) * tileSize
|
|
if bandBytes <= MaxBandBytes:
|
|
let streamed = sliceRows(imagePath, tempDir, imgW, imgH, tileSize, cols, rows, plan)
|
|
if streamed.rc != 0:
|
|
removeTemp(tempDir)
|
|
return failImport(streamed.message, 1)
|
|
else:
|
|
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
|