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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
"""Fresh deterministic symbolic renderer for ``clevr_world_v1`` scenes.

This is deliberately a structured renderer, not an image editor.  It projects
the official scene coordinates onto a clean canvas and draws simple
attribute-complete object glyphs: fill encodes color, geometry encodes shape,
extent encodes size, and outline/highlight encodes material.  A hidden object
is replaced by a fixed position-only patch, so completion worlds that differ in
that object's hidden attributes render byte-identically.
"""

from __future__ import annotations

import io
from collections.abc import Mapping, Sequence
from typing import Any

from ..sources.base import World
from ..sources.world_ops import hidden_nodes
from .base import (
    RenderedAssets,
    RendererFamily,
    RendererKind,
    RenderError,
    _encode_uint32_png,
    build_render_manifest,
    build_text_manifest,
    validate_rendered_assets,
)

_NAME = "clevr_renderer"
_VERSION = "1"
_KIND: RendererKind = "clevr"
_MIN_WIDTH = 240
_MIN_HEIGHT = 160

_TRAIN_FAMILY = RendererFamily(
    name="clevr_train_v1",
    kind=_KIND,
    font_name="DejaVu Sans",
    palette={
        "background": "#E9EEF5",
        "ground": "#CCD5E1",
        "outline": "#202733",
        "metal": "#F8FAFC",
        "redact": "#111827",
        "gray": "#777F8C",
        "red": "#D64545",
        "blue": "#3F6FD8",
        "green": "#39A66A",
        "brown": "#93643D",
        "purple": "#8654B5",
        "cyan": "#32AFC4",
        "yellow": "#D9B62E",
    },
    layout={"source_width": 480, "source_height": 320, "horizon": 0.78},
)

_HELDOUT_FAMILY = RendererFamily(
    name="clevr_heldout_v1",
    kind=_KIND,
    font_name="DejaVu Serif",
    palette={
        "background": "#FFF8EA",
        "ground": "#E8D8BC",
        "outline": "#3B2F2F",
        "metal": "#FFFDF7",
        "redact": "#291F1A",
        "gray": "#626B73",
        "red": "#B52F57",
        "blue": "#225E9F",
        "green": "#1F8860",
        "brown": "#7B4E35",
        "purple": "#714099",
        "cyan": "#18899A",
        "yellow": "#C69516",
    },
    layout={"source_width": 480, "source_height": 320, "horizon": 0.74},
)

CLEVR_FAMILIES: dict[str, RendererFamily] = {
    _TRAIN_FAMILY.name: _TRAIN_FAMILY,
    _HELDOUT_FAMILY.name: _HELDOUT_FAMILY,
}


class _Canvas:
    def __init__(self, width: int, height: int, family: RendererFamily) -> None:
        import numpy as np
        from PIL import Image, ImageDraw

        self.width = width
        self.height = height
        self.family = family
        self.image = Image.new("RGBA", (width, height), family.palette["background"])
        self.owners = Image.new("I", (width, height), 0)
        self.draw = ImageDraw.Draw(self.image)
        self.owner_draw = ImageDraw.Draw(self.owners)
        self.owner_ids: list[str] = []
        self.owner_index: dict[str, int] = {}
        self._np = np

    def reserve(self, node_id: str) -> None:
        self._owner(node_id)

    def _owner(self, node_id: str) -> int:
        value = self.owner_index.get(node_id)
        if value is None:
            self.owner_ids.append(node_id)
            value = len(self.owner_ids)
            self.owner_index[node_id] = value
        return value

    def polygon(
        self,
        node_id: str,
        points: Sequence[tuple[float, float]],
        *,
        fill: str,
        outline: str,
        width: int,
    ) -> None:
        owner = self._owner(node_id)
        self.draw.polygon(points, fill=fill, outline=outline)
        if width > 1:
            self.draw.line([*points, points[0]], fill=outline, width=width, joint="curve")
        self.owner_draw.polygon(points, fill=owner)

    def ellipse(
        self,
        node_id: str,
        box: tuple[float, float, float, float],
        *,
        fill: str,
        outline: str,
        width: int,
    ) -> None:
        owner = self._owner(node_id)
        self.draw.ellipse(box, fill=fill, outline=outline, width=width)
        self.owner_draw.ellipse(box, fill=owner)

    def rectangle(
        self,
        node_id: str,
        box: tuple[float, float, float, float],
        *,
        fill: str,
        outline: str,
        width: int,
    ) -> None:
        owner = self._owner(node_id)
        self.draw.rounded_rectangle(
            box,
            radius=max(2, int((box[2] - box[0]) * 0.12)),
            fill=fill,
            outline=outline,
            width=width,
        )
        self.owner_draw.rounded_rectangle(
            box,
            radius=max(2, int((box[2] - box[0]) * 0.12)),
            fill=owner,
        )

    def highlight(
        self,
        node_id: str,
        points: Sequence[tuple[float, float]],
        *,
        fill: str,
        width: int,
    ) -> None:
        owner = self._owner(node_id)
        self.draw.line(points, fill=fill, width=width)
        self.owner_draw.line(points, fill=owner, width=max(1, width))

    def redact(self, x: float, y: float) -> None:
        radius = max(11, int(min(self.width, self.height) * 0.055))
        box = (x - radius, y - radius, x + radius, y + radius)
        self.draw.rounded_rectangle(
            box,
            radius=max(3, radius // 4),
            fill=self.family.palette["redact"],
        )
        self.draw.line(
            (x - radius * 0.6, y, x + radius * 0.6, y),
            fill="#FFFFFF",
            width=max(2, radius // 7),
        )
        # Redaction pixels intentionally belong to background, never the hidden node.
        self.owner_draw.rounded_rectangle(box, radius=max(3, radius // 4), fill=0)

    def finish(self) -> tuple[bytes, bytes, dict[str, int]]:
        owner_array = self._np.asarray(self.owners, dtype="<u4")
        rgba = io.BytesIO()
        self.image.save(rgba, format="PNG", compress_level=9, optimize=False)
        counts = {
            node_id: int(self._np.count_nonzero(owner_array == index))
            for node_id, index in self.owner_index.items()
        }
        return rgba.getvalue(), _encode_uint32_png(owner_array), counts


class ClevrRenderer:
    """Render normalized CLEVR scene objects with semantic ownership."""

    name = _NAME
    version = _VERSION
    kind = _KIND

    def render(
        self,
        world: World,
        *,
        renderer_id: str,
        seed: int,
        width: int,
        height: int,
        family: RendererFamily | None = None,
    ) -> RenderedAssets:
        if world.get("world_schema") != "clevr_world_v1":
            raise RenderError(
                f"CLEVR renderer expects clevr_world_v1, got {world.get('world_schema')!r}"
            )
        family = family or _TRAIN_FAMILY
        if family.kind != self.kind:
            raise RenderError(
                f"renderer family {family.name!r} has kind {family.kind!r}, expected {self.kind!r}"
            )
        if renderer_id != family.name:
            raise RenderError(f"renderer_id {renderer_id!r} does not match family {family.name!r}")
        if width < _MIN_WIDTH or height < _MIN_HEIGHT:
            raise RenderError(
                f"CLEVR canvas must be at least {_MIN_WIDTH}x{_MIN_HEIGHT}, got {width}x{height}"
            )
        objects = _objects(world)
        hidden = hidden_nodes(world)
        canvas = _Canvas(width, height, family)
        horizon = int(height * float(family.layout.get("horizon", 0.78)))
        canvas.draw.rectangle(
            (0, horizon, width, height),
            fill=family.palette["ground"],
        )

        visible = tuple(sorted(str(obj["id"]) for obj in objects if obj["id"] not in hidden))
        for node_id in visible:
            canvas.reserve(node_id)
        for obj in sorted(objects, key=_draw_order, reverse=True):
            x, y = _position(obj, width, height, family)
            node_id = str(obj["id"])
            if node_id in hidden:
                canvas.redact(x, y)
            else:
                _draw_object(canvas, obj, x=x, y=y, family=family)
        rgba_png, node_map_png, counts = canvas.finish()
        manifest = build_render_manifest(
            renderer_id=renderer_id,
            renderer_name=self.name,
            renderer_version=self.version,
            family=family,
            world=world,
            seed=seed,
            width=width,
            height=height,
            rgba_png=rgba_png,
            node_map_png=node_map_png,
            visible_node_ids=visible,
            owner_ids=canvas.owner_ids,
            node_pixel_counts=counts,
            glyph_count=0,
            backend="pillow",
            backend_version=_pillow_version(),
        )
        manifest["scene_object_count"] = len(objects)
        assets = RenderedAssets(
            rgba_png=rgba_png,
            node_map_png=node_map_png,
            render_manifest=manifest,
            text_manifest=build_text_manifest((), world=world),
        )
        validate_rendered_assets(assets)
        return assets


def _objects(world: World) -> tuple[Mapping[str, Any], ...]:
    raw = world.get("objects")
    if not isinstance(raw, list):
        raise RenderError("CLEVR world objects is not an array")
    output: list[Mapping[str, Any]] = []
    seen: set[str] = set()
    for obj in raw:
        if not isinstance(obj, Mapping) or not obj.get("id"):
            raise RenderError("CLEVR object is missing an id")
        node_id = str(obj["id"])
        if node_id in seen:
            raise RenderError(f"duplicate CLEVR object id {node_id!r}")
        seen.add(node_id)
        output.append(obj)
    return tuple(output)


def _draw_order(obj: Mapping[str, Any]) -> tuple[float, str]:
    coords = obj.get("pixel_coords")
    depth = (
        float(coords[2])
        if isinstance(coords, list) and len(coords) >= 3 and isinstance(coords[2], (int, float))
        else 0.0
    )
    return depth, str(obj.get("id", ""))


def _position(
    obj: Mapping[str, Any],
    width: int,
    height: int,
    family: RendererFamily,
) -> tuple[float, float]:
    coords = obj.get("pixel_coords")
    if (
        isinstance(coords, list)
        and len(coords) >= 2
        and all(isinstance(value, (int, float)) for value in coords[:2])
    ):
        source_width = float(family.layout.get("source_width", 480))
        source_height = float(family.layout.get("source_height", 320))
        x = float(coords[0]) / source_width * width
        y = float(coords[1]) / source_height * height
    else:
        coords = obj.get("3d_coords")
        if (
            not isinstance(coords, list)
            or len(coords) < 2
            or not all(isinstance(value, (int, float)) for value in coords[:2])
        ):
            raise RenderError(f"CLEVR object {obj.get('id')!r} has no usable coordinates")
        x = (float(coords[0]) + 3.0) / 6.0 * width
        y = (3.0 - float(coords[1])) / 6.0 * height
    margin = max(14, int(min(width, height) * 0.06))
    return (
        min(width - margin, max(margin, x)),
        min(height - margin, max(margin, y)),
    )


def _draw_object(
    canvas: _Canvas,
    obj: Mapping[str, Any],
    *,
    x: float,
    y: float,
    family: RendererFamily,
) -> None:
    node_id = str(obj["id"])
    color = obj.get("color")
    shape = obj.get("shape")
    size = obj.get("size")
    material = obj.get("material")
    if not isinstance(color, str) or color not in family.palette:
        raise RenderError(f"CLEVR object {node_id!r} has invalid color {color!r}")
    if shape not in {"cube", "sphere", "cylinder"}:
        raise RenderError(f"CLEVR object {node_id!r} has invalid shape {shape!r}")
    if size not in {"small", "large"}:
        raise RenderError(f"CLEVR object {node_id!r} has invalid size {size!r}")
    if material not in {"rubber", "metal"}:
        raise RenderError(f"CLEVR object {node_id!r} has invalid material {material!r}")
    radius = max(10, int(min(canvas.width, canvas.height) * (0.052 if size == "small" else 0.078)))
    fill = family.palette[color]
    outline = family.palette["metal"] if material == "metal" else family.palette["outline"]
    width = max(2, radius // 7) if material == "metal" else max(1, radius // 11)
    if shape == "sphere":
        canvas.ellipse(
            node_id,
            (x - radius, y - radius, x + radius, y + radius),
            fill=fill,
            outline=outline,
            width=width,
        )
    elif shape == "cube":
        skew = radius * 0.38
        points = (
            (x - radius, y - radius + skew),
            (x - skew, y - radius),
            (x + radius, y - radius + skew),
            (x + radius - skew, y + radius),
            (x - radius, y + radius - skew),
        )
        canvas.polygon(node_id, points, fill=fill, outline=outline, width=width)
    else:
        canvas.rectangle(
            node_id,
            (x - radius * 0.82, y - radius, x + radius * 0.82, y + radius),
            fill=fill,
            outline=outline,
            width=width,
        )
        canvas.ellipse(
            node_id,
            (x - radius * 0.82, y - radius, x + radius * 0.82, y - radius * 0.45),
            fill=fill,
            outline=outline,
            width=width,
        )
    if material == "metal":
        canvas.highlight(
            node_id,
            ((x - radius * 0.45, y - radius * 0.45), (x + radius * 0.15, y - radius * 0.12)),
            fill=family.palette["metal"],
            width=max(2, radius // 6),
        )


def _pillow_version() -> str:
    import PIL

    return PIL.__version__


__all__ = ["CLEVR_FAMILIES", "ClevrRenderer"]