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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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#!/usr/bin/env python3
"""pixelkit — shared helpers for drawing pixel art with Python (PIL + numpy).

Copy it into the project (cp -n <agent-web>/scripts/pixelkit.py tools/pixelkit.py)
and import it from drawing scripts:

    import sys; sys.path.insert(0, "tools")
    from pixelkit import *

    skin = ramp("#f48d6b", 8)             # 8 tones dark -> light, hue shifted
    s = Sprite(48, 48)
    body = s.ellipse_mask(24, 28, 14, 12)  # boolean mask of a shape
    s.shade(body, skin, light=(-1, -1))    # volume shading, light from top-left
    s.selout()                             # coloured outline from the inside colours
    s.contact_shadow(24, 41, 13, 3, "#1a102480")
    s.save("art/sprites/blob.png", preview=6)

Then check the PNG with the pixel_lint tool (Agent Web) and fix what it finds.
The project keeps its own copy: improve it there (new brushes, materials) so
the next drawing starts from a better kit.
"""
import math
import sys

import numpy as np
from PIL import Image

__all__ = ["hex2rgba", "rgba2hex", "ramp", "Sprite", "sheet", "luminance"]


# ---- colours ----

def hex2rgba(value):
    """'#rgb', '#rrggbb' or '#rrggbbaa' -> (r, g, b, a)."""
    if isinstance(value, (tuple, list)):
        return tuple(value) if len(value) == 4 else (*value, 255)
    s = value.strip().lstrip("#")
    if len(s) == 3:
        s = "".join(c * 2 for c in s)
    if len(s) not in (6, 8):
        raise ValueError(f"bad colour {value!r}")
    rgb = tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
    return (*rgb, int(s[6:8], 16) if len(s) == 8 else 255)


def rgba2hex(c):
    return "#" + "".join(f"{v:02x}" for v in (c[:3] if len(c) == 3 or c[3] == 255 else c))


def luminance(c):
    c = hex2rgba(c)
    return 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]


def _lin(c):
    v = c / 255
    return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4


def _srgb(v):
    c = v * 12.92 if v <= 0.0031308 else 1.055 * (max(v, 0) ** (1 / 2.4)) - 0.055
    return c * 255


def _oklab(rgb):
    r, g, b = (_lin(x) for x in rgb[:3])
    l = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b) ** (1 / 3)
    m = (0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b) ** (1 / 3)
    s = (0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b) ** (1 / 3)
    return (0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
            1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
            0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s)


def _from_oklab(L, a, b):
    l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
    m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
    s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3
    return (_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
            _srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
            _srgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s))


def _lch_to_rgb(L, C, h):
    def at(c):
        return _from_oklab(L, c * math.cos(math.radians(h)), c * math.sin(math.radians(h)))

    def ok(rgb):
        return all(-0.5 <= v <= 255.5 for v in rgb)

    rgb = at(C)
    if ok(rgb):
        return rgb
    lo, hi, best = 0.0, C, at(0)
    for _ in range(18):
        mid = (lo + hi) / 2
        t = at(mid)
        if ok(t):
            lo, best = mid, t
        else:
            hi = mid
    return best


def _toward(h, target, amount):
    d = (target - h + 540) % 360 - 180
    return target if abs(d) < amount else (h + math.copysign(amount, d)) % 360


