# DDS fixtures (tools/fixtures.py): # - files written by NVIDIA Texture Tools (nvcompress: uncompressed BGRA, BC1 / BC1a / BC2 / BC3 / BC4 / BC5 / BC6H / # BC7, with and without mip chains, legacy and DX10 headers; nvassemble: cube maps, arrays, volumes) and by # ImageMagick (none / DXT1 / DXT5 with mip maps); # - hand-written ones for the uncompressed DXGI and legacy formats nothing here writes (floats, snorm, packed, # shared exponent, YUY2, luminance, bit masks, D3DFMT numbers), with the values they hold; # - our encoder's files (tools/fixtures/_tex_encode.luau -a dds) read back by Pillow and nvddsinfo. # Reference pixels: every surface is cut out here (an independent walk of the DDS layout) and decoded by Pillow # (BCn through a one-surface DX10 file; BC6H by Godot as floats); the hand-written files carry their expected values. # tests/gen/dds.luau { cases = { { name, data, layout, mips, layers, depth, surfaces = { { level, layer, slice, w, # h, rgba?, floats?, tol } } } }, ours = { { name, data, pillow?, info } } } import importlib.util, json, math, os, random, shutil, struct, subprocess, tempfile, zlib _spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py")) R = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(R) INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Rosetta/image/dds", "src/Rosetta/codecs/image/Bcn", "src/Rosetta/codecs/image/Texture.luau"] BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc6h": 16, "bc7": 16} DXGI_BC = {70: "bc1", 71: "bc1", 72: "bc1", 73: "bc2", 74: "bc2", 75: "bc2", 76: "bc3", 77: "bc3", 78: "bc3", 79: "bc4", 80: "bc4", 82: "bc5", 83: "bc5", 94: "bc6h", 95: "bc6h", 97: "bc7", 98: "bc7", 99: "bc7"} FOURCC_BC = {b"DXT1": "bc1", b"DXT3": "bc2", b"DXT5": "bc3", b"ATI1": "bc4", b"BC4U": "bc4", b"ATI2": "bc5", b"BC5U": "bc5"} def png(w, h, rgba): raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h)) def chunk(t, d): return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")) def source(w, h, salt=0): out = bytearray() for y in range(h): for x in range(w): r = x / max(1, w - 1) g = y / max(1, h - 1) b = ((x * 7 + y * 13 + salt * 31) % 64) / 63 a = ((x + y + salt) % 5) / 4 out += bytes(int(v * 255 + 0.5) for v in (r, g, b, a)) return bytes(out) def layout(data): """an independent walk of a DDS file: (info, [(level, layer, slice, w, h, format, offset, size)])""" flags, h, w, pitch, depth, mips = struct.unpack("<6I", data[8:32]) pf_flags, fourcc, bits, rm, gm, bm, am = struct.unpack(" rgba8 with rounding (the Texel rule)""" out = bytearray() nb = bits // 8 for i in range(0, len(raw), nb): v = int.from_bytes(raw[i:i + nb], "little") px = [] for k, m in enumerate(masks): if m == 0: px.append(255 if k == 3 else 0) continue sh = (m & -m).bit_length() - 1 mx = m >> sh px.append(int(((v & m) >> sh) / mx * 255 + 0.5)) out += bytes(px) return bytes(out) def references(ctx, cases): """fill c["surfaces"] for files from the tools: Pillow per surface (BCn / masks), Godot floats for BC6H""" pil_files, pil_targets, gd_jobs, gd_targets = [], [], [], [] for c in cases: info, surf = layout(c["data"]) c["layout"] = "volume" if info["volume"] else ("cube" if info["cube"] else ("array" if info["layers"] > 1 else "2d")) c["mips"], c["layers"], c["depth"] = info["mips"], info["layers"], info["depth"] c["surfaces"] = [] for (level, layer, s, w, h, fmt, off, size) in surf: if level > 0 and (layer > 0 or s > 0): continue sd = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": 0} raw = c["data"][off:off + size] c["surfaces"].append(sd) if fmt == "bc6h": gd_jobs.append((raw, w, h, R.GODOT["bc6h"], True)) gd_targets.append(sd) elif fmt in BLOCK: dx = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc7": 98}[fmt] pil_files.append(R.dds_dx10(w, h, dx, raw)) pil_targets.append((sd, fmt)) elif fmt.startswith("rgb"): sd["rgba"] = mask_decode(raw, info["bits"], info["masks"]) elif fmt == "dxgi28": sd["rgba"] = raw elif fmt == "dxgi87": sd["rgba"] = bytes(raw[i + k] for i in range(0, len(raw), 4) for k in (2, 1, 0, 3)) for (sd, fmt), (mode, w, h, raw) in zip(pil_targets, R.pillow(ctx, pil_files)): rgba = R.rgba_from(mode, raw) if fmt == "bc5": rgba = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(rgba)) sd["rgba"] = rgba for sd, out in zip(gd_targets, R.godot(ctx, gd_jobs)): sd["floats"] = out def hand_cases(rng): """uncompressed formats with known values: (name, dds bytes, expected rgba8, expected floats or None)""" W, H = 5, 3 cases = [] def f32(v): return struct.unpack("= 1 else int(v * 255 + 0.5)) def add(name, dds, texels): """texels: list of (r, g, b, a) floats (the native values) -> expected rgba8 by the rules""" cases.append({"name": name, "data": dds, "rgba8": bytes(q8(v) for t in texels for v in t), "floats": b"".join(struct.pack("<4f", *t) for t in texels)}) # floats vals = [(rng.uniform(-0.5, 3), rng.uniform(0, 1), rng.uniform(0, 1.5), rng.uniform(0, 1)) for _ in range(W * H)] data = b"".join(struct.pack("<4f", *v) for v in vals) add("dxgi R32G32B32A32_FLOAT", R.dds_dx10(W, H, 2, data), [tuple(f32(x) for x in v) for v in vals]) data = b"".join(struct.pack("<4e", *v) for v in vals) add("dxgi R16G16B16A16_FLOAT", R.dds_dx10(W, H, 10, data), [tuple(half(x) for x in v) for v in vals]) add("d3dfmt 113 (A16B16G16R16F)", R.dds_fourcc(W, H, struct.pack("> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32]) def uf(v, mb): e, m = v >> mb, v & ((1 << mb) - 1) if e == 0: return m / (1 << mb) * 2 ** -14 return (1 + m / (1 << mb)) * 2 ** (e - 15) p11 = [rng.getrandbits(32) & ~((1 << 30) | (1 << 9) | (1 << 20)) for _ in range(W * H)] # keep exponents < 31 add("dxgi R11G11B10_FLOAT", R.dds_dx10(W, H, 26, b"".join(struct.pack("> 11) & 2047, 6), uf(v >> 22, 5), 1.0) for v in p11]) add("dxgi R9G9B9E5_SHAREDEXP", R.dds_dx10(W, H, 67, b"".join(struct.pack("> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32]) p16 = [rng.getrandbits(16) for _ in range(W * H)] add("dxgi B5G6R5_UNORM", R.dds_dx10(W, H, 85, b"".join(struct.pack("> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16]) add("dxgi B5G5R5A1_UNORM", R.dds_dx10(W, H, 86, b"".join(struct.pack("> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16]) add("dxgi B4G4R4A4_UNORM", R.dds_dx10(W, H, 115, b"".join(struct.pack("> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16]) # legacy masks def legacy(bits, flags, masks, data): pf = struct.pack("<2I4s5I", 32, flags, b"\0\0\0\0", bits, *masks) return R.dds_header(W, H, pf) + data add("legacy R5G6B5", legacy(16, 0x40, (0xF800, 0x7E0, 0x1F, 0), b"".join(struct.pack("> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16]) add("legacy A1R5G5B5", legacy(16, 0x41, (0x7C00, 0x3E0, 0x1F, 0x8000), b"".join(struct.pack("> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16]) add("legacy X8R8G8B8", legacy(32, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32]) add("legacy R8G8B8 (24-bit)", legacy(24, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32]) add("legacy A2B10G10R10", legacy(32, 0x41, (0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000), b"".join(struct.pack("> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32]) add("legacy L8", legacy(8, 0x20000, (0xFF, 0, 0, 0), bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8]) add("legacy A8L8", legacy(16, 0x20001, (0xFF, 0, 0, 0xFF00), bytes(x for v in u8 for x in (v[0], v[3]))), [(v[0] / 255,) * 3 + (v[3] / 255,) for v in u8]) add("legacy A8", legacy(8, 0x2, (0, 0, 0, 0xFF), bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8]) add("legacy A4R4G4B4", legacy(16, 0x41, (0xF00, 0xF0, 0xF, 0xF000), b"".join(struct.pack("> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16]) # YUY2 (BT.601 limited range) def ycc(y, u, v): c, d, e = 1.164 * (y - 16), u - 128, v - 128 cl = lambda x: max(0, min(255, int(math.floor(x + 0.5)))) return (cl(c + 1.596 * e), cl(c - 0.392 * d - 0.813 * e), cl(c + 2.017 * d), 255) W2 = 6 yuy = bytes(rng.randrange(16, 240) for _ in range(W2 * H * 2)) exp = [] for y in range(H): for x in range(W2): q = y * W2 * 2 + (x // 2) * 4 exp.append(ycc(yuy[q + (2 if x % 2 else 0)], yuy[q + 1], yuy[q + 3])) pf = struct.pack("<2I4s5I", 32, 4, b"YUY2", 0, 0, 0, 0, 0) cases.append({"name": "fourcc YUY2", "data": R.dds_header(W2, H, pf) + yuy, "rgba8": bytes(v for t in exp for v in t)}) return cases def generate(ctx): rng = random.Random(5) work = tempfile.mkdtemp(prefix="formats-dds-") try: cases = _tools(ctx, work) references(ctx, cases) hand = hand_cases(rng) ours = _ours(ctx, work) finally: shutil.rmtree(work, ignore_errors=True) ctx.emit("dds", {"cases": cases, "hand": hand, "ours": ours}) def _tools(ctx, work): cases = [] for name, w, h in (("a", 37, 23), ("b", 64, 32)): with open(os.path.join(work, name + ".png"), "wb") as f: f.write(png(w, h, source(w, h))) jobs = [] for src in ("a", "b"): for fl in ("-rgb", "-bc1", "-bc1a", "-bc2", "-bc3", "-bc4", "-bc5", "-bc7"): jobs.append((src, fl, [])) jobs.append((src, "-bc1", ["-nomips", "-dds10"])) jobs.append(("a", "-bc6", ["-nomips"])) script = [] for src, fl, extra in jobs: out = "%s%s%s.dds" % (src, fl, "".join(extra)) script.append("nvcompress -silent %s %s %s.png %s" % (fl, " ".join(extra), src, out)) for i in range(6): with open(os.path.join(work, "f%d.png" % i), "wb") as f: f.write(png(16, 16, source(16, 16, i + 1))) faces = " ".join("f%d.png" % i for i in range(6)) script.append("nvassemble -cube %s -o cube.dds" % faces) script.append("nvassemble -array f0.png f1.png f2.png -o array.dds") script.append("nvassemble -volume f0.png f1.png f2.png f3.png -o volume.dds") ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(script))]) im = [] for comp in ("none", "dxt1", "dxt5"): im.append("magick a.png -define dds:compression=%s -define dds:mipmaps=3 im_%s.dds" % (comp, comp)) ctx.nix("imagemagick", ["sh", "-c", "cd %s && %s" % (work, " && ".join(im))]) names = ["%s%s%s.dds" % (s, f, "".join(e)) for s, f, e in jobs] + ["cube.dds", "array.dds", "volume.dds"] + ["im_%s.dds" % c for c in ("none", "dxt1", "dxt5")] for n in names: cases.append({"name": n, "data": open(os.path.join(work, n), "rb").read()}) return cases def _ours(ctx, work): exe = shutil.which("luau") cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "dds"], cwd=ctx.root, capture_output=True, check=True) files = {} for line in res.stdout.decode().split("\n"): if "\t" in line: n, hx = line.split("\t", 1) files[n] = bytes.fromhex(hx.strip()) out = [] pil, pil_idx = [], [] names = sorted(files) for n in names: with open(os.path.join(work, n), "wb") as f: f.write(files[n]) info = ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && for f in %s; do echo \"== $f\"; nvddsinfo $f; done" % (work, " ".join(names))]).decode(errors="replace") blocks = {} for part in info.split("== ")[1:]: n, body = part.split("\n", 1) blocks[n.strip()] = body for i, n in enumerate(names): body = blocks.get(n, "") def field(key): for line in body.split("\n"): if line.strip().startswith(key): return line.split(":", 1)[1].strip() return "" e = {"name": n, "data": files[n], "width": int(field("Width") or 0), "height": int(field("Height") or 0), "mipcount": int(field("Mipmap count") or 0), "dxgi": field("DXGI Format"), "array": field("Array size"), "caps2": field("Caps 2")} out.append(e) if not any(k in n for k in ("rgba16", "rgba32f", "rgba16f", "cube", "array")): pil.append(files[n]) pil_idx.append(i) for i, (mode, w, h, raw) in zip(pil_idx, R.pillow(ctx, pil)): out[i]["pillow"] = R.rgba_from(mode, raw) out[i]["pillowMode"] = mode return out