File size: 17,927 Bytes
6da8440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292dc80
6da8440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
"""Converts Minecraft voxel builds into Roblox Part builds.

Neighbouring blocks of the same material are merged into larger boxes (greedy
meshing) so a house becomes ~30-120 Parts instead of thousands of cubes.
1 Minecraft block = 3 studs, which puts doors at ~6-7 studs and matches Roblox
character scale.
"""

from __future__ import annotations

import random
import re
from collections import Counter, defaultdict

from .common import pascal, pretty_name
from .luau_build import Build, Part, answer

BLOCK = 3.0  # studs per Minecraft block

# ---------------------------------------------------------------- materials
DYES = {
    "white": "f0f0f0", "orange": "f07613", "magenta": "bd44b3", "light blue": "3aafd9",
    "yellow": "f8c527", "lime": "70b919", "pink": "ed8dac", "light gray": "8e8e86",
    "silver": "8e8e86", "gray": "3e4447", "cyan": "158991", "purple": "792aac",
    "blue": "35399d", "brown": "724728", "green": "546d1b", "red": "a12722", "black": "141519",
}
WOODS = {  # planks, log/bark
    "dark oak": ("4f3218", "3e2e17"), "oak": ("b8945f", "6b5130"), "spruce": ("7a5a34", "3b2711"),
    "birch": ("d7c185", "d5d0c4"), "jungle": ("b88764", "554419"), "acacia": ("ba6337", "676157"),
    "mangrove": ("773a33", "5b4a3a"), "cherry": ("e3b3ad", "35202a"), "crimson": ("6a344b", "5c1d1e"),
    "warped": ("2b6963", "3a3a4d"), "bamboo": ("c4b05a", "c4b05a"),
}

# (keywords that must all appear, material, hex, transparency). First match wins.
RULES: list[tuple[tuple[str, ...], str, str, float]] = [
    (("water",), "Glass", "3f76e4", 0.5),
    (("lava",), "Neon", "d96415", 0),
    (("sea lantern",), "Neon", "acdcd6", 0),
    (("glowstone",), "Neon", "f8d98c", 0),
    (("lantern",), "Neon", "f8c070", 0),
    (("redstone lamp",), "Neon", "f8c070", 0),
    (("shroomlight",), "Neon", "f19b46", 0),
    (("ice",), "Ice", "91b8ff", 0.15),
    (("snow",), "Snow", "f5fbfb", 0),
    (("mossy", "cobble"), "Cobblestone", "6a7a5a", 0),
    (("cobble",), "Cobblestone", "7a7a7a", 0),
    (("mossy", "brick"), "Slate", "6f7a63", 0),
    (("stone brick",), "Slate", "7b7b7b", 0),
    (("stonebrick",), "Slate", "7b7b7b", 0),
    (("nether brick",), "Brick", "2c1519", 0),
    (("red sandstone",), "Sandstone", "ba6427", 0),
    (("sandstone",), "Sandstone", "d9cb94", 0),
    (("brick",), "Brick", "966253", 0),
    (("smooth stone",), "Concrete", "a0a0a0", 0),
    (("andesite",), "Rock", "888888", 0),
    (("diorite",), "Rock", "bfbfbf", 0),
    (("granite",), "Rock", "9a6b58", 0),
    (("deepslate",), "Slate", "4d4d50", 0),
    (("blackstone",), "Basalt", "2a2328", 0),
    (("obsidian",), "Basalt", "14111c", 0),
    (("bedrock",), "Basalt", "555555", 0),
    (("quartz",), "Marble", "ebe5de", 0),
    (("purpur",), "Marble", "a77ea7", 0),
    (("prismarine",), "Slate", "5fa596", 0),
    (("end stone",), "Sandstone", "dbdea0", 0),
    (("netherrack",), "Rock", "6f3535", 0),
    (("soul sand",), "Sand", "513e32", 0),
    (("concrete powder",), "Sand", "", 0),
    (("concrete",), "Concrete", "", 0),
    (("terracotta",), "Concrete", "", 0),
    (("stained clay",), "Concrete", "", 0),
    (("hardened clay",), "Concrete", "985e43", 0),
    (("stained glass",), "Glass", "", 0.4),
    (("glass",), "Glass", "c0e4ec", 0.6),
    (("wool",), "Fabric", "", 0),
    (("carpet",), "Fabric", "", 0),
    (("leaves",), "LeafyGrass", "3f7b2d", 0),
    (("leaf",), "LeafyGrass", "3f7b2d", 0),
    (("bookshelf",), "WoodPlanks", "6b5130", 0),
    (("chest",), "WoodPlanks", "a0752f", 0),
    (("barrel",), "WoodPlanks", "7a5a34", 0),
    (("crafting",), "WoodPlanks", "8a6a3b", 0),
    (("furnace",), "Cobblestone", "6e6e6e", 0),
    (("dispenser",), "Cobblestone", "6e6e6e", 0),
    (("dropper",), "Cobblestone", "6e6e6e", 0),
    (("hopper",), "Metal", "3e4447", 0),
    (("anvil",), "Metal", "3e4447", 0),
    (("cauldron",), "Metal", "3e4447", 0),
    (("piston",), "WoodPlanks", "9a8a6a", 0),
    (("hay",), "Fabric", "c9a227", 0),
    (("pumpkin",), "SmoothPlastic", "e3901d", 0),
    (("melon",), "SmoothPlastic", "6f9a1f", 0),
    (("iron bars",), "Metal", "6e6e6e", 0),
    (("iron",), "Metal", "d8d8d8", 0),
    (("gold",), "Metal", "f9d849", 0),
    (("diamond",), "SmoothPlastic", "62dbd5", 0),
    (("emerald",), "SmoothPlastic", "2ac65f", 0),
    (("lapis",), "SmoothPlastic", "2a4f9b", 0),
    (("coal",), "Basalt", "1a1a1a", 0),
    (("redstone",), "SmoothPlastic", "aa1d0f", 0),
    (("clay",), "Concrete", "a0a6b2", 0),
    (("gravel",), "Pebble", "857b7b", 0),
    (("sand",), "Sand", "dbcfa3", 0),
    (("path",), "Ground", "a68d55", 0),
    (("farmland",), "Ground", "5a3b1f", 0),
    (("podzol",), "Ground", "5a3d1c", 0),
    (("mycelium",), "Ground", "6f6265", 0),
    (("dirt",), "Ground", "866043", 0),
    (("grass",), "Grass", "5d9b3a", 0),
    (("moss",), "Grass", "596e2d", 0),
    (("stone",), "Rock", "7d7d7d", 0),
]

SKIP = re.compile(
    r"\b(air|torch|flower|poppy|dandelion|tulip|orchid|allium|daisy|cornflower|lily|rose|sapling|"
    r"tall grass|tallgrass|fern|dead bush|mushroom|redstone wire|redstone dust|rail|button|lever|"
    r"sign|banner|ladder|vine|tripwire|string|cobweb|web|door|trapdoor|bed|painting|item frame|"
    r"head|skull|pressure plate|repeater|comparator|flower pot|potted|crop|wheat|carrot|potato|"
    r"sugar cane|reeds|cactus|kelp|seagrass|bell|candle|chain|end rod|beetroot|nether wart|fire|portal|"
    r"structure void|barrier)\b"
)
POST = re.compile(r"\b(fence|wall|bars|post)\b")
SLAB = re.compile(r"\bslab|step\b")
CARPET = re.compile(r"\b(carpet|snow layer|layer)\b")
PANE = re.compile(r"\bpane\b")

# Legacy numeric Minecraft ids (pre-1.13) -> names.
LEGACY_IDS = {
    1: "stone", 2: "grass block", 3: "dirt", 4: "cobblestone", 5: "oak planks", 7: "bedrock",
    8: "water", 9: "water", 10: "lava", 11: "lava", 12: "sand", 13: "gravel", 14: "stone",
    15: "stone", 16: "stone", 17: "oak log", 18: "oak leaves", 19: "hay", 20: "glass",
    21: "stone", 22: "lapis block", 24: "sandstone", 35: "white wool", 41: "gold block",
    42: "iron block", 43: "smooth stone", 44: "stone slab", 45: "brick", 46: "red concrete",
    47: "bookshelf", 48: "mossy cobblestone", 49: "obsidian", 53: "oak stairs", 54: "oak planks",
    57: "diamond block", 58: "oak planks", 60: "farmland", 61: "cobblestone", 62: "cobblestone",
    67: "cobblestone stairs", 78: "snow layer", 79: "ice", 80: "snow block", 82: "clay",
    85: "oak fence", 86: "pumpkin", 87: "netherrack", 88: "soul sand", 89: "glowstone",
    91: "pumpkin", 95: "white stained glass", 98: "stone bricks", 99: "oak planks",
    100: "oak planks", 101: "iron bars", 102: "glass pane", 103: "melon", 107: "oak fence",
    108: "brick stairs", 109: "stone brick stairs", 110: "mycelium", 112: "nether brick",
    113: "nether brick fence", 114: "nether brick stairs", 121: "end stone", 123: "redstone lamp",
    124: "redstone lamp", 125: "oak planks", 126: "oak slab", 128: "sandstone stairs",
    133: "emerald block", 134: "spruce stairs", 135: "birch stairs", 136: "jungle stairs",
    139: "cobblestone wall", 152: "redstone block", 155: "quartz block", 156: "quartz stairs",
    159: "white terracotta", 160: "white stained glass pane", 161: "acacia leaves",
    162: "acacia log", 163: "acacia stairs", 164: "dark oak stairs", 168: "prismarine",
    169: "sea lantern", 170: "hay", 171: "white carpet", 172: "hardened clay", 173: "coal block",
    174: "packed ice", 179: "red sandstone", 180: "red sandstone stairs", 181: "red sandstone",
    182: "red sandstone slab", 183: "spruce fence", 184: "birch fence", 185: "jungle fence",
    186: "dark oak fence", 187: "acacia fence", 188: "spruce fence", 189: "birch fence",
    190: "jungle fence", 191: "dark oak fence", 192: "acacia fence", 201: "purpur block",
    202: "purpur block", 203: "purpur stairs", 205: "purpur slab", 206: "end stone bricks",
    208: "grass path", 213: "netherrack", 214: "nether wart block", 215: "red nether brick",
    216: "bone block", 235: "white terracotta", 251: "white concrete", 252: "white concrete powder",
}
LEGACY_SKIP = {0, 6, 26, 27, 28, 30, 31, 32, 37, 38, 39, 40, 50, 51, 55, 59, 63, 64, 65, 66, 68,
               69, 70, 71, 72, 75, 76, 77, 81, 83, 90, 93, 94, 96, 104, 105, 106, 111, 115, 117,
               118, 119, 120, 127, 131, 132, 140, 141, 142, 143, 144, 145, 147, 148, 149, 150,
               157, 166, 167, 175, 176, 177, 193, 194, 195, 196, 197, 198, 199, 200, 207, 209,
               217, 255}


def classify(raw: str) -> tuple[str, str, str, str, float] | None:
    """Minecraft block name -> (kind, part name, Roblox material, hex, transparency)."""
    name = raw.strip().lower().replace("_", " ")
    name = re.sub(r"^minecraft:", "", name)
    base = re.sub(r"\(.*?\)|\[.*?\]", "", name).strip()
    if not base or SKIP.search(base):
        return None

    if CARPET.search(base):
        kind = "carpet"
    elif SLAB.search(base):
        kind = "slab_top" if re.search(r"upper|top", name) else "slab_bottom"
    elif POST.search(base):
        kind = "post"
    else:
        kind = "full"  # stairs and everything else approximate a full block

    mat, color, tr = "SmoothPlastic", "a3a2a5", 0.0
    wood = next((w for w in WOODS if w in base), None)
    if wood and re.search(r"plank|slab|stair|fence|wood|log|stem|hyphae", base) and "leaves" not in base:
        planks, bark = WOODS[wood]
        if re.search(r"\blog|stem|hyphae|\bwood\b(?! plank| slab| stair| fence)", base) and "plank" not in base:
            mat, color = "Wood", bark
        else:
            mat, color = "WoodPlanks", planks
    elif re.search(r"\bplanks?\b|wooden|wood slab|wood stair", base):
        mat, color = "WoodPlanks", WOODS["oak"][0]
    elif re.search(r"\blog\b", base):
        mat, color = "Wood", WOODS["oak"][1]
    else:
        for keys, m, hx, t in RULES:
            if all(k in base for k in keys):
                mat, color, tr = m, hx, t
                break
        if not color:  # dyed family: pick the dye colour
            dye = next((d for d in sorted(DYES, key=len, reverse=True) if d in base), "white")
            color = DYES[dye]
            if "terracotta" in base or "clay" in base:
                color = _darken(color, 0.72)
        if mat == "Glass" and PANE.search(base) and tr == 0:
            tr = 0.5
    label = pascal(re.sub(r"\b(block|minecraft|of)\b", "", base))[:24] or "Block"
    return kind, label, mat, color, tr


def _darken(hx: str, f: float) -> str:
    r, g, b = (int(hx[i:i + 2], 16) for i in (0, 2, 4))
    return "".join(f"{max(0, min(255, int(c * f))):02x}" for c in (r, g, b))


def legacy_name(block_id) -> str | None:
    s = str(block_id).strip()
    meta = None
    if ":" in s:
        s, meta = s.split(":", 1)
    try:
        i = int(float(s))
    except ValueError:
        return s  # already a name
    if i in LEGACY_SKIP:
        return None
    name = LEGACY_IDS.get(i)
    if name and meta and meta.isdigit() and i in (35, 95, 159, 160, 171, 251, 252):
        order = ["white", "orange", "magenta", "light blue", "yellow", "lime", "pink", "gray",
                 "light gray", "cyan", "purple", "blue", "brown", "green", "red", "black"]
        name = name.replace("white", order[int(meta) % 16])
    return name or "stone"


# ---------------------------------------------------------------- meshing
def greedy_boxes(cells: set[tuple[int, int, int]], kind: str):
    """Merge unit cells into boxes. Yields (x0, y0, z0, dx, dy, dz)."""
    used: set[tuple[int, int, int]] = set()
    for c in sorted(cells, key=lambda c: (c[1], c[2], c[0])):
        if c in used:
            continue
        x, y, z = c
        if kind == "post":
            dy = 1
            while (x, y + dy, z) in cells and (x, y + dy, z) not in used:
                dy += 1
            for k in range(dy):
                used.add((x, y + k, z))
            yield x, y, z, 1, dy, 1
            continue
        dx = 1
        while (x + dx, y, z) in cells and (x + dx, y, z) not in used:
            dx += 1
        dz = 1
        while all((x + i, y, z + dz) in cells and (x + i, y, z + dz) not in used for i in range(dx)):
            dz += 1
        dy = 1
        if kind == "full":
            while all(
                (x + i, y + dy, z + k) in cells and (x + i, y + dy, z + k) not in used
                for i in range(dx) for k in range(dz)
            ):
                dy += 1
        for i in range(dx):
            for j in range(dy):
                for k in range(dz):
                    used.add((x + i, y + j, z + k))
        yield x, y, z, dx, dy, dz


def voxels_to_build(blocks: list[tuple[int, int, int, str]], model_name: str, rotate: int = 0,
                    simplify: bool = False):
    """blocks: (x, y, z, minecraft_name). Returns (Build, stats) or (None, reason)."""
    groups: dict[tuple, set] = defaultdict(set)
    counts: Counter = Counter()
    label_votes: dict[tuple, Counter] = defaultdict(Counter)
    for x, y, z, raw in blocks:
        info = classify(raw)
        if info is None:
            continue
        kind, label, mat, color, tr = info
        if simplify:  # fewer, bigger parts: slabs become blocks, same-look blocks share one group
            if kind == "carpet":
                continue
            if kind != "post":
                kind = "full"
            label_votes[(kind, mat, color, tr)][label] += 1
            label = ""
        if rotate == 1:
            x, z = z, -x
        elif rotate == 2:
            x, z = -x, -z
        elif rotate == 3:
            x, z = -z, x
        groups[(kind, label, mat, color, tr)].add((x, y, z))
        counts[(mat, label)] += 1
    if simplify:
        groups = {(k, label_votes[(k, m, c, t)].most_common(1)[0][0], m, c, t): cells
                  for (k, _, m, c, t), cells in groups.items()}
        counts = Counter()
        for (k, lbl, m, c, t), cells in groups.items():
            counts[(m, lbl)] += len(cells)
    if not groups:
        return None, "empty"
    allc = [c for s in groups.values() for c in s]
    xs, ys, zs = zip(*allc)
    minx, maxx, miny, maxy, minz, maxz = min(xs), max(xs), min(ys), max(ys), min(zs), max(zs)
    cx, cz = (minx + maxx + 1) / 2, (minz + maxz + 1) / 2

    b = Build(model_name)
    for (kind, label, mat, color, tr), cells in sorted(groups.items(), key=lambda kv: -len(kv[1])):
        for x0, y0, z0, dx, dy, dz in greedy_boxes(cells, kind):
            px = (x0 - cx + dx / 2) * BLOCK
            pz = (z0 - cz + dz / 2) * BLOCK
            base_y = (y0 - miny) * BLOCK
            if kind == "full":
                size, py = (dx * BLOCK, dy * BLOCK, dz * BLOCK), base_y + dy * BLOCK / 2
            elif kind == "slab_bottom":
                size, py = (dx * BLOCK, BLOCK / 2, dz * BLOCK), base_y + BLOCK / 4
            elif kind == "slab_top":
                size, py = (dx * BLOCK, BLOCK / 2, dz * BLOCK), base_y + BLOCK * 3 / 4
            elif kind == "carpet":
                size, py = (dx * BLOCK, 0.2, dz * BLOCK), base_y + 0.1
            else:  # post
                size, py = (0.75, dy * BLOCK, 0.75), base_y + dy * BLOCK / 2
            b.add(Part(label, size, (px, py, pz), mat, color, None, tr))
    stats = {
        "blocks": sum(len(s) for s in groups.values()),
        "dims_blocks": (maxx - minx + 1, maxy - miny + 1, maxz - minz + 1),
        "top_materials": [lbl for (_, lbl), _ in counts.most_common(4)],
    }
    return b, stats


# ---------------------------------------------------------------- prompts
PROMPTS = [
    "Build a {name} in Roblox Studio.",
    "Make me a {name}.",
    "build a {name}",
    "Can you build a {name}? Keep it around {w} by {d} studs.",
    "Create a {name} out of parts.",
    "I need a {name} for my game. Build it.",
    "Build a {name} using {m0} and {m1}.",
    "Make a {name}, about {h} studs tall.",
    "Could you make a {name} for my map?",
    "Generate a {name} build I can paste in the command bar.",
]
INTROS = [
    "Here's a {name} ({w}x{d} studs, {h} tall) built from {mats}.",
    "Here's the {name}. It's {w} by {d} studs and {h} studs tall, mostly {mats}.",
    "This {name} uses {n} anchored parts made of {mats}. Paste it in the command bar and it appears where your camera is looking.",
    "{Name} done: {n} parts, {w}x{d} studs footprint, {h} studs tall.",
]


def _human(label: str) -> str:
    return re.sub(r"(?<!^)(?=[A-Z])", " ", label).lower()


def make_example(structure: str, blocks, rng: random.Random, max_parts: int, min_parts: int = 6,
                 rotate: int = 0, desc: str | None = None):
    name = pretty_name(structure).lower()
    name = re.sub(r"\b(minecraft|schematic|mcedit|download|tutorial|world ?edit|v\d+|\d+x\d+)\b", " ", name)
    name = re.sub(r"\s+", " ", name).strip(" -") or "build"
    name = re.sub(r"^(a|an|the|my)\s+", "", name)
    if len(name) < 3:
        return None, "bad name"
    build, stats = voxels_to_build(blocks, pascal(name), rotate=rotate)
    if build is None:
        return None, stats
    if len(build.parts) > max_parts:  # try a simpler version before giving up
        build, stats = voxels_to_build(blocks, pascal(name), rotate=rotate, simplify=True)
        if build is None:
            return None, stats
    n = len(build.parts)
    if n < min_parts:
        return None, "too few parts"
    if n > max_parts:
        return None, "too many parts"
    w, h, d = build.bounds()
    mats = [_human(m) for m in stats["top_materials"]] or ["parts"]
    fmt = dict(name=name, Name=name[:1].upper() + name[1:], w=int(w), d=int(d), h=int(h), n=n,
               m0=mats[0], m1=mats[1] if len(mats) > 1 else mats[0],
               mats=", ".join(mats[:-1]) + (" and " + mats[-1] if len(mats) > 1 else mats[0]))
    if desc:
        user = desc.strip()
    else:
        user = rng.choice(PROMPTS).format(**fmt)
    intro = rng.choice(INTROS).format(**fmt)
    return (user, answer(intro, build)), stats