57 lines
2.2 KiB
Luau
57 lines
2.2 KiB
Luau
-- examples/tilemap.luau: read a TMX map, walk a tile layer, find an object, edit, write TMJ (docs/guide/tilemap.md).
|
|
local F = require("@rosetta")
|
|
|
|
local tmx = [[<?xml version="1.0" encoding="UTF-8"?>
|
|
<map version="1.10" orientation="orthogonal" renderorder="right-down" width="5" height="3" tilewidth="16"
|
|
tileheight="16" infinite="0" nextlayerid="3" nextobjectid="2">
|
|
<tileset firstgid="1" name="terrain" tilewidth="16" tileheight="16" tilecount="16" columns="4">
|
|
<image source="terrain.png" width="64" height="64"/>
|
|
</tileset>
|
|
<layer id="1" name="ground" width="5" height="3">
|
|
<data encoding="csv">
|
|
1,2,2,2,3,
|
|
5,0,0,0,7,
|
|
9,10,2147483658,10,11
|
|
</data>
|
|
</layer>
|
|
<objectgroup id="2" name="things">
|
|
<object id="1" name="door" type="Door" x="32" y="16" width="16" height="16">
|
|
<properties><property name="locked" type="bool" value="true"/></properties>
|
|
</object>
|
|
</objectgroup>
|
|
</map>]]
|
|
|
|
local map = assert(F.load(tmx))
|
|
print(string.format("%dx%d tiles of %dx%d px, %d layers", map.width, map.height, map.tileWidth, map.tileHeight, #map.layers))
|
|
|
|
local FLIP_H, FLAGS = 0x80000000, 0xF0000000
|
|
local ground = map.layers[1]
|
|
for y = 0, ground.height - 1 do
|
|
local row = {}
|
|
for x = 0, ground.width - 1 do
|
|
local raw = ground.data[1 + x + y * ground.width]
|
|
local gid = bit32.band(raw, bit32.bnot(FLAGS))
|
|
row[#row + 1] = if gid == 0 then " ." elseif bit32.btest(raw, FLIP_H) then string.format("%2dh", gid) else string.format("%2d", gid)
|
|
end
|
|
print(table.concat(row, " "))
|
|
end
|
|
|
|
local door
|
|
for _, o in map.layers[2].objects do
|
|
if o.class == "Door" then
|
|
door = o
|
|
end
|
|
end
|
|
assert(door and door.properties.locked == true)
|
|
print(string.format("door at tile (%d, %d), locked", door.x // map.tileWidth, door.y // map.tileHeight))
|
|
|
|
-- edit: fill the hole in the middle row, then write TMJ and read it back
|
|
for x = 1, 3 do
|
|
ground.data[1 + x + 1 * ground.width] = 6
|
|
end
|
|
local tmj = assert(F.saveString(map, { format = "tmj" }))
|
|
local back = assert(F.load(tmj, { format = "tiled" }))
|
|
assert(back.layers[1].data[8] == 6 and back.layers[1].data[13] == 0x8000000A)
|
|
assert(back.layers[2].objects[1].properties.locked == true)
|
|
print("as TMJ: " .. #tmj .. " characters; tileset image " .. back.tilesets[1].imageSource)
|