def ramp(base, steps=7, hue_shift=1.0, dark=None, light=None):
    """Material ramp dark -> light around `base` (same algorithm as the
    pixel_ramp tool): even OKLab lightness steps, shadows cool, lights warm."""
    rgb = hex2rgba(base)[:3]
    L0, a0, b0 = _oklab(rgb)
    C0 = math.hypot(a0, b0)
    h0 = (math.degrees(math.atan2(b0, a0)) + 360) % 360
    n = max(3, min(12, int(steps)))
    lmin = max(0.12, min(L0 - 0.18, 0.24)) if dark is None else dark
    lmax = min(0.97, max(L0 + 0.18, 0.9)) if light is None else light
    k = max(1, min(n - 2, round((L0 - lmin) / max(0.01, lmax - lmin) * (n - 1))))
    grey = C0 < 0.03
    out = []
    for i in range(n):
        if i == k:
            out.append(rgba2hex((*rgb, 255)))
            continue
        if i < k:
            t = -(k - i) / k
            L = L0 + (lmin - L0) * (-t)
        else:
            t = (i - k) / (n - 1 - k)
            L = L0 + (lmax - L0) * t
        a = abs(t)
        if grey:
            h = 285 if t < 0 else 90
            C = C0 + 0.025 * hue_shift * a
        elif t < 0:
            h = _toward(h0, 285, 40 * hue_shift * a)
            C = C0 * (1 - 0.3 * a) * (0.85 if a > 0.75 else 1)
        else:
            h = _toward(h0, 95, 30 * hue_shift * a)
            C = C0 * (1 - 0.6 * a ** 1.3)
        r, g, b = _lch_to_rgb(L, max(0.0, C), h)
        out.append(rgba2hex((round(max(0, min(255, r))), round(max(0, min(255, g))), round(max(0, min(255, b))), 255)))
    return out


# ---- sprite ----

BAYER4 = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]]) / 16.0


class Sprite:
    """RGBA pixel canvas. Coordinates are (x, y) from the top-left."""

    def __init__(self, w, h, data=None):
        self.w, self.h = w, h
        self.a = np.zeros((h, w, 4), dtype=np.uint8) if data is None else data

    @classmethod
    def load(cls, path):
        im = np.array(Image.open(path).convert("RGBA"))
        return cls(im.shape[1], im.shape[0], im)

    # pixels
    def px(self, x, y, c):
        if 0 <= x < self.w and 0 <= y < self.h:
            self.a[y, x] = hex2rgba(c)

    def px_if_empty(self, x, y, c):
        if 0 <= x < self.w and 0 <= y < self.h and self.a[y, x, 3] == 0:
            self.a[y, x] = hex2rgba(c)

    def rows(self, x, y, rows, legend):
        """Hand-drawn block: rows of characters, legend {'a': '#hex'}; '.' skips."""
        for j, row in enumerate(rows):
            for i, ch in enumerate(row):
                if ch in legend:
                    self.px(x + i, y + j, legend[ch])

    def get(self, x, y):
        return rgba2hex(tuple(int(v) for v in self.a[y, x]))

    def opaque(self):
        return self.a[:, :, 3] > 0

    # shapes -> masks (combine with | & ~), then fill or shade them
    def ellipse_mask(self, cx, cy, rx, ry):
        yy, xx = np.mgrid[0:self.h, 0:self.w]
        # Pixel centres are at +0.5: cx=16 is the line between pixels 15 and 16.
        return ((xx + 0.5 - cx) / max(rx, 0.5)) ** 2 + ((yy + 0.5 - cy) / max(ry, 0.5)) ** 2 <= 1.0

    def rect_mask(self, x, y, w, h):
        m = np.zeros((self.h, self.w), dtype=bool)
        m[max(0, y):max(0, y + h), max(0, x):max(0, x + w)] = True
        return m

    def poly_mask(self, points):
        from PIL import ImageDraw
        im = Image.new("1", (self.w, self.h), 0)
        ImageDraw.Draw(im).polygon([tuple(p) for p in points], fill=1, outline=1)
        return np.array(im, dtype=bool)

    def fill(self, mask, c):
        self.a[mask] = hex2rgba(c)

    def line(self, x0, y0, x1, y1, c):
        dx, dy = abs(x1 - x0), -abs(y1 - y0)
        sx, sy = (1 if x0 < x1 else -1), (1 if y0 < y1 else -1)
        err = dx + dy
        while True:
            self.px(x0, y0, c)
            if x0 == x1 and y0 == y1:
                break
            e2 = 2 * err
            if e2 >= dy:
                err += dy
                x0 += sx
            if e2 <= dx:
                err += dx
                y0 += sy

    # volume
    def shade(self, mask, tones, light=(-1.0, -1.0), height=1.0, ambient=0.15, dither=False, outline=True):
        """Shade a shape as a soft 3D volume: normals from the distance to the
        mask edge, Lambert light from `light` (x, y; default top-left), mapped
        onto `tones` (dark -> light). outline=True keeps tones[0] for the rim."""
        mask = np.asarray(mask, dtype=bool)
        if not mask.any():
            return
        dist = _distance(mask)
        r = dist / max(1.0, dist.max())
        # Sphere-like height profile: steep at the rim, flat on top.
        z = np.sqrt(np.clip(1 - (1 - r) ** 2, 0, 1)) * height * dist.max()
        gy, gx = np.gradient(z)
        nx, ny, nz = -gx, -gy, np.ones_like(z)
        norm = np.sqrt(nx ** 2 + ny ** 2 + nz ** 2)
        lx, ly = light
        lz = 0.9
        ln = math.sqrt(lx * lx + ly * ly + lz * lz)
        lam = (nx * lx + ny * ly + nz * lz) / (norm * ln)
        # Spread the lit range over the whole ramp (every tone gets used).
        lo, hi = np.percentile(lam[mask], 2), np.percentile(lam[mask], 98)
        v = np.clip((lam - lo) / max(1e-6, hi - lo), 0, 1)
        v = ambient + (1 - ambient) * v
        inner = tones[1:] if outline and len(tones) >= 4 else tones
        idx = v * (len(inner) - 1)
        if dither:
            yy, xx = np.mgrid[0:self.h, 0:self.w]
            frac = idx - np.floor(idx)
            idx = np.floor(idx) + (frac > BAYER4[yy % 4, xx % 4])
        else:
            idx = np.round(idx)
        idx = np.clip(idx, 0, len(inner) - 1).astype(int)
        cols = np.array([hex2rgba(t) for t in inner], dtype=np.uint8)
        self.a[mask] = cols[idx[mask]]
        if outline and len(tones) >= 4:
            edge = mask & ~_erode(mask)
            self.a[edge] = hex2rgba(tones[0])

    def highlight(self, x, y, tones, size=1):
        """Small specular glint: brightest tone with the next one around it."""
        self.px(x, y, tones[-1])
        if size > 1:
            for dx, dy in ((1, 0), (0, 1)):
                self.px(x + dx, y + dy, tones[-2])

    # outlines and light
    def outline(self, c, corners=False):
        """1px outline outside the art."""
        op = self.opaque()
        grow = _dilate(op, corners) & ~op
        self.a[grow] = hex2rgba(c)

    def selout(self, factor_lit=0.72, factor_dark=0.5, tint="#1a1030"):
        """Recolour the silhouette with darker shades of the colour just inside
        it (lit top/left side less dark): a coloured, selective outline."""
        op = self.opaque()
        edge = op & ~_erode(op)
        tint = np.array(hex2rgba(tint)[:3], dtype=float)
        src = self.a.copy()
        for y, x in zip(*np.nonzero(edge)):
            inside = [src[y + dy, x + dx] for dy in (-1, 0, 1) for dx in (-1, 0, 1)
                      if (dx or dy) and 0 <= y + dy < self.h and 0 <= x + dx < self.w and op[y + dy, x + dx] and not edge[y + dy, x + dx]]
            base = np.array(inside[0][:3] if inside else src[y, x][:3], dtype=float)
            if inside:
                base = np.mean([c[:3] for c in inside], axis=0)
            lit = (y == 0 or not op[y - 1, x]) or (x == 0 or not op[y, x - 1])
            f = factor_lit if lit else factor_dark
            col = base * f + tint * (1 - f) * 0.6
            self.a[y, x] = (*np.clip(col, 0, 255).astype(np.uint8), 255)

    def contact_shadow(self, cx, cy, rx, ry, c="#1a102470"):
        """Translucent ground shadow under the art (drawn behind it)."""
        m = self.ellipse_mask(cx, cy, rx, ry) & ~self.opaque()
        self.a[m] = hex2rgba(c)

    def ao(self, casters, target, depth=3, tones=None, darken=0.75):
        """Darken `target` (mask) near `casters` (mask): contact shadow at the
        foot of walls and objects, strongest at the contact."""
        d = np.full((self.h, self.w), 99, dtype=int)
        cur = np.asarray(casters, dtype=bool)
        for k in range(1, depth + 1):
            cur = _dilate(cur, True)
            d[(d == 99) & cur] = k
        for k in range(1, depth + 1):
            m = (d == k) & np.asarray(target, dtype=bool)
            f = darken ** ((depth - k + 1) / depth * 1.5)
            self.a[m, :3] = (self.a[m, :3] * f).astype(np.uint8)

    def clean_orphans(self):
        """Lone pixels whose 4 neighbours share one other colour take it."""
        src = self.a.copy()
        for y in range(1, self.h - 1):
            for x in range(1, self.w - 1):
                n = [tuple(src[y, x - 1]), tuple(src[y, x + 1]), tuple(src[y - 1, x]), tuple(src[y + 1, x])]
                if all(c == n[0] for c in n) and n[0] != tuple(src[y, x]):
                    self.a[y, x] = n[0]

    def colors(self):
        flat = self.a.reshape(-1, 4)
        flat = flat[flat[:, 3] > 0]
        return sorted({rgba2hex(tuple(int(v) for v in c)) for c in flat}, key=luminance)

    # output
    def image(self, scale=1):
        im = Image.fromarray(self.a, "RGBA")
        return im if scale == 1 else im.resize((self.w * scale, self.h * scale), Image.NEAREST)

    def save(self, path, preview=0):
        """Save the native PNG (for the game and pixel_lint) and, with
        preview=N, an N-times enlarged copy next to it (<name>_xN.png)."""
        import os
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        self.image().save(path)
        if preview and preview > 1:
            root, ext = os.path.splitext(path)
            self.image(preview).save(f"{root}_x{preview}{ext}")
        return path


