Files
dusk/tools/assetstool/tilesetparser.py
2025-08-24 13:57:12 -05:00

74 lines
2.5 KiB
Python

from os import abort
import os
import xml.etree.ElementTree as ET
from imageparser import parseImage
from header import getOutputDir, getHeaderInclude
def parseTileset(assetPath):
tree = ET.parse(assetPath)
root = tree.getroot()
# Should have tilewidth, tileheight, tilecount and columns attributes
if not all(attr in root.attrib for attr in ['tilewidth', 'tileheight', 'tilecount', 'columns']):
print(f"Error: Missing required attributes in tileset {assetPath}")
return []
tileWidth = int(root.attrib['tilewidth'])
tileHeight = int(root.attrib['tileheight'])
tileCount = int(root.attrib['tilecount'])
columns = int(root.attrib['columns'])
# Find image elements
images = root.findall('image')
if not images:
abort(f"Error: No image elements found in tileset {assetPath}")
imageSources = []
for image in images:
imageSource = image.attrib.get('source')
if not imageSource:
abort(f"Error: Image element missing 'source' attribute in tileset {assetPath}")
# Get relative dir from this assetPath
assetDir = os.path.dirname(assetPath)
imageSource = os.path.normpath(os.path.join(assetDir, imageSource))
imageSources.extend(parseImage(imageSource))
# Now do our own header.
headers = []
print(f"Generating tileset header for {assetPath}")
name = os.path.splitext(os.path.basename(assetPath))[0]
name = name.upper().replace(' ', '_')
imageNameWithoutExtension = os.path.splitext(os.path.splitext(os.path.basename(imageSources[0]))[0])[0]
imageNameWithoutExtension = imageNameWithoutExtension.upper().replace(' ', '_')
dataOut = ""
dataOut += f"// Auto-generated tileset header for {os.path.basename(assetPath)}\n"
dataOut += f"#pragma once\n"
dataOut += f"#include \"asset/assettileset.h\"\n"
for imgHeader in imageSources:
dataOut += getHeaderInclude(imgHeader) + "\n"
dataOut += f"\n"
dataOut += f"static const assettileset_t TILESET_{name} = {{\n"
dataOut += f" .tileCount = {tileCount},\n"
dataOut += f" .columns = {columns},\n"
dataOut += f" .tileHeight = {tileHeight},\n"
dataOut += f" .tileWidth = {tileWidth},\n"
dataOut += f" .image = &{imageNameWithoutExtension},\n"
dataOut += f"}};\n"
# Write out to output dir
outputDir = getOutputDir()
if not os.path.isdir(outputDir):
os.makedirs(outputDir)
outputFile = os.path.join(outputDir, f"tileset_{os.path.basename(assetPath)}.h")
with open(outputFile, 'w') as f:
f.write(dataOut)
headers.append(outputFile)
headers.extend(imageSources)
return headers