archive/unitypackage: Unity asset packages read + write as an Archive keyed by asset paths (.meta beside each asset, guids, folders, previews)
This commit is contained in:
1 parent
0b6773db8b
commit
5096eb4898
8 files changed
+538
-1
No files matched your search
@@ -0,0 +1,36 @@
|
||||
-- tools/fixtures/_unitypackage_encode: run by tools/fixtures/unitypackage.py (luau CLI, repo root): re-encodes every
|
||||
-- package case and a package built from scratch, printing "<file>\t<hex>" lines for Python's tarfile to read.
|
||||
local UnityPackage = require("@rosetta/archive/unitypackage")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Fx = require("@tests/gen/unitypackage")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = HEX[buffer.readu8(b, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local a = UnityPackage.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if a then
|
||||
local out = UnityPackage.encode(a)
|
||||
if out then
|
||||
print(c.name .. ".unitypackage\t" .. hex(out))
|
||||
end
|
||||
end
|
||||
end
|
||||
local a = UnityPackage.new()
|
||||
a:add("Assets/Models", "", { dir = true })
|
||||
a:add("Assets/Models/cube.obj", "v 0 0 0\n")
|
||||
a:add("Assets/readme.txt", "hello\n")
|
||||
a:add("Assets/readme.txt.meta", "fileFormatVersion: 2\nguid: 0123456789abcdef0123456789abcdef\n")
|
||||
local out = UnityPackage.encode(a)
|
||||
if out then
|
||||
print("scratch.unitypackage\t" .. hex(out))
|
||||
end
|
||||
@@ -0,0 +1,95 @@
|
||||
# .unitypackage fixtures (tools/fixtures.py): packages built here with Python's tarfile + gzip to the layout Unity
|
||||
# writes (<guid>/asset, <guid>/asset.meta, <guid>/pathname, optional preview.png; folders carry only a meta), with
|
||||
# the expected asset table; then our encoder's output (tools/fixtures/_unitypackage_encode.luau) read back by
|
||||
# Python's tarfile.
|
||||
# tests/gen/unitypackage.luau { cases = { { name, data, assets = { { path, guid, md5?, metaMd5, dir } } } },
|
||||
# ours = { { name, ok, assets = { { path, guid, md5?, metaMd5, dir } }, error? } } }
|
||||
import gzip, hashlib, importlib.util, io, os, tarfile, uuid
|
||||
|
||||
INPUTS = ["src/Rosetta/archive/unitypackage", "tools/fixtures/_unitypackage_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
|
||||
|
||||
def meta(guid, folder=False):
|
||||
s = "fileFormatVersion: 2\nguid: %s\n" % guid
|
||||
if folder:
|
||||
s += "folderAsset: yes\n"
|
||||
return (s + "DefaultImporter:\n externalObjects: {}\n userData: \n").encode()
|
||||
|
||||
|
||||
def build(items, dot=False, extra_line=False, mtime=1600000000):
|
||||
"""items: [(path, data or None for a folder, preview bytes or None)]"""
|
||||
raw = io.BytesIO()
|
||||
assets = []
|
||||
with tarfile.open(fileobj=raw, mode="w", format=tarfile.GNU_FORMAT) as tf:
|
||||
def add(name, data):
|
||||
ti = tarfile.TarInfo(("./" if dot else "") + name)
|
||||
ti.size = len(data)
|
||||
ti.mtime = mtime
|
||||
tf.addfile(ti, io.BytesIO(data))
|
||||
for path, data, preview in items:
|
||||
guid = uuid.uuid5(uuid.NAMESPACE_URL, path).hex
|
||||
d = tarfile.TarInfo(("./" if dot else "") + guid)
|
||||
d.type = tarfile.DIRTYPE
|
||||
d.mtime = mtime
|
||||
tf.addfile(d)
|
||||
m = meta(guid, data is None)
|
||||
if data is not None:
|
||||
add(guid + "/asset", data)
|
||||
add(guid + "/asset.meta", m)
|
||||
add(guid + "/pathname", (path + ("\n00" if extra_line else "")).encode())
|
||||
if preview:
|
||||
add(guid + "/preview.png", preview)
|
||||
a = {"path": path, "guid": guid, "metaMd5": hashlib.md5(m).hexdigest(), "dir": data is None}
|
||||
if data is not None:
|
||||
a["md5"] = hashlib.md5(data).hexdigest()
|
||||
assets.append(a)
|
||||
return gzip.compress(raw.getvalue(), mtime=0), assets
|
||||
|
||||
|
||||
def read_package(data):
|
||||
out = []
|
||||
with tarfile.open(fileobj=io.BytesIO(gzip.decompress(data))) as tf:
|
||||
files = {}
|
||||
for m in tf.getmembers():
|
||||
if m.isfile():
|
||||
files[m.name] = tf.extractfile(m).read()
|
||||
guids = sorted({n.split("/")[0] for n in files})
|
||||
for g in guids:
|
||||
path = files[g + "/pathname"].decode().split("\n")[0]
|
||||
m = files[g + "/asset.meta"]
|
||||
if ("guid: " + g).encode() not in m:
|
||||
raise ValueError("meta guid mismatch for " + path)
|
||||
a = {"path": path, "guid": g, "metaMd5": hashlib.md5(m).hexdigest(), "dir": (g + "/asset") not in files}
|
||||
if not a["dir"]:
|
||||
a["md5"] = hashlib.md5(files[g + "/asset"]).hexdigest()
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(7)
|
||||
png = b"\x89PNG\r\n\x1a\n" + rng.randbytes(200)
|
||||
items = [
|
||||
("Assets", None, None),
|
||||
("Assets/Textures", None, None),
|
||||
("Assets/Textures/brick.png", png, b"\x89PNG\r\n\x1a\npreview"),
|
||||
("Assets/Scripts/Player.cs", b"using UnityEngine;\npublic class Player : MonoBehaviour { }\n", None),
|
||||
("Assets/Scenes/Main Scene.unity", b"%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &1\n", None),
|
||||
("Assets/Audio/empty.wav", b"", None),
|
||||
("Assets/Big/blob.bin", rng.randbytes(70000), None),
|
||||
]
|
||||
cases = []
|
||||
for name, kw in (("plain", {}), ("dot", {"dot": True}), ("extra-line", {"extra_line": True})):
|
||||
data, assets = build(items, **kw)
|
||||
cases.append({"name": name, "data": data, "assets": assets})
|
||||
ctx.emit("unitypackage", {"cases": cases, "ours": []})
|
||||
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
|
||||
M = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(M)
|
||||
ours = []
|
||||
for name, data in sorted(M.luau_encode(ctx, "tools/fixtures/_unitypackage_encode.luau").items()):
|
||||
try:
|
||||
ours.append({"name": name, "ok": True, "assets": read_package(data)})
|
||||
except Exception as e:
|
||||
ours.append({"name": name, "ok": False, "assets": [], "error": str(e)})
|
||||
ctx.emit("unitypackage", {"cases": cases, "ours": ours})
|
||||
Reference in new issue
Block a user