def sheet(frames, cols=None):
    """Frames (Sprites of one size) side by side, `cols` per row."""
    cols = cols or len(frames)
    w, h = frames[0].w, frames[0].h
    rows = math.ceil(len(frames) / cols)
    out = Sprite(w * cols, h * rows)
    for i, f in enumerate(frames):
        x, y = (i % cols) * w, (i // cols) * h
        out.a[y:y + h, x:x + w] = f.a
    return out


# ---- mask helpers ----

def _erode(m):
    m = np.asarray(m, dtype=bool)
    out = m.copy()
    out[1:, :] &= m[:-1, :]
    out[:-1, :] &= m[1:, :]
    out[:, 1:] &= m[:, :-1]
    out[:, :-1] &= m[:, 1:]
    out[0, :] = out[-1, :] = False
    out[:, 0] = out[:, -1] = False
    return out & m


def _dilate(m, corners=False):
    m = np.asarray(m, dtype=bool)
    out = m.copy()
    out[1:, :] |= m[:-1, :]
    out[:-1, :] |= m[1:, :]
    out[:, 1:] |= m[:, :-1]
    out[:, :-1] |= m[:, 1:]
    if corners:
        out[1:, 1:] |= m[:-1, :-1]
        out[1:, :-1] |= m[:-1, 1:]
        out[:-1, 1:] |= m[1:, :-1]
        out[:-1, :-1] |= m[1:, 1:]
    return out


def _distance(m):
    """Distance (in pixels, 4-connected) from each mask pixel to the outside."""
    m = np.asarray(m, dtype=bool)
    d = np.zeros(m.shape, dtype=float)
    cur = m.copy()
    k = 0
    while cur.any():
        k += 1
        d[cur] = k
        cur = _erode(cur)
    return d


if __name__ == "__main__":
    if "--demo" in sys.argv:
        s = Sprite(32, 32)
        green = ramp("#3e8948", 7)
        body = s.ellipse_mask(16, 18, 12, 10)
        s.shade(body, green)
        s.highlight(10, 12, green, 2)
        s.contact_shadow(16, 28, 11, 2)
        s.save("/tmp/pixelkit_demo.png", preview=8)
        print("ramp", green)
        print("colours", len(s.colors()), "-> /tmp/pixelkit_demo.png")
    else:
        print(__doc__)
        print("Functions:", ", ".join(__all__))
        print("Sprite methods:", ", ".join(m for m in dir(Sprite) if not m.startswith("_")))