Keep supplied source text in canonical Git line endings
This commit is contained in:
parent
86c6142469
commit
c9944bb832
13 changed files with 8437 additions and 8397 deletions
|
|
@ -35,4 +35,4 @@ jobs:
|
|||
with:
|
||||
name: DuneRealms-Supplied-Item-Art
|
||||
path: supplied-item-art/
|
||||
if-no-files-found: error
|
||||
if-no-files-found: error
|
||||
|
|
|
|||
40
docs/DUNE-ITEM-ART-20261203.md
Normal file
40
docs/DUNE-ITEM-ART-20261203.md
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
# Soft Dune item art (all item sprites)
|
||||
|
||||
Direction: items should feel like Arrakis. The Butlerian Jihad means no screens, holograms or circuit lattices: the
|
||||
futurism is clean machined brass, bone, sun-bleached stillsuit cloth, spice-amber crystal and water-glass, painted
|
||||
with soft light and warm umber shadows instead of black outlines or neon glow. GUI/menu/tooltip textures are untouched.
|
||||
|
||||
## What changed
|
||||
|
||||
- **Custom generated items** (`central/generator/soft_*.py`, `dunesoft.py`): coins, notes and legacy Dunemark ids,
|
||||
planet sigils, office crests, spy module, spice crystals, water vials, Imperial Codex, and all 224 equipment icons.
|
||||
`build_pack.py` now imports the soft modules; its output replaces the 268 generated PNGs in `central/overlay`.
|
||||
Item model and definition JSON are unchanged.
|
||||
- **Equipment orientation follows vanilla sprites**: grip bottom-left and working end top-right for sword, pickaxe,
|
||||
axe, shovel, mace and trident; the hoe blade hooks to the upper-left; bow and crossbow face the upper-left.
|
||||
Tools are classic silhouettes with bone blades, leather-wrapped grips, brass sockets and small cog details.
|
||||
Armour reads as stillsuits: veiled hoods, catchtubes, brass buckles and boots with leather straps.
|
||||
- **Vanilla items** (`dune-items/overlay`): all 833 item sprites in `vanilla-art` + `owner-items` regraded by
|
||||
`central/generator/dune_item_grade.py`. Alpha, size and silhouette are unchanged. This is a deterministic
|
||||
recolour into one dusty palette (greens to sage, yellows to ochre, reds to terracotta, metals to pewter/brass,
|
||||
diamond to pale water-crystal), not 833 new drawings. The seven ingot/raw icons are redrawn.
|
||||
- **Hand-supplied custom items** (`dune-items/custom`): ecology items, crysknife, maker's tooth, wrench and the
|
||||
Goldmembers shovel get the same colour grade only.
|
||||
|
||||
## Protected functional art
|
||||
|
||||
Tint layers (`*_overlay`, `tipped_arrow_head`, map markings) are copied byte-for-byte. Dye-tinted base sprites
|
||||
(leather armour, wolf armour, firework star) only get a lightness curve so dye colours stay correct. Colour-coded
|
||||
items (dyes, bundles, candles, harnesses, spawn eggs, discs, potions) keep their hues with a lighter grade.
|
||||
|
||||
## Reproduce and check
|
||||
|
||||
```
|
||||
python3 network/resource-pack/central/generator/build_pack.py /tmp/central # custom items
|
||||
python3 network/resource-pack/central/generator/dune_item_grade.py network/resource-pack/dune-items
|
||||
python3 tools/test_dune_item_grade.py -v
|
||||
```
|
||||
|
||||
`tools/plugin_resource_pack.py` loads `dune-items/overlay` after `owner-items` and `dune-items/custom` last.
|
||||
Not run here: the full pack build needs the pinned Mojang client jar, so the pack hash, `test_plugin_resource_pack`
|
||||
and the hash pins for changed files need a CI run and a connected-client check. Offline sheets are not in-game proof.
|
||||
|
|
@ -1,118 +1,118 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Build the DuneRealms central resource pack (overlay) from procedural art. Run: python3 build_pack.py OUTDIR"""
|
||||
import json, os, shutil, sys, hashlib, zipfile
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from PIL import Image
|
||||
import soft_items as M
|
||||
import soft_equipment as E
|
||||
import blocks as B
|
||||
|
||||
OUT = sys.argv[1] if len(sys.argv) > 1 else "out/DuneRealms-Central-Pack"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OLD = str(ROOT / "legacy/assets/dunerealms/textures")
|
||||
TOOLTIP = str(ROOT / "overlay/assets/dunerealms/textures/gui/sprites/tooltip")
|
||||
A = f"{OUT}/assets/dunerealms"
|
||||
MC = f"{OUT}/assets/minecraft"
|
||||
manifest = {"textures": [], "item_models": []}
|
||||
|
||||
|
||||
def save(img, path):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
img.save(path, optimize=True)
|
||||
manifest["textures"].append(os.path.relpath(path, OUT))
|
||||
|
||||
|
||||
def wjson(path, obj):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
json.dump(obj, f, separators=(",", ":"))
|
||||
|
||||
|
||||
def item_def(rel_id, model_path, tex, handheld=False, parent=None):
|
||||
"""rel_id: 'currency/coin_001' -> items/currency/coin_001.json ; model_path: 'item/currency/coin_001'"""
|
||||
wjson(f"{A}/items/{rel_id}.json", {"model": {"type": "minecraft:model", "model": f"dunerealms:{model_path}"}})
|
||||
wjson(f"{A}/models/{model_path}.json", {"parent": parent or ("minecraft:item/handheld" if handheld else "minecraft:item/generated"), "textures": {"layer0": f"dunerealms:{tex}"}})
|
||||
manifest["item_models"].append(f"dunerealms:{rel_id}")
|
||||
|
||||
|
||||
# ---- pack.mcmeta -------------------------------------------------------
|
||||
wjson(f"{OUT}/pack.mcmeta", {"pack": {
|
||||
"pack_format": 64,
|
||||
"supported_formats": {"min_inclusive": 46, "max_inclusive": 99},
|
||||
"description": "§6DuneRealms §7— central Dune pack · soft brass on desert sand"}})
|
||||
|
||||
# ---- currency (names match the live pack 1:1) ---------------------------
|
||||
for n in M.COINS:
|
||||
save(M.coin(n), f"{A}/textures/item/currency/{n}.png")
|
||||
item_def(f"currency/{n}", f"item/currency/{n}", f"item/currency/{n}")
|
||||
for n in M.NOTES:
|
||||
save(M.note(n), f"{A}/textures/item/currency/{n}.png")
|
||||
item_def(f"currency/{n}", f"item/currency/{n}", f"item/currency/{n}")
|
||||
|
||||
# ---- spy module ----------------------------------------------------------
|
||||
save(M.spy_module(), f"{A}/textures/item/spy_module.png")
|
||||
item_def("spy_module", "item/spy_module", "item/spy_module")
|
||||
|
||||
# ---- legacy ids kept so older plugin builds still resolve ------------------
|
||||
for v in ("1", "5", "100", "1000", "5000", "note"):
|
||||
save(M.legacy_note(v), f"{A}/textures/item/dunemark_{v}.png")
|
||||
item_def(f"dunemark_{v}", f"item/dunemark_{v}", f"item/dunemark_{v}")
|
||||
for p in M.PLANET_TINT:
|
||||
save(M.planet(p, Image.open(f"{OLD}/item/planet_{p}.png")), f"{A}/textures/item/planet_{p}.png")
|
||||
item_def(f"planet_{p}", f"item/planet_{p}", f"item/planet_{p}")
|
||||
for k in ("crown", "spice", "water"):
|
||||
save(M.office(k), f"{A}/textures/item/office_{k}.png")
|
||||
item_def(f"office_{k}", f"item/office_{k}", f"item/office_{k}")
|
||||
save(Image.new("RGBA", (1, 1), (0, 0, 0, 0)), f"{A}/textures/item/drgui_transparent.png")
|
||||
item_def("drgui_transparent", "item/drgui_transparent", "item/drgui_transparent")
|
||||
|
||||
# ---- extra icons (hooks the plugins can adopt via item_model) --------------
|
||||
extras = {
|
||||
"spice_common": M.spice_crystal("#f4b85f", "#c9692b", "#e8913a"),
|
||||
"spice_smuggled": M.spice_crystal("#eaa656", "#8f4a1f", "#d9822f", smuggled=True),
|
||||
"spice_dense": M.spice_crystal("#f8c872", "#c05a1d", "#f0a640", dense=True),
|
||||
"spice_refined": M.spice_crystal("#fbe2a2", "#e0912f", "#f3c45e", dense=True),
|
||||
"water_vial": M.water_vial(),
|
||||
"smugglers_water_vial": M.water_vial("#6ee7d8", smuggled=True),
|
||||
"imperial_codex": M.imperial_codex(),
|
||||
}
|
||||
for n, img in extras.items():
|
||||
save(img, f"{A}/textures/item/{n}.png")
|
||||
item_def(n, f"item/{n}", f"item/{n}")
|
||||
|
||||
# ---- equipment: every valid (quality, mark) x type -------------------------
|
||||
count = 0
|
||||
for quality, mark in E.valid_marks():
|
||||
tier = E.QUALITY.index(quality)
|
||||
pips = (mark % 3) + 1 if quality != "mythic" else 3
|
||||
for kind in E.TYPES:
|
||||
name = f"{quality}_mk{mark}_{kind}"
|
||||
save(E.draw(kind, tier, pips), f"{A}/textures/item/equipment/{name}.png")
|
||||
item_def(f"equipment/{name}", f"item/equipment/{name}", f"item/equipment/{name}", handheld=kind in E.HANDHELD)
|
||||
count += 1
|
||||
|
||||
# ---- blocks ---------------------------------------------------------------
|
||||
for kind, bid, seed in (("spice", "spice_block", 7), ("smuggled", "smuggled_spice_block", 17), ("contaminated", "contaminated_spice_block", 27)):
|
||||
for face in ("side", "top", "bottom"):
|
||||
save(B.spice_face(kind, face, 32, seed), f"{A}/textures/block/{bid}_{face}.png")
|
||||
wjson(f"{A}/models/block/{bid}.json", {"parent": "minecraft:block/cube_bottom_top", "textures": {
|
||||
"side": f"dunerealms:block/{bid}_side", "top": f"dunerealms:block/{bid}_top", "bottom": f"dunerealms:block/{bid}_bottom"}})
|
||||
wjson(f"{A}/items/{bid}.json", {"model": {"type": "minecraft:model", "model": f"dunerealms:block/{bid}"}})
|
||||
manifest["item_models"].append(f"dunerealms:{bid}")
|
||||
# carrier: the plugin's spice blocks are DRIED_KELP_BLOCK, so retexture the carrier everywhere
|
||||
for face in ("side", "top", "bottom"):
|
||||
save(B.spice_face("spice", face, 32, 7), f"{MC}/textures/block/dried_kelp_{face}.png")
|
||||
for st in range(4):
|
||||
save(B.suspicious_sand(st), f"{MC}/textures/block/suspicious_sand_{st}.png")
|
||||
|
||||
# ---- tooltip sprites (item-card frame), copied from the approved design ------
|
||||
for f in ("dune_background.png", "dune_background.png.mcmeta", "dune_frame.png", "dune_frame.png.mcmeta"):
|
||||
d = f"{A}/textures/gui/sprites/tooltip"
|
||||
os.makedirs(d, exist_ok=True)
|
||||
shutil.copy(f"{TOOLTIP}/{f}", f"{d}/{f}")
|
||||
manifest["textures"].append(os.path.relpath(f"{d}/{f}", OUT))
|
||||
|
||||
with open(f"{OUT}/MANIFEST.json", "w") as f:
|
||||
json.dump(manifest, f, indent=1)
|
||||
print("equipment icons:", count, "| textures:", len(manifest["textures"]), "| item models:", len(manifest["item_models"]))
|
||||
#!/usr/bin/env python3
|
||||
"""Build the DuneRealms central resource pack (overlay) from procedural art. Run: python3 build_pack.py OUTDIR"""
|
||||
import json, os, shutil, sys, hashlib, zipfile
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from PIL import Image
|
||||
import soft_items as M
|
||||
import soft_equipment as E
|
||||
import blocks as B
|
||||
|
||||
OUT = sys.argv[1] if len(sys.argv) > 1 else "out/DuneRealms-Central-Pack"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OLD = str(ROOT / "legacy/assets/dunerealms/textures")
|
||||
TOOLTIP = str(ROOT / "overlay/assets/dunerealms/textures/gui/sprites/tooltip")
|
||||
A = f"{OUT}/assets/dunerealms"
|
||||
MC = f"{OUT}/assets/minecraft"
|
||||
manifest = {"textures": [], "item_models": []}
|
||||
|
||||
|
||||
def save(img, path):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
img.save(path, optimize=True)
|
||||
manifest["textures"].append(os.path.relpath(path, OUT))
|
||||
|
||||
|
||||
def wjson(path, obj):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
json.dump(obj, f, separators=(",", ":"))
|
||||
|
||||
|
||||
def item_def(rel_id, model_path, tex, handheld=False, parent=None):
|
||||
"""rel_id: 'currency/coin_001' -> items/currency/coin_001.json ; model_path: 'item/currency/coin_001'"""
|
||||
wjson(f"{A}/items/{rel_id}.json", {"model": {"type": "minecraft:model", "model": f"dunerealms:{model_path}"}})
|
||||
wjson(f"{A}/models/{model_path}.json", {"parent": parent or ("minecraft:item/handheld" if handheld else "minecraft:item/generated"), "textures": {"layer0": f"dunerealms:{tex}"}})
|
||||
manifest["item_models"].append(f"dunerealms:{rel_id}")
|
||||
|
||||
|
||||
# ---- pack.mcmeta -------------------------------------------------------
|
||||
wjson(f"{OUT}/pack.mcmeta", {"pack": {
|
||||
"pack_format": 64,
|
||||
"supported_formats": {"min_inclusive": 46, "max_inclusive": 99},
|
||||
"description": "§6DuneRealms §7— central Dune pack · soft brass on desert sand"}})
|
||||
|
||||
# ---- currency (names match the live pack 1:1) ---------------------------
|
||||
for n in M.COINS:
|
||||
save(M.coin(n), f"{A}/textures/item/currency/{n}.png")
|
||||
item_def(f"currency/{n}", f"item/currency/{n}", f"item/currency/{n}")
|
||||
for n in M.NOTES:
|
||||
save(M.note(n), f"{A}/textures/item/currency/{n}.png")
|
||||
item_def(f"currency/{n}", f"item/currency/{n}", f"item/currency/{n}")
|
||||
|
||||
# ---- spy module ----------------------------------------------------------
|
||||
save(M.spy_module(), f"{A}/textures/item/spy_module.png")
|
||||
item_def("spy_module", "item/spy_module", "item/spy_module")
|
||||
|
||||
# ---- legacy ids kept so older plugin builds still resolve ------------------
|
||||
for v in ("1", "5", "100", "1000", "5000", "note"):
|
||||
save(M.legacy_note(v), f"{A}/textures/item/dunemark_{v}.png")
|
||||
item_def(f"dunemark_{v}", f"item/dunemark_{v}", f"item/dunemark_{v}")
|
||||
for p in M.PLANET_TINT:
|
||||
save(M.planet(p, Image.open(f"{OLD}/item/planet_{p}.png")), f"{A}/textures/item/planet_{p}.png")
|
||||
item_def(f"planet_{p}", f"item/planet_{p}", f"item/planet_{p}")
|
||||
for k in ("crown", "spice", "water"):
|
||||
save(M.office(k), f"{A}/textures/item/office_{k}.png")
|
||||
item_def(f"office_{k}", f"item/office_{k}", f"item/office_{k}")
|
||||
save(Image.new("RGBA", (1, 1), (0, 0, 0, 0)), f"{A}/textures/item/drgui_transparent.png")
|
||||
item_def("drgui_transparent", "item/drgui_transparent", "item/drgui_transparent")
|
||||
|
||||
# ---- extra icons (hooks the plugins can adopt via item_model) --------------
|
||||
extras = {
|
||||
"spice_common": M.spice_crystal("#f4b85f", "#c9692b", "#e8913a"),
|
||||
"spice_smuggled": M.spice_crystal("#eaa656", "#8f4a1f", "#d9822f", smuggled=True),
|
||||
"spice_dense": M.spice_crystal("#f8c872", "#c05a1d", "#f0a640", dense=True),
|
||||
"spice_refined": M.spice_crystal("#fbe2a2", "#e0912f", "#f3c45e", dense=True),
|
||||
"water_vial": M.water_vial(),
|
||||
"smugglers_water_vial": M.water_vial("#6ee7d8", smuggled=True),
|
||||
"imperial_codex": M.imperial_codex(),
|
||||
}
|
||||
for n, img in extras.items():
|
||||
save(img, f"{A}/textures/item/{n}.png")
|
||||
item_def(n, f"item/{n}", f"item/{n}")
|
||||
|
||||
# ---- equipment: every valid (quality, mark) x type -------------------------
|
||||
count = 0
|
||||
for quality, mark in E.valid_marks():
|
||||
tier = E.QUALITY.index(quality)
|
||||
pips = (mark % 3) + 1 if quality != "mythic" else 3
|
||||
for kind in E.TYPES:
|
||||
name = f"{quality}_mk{mark}_{kind}"
|
||||
save(E.draw(kind, tier, pips), f"{A}/textures/item/equipment/{name}.png")
|
||||
item_def(f"equipment/{name}", f"item/equipment/{name}", f"item/equipment/{name}", handheld=kind in E.HANDHELD)
|
||||
count += 1
|
||||
|
||||
# ---- blocks ---------------------------------------------------------------
|
||||
for kind, bid, seed in (("spice", "spice_block", 7), ("smuggled", "smuggled_spice_block", 17), ("contaminated", "contaminated_spice_block", 27)):
|
||||
for face in ("side", "top", "bottom"):
|
||||
save(B.spice_face(kind, face, 32, seed), f"{A}/textures/block/{bid}_{face}.png")
|
||||
wjson(f"{A}/models/block/{bid}.json", {"parent": "minecraft:block/cube_bottom_top", "textures": {
|
||||
"side": f"dunerealms:block/{bid}_side", "top": f"dunerealms:block/{bid}_top", "bottom": f"dunerealms:block/{bid}_bottom"}})
|
||||
wjson(f"{A}/items/{bid}.json", {"model": {"type": "minecraft:model", "model": f"dunerealms:block/{bid}"}})
|
||||
manifest["item_models"].append(f"dunerealms:{bid}")
|
||||
# carrier: the plugin's spice blocks are DRIED_KELP_BLOCK, so retexture the carrier everywhere
|
||||
for face in ("side", "top", "bottom"):
|
||||
save(B.spice_face("spice", face, 32, 7), f"{MC}/textures/block/dried_kelp_{face}.png")
|
||||
for st in range(4):
|
||||
save(B.suspicious_sand(st), f"{MC}/textures/block/suspicious_sand_{st}.png")
|
||||
|
||||
# ---- tooltip sprites (item-card frame), copied from the approved design ------
|
||||
for f in ("dune_background.png", "dune_background.png.mcmeta", "dune_frame.png", "dune_frame.png.mcmeta"):
|
||||
d = f"{A}/textures/gui/sprites/tooltip"
|
||||
os.makedirs(d, exist_ok=True)
|
||||
shutil.copy(f"{TOOLTIP}/{f}", f"{d}/{f}")
|
||||
manifest["textures"].append(os.path.relpath(f"{d}/{f}", OUT))
|
||||
|
||||
with open(f"{OUT}/MANIFEST.json", "w") as f:
|
||||
json.dump(manifest, f, indent=1)
|
||||
print("equipment icons:", count, "| textures:", len(manifest["textures"]), "| item models:", len(manifest["item_models"]))
|
||||
|
|
|
|||
|
|
@ -1,192 +1,192 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Restyle every vanilla item sprite into the soft Dune palette (dust, brass, terracotta, sage, Fremen blue).
|
||||
|
||||
Run: python3 dune_item_grade.py ../../dune-items (reads ../../vanilla-art, ../../owner-items, custom hand-made items)
|
||||
|
||||
The effective source of each sprite is the owner-supplied sprite when one exists, otherwise the vanilla-art
|
||||
sprite. Alpha is never changed, so silhouettes, UV masks and animation frames stay exactly where they were.
|
||||
Functional colour is protected: tint layers are skipped, dye-tinted base sprites only get a lightness curve, and
|
||||
colour-coded items (dyes, bundles, candles, spawn eggs...) keep their hues with a lighter touch.
|
||||
No game assets are downloaded; this is a deterministic recolour of sprites already in the repository.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageFilter
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import soft_metals
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2] # network/resource-pack
|
||||
SOURCES = [ROOT / "vanilla-art/overlay/assets/minecraft/textures/item",
|
||||
ROOT / "owner-items/overlay/assets/minecraft/textures/item"] # later wins
|
||||
|
||||
# ------------------------------------------------------------------ colour science (OKLab)
|
||||
M1 = np.array([[0.4122214708, 0.5363325363, 0.0514459929],
|
||||
[0.2119034982, 0.6806995451, 0.1073969566],
|
||||
[0.0883024619, 0.2817188376, 0.6299787005]])
|
||||
M2 = np.array([[0.2104542553, 0.7936177850, -0.0040720468],
|
||||
[1.9779984951, -2.4285922050, 0.4505937099],
|
||||
[0.0259040371, 0.7827717662, -0.8086757660]])
|
||||
M1i, M2i = np.linalg.inv(M1), np.linalg.inv(M2)
|
||||
|
||||
|
||||
def to_lab(rgb):
|
||||
lin = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
|
||||
lms = np.cbrt(lin @ M1.T)
|
||||
return lms @ M2.T
|
||||
|
||||
|
||||
def to_rgb(lab):
|
||||
lms = (lab @ M2i.T) ** 3
|
||||
lin = np.clip(lms @ M1i.T, 0, 1)
|
||||
return np.where(lin <= 0.0031308, lin * 12.92, 1.055 * lin ** (1 / 2.4) - 0.055)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ the Dune grade
|
||||
HUE_IN = np.array([0, 30, 55, 85, 110, 135, 160, 190, 250, 300, 340, 360], dtype=float)
|
||||
HUE_OUT = np.array([14, 38, 58, 78, 92, 108, 124, 202, 258, 322, 352, 374], dtype=float) # greens -> sage, yellow -> ochre
|
||||
|
||||
MODES = {
|
||||
# chroma cmax L-lift L-gain warm hue-remap
|
||||
"dune": dict(c=.93, cmax=.15, l0=.17, lg=.82, warm=.9, remap=True),
|
||||
"mild": dict(c=.97, cmax=.17, l0=.12, lg=.88, warm=.3, remap=False),
|
||||
"neutral": dict(c=1.0, cmax=1.0, l0=.16, lg=.84, warm=0.0, remap=False),
|
||||
}
|
||||
# material families: (hue target or None, chroma scale, lightness shift)
|
||||
FAMILY = [
|
||||
(r"^(iron_|chainmail_|chain|iron$|shears|flint_and_steel|bucket|anvil)", (None, .45, 0.0)), # pewter
|
||||
(r"^(golden_|gold_)", (86, .85, 0.0)), # brass
|
||||
(r"^diamond", (232, .80, .02)), # pale water-crystal
|
||||
(r"^netherite", (None, .35, -.03)), # dark umber-ink
|
||||
(r"^copper_", (52, 1.0, -.02)),
|
||||
(r"^stone_", (80, .45, 0.0)), # sandstone
|
||||
(r"^wooden_", (62, .85, .03)), # sun-bleached wood
|
||||
]
|
||||
|
||||
SKIP = re.compile(r"(_overlay$|^filled_map_markings$|^tipped_arrow_head$)")
|
||||
NEUTRAL = re.compile(r"^(leather_(helmet|chestplate|leggings|boots|horse_armor)|wolf_armor|firework_star)$")
|
||||
MILD = re.compile(r"(_dye$|_bundle|^bundle|_candle$|_harness$|_cushion$|_spawn_egg$|_egg$|banner_pattern|^firework|^potion|^splash|^lingering|^tipped|^experience|^enchanted_book|^music_disc)")
|
||||
|
||||
|
||||
def classify(stem):
|
||||
if SKIP.search(stem):
|
||||
return "skip"
|
||||
if NEUTRAL.search(stem):
|
||||
return "neutral"
|
||||
if MILD.search(stem):
|
||||
return "mild"
|
||||
return "dune"
|
||||
|
||||
|
||||
def grade_array(rgb, alpha, mode, stem):
|
||||
p = MODES[mode]
|
||||
lab = to_lab(rgb)
|
||||
L, a, b = lab[..., 0], lab[..., 1], lab[..., 2]
|
||||
C = np.hypot(a, b)
|
||||
h = (np.degrees(np.arctan2(b, a)) + 360) % 360
|
||||
cs, dl = p["c"], 0.0
|
||||
famscale = 1.0
|
||||
if mode == "dune":
|
||||
for pattern, (hue, scale, shift) in FAMILY:
|
||||
if re.search(pattern, stem):
|
||||
cs, dl = p["c"] * scale / .8, shift
|
||||
if hue is not None:
|
||||
h = np.where(C > .02, hue, h)
|
||||
break
|
||||
else:
|
||||
pass
|
||||
if p["remap"]:
|
||||
fam = any(re.search(pt, stem) and hu is not None for pt, (hu, _, _) in FAMILY)
|
||||
if not fam:
|
||||
h = np.interp(h, HUE_IN, HUE_OUT)
|
||||
Cn = C * cs
|
||||
Cn = p["cmax"] * np.tanh(Cn / p["cmax"]) if mode != "neutral" else Cn
|
||||
Ln = p["l0"] + p["lg"] * L
|
||||
Ln = Ln - 0.05 * np.clip((Ln - .84) / .16, 0, 1) # roll highlights off, never blown white
|
||||
Ln = Ln + dl
|
||||
ys = np.linspace(1.03, .975, rgb.shape[0])[:, None] # faint sun-bleach from top to bottom
|
||||
Ln = Ln * (ys if mode != "neutral" else 1.0)
|
||||
hr = np.radians(h)
|
||||
an, bn = Cn * np.cos(hr), Cn * np.sin(hr)
|
||||
w = p["warm"]
|
||||
if w:
|
||||
neutrality = np.clip(1 - Cn / .11, 0, 1)
|
||||
shadow = np.clip(1 - Ln / .5, 0, 1)
|
||||
an = an + w * (.010 * neutrality + .012 * shadow)
|
||||
bn = bn + w * (.022 * neutrality + .020 * shadow)
|
||||
out = to_rgb(np.stack([Ln, an, bn], -1))
|
||||
out = np.clip(out, 0, 1)
|
||||
return out
|
||||
|
||||
|
||||
def grade_image(img, stem):
|
||||
mode = classify(stem)
|
||||
if mode == "skip":
|
||||
return img.copy(), mode
|
||||
arr = np.asarray(img.convert("RGBA"), dtype=np.float32) / 255.0
|
||||
rgb, alpha = arr[..., :3], arr[..., 3]
|
||||
out = grade_array(rgb, alpha, mode, stem)
|
||||
# whisper of softness: 15% blend with the local average, only between opaque neighbours
|
||||
if mode != "neutral":
|
||||
blur = np.asarray(Image.fromarray((out * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(.6)), dtype=np.float32) / 255
|
||||
out = out * .85 + blur * .15
|
||||
res = np.concatenate([out, alpha[..., None]], -1)
|
||||
res[alpha == 0, :3] = rgb[alpha == 0] # keep invisible pixels untouched
|
||||
return Image.fromarray((np.clip(res, 0, 1) * 255 + .5).astype(np.uint8), "RGBA"), mode
|
||||
|
||||
|
||||
def sources():
|
||||
files = {}
|
||||
for root in SOURCES:
|
||||
if root.is_dir():
|
||||
for p in sorted(root.glob("*.png")):
|
||||
files[p.stem] = p
|
||||
return files
|
||||
|
||||
|
||||
CUSTOM = ROOT / "central"
|
||||
CUSTOM_FILES = ( # hand-supplied custom items outside the generator; badge glyphs (item/quality) are UI and stay untouched
|
||||
[("legacy", f"assets/dunerealms/textures/item/ecology/{p.name}") for p in sorted((CUSTOM / "legacy/assets/dunerealms/textures/item/ecology").glob("*.png"))]
|
||||
+ [("overlay", f"assets/dunerealms/textures/item/{n}.png") for n in ("crysknife", "maker_tooth", "wrench")]
|
||||
+ [("overlay", "assets/dunerealms/textures/item/pillager/goldmembers_shovel_mk8.png")])
|
||||
|
||||
|
||||
def main(out_dir):
|
||||
out_root = Path(out_dir)
|
||||
out = out_root / "overlay/assets/minecraft/textures/item"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
counts, manifest = {}, {}
|
||||
authored = {f"{n}" for n in soft_metals.NAMES}
|
||||
for stem, path in sources().items():
|
||||
if stem in authored:
|
||||
img, mode = soft_metals.draw(stem), "authored"
|
||||
else:
|
||||
img, mode = grade_image(Image.open(path), stem)
|
||||
counts[mode] = counts.get(mode, 0) + 1
|
||||
target = out / f"{stem}.png"
|
||||
img.save(target, optimize=True)
|
||||
manifest[f"overlay/assets/minecraft/textures/item/{stem}.png"] = {
|
||||
"mode": mode, "size": list(img.size), "sha256": hashlib.sha256(target.read_bytes()).hexdigest()}
|
||||
for layer, rel in CUSTOM_FILES: # custom items keep their own drawing; they only get the shared Dune colour grade
|
||||
src = CUSTOM / layer / rel
|
||||
if not src.is_file():
|
||||
continue
|
||||
img, mode = grade_image(Image.open(src), Path(rel).stem)
|
||||
mode = "custom-" + mode
|
||||
target = out_root / "custom" / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
img.save(target, optimize=True)
|
||||
counts[mode] = counts.get(mode, 0) + 1
|
||||
manifest[f"custom/{rel}"] = {"mode": mode, "size": list(img.size), "sha256": hashlib.sha256(target.read_bytes()).hexdigest()}
|
||||
(out_root / "MANIFEST.json").write_text(json.dumps({"counts": counts, "files": manifest}, indent=1))
|
||||
print(counts, "total", sum(counts.values()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1] if len(sys.argv) > 1 else "out/dune-items")
|
||||
#!/usr/bin/env python3
|
||||
"""Restyle every vanilla item sprite into the soft Dune palette (dust, brass, terracotta, sage, Fremen blue).
|
||||
|
||||
Run: python3 dune_item_grade.py ../../dune-items (reads ../../vanilla-art, ../../owner-items, custom hand-made items)
|
||||
|
||||
The effective source of each sprite is the owner-supplied sprite when one exists, otherwise the vanilla-art
|
||||
sprite. Alpha is never changed, so silhouettes, UV masks and animation frames stay exactly where they were.
|
||||
Functional colour is protected: tint layers are skipped, dye-tinted base sprites only get a lightness curve, and
|
||||
colour-coded items (dyes, bundles, candles, spawn eggs...) keep their hues with a lighter touch.
|
||||
No game assets are downloaded; this is a deterministic recolour of sprites already in the repository.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageFilter
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import soft_metals
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2] # network/resource-pack
|
||||
SOURCES = [ROOT / "vanilla-art/overlay/assets/minecraft/textures/item",
|
||||
ROOT / "owner-items/overlay/assets/minecraft/textures/item"] # later wins
|
||||
|
||||
# ------------------------------------------------------------------ colour science (OKLab)
|
||||
M1 = np.array([[0.4122214708, 0.5363325363, 0.0514459929],
|
||||
[0.2119034982, 0.6806995451, 0.1073969566],
|
||||
[0.0883024619, 0.2817188376, 0.6299787005]])
|
||||
M2 = np.array([[0.2104542553, 0.7936177850, -0.0040720468],
|
||||
[1.9779984951, -2.4285922050, 0.4505937099],
|
||||
[0.0259040371, 0.7827717662, -0.8086757660]])
|
||||
M1i, M2i = np.linalg.inv(M1), np.linalg.inv(M2)
|
||||
|
||||
|
||||
def to_lab(rgb):
|
||||
lin = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
|
||||
lms = np.cbrt(lin @ M1.T)
|
||||
return lms @ M2.T
|
||||
|
||||
|
||||
def to_rgb(lab):
|
||||
lms = (lab @ M2i.T) ** 3
|
||||
lin = np.clip(lms @ M1i.T, 0, 1)
|
||||
return np.where(lin <= 0.0031308, lin * 12.92, 1.055 * lin ** (1 / 2.4) - 0.055)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ the Dune grade
|
||||
HUE_IN = np.array([0, 30, 55, 85, 110, 135, 160, 190, 250, 300, 340, 360], dtype=float)
|
||||
HUE_OUT = np.array([14, 38, 58, 78, 92, 108, 124, 202, 258, 322, 352, 374], dtype=float) # greens -> sage, yellow -> ochre
|
||||
|
||||
MODES = {
|
||||
# chroma cmax L-lift L-gain warm hue-remap
|
||||
"dune": dict(c=.93, cmax=.15, l0=.17, lg=.82, warm=.9, remap=True),
|
||||
"mild": dict(c=.97, cmax=.17, l0=.12, lg=.88, warm=.3, remap=False),
|
||||
"neutral": dict(c=1.0, cmax=1.0, l0=.16, lg=.84, warm=0.0, remap=False),
|
||||
}
|
||||
# material families: (hue target or None, chroma scale, lightness shift)
|
||||
FAMILY = [
|
||||
(r"^(iron_|chainmail_|chain|iron$|shears|flint_and_steel|bucket|anvil)", (None, .45, 0.0)), # pewter
|
||||
(r"^(golden_|gold_)", (86, .85, 0.0)), # brass
|
||||
(r"^diamond", (232, .80, .02)), # pale water-crystal
|
||||
(r"^netherite", (None, .35, -.03)), # dark umber-ink
|
||||
(r"^copper_", (52, 1.0, -.02)),
|
||||
(r"^stone_", (80, .45, 0.0)), # sandstone
|
||||
(r"^wooden_", (62, .85, .03)), # sun-bleached wood
|
||||
]
|
||||
|
||||
SKIP = re.compile(r"(_overlay$|^filled_map_markings$|^tipped_arrow_head$)")
|
||||
NEUTRAL = re.compile(r"^(leather_(helmet|chestplate|leggings|boots|horse_armor)|wolf_armor|firework_star)$")
|
||||
MILD = re.compile(r"(_dye$|_bundle|^bundle|_candle$|_harness$|_cushion$|_spawn_egg$|_egg$|banner_pattern|^firework|^potion|^splash|^lingering|^tipped|^experience|^enchanted_book|^music_disc)")
|
||||
|
||||
|
||||
def classify(stem):
|
||||
if SKIP.search(stem):
|
||||
return "skip"
|
||||
if NEUTRAL.search(stem):
|
||||
return "neutral"
|
||||
if MILD.search(stem):
|
||||
return "mild"
|
||||
return "dune"
|
||||
|
||||
|
||||
def grade_array(rgb, alpha, mode, stem):
|
||||
p = MODES[mode]
|
||||
lab = to_lab(rgb)
|
||||
L, a, b = lab[..., 0], lab[..., 1], lab[..., 2]
|
||||
C = np.hypot(a, b)
|
||||
h = (np.degrees(np.arctan2(b, a)) + 360) % 360
|
||||
cs, dl = p["c"], 0.0
|
||||
famscale = 1.0
|
||||
if mode == "dune":
|
||||
for pattern, (hue, scale, shift) in FAMILY:
|
||||
if re.search(pattern, stem):
|
||||
cs, dl = p["c"] * scale / .8, shift
|
||||
if hue is not None:
|
||||
h = np.where(C > .02, hue, h)
|
||||
break
|
||||
else:
|
||||
pass
|
||||
if p["remap"]:
|
||||
fam = any(re.search(pt, stem) and hu is not None for pt, (hu, _, _) in FAMILY)
|
||||
if not fam:
|
||||
h = np.interp(h, HUE_IN, HUE_OUT)
|
||||
Cn = C * cs
|
||||
Cn = p["cmax"] * np.tanh(Cn / p["cmax"]) if mode != "neutral" else Cn
|
||||
Ln = p["l0"] + p["lg"] * L
|
||||
Ln = Ln - 0.05 * np.clip((Ln - .84) / .16, 0, 1) # roll highlights off, never blown white
|
||||
Ln = Ln + dl
|
||||
ys = np.linspace(1.03, .975, rgb.shape[0])[:, None] # faint sun-bleach from top to bottom
|
||||
Ln = Ln * (ys if mode != "neutral" else 1.0)
|
||||
hr = np.radians(h)
|
||||
an, bn = Cn * np.cos(hr), Cn * np.sin(hr)
|
||||
w = p["warm"]
|
||||
if w:
|
||||
neutrality = np.clip(1 - Cn / .11, 0, 1)
|
||||
shadow = np.clip(1 - Ln / .5, 0, 1)
|
||||
an = an + w * (.010 * neutrality + .012 * shadow)
|
||||
bn = bn + w * (.022 * neutrality + .020 * shadow)
|
||||
out = to_rgb(np.stack([Ln, an, bn], -1))
|
||||
out = np.clip(out, 0, 1)
|
||||
return out
|
||||
|
||||
|
||||
def grade_image(img, stem):
|
||||
mode = classify(stem)
|
||||
if mode == "skip":
|
||||
return img.copy(), mode
|
||||
arr = np.asarray(img.convert("RGBA"), dtype=np.float32) / 255.0
|
||||
rgb, alpha = arr[..., :3], arr[..., 3]
|
||||
out = grade_array(rgb, alpha, mode, stem)
|
||||
# whisper of softness: 15% blend with the local average, only between opaque neighbours
|
||||
if mode != "neutral":
|
||||
blur = np.asarray(Image.fromarray((out * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(.6)), dtype=np.float32) / 255
|
||||
out = out * .85 + blur * .15
|
||||
res = np.concatenate([out, alpha[..., None]], -1)
|
||||
res[alpha == 0, :3] = rgb[alpha == 0] # keep invisible pixels untouched
|
||||
return Image.fromarray((np.clip(res, 0, 1) * 255 + .5).astype(np.uint8), "RGBA"), mode
|
||||
|
||||
|
||||
def sources():
|
||||
files = {}
|
||||
for root in SOURCES:
|
||||
if root.is_dir():
|
||||
for p in sorted(root.glob("*.png")):
|
||||
files[p.stem] = p
|
||||
return files
|
||||
|
||||
|
||||
CUSTOM = ROOT / "central"
|
||||
CUSTOM_FILES = ( # hand-supplied custom items outside the generator; badge glyphs (item/quality) are UI and stay untouched
|
||||
[("legacy", f"assets/dunerealms/textures/item/ecology/{p.name}") for p in sorted((CUSTOM / "legacy/assets/dunerealms/textures/item/ecology").glob("*.png"))]
|
||||
+ [("overlay", f"assets/dunerealms/textures/item/{n}.png") for n in ("crysknife", "maker_tooth", "wrench")]
|
||||
+ [("overlay", "assets/dunerealms/textures/item/pillager/goldmembers_shovel_mk8.png")])
|
||||
|
||||
|
||||
def main(out_dir):
|
||||
out_root = Path(out_dir)
|
||||
out = out_root / "overlay/assets/minecraft/textures/item"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
counts, manifest = {}, {}
|
||||
authored = {f"{n}" for n in soft_metals.NAMES}
|
||||
for stem, path in sources().items():
|
||||
if stem in authored:
|
||||
img, mode = soft_metals.draw(stem), "authored"
|
||||
else:
|
||||
img, mode = grade_image(Image.open(path), stem)
|
||||
counts[mode] = counts.get(mode, 0) + 1
|
||||
target = out / f"{stem}.png"
|
||||
img.save(target, optimize=True)
|
||||
manifest[f"overlay/assets/minecraft/textures/item/{stem}.png"] = {
|
||||
"mode": mode, "size": list(img.size), "sha256": hashlib.sha256(target.read_bytes()).hexdigest()}
|
||||
for layer, rel in CUSTOM_FILES: # custom items keep their own drawing; they only get the shared Dune colour grade
|
||||
src = CUSTOM / layer / rel
|
||||
if not src.is_file():
|
||||
continue
|
||||
img, mode = grade_image(Image.open(src), Path(rel).stem)
|
||||
mode = "custom-" + mode
|
||||
target = out_root / "custom" / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
img.save(target, optimize=True)
|
||||
counts[mode] = counts.get(mode, 0) + 1
|
||||
manifest[f"custom/{rel}"] = {"mode": mode, "size": list(img.size), "sha256": hashlib.sha256(target.read_bytes()).hexdigest()}
|
||||
(out_root / "MANIFEST.json").write_text(json.dumps({"counts": counts, "files": manifest}, indent=1))
|
||||
print(counts, "total", sum(counts.values()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1] if len(sys.argv) > 1 else "out/dune-items")
|
||||
|
|
|
|||
|
|
@ -1,103 +1,103 @@
|
|||
"""Soft, hand-made Dune palette and drawing helpers for item artwork.
|
||||
|
||||
Design rule (the Butlerian Jihad): no screens, holograms, circuit lattices or neon. Futurism is carried by
|
||||
clean machined geometry, brass, bone, sun-bleached cloth, spice-amber crystal and water-glass, drawn with soft
|
||||
light and warm umber shadows instead of black outlines.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
from PIL import Image, ImageChops, ImageDraw, ImageFilter
|
||||
from dunelib import Cv, SS, mix, rgb, FONT_BOLD
|
||||
|
||||
SP = dict(
|
||||
ink="#2f231b", umber="#4a3426", umber2="#6b4b36", leather="#8a5c3b", leather2="#b27c52",
|
||||
sand="#f1e4c3", sand2="#dcc594", dune="#c9a46d", dune2="#a98350", ochre="#d6a550",
|
||||
amber="#e8a23c", amber2="#f5c872", terracotta="#b5694b", clay="#cc8f70", rose="#d1a090",
|
||||
brass="#c39c50", brass2="#e6cb85", brass3="#8c6b33", bronze="#a4723f", copper="#c47f58",
|
||||
pewter="#9b9a8f", pewter2="#cfcbb9", bone="#f0e7cf", bone2="#cfc2a2",
|
||||
fremen="#41699f", fremen2="#86abd3", water="#a6d4df", water2="#5f93b8",
|
||||
sage="#8e9b6c", dusk="#7d5d72", dusk2="#a98ab0", ember="#d8744d", night="#2b2a33",
|
||||
)
|
||||
# quality tiers, softened: dust, sage, fremen blue, dusk violet, spice gold, ember
|
||||
QUAL = ["#d9cdb2", "#9db37d", "#7da7d4", "#aa8cc6", "#e6b45c", "#dc7a50"]
|
||||
|
||||
|
||||
def umber_edge(cv, mask, width=0.9, alpha=0.85, color=None):
|
||||
cv.edge(mask, color or SP["umber"], width, alpha)
|
||||
|
||||
|
||||
def soft_body(cv, mask, hi, lo, edge=None, ew=0.9, light=0.38, dark=0.22, d=1.1):
|
||||
"""gradient + gentle bevel + warm umber outline, the standard soft material"""
|
||||
cv.fill(mask, hi, lo)
|
||||
cv.bevel(mask, light, dark, d)
|
||||
cv.edge(mask, edge or SP["umber"], ew, 0.8)
|
||||
|
||||
|
||||
def warm_glow(cv, mask, color, radius, strength=0.35):
|
||||
cv.glow(mask, color, radius, strength)
|
||||
|
||||
|
||||
def rivet(cv, x, y, r=1.4, color=None):
|
||||
cv.solid(cv.circle(x + .3, y + .5, r), SP["umber"], .55)
|
||||
cv.fill(cv.circle(x, y, r), SP["brass2"], SP["brass3"])
|
||||
cv.solid(cv.circle(x - r * .3, y - r * .3, r * .35), "#fff6d8", .8)
|
||||
|
||||
|
||||
def gear(cv, cx, cy, r, teeth=10, depth=0.16, hole=0.38):
|
||||
"""machined cog: the 'old-school futuristic' motif"""
|
||||
pts = []
|
||||
n = teeth * 4
|
||||
for i in range(n):
|
||||
a = 2 * math.pi * i / n
|
||||
k = i % 4
|
||||
rr = r * (1 + depth) if k in (1, 2) else r * (1 - depth * .4)
|
||||
pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
|
||||
m = cv.poly(pts)
|
||||
if hole:
|
||||
m = ImageChops.subtract(m, cv.circle(cx, cy, r * hole))
|
||||
return m
|
||||
|
||||
|
||||
def worm_arc(cv, cx, cy, r, color, w=2.2, a=1.0, segments=9, start=200):
|
||||
"""segmented sandworm crescent"""
|
||||
for i in range(segments):
|
||||
t0 = math.radians(start + i * 17)
|
||||
t1 = t0 + math.radians(13)
|
||||
pts = [(cx + r * math.cos(t0), cy + r * math.sin(t0)), (cx + r * math.cos(t1), cy + r * math.sin(t1))]
|
||||
cv.solid(cv.line(pts, w * (0.55 + 0.45 * math.sin(i / max(1, segments - 1) * math.pi))), color, a)
|
||||
|
||||
|
||||
def dust(cv, pts, color="#fff3d2", r=0.9, a=0.8):
|
||||
for x, y in pts:
|
||||
cv.solid(cv.circle(x, y, r), color, a)
|
||||
|
||||
|
||||
def engrave(cv, mask, color=None, off=0.7):
|
||||
"""inset lettering: dark body with a light lower lip"""
|
||||
lip = ImageChops.offset(mask, int(off * SS), int(off * SS))
|
||||
cv.solid(ImageChops.subtract(lip, mask), "#fff3d4", .55)
|
||||
cv.solid(mask, color or SP["umber"], .92)
|
||||
|
||||
|
||||
def finish(cv, size=None, shadow=0.26, grain=0.018, seed=1):
|
||||
"""soft contact shadow + faint paper grain, then downsample"""
|
||||
im = cv.im
|
||||
a = im.getchannel("A")
|
||||
sh = a.filter(ImageFilter.GaussianBlur(1.3 * SS))
|
||||
sh = ImageChops.offset(sh, int(0.9 * SS), int(1.3 * SS))
|
||||
sh = sh.point(lambda v: int(v * shadow))
|
||||
under = Image.new("RGBA", im.size, rgb(SP["umber"]))
|
||||
under.putalpha(sh)
|
||||
out = Image.alpha_composite(under, im)
|
||||
if grain:
|
||||
rng = np.random.default_rng(seed)
|
||||
arr = np.asarray(out, dtype=np.float32)
|
||||
noise = rng.normal(0, grain * 255, arr.shape[:2])[..., None]
|
||||
arr[..., :3] = np.clip(arr[..., :3] + noise * (arr[..., 3:4] / 255.0), 0, 255)
|
||||
out = Image.fromarray(arr.astype(np.uint8), "RGBA")
|
||||
s = size or (cv.w, cv.h)
|
||||
return out.resize(s, Image.LANCZOS)
|
||||
|
||||
|
||||
def tint_of(tier):
|
||||
return QUAL[tier]
|
||||
"""Soft, hand-made Dune palette and drawing helpers for item artwork.
|
||||
|
||||
Design rule (the Butlerian Jihad): no screens, holograms, circuit lattices or neon. Futurism is carried by
|
||||
clean machined geometry, brass, bone, sun-bleached cloth, spice-amber crystal and water-glass, drawn with soft
|
||||
light and warm umber shadows instead of black outlines.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
from PIL import Image, ImageChops, ImageDraw, ImageFilter
|
||||
from dunelib import Cv, SS, mix, rgb, FONT_BOLD
|
||||
|
||||
SP = dict(
|
||||
ink="#2f231b", umber="#4a3426", umber2="#6b4b36", leather="#8a5c3b", leather2="#b27c52",
|
||||
sand="#f1e4c3", sand2="#dcc594", dune="#c9a46d", dune2="#a98350", ochre="#d6a550",
|
||||
amber="#e8a23c", amber2="#f5c872", terracotta="#b5694b", clay="#cc8f70", rose="#d1a090",
|
||||
brass="#c39c50", brass2="#e6cb85", brass3="#8c6b33", bronze="#a4723f", copper="#c47f58",
|
||||
pewter="#9b9a8f", pewter2="#cfcbb9", bone="#f0e7cf", bone2="#cfc2a2",
|
||||
fremen="#41699f", fremen2="#86abd3", water="#a6d4df", water2="#5f93b8",
|
||||
sage="#8e9b6c", dusk="#7d5d72", dusk2="#a98ab0", ember="#d8744d", night="#2b2a33",
|
||||
)
|
||||
# quality tiers, softened: dust, sage, fremen blue, dusk violet, spice gold, ember
|
||||
QUAL = ["#d9cdb2", "#9db37d", "#7da7d4", "#aa8cc6", "#e6b45c", "#dc7a50"]
|
||||
|
||||
|
||||
def umber_edge(cv, mask, width=0.9, alpha=0.85, color=None):
|
||||
cv.edge(mask, color or SP["umber"], width, alpha)
|
||||
|
||||
|
||||
def soft_body(cv, mask, hi, lo, edge=None, ew=0.9, light=0.38, dark=0.22, d=1.1):
|
||||
"""gradient + gentle bevel + warm umber outline, the standard soft material"""
|
||||
cv.fill(mask, hi, lo)
|
||||
cv.bevel(mask, light, dark, d)
|
||||
cv.edge(mask, edge or SP["umber"], ew, 0.8)
|
||||
|
||||
|
||||
def warm_glow(cv, mask, color, radius, strength=0.35):
|
||||
cv.glow(mask, color, radius, strength)
|
||||
|
||||
|
||||
def rivet(cv, x, y, r=1.4, color=None):
|
||||
cv.solid(cv.circle(x + .3, y + .5, r), SP["umber"], .55)
|
||||
cv.fill(cv.circle(x, y, r), SP["brass2"], SP["brass3"])
|
||||
cv.solid(cv.circle(x - r * .3, y - r * .3, r * .35), "#fff6d8", .8)
|
||||
|
||||
|
||||
def gear(cv, cx, cy, r, teeth=10, depth=0.16, hole=0.38):
|
||||
"""machined cog: the 'old-school futuristic' motif"""
|
||||
pts = []
|
||||
n = teeth * 4
|
||||
for i in range(n):
|
||||
a = 2 * math.pi * i / n
|
||||
k = i % 4
|
||||
rr = r * (1 + depth) if k in (1, 2) else r * (1 - depth * .4)
|
||||
pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
|
||||
m = cv.poly(pts)
|
||||
if hole:
|
||||
m = ImageChops.subtract(m, cv.circle(cx, cy, r * hole))
|
||||
return m
|
||||
|
||||
|
||||
def worm_arc(cv, cx, cy, r, color, w=2.2, a=1.0, segments=9, start=200):
|
||||
"""segmented sandworm crescent"""
|
||||
for i in range(segments):
|
||||
t0 = math.radians(start + i * 17)
|
||||
t1 = t0 + math.radians(13)
|
||||
pts = [(cx + r * math.cos(t0), cy + r * math.sin(t0)), (cx + r * math.cos(t1), cy + r * math.sin(t1))]
|
||||
cv.solid(cv.line(pts, w * (0.55 + 0.45 * math.sin(i / max(1, segments - 1) * math.pi))), color, a)
|
||||
|
||||
|
||||
def dust(cv, pts, color="#fff3d2", r=0.9, a=0.8):
|
||||
for x, y in pts:
|
||||
cv.solid(cv.circle(x, y, r), color, a)
|
||||
|
||||
|
||||
def engrave(cv, mask, color=None, off=0.7):
|
||||
"""inset lettering: dark body with a light lower lip"""
|
||||
lip = ImageChops.offset(mask, int(off * SS), int(off * SS))
|
||||
cv.solid(ImageChops.subtract(lip, mask), "#fff3d4", .55)
|
||||
cv.solid(mask, color or SP["umber"], .92)
|
||||
|
||||
|
||||
def finish(cv, size=None, shadow=0.26, grain=0.018, seed=1):
|
||||
"""soft contact shadow + faint paper grain, then downsample"""
|
||||
im = cv.im
|
||||
a = im.getchannel("A")
|
||||
sh = a.filter(ImageFilter.GaussianBlur(1.3 * SS))
|
||||
sh = ImageChops.offset(sh, int(0.9 * SS), int(1.3 * SS))
|
||||
sh = sh.point(lambda v: int(v * shadow))
|
||||
under = Image.new("RGBA", im.size, rgb(SP["umber"]))
|
||||
under.putalpha(sh)
|
||||
out = Image.alpha_composite(under, im)
|
||||
if grain:
|
||||
rng = np.random.default_rng(seed)
|
||||
arr = np.asarray(out, dtype=np.float32)
|
||||
noise = rng.normal(0, grain * 255, arr.shape[:2])[..., None]
|
||||
arr[..., :3] = np.clip(arr[..., :3] + noise * (arr[..., 3:4] / 255.0), 0, 255)
|
||||
out = Image.fromarray(arr.astype(np.uint8), "RGBA")
|
||||
s = size or (cv.w, cv.h)
|
||||
return out.resize(s, Image.LANCZOS)
|
||||
|
||||
|
||||
def tint_of(tier):
|
||||
return QUAL[tier]
|
||||
|
|
|
|||
|
|
@ -1,292 +1,292 @@
|
|||
"""Equipment icons in the soft Dune style: classic silhouettes, machined brass-and-bone detailing.
|
||||
|
||||
Orientation follows vanilla item sprites: handheld tools and weapons have the grip bottom-left and the working end
|
||||
top-right (hoe blade hooks to the upper-left); bow and crossbow face the upper-left.
|
||||
"""
|
||||
import math
|
||||
from dunelib import Cv, SS, mix, rgb
|
||||
from dunesoft import *
|
||||
|
||||
TOOLS = ["sword", "pickaxe", "axe", "shovel", "hoe", "bow", "crossbow", "mace", "trident"]
|
||||
ARMOUR = ["helmet", "chestplate", "leggings", "boots", "elytra"]
|
||||
TYPES = TOOLS + ARMOUR
|
||||
HANDHELD = set(TOOLS)
|
||||
QUALITY = ["common", "uncommon", "rare", "very_rare", "legendary", "mythic"]
|
||||
|
||||
|
||||
def valid_marks():
|
||||
out = []
|
||||
for m in range(15):
|
||||
out.append((QUALITY[m // 3], m))
|
||||
out.append(("mythic", 14))
|
||||
return out
|
||||
|
||||
|
||||
class Axis:
|
||||
"""Local (u along the tool, v across) -> 64px canvas. 'ne' = grip bottom-left, head top-right."""
|
||||
def __init__(self, facing="ne", k=0.78, origin=(27, 33), u0=32):
|
||||
s = math.sqrt(.5)
|
||||
self.k, self.origin, self.u0 = k, origin, u0
|
||||
if facing == "ne":
|
||||
self.d, self.n = (s, -s), (s, s)
|
||||
else: # 'nw': working end toward the upper-left, v positive toward the upper-right
|
||||
self.d, self.n = (-s, -s), (s, -s)
|
||||
|
||||
def T(self, u, v):
|
||||
x = self.origin[0] + ((u - self.u0) * self.d[0] + v * self.n[0]) * self.k
|
||||
y = self.origin[1] + ((u - self.u0) * self.d[1] + v * self.n[1]) * self.k
|
||||
return (x, y)
|
||||
|
||||
def P(self, pts):
|
||||
return [self.T(u, v) for u, v in pts]
|
||||
|
||||
|
||||
def metal(cv, mask, tier, dark=False):
|
||||
"""beaten brass, nudged toward the quality colour; 'dark' is aged bronze for guards and collars"""
|
||||
q = QUAL[tier]
|
||||
if dark:
|
||||
hi, lo = mix(SP["bronze"], q, .12), mix(SP["umber2"], SP["umber"], .4)
|
||||
else:
|
||||
hi, lo = mix(SP["brass2"], q, .42), mix(mix(SP["brass3"], SP["umber2"], .25), q, .22)
|
||||
soft_body(cv, mask, hi, lo, ew=.85, light=.4, dark=.25, d=1.0)
|
||||
|
||||
|
||||
def inlay(cv, pts, tier, width=1.0):
|
||||
m = cv.line(pts, width)
|
||||
if tier >= 3:
|
||||
warm_glow(cv, m, QUAL[tier], 1.3 + (tier - 3) * .5, .28)
|
||||
cv.solid(m, mix(QUAL[tier], "#fff6dc", .3))
|
||||
|
||||
|
||||
def pips(cv, tier, count):
|
||||
for i in range(count):
|
||||
c = cv.circle(7 + i * 5.2, 57, 1.7)
|
||||
cv.fill(c, mix(QUAL[tier], "#fff6dc", .45), QUAL[tier])
|
||||
cv.edge(c, SP["umber"], .45, .8)
|
||||
|
||||
|
||||
def aura(cv, tier):
|
||||
if tier >= 3:
|
||||
warm_glow(cv, cv.circle(32, 32, 17 + tier * 1.4), QUAL[tier], 10, .10 + .04 * (tier - 3))
|
||||
if tier >= 4:
|
||||
dust(cv, [(52, 12), (13, 20), (54, 46)], "#fff0cc", .7, .55)
|
||||
|
||||
|
||||
def wrap_handle(cv, t, u0=0, u1=46, half=3.0):
|
||||
"""leather-wrapped grip with brass ferrule rings"""
|
||||
h = cv.poly(t.P([(u0, -half), (u1, -half), (u1, half), (u0, half)]))
|
||||
cv.fill(h, SP["leather2"], SP["umber2"])
|
||||
cv.edge(h, SP["umber"], .7, .85)
|
||||
for u in range(int(u0) + 5, int(u1) - 2, 5): # diagonal wrap bands
|
||||
cv.solid(cv.clip(cv.line(t.P([(u, -half), (u + 3, half)]), .8), h), SP["umber"], .5)
|
||||
ring = cv.poly(t.P([(u1 - 3, -half - .6), (u1, -half - .6), (u1, half + .6), (u1 - 3, half + .6)]))
|
||||
cv.fill(ring, SP["brass2"], SP["brass3"])
|
||||
cv.edge(ring, SP["umber"], .4, .8)
|
||||
|
||||
|
||||
def socket(cv, t, tier, u, half=4.4, length=4):
|
||||
s = cv.poly(t.P([(u, -half), (u + length, -half), (u + length, half), (u, half)]))
|
||||
metal(cv, s, tier, True)
|
||||
|
||||
|
||||
def draw_tool(kind, tier, pip_count):
|
||||
cv = Cv(64)
|
||||
aura(cv, tier)
|
||||
t = Axis("nw", k=.66, origin=(34, 34), u0=14) if kind in ("bow", "crossbow") else Axis("ne")
|
||||
q = QUAL[tier]
|
||||
if kind == "sword":
|
||||
wrap_handle(cv, t, 0, 17, 2.8)
|
||||
pom = gear(cv, *t.T(0, 0), 3.4, 8, .15, .3)
|
||||
cv.fill(pom, SP["brass2"], SP["brass3"]); cv.edge(pom, SP["umber"], .4, .8)
|
||||
guard = cv.poly(t.P([(15, -13), (19, -15), (23, -12), (23, 12), (19, 15), (15, 13), (17, 0)]))
|
||||
metal(cv, guard, tier, True)
|
||||
blade = cv.poly(t.P([(23, -5.6), (55, -5.6), (67, 0), (55, 5.6), (23, 5.6)]))
|
||||
cv.fill(blade, SP["bone"], SP["bone2"])
|
||||
cv.bevel(blade, .6, .3, 1.0)
|
||||
cv.edge(blade, SP["umber"], .75, .75)
|
||||
cv.solid(cv.clip(blade, cv.poly(t.P([(23, 0), (67, 0), (67, 5.6), (23, 5.6)]))), SP["bone2"], .55)
|
||||
inlay(cv, t.P([(26, 0), (58, 0)]), tier, .9)
|
||||
elif kind == "pickaxe":
|
||||
wrap_handle(cv, t, 0, 56, 2.8)
|
||||
outer, inner = [], []
|
||||
for i in range(-12, 13):
|
||||
q2 = i / 12
|
||||
outer.append((38 + 22 * (1 - q2 * q2), 31 * q2))
|
||||
inner.append((38 + 22 * (1 - q2 * q2) - 11 * (1 - q2 * q2) ** .8, 31 * q2))
|
||||
head = cv.poly(t.P(outer + list(reversed(inner))))
|
||||
metal(cv, head, tier)
|
||||
inlay(cv, t.P([(u - 5.5 * (1 - (v / 31) ** 2), v * .78) for u, v in outer[4:-4]]), tier, .9)
|
||||
socket(cv, t, tier, 48, 4.2, 4.5)
|
||||
elif kind == "axe":
|
||||
wrap_handle(cv, t, 0, 52, 2.8)
|
||||
head = cv.poly(t.P([(41, -4), (55, -4), (62, 3), (69, 14), (67, 30), (57, 38), (46, 33), (41, 20)]))
|
||||
metal(cv, head, tier)
|
||||
cv.solid(cv.line(t.P([(66, 15), (65, 30), (58, 36)]), .9), "#fff1cf", .55) # honed edge
|
||||
inlay(cv, t.P([(48, 10), (56, 14), (58, 26)]), tier, .9)
|
||||
socket(cv, t, tier, 40, 4.2, 4.5)
|
||||
elif kind == "shovel":
|
||||
wrap_handle(cv, t, 0, 40, 2.6)
|
||||
grip = cv.poly(t.P([(0, -5.5), (4, -5.5), (4, 5.5), (0, 5.5)]))
|
||||
cv.fill(grip, SP["brass2"], SP["brass3"]); cv.edge(grip, SP["umber"], .5, .8)
|
||||
blade = cv.poly(t.P([(38, -3), (46, -11), (60, -11), (69, 0), (60, 11), (46, 11), (38, 3)]))
|
||||
metal(cv, blade, tier)
|
||||
inlay(cv, t.P([(46, 0), (62, 0)]), tier, .9)
|
||||
for v in (-6, 6):
|
||||
cv.solid(cv.line(t.P([(48, v), (60, v * .8)]), .6), SP["umber"], .45)
|
||||
elif kind == "hoe":
|
||||
wrap_handle(cv, t, 0, 58, 2.8)
|
||||
head = cv.poly(t.P([(44, 3.2), (62, 3.2), (67, -4), (66, -27), (56, -31), (56, -12), (44, -12)]))
|
||||
metal(cv, head, tier)
|
||||
inlay(cv, t.P([(62, -6), (61.5, -24)]), tier, .9)
|
||||
socket(cv, t, tier, 40, 4.2, 4.5)
|
||||
elif kind == "bow":
|
||||
pts = [(24 - 29 * (i / 12) ** 2, 29 * i / 12) for i in range(-12, 13)]
|
||||
# composite limb: bone core under leather, brass cam wheels at the tips
|
||||
limb = cv.line(t.P(pts), 4.2)
|
||||
cv.fill(limb, SP["bone2"], SP["dune2"])
|
||||
cv.edge(limb, SP["umber"], .8, .85)
|
||||
grip = cv.line(t.P([(24, -5), (24, 5)]), 5.2)
|
||||
cv.fill(grip, SP["leather2"], SP["umber2"]); cv.edge(grip, SP["umber"], .5, .8)
|
||||
for p in (pts[0], pts[-1]):
|
||||
cx, cy = t.T(*p)
|
||||
cam = gear(cv, cx, cy, 2.9, 8, .16, .35)
|
||||
cv.fill(cam, SP["brass2"], SP["brass3"]); cv.edge(cam, SP["umber"], .4, .85)
|
||||
cv.solid(cv.line(t.P([pts[0], pts[-1]]), .65), SP["umber"], .8)
|
||||
arrow = cv.line(t.P([(-1, 0), (42, 0)]), .9)
|
||||
cv.solid(arrow, SP["bone"])
|
||||
cv.solid(cv.poly(t.P([(42, -2.2), (49, 0), (42, 2.2)])), mix(q, SP["brass2"], .4))
|
||||
cv.solid(cv.line(t.P([(-3, -1.6), (3, 0), (-3, 1.6)]), .8), q, .9)
|
||||
elif kind == "crossbow":
|
||||
# stock runs bottom-right -> upper-left
|
||||
stock = cv.poly(t.P([(-14, -3), (30, -3.6), (44, -2.2), (44, 2.2), (30, 3.6), (-14, 3)]))
|
||||
cv.fill(stock, SP["leather2"], SP["umber2"]); cv.edge(stock, SP["umber"], .8, .85)
|
||||
cv.solid(cv.clip(stock, cv.poly(t.P([(-14, 0), (44, 0), (44, 3), (-14, 3)]))), SP["umber"], .22)
|
||||
pts = [(40 - 9 * (1 - (i / 12) ** 2), 27 * i / 12) for i in range(-12, 13)]
|
||||
limb = cv.line(t.P(pts), 4.4)
|
||||
metal(cv, limb, tier)
|
||||
cv.solid(cv.line(t.P([pts[0], (28, 0), pts[-1]]), .65), SP["umber"], .85)
|
||||
crank = gear(cv, *t.T(12, 0), 4.2, 9, .16, .4)
|
||||
cv.fill(crank, SP["brass2"], SP["brass3"]); cv.edge(crank, SP["umber"], .45, .85)
|
||||
inlay(cv, t.P([(30, 0), (52, 0)]), tier, .8)
|
||||
cv.solid(cv.poly(t.P([(52, -2.2), (60, 0), (52, 2.2)])), mix(q, SP["brass2"], .4))
|
||||
elif kind == "mace":
|
||||
wrap_handle(cv, t, 0, 46, 2.8)
|
||||
cx, cy = t.T(56, 0)
|
||||
for i in range(8):
|
||||
a = math.radians(i * 45 + 22.5)
|
||||
sp = cv.poly([(cx + 9 * math.cos(a - .34), cy + 9 * math.sin(a - .34)), (cx + 16.5 * math.cos(a), cy + 16.5 * math.sin(a)), (cx + 9 * math.cos(a + .34), cy + 9 * math.sin(a + .34))])
|
||||
metal(cv, sp, tier, True)
|
||||
ball = cv.circle(cx, cy, 10.5)
|
||||
metal(cv, ball, tier)
|
||||
cv.solid(cv.circle(cx - 3, cy - 3, 3.2), "#fff3d0", .35)
|
||||
gem = cv.circle(cx, cy, 3.4)
|
||||
warm_glow(cv, gem, q, 2, .35)
|
||||
cv.fill(gem, mix(q, "#ffffff", .5), q); cv.edge(gem, SP["umber"], .4, .8)
|
||||
elif kind == "trident":
|
||||
wrap_handle(cv, t, 0, 52, 2.6)
|
||||
for v in (-11, 11):
|
||||
prong = cv.line(t.P([(46, 0), (50, v), (61, v), (67, v * .9)]), 2.2)
|
||||
metal(cv, prong, tier)
|
||||
cv.solid(cv.poly(t.P([(66, v * .9 - 2), (73, v * .9), (66, v * .9 + 2)])), SP["bone"])
|
||||
mid = cv.poly(t.P([(49, -1.8), (66, -1.8), (74, 0), (66, 1.8), (49, 1.8)]))
|
||||
cv.fill(mid, SP["bone"], SP["bone2"]); cv.edge(mid, SP["umber"], .6, .8)
|
||||
bar = cv.poly(t.P([(44, -11.5), (47.5, -11.5), (47.5, 11.5), (44, 11.5)]))
|
||||
metal(cv, bar, tier, True)
|
||||
rivet(cv, *t.T(45.7, 0), 1.5)
|
||||
pips(cv, tier, pip_count)
|
||||
return finish(cv, seed=ord(kind[0]) + tier)
|
||||
|
||||
|
||||
def sym(pts_left):
|
||||
return pts_left + [(64 - x, y) for x, y in reversed(pts_left)]
|
||||
|
||||
|
||||
def cloth(cv, mask, tier, dark=False):
|
||||
"""sun-bleached stillsuit fabric"""
|
||||
hi, lo = (SP["dune"], SP["dune2"]) if not dark else (SP["dune2"], SP["umber2"])
|
||||
soft_body(cv, mask, mix(mix(hi, "#fff4d8", .12), QUAL[tier], .2 if tier else 0), mix(lo, QUAL[tier], .2 if tier else 0), ew=.85, light=.3, dark=.22)
|
||||
|
||||
|
||||
def trim_band(cv, pts, tier, w=1.0):
|
||||
m = cv.line(pts, w)
|
||||
cv.solid(m, mix(QUAL[tier], SP["brass2"], .25))
|
||||
|
||||
|
||||
def tubes(cv, pts, w=.9):
|
||||
"""catchtube: dark hose with a water-blue glint"""
|
||||
cv.solid(cv.line(pts, w + .8), SP["umber"], .8)
|
||||
cv.solid(cv.line(pts, w * .5), SP["water2"], .9)
|
||||
|
||||
|
||||
def draw_armour(kind, tier, pip_count):
|
||||
cv = Cv(64)
|
||||
aura(cv, tier)
|
||||
q = QUAL[tier]
|
||||
if kind == "helmet":
|
||||
left = [(32, 5), (22, 7), (13, 15), (9, 27), (9, 44), (13, 52), (21, 52), (21, 42), (26, 40)]
|
||||
hood = cv.poly(left + [(64 - x, y) for x, y in reversed(left)])
|
||||
cloth(cv, hood, tier)
|
||||
mask = cv.poly([(15, 29), (49, 29), (47, 40), (41, 44), (23, 44), (17, 40)]) # face veil
|
||||
cv.fill(mask, SP["sand2"], SP["dune"]); cv.edge(mask, SP["umber"], .7, .8)
|
||||
visor = cv.poly([(16, 31), (48, 31), (46, 36), (18, 36)])
|
||||
cv.fill(visor, SP["night"], "#14121a"); cv.edge(visor, SP["umber"], .5, .8)
|
||||
cv.solid(cv.line([(19, 33.5), (45, 33.5)], 1.0), mix(SP["fremen2"], "#ffffff", .15), .95) # eye slit
|
||||
trim_band(cv, [(32, 8), (32, 27)], tier, 1.3)
|
||||
tubes(cv, [(21, 41), (18, 50)]); tubes(cv, [(43, 41), (46, 50)])
|
||||
n = cv.poly([(28, 6), (32, 2), (36, 6)]); metal(cv, n, tier)
|
||||
elif kind == "chestplate":
|
||||
left = [(32, 12), (26, 10), (20, 7), (9, 12), (4, 24), (10, 32), (15, 30), (15, 57), (32, 57)]
|
||||
body = cv.poly(left + [(64 - x, y) for x, y in reversed(left)])
|
||||
cloth(cv, body, tier)
|
||||
yoke = cv.poly([(20, 8), (32, 14), (44, 8), (44, 17), (32, 22), (20, 17)])
|
||||
cv.fill(yoke, SP["leather2"], SP["umber2"]); cv.edge(yoke, SP["umber"], .6, .8)
|
||||
tubes(cv, [(20, 20), (19, 36), (24, 50)]); tubes(cv, [(44, 20), (45, 36), (40, 50)])
|
||||
buckle = gear(cv, 32, 33, 7.2, 10, .13, .42)
|
||||
cv.fill(buckle, SP["brass2"], SP["brass3"]); cv.edge(buckle, SP["umber"], .5, .85)
|
||||
cv.solid(cv.circle(32, 33, 2.4), mix(q, "#fff4d8", .35))
|
||||
trim_band(cv, [(9, 14), (16, 21)], tier, 1.1); trim_band(cv, [(55, 14), (48, 21)], tier, 1.1)
|
||||
trim_band(cv, [(16, 54), (48, 54)], tier, 1.2)
|
||||
elif kind == "leggings":
|
||||
body = cv.poly([(13, 6), (51, 6), (53, 56), (37, 56), (32, 22), (27, 56), (11, 56)])
|
||||
cloth(cv, body, tier)
|
||||
belt = cv.rrect(13, 6, 51, 14, 2)
|
||||
cv.fill(belt, SP["leather2"], SP["umber2"]); cv.edge(belt, SP["umber"], .6, .85)
|
||||
bk = gear(cv, 32, 10, 3.4, 8, .15, .3)
|
||||
cv.fill(bk, SP["brass2"], SP["brass3"]); cv.edge(bk, SP["umber"], .4, .85)
|
||||
tubes(cv, [(20, 16), (19, 50)]); tubes(cv, [(44, 16), (45, 50)])
|
||||
trim_band(cv, [(12, 52), (28, 52)], tier, 1.1); trim_band(cv, [(36, 52), (52, 52)], tier, 1.1)
|
||||
elif kind == "boots":
|
||||
for ox, mirror in ((0, 1), (32, -1)):
|
||||
def X(x):
|
||||
return ox + (x if mirror == 1 else 32 - x)
|
||||
b = cv.poly([(X(7), 10), (X(24), 10), (X(24), 38), (X(31), 44), (X(31), 54), (X(4), 54), (X(6), 38)])
|
||||
soft_body(cv, b, SP["leather2"], SP["umber2"], ew=.85)
|
||||
cuff = cv.rrect(min(X(7), X(24)), 10, max(X(7), X(24)), 15, 1.5)
|
||||
cv.fill(cuff, SP["dune"], SP["dune2"]); cv.edge(cuff, SP["umber"], .5, .8)
|
||||
trim_band(cv, [(X(8), 47), (X(28), 47)], tier, 1.1)
|
||||
for yy in (22, 30):
|
||||
cv.solid(cv.line([(X(9), yy), (X(22), yy)], .7), SP["brass2"], .9)
|
||||
elif kind == "elytra":
|
||||
left = [(31, 8), (19, 9), (7, 16), (3, 32), (8, 48), (20, 57), (30, 50), (31, 30)]
|
||||
for side in (0, 1):
|
||||
pts = left if side == 0 else [(64 - x, y) for x, y in left]
|
||||
w = cv.poly(pts)
|
||||
cv.fill(w, mix(SP["sand2"], "#ffffff", .1), SP["dune2"])
|
||||
cv.bevel(w, .35, .25, 1)
|
||||
cv.edge(w, SP["umber"], .85, .85)
|
||||
for k in range(1, 5): # brass ribs like an ornithopter wing
|
||||
f = k / 5
|
||||
a = (31, 14 + f * 6)
|
||||
b2 = (6 + f * 2, 18 + f * 32)
|
||||
if side:
|
||||
a, b2 = (64 - a[0], a[1]), (64 - b2[0], b2[1])
|
||||
cv.solid(cv.line([a, b2], .8), SP["brass3"], .9)
|
||||
trim_band(cv, [pts[1], pts[2], pts[3]], tier, .9)
|
||||
hub = gear(cv, 32, 28, 4.2, 8, .16, .4)
|
||||
cv.fill(hub, SP["brass2"], SP["brass3"]); cv.edge(hub, SP["umber"], .45, .85)
|
||||
pips(cv, tier, pip_count)
|
||||
return finish(cv, seed=ord(kind[0]) + tier * 3)
|
||||
|
||||
|
||||
def draw(kind, tier, pip_count):
|
||||
return draw_tool(kind, tier, pip_count) if kind in HANDHELD else draw_armour(kind, tier, pip_count)
|
||||
"""Equipment icons in the soft Dune style: classic silhouettes, machined brass-and-bone detailing.
|
||||
|
||||
Orientation follows vanilla item sprites: handheld tools and weapons have the grip bottom-left and the working end
|
||||
top-right (hoe blade hooks to the upper-left); bow and crossbow face the upper-left.
|
||||
"""
|
||||
import math
|
||||
from dunelib import Cv, SS, mix, rgb
|
||||
from dunesoft import *
|
||||
|
||||
TOOLS = ["sword", "pickaxe", "axe", "shovel", "hoe", "bow", "crossbow", "mace", "trident"]
|
||||
ARMOUR = ["helmet", "chestplate", "leggings", "boots", "elytra"]
|
||||
TYPES = TOOLS + ARMOUR
|
||||
HANDHELD = set(TOOLS)
|
||||
QUALITY = ["common", "uncommon", "rare", "very_rare", "legendary", "mythic"]
|
||||
|
||||
|
||||
def valid_marks():
|
||||
out = []
|
||||
for m in range(15):
|
||||
out.append((QUALITY[m // 3], m))
|
||||
out.append(("mythic", 14))
|
||||
return out
|
||||
|
||||
|
||||
class Axis:
|
||||
"""Local (u along the tool, v across) -> 64px canvas. 'ne' = grip bottom-left, head top-right."""
|
||||
def __init__(self, facing="ne", k=0.78, origin=(27, 33), u0=32):
|
||||
s = math.sqrt(.5)
|
||||
self.k, self.origin, self.u0 = k, origin, u0
|
||||
if facing == "ne":
|
||||
self.d, self.n = (s, -s), (s, s)
|
||||
else: # 'nw': working end toward the upper-left, v positive toward the upper-right
|
||||
self.d, self.n = (-s, -s), (s, -s)
|
||||
|
||||
def T(self, u, v):
|
||||
x = self.origin[0] + ((u - self.u0) * self.d[0] + v * self.n[0]) * self.k
|
||||
y = self.origin[1] + ((u - self.u0) * self.d[1] + v * self.n[1]) * self.k
|
||||
return (x, y)
|
||||
|
||||
def P(self, pts):
|
||||
return [self.T(u, v) for u, v in pts]
|
||||
|
||||
|
||||
def metal(cv, mask, tier, dark=False):
|
||||
"""beaten brass, nudged toward the quality colour; 'dark' is aged bronze for guards and collars"""
|
||||
q = QUAL[tier]
|
||||
if dark:
|
||||
hi, lo = mix(SP["bronze"], q, .12), mix(SP["umber2"], SP["umber"], .4)
|
||||
else:
|
||||
hi, lo = mix(SP["brass2"], q, .42), mix(mix(SP["brass3"], SP["umber2"], .25), q, .22)
|
||||
soft_body(cv, mask, hi, lo, ew=.85, light=.4, dark=.25, d=1.0)
|
||||
|
||||
|
||||
def inlay(cv, pts, tier, width=1.0):
|
||||
m = cv.line(pts, width)
|
||||
if tier >= 3:
|
||||
warm_glow(cv, m, QUAL[tier], 1.3 + (tier - 3) * .5, .28)
|
||||
cv.solid(m, mix(QUAL[tier], "#fff6dc", .3))
|
||||
|
||||
|
||||
def pips(cv, tier, count):
|
||||
for i in range(count):
|
||||
c = cv.circle(7 + i * 5.2, 57, 1.7)
|
||||
cv.fill(c, mix(QUAL[tier], "#fff6dc", .45), QUAL[tier])
|
||||
cv.edge(c, SP["umber"], .45, .8)
|
||||
|
||||
|
||||
def aura(cv, tier):
|
||||
if tier >= 3:
|
||||
warm_glow(cv, cv.circle(32, 32, 17 + tier * 1.4), QUAL[tier], 10, .10 + .04 * (tier - 3))
|
||||
if tier >= 4:
|
||||
dust(cv, [(52, 12), (13, 20), (54, 46)], "#fff0cc", .7, .55)
|
||||
|
||||
|
||||
def wrap_handle(cv, t, u0=0, u1=46, half=3.0):
|
||||
"""leather-wrapped grip with brass ferrule rings"""
|
||||
h = cv.poly(t.P([(u0, -half), (u1, -half), (u1, half), (u0, half)]))
|
||||
cv.fill(h, SP["leather2"], SP["umber2"])
|
||||
cv.edge(h, SP["umber"], .7, .85)
|
||||
for u in range(int(u0) + 5, int(u1) - 2, 5): # diagonal wrap bands
|
||||
cv.solid(cv.clip(cv.line(t.P([(u, -half), (u + 3, half)]), .8), h), SP["umber"], .5)
|
||||
ring = cv.poly(t.P([(u1 - 3, -half - .6), (u1, -half - .6), (u1, half + .6), (u1 - 3, half + .6)]))
|
||||
cv.fill(ring, SP["brass2"], SP["brass3"])
|
||||
cv.edge(ring, SP["umber"], .4, .8)
|
||||
|
||||
|
||||
def socket(cv, t, tier, u, half=4.4, length=4):
|
||||
s = cv.poly(t.P([(u, -half), (u + length, -half), (u + length, half), (u, half)]))
|
||||
metal(cv, s, tier, True)
|
||||
|
||||
|
||||
def draw_tool(kind, tier, pip_count):
|
||||
cv = Cv(64)
|
||||
aura(cv, tier)
|
||||
t = Axis("nw", k=.66, origin=(34, 34), u0=14) if kind in ("bow", "crossbow") else Axis("ne")
|
||||
q = QUAL[tier]
|
||||
if kind == "sword":
|
||||
wrap_handle(cv, t, 0, 17, 2.8)
|
||||
pom = gear(cv, *t.T(0, 0), 3.4, 8, .15, .3)
|
||||
cv.fill(pom, SP["brass2"], SP["brass3"]); cv.edge(pom, SP["umber"], .4, .8)
|
||||
guard = cv.poly(t.P([(15, -13), (19, -15), (23, -12), (23, 12), (19, 15), (15, 13), (17, 0)]))
|
||||
metal(cv, guard, tier, True)
|
||||
blade = cv.poly(t.P([(23, -5.6), (55, -5.6), (67, 0), (55, 5.6), (23, 5.6)]))
|
||||
cv.fill(blade, SP["bone"], SP["bone2"])
|
||||
cv.bevel(blade, .6, .3, 1.0)
|
||||
cv.edge(blade, SP["umber"], .75, .75)
|
||||
cv.solid(cv.clip(blade, cv.poly(t.P([(23, 0), (67, 0), (67, 5.6), (23, 5.6)]))), SP["bone2"], .55)
|
||||
inlay(cv, t.P([(26, 0), (58, 0)]), tier, .9)
|
||||
elif kind == "pickaxe":
|
||||
wrap_handle(cv, t, 0, 56, 2.8)
|
||||
outer, inner = [], []
|
||||
for i in range(-12, 13):
|
||||
q2 = i / 12
|
||||
outer.append((38 + 22 * (1 - q2 * q2), 31 * q2))
|
||||
inner.append((38 + 22 * (1 - q2 * q2) - 11 * (1 - q2 * q2) ** .8, 31 * q2))
|
||||
head = cv.poly(t.P(outer + list(reversed(inner))))
|
||||
metal(cv, head, tier)
|
||||
inlay(cv, t.P([(u - 5.5 * (1 - (v / 31) ** 2), v * .78) for u, v in outer[4:-4]]), tier, .9)
|
||||
socket(cv, t, tier, 48, 4.2, 4.5)
|
||||
elif kind == "axe":
|
||||
wrap_handle(cv, t, 0, 52, 2.8)
|
||||
head = cv.poly(t.P([(41, -4), (55, -4), (62, 3), (69, 14), (67, 30), (57, 38), (46, 33), (41, 20)]))
|
||||
metal(cv, head, tier)
|
||||
cv.solid(cv.line(t.P([(66, 15), (65, 30), (58, 36)]), .9), "#fff1cf", .55) # honed edge
|
||||
inlay(cv, t.P([(48, 10), (56, 14), (58, 26)]), tier, .9)
|
||||
socket(cv, t, tier, 40, 4.2, 4.5)
|
||||
elif kind == "shovel":
|
||||
wrap_handle(cv, t, 0, 40, 2.6)
|
||||
grip = cv.poly(t.P([(0, -5.5), (4, -5.5), (4, 5.5), (0, 5.5)]))
|
||||
cv.fill(grip, SP["brass2"], SP["brass3"]); cv.edge(grip, SP["umber"], .5, .8)
|
||||
blade = cv.poly(t.P([(38, -3), (46, -11), (60, -11), (69, 0), (60, 11), (46, 11), (38, 3)]))
|
||||
metal(cv, blade, tier)
|
||||
inlay(cv, t.P([(46, 0), (62, 0)]), tier, .9)
|
||||
for v in (-6, 6):
|
||||
cv.solid(cv.line(t.P([(48, v), (60, v * .8)]), .6), SP["umber"], .45)
|
||||
elif kind == "hoe":
|
||||
wrap_handle(cv, t, 0, 58, 2.8)
|
||||
head = cv.poly(t.P([(44, 3.2), (62, 3.2), (67, -4), (66, -27), (56, -31), (56, -12), (44, -12)]))
|
||||
metal(cv, head, tier)
|
||||
inlay(cv, t.P([(62, -6), (61.5, -24)]), tier, .9)
|
||||
socket(cv, t, tier, 40, 4.2, 4.5)
|
||||
elif kind == "bow":
|
||||
pts = [(24 - 29 * (i / 12) ** 2, 29 * i / 12) for i in range(-12, 13)]
|
||||
# composite limb: bone core under leather, brass cam wheels at the tips
|
||||
limb = cv.line(t.P(pts), 4.2)
|
||||
cv.fill(limb, SP["bone2"], SP["dune2"])
|
||||
cv.edge(limb, SP["umber"], .8, .85)
|
||||
grip = cv.line(t.P([(24, -5), (24, 5)]), 5.2)
|
||||
cv.fill(grip, SP["leather2"], SP["umber2"]); cv.edge(grip, SP["umber"], .5, .8)
|
||||
for p in (pts[0], pts[-1]):
|
||||
cx, cy = t.T(*p)
|
||||
cam = gear(cv, cx, cy, 2.9, 8, .16, .35)
|
||||
cv.fill(cam, SP["brass2"], SP["brass3"]); cv.edge(cam, SP["umber"], .4, .85)
|
||||
cv.solid(cv.line(t.P([pts[0], pts[-1]]), .65), SP["umber"], .8)
|
||||
arrow = cv.line(t.P([(-1, 0), (42, 0)]), .9)
|
||||
cv.solid(arrow, SP["bone"])
|
||||
cv.solid(cv.poly(t.P([(42, -2.2), (49, 0), (42, 2.2)])), mix(q, SP["brass2"], .4))
|
||||
cv.solid(cv.line(t.P([(-3, -1.6), (3, 0), (-3, 1.6)]), .8), q, .9)
|
||||
elif kind == "crossbow":
|
||||
# stock runs bottom-right -> upper-left
|
||||
stock = cv.poly(t.P([(-14, -3), (30, -3.6), (44, -2.2), (44, 2.2), (30, 3.6), (-14, 3)]))
|
||||
cv.fill(stock, SP["leather2"], SP["umber2"]); cv.edge(stock, SP["umber"], .8, .85)
|
||||
cv.solid(cv.clip(stock, cv.poly(t.P([(-14, 0), (44, 0), (44, 3), (-14, 3)]))), SP["umber"], .22)
|
||||
pts = [(40 - 9 * (1 - (i / 12) ** 2), 27 * i / 12) for i in range(-12, 13)]
|
||||
limb = cv.line(t.P(pts), 4.4)
|
||||
metal(cv, limb, tier)
|
||||
cv.solid(cv.line(t.P([pts[0], (28, 0), pts[-1]]), .65), SP["umber"], .85)
|
||||
crank = gear(cv, *t.T(12, 0), 4.2, 9, .16, .4)
|
||||
cv.fill(crank, SP["brass2"], SP["brass3"]); cv.edge(crank, SP["umber"], .45, .85)
|
||||
inlay(cv, t.P([(30, 0), (52, 0)]), tier, .8)
|
||||
cv.solid(cv.poly(t.P([(52, -2.2), (60, 0), (52, 2.2)])), mix(q, SP["brass2"], .4))
|
||||
elif kind == "mace":
|
||||
wrap_handle(cv, t, 0, 46, 2.8)
|
||||
cx, cy = t.T(56, 0)
|
||||
for i in range(8):
|
||||
a = math.radians(i * 45 + 22.5)
|
||||
sp = cv.poly([(cx + 9 * math.cos(a - .34), cy + 9 * math.sin(a - .34)), (cx + 16.5 * math.cos(a), cy + 16.5 * math.sin(a)), (cx + 9 * math.cos(a + .34), cy + 9 * math.sin(a + .34))])
|
||||
metal(cv, sp, tier, True)
|
||||
ball = cv.circle(cx, cy, 10.5)
|
||||
metal(cv, ball, tier)
|
||||
cv.solid(cv.circle(cx - 3, cy - 3, 3.2), "#fff3d0", .35)
|
||||
gem = cv.circle(cx, cy, 3.4)
|
||||
warm_glow(cv, gem, q, 2, .35)
|
||||
cv.fill(gem, mix(q, "#ffffff", .5), q); cv.edge(gem, SP["umber"], .4, .8)
|
||||
elif kind == "trident":
|
||||
wrap_handle(cv, t, 0, 52, 2.6)
|
||||
for v in (-11, 11):
|
||||
prong = cv.line(t.P([(46, 0), (50, v), (61, v), (67, v * .9)]), 2.2)
|
||||
metal(cv, prong, tier)
|
||||
cv.solid(cv.poly(t.P([(66, v * .9 - 2), (73, v * .9), (66, v * .9 + 2)])), SP["bone"])
|
||||
mid = cv.poly(t.P([(49, -1.8), (66, -1.8), (74, 0), (66, 1.8), (49, 1.8)]))
|
||||
cv.fill(mid, SP["bone"], SP["bone2"]); cv.edge(mid, SP["umber"], .6, .8)
|
||||
bar = cv.poly(t.P([(44, -11.5), (47.5, -11.5), (47.5, 11.5), (44, 11.5)]))
|
||||
metal(cv, bar, tier, True)
|
||||
rivet(cv, *t.T(45.7, 0), 1.5)
|
||||
pips(cv, tier, pip_count)
|
||||
return finish(cv, seed=ord(kind[0]) + tier)
|
||||
|
||||
|
||||
def sym(pts_left):
|
||||
return pts_left + [(64 - x, y) for x, y in reversed(pts_left)]
|
||||
|
||||
|
||||
def cloth(cv, mask, tier, dark=False):
|
||||
"""sun-bleached stillsuit fabric"""
|
||||
hi, lo = (SP["dune"], SP["dune2"]) if not dark else (SP["dune2"], SP["umber2"])
|
||||
soft_body(cv, mask, mix(mix(hi, "#fff4d8", .12), QUAL[tier], .2 if tier else 0), mix(lo, QUAL[tier], .2 if tier else 0), ew=.85, light=.3, dark=.22)
|
||||
|
||||
|
||||
def trim_band(cv, pts, tier, w=1.0):
|
||||
m = cv.line(pts, w)
|
||||
cv.solid(m, mix(QUAL[tier], SP["brass2"], .25))
|
||||
|
||||
|
||||
def tubes(cv, pts, w=.9):
|
||||
"""catchtube: dark hose with a water-blue glint"""
|
||||
cv.solid(cv.line(pts, w + .8), SP["umber"], .8)
|
||||
cv.solid(cv.line(pts, w * .5), SP["water2"], .9)
|
||||
|
||||
|
||||
def draw_armour(kind, tier, pip_count):
|
||||
cv = Cv(64)
|
||||
aura(cv, tier)
|
||||
q = QUAL[tier]
|
||||
if kind == "helmet":
|
||||
left = [(32, 5), (22, 7), (13, 15), (9, 27), (9, 44), (13, 52), (21, 52), (21, 42), (26, 40)]
|
||||
hood = cv.poly(left + [(64 - x, y) for x, y in reversed(left)])
|
||||
cloth(cv, hood, tier)
|
||||
mask = cv.poly([(15, 29), (49, 29), (47, 40), (41, 44), (23, 44), (17, 40)]) # face veil
|
||||
cv.fill(mask, SP["sand2"], SP["dune"]); cv.edge(mask, SP["umber"], .7, .8)
|
||||
visor = cv.poly([(16, 31), (48, 31), (46, 36), (18, 36)])
|
||||
cv.fill(visor, SP["night"], "#14121a"); cv.edge(visor, SP["umber"], .5, .8)
|
||||
cv.solid(cv.line([(19, 33.5), (45, 33.5)], 1.0), mix(SP["fremen2"], "#ffffff", .15), .95) # eye slit
|
||||
trim_band(cv, [(32, 8), (32, 27)], tier, 1.3)
|
||||
tubes(cv, [(21, 41), (18, 50)]); tubes(cv, [(43, 41), (46, 50)])
|
||||
n = cv.poly([(28, 6), (32, 2), (36, 6)]); metal(cv, n, tier)
|
||||
elif kind == "chestplate":
|
||||
left = [(32, 12), (26, 10), (20, 7), (9, 12), (4, 24), (10, 32), (15, 30), (15, 57), (32, 57)]
|
||||
body = cv.poly(left + [(64 - x, y) for x, y in reversed(left)])
|
||||
cloth(cv, body, tier)
|
||||
yoke = cv.poly([(20, 8), (32, 14), (44, 8), (44, 17), (32, 22), (20, 17)])
|
||||
cv.fill(yoke, SP["leather2"], SP["umber2"]); cv.edge(yoke, SP["umber"], .6, .8)
|
||||
tubes(cv, [(20, 20), (19, 36), (24, 50)]); tubes(cv, [(44, 20), (45, 36), (40, 50)])
|
||||
buckle = gear(cv, 32, 33, 7.2, 10, .13, .42)
|
||||
cv.fill(buckle, SP["brass2"], SP["brass3"]); cv.edge(buckle, SP["umber"], .5, .85)
|
||||
cv.solid(cv.circle(32, 33, 2.4), mix(q, "#fff4d8", .35))
|
||||
trim_band(cv, [(9, 14), (16, 21)], tier, 1.1); trim_band(cv, [(55, 14), (48, 21)], tier, 1.1)
|
||||
trim_band(cv, [(16, 54), (48, 54)], tier, 1.2)
|
||||
elif kind == "leggings":
|
||||
body = cv.poly([(13, 6), (51, 6), (53, 56), (37, 56), (32, 22), (27, 56), (11, 56)])
|
||||
cloth(cv, body, tier)
|
||||
belt = cv.rrect(13, 6, 51, 14, 2)
|
||||
cv.fill(belt, SP["leather2"], SP["umber2"]); cv.edge(belt, SP["umber"], .6, .85)
|
||||
bk = gear(cv, 32, 10, 3.4, 8, .15, .3)
|
||||
cv.fill(bk, SP["brass2"], SP["brass3"]); cv.edge(bk, SP["umber"], .4, .85)
|
||||
tubes(cv, [(20, 16), (19, 50)]); tubes(cv, [(44, 16), (45, 50)])
|
||||
trim_band(cv, [(12, 52), (28, 52)], tier, 1.1); trim_band(cv, [(36, 52), (52, 52)], tier, 1.1)
|
||||
elif kind == "boots":
|
||||
for ox, mirror in ((0, 1), (32, -1)):
|
||||
def X(x):
|
||||
return ox + (x if mirror == 1 else 32 - x)
|
||||
b = cv.poly([(X(7), 10), (X(24), 10), (X(24), 38), (X(31), 44), (X(31), 54), (X(4), 54), (X(6), 38)])
|
||||
soft_body(cv, b, SP["leather2"], SP["umber2"], ew=.85)
|
||||
cuff = cv.rrect(min(X(7), X(24)), 10, max(X(7), X(24)), 15, 1.5)
|
||||
cv.fill(cuff, SP["dune"], SP["dune2"]); cv.edge(cuff, SP["umber"], .5, .8)
|
||||
trim_band(cv, [(X(8), 47), (X(28), 47)], tier, 1.1)
|
||||
for yy in (22, 30):
|
||||
cv.solid(cv.line([(X(9), yy), (X(22), yy)], .7), SP["brass2"], .9)
|
||||
elif kind == "elytra":
|
||||
left = [(31, 8), (19, 9), (7, 16), (3, 32), (8, 48), (20, 57), (30, 50), (31, 30)]
|
||||
for side in (0, 1):
|
||||
pts = left if side == 0 else [(64 - x, y) for x, y in left]
|
||||
w = cv.poly(pts)
|
||||
cv.fill(w, mix(SP["sand2"], "#ffffff", .1), SP["dune2"])
|
||||
cv.bevel(w, .35, .25, 1)
|
||||
cv.edge(w, SP["umber"], .85, .85)
|
||||
for k in range(1, 5): # brass ribs like an ornithopter wing
|
||||
f = k / 5
|
||||
a = (31, 14 + f * 6)
|
||||
b2 = (6 + f * 2, 18 + f * 32)
|
||||
if side:
|
||||
a, b2 = (64 - a[0], a[1]), (64 - b2[0], b2[1])
|
||||
cv.solid(cv.line([a, b2], .8), SP["brass3"], .9)
|
||||
trim_band(cv, [pts[1], pts[2], pts[3]], tier, .9)
|
||||
hub = gear(cv, 32, 28, 4.2, 8, .16, .4)
|
||||
cv.fill(hub, SP["brass2"], SP["brass3"]); cv.edge(hub, SP["umber"], .45, .85)
|
||||
pips(cv, tier, pip_count)
|
||||
return finish(cv, seed=ord(kind[0]) + tier * 3)
|
||||
|
||||
|
||||
def draw(kind, tier, pip_count):
|
||||
return draw_tool(kind, tier, pip_count) if kind in HANDHELD else draw_armour(kind, tier, pip_count)
|
||||
|
|
|
|||
|
|
@ -1,269 +1,269 @@
|
|||
"""Soft Dune currency, devices, sigils, crests and keepsakes. Same public names as the old items_misc module."""
|
||||
import math
|
||||
from PIL import Image, ImageChops
|
||||
from dunelib import Cv, SS, mix, rgb, hexagon
|
||||
from dunesoft import *
|
||||
|
||||
# ---------------------------------------------------------------- coins
|
||||
COINS = {
|
||||
# name: (label, sub, rim_hi, rim_lo, field)
|
||||
"coin_001": ("1", "CENT", "#d8a273", "#8a5334", "#b9794f"),
|
||||
"coin_002": ("2", "CENT", "#dcaa7c", "#8d5736", "#bd7d54"),
|
||||
"coin_005": ("5", "CENT", "#e0b387", "#935c3a", "#c4865c"),
|
||||
"coin_010": ("10", "CENT", "#d8d6c6", "#7c7b70", "#a9a89b"),
|
||||
"coin_020": ("20", "CENT", "#dfdccd", "#827f73", "#b0aea0"),
|
||||
"coin_050": ("50", "CENT", "#e6e3d4", "#898678", "#b8b5a6"),
|
||||
"coin_1dm": ("1", "DM", "#f0d795", "#9a7633", "#cfa955"),
|
||||
"coin_1dm_gold": ("1", "DM", "#f6e2a3", "#a67f2f", "#dcb45a"),
|
||||
"coin_1dm_silver": ("1", "DM", "#eceae0", "#8a897f", "#bdbbae"),
|
||||
"coin_2dm": ("2", "DM", "#f3dc9b", "#9e7a31", "#d4ad57"),
|
||||
}
|
||||
|
||||
|
||||
def coin(name):
|
||||
label, sub, hi, lo, field = COINS[name]
|
||||
cv = Cv(128)
|
||||
c = 64
|
||||
outer = gear(cv, c, c, 52, 28, 0.045, 0)
|
||||
cv.fill(outer, hi, lo)
|
||||
cv.bevel(outer, .5, .32, 1.8)
|
||||
cv.edge(outer, SP["umber"], 1.0, .75)
|
||||
ring = cv.circle(c, c, 45)
|
||||
cv.fill(ring, lo, hi)
|
||||
face = cv.circle(c, c, 41)
|
||||
cv.fill(face, mix(field, "#ffffff", .18), mix(field, SP["umber"], .22))
|
||||
cv.bevel(face, .25, .3, 1.4)
|
||||
# fine milled grooves, hand-struck rather than circuit-drawn
|
||||
for r in (36, 33.5):
|
||||
cv.edge(cv.circle(c, c, r), lo, .55, .45)
|
||||
worm_arc(cv, c, c, 36, mix(hi, "#ffffff", .25), 1.8, .55)
|
||||
big = 44 if len(label) == 1 else 34
|
||||
t = cv.text((c, c - 3), label, big)
|
||||
engrave(cv, t, mix(lo, SP["umber"], .55))
|
||||
s = cv.text((c, c + 26), sub, 10)
|
||||
engrave(cv, s, mix(lo, SP["umber"], .45), .5)
|
||||
cv.solid(cv.circle(38, 33, 9), "#ffffff", .10)
|
||||
return finish(cv, seed=hash(name) % 997)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- notes
|
||||
NOTES = {
|
||||
"note_5": ("5", "#7f9a6a", "#e7e2c3"),
|
||||
"note_10": ("10", "#6fa0a4", "#e3e4c9"),
|
||||
"note_20": ("20", "#6d92bd", "#e3e1cb"),
|
||||
"note_50": ("50", "#7e83b4", "#e5e0cd"),
|
||||
"note_100": ("100", "#9b7bb0", "#e8dfcc"),
|
||||
"note_200": ("200", "#b7799f", "#ebdecd"),
|
||||
"note_500": ("500", "#c9774f", "#efdfc4"),
|
||||
"note_1000": ("1000", "#cf9a3c", "#f1e2bb"),
|
||||
"note_5000": ("5000", "#a8452c", "#f2dfbd"),
|
||||
"note_0_house": ("", "#a68345", "#e9dfc3"),
|
||||
"note_0_leto": ("", "#c9803a", "#efdcb6"),
|
||||
}
|
||||
|
||||
|
||||
def note(name):
|
||||
label, tint, paper = NOTES[name]
|
||||
cv = Cv(128)
|
||||
body = cv.rrect(4, 26, 124, 102, 7)
|
||||
cv.fill(body, mix(paper, "#ffffff", .25), mix(paper, SP["dune"], .35))
|
||||
cv.bevel(body, .3, .22, 1.2)
|
||||
cv.edge(body, SP["umber"], 1.0, .75)
|
||||
# engraved border band, guilloche-like overlapping rings
|
||||
band = cv.rrect(8, 30, 120, 98, 5)
|
||||
cv.edge(band, tint, 1.7, .85)
|
||||
cv.edge(cv.rrect(11.5, 33.5, 116.5, 94.5, 3.5), tint, .55, .6)
|
||||
ex, ey = 93, 64
|
||||
for k in range(7):
|
||||
a = math.radians(k * 25.7)
|
||||
cv.edge(cv.circle(ex + 6 * math.cos(a), ey + 6 * math.sin(a), 18), tint, .45, .32)
|
||||
seal = cv.circle(ex, ey, 21)
|
||||
cv.fill(seal, mix(paper, tint, .22), mix(paper, tint, .45))
|
||||
cv.edge(seal, tint, 1.1, .9)
|
||||
cv.edge(cv.circle(ex, ey, 17), SP["brass3"], .6, .8)
|
||||
if name == "note_0_house":
|
||||
pts = [(ex - 10, ey + 5), (ex - 11, ey - 7), (ex - 5, ey - 1), (ex, ey - 9), (ex + 5, ey - 1), (ex + 11, ey - 7), (ex + 10, ey + 5)]
|
||||
cv.solid(cv.line(pts + [pts[0]], 1.5), SP["brass3"])
|
||||
cv.solid(cv.line([(ex - 10, ey + 9), (ex + 10, ey + 9)], 1.5), SP["brass3"])
|
||||
elif name == "note_0_leto":
|
||||
for r in (13, 9, 5):
|
||||
worm_arc(cv, ex, ey, r, SP["terracotta"], 1.7)
|
||||
cv.solid(cv.circle(ex, ey, 2), SP["umber2"])
|
||||
else:
|
||||
worm_arc(cv, ex, ey, 11, mix(tint, SP["umber"], .25), 2.3)
|
||||
cv.solid(cv.circle(ex, ey, 2.6), SP["umber2"])
|
||||
num = label or "0"
|
||||
size = {1: 40, 2: 34, 3: 28, 4: 21}[len(num)]
|
||||
engrave(cv, cv.text((34, 56), num, size), mix(tint, SP["umber"], .45))
|
||||
engrave(cv, cv.text((34, 82), "DUNEMARK", 8.2), mix(tint, SP["umber"], .4), .4)
|
||||
cv.solid(cv.line([(14, 90), (60, 90)], .8), tint, .7)
|
||||
cv.solid(cv.line([(14, 38), (44, 38)], .8), tint, .7)
|
||||
return finish(cv, seed=hash(name) % 997)
|
||||
|
||||
|
||||
def legacy_note(value):
|
||||
m = {"1": "note_5", "5": "note_5", "100": "note_100", "1000": "note_1000", "5000": "note_5000", "note": "note_100"}
|
||||
return note(m[value])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- spy module
|
||||
def spy_module():
|
||||
"""brass-and-glass seeker egg: a thinking-machine-free hunter-seeker shell"""
|
||||
cv = Cv(128)
|
||||
pts = []
|
||||
for i in range(72):
|
||||
t = i / 72 * 2 * math.pi
|
||||
x = 64 + 36 * math.sin(t)
|
||||
y = 66 - 46 * math.cos(t) * (1.0 if math.cos(t) > 0 else .86)
|
||||
if math.cos(t) > 0:
|
||||
x = 64 + 36 * math.sin(t) * (1 - .18 * math.cos(t))
|
||||
pts.append((x, y))
|
||||
body = cv.poly(pts)
|
||||
cv.fill(body, SP["brass2"], SP["brass3"])
|
||||
cv.bevel(body, .5, .35, 2.2)
|
||||
cv.edge(body, SP["umber"], 1.2, .8)
|
||||
# riveted plate seams
|
||||
for yy in (44, 88):
|
||||
cv.solid(cv.clip(cv.line([(20, yy), (108, yy)], 1.0), body), SP["umber"], .45)
|
||||
for x, y in ((38, 44), (90, 44), (36, 88), (92, 88), (64, 26)):
|
||||
rivet(cv, x, y, 1.9)
|
||||
ring = gear(cv, 64, 66, 25, 12, .12, 0)
|
||||
cv.fill(ring, SP["bronze"], SP["umber2"])
|
||||
cv.edge(ring, SP["umber"], .8, .8)
|
||||
lens_rim = cv.circle(64, 66, 17)
|
||||
cv.fill(lens_rim, SP["brass2"], SP["brass3"])
|
||||
lens = cv.circle(64, 66, 13.5)
|
||||
cv.fill(lens, SP["water"], SP["fremen"])
|
||||
cv.solid(cv.circle(64, 66, 8), SP["fremen"]) # blue-within-blue
|
||||
cv.solid(cv.circle(64, 66, 3.8), SP["night"])
|
||||
cv.solid(cv.circle(59, 61, 3), "#ffffff", .75)
|
||||
for sx in (-1, 1): # soft fins
|
||||
fin = cv.poly([(64 + sx * 35, 54), (64 + sx * 50, 44), (64 + sx * 44, 64)])
|
||||
soft_body(cv, fin, SP["brass2"], SP["bronze"], ew=.8)
|
||||
return finish(cv, seed=5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- planet sigils
|
||||
PLANET_TINT = {
|
||||
"nivareth": "#7fa6c6", "orivane": "#c9a05a", "pelareth": "#7fae9d", "serevan": "#a58bb4", "varkesh": "#c9765a",
|
||||
}
|
||||
|
||||
|
||||
def planet(name, src_img):
|
||||
tint = PLANET_TINT[name]
|
||||
cv = Cv(128)
|
||||
disc = cv.circle(64, 64, 58)
|
||||
cv.fill(disc, SP["brass2"], SP["brass3"])
|
||||
cv.bevel(disc, .5, .35, 2)
|
||||
cv.edge(disc, SP["umber"], 1.1, .8)
|
||||
inner = cv.circle(64, 64, 49)
|
||||
cv.fill(inner, mix(tint, "#ffffff", .38), mix(tint, SP["umber"], .38))
|
||||
cv.edge(inner, SP["umber2"], .8, .7)
|
||||
for i in range(36): # milled rim ticks
|
||||
a = math.radians(i * 10)
|
||||
cv.solid(cv.line([(64 + 52.5 * math.cos(a), 64 + 52.5 * math.sin(a)), (64 + 56 * math.cos(a), 64 + 56 * math.sin(a))], .7), SP["umber2"], .6)
|
||||
layer = cv.im
|
||||
s = src_img.convert("RGBA").resize((128 * SS, 128 * SS), Image.LANCZOS)
|
||||
a = s.getchannel("A").point(lambda v: min(255, int(v * 1.25)))
|
||||
# glyph rendered as dark engraved ink, clipped to the inner disc
|
||||
a = ImageChops.multiply(a, cv.circle(64, 64, 49))
|
||||
ink = Image.new("RGBA", s.size, rgb(SP["umber"]))
|
||||
ink.putalpha(a.point(lambda v: int(v * .88)))
|
||||
hi = Image.new("RGBA", s.size, rgb("#fff1cf"))
|
||||
hi.putalpha(ImageChops.offset(a, int(.8 * SS), int(.9 * SS)).point(lambda v: int(v * .45)))
|
||||
cv.im = Image.alpha_composite(Image.alpha_composite(layer, hi), ink)
|
||||
return finish(cv, seed=len(name))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- office crests
|
||||
def office(kind):
|
||||
cv = Cv(64)
|
||||
sh = cv.poly([(32, 4), (56, 13), (56, 34), (32, 60), (8, 34), (8, 13)])
|
||||
tint = {"crown": SP["brass"], "spice": SP["amber"], "water": SP["fremen2"]}[kind]
|
||||
field = {"crown": "#6a4a38", "spice": "#8d5a37", "water": "#415f80"}[kind]
|
||||
cv.fill(sh, SP["brass2"], SP["brass3"])
|
||||
cv.bevel(sh, .4, .3, 1)
|
||||
cv.edge(sh, SP["umber"], 1, .8)
|
||||
inner = cv.poly([(32, 9), (51, 16), (51, 33), (32, 53), (13, 33), (13, 16)])
|
||||
cv.fill(inner, mix(field, "#ffffff", .15), mix(field, SP["ink"], .3))
|
||||
cv.edge(inner, SP["umber"], .6, .6)
|
||||
if kind == "crown":
|
||||
pts = [(18, 38), (17, 20), (25, 28), (32, 16), (39, 28), (47, 20), (46, 38)]
|
||||
cv.solid(cv.line(pts + [pts[0]], 2.2), SP["brass2"])
|
||||
for x, y in ((17, 20), (32, 16), (47, 20)):
|
||||
cv.solid(cv.circle(x, y, 1.9), "#fff1c8")
|
||||
elif kind == "spice":
|
||||
d = cv.poly([(32, 14), (44, 30), (32, 48), (20, 30)])
|
||||
warm_glow(cv, d, SP["amber"], 2.5, .5)
|
||||
cv.fill(d, SP["amber2"], SP["terracotta"])
|
||||
cv.edge(d, "#ffe9b8", .6, .7)
|
||||
cv.solid(cv.line([(32, 14), (32, 48)], .7), "#fff1c8", .5)
|
||||
else:
|
||||
drop = cv.circle(32, 36, 11)
|
||||
tri = cv.poly([(32, 12), (42, 31), (22, 31)])
|
||||
full = ImageChops.lighter(drop, tri)
|
||||
cv.fill(full, SP["water"], SP["fremen"])
|
||||
cv.edge(full, "#e6f4f6", .6, .6)
|
||||
cv.solid(cv.circle(28, 34, 2.4), "#ffffff", .75)
|
||||
return finish(cv, seed=3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- spice, water, codex
|
||||
def spice_crystal(tint_a, tint_b, glow, smuggled=False, dense=False):
|
||||
cv = Cv(64)
|
||||
base = cv.circle(32, 42, 17)
|
||||
warm_glow(cv, base, glow, 7, .30 if not dense else .5)
|
||||
shards = [([(32, 8), (42, 30), (32, 52), (22, 30)], 1.0), ([(16, 22), (24, 40), (14, 54), (8, 38)], .75),
|
||||
([(48, 20), (56, 38), (48, 54), (40, 38)], .8)]
|
||||
if dense:
|
||||
shards.append(([(32, 24), (38, 40), (32, 58), (26, 40)], .9))
|
||||
for pts, k in shards:
|
||||
m = cv.poly(pts)
|
||||
cv.fill(m, mix(tint_a, "#fff4d8", .10 * k), tint_b)
|
||||
cv.bevel(m, .5, .3, 1)
|
||||
cv.edge(m, SP["umber"], .7, .65)
|
||||
# one soft inner facet
|
||||
cx = sum(p[0] for p in pts) / 4
|
||||
cv.solid(cv.clip(m, cv.poly([(cx, pts[0][1]), (pts[1][0], pts[1][1]), (cx, pts[2][1])])), "#fff1c6", .22)
|
||||
if smuggled: # twine-bound in a scrap of dark cloth
|
||||
band = cv.rrect(8, 47, 56, 52, 2)
|
||||
cv.fill(band, SP["umber2"], SP["umber"])
|
||||
cv.solid(cv.line([(8, 49.5), (56, 49.5)], .6), SP["fremen2"], .8)
|
||||
dust(cv, [(38, 15), (46, 24), (19, 30)], "#fff3d2", .9, .85)
|
||||
return finish(cv, seed=9)
|
||||
|
||||
|
||||
def water_vial(tint="#5f93b8", smuggled=False):
|
||||
cv = Cv(64)
|
||||
glass = cv.rrect(22, 14, 42, 56, 8)
|
||||
cv.fill(glass, "#eef7f6", SP["water"], .62)
|
||||
liquid = cv.rrect(24, 28, 40, 54, 7)
|
||||
cv.fill(liquid, SP["water"], mix(tint, SP["fremen"], .35))
|
||||
cv.edge(glass, "#d9ecee", 1.0, .9)
|
||||
cv.edge(glass, SP["umber2"], .5, .55)
|
||||
cap = cv.rrect(24, 7, 40, 17, 2.5)
|
||||
cv.fill(cap, SP["brass2"], SP["brass3"])
|
||||
cv.edge(cap, SP["umber"], .6, .8)
|
||||
cv.solid(cv.line([(26.5, 24), (26.5, 46)], 1.5), "#ffffff", .6)
|
||||
if smuggled:
|
||||
cv.solid(cv.rrect(21, 36, 43, 41, 1), SP["leather2"])
|
||||
cv.solid(cv.line([(21, 38.5), (43, 38.5)], .5), SP["umber"], .7)
|
||||
return finish(cv, seed=2)
|
||||
|
||||
|
||||
def imperial_codex():
|
||||
cv = Cv(64)
|
||||
book = cv.rrect(12, 6, 52, 58, 4)
|
||||
cv.fill(book, "#7c5438", "#4b3223")
|
||||
cv.bevel(book, .3, .25, 1)
|
||||
cv.edge(book, SP["umber"], 1, .85)
|
||||
cv.solid(cv.rrect(12, 6, 18, 58, 2), "#3c281c")
|
||||
for y in (14, 28, 42):
|
||||
cv.solid(cv.line([(12, y), (18, y)], .9), SP["brass"], .9)
|
||||
for cx, cy in ((46, 12), (46, 52)): # brass corner caps
|
||||
cv.fill(cv.rrect(cx - 4, cy - 4, cx + 6, cy + 6, 1.5), SP["brass2"], SP["brass3"])
|
||||
medal = gear(cv, 35, 32, 10, 10, .14, .3)
|
||||
cv.fill(medal, SP["brass2"], SP["brass3"])
|
||||
cv.edge(medal, SP["umber"], .5, .8)
|
||||
cv.solid(cv.circle(35, 32, 2.6), SP["umber"], .8)
|
||||
return finish(cv, seed=4)
|
||||
"""Soft Dune currency, devices, sigils, crests and keepsakes. Same public names as the old items_misc module."""
|
||||
import math
|
||||
from PIL import Image, ImageChops
|
||||
from dunelib import Cv, SS, mix, rgb, hexagon
|
||||
from dunesoft import *
|
||||
|
||||
# ---------------------------------------------------------------- coins
|
||||
COINS = {
|
||||
# name: (label, sub, rim_hi, rim_lo, field)
|
||||
"coin_001": ("1", "CENT", "#d8a273", "#8a5334", "#b9794f"),
|
||||
"coin_002": ("2", "CENT", "#dcaa7c", "#8d5736", "#bd7d54"),
|
||||
"coin_005": ("5", "CENT", "#e0b387", "#935c3a", "#c4865c"),
|
||||
"coin_010": ("10", "CENT", "#d8d6c6", "#7c7b70", "#a9a89b"),
|
||||
"coin_020": ("20", "CENT", "#dfdccd", "#827f73", "#b0aea0"),
|
||||
"coin_050": ("50", "CENT", "#e6e3d4", "#898678", "#b8b5a6"),
|
||||
"coin_1dm": ("1", "DM", "#f0d795", "#9a7633", "#cfa955"),
|
||||
"coin_1dm_gold": ("1", "DM", "#f6e2a3", "#a67f2f", "#dcb45a"),
|
||||
"coin_1dm_silver": ("1", "DM", "#eceae0", "#8a897f", "#bdbbae"),
|
||||
"coin_2dm": ("2", "DM", "#f3dc9b", "#9e7a31", "#d4ad57"),
|
||||
}
|
||||
|
||||
|
||||
def coin(name):
|
||||
label, sub, hi, lo, field = COINS[name]
|
||||
cv = Cv(128)
|
||||
c = 64
|
||||
outer = gear(cv, c, c, 52, 28, 0.045, 0)
|
||||
cv.fill(outer, hi, lo)
|
||||
cv.bevel(outer, .5, .32, 1.8)
|
||||
cv.edge(outer, SP["umber"], 1.0, .75)
|
||||
ring = cv.circle(c, c, 45)
|
||||
cv.fill(ring, lo, hi)
|
||||
face = cv.circle(c, c, 41)
|
||||
cv.fill(face, mix(field, "#ffffff", .18), mix(field, SP["umber"], .22))
|
||||
cv.bevel(face, .25, .3, 1.4)
|
||||
# fine milled grooves, hand-struck rather than circuit-drawn
|
||||
for r in (36, 33.5):
|
||||
cv.edge(cv.circle(c, c, r), lo, .55, .45)
|
||||
worm_arc(cv, c, c, 36, mix(hi, "#ffffff", .25), 1.8, .55)
|
||||
big = 44 if len(label) == 1 else 34
|
||||
t = cv.text((c, c - 3), label, big)
|
||||
engrave(cv, t, mix(lo, SP["umber"], .55))
|
||||
s = cv.text((c, c + 26), sub, 10)
|
||||
engrave(cv, s, mix(lo, SP["umber"], .45), .5)
|
||||
cv.solid(cv.circle(38, 33, 9), "#ffffff", .10)
|
||||
return finish(cv, seed=hash(name) % 997)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- notes
|
||||
NOTES = {
|
||||
"note_5": ("5", "#7f9a6a", "#e7e2c3"),
|
||||
"note_10": ("10", "#6fa0a4", "#e3e4c9"),
|
||||
"note_20": ("20", "#6d92bd", "#e3e1cb"),
|
||||
"note_50": ("50", "#7e83b4", "#e5e0cd"),
|
||||
"note_100": ("100", "#9b7bb0", "#e8dfcc"),
|
||||
"note_200": ("200", "#b7799f", "#ebdecd"),
|
||||
"note_500": ("500", "#c9774f", "#efdfc4"),
|
||||
"note_1000": ("1000", "#cf9a3c", "#f1e2bb"),
|
||||
"note_5000": ("5000", "#a8452c", "#f2dfbd"),
|
||||
"note_0_house": ("", "#a68345", "#e9dfc3"),
|
||||
"note_0_leto": ("", "#c9803a", "#efdcb6"),
|
||||
}
|
||||
|
||||
|
||||
def note(name):
|
||||
label, tint, paper = NOTES[name]
|
||||
cv = Cv(128)
|
||||
body = cv.rrect(4, 26, 124, 102, 7)
|
||||
cv.fill(body, mix(paper, "#ffffff", .25), mix(paper, SP["dune"], .35))
|
||||
cv.bevel(body, .3, .22, 1.2)
|
||||
cv.edge(body, SP["umber"], 1.0, .75)
|
||||
# engraved border band, guilloche-like overlapping rings
|
||||
band = cv.rrect(8, 30, 120, 98, 5)
|
||||
cv.edge(band, tint, 1.7, .85)
|
||||
cv.edge(cv.rrect(11.5, 33.5, 116.5, 94.5, 3.5), tint, .55, .6)
|
||||
ex, ey = 93, 64
|
||||
for k in range(7):
|
||||
a = math.radians(k * 25.7)
|
||||
cv.edge(cv.circle(ex + 6 * math.cos(a), ey + 6 * math.sin(a), 18), tint, .45, .32)
|
||||
seal = cv.circle(ex, ey, 21)
|
||||
cv.fill(seal, mix(paper, tint, .22), mix(paper, tint, .45))
|
||||
cv.edge(seal, tint, 1.1, .9)
|
||||
cv.edge(cv.circle(ex, ey, 17), SP["brass3"], .6, .8)
|
||||
if name == "note_0_house":
|
||||
pts = [(ex - 10, ey + 5), (ex - 11, ey - 7), (ex - 5, ey - 1), (ex, ey - 9), (ex + 5, ey - 1), (ex + 11, ey - 7), (ex + 10, ey + 5)]
|
||||
cv.solid(cv.line(pts + [pts[0]], 1.5), SP["brass3"])
|
||||
cv.solid(cv.line([(ex - 10, ey + 9), (ex + 10, ey + 9)], 1.5), SP["brass3"])
|
||||
elif name == "note_0_leto":
|
||||
for r in (13, 9, 5):
|
||||
worm_arc(cv, ex, ey, r, SP["terracotta"], 1.7)
|
||||
cv.solid(cv.circle(ex, ey, 2), SP["umber2"])
|
||||
else:
|
||||
worm_arc(cv, ex, ey, 11, mix(tint, SP["umber"], .25), 2.3)
|
||||
cv.solid(cv.circle(ex, ey, 2.6), SP["umber2"])
|
||||
num = label or "0"
|
||||
size = {1: 40, 2: 34, 3: 28, 4: 21}[len(num)]
|
||||
engrave(cv, cv.text((34, 56), num, size), mix(tint, SP["umber"], .45))
|
||||
engrave(cv, cv.text((34, 82), "DUNEMARK", 8.2), mix(tint, SP["umber"], .4), .4)
|
||||
cv.solid(cv.line([(14, 90), (60, 90)], .8), tint, .7)
|
||||
cv.solid(cv.line([(14, 38), (44, 38)], .8), tint, .7)
|
||||
return finish(cv, seed=hash(name) % 997)
|
||||
|
||||
|
||||
def legacy_note(value):
|
||||
m = {"1": "note_5", "5": "note_5", "100": "note_100", "1000": "note_1000", "5000": "note_5000", "note": "note_100"}
|
||||
return note(m[value])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- spy module
|
||||
def spy_module():
|
||||
"""brass-and-glass seeker egg: a thinking-machine-free hunter-seeker shell"""
|
||||
cv = Cv(128)
|
||||
pts = []
|
||||
for i in range(72):
|
||||
t = i / 72 * 2 * math.pi
|
||||
x = 64 + 36 * math.sin(t)
|
||||
y = 66 - 46 * math.cos(t) * (1.0 if math.cos(t) > 0 else .86)
|
||||
if math.cos(t) > 0:
|
||||
x = 64 + 36 * math.sin(t) * (1 - .18 * math.cos(t))
|
||||
pts.append((x, y))
|
||||
body = cv.poly(pts)
|
||||
cv.fill(body, SP["brass2"], SP["brass3"])
|
||||
cv.bevel(body, .5, .35, 2.2)
|
||||
cv.edge(body, SP["umber"], 1.2, .8)
|
||||
# riveted plate seams
|
||||
for yy in (44, 88):
|
||||
cv.solid(cv.clip(cv.line([(20, yy), (108, yy)], 1.0), body), SP["umber"], .45)
|
||||
for x, y in ((38, 44), (90, 44), (36, 88), (92, 88), (64, 26)):
|
||||
rivet(cv, x, y, 1.9)
|
||||
ring = gear(cv, 64, 66, 25, 12, .12, 0)
|
||||
cv.fill(ring, SP["bronze"], SP["umber2"])
|
||||
cv.edge(ring, SP["umber"], .8, .8)
|
||||
lens_rim = cv.circle(64, 66, 17)
|
||||
cv.fill(lens_rim, SP["brass2"], SP["brass3"])
|
||||
lens = cv.circle(64, 66, 13.5)
|
||||
cv.fill(lens, SP["water"], SP["fremen"])
|
||||
cv.solid(cv.circle(64, 66, 8), SP["fremen"]) # blue-within-blue
|
||||
cv.solid(cv.circle(64, 66, 3.8), SP["night"])
|
||||
cv.solid(cv.circle(59, 61, 3), "#ffffff", .75)
|
||||
for sx in (-1, 1): # soft fins
|
||||
fin = cv.poly([(64 + sx * 35, 54), (64 + sx * 50, 44), (64 + sx * 44, 64)])
|
||||
soft_body(cv, fin, SP["brass2"], SP["bronze"], ew=.8)
|
||||
return finish(cv, seed=5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- planet sigils
|
||||
PLANET_TINT = {
|
||||
"nivareth": "#7fa6c6", "orivane": "#c9a05a", "pelareth": "#7fae9d", "serevan": "#a58bb4", "varkesh": "#c9765a",
|
||||
}
|
||||
|
||||
|
||||
def planet(name, src_img):
|
||||
tint = PLANET_TINT[name]
|
||||
cv = Cv(128)
|
||||
disc = cv.circle(64, 64, 58)
|
||||
cv.fill(disc, SP["brass2"], SP["brass3"])
|
||||
cv.bevel(disc, .5, .35, 2)
|
||||
cv.edge(disc, SP["umber"], 1.1, .8)
|
||||
inner = cv.circle(64, 64, 49)
|
||||
cv.fill(inner, mix(tint, "#ffffff", .38), mix(tint, SP["umber"], .38))
|
||||
cv.edge(inner, SP["umber2"], .8, .7)
|
||||
for i in range(36): # milled rim ticks
|
||||
a = math.radians(i * 10)
|
||||
cv.solid(cv.line([(64 + 52.5 * math.cos(a), 64 + 52.5 * math.sin(a)), (64 + 56 * math.cos(a), 64 + 56 * math.sin(a))], .7), SP["umber2"], .6)
|
||||
layer = cv.im
|
||||
s = src_img.convert("RGBA").resize((128 * SS, 128 * SS), Image.LANCZOS)
|
||||
a = s.getchannel("A").point(lambda v: min(255, int(v * 1.25)))
|
||||
# glyph rendered as dark engraved ink, clipped to the inner disc
|
||||
a = ImageChops.multiply(a, cv.circle(64, 64, 49))
|
||||
ink = Image.new("RGBA", s.size, rgb(SP["umber"]))
|
||||
ink.putalpha(a.point(lambda v: int(v * .88)))
|
||||
hi = Image.new("RGBA", s.size, rgb("#fff1cf"))
|
||||
hi.putalpha(ImageChops.offset(a, int(.8 * SS), int(.9 * SS)).point(lambda v: int(v * .45)))
|
||||
cv.im = Image.alpha_composite(Image.alpha_composite(layer, hi), ink)
|
||||
return finish(cv, seed=len(name))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- office crests
|
||||
def office(kind):
|
||||
cv = Cv(64)
|
||||
sh = cv.poly([(32, 4), (56, 13), (56, 34), (32, 60), (8, 34), (8, 13)])
|
||||
tint = {"crown": SP["brass"], "spice": SP["amber"], "water": SP["fremen2"]}[kind]
|
||||
field = {"crown": "#6a4a38", "spice": "#8d5a37", "water": "#415f80"}[kind]
|
||||
cv.fill(sh, SP["brass2"], SP["brass3"])
|
||||
cv.bevel(sh, .4, .3, 1)
|
||||
cv.edge(sh, SP["umber"], 1, .8)
|
||||
inner = cv.poly([(32, 9), (51, 16), (51, 33), (32, 53), (13, 33), (13, 16)])
|
||||
cv.fill(inner, mix(field, "#ffffff", .15), mix(field, SP["ink"], .3))
|
||||
cv.edge(inner, SP["umber"], .6, .6)
|
||||
if kind == "crown":
|
||||
pts = [(18, 38), (17, 20), (25, 28), (32, 16), (39, 28), (47, 20), (46, 38)]
|
||||
cv.solid(cv.line(pts + [pts[0]], 2.2), SP["brass2"])
|
||||
for x, y in ((17, 20), (32, 16), (47, 20)):
|
||||
cv.solid(cv.circle(x, y, 1.9), "#fff1c8")
|
||||
elif kind == "spice":
|
||||
d = cv.poly([(32, 14), (44, 30), (32, 48), (20, 30)])
|
||||
warm_glow(cv, d, SP["amber"], 2.5, .5)
|
||||
cv.fill(d, SP["amber2"], SP["terracotta"])
|
||||
cv.edge(d, "#ffe9b8", .6, .7)
|
||||
cv.solid(cv.line([(32, 14), (32, 48)], .7), "#fff1c8", .5)
|
||||
else:
|
||||
drop = cv.circle(32, 36, 11)
|
||||
tri = cv.poly([(32, 12), (42, 31), (22, 31)])
|
||||
full = ImageChops.lighter(drop, tri)
|
||||
cv.fill(full, SP["water"], SP["fremen"])
|
||||
cv.edge(full, "#e6f4f6", .6, .6)
|
||||
cv.solid(cv.circle(28, 34, 2.4), "#ffffff", .75)
|
||||
return finish(cv, seed=3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- spice, water, codex
|
||||
def spice_crystal(tint_a, tint_b, glow, smuggled=False, dense=False):
|
||||
cv = Cv(64)
|
||||
base = cv.circle(32, 42, 17)
|
||||
warm_glow(cv, base, glow, 7, .30 if not dense else .5)
|
||||
shards = [([(32, 8), (42, 30), (32, 52), (22, 30)], 1.0), ([(16, 22), (24, 40), (14, 54), (8, 38)], .75),
|
||||
([(48, 20), (56, 38), (48, 54), (40, 38)], .8)]
|
||||
if dense:
|
||||
shards.append(([(32, 24), (38, 40), (32, 58), (26, 40)], .9))
|
||||
for pts, k in shards:
|
||||
m = cv.poly(pts)
|
||||
cv.fill(m, mix(tint_a, "#fff4d8", .10 * k), tint_b)
|
||||
cv.bevel(m, .5, .3, 1)
|
||||
cv.edge(m, SP["umber"], .7, .65)
|
||||
# one soft inner facet
|
||||
cx = sum(p[0] for p in pts) / 4
|
||||
cv.solid(cv.clip(m, cv.poly([(cx, pts[0][1]), (pts[1][0], pts[1][1]), (cx, pts[2][1])])), "#fff1c6", .22)
|
||||
if smuggled: # twine-bound in a scrap of dark cloth
|
||||
band = cv.rrect(8, 47, 56, 52, 2)
|
||||
cv.fill(band, SP["umber2"], SP["umber"])
|
||||
cv.solid(cv.line([(8, 49.5), (56, 49.5)], .6), SP["fremen2"], .8)
|
||||
dust(cv, [(38, 15), (46, 24), (19, 30)], "#fff3d2", .9, .85)
|
||||
return finish(cv, seed=9)
|
||||
|
||||
|
||||
def water_vial(tint="#5f93b8", smuggled=False):
|
||||
cv = Cv(64)
|
||||
glass = cv.rrect(22, 14, 42, 56, 8)
|
||||
cv.fill(glass, "#eef7f6", SP["water"], .62)
|
||||
liquid = cv.rrect(24, 28, 40, 54, 7)
|
||||
cv.fill(liquid, SP["water"], mix(tint, SP["fremen"], .35))
|
||||
cv.edge(glass, "#d9ecee", 1.0, .9)
|
||||
cv.edge(glass, SP["umber2"], .5, .55)
|
||||
cap = cv.rrect(24, 7, 40, 17, 2.5)
|
||||
cv.fill(cap, SP["brass2"], SP["brass3"])
|
||||
cv.edge(cap, SP["umber"], .6, .8)
|
||||
cv.solid(cv.line([(26.5, 24), (26.5, 46)], 1.5), "#ffffff", .6)
|
||||
if smuggled:
|
||||
cv.solid(cv.rrect(21, 36, 43, 41, 1), SP["leather2"])
|
||||
cv.solid(cv.line([(21, 38.5), (43, 38.5)], .5), SP["umber"], .7)
|
||||
return finish(cv, seed=2)
|
||||
|
||||
|
||||
def imperial_codex():
|
||||
cv = Cv(64)
|
||||
book = cv.rrect(12, 6, 52, 58, 4)
|
||||
cv.fill(book, "#7c5438", "#4b3223")
|
||||
cv.bevel(book, .3, .25, 1)
|
||||
cv.edge(book, SP["umber"], 1, .85)
|
||||
cv.solid(cv.rrect(12, 6, 18, 58, 2), "#3c281c")
|
||||
for y in (14, 28, 42):
|
||||
cv.solid(cv.line([(12, y), (18, y)], .9), SP["brass"], .9)
|
||||
for cx, cy in ((46, 12), (46, 52)): # brass corner caps
|
||||
cv.fill(cv.rrect(cx - 4, cy - 4, cx + 6, cy + 6, 1.5), SP["brass2"], SP["brass3"])
|
||||
medal = gear(cv, 35, 32, 10, 10, .14, .3)
|
||||
cv.fill(medal, SP["brass2"], SP["brass3"])
|
||||
cv.edge(medal, SP["umber"], .5, .8)
|
||||
cv.solid(cv.circle(35, 32, 2.6), SP["umber"], .8)
|
||||
return finish(cv, seed=4)
|
||||
|
|
|
|||
|
|
@ -1,39 +1,39 @@
|
|||
"""Ingots and raw ore in the soft Dune style: pressed brass-age bars and rough nuggets with a small stamp."""
|
||||
from dunelib import Cv, mix
|
||||
from dunesoft import *
|
||||
|
||||
NAMES = {'iron_ingot', 'gold_ingot', 'copper_ingot', 'netherite_ingot', 'raw_iron', 'raw_gold', 'raw_copper'}
|
||||
MATERIALS = { # hi, lo, stamp
|
||||
'iron': ('#d9d6c4', '#7d7c70', '#41699f'),
|
||||
'gold': ('#f0d58c', '#a47f38', '#8c4f2d'),
|
||||
'copper': ('#e2a37c', '#8d5636', '#5c8c76'),
|
||||
'netherite': ('#8b8087', '#3a3238', '#c9803a'),
|
||||
}
|
||||
|
||||
|
||||
def draw(name):
|
||||
material = name.removeprefix('raw_').removesuffix('_ingot')
|
||||
hi, lo, stamp = MATERIALS[material]
|
||||
cv = Cv(64)
|
||||
if name.startswith('raw_'):
|
||||
for pts in ([(10, 27), (16, 14), (29, 11), (35, 23), (28, 40), (15, 43)],
|
||||
[(27, 15), (39, 7), (53, 14), (57, 31), (47, 43), (32, 37)],
|
||||
[(18, 39), (32, 30), (48, 37), (50, 50), (36, 58), (20, 53)]):
|
||||
m = cv.poly(pts)
|
||||
soft_body(cv, m, mix(hi, SP["sand"], .15), mix(lo, SP["dune2"], .25), ew=.9, light=.45, dark=.28)
|
||||
for path in ([(17, 18), (24, 24), (20, 35)], [(39, 12), (42, 23), (52, 29)], [(25, 44), (35, 40), (43, 48)]):
|
||||
cv.solid(cv.line(path, 1.0), SP["umber"], .38)
|
||||
dust(cv, [(22, 20), (44, 18), (38, 48)], "#fff3d2", 1.0, .75)
|
||||
else:
|
||||
side = cv.poly([(6, 28), (41, 15), (58, 27), (58, 43), (23, 56), (6, 45)])
|
||||
cv.fill(side, mix(lo, SP["umber"], .1), mix(lo, SP["umber"], .45))
|
||||
cv.bevel(side, .25, .3, 1); cv.edge(side, SP["umber"], .9, .85)
|
||||
top = cv.poly([(6, 27), (41, 13), (58, 25), (23, 40)])
|
||||
cv.fill(top, mix(hi, "#ffffff", .2), hi)
|
||||
cv.bevel(top, .5, .25, 1); cv.edge(top, SP["umber"], .8, .8)
|
||||
for pts in ([(13, 29), (24, 25)], [(30, 38), (47, 28)]): # soft pressed grooves
|
||||
cv.solid(cv.line(pts, .8), SP["umber"], .22)
|
||||
st = gear(cv, 33, 28, 4.6, 8, .15, .32) # maker's stamp
|
||||
cv.solid(st, stamp, .72)
|
||||
cv.solid(cv.line([(12, 38), (30, 47)], 1.0), "#fff1cf", .22)
|
||||
return finish(cv, seed=len(name))
|
||||
"""Ingots and raw ore in the soft Dune style: pressed brass-age bars and rough nuggets with a small stamp."""
|
||||
from dunelib import Cv, mix
|
||||
from dunesoft import *
|
||||
|
||||
NAMES = {'iron_ingot', 'gold_ingot', 'copper_ingot', 'netherite_ingot', 'raw_iron', 'raw_gold', 'raw_copper'}
|
||||
MATERIALS = { # hi, lo, stamp
|
||||
'iron': ('#d9d6c4', '#7d7c70', '#41699f'),
|
||||
'gold': ('#f0d58c', '#a47f38', '#8c4f2d'),
|
||||
'copper': ('#e2a37c', '#8d5636', '#5c8c76'),
|
||||
'netherite': ('#8b8087', '#3a3238', '#c9803a'),
|
||||
}
|
||||
|
||||
|
||||
def draw(name):
|
||||
material = name.removeprefix('raw_').removesuffix('_ingot')
|
||||
hi, lo, stamp = MATERIALS[material]
|
||||
cv = Cv(64)
|
||||
if name.startswith('raw_'):
|
||||
for pts in ([(10, 27), (16, 14), (29, 11), (35, 23), (28, 40), (15, 43)],
|
||||
[(27, 15), (39, 7), (53, 14), (57, 31), (47, 43), (32, 37)],
|
||||
[(18, 39), (32, 30), (48, 37), (50, 50), (36, 58), (20, 53)]):
|
||||
m = cv.poly(pts)
|
||||
soft_body(cv, m, mix(hi, SP["sand"], .15), mix(lo, SP["dune2"], .25), ew=.9, light=.45, dark=.28)
|
||||
for path in ([(17, 18), (24, 24), (20, 35)], [(39, 12), (42, 23), (52, 29)], [(25, 44), (35, 40), (43, 48)]):
|
||||
cv.solid(cv.line(path, 1.0), SP["umber"], .38)
|
||||
dust(cv, [(22, 20), (44, 18), (38, 48)], "#fff3d2", 1.0, .75)
|
||||
else:
|
||||
side = cv.poly([(6, 28), (41, 15), (58, 27), (58, 43), (23, 56), (6, 45)])
|
||||
cv.fill(side, mix(lo, SP["umber"], .1), mix(lo, SP["umber"], .45))
|
||||
cv.bevel(side, .25, .3, 1); cv.edge(side, SP["umber"], .9, .85)
|
||||
top = cv.poly([(6, 27), (41, 13), (58, 25), (23, 40)])
|
||||
cv.fill(top, mix(hi, "#ffffff", .2), hi)
|
||||
cv.bevel(top, .5, .25, 1); cv.edge(top, SP["umber"], .8, .8)
|
||||
for pts in ([(13, 29), (24, 25)], [(30, 38), (47, 28)]): # soft pressed grooves
|
||||
cv.solid(cv.line(pts, .8), SP["umber"], .22)
|
||||
st = gear(cv, 33, 28, 4.6, 8, .15, .32) # maker's stamp
|
||||
cv.solid(st, stamp, .72)
|
||||
cv.solid(cv.line([(12, 38), (30, 47)], 1.0), "#fff1cf", .22)
|
||||
return finish(cv, seed=len(name))
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,260 +1,260 @@
|
|||
"""Deterministic resource-pack assembly and dependency closure; never runs plugin/game code."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import urllib.request
|
||||
import zipfile
|
||||
import plugin_vanilla_art
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / 'network/resource-pack/central'
|
||||
PACK_ID = 'c24c7cf5-a292-539d-971f-a96d8b838162'
|
||||
VALID = re.compile(r'[a-z0-9_.-]+:[a-z0-9_./-]+\Z')
|
||||
|
||||
|
||||
def encoded(value): return (json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))+'\n').encode()
|
||||
def resource(value):
|
||||
value = value if ':' in value else 'minecraft:'+value
|
||||
if not VALID.fullmatch(value) or '..' in value.split(':')[1].split('/'): raise ValueError('Invalid resource ID: '+value)
|
||||
return value.split(':', 1)
|
||||
def path_for(value, kind, suffix='.json'):
|
||||
ns, path = resource(value); return f'assets/{ns}/{kind}/{path}{suffix}'
|
||||
def read_zip(path):
|
||||
files = {}
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
for item in archive.infolist():
|
||||
name = item.filename
|
||||
if item.is_dir(): continue
|
||||
if name in files or name.startswith('/') or '\\' in name or '..' in name.split('/'):
|
||||
raise ValueError('Unsafe/duplicate archive entry: '+name)
|
||||
files[name] = archive.read(item)
|
||||
return files
|
||||
|
||||
|
||||
def client_assets(cache, supplied=None):
|
||||
lock = json.loads((SOURCE/'inputs.lock.json').read_text(encoding='utf-8'))['client']
|
||||
path = Path(supplied) if supplied else Path(cache)/'minecraft-26.3-client.jar'
|
||||
if not path.exists():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with urllib.request.urlopen(lock['url'], timeout=60) as response: payload=response.read(lock['size']+1)
|
||||
if len(payload)!=lock['size'] or hashlib.sha1(payload).hexdigest()!=lock['sha1']: raise ValueError('Official client download differs')
|
||||
path.write_bytes(payload)
|
||||
if path.stat().st_size!=lock['size'] or hashlib.sha1(path.read_bytes()).hexdigest()!=lock['sha1']: raise ValueError('Pinned client assets differ')
|
||||
return {key:value for key,value in read_zip(path).items() if key.startswith('assets/')}
|
||||
|
||||
|
||||
def strings_named(value, name):
|
||||
if isinstance(value, dict):
|
||||
for key, child in value.items():
|
||||
if key==name and isinstance(child, str): yield child
|
||||
else: yield from strings_named(child, name)
|
||||
elif isinstance(value, list):
|
||||
for child in value: yield from strings_named(child, name)
|
||||
|
||||
|
||||
class Closure:
|
||||
def __init__(self, pack, vanilla):
|
||||
self.pack=pack; self.files=dict(vanilla, **pack); self.cache={}
|
||||
def model(self, key, chain=()):
|
||||
if key in chain: raise ValueError('Model parent cycle: '+key)
|
||||
if key not in self.files: raise ValueError('Missing model: '+key)
|
||||
obj=json.loads(self.files[key]); textures={}; elements=[]
|
||||
parent=obj.get('parent')
|
||||
if parent and not parent.split(':')[-1].startswith('builtin/'):
|
||||
inherited, elements=self.model(path_for(parent,'models'),chain+(key,)); textures.update(inherited)
|
||||
textures.update(obj.get('textures',{})); elements=obj.get('elements',elements)
|
||||
if chain:return textures,elements
|
||||
def resolve(ref, seen=()):
|
||||
if isinstance(ref,dict): ref=ref['sprite']
|
||||
if ref.startswith('#'):
|
||||
name=ref[1:]
|
||||
if name in seen or name not in textures: raise ValueError('Unresolved model texture variable: '+key+' '+ref)
|
||||
return resolve(textures[name],seen+(name,))
|
||||
if key=='assets/minecraft/models/block/air.json' and ref in ('missingno','minecraft:missingno') and not elements:return ref
|
||||
target=path_for(ref,'textures','.png')
|
||||
if target not in self.files: raise ValueError('Missing texture: '+target+' in '+key)
|
||||
png=self.files[target]
|
||||
if not png.startswith(b'\x89PNG\r\n\x1a\n') or len(png)<24: raise ValueError('Invalid PNG: '+target)
|
||||
return ref
|
||||
for ref in textures.values(): resolve(ref)
|
||||
for element in elements:
|
||||
span=[abs(b-a) for a,b in zip(element.get('from',[0,0,0]),element.get('to',[16,16,16]))]
|
||||
for side,face in element.get('faces',{}).items():
|
||||
axes={'north':(0,1),'south':(0,1),'east':(1,2),'west':(1,2),'up':(0,2),'down':(0,2)}.get(side)
|
||||
if axes and span[axes[0]]*span[axes[1]]==0:continue
|
||||
if 'texture' in face:
|
||||
ref=face['texture'];resolve('#'+ref if isinstance(ref,str) and ref in textures else ref)
|
||||
return textures,elements
|
||||
def font(self,key,chain=()):
|
||||
if key in chain: raise ValueError('Font reference cycle: '+key)
|
||||
if key not in self.files: raise ValueError('Missing font: '+key)
|
||||
for provider in json.loads(self.files[key]).get('providers',[]):
|
||||
kind=provider['type'].split(':')[-1]
|
||||
if kind=='reference': self.font(path_for(provider['id'],'font'),chain+(key,))
|
||||
elif 'file' in provider:
|
||||
target=path_for(provider['file'],'textures' if kind=='bitmap' else 'font','')
|
||||
if target not in self.files: raise ValueError('Missing font file: '+target)
|
||||
if kind=='bitmap' and not self.files[target].startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid font bitmap: '+target)
|
||||
def validate(self):
|
||||
counts={'models':0,'fonts':0,'items':0,'blockstates':0}
|
||||
parents={path_for(parent,'models') for key,payload in self.files.items() if '/models/' in key and key.endswith('.json') for parent in [json.loads(payload).get('parent')] if parent and not parent.split(':')[-1].startswith('builtin/')}
|
||||
for key,payload in self.pack.items():
|
||||
if key.startswith('assets/') and not re.fullmatch(r'assets/[a-z0-9_./-]+',key): raise ValueError('Invalid asset path: '+key)
|
||||
if key.endswith('.png') and not payload.startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid PNG: '+key)
|
||||
if not key.endswith('.json'): continue
|
||||
value=json.loads(payload)
|
||||
if '/models/' in key: self.model(key,('__template__',) if key in parents else ()); counts['models']+=1
|
||||
elif '/font/' in key: self.font(key); counts['fonts']+=1
|
||||
elif '/items/' in key or '/blockstates/' in key:
|
||||
for ref in strings_named(value,'model'): self.model(path_for(ref,'models'))
|
||||
counts['items' if '/items/' in key else 'blockstates']+=1
|
||||
elif '/atlases/' in key:
|
||||
seen=set()
|
||||
for source in value.get('sources',[]):
|
||||
if source['type'].split(':')[-1]=='single':
|
||||
ref=source.get('sprite',source['resource'])
|
||||
if ref in seen: raise ValueError('Duplicate atlas sprite: '+ref)
|
||||
seen.add(ref)
|
||||
if path_for(source['resource'],'textures','.png') not in self.files: raise ValueError('Missing atlas texture: '+ref)
|
||||
return counts
|
||||
|
||||
def vanilla_catalog(files,vanilla):
|
||||
"""Prove coverage of every concrete static texture referenced by vanilla item models.
|
||||
|
||||
Trim sprites are generated by the native paletted atlas, not separate PNG files.
|
||||
Native special renderers/player-head skins retain their original model definitions.
|
||||
"""
|
||||
audit=Closure(files,vanilla);generated=set();static=set();definitions=0;references=0
|
||||
atlas=json.loads(vanilla['assets/minecraft/atlases/items.json'])
|
||||
for source in atlas['sources']:
|
||||
if source['type'].split(':')[-1]!='paletted_permutations':continue
|
||||
for base in source['textures']:
|
||||
template=path_for(base,'textures','.png')
|
||||
if template not in vanilla or template in files:raise ValueError('Native trim template must be preserved: '+template)
|
||||
for suffix in source['permutations']:generated.add(path_for(base+'_'+suffix,'textures','.png'))
|
||||
for ref in [source['palette_key'],*source['permutations'].values()]:
|
||||
ns,path=resource(ref)
|
||||
if f'assets/{ns}/textures/palettes/{path}.png' not in vanilla:raise ValueError('Missing native trim palette')
|
||||
for key,payload in vanilla.items():
|
||||
if not key.startswith('assets/minecraft/items/') or not key.endswith('.json'):continue
|
||||
definitions+=1;value=json.loads(payload)
|
||||
for ref in [*strings_named(value,'model'),*strings_named(value,'base')]:
|
||||
references+=1;textures,_=audit.model(path_for(ref,'models'),('vanilla-catalog',))
|
||||
for texture in textures.values():
|
||||
if isinstance(texture,dict):texture=texture['sprite']
|
||||
if texture.startswith('#'):continue
|
||||
target=path_for(texture,'textures','.png')
|
||||
if target in generated or target=='assets/minecraft/textures/missingno.png':continue
|
||||
if target not in files:raise ValueError('Uncovered vanilla item texture: '+target)
|
||||
static.add(target)
|
||||
return {'definitions':definitions,'modelReferences':references,'staticTextureReferences':len(static),'nativeGeneratedTrimSprites':len(generated),'specialRendererModels':'preserved'}
|
||||
|
||||
|
||||
def required_item_sprites(files, vanilla):
|
||||
"""Modern item definitions may point at models/entity or any other model directory."""
|
||||
sprites=set(); audit=Closure(files,vanilla)
|
||||
for key,payload in files.items():
|
||||
if '/items/' not in key or not key.endswith('.json'): continue
|
||||
definition=json.loads(payload)
|
||||
for model in [*strings_named(definition,'model'), *strings_named(definition,'base')]:
|
||||
textures,elements=audit.model(path_for(model,'models'))
|
||||
for ref in textures.values():
|
||||
if isinstance(ref,dict):ref=ref['sprite']
|
||||
if not ref.startswith('#'):
|
||||
ns,leaf=resource(ref)
|
||||
if ns!='minecraft' and not leaf.startswith(('item/','block/')):sprites.add(ns+':'+leaf)
|
||||
return sprites
|
||||
|
||||
|
||||
def validate_item_atlas(files, vanilla):
|
||||
sources=json.loads(files.get('assets/minecraft/atlases/items.json',b'{"sources":[]}'))['sources']
|
||||
published={source.get('sprite',source['resource']) for source in sources if source['type'].split(':')[-1]=='single'}
|
||||
missing=required_item_sprites(files,vanilla)-published
|
||||
if missing:raise ValueError('Item atlas missing custom sprites: '+', '.join(sorted(missing)))
|
||||
|
||||
|
||||
def validate_block_layer(files, vanilla, paths):
|
||||
atlas=json.loads(vanilla['assets/minecraft/atlases/blocks.json'])
|
||||
if not any(s.get('type') in ('directory','minecraft:directory') and s.get('source')=='block' and s.get('prefix')=='block/' for s in atlas['sources']):raise ValueError('Native block sprite directory contract changed')
|
||||
audit=Closure(files,vanilla);states=0;references=0
|
||||
for key,payload in audit.files.items():
|
||||
if '/blockstates/' in key and key.endswith('.json') and key in vanilla:
|
||||
for model in strings_named(json.loads(payload),'model'):audit.model(path_for(model,'models'))
|
||||
for key in paths:
|
||||
if not key.startswith('assets/minecraft/blockstates/') or key not in vanilla:continue
|
||||
states+=1
|
||||
for model in strings_named(json.loads(files[key]),'model'):
|
||||
textures,elements=audit.model(path_for(model,'models'))
|
||||
for ref in textures.values():
|
||||
if isinstance(ref,dict):ref=ref['sprite']
|
||||
if ref.startswith('#'):continue
|
||||
ns,leaf=resource(ref)
|
||||
if ns=='minecraft' and leaf=='missingno' and not elements:continue
|
||||
if ns!='minecraft' or not leaf.startswith('block/'):raise ValueError('Block sprite outside reviewed native atlas: '+ref)
|
||||
target=path_for(ref,'textures','.png')
|
||||
if target not in audit.files:raise ValueError('Missing block sprite: '+ref)
|
||||
references+=1
|
||||
entity_sprites=0
|
||||
native_sources=[source for key,payload in vanilla.items() if key.startswith('assets/minecraft/atlases/') and key.endswith('.json') for source in json.loads(payload).get('sources',[])]
|
||||
for key in paths:
|
||||
if not key.startswith('assets/minecraft/textures/entity/') or not key.endswith('.png'):continue
|
||||
leaf=key[len('assets/minecraft/textures/'):-4]
|
||||
covered=any((source.get('type','').split(':')[-1]=='directory' and leaf.startswith(source.get('source','')+'/') and source.get('prefix')==source.get('source')+'/') or (source.get('type','').split(':')[-1]=='single' and tuple(resource(source.get('resource','')))==('minecraft',leaf)) for source in native_sources)
|
||||
if not covered:raise ValueError('Block-entity sprite lacks a native atlas source: '+key)
|
||||
entity_sprites+=1
|
||||
return {'blockstates':states,'resolvedSpriteReferences':references,'blockEntitySprites':entity_sprites,'atlas':'native atlas sources; no atlas overrides'}
|
||||
|
||||
def build(output, source_commit, vanilla, source_root=SOURCE):
|
||||
if not re.fullmatch('[a-f0-9]{40}',source_commit):raise ValueError('Exact source SHA required')
|
||||
lock=json.loads((source_root/'inputs.lock.json').read_text(encoding='utf-8'))
|
||||
files,vanilla_art=plugin_vanilla_art.load(vanilla)
|
||||
owner_root=ROOT/'network/resource-pack/owner-items'
|
||||
if (owner_root/'inputs.json').is_file():
|
||||
approved=json.loads((owner_root/'inputs.json').read_text(encoding='utf-8'))['entries']
|
||||
expected={r['path']:r['sha256'] for r in approved}
|
||||
actual={p.relative_to(owner_root/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (owner_root/'overlay').rglob('*') if p.is_file()}
|
||||
if actual!=expected or any(not n.startswith('assets/minecraft/textures/item/') or '..' in Path(n).parts or not n.endswith(('.png','.png.mcmeta')) for n in actual):raise ValueError('Owner item overlay differs from its reviewed boundary')
|
||||
excal=ROOT/'network/resource-pack/excalibur'
|
||||
if (excal/'inputs.json').is_file():
|
||||
approved=json.loads((excal/'inputs.json').read_text(encoding='utf-8'))['entries']
|
||||
expected={r['path']:r['sha256'] for r in approved}
|
||||
actual={p.relative_to(excal/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (excal/'overlay').rglob('*') if p.is_file()}
|
||||
if actual!=expected or any(not n.startswith(('assets/minecraft/textures/block/','assets/minecraft/models/block/','assets/minecraft/blockstates/','assets/minecraft/textures/entity/chest/','assets/minecraft/textures/entity/bed/','assets/minecraft/textures/entity/signs/','assets/minecraft/textures/entity/bell/','assets/minecraft/textures/entity/conduit/','assets/minecraft/textures/entity/decorated_pot/','assets/minecraft/textures/entity/enchantment/')) or '..' in Path(n).parts for n in actual):raise ValueError('Excalibur block layer differs from reviewed bytes/scope')
|
||||
if set(actual)&plugin_vanilla_art.PROTECTED:raise ValueError('Excalibur replaces protected spice artwork')
|
||||
replacements=[]
|
||||
for directory in (ROOT/'network/resource-pack/excalibur/overlay',ROOT/'network/resource-pack/owner-items/overlay',ROOT/'network/resource-pack/dune-items/overlay',source_root/'legacy',ROOT/'network/resource-pack/shared',source_root/'overlay',ROOT/'network/resource-pack/dune-items/custom'):
|
||||
for path in sorted(directory.rglob('*')):
|
||||
if path.is_file():
|
||||
key=path.relative_to(directory).as_posix();payload=path.read_bytes()
|
||||
if key in files and files[key]!=payload:replacements.append(key)
|
||||
files[key]=payload
|
||||
# Compatibility alias removes the historical dangling default-font reference without replacing source artwork.
|
||||
files['assets/dunerealms/font/imperial_menus.json']=encoded({'providers':[{'type':'reference','id':'dunerealms:card_art'},{'type':'reference','id':'dunerealms:lore_panels'}]})
|
||||
# Item-only sprites outside the vanilla item directory need explicit registration; register in ONE atlas.
|
||||
sprites=required_item_sprites(files,vanilla)
|
||||
files['assets/minecraft/atlases/items.json']=encoded({'sources':[{'type':'minecraft:single','resource':ref,'sprite':ref} for ref in sorted(sprites)]})
|
||||
transport_path=ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip'
|
||||
if hashlib.sha256(transport_path.read_bytes()).hexdigest()!=lock['transportSha256']:raise ValueError('Transport input differs')
|
||||
transport=read_zip(transport_path)
|
||||
for key,value in transport.items():
|
||||
if key=='pack.mcmeta':continue
|
||||
if key in files and files[key]!=value:raise ValueError('Unexpected GUI transport collision: '+key)
|
||||
files[key]=value
|
||||
meta=json.loads(transport['pack.mcmeta']);meta['pack']={'description':'DuneRealms | One central network resource pack','min_format':88,'max_format':97}
|
||||
files['pack.mcmeta']=encoded(meta)
|
||||
files['CREDITS-DuneRealms.txt']=b'DuneRealms central artwork: owner-supplied procedural source and assets. Vanilla material layer extends that generator, retaining Minecraft/Mojang silhouettes and UV relief where noted; futuristic ore/metal icons and masonry/furniture materials by DuneRealms. Existing custom card atlases, legacy custom item/entity artwork and MCGUI transport preserved. No Xeindom/XAE assets.\n'
|
||||
if (excal/'inputs.json').is_file():
|
||||
files['CREDITS-Excalibur.txt']=(excal/'CREATOR-LICENSE.txt').read_bytes()+b'\nOfficial project: https://www.planetminecraft.com/texture-pack/excalibur/\nBlock-only network integration: Owner attested permission to merge on2026-11-29. Original licence retained; no general derivative permission claimed.\n'
|
||||
counts=Closure(files,vanilla).validate()
|
||||
validate_item_atlas(files,vanilla)
|
||||
if (excal/'inputs.json').is_file():counts['excalibur']=validate_block_layer(files,vanilla,[r['path'] for r in approved])
|
||||
vanilla_art['itemCatalog']=vanilla_catalog(files,vanilla)
|
||||
output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
|
||||
with zipfile.ZipFile(output,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=9) as zipout:
|
||||
for key,value in sorted(files.items()):
|
||||
info=zipfile.ZipInfo(key,(2026,11,29,0,0,0));info.create_system=0;info.compress_type=zipfile.ZIP_DEFLATED;zipout.writestr(info,value,compresslevel=9)
|
||||
if read_zip(output)!=files:raise ValueError('Built ZIP differs from source assembly')
|
||||
data=output.read_bytes();manifest={'filename':output.name,'sourceCommit':source_commit,'packId':PACK_ID,'delivery':'server','unified':True,'bytes':len(data),'sha1':hashlib.sha1(data).hexdigest(),'sha256':hashlib.sha256(data).hexdigest(),'entries':len(files),'validation':counts,'vanillaArtwork':vanilla_art,'inputs':lock,'replacedAssetPaths':sorted(set(replacements))}
|
||||
output.with_suffix('.manifest.json').write_bytes(encoded(manifest));return manifest
|
||||
"""Deterministic resource-pack assembly and dependency closure; never runs plugin/game code."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import urllib.request
|
||||
import zipfile
|
||||
import plugin_vanilla_art
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / 'network/resource-pack/central'
|
||||
PACK_ID = 'c24c7cf5-a292-539d-971f-a96d8b838162'
|
||||
VALID = re.compile(r'[a-z0-9_.-]+:[a-z0-9_./-]+\Z')
|
||||
|
||||
|
||||
def encoded(value): return (json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))+'\n').encode()
|
||||
def resource(value):
|
||||
value = value if ':' in value else 'minecraft:'+value
|
||||
if not VALID.fullmatch(value) or '..' in value.split(':')[1].split('/'): raise ValueError('Invalid resource ID: '+value)
|
||||
return value.split(':', 1)
|
||||
def path_for(value, kind, suffix='.json'):
|
||||
ns, path = resource(value); return f'assets/{ns}/{kind}/{path}{suffix}'
|
||||
def read_zip(path):
|
||||
files = {}
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
for item in archive.infolist():
|
||||
name = item.filename
|
||||
if item.is_dir(): continue
|
||||
if name in files or name.startswith('/') or '\\' in name or '..' in name.split('/'):
|
||||
raise ValueError('Unsafe/duplicate archive entry: '+name)
|
||||
files[name] = archive.read(item)
|
||||
return files
|
||||
|
||||
|
||||
def client_assets(cache, supplied=None):
|
||||
lock = json.loads((SOURCE/'inputs.lock.json').read_text(encoding='utf-8'))['client']
|
||||
path = Path(supplied) if supplied else Path(cache)/'minecraft-26.3-client.jar'
|
||||
if not path.exists():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with urllib.request.urlopen(lock['url'], timeout=60) as response: payload=response.read(lock['size']+1)
|
||||
if len(payload)!=lock['size'] or hashlib.sha1(payload).hexdigest()!=lock['sha1']: raise ValueError('Official client download differs')
|
||||
path.write_bytes(payload)
|
||||
if path.stat().st_size!=lock['size'] or hashlib.sha1(path.read_bytes()).hexdigest()!=lock['sha1']: raise ValueError('Pinned client assets differ')
|
||||
return {key:value for key,value in read_zip(path).items() if key.startswith('assets/')}
|
||||
|
||||
|
||||
def strings_named(value, name):
|
||||
if isinstance(value, dict):
|
||||
for key, child in value.items():
|
||||
if key==name and isinstance(child, str): yield child
|
||||
else: yield from strings_named(child, name)
|
||||
elif isinstance(value, list):
|
||||
for child in value: yield from strings_named(child, name)
|
||||
|
||||
|
||||
class Closure:
|
||||
def __init__(self, pack, vanilla):
|
||||
self.pack=pack; self.files=dict(vanilla, **pack); self.cache={}
|
||||
def model(self, key, chain=()):
|
||||
if key in chain: raise ValueError('Model parent cycle: '+key)
|
||||
if key not in self.files: raise ValueError('Missing model: '+key)
|
||||
obj=json.loads(self.files[key]); textures={}; elements=[]
|
||||
parent=obj.get('parent')
|
||||
if parent and not parent.split(':')[-1].startswith('builtin/'):
|
||||
inherited, elements=self.model(path_for(parent,'models'),chain+(key,)); textures.update(inherited)
|
||||
textures.update(obj.get('textures',{})); elements=obj.get('elements',elements)
|
||||
if chain:return textures,elements
|
||||
def resolve(ref, seen=()):
|
||||
if isinstance(ref,dict): ref=ref['sprite']
|
||||
if ref.startswith('#'):
|
||||
name=ref[1:]
|
||||
if name in seen or name not in textures: raise ValueError('Unresolved model texture variable: '+key+' '+ref)
|
||||
return resolve(textures[name],seen+(name,))
|
||||
if key=='assets/minecraft/models/block/air.json' and ref in ('missingno','minecraft:missingno') and not elements:return ref
|
||||
target=path_for(ref,'textures','.png')
|
||||
if target not in self.files: raise ValueError('Missing texture: '+target+' in '+key)
|
||||
png=self.files[target]
|
||||
if not png.startswith(b'\x89PNG\r\n\x1a\n') or len(png)<24: raise ValueError('Invalid PNG: '+target)
|
||||
return ref
|
||||
for ref in textures.values(): resolve(ref)
|
||||
for element in elements:
|
||||
span=[abs(b-a) for a,b in zip(element.get('from',[0,0,0]),element.get('to',[16,16,16]))]
|
||||
for side,face in element.get('faces',{}).items():
|
||||
axes={'north':(0,1),'south':(0,1),'east':(1,2),'west':(1,2),'up':(0,2),'down':(0,2)}.get(side)
|
||||
if axes and span[axes[0]]*span[axes[1]]==0:continue
|
||||
if 'texture' in face:
|
||||
ref=face['texture'];resolve('#'+ref if isinstance(ref,str) and ref in textures else ref)
|
||||
return textures,elements
|
||||
def font(self,key,chain=()):
|
||||
if key in chain: raise ValueError('Font reference cycle: '+key)
|
||||
if key not in self.files: raise ValueError('Missing font: '+key)
|
||||
for provider in json.loads(self.files[key]).get('providers',[]):
|
||||
kind=provider['type'].split(':')[-1]
|
||||
if kind=='reference': self.font(path_for(provider['id'],'font'),chain+(key,))
|
||||
elif 'file' in provider:
|
||||
target=path_for(provider['file'],'textures' if kind=='bitmap' else 'font','')
|
||||
if target not in self.files: raise ValueError('Missing font file: '+target)
|
||||
if kind=='bitmap' and not self.files[target].startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid font bitmap: '+target)
|
||||
def validate(self):
|
||||
counts={'models':0,'fonts':0,'items':0,'blockstates':0}
|
||||
parents={path_for(parent,'models') for key,payload in self.files.items() if '/models/' in key and key.endswith('.json') for parent in [json.loads(payload).get('parent')] if parent and not parent.split(':')[-1].startswith('builtin/')}
|
||||
for key,payload in self.pack.items():
|
||||
if key.startswith('assets/') and not re.fullmatch(r'assets/[a-z0-9_./-]+',key): raise ValueError('Invalid asset path: '+key)
|
||||
if key.endswith('.png') and not payload.startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid PNG: '+key)
|
||||
if not key.endswith('.json'): continue
|
||||
value=json.loads(payload)
|
||||
if '/models/' in key: self.model(key,('__template__',) if key in parents else ()); counts['models']+=1
|
||||
elif '/font/' in key: self.font(key); counts['fonts']+=1
|
||||
elif '/items/' in key or '/blockstates/' in key:
|
||||
for ref in strings_named(value,'model'): self.model(path_for(ref,'models'))
|
||||
counts['items' if '/items/' in key else 'blockstates']+=1
|
||||
elif '/atlases/' in key:
|
||||
seen=set()
|
||||
for source in value.get('sources',[]):
|
||||
if source['type'].split(':')[-1]=='single':
|
||||
ref=source.get('sprite',source['resource'])
|
||||
if ref in seen: raise ValueError('Duplicate atlas sprite: '+ref)
|
||||
seen.add(ref)
|
||||
if path_for(source['resource'],'textures','.png') not in self.files: raise ValueError('Missing atlas texture: '+ref)
|
||||
return counts
|
||||
|
||||
def vanilla_catalog(files,vanilla):
|
||||
"""Prove coverage of every concrete static texture referenced by vanilla item models.
|
||||
|
||||
Trim sprites are generated by the native paletted atlas, not separate PNG files.
|
||||
Native special renderers/player-head skins retain their original model definitions.
|
||||
"""
|
||||
audit=Closure(files,vanilla);generated=set();static=set();definitions=0;references=0
|
||||
atlas=json.loads(vanilla['assets/minecraft/atlases/items.json'])
|
||||
for source in atlas['sources']:
|
||||
if source['type'].split(':')[-1]!='paletted_permutations':continue
|
||||
for base in source['textures']:
|
||||
template=path_for(base,'textures','.png')
|
||||
if template not in vanilla or template in files:raise ValueError('Native trim template must be preserved: '+template)
|
||||
for suffix in source['permutations']:generated.add(path_for(base+'_'+suffix,'textures','.png'))
|
||||
for ref in [source['palette_key'],*source['permutations'].values()]:
|
||||
ns,path=resource(ref)
|
||||
if f'assets/{ns}/textures/palettes/{path}.png' not in vanilla:raise ValueError('Missing native trim palette')
|
||||
for key,payload in vanilla.items():
|
||||
if not key.startswith('assets/minecraft/items/') or not key.endswith('.json'):continue
|
||||
definitions+=1;value=json.loads(payload)
|
||||
for ref in [*strings_named(value,'model'),*strings_named(value,'base')]:
|
||||
references+=1;textures,_=audit.model(path_for(ref,'models'),('vanilla-catalog',))
|
||||
for texture in textures.values():
|
||||
if isinstance(texture,dict):texture=texture['sprite']
|
||||
if texture.startswith('#'):continue
|
||||
target=path_for(texture,'textures','.png')
|
||||
if target in generated or target=='assets/minecraft/textures/missingno.png':continue
|
||||
if target not in files:raise ValueError('Uncovered vanilla item texture: '+target)
|
||||
static.add(target)
|
||||
return {'definitions':definitions,'modelReferences':references,'staticTextureReferences':len(static),'nativeGeneratedTrimSprites':len(generated),'specialRendererModels':'preserved'}
|
||||
|
||||
|
||||
def required_item_sprites(files, vanilla):
|
||||
"""Modern item definitions may point at models/entity or any other model directory."""
|
||||
sprites=set(); audit=Closure(files,vanilla)
|
||||
for key,payload in files.items():
|
||||
if '/items/' not in key or not key.endswith('.json'): continue
|
||||
definition=json.loads(payload)
|
||||
for model in [*strings_named(definition,'model'), *strings_named(definition,'base')]:
|
||||
textures,elements=audit.model(path_for(model,'models'))
|
||||
for ref in textures.values():
|
||||
if isinstance(ref,dict):ref=ref['sprite']
|
||||
if not ref.startswith('#'):
|
||||
ns,leaf=resource(ref)
|
||||
if ns!='minecraft' and not leaf.startswith(('item/','block/')):sprites.add(ns+':'+leaf)
|
||||
return sprites
|
||||
|
||||
|
||||
def validate_item_atlas(files, vanilla):
|
||||
sources=json.loads(files.get('assets/minecraft/atlases/items.json',b'{"sources":[]}'))['sources']
|
||||
published={source.get('sprite',source['resource']) for source in sources if source['type'].split(':')[-1]=='single'}
|
||||
missing=required_item_sprites(files,vanilla)-published
|
||||
if missing:raise ValueError('Item atlas missing custom sprites: '+', '.join(sorted(missing)))
|
||||
|
||||
|
||||
def validate_block_layer(files, vanilla, paths):
|
||||
atlas=json.loads(vanilla['assets/minecraft/atlases/blocks.json'])
|
||||
if not any(s.get('type') in ('directory','minecraft:directory') and s.get('source')=='block' and s.get('prefix')=='block/' for s in atlas['sources']):raise ValueError('Native block sprite directory contract changed')
|
||||
audit=Closure(files,vanilla);states=0;references=0
|
||||
for key,payload in audit.files.items():
|
||||
if '/blockstates/' in key and key.endswith('.json') and key in vanilla:
|
||||
for model in strings_named(json.loads(payload),'model'):audit.model(path_for(model,'models'))
|
||||
for key in paths:
|
||||
if not key.startswith('assets/minecraft/blockstates/') or key not in vanilla:continue
|
||||
states+=1
|
||||
for model in strings_named(json.loads(files[key]),'model'):
|
||||
textures,elements=audit.model(path_for(model,'models'))
|
||||
for ref in textures.values():
|
||||
if isinstance(ref,dict):ref=ref['sprite']
|
||||
if ref.startswith('#'):continue
|
||||
ns,leaf=resource(ref)
|
||||
if ns=='minecraft' and leaf=='missingno' and not elements:continue
|
||||
if ns!='minecraft' or not leaf.startswith('block/'):raise ValueError('Block sprite outside reviewed native atlas: '+ref)
|
||||
target=path_for(ref,'textures','.png')
|
||||
if target not in audit.files:raise ValueError('Missing block sprite: '+ref)
|
||||
references+=1
|
||||
entity_sprites=0
|
||||
native_sources=[source for key,payload in vanilla.items() if key.startswith('assets/minecraft/atlases/') and key.endswith('.json') for source in json.loads(payload).get('sources',[])]
|
||||
for key in paths:
|
||||
if not key.startswith('assets/minecraft/textures/entity/') or not key.endswith('.png'):continue
|
||||
leaf=key[len('assets/minecraft/textures/'):-4]
|
||||
covered=any((source.get('type','').split(':')[-1]=='directory' and leaf.startswith(source.get('source','')+'/') and source.get('prefix')==source.get('source')+'/') or (source.get('type','').split(':')[-1]=='single' and tuple(resource(source.get('resource','')))==('minecraft',leaf)) for source in native_sources)
|
||||
if not covered:raise ValueError('Block-entity sprite lacks a native atlas source: '+key)
|
||||
entity_sprites+=1
|
||||
return {'blockstates':states,'resolvedSpriteReferences':references,'blockEntitySprites':entity_sprites,'atlas':'native atlas sources; no atlas overrides'}
|
||||
|
||||
def build(output, source_commit, vanilla, source_root=SOURCE):
|
||||
if not re.fullmatch('[a-f0-9]{40}',source_commit):raise ValueError('Exact source SHA required')
|
||||
lock=json.loads((source_root/'inputs.lock.json').read_text(encoding='utf-8'))
|
||||
files,vanilla_art=plugin_vanilla_art.load(vanilla)
|
||||
owner_root=ROOT/'network/resource-pack/owner-items'
|
||||
if (owner_root/'inputs.json').is_file():
|
||||
approved=json.loads((owner_root/'inputs.json').read_text(encoding='utf-8'))['entries']
|
||||
expected={r['path']:r['sha256'] for r in approved}
|
||||
actual={p.relative_to(owner_root/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (owner_root/'overlay').rglob('*') if p.is_file()}
|
||||
if actual!=expected or any(not n.startswith('assets/minecraft/textures/item/') or '..' in Path(n).parts or not n.endswith(('.png','.png.mcmeta')) for n in actual):raise ValueError('Owner item overlay differs from its reviewed boundary')
|
||||
excal=ROOT/'network/resource-pack/excalibur'
|
||||
if (excal/'inputs.json').is_file():
|
||||
approved=json.loads((excal/'inputs.json').read_text(encoding='utf-8'))['entries']
|
||||
expected={r['path']:r['sha256'] for r in approved}
|
||||
actual={p.relative_to(excal/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (excal/'overlay').rglob('*') if p.is_file()}
|
||||
if actual!=expected or any(not n.startswith(('assets/minecraft/textures/block/','assets/minecraft/models/block/','assets/minecraft/blockstates/','assets/minecraft/textures/entity/chest/','assets/minecraft/textures/entity/bed/','assets/minecraft/textures/entity/signs/','assets/minecraft/textures/entity/bell/','assets/minecraft/textures/entity/conduit/','assets/minecraft/textures/entity/decorated_pot/','assets/minecraft/textures/entity/enchantment/')) or '..' in Path(n).parts for n in actual):raise ValueError('Excalibur block layer differs from reviewed bytes/scope')
|
||||
if set(actual)&plugin_vanilla_art.PROTECTED:raise ValueError('Excalibur replaces protected spice artwork')
|
||||
replacements=[]
|
||||
for directory in (ROOT/'network/resource-pack/excalibur/overlay',ROOT/'network/resource-pack/owner-items/overlay',ROOT/'network/resource-pack/dune-items/overlay',source_root/'legacy',ROOT/'network/resource-pack/shared',source_root/'overlay',ROOT/'network/resource-pack/dune-items/custom'):
|
||||
for path in sorted(directory.rglob('*')):
|
||||
if path.is_file():
|
||||
key=path.relative_to(directory).as_posix();payload=path.read_bytes()
|
||||
if key in files and files[key]!=payload:replacements.append(key)
|
||||
files[key]=payload
|
||||
# Compatibility alias removes the historical dangling default-font reference without replacing source artwork.
|
||||
files['assets/dunerealms/font/imperial_menus.json']=encoded({'providers':[{'type':'reference','id':'dunerealms:card_art'},{'type':'reference','id':'dunerealms:lore_panels'}]})
|
||||
# Item-only sprites outside the vanilla item directory need explicit registration; register in ONE atlas.
|
||||
sprites=required_item_sprites(files,vanilla)
|
||||
files['assets/minecraft/atlases/items.json']=encoded({'sources':[{'type':'minecraft:single','resource':ref,'sprite':ref} for ref in sorted(sprites)]})
|
||||
transport_path=ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip'
|
||||
if hashlib.sha256(transport_path.read_bytes()).hexdigest()!=lock['transportSha256']:raise ValueError('Transport input differs')
|
||||
transport=read_zip(transport_path)
|
||||
for key,value in transport.items():
|
||||
if key=='pack.mcmeta':continue
|
||||
if key in files and files[key]!=value:raise ValueError('Unexpected GUI transport collision: '+key)
|
||||
files[key]=value
|
||||
meta=json.loads(transport['pack.mcmeta']);meta['pack']={'description':'DuneRealms | One central network resource pack','min_format':88,'max_format':97}
|
||||
files['pack.mcmeta']=encoded(meta)
|
||||
files['CREDITS-DuneRealms.txt']=b'DuneRealms central artwork: owner-supplied procedural source and assets. Vanilla material layer extends that generator, retaining Minecraft/Mojang silhouettes and UV relief where noted; futuristic ore/metal icons and masonry/furniture materials by DuneRealms. Existing custom card atlases, legacy custom item/entity artwork and MCGUI transport preserved. No Xeindom/XAE assets.\n'
|
||||
if (excal/'inputs.json').is_file():
|
||||
files['CREDITS-Excalibur.txt']=(excal/'CREATOR-LICENSE.txt').read_bytes()+b'\nOfficial project: https://www.planetminecraft.com/texture-pack/excalibur/\nBlock-only network integration: Owner attested permission to merge on2026-11-29. Original licence retained; no general derivative permission claimed.\n'
|
||||
counts=Closure(files,vanilla).validate()
|
||||
validate_item_atlas(files,vanilla)
|
||||
if (excal/'inputs.json').is_file():counts['excalibur']=validate_block_layer(files,vanilla,[r['path'] for r in approved])
|
||||
vanilla_art['itemCatalog']=vanilla_catalog(files,vanilla)
|
||||
output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
|
||||
with zipfile.ZipFile(output,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=9) as zipout:
|
||||
for key,value in sorted(files.items()):
|
||||
info=zipfile.ZipInfo(key,(2026,11,29,0,0,0));info.create_system=0;info.compress_type=zipfile.ZIP_DEFLATED;zipout.writestr(info,value,compresslevel=9)
|
||||
if read_zip(output)!=files:raise ValueError('Built ZIP differs from source assembly')
|
||||
data=output.read_bytes();manifest={'filename':output.name,'sourceCommit':source_commit,'packId':PACK_ID,'delivery':'server','unified':True,'bytes':len(data),'sha1':hashlib.sha1(data).hexdigest(),'sha256':hashlib.sha256(data).hexdigest(),'entries':len(files),'validation':counts,'vanillaArtwork':vanilla_art,'inputs':lock,'replacedAssetPaths':sorted(set(replacements))}
|
||||
output.with_suffix('.manifest.json').write_bytes(encoded(manifest));return manifest
|
||||
|
|
|
|||
|
|
@ -54,4 +54,4 @@ if __name__ == '__main__':
|
|||
for field in ('baseline', 'source', 'pins', 'output'):
|
||||
parser.add_argument(field, type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(assemble(args.variant, args.baseline, args.source, args.pins, args.output), indent=2))
|
||||
print(json.dumps(assemble(args.variant, args.baseline, args.source, args.pins, args.output), indent=2))
|
||||
|
|
|
|||
|
|
@ -1,66 +1,66 @@
|
|||
"""Invariants for the soft Dune item layer: alpha/size preserved, tint layers untouched, files match the manifest."""
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RP = ROOT / "network/resource-pack"
|
||||
sys.path.insert(0, str(RP / "central/generator"))
|
||||
import dune_item_grade as grade
|
||||
import soft_metals
|
||||
|
||||
LAYER = RP / "dune-items"
|
||||
|
||||
|
||||
class DuneItemGradeTests(unittest.TestCase):
|
||||
def test_alpha_and_size_preserved_for_every_graded_sprite(self):
|
||||
checked = 0
|
||||
for stem, path in grade.sources().items():
|
||||
new = LAYER / "overlay/assets/minecraft/textures/item" / f"{stem}.png"
|
||||
self.assertTrue(new.is_file(), stem)
|
||||
if stem in soft_metals.NAMES:
|
||||
self.assertEqual(Image.open(new).size[0], Image.open(new).size[1], stem) # redrawn at 64px; item models are size-independent
|
||||
continue
|
||||
a, b = Image.open(path).convert("RGBA"), Image.open(new).convert("RGBA")
|
||||
self.assertEqual(a.size, b.size, stem)
|
||||
self.assertTrue(np.array_equal(np.asarray(a)[..., 3], np.asarray(b)[..., 3]), "alpha changed: " + stem)
|
||||
checked += 1
|
||||
self.assertGreater(checked, 800)
|
||||
|
||||
def test_tint_layers_are_byte_identical_and_neutral_sprites_stay_neutral(self):
|
||||
for stem, path in grade.sources().items():
|
||||
if grade.classify(stem) == "skip":
|
||||
self.assertEqual(Image.open(path).convert("RGBA").tobytes(),
|
||||
Image.open(LAYER / "overlay/assets/minecraft/textures/item" / f"{stem}.png").convert("RGBA").tobytes(), stem)
|
||||
if grade.classify(stem) == "neutral":
|
||||
arr = np.asarray(Image.open(LAYER / "overlay/assets/minecraft/textures/item" / f"{stem}.png").convert("RGBA"), dtype=float)
|
||||
opaque = arr[arr[..., 3] > 0][:, :3]
|
||||
src = np.asarray(Image.open(path).convert("RGBA"), dtype=float)
|
||||
srcc = src[src[..., 3] > 0][:, :3]
|
||||
self.assertLess(abs(float((opaque.max(1) - opaque.min(1)).mean()) - float((srcc.max(1) - srcc.min(1)).mean())), 12, stem)
|
||||
|
||||
def test_manifest_hashes_match_files(self):
|
||||
manifest = json.loads((LAYER / "MANIFEST.json").read_text())["files"]
|
||||
for rel, info in manifest.items():
|
||||
self.assertEqual(hashlib.sha256((LAYER / rel).read_bytes()).hexdigest(), info["sha256"], rel)
|
||||
|
||||
def test_layer_only_contains_item_textures(self):
|
||||
for p in list((LAYER / "overlay").rglob("*")) + list((LAYER / "custom").rglob("*")):
|
||||
if p.is_file():
|
||||
rel = p.relative_to(LAYER).as_posix()
|
||||
self.assertTrue(rel.startswith(("overlay/assets/minecraft/textures/item/", "custom/assets/dunerealms/textures/item/")), rel)
|
||||
self.assertTrue(rel.endswith(".png"), rel)
|
||||
|
||||
def test_grade_is_deterministic(self):
|
||||
for stem in ("apple", "diamond_sword", "leather_chestplate"):
|
||||
img = Image.open(grade.sources()[stem])
|
||||
self.assertEqual(grade.grade_image(img, stem)[0].tobytes(), grade.grade_image(img, stem)[0].tobytes())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
"""Invariants for the soft Dune item layer: alpha/size preserved, tint layers untouched, files match the manifest."""
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RP = ROOT / "network/resource-pack"
|
||||
sys.path.insert(0, str(RP / "central/generator"))
|
||||
import dune_item_grade as grade
|
||||
import soft_metals
|
||||
|
||||
LAYER = RP / "dune-items"
|
||||
|
||||
|
||||
class DuneItemGradeTests(unittest.TestCase):
|
||||
def test_alpha_and_size_preserved_for_every_graded_sprite(self):
|
||||
checked = 0
|
||||
for stem, path in grade.sources().items():
|
||||
new = LAYER / "overlay/assets/minecraft/textures/item" / f"{stem}.png"
|
||||
self.assertTrue(new.is_file(), stem)
|
||||
if stem in soft_metals.NAMES:
|
||||
self.assertEqual(Image.open(new).size[0], Image.open(new).size[1], stem) # redrawn at 64px; item models are size-independent
|
||||
continue
|
||||
a, b = Image.open(path).convert("RGBA"), Image.open(new).convert("RGBA")
|
||||
self.assertEqual(a.size, b.size, stem)
|
||||
self.assertTrue(np.array_equal(np.asarray(a)[..., 3], np.asarray(b)[..., 3]), "alpha changed: " + stem)
|
||||
checked += 1
|
||||
self.assertGreater(checked, 800)
|
||||
|
||||
def test_tint_layers_are_byte_identical_and_neutral_sprites_stay_neutral(self):
|
||||
for stem, path in grade.sources().items():
|
||||
if grade.classify(stem) == "skip":
|
||||
self.assertEqual(Image.open(path).convert("RGBA").tobytes(),
|
||||
Image.open(LAYER / "overlay/assets/minecraft/textures/item" / f"{stem}.png").convert("RGBA").tobytes(), stem)
|
||||
if grade.classify(stem) == "neutral":
|
||||
arr = np.asarray(Image.open(LAYER / "overlay/assets/minecraft/textures/item" / f"{stem}.png").convert("RGBA"), dtype=float)
|
||||
opaque = arr[arr[..., 3] > 0][:, :3]
|
||||
src = np.asarray(Image.open(path).convert("RGBA"), dtype=float)
|
||||
srcc = src[src[..., 3] > 0][:, :3]
|
||||
self.assertLess(abs(float((opaque.max(1) - opaque.min(1)).mean()) - float((srcc.max(1) - srcc.min(1)).mean())), 12, stem)
|
||||
|
||||
def test_manifest_hashes_match_files(self):
|
||||
manifest = json.loads((LAYER / "MANIFEST.json").read_text())["files"]
|
||||
for rel, info in manifest.items():
|
||||
self.assertEqual(hashlib.sha256((LAYER / rel).read_bytes()).hexdigest(), info["sha256"], rel)
|
||||
|
||||
def test_layer_only_contains_item_textures(self):
|
||||
for p in list((LAYER / "overlay").rglob("*")) + list((LAYER / "custom").rglob("*")):
|
||||
if p.is_file():
|
||||
rel = p.relative_to(LAYER).as_posix()
|
||||
self.assertTrue(rel.startswith(("overlay/assets/minecraft/textures/item/", "custom/assets/dunerealms/textures/item/")), rel)
|
||||
self.assertTrue(rel.endswith(".png"), rel)
|
||||
|
||||
def test_grade_is_deterministic(self):
|
||||
for stem in ("apple", "diamond_sword", "leather_chestplate"):
|
||||
img = Image.open(grade.sources()[stem])
|
||||
self.assertEqual(grade.grade_image(img, stem)[0].tobytes(), grade.grade_image(img, stem)[0].tobytes())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -1,146 +1,146 @@
|
|||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import hashlib
|
||||
import unittest
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parent))
|
||||
import plugin_resource_pack as pack
|
||||
|
||||
PNG=b'\x89PNG\r\n\x1a\n'+b'\0'*16
|
||||
class DependencyTests(unittest.TestCase):
|
||||
def test_native_empty_air_builtin_is_not_a_general_missing_texture_bypass(self):
|
||||
key='assets/minecraft/models/block/air.json';obj={'textures':{'particle':'minecraft:missingno'}}
|
||||
pack.Closure({key:pack.encoded(obj)},{}).model(key)
|
||||
with self.assertRaises(ValueError):pack.Closure({'assets/test/models/air.json':pack.encoded(obj)},{}).validate()
|
||||
obj['elements']=[{'faces':{'north':{'texture':'#particle'}}}]
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded(obj)},{}).model(key)
|
||||
def test_zero_area_faces_do_not_require_invisible_texture_but_visible_faces_do(self):
|
||||
key='assets/test/models/plane.json';obj={'elements':[{'from':[0,0,8],'to':[16,16,8],'faces':{'east':{'texture':'#missing'}}}]}
|
||||
pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
obj['elements'][0]['faces']={'north':{'texture':'#missing'}}
|
||||
with self.assertRaisesRegex(ValueError,'Unresolved'):pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
def test_imported_templates_are_checked_in_bound_child_context(self):
|
||||
files={'assets/test/models/template.json':pack.encoded({'elements':[{'faces':{'north':{'texture':'#all'}}}]}),'assets/test/models/child.json':pack.encoded({'parent':'test:template','textures':{'all':'test:real'}}),'assets/test/textures/real.png':PNG}
|
||||
pack.Closure(files,{}).validate()
|
||||
files['assets/test/models/child.json']=pack.encoded({'parent':'test:template'})
|
||||
with self.assertRaisesRegex(ValueError,'Unresolved'):pack.Closure(files,{}).validate()
|
||||
def test_native_bare_face_slot_requires_an_existing_bound_texture(self):
|
||||
key='assets/test/models/solid.json';obj={'textures':{'all':'test:real'},'elements':[{'faces':{'north':{'texture':'all'}}}]}
|
||||
pack.Closure({key:pack.encoded(obj),'assets/test/textures/real.png':PNG},{}).validate()
|
||||
del obj['textures']['all']
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
def test_item_display_entity_model_requires_an_explicit_item_atlas_sprite(self):
|
||||
files={'assets/test/items/entity/animal.json':pack.encoded({'model':{'type':'minecraft:model','model':'test:entity/animal'}}),
|
||||
'assets/test/models/entity/animal.json':pack.encoded({'textures':{'fur':'test:entity/animal','particle':'#fur'}}),
|
||||
'assets/test/textures/entity/animal.png':PNG}
|
||||
self.assertEqual(pack.required_item_sprites(files,{}),{'test:entity/animal'})
|
||||
with self.assertRaisesRegex(ValueError,'Item atlas missing'):pack.validate_item_atlas(files,{})
|
||||
files['assets/minecraft/atlases/items.json']=pack.encoded({'sources':[{'type':'minecraft:single','resource':'test:entity/animal','sprite':'test:entity/animal'}]})
|
||||
pack.validate_item_atlas(files,{})
|
||||
def test_historical_missing_default_font_is_rejected(self):
|
||||
files={'assets/minecraft/font/default.json':pack.encoded({'providers':[{'type':'reference','id':'dunerealms:imperial_menus'}]})}
|
||||
with self.assertRaisesRegex(ValueError,'Missing font'):pack.Closure(files,{}).validate()
|
||||
def test_font_cycles_and_missing_bitmap_fail(self):
|
||||
key='assets/test/font/a.json'
|
||||
for provider in ({'type':'reference','id':'test:a'},{'type':'bitmap','file':'test:absent.png'}):
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded({'providers':[provider]})},{}).validate()
|
||||
def test_parent_cycles_and_missing_texture_fail(self):
|
||||
key='assets/test/models/a.json'
|
||||
for obj in ({'parent':'test:a'},{'textures':{'layer0':'test:absent'}}):
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
def test_inherited_face_variables_resolve_in_child_context(self):
|
||||
parent={'elements':[{'faces':{'north':{'texture':'#all'}}}]}
|
||||
files={'assets/test/models/child.json':pack.encoded({'parent':'test:parent','textures':{'all':'test:real'}}),'assets/test/textures/real.png':PNG}
|
||||
self.assertEqual(pack.Closure(files,{'assets/test/models/parent.json':pack.encoded(parent)}).validate()['models'],1)
|
||||
def test_duplicate_atlas_sprite_and_dangling_item_target_fail(self):
|
||||
source={'type':'minecraft:single','resource':'test:real'}
|
||||
with self.assertRaisesRegex(ValueError,'Duplicate atlas'):pack.Closure({'assets/minecraft/atlases/items.json':pack.encoded({'sources':[source,source]}),'assets/test/textures/real.png':PNG},{}).validate()
|
||||
with self.assertRaisesRegex(ValueError,'Missing model'):pack.Closure({'assets/test/items/a.json':pack.encoded({'model':{'type':'minecraft:model','model':'test:absent'}})},{}).validate()
|
||||
|
||||
class CompletePackTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
import os
|
||||
cls.vanilla=pack.client_assets(pack.ROOT/'build/resourcepack-cache',os.environ.get('DUNE_PACK_CLIENT'))
|
||||
def test_actual_complete_pack_closure_and_all224_equipment_keys(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out=Path(tmp)/('DuneRealms-Resources-'+'a'*40+'.zip');result=pack.build(out,'a'*40,self.vanilla);files=pack.read_zip(out)
|
||||
self.assertTrue(result['unified']);self.assertEqual(result['delivery'],'server')
|
||||
owner=pack.ROOT/'network/resource-pack/owner-items'
|
||||
if (owner/'baseline-02e.json').is_file():
|
||||
baseline=json.loads((owner/'baseline-02e.json').read_text(encoding='utf-8'))['entries']
|
||||
changes={r['path']:r['sha256'] for r in json.loads((owner/'inputs.json').read_text(encoding='utf-8'))['entries']}
|
||||
self.assertEqual(len(changes),654)
|
||||
excal=pack.ROOT/'network/resource-pack/excalibur/inputs.json'
|
||||
if excal.is_file():
|
||||
additions=json.loads(excal.read_text(encoding='utf-8'))['entries'];changes.update({r['path']:r['sha256'] for r in additions})
|
||||
import plugin_vanilla_art as art_compat
|
||||
import urllib.request
|
||||
compatibility=art_compat.compatibility_inputs()[1]['client']
|
||||
cache=pack.ROOT/'build/resourcepack-cache/minecraft-26.2-client.jar'
|
||||
if not cache.exists():
|
||||
with urllib.request.urlopen(compatibility['url'],timeout=60) as response:cache.write_bytes(response.read())
|
||||
self.assertEqual(hashlib.sha1(cache.read_bytes()).hexdigest(),compatibility['sha1'])
|
||||
older={k:v for k,v in pack.read_zip(cache).items() if k.startswith('assets/')}
|
||||
custom={k:v for k,v in files.items() if k.startswith('assets/dunerealms/')}
|
||||
pack.Closure(custom,dict(older,**files)).validate()
|
||||
pack.validate_block_layer(files,older,[r['path'] for r in additions])
|
||||
|
||||
native_items={f'assets/dunerealms/{kind}/{item}.{extension}'
|
||||
for item in ('crysknife','maker_tooth')
|
||||
for kind,extension in (('items','json'),('models/item','json'),('textures/item','png'))}
|
||||
from plugin_dunechest_pack import ASSETS
|
||||
self.assertEqual(set(files),set(baseline)|set(changes)|{'CREDITS-Excalibur.txt'}|native_items|ASSETS)
|
||||
else:self.assertEqual(set(files),set(baseline))
|
||||
# Only the approved redesigned jerboa models and texture replace the owner baseline.
|
||||
changes.update({
|
||||
'assets/dunerealms/models/entity/jerboa.json': '6785d870031b326814b79a1f75fa0e69c1e0f2ba2c14644d4f046032a2c81df6',
|
||||
'assets/dunerealms/models/entity/jerboa_curled.json': 'dd089bd58ab333fe08910f1f826d904c170507e4e41930d94f6b09f216c264e9',
|
||||
'assets/dunerealms/models/entity/jerboa_walk_left.json': '13c9797d60e56719125474138c5efdcf0667b94df0e70e6998f3956f618a7012',
|
||||
'assets/dunerealms/models/entity/jerboa_walk_right.json': '52cb0005d6a90b5e3e8f73375c3795b00c7fe8d639794b84024343be010915ff',
|
||||
'assets/dunerealms/textures/entity/jerboa.png': '7cb10841fd92827f536c8138fdbebde7b0871de143cf8d5b715e7dc0d474f967',
|
||||
})
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import hashlib
|
||||
import unittest
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parent))
|
||||
import plugin_resource_pack as pack
|
||||
|
||||
PNG=b'\x89PNG\r\n\x1a\n'+b'\0'*16
|
||||
class DependencyTests(unittest.TestCase):
|
||||
def test_native_empty_air_builtin_is_not_a_general_missing_texture_bypass(self):
|
||||
key='assets/minecraft/models/block/air.json';obj={'textures':{'particle':'minecraft:missingno'}}
|
||||
pack.Closure({key:pack.encoded(obj)},{}).model(key)
|
||||
with self.assertRaises(ValueError):pack.Closure({'assets/test/models/air.json':pack.encoded(obj)},{}).validate()
|
||||
obj['elements']=[{'faces':{'north':{'texture':'#particle'}}}]
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded(obj)},{}).model(key)
|
||||
def test_zero_area_faces_do_not_require_invisible_texture_but_visible_faces_do(self):
|
||||
key='assets/test/models/plane.json';obj={'elements':[{'from':[0,0,8],'to':[16,16,8],'faces':{'east':{'texture':'#missing'}}}]}
|
||||
pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
obj['elements'][0]['faces']={'north':{'texture':'#missing'}}
|
||||
with self.assertRaisesRegex(ValueError,'Unresolved'):pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
def test_imported_templates_are_checked_in_bound_child_context(self):
|
||||
files={'assets/test/models/template.json':pack.encoded({'elements':[{'faces':{'north':{'texture':'#all'}}}]}),'assets/test/models/child.json':pack.encoded({'parent':'test:template','textures':{'all':'test:real'}}),'assets/test/textures/real.png':PNG}
|
||||
pack.Closure(files,{}).validate()
|
||||
files['assets/test/models/child.json']=pack.encoded({'parent':'test:template'})
|
||||
with self.assertRaisesRegex(ValueError,'Unresolved'):pack.Closure(files,{}).validate()
|
||||
def test_native_bare_face_slot_requires_an_existing_bound_texture(self):
|
||||
key='assets/test/models/solid.json';obj={'textures':{'all':'test:real'},'elements':[{'faces':{'north':{'texture':'all'}}}]}
|
||||
pack.Closure({key:pack.encoded(obj),'assets/test/textures/real.png':PNG},{}).validate()
|
||||
del obj['textures']['all']
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
def test_item_display_entity_model_requires_an_explicit_item_atlas_sprite(self):
|
||||
files={'assets/test/items/entity/animal.json':pack.encoded({'model':{'type':'minecraft:model','model':'test:entity/animal'}}),
|
||||
'assets/test/models/entity/animal.json':pack.encoded({'textures':{'fur':'test:entity/animal','particle':'#fur'}}),
|
||||
'assets/test/textures/entity/animal.png':PNG}
|
||||
self.assertEqual(pack.required_item_sprites(files,{}),{'test:entity/animal'})
|
||||
with self.assertRaisesRegex(ValueError,'Item atlas missing'):pack.validate_item_atlas(files,{})
|
||||
files['assets/minecraft/atlases/items.json']=pack.encoded({'sources':[{'type':'minecraft:single','resource':'test:entity/animal','sprite':'test:entity/animal'}]})
|
||||
pack.validate_item_atlas(files,{})
|
||||
def test_historical_missing_default_font_is_rejected(self):
|
||||
files={'assets/minecraft/font/default.json':pack.encoded({'providers':[{'type':'reference','id':'dunerealms:imperial_menus'}]})}
|
||||
with self.assertRaisesRegex(ValueError,'Missing font'):pack.Closure(files,{}).validate()
|
||||
def test_font_cycles_and_missing_bitmap_fail(self):
|
||||
key='assets/test/font/a.json'
|
||||
for provider in ({'type':'reference','id':'test:a'},{'type':'bitmap','file':'test:absent.png'}):
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded({'providers':[provider]})},{}).validate()
|
||||
def test_parent_cycles_and_missing_texture_fail(self):
|
||||
key='assets/test/models/a.json'
|
||||
for obj in ({'parent':'test:a'},{'textures':{'layer0':'test:absent'}}):
|
||||
with self.assertRaises(ValueError):pack.Closure({key:pack.encoded(obj)},{}).validate()
|
||||
def test_inherited_face_variables_resolve_in_child_context(self):
|
||||
parent={'elements':[{'faces':{'north':{'texture':'#all'}}}]}
|
||||
files={'assets/test/models/child.json':pack.encoded({'parent':'test:parent','textures':{'all':'test:real'}}),'assets/test/textures/real.png':PNG}
|
||||
self.assertEqual(pack.Closure(files,{'assets/test/models/parent.json':pack.encoded(parent)}).validate()['models'],1)
|
||||
def test_duplicate_atlas_sprite_and_dangling_item_target_fail(self):
|
||||
source={'type':'minecraft:single','resource':'test:real'}
|
||||
with self.assertRaisesRegex(ValueError,'Duplicate atlas'):pack.Closure({'assets/minecraft/atlases/items.json':pack.encoded({'sources':[source,source]}),'assets/test/textures/real.png':PNG},{}).validate()
|
||||
with self.assertRaisesRegex(ValueError,'Missing model'):pack.Closure({'assets/test/items/a.json':pack.encoded({'model':{'type':'minecraft:model','model':'test:absent'}})},{}).validate()
|
||||
|
||||
class CompletePackTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
import os
|
||||
cls.vanilla=pack.client_assets(pack.ROOT/'build/resourcepack-cache',os.environ.get('DUNE_PACK_CLIENT'))
|
||||
def test_actual_complete_pack_closure_and_all224_equipment_keys(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out=Path(tmp)/('DuneRealms-Resources-'+'a'*40+'.zip');result=pack.build(out,'a'*40,self.vanilla);files=pack.read_zip(out)
|
||||
self.assertTrue(result['unified']);self.assertEqual(result['delivery'],'server')
|
||||
owner=pack.ROOT/'network/resource-pack/owner-items'
|
||||
if (owner/'baseline-02e.json').is_file():
|
||||
baseline=json.loads((owner/'baseline-02e.json').read_text(encoding='utf-8'))['entries']
|
||||
changes={r['path']:r['sha256'] for r in json.loads((owner/'inputs.json').read_text(encoding='utf-8'))['entries']}
|
||||
self.assertEqual(len(changes),654)
|
||||
excal=pack.ROOT/'network/resource-pack/excalibur/inputs.json'
|
||||
if excal.is_file():
|
||||
additions=json.loads(excal.read_text(encoding='utf-8'))['entries'];changes.update({r['path']:r['sha256'] for r in additions})
|
||||
import plugin_vanilla_art as art_compat
|
||||
import urllib.request
|
||||
compatibility=art_compat.compatibility_inputs()[1]['client']
|
||||
cache=pack.ROOT/'build/resourcepack-cache/minecraft-26.2-client.jar'
|
||||
if not cache.exists():
|
||||
with urllib.request.urlopen(compatibility['url'],timeout=60) as response:cache.write_bytes(response.read())
|
||||
self.assertEqual(hashlib.sha1(cache.read_bytes()).hexdigest(),compatibility['sha1'])
|
||||
older={k:v for k,v in pack.read_zip(cache).items() if k.startswith('assets/')}
|
||||
custom={k:v for k,v in files.items() if k.startswith('assets/dunerealms/')}
|
||||
pack.Closure(custom,dict(older,**files)).validate()
|
||||
pack.validate_block_layer(files,older,[r['path'] for r in additions])
|
||||
|
||||
native_items={f'assets/dunerealms/{kind}/{item}.{extension}'
|
||||
for item in ('crysknife','maker_tooth')
|
||||
for kind,extension in (('items','json'),('models/item','json'),('textures/item','png'))}
|
||||
from plugin_dunechest_pack import ASSETS
|
||||
self.assertEqual(set(files),set(baseline)|set(changes)|{'CREDITS-Excalibur.txt'}|native_items|ASSETS)
|
||||
else:self.assertEqual(set(files),set(baseline))
|
||||
# Only the approved redesigned jerboa models and texture replace the owner baseline.
|
||||
changes.update({
|
||||
'assets/dunerealms/models/entity/jerboa.json': '6785d870031b326814b79a1f75fa0e69c1e0f2ba2c14644d4f046032a2c81df6',
|
||||
'assets/dunerealms/models/entity/jerboa_curled.json': 'dd089bd58ab333fe08910f1f826d904c170507e4e41930d94f6b09f216c264e9',
|
||||
'assets/dunerealms/models/entity/jerboa_walk_left.json': '13c9797d60e56719125474138c5efdcf0667b94df0e70e6998f3956f618a7012',
|
||||
'assets/dunerealms/models/entity/jerboa_walk_right.json': '52cb0005d6a90b5e3e8f73375c3795b00c7fe8d639794b84024343be010915ff',
|
||||
'assets/dunerealms/textures/entity/jerboa.png': '7cb10841fd92827f536c8138fdbebde7b0871de143cf8d5b715e7dc0d474f967',
|
||||
})
|
||||
supplied_items=pack.ROOT/'network/resource-pack/dune-items/publication-pins.json'
|
||||
if supplied_items.is_file():
|
||||
reviewed=json.loads(supplied_items.read_text(encoding='utf-8'))
|
||||
self.assertTrue(set(reviewed)<=set(files))
|
||||
for key,sha in reviewed.items():self.assertEqual(hashlib.sha256(files[key]).hexdigest(),sha,key)
|
||||
changes.update(reviewed)
|
||||
for key,expected in baseline.items():
|
||||
if key!='pack.mcmeta':self.assertEqual(hashlib.sha256(files[key]).hexdigest(),changes.get(key,expected),key)
|
||||
|
||||
self.assertEqual(len([n for n in files if n.startswith('assets/dunerealms/items/equipment/')]),224)
|
||||
for key in ['ecology/jerboa_cooked_meat','equipment/uncommon_mk3_helmet','equipment/uncommon_mk3_chestplate','equipment/uncommon_mk3_leggings','equipment/uncommon_mk3_boots','currency/coin_001','spy_module']:
|
||||
self.assertIn('assets/dunerealms/items/'+key+'.json',files)
|
||||
self.assertIn('assets/dunerealms/font/card_art.json',files)
|
||||
self.assertEqual(result['vanillaArtwork']['textures'],2289)
|
||||
self.assertEqual(result['vanillaArtwork']['itemCatalog']['definitions'],1658)
|
||||
self.assertEqual(result['vanillaArtwork']['itemCatalog']['modelReferences'],2344)
|
||||
self.assertEqual(result['vanillaArtwork']['itemCatalog']['nativeGeneratedTrimSprites'],64)
|
||||
meta=json.loads(files['pack.mcmeta'])
|
||||
original_meta=json.loads(pack.read_zip(pack.ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip')['pack.mcmeta'])
|
||||
self.assertEqual(meta['overlays'],original_meta['overlays'])
|
||||
import plugin_vanilla_art as art
|
||||
for key in art.PROTECTED:self.assertEqual(files[key],(pack.SOURCE/'overlay'/key).read_bytes())
|
||||
expected_custom={}
|
||||
for directory in (pack.SOURCE/'legacy',pack.ROOT/'network/resource-pack/shared',pack.SOURCE/'overlay'):
|
||||
for path in directory.rglob('*'):
|
||||
if path.is_file() and path.relative_to(directory).as_posix().startswith('assets/dunerealms/'):
|
||||
expected_custom[path.relative_to(directory).as_posix()]=path.read_bytes()
|
||||
for key,payload in expected_custom.items():self.assertTrue(files.get(key)==payload,key)
|
||||
self.assertNotIn('assets/minecraft/font/default.json',files)
|
||||
sprites={source['sprite'] for source in json.loads(files['assets/minecraft/atlases/items.json'])['sources']}
|
||||
self.assertIn('dunerealms:entity/jerboa',sprites)
|
||||
self.assertIn('assets/dunerealms/items/entity/tiny_worm.json',files)
|
||||
pack.validate_item_atlas(files,self.vanilla)
|
||||
transport=pack.read_zip(pack.ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip')
|
||||
for name,payload in transport.items():
|
||||
if name!='pack.mcmeta':self.assertEqual(files[name],payload)
|
||||
self.assertGreater(result['validation']['models'],300)
|
||||
first=out.read_bytes();pack.build(out,'a'*40,self.vanilla);self.assertEqual(first,out.read_bytes())
|
||||
import plugin_menu_pack as contract
|
||||
self.assertTrue(contract.load_menu(Path(tmp),'a'*40)[1]['unified'])
|
||||
configs=contract.config_payloads(result);self.assertIn('delivery: server',configs['DunerealmsGUI/menu-pack.yml']);self.assertIn(result['packId'],configs['DunerealmsGUI/menu-pack.yml'])
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
for key,expected in baseline.items():
|
||||
if key!='pack.mcmeta':self.assertEqual(hashlib.sha256(files[key]).hexdigest(),changes.get(key,expected),key)
|
||||
|
||||
self.assertEqual(len([n for n in files if n.startswith('assets/dunerealms/items/equipment/')]),224)
|
||||
for key in ['ecology/jerboa_cooked_meat','equipment/uncommon_mk3_helmet','equipment/uncommon_mk3_chestplate','equipment/uncommon_mk3_leggings','equipment/uncommon_mk3_boots','currency/coin_001','spy_module']:
|
||||
self.assertIn('assets/dunerealms/items/'+key+'.json',files)
|
||||
self.assertIn('assets/dunerealms/font/card_art.json',files)
|
||||
self.assertEqual(result['vanillaArtwork']['textures'],2289)
|
||||
self.assertEqual(result['vanillaArtwork']['itemCatalog']['definitions'],1658)
|
||||
self.assertEqual(result['vanillaArtwork']['itemCatalog']['modelReferences'],2344)
|
||||
self.assertEqual(result['vanillaArtwork']['itemCatalog']['nativeGeneratedTrimSprites'],64)
|
||||
meta=json.loads(files['pack.mcmeta'])
|
||||
original_meta=json.loads(pack.read_zip(pack.ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip')['pack.mcmeta'])
|
||||
self.assertEqual(meta['overlays'],original_meta['overlays'])
|
||||
import plugin_vanilla_art as art
|
||||
for key in art.PROTECTED:self.assertEqual(files[key],(pack.SOURCE/'overlay'/key).read_bytes())
|
||||
expected_custom={}
|
||||
for directory in (pack.SOURCE/'legacy',pack.ROOT/'network/resource-pack/shared',pack.SOURCE/'overlay'):
|
||||
for path in directory.rglob('*'):
|
||||
if path.is_file() and path.relative_to(directory).as_posix().startswith('assets/dunerealms/'):
|
||||
expected_custom[path.relative_to(directory).as_posix()]=path.read_bytes()
|
||||
for key,payload in expected_custom.items():self.assertTrue(files.get(key)==payload,key)
|
||||
self.assertNotIn('assets/minecraft/font/default.json',files)
|
||||
sprites={source['sprite'] for source in json.loads(files['assets/minecraft/atlases/items.json'])['sources']}
|
||||
self.assertIn('dunerealms:entity/jerboa',sprites)
|
||||
self.assertIn('assets/dunerealms/items/entity/tiny_worm.json',files)
|
||||
pack.validate_item_atlas(files,self.vanilla)
|
||||
transport=pack.read_zip(pack.ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip')
|
||||
for name,payload in transport.items():
|
||||
if name!='pack.mcmeta':self.assertEqual(files[name],payload)
|
||||
self.assertGreater(result['validation']['models'],300)
|
||||
first=out.read_bytes();pack.build(out,'a'*40,self.vanilla);self.assertEqual(first,out.read_bytes())
|
||||
import plugin_menu_pack as contract
|
||||
self.assertTrue(contract.load_menu(Path(tmp),'a'*40)[1]['unified'])
|
||||
configs=contract.config_payloads(result);self.assertIn('delivery: server',configs['DunerealmsGUI/menu-pack.yml']);self.assertIn(result['packId'],configs['DunerealmsGUI/menu-pack.yml'])
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff