forge
Explore
Log in

Don't you dare go Hollow

courier

Clone
★ 0

0 watching0 forksRustAGPL-3.05.3 MiB6d9eeb9Tahinli21 days ago3 commits

vox.py364 lines, 13.7 KiBHistoryRawDownload
1import json
2import math
3import os
4
5import numpy as np
6from PIL import Image
7
8ROOT = '/home/tahinli/Documents/Code/Rust/courier'
9GFX = os.path.join(ROOT, 'assets', 'gfx')
10MANIFEST = os.path.join(ROOT, 'tools', 'manifest')
11OUTLINE_RGB = np.array([27, 20, 32], float)
12_U = np.uint64
13_MASK64 = (1 << 64) - 1
14_MATS = [None]
15
16P = {
17 'grass': [(40, 62, 48), (62, 92, 56), (88, 118, 68), (120, 146, 84)],
18 'grass_dry': [(70, 62, 40), (104, 92, 52), (136, 122, 70), (166, 150, 96)],
19 'dirt': [(52, 40, 34), (84, 64, 48), (116, 92, 66), (146, 120, 88)],
20 'mud': [(40, 34, 32), (64, 54, 46), (90, 76, 62), (118, 100, 80)],
21 'cobble': [(54, 56, 62), (84, 84, 88), (114, 112, 112), (142, 136, 128)],
22 'stone': [(86, 88, 96), (122, 120, 118), (156, 150, 140), (186, 178, 164)],
23 'stone_dark': [(38, 38, 44), (62, 60, 64), (90, 86, 84), (118, 110, 104)],
24 'brick': [(92, 38, 34), (124, 54, 44), (152, 78, 58), (178, 108, 76)],
25 'brick_dark': [(56, 28, 30), (80, 40, 38), (106, 56, 48), (130, 76, 62)],
26 'plaster': [(176, 166, 150), (198, 190, 172), (218, 210, 190), (232, 226, 206)],
27 'thatch': [(110, 84, 44), (146, 114, 58), (178, 146, 80), (204, 176, 108)],
28 'wood': [(70, 46, 32), (104, 70, 44), (136, 98, 62), (164, 124, 80)],
29 'wood_dark': [(42, 30, 26), (62, 44, 36), (86, 62, 46), (110, 82, 58)],
30 'slate': [(56, 62, 72), (78, 84, 96), (102, 108, 118), (126, 128, 136)],
31 'coal': [(20, 20, 24), (36, 36, 42), (54, 52, 58), (74, 70, 74)],
32 'water': [(30, 56, 72), (44, 80, 100), (64, 108, 126), (92, 138, 150)],
33 'foliage': [(34, 66, 46), (52, 94, 60), (76, 122, 72), (104, 148, 88)],
34 'foliage_dark': [(26, 46, 40), (38, 66, 52), (54, 90, 62), (74, 112, 76)],
35 'bark': [(44, 34, 30), (64, 50, 40), (88, 70, 54), (114, 92, 70)],
36 'skin': [(120, 78, 62), (164, 112, 88), (200, 146, 116), (224, 176, 144)],
37 'hair_brown': [(44, 30, 24), (70, 48, 34), (98, 70, 46), (124, 94, 64)],
38 'hair_black': [(18, 16, 20), (30, 28, 34), (46, 44, 50), (64, 62, 68)],
39 'hair_gray': [(90, 88, 94), (124, 122, 126), (156, 154, 156), (186, 184, 184)],
40 'cloth_brown': [(60, 40, 30), (88, 60, 42), (118, 84, 58), (146, 108, 76)],
41 'cloth_navy': [(24, 32, 52), (36, 48, 74), (54, 70, 100), (78, 96, 128)],
42 'cloth_green': [(30, 48, 38), (44, 70, 54), (64, 96, 74), (90, 122, 96)],
43 'cloth_wine': [(54, 22, 32), (82, 34, 44), (110, 52, 60), (138, 76, 80)],
44 'cloth_gray': [(56, 58, 66), (84, 86, 94), (112, 114, 120), (140, 142, 146)],
45 'cloth_black': [(18, 18, 24), (30, 30, 38), (46, 46, 54), (66, 64, 72)],
46 'cloth_cream': [(150, 136, 112), (180, 168, 140), (206, 196, 168), (226, 218, 192)],
47 'leather': [(36, 24, 20), (60, 40, 30), (90, 62, 44), (118, 86, 60)],
48 'metal': [(44, 50, 58), (74, 82, 92), (108, 116, 124), (146, 152, 158)],
49 'brass': [(92, 70, 34), (128, 100, 50), (164, 136, 72), (198, 170, 100)],
50 'window': [(214, 156, 64), (240, 196, 96), (252, 224, 140)],
51 'canvas': [(120, 106, 84), (152, 138, 110), (180, 168, 140), (206, 196, 166)],
52 'fire': [(160, 48, 24), (220, 96, 32), (246, 160, 48), (255, 220, 110)],
53}
54
55
56def mat(ramp, pattern=None, emissive=False):
57 assert 3 <= len(ramp) <= 6
58 _MATS.append((np.array(ramp, np.int64), pattern, bool(emissive)))
59 return len(_MATS) - 1
60
61
62def hash3(cx, cy, cz, seed=0):
63 h = np.asarray(cx, np.int64).astype(_U) * _U(0x9E3779B97F4A7C15)
64 h ^= np.asarray(cy, np.int64).astype(_U) * _U(0xC2B2AE3D27D4EB4F)
65 h ^= np.asarray(cz, np.int64).astype(_U) * _U(0x165667B19E3779F9)
66 h ^= _U((seed * 0x27D4EB2F165667C5) & _MASK64)
67 h ^= h >> _U(31)
68 h *= _U(0xBF58476D1CE4E5B9)
69 h ^= h >> _U(29)
70 h *= _U(0x94D049BB133111EB)
71 h ^= h >> _U(32)
72 return (h >> _U(11)).astype(np.float64) / 9007199254740992.0
73
74
75def noise(amount=1, seed=0):
76 def f(cx, cy, cz, face):
77 return np.floor(hash3(cx, cy, cz, seed) * (2 * amount + 1)).astype(np.int64) - amount
78 return f
79
80
81def rows(h=4):
82 def f(cx, cy, cz, face):
83 return np.where(np.asarray(cz) % h == 0, -1, 0)
84 return f
85
86
87def bricks(h=4, w=12):
88 def f(cx, cy, cz, face):
89 cx, cy, cz, face = (np.asarray(a, np.int64) for a in (cx, cy, cz, face))
90 along = np.where(face == 1, cx, cy)
91 course = cz // h
92 off = along + (course & 1) * (w // 2)
93 mortar = (cz % h == 0) | (off % w == 0)
94 var = np.floor(hash3(off // w, course, face, 5) * 3).astype(np.int64) - 1
95 return np.where(mortar, 1, var)
96 return f
97
98
99def planks(w=6, axis=2):
100 def f(cx, cy, cz, face):
101 c = [np.asarray(a, np.int64) for a in (cx, cy, cz)]
102 face = np.asarray(face, np.int64)
103 s = np.zeros(c[0].shape, np.int64)
104 for fa in range(3):
105 k = [i for i in range(3) if i not in (axis, fa)][0]
106 s = np.where(face == fa, c[k], s)
107 var = np.floor(hash3(s // w, face, axis, 9) * 3).astype(np.int64) - 1
108 return np.where(s % w == 0, -1, var)
109 return f
110
111
112class Model:
113 def __init__(self, sx, sy, sz):
114 self.v = np.zeros((sx, sy, sz), np.uint8)
115
116 def _fill(self, lo, hi, fn, m):
117 sl = []
118 for a in range(3):
119 i0 = max(0, math.floor(lo[a]) - 1)
120 i1 = min(self.v.shape[a], math.ceil(hi[a]) + 1)
121 if i1 <= i0:
122 return
123 sl.append(slice(i0, i1))
124 X, Y, Z = [np.arange(s.start, s.stop) + 0.5 for s in sl]
125 mask = fn(X[:, None, None], Y[None, :, None], Z[None, None, :])
126 sub = self.v[sl[0], sl[1], sl[2]]
127 sub[np.broadcast_to(mask, sub.shape)] = m
128
129 def box(self, x0, y0, z0, x1, y1, z1, m):
130 def fn(X, Y, Z):
131 return (X >= x0) & (X <= x1) & (Y >= y0) & (Y <= y1) & (Z >= z0) & (Z <= z1)
132 self._fill((x0, y0, z0), (x1, y1, z1), fn, m)
133
134 def obox(self, cx, cy, cz, hx, hy, hz, yaw, m):
135 c, s = math.cos(yaw), math.sin(yaw)
136 R = math.hypot(hx, hy)
137
138 def fn(X, Y, Z):
139 dx = X - cx
140 dy = Y - cy
141 lx = dx * c + dy * s
142 ly = dy * c - dx * s
143 return (np.abs(lx) <= hx) & (np.abs(ly) <= hy) & (np.abs(Z - cz) <= hz)
144 self._fill((cx - R, cy - R, cz - hz), (cx + R, cy + R, cz + hz), fn, m)
145
146 def ellipsoid(self, cx, cy, cz, rx, ry, rz, m):
147 def fn(X, Y, Z):
148 return ((X - cx) / rx) ** 2 + ((Y - cy) / ry) ** 2 + ((Z - cz) / rz) ** 2 <= 1
149 self._fill((cx - rx, cy - ry, cz - rz), (cx + rx, cy + ry, cz + rz), fn, m)
150
151 def capsule(self, a, b, r, m):
152 a = np.asarray(a, float)
153 ab = np.asarray(b, float) - a
154 L2 = max(float(ab @ ab), 1e-12)
155
156 def fn(X, Y, Z):
157 px, py, pz = X - a[0], Y - a[1], Z - a[2]
158 t = np.clip((px * ab[0] + py * ab[1] + pz * ab[2]) / L2, 0, 1)
159 dx, dy, dz = px - t * ab[0], py - t * ab[1], pz - t * ab[2]
160 return dx * dx + dy * dy + dz * dz <= r * r
161 lo = np.minimum(a, a + ab) - r
162 hi = np.maximum(a, a + ab) + r
163 self._fill(lo, hi, fn, m)
164
165 def cylinder(self, a, b, r, m):
166 a = np.asarray(a, float)
167 ab = np.asarray(b, float) - a
168 L = float(np.linalg.norm(ab))
169 u = ab / max(L, 1e-12)
170
171 def fn(X, Y, Z):
172 px, py, pz = X - a[0], Y - a[1], Z - a[2]
173 along = px * u[0] + py * u[1] + pz * u[2]
174 d2 = px * px + py * py + pz * pz - along * along
175 return (along >= 0) & (along <= L) & (d2 <= r * r)
176 lo = np.minimum(a, a + ab) - r
177 hi = np.maximum(a, a + ab) + r
178 self._fill(lo, hi, fn, m)
179
180 def gable(self, x0, y0, x1, y1, z0, z1, axis, m, overhang=0):
181 o = overhang
182 if axis == 'x':
183 a0, a1, b0, b1, ca, cb = x0, x1, y0, y1, 0, 1
184 else:
185 a0, a1, b0, b1, ca, cb = y0, y1, x0, x1, 1, 0
186 bc = (b0 + b1) / 2
187 hw = (b1 - b0) / 2
188
189 def fn(X, Y, Z):
190 pos = (X, Y)
191 A = pos[ca]
192 B = pos[cb]
193 d = np.abs(B - bc) / hw
194 h = z0 + (z1 - z0) * (1 - np.minimum(d, 1))
195 return (A >= a0 - o) & (A <= a1 + o) & (d <= 1 + o / hw) & (Z >= z0) & (Z <= h)
196 self._fill((x0 - o, y0 - o, z0), (x1 + o, y1 + o, z1), fn, m)
197
198 def paint(self, fn, m):
199 ix, iy, iz = np.nonzero(self.v)
200 sel = np.broadcast_to(fn(ix + 0.5, iy + 0.5, iz + 0.5), ix.shape)
201 self.v[ix[sel], iy[sel], iz[sel]] = m
202
203
204def render(model, outline=True, edges=True):
205 v = model.v
206 sx, sy, sz = v.shape
207 W = sx + sy
208 H = int(math.ceil((sx + sy) / 2 + sz))
209 U, V = np.meshgrid(np.arange(W) - sy + 0.5, np.arange(H) - sz + 0.5)
210 bounds = np.stack([2 * sx - U, 2 * sy + U, 2 * (sz + V)])
211 face = np.argmin(bounds, axis=0).reshape(-1)
212 s0 = bounds.min(axis=0)
213 lo = np.maximum(np.maximum(-U, U), 2 * V)
214 idx = np.flatnonzero((s0 >= lo).reshape(-1))
215 P0 = np.stack([(s0 + U) / 2, (s0 - U) / 2, s0 / 2 - V], -1).reshape(-1, 3)
216 p = P0[idx]
217 f = face[idx]
218 dims = np.array(v.shape)
219 hit_mat = np.zeros(H * W, np.uint8)
220 hit_face = np.zeros(H * W, np.int64)
221 hit_cell = np.zeros((H * W, 3), np.int64)
222 for _ in range(4 * (sx + sy + sz) + 8):
223 if not idx.size:
224 break
225 c = np.floor(p - 1e-6).astype(np.int64)
226 inside = (c >= 0).all(1)
227 cc = np.clip(c, 0, dims - 1)
228 mt = v[cc[:, 0], cc[:, 1], cc[:, 2]]
229 occ = inside & (mt > 0)
230 hi_ = idx[occ]
231 hit_mat[hi_] = mt[occ]
232 hit_face[hi_] = f[occ]
233 hit_cell[hi_] = c[occ]
234 go = inside & ~occ
235 idx, p, c = idx[go], p[go], c[go]
236 d = p - c
237 t = d.min(1)
238 f = d.argmin(1)
239 p = p - t[:, None]
240
241 M = (hit_mat > 0).reshape(H, W)
242 mat_img = hit_mat.reshape(H, W)
243 face_img = hit_face.reshape(H, W)
244 cell_img = hit_cell.reshape(H, W, 3)
245 D = cell_img.sum(2)
246
247 Mr = np.zeros_like(M)
248 Mb = np.zeros_like(M)
249 Dr = np.zeros_like(D)
250 Db = np.zeros_like(D)
251 Mr[:, :-1] = M[:, 1:]
252 Dr[:, :-1] = D[:, 1:]
253 Mb[:-1, :] = M[1:, :]
254 Db[:-1, :] = D[1:, :]
255 edge = M & (~Mr | (np.abs(D - Dr) > 4) | ~Mb | (np.abs(D - Db) > 4))
256
257 shade = np.zeros((H, W), np.int64)
258 emis = np.zeros((H, W), bool)
259 glass = np.zeros((H, W), bool)
260 lens = np.zeros((H, W), np.int64)
261 rgb = np.zeros((H, W, 3))
262 mids = np.unique(mat_img[M])
263 for mid in mids:
264 ramp, pat, em = _MATS[mid]
265 sel = mat_img == mid
266 fa = face_img[sel]
267 L = len(ramp)
268 base = np.where(fa == 2, L - 2, np.where(fa == 1, L - 3, L - 4))
269 if pat is not None:
270 cl = cell_img[sel]
271 base = base + pat(cl[:, 0], cl[:, 1], cl[:, 2], fa)
272 shade[sel] = base
273 emis[sel] = em
274 glass[sel] = em and len(ramp) == len(P['window']) and bool(np.all(ramp == np.array(P['window'])))
275 lens[sel] = L
276 shade = shade - (edge if edges else 0)
277 for mid in mids:
278 ramp = _MATS[mid][0]
279 sel = mat_img == mid
280 idx_ = np.clip(shade[sel], 0, len(ramp) - 1)
281 rgb[sel] = ramp[idx_]
282
283 Hc, Wc = H + 2, W + 2
284 img = np.zeros((Hc, Wc, 4), np.uint8)
285 img[1:-1, 1:-1, :3] = np.round(rgb).astype(np.uint8)
286 img[1:-1, 1:-1, 3] = M * 255
287
288 if outline:
289 A = img[..., 3] > 0
290 col = img[..., :3].astype(float)
291 out = np.zeros_like(col)
292 got = np.zeros((Hc, Wc), bool)
293 for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
294 nA = np.roll(A, (dy, dx), (0, 1))
295 nC = np.roll(col, (dy, dx), (0, 1))
296 take = nA & ~A & ~got
297 out[take] = 0.35 * nC[take] + 0.65 * OUTLINE_RGB
298 got |= take
299 img[got, :3] = np.round(out[got]).astype(np.uint8)
300 img[got, 3] = 255
301
302 em_img = None
303 E = np.zeros((Hc, Wc), bool)
304 E[1:-1, 1:-1] = emis & M
305 ys, xs = np.nonzero(img[..., 3])
306 x0, x1 = max(int(xs.min()) - 1, 0), min(int(xs.max()) + 2, Wc)
307 y0, y1 = max(int(ys.min()) - 1, 0), min(int(ys.max()) + 2, Hc)
308 if E.any():
309 em = np.zeros_like(img)
310 em[E] = img[E]
311 em_img = Image.fromarray(em[y0:y1, x0:x1])
312 G = np.zeros((Hc, Wc), bool)
313 G[1:-1, 1:-1] = glass & M
314 img[G, :3] = np.round(img[G, :3] * 0.22 + np.array([34, 40, 52]) * 0.78).astype(np.uint8)
315 origin = (sy + 1 - x0, sz + 1 - y0)
316 return Image.fromarray(img[y0:y1, x0:x1]), em_img, origin
317
318
319def project(x, y, z, origin):
320 return origin[0] + (x - y), origin[1] + (x + y) / 2 - z
321
322
323def smoke_offset(px, py, origin):
324 return ((px - origin[0]) * 2, -(py - origin[1]) * 2)
325
326
327def save(name, img, origin, foot=(1, 1), smoke=(), cell=None, grid=None, emissive=None, group='misc'):
328 os.makedirs(GFX, exist_ok=True)
329 os.makedirs(MANIFEST, exist_ok=True)
330 img.save(os.path.join(GFX, name + '.png'))
331 if emissive is not None:
332 emissive.save(os.path.join(GFX, name + '_e.png'))
333 path = os.path.join(MANIFEST, group + '.json')
334 data = {}
335 if os.path.exists(path):
336 with open(path) as fh:
337 data = json.load(fh)
338 data[name] = {
339 'size': list(img.size),
340 'origin': [int(origin[0]), int(origin[1])],
341 'foot': list(foot),
342 'smoke': [list(s) for s in smoke],
343 'cell': list(cell) if cell is not None else None,
344 'grid': list(grid) if grid is not None else None,
345 'glow': emissive is not None,
346 }
347 with open(path, 'w') as fh:
348 json.dump(data, fh, indent=2)
349
350
351def atlas(frames_rows):
352 frames = [fr for row in frames_rows for fr in row]
353 L = max(o[0] for _, o in frames)
354 T = max(o[1] for _, o in frames)
355 R = max(img.size[0] - o[0] for img, o in frames)
356 B = max(img.size[1] - o[1] for img, o in frames)
357 cw, ch = L + R, T + B
358 cols = max(len(r) for r in frames_rows)
359 rows_n = len(frames_rows)
360 out = Image.new('RGBA', (cols * cw, rows_n * ch), (0, 0, 0, 0))
361 for j, row in enumerate(frames_rows):
362 for i, (img, o) in enumerate(row):
363 out.paste(img, (i * cw + L - o[0], j * ch + T - o[1]))
364 return out, (cw, ch), (cols, rows_n), (L, T)