Skip to content

anbeime/skill / skills/img2threejs/img2threejs

img2threejs

Verified

Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.

FileKindSize
.github/FUNDING.ymlconfig94 B
.github/ISSUE_TEMPLATE/bug_report.ymlconfig2.3 KB
.github/ISSUE_TEMPLATE/contribution_intent.ymlconfig1.8 KB
.github/ISSUE_TEMPLATE/feature_request.ymlconfig1.4 KB
.github/pull_request_template.mdmarkdown1.1 KB
.github/release.ymlconfig471 B
.github/workflows/beta-release.ymlconfig1.9 KB
.github/workflows/ci.ymlconfig349 B
.github/workflows/issue-triage.ymlconfig783 B
.github/workflows/pr-issue-close-policy.ymlconfig279 B
.github/workflows/release.ymlconfig625 B
.gitignoreother2.4 KB
CHANGELOG.mdmarkdown33.1 KB
CLAUDE.mdmarkdown2.8 KB
CONTRIBUTING.mdmarkdown4.7 KB
LAB-FINDINGS.mdmarkdown5.7 KB
LICENSEother11.1 KB
README.mdmarkdown38.9 KB
ROADMAP.mdmarkdown16.3 KB
SKILL.mdskill md30.8 KB
assets/logo.svgother2.0 KB
assets/sponsors/atlas-cloud-logomark-black.svgother595 B
assets/sponsors/atlas-cloud-logomark-white.svgother595 B
assets/sponsors/hyper3d-logomark-black.pngbinary1.1 KB
assets/sponsors/hyper3d-logomark-white.pngbinary1.2 KB
assets/sponsors/tripo-logomark-black.svgother1002 B
assets/sponsors/tripo-logomark-white.svgother1002 B
docs/ARCHITECTURE.mdmarkdown14.0 KB
docs/GLB_ANIMATED_CHARACTER_PROMPT.mdmarkdown13.1 KB
docs/GLB_CHARACTER_ANIMATION_PROMPT.mdmarkdown14.6 KB
docs/GLB_CHARACTER_POLISH_PROMPT.mdmarkdown10.6 KB
docs/GLB_CHARACTER_PROMPT.mdmarkdown19.1 KB
docs/HAIR_PIPELINE.mdmarkdown10.5 KB
docs/RESEARCH_TRELLIS2_TO_IMG2THREEJS.mdmarkdown35.4 KB
docs/STAGE_R_BACKLOG.mdmarkdown18.0 KB
docs/STAGE_R_TEST_PLAN.mdmarkdown14.0 KB
docs/TOKEN_COST.mdmarkdown2.5 KB
docs/UPGRADE_PLAN.mdmarkdown30.4 KB
docs/cs2-anatomy/gloves.mdmarkdown11.6 KB
docs/cs2-anatomy/heavy.mdmarkdown13.8 KB
docs/cs2-anatomy/knives.mdmarkdown18.2 KB
docs/cs2-anatomy/pistols.mdmarkdown12.0 KB
docs/cs2-anatomy/rifles.mdmarkdown13.1 KB
docs/cs2-anatomy/smgs.mdmarkdown13.4 KB
docs/cs2-anatomy/snipers.mdmarkdown13.8 KB
docs/cs2/3D_Technical_Mapping.jsonconfig10.6 KB
docs/cs2/3D_Technical_Reference.mdmarkdown22.2 KB
docs/cs2/3D_Vocabulary_CS2.jsonconfig10.0 KB
docs/cs2/3D_Vocabulary_CS2_Dictionary.mdmarkdown26.6 KB
docs/cs2/distill.mdmarkdown9.9 KB
docs/cs2/review-gates.mdmarkdown2.5 KB
docs/integrations/reference_fidelity_tooling.mdmarkdown6.2 KB
docs/issue-triage.mdmarkdown1.8 KB
docs/materials/IMAGE_MATERIAL_ANALYSIS.mdmarkdown5.0 KB
docs/materials/README.mdmarkdown5.2 KB
docs/materials/THREEJS_MATERIAL_REFERENCE.mdmarkdown11.4 KB
docs/materials/material-reference.jsonconfig55.0 KB
docs/pipelines/character-rigging-animation-1.5.2.mdmarkdown22.3 KB
docs/raw/.keepother0 B
docs/raw/img2threejs-skill-dataset.jsonconfig107.3 KB
docs/specs/render-profile.v2.example.jsonconfig2.6 KB
docs/specs/render-profile.v2.schema.jsonconfig3.8 KB
docs/specs/vocabulary/README.mdmarkdown4.4 KB
docs/specs/vocabulary/core_3d.jsonlother13.2 KB
docs/specs/vocabulary/core_3d_reconstruction.jsonlother56.1 KB
docs/specs/vocabulary/cs2.jsonlother7.1 KB
docs/specs/vocabulary/cs2_reconstruction.jsonlother85.7 KB
docs/standard-prompts/README.mdmarkdown2.2 KB
docs/standard-prompts/build.mdmarkdown5.2 KB
docs/standard-prompts/glb-force-measured.mdmarkdown8.6 KB
docs/standard-prompts/polish.mdmarkdown2.7 KB
docs/standard-prompts/vfx.mdmarkdown5.7 KB
forge/_shared/artifact_cache.pyscript1.7 KB
forge/_shared/chirality.pyscript12.1 KB
forge/_shared/color_metrics.pyscript3.6 KB
forge/_shared/feature_acceptance_policy.pyscript4.2 KB
forge/_shared/image_hash.pyscript4.0 KB
forge/_shared/jpeg.pyscript16.0 KB
forge/_shared/material_physics.pyscript12.2 KB
forge/_shared/pipeline_routing.pyscript7.0 KB
forge/_shared/scalp_field.pyscript14.3 KB
forge/_shared/sdf_primitives.pyscript8.3 KB
forge/_shared/spec_search.pyscript61.9 KB
forge/_shared/spec_search_profiles.jsonconfig1.4 KB
forge/_shared/status_banner.pyscript1.4 KB
forge/_shared/subdivision.pyscript10.5 KB
forge/_shared/vertex_paint.pyscript10.8 KB
forge/_shared/workflow_state.pyscript20.5 KB
forge/materials/__init__.pyscript355 B
forge/materials/compatibility.pyscript5.1 KB
forge/materials/reference.pyscript10.2 KB
forge/next.pyscript4.4 KB
forge/report.pyscript1.5 KB
forge/requirements.txtmanifest335 B
forge/stage1_intake/analyze_texture.pyscript12.1 KB
forge/stage1_intake/bind_detail_properties.pyscript4.6 KB
forge/stage1_intake/build_detail_inventory.pyscript13.0 KB
forge/stage1_intake/camera_fitting_math.pyscript5.5 KB
forge/stage1_intake/camera_fitting_solver.pyscript8.2 KB
forge/stage1_intake/camera_fitting_types.pyscript8.2 KB
forge/stage1_intake/camera_image_helpers.pyscript6.0 KB
forge/stage1_intake/check_intake_correctness.pyscript4.8 KB
forge/stage1_intake/check_reference_admission.pyscript7.6 KB
forge/stage1_intake/cs2_foundation.pyscript7.9 KB
forge/stage1_intake/cs2_manifest.pyscript10.5 KB
forge/stage1_intake/cs2_review_contract.pyscript1.7 KB
forge/stage1_intake/delight_albedo.pyscript14.2 KB
forge/stage1_intake/detect_cs2.pyscript9.7 KB
forge/stage1_intake/detect_reference_effects.pyscript8.9 KB
forge/stage1_intake/extract_cs2_textures.pyscript5.6 KB
forge/stage1_intake/extract_gradient_stops.pyscript5.8 KB
forge/stage1_intake/extract_hair_evidence.pyscript18.6 KB
forge/stage1_intake/extract_landmarks.pyscript16.0 KB
forge/stage1_intake/extract_part_color_recipe.pyscript20.8 KB
forge/stage1_intake/extract_pbr_evidence.pyscript32.5 KB
forge/stage1_intake/fetch_cs2_metadata.pyscript6.4 KB
forge/stage1_intake/label_glb_nodes.pyscript13.0 KB
forge/stage1_intake/locate_cs2_vpk.pyscript2.6 KB
forge/stage1_intake/material_region_analysis.pyscript9.8 KB
forge/stage1_intake/probe_glb.pyscript15.0 KB
forge/stage1_intake/probe_image.pyscript5.4 KB
forge/stage1_intake/run_vision_adapter.pyscript1.6 KB
forge/stage1_intake/search_specs.pyscript7.5 KB
forge/stage1_intake/semantic_decomposition.pyscript4.5 KB
forge/stage1_intake/solve_camera_pose.pyscript10.7 KB
forge/stage2_spec/apply_material_analysis.pyscript8.6 KB
forge/stage2_spec/cs2_adapters.pyscript3.0 KB
forge/stage2_spec/derive_geometry.pyscript4.3 KB
forge/stage2_spec/hair_profile.pyscript14.5 KB
forge/stage2_spec/humanoid_proportions.pyscript9.0 KB
forge/stage2_spec/new_pre_spec_assessment.pyscript12.1 KB
forge/stage2_spec/new_sculpt_spec.pyscript127.4 KB
forge/stage2_spec/validate_sculpt_spec.pyscript144.5 KB
forge/stage3_build/bake_projected_texture.pyscript8.8 KB
forge/stage3_build/decimate.pyscript10.4 KB
forge/stage3_build/generate_threejs_factory.pyscript207.6 KB
forge/stage3_build/module_cache.pyscript5.6 KB
forge/stage3_build/morph_targets.pyscript7.3 KB
forge/stage3_build/orchestrate_passes.pyscript27.6 KB
forge/stage3_build/uv_unwrap.pyscript24.7 KB
forge/stage3_build/visual_hull.pyscript16.4 KB
forge/stage4_review/_fit_divine_eye.pyscript2.6 KB
forge/stage4_review/append_review.pyscript20.4 KB
forge/stage4_review/attachment_anchor.pyscript16.2 KB
forge/stage4_review/calibrate_eye.pyscript5.4 KB
forge/stage4_review/check_part_coverage.pyscript13.1 KB
forge/stage4_review/compare_region_passes.pyscript7.6 KB
forge/stage4_review/correction_loop.pyscript10.2 KB
forge/stage4_review/cs2_review.pyscript8.7 KB
forge/stage4_review/diagnose_render.pyscript15.5 KB
forge/stage4_review/diagnose_render_multi_angle.pyscript5.6 KB
forge/stage4_review/divine_eye.pyscript21.0 KB
forge/stage4_review/fit_params.pyscript16.6 KB
forge/stage4_review/geometry_integrity.pyscript15.1 KB
forge/stage4_review/hair_gate.pyscript9.5 KB
forge/stage4_review/interior_difference.pyscript7.8 KB
forge/stage4_review/joint_loops.pyscript8.2 KB
forge/stage4_review/make_comparison_sheet.pyscript10.9 KB
forge/stage4_review/material_comparator.pyscript7.9 KB
forge/stage4_review/material_feedback.pyscript6.7 KB
forge/stage4_review/material_gate.pyscript5.8 KB
forge/stage4_review/material_views.pyscript7.5 KB
forge/stage4_review/mesh_reference_compare.pyscript16.2 KB
forge/stage4_review/multi_pass.pyscript3.1 KB
forge/stage4_review/objectness.pyscript5.4 KB
forge/stage4_review/pairwise_penetration.pyscript16.2 KB
forge/stage4_review/per_feature.pyscript6.8 KB
forge/stage4_review/render_bridge.pyscript24.1 KB
forge/stage4_review/scalp_exposure.pyscript11.5 KB
forge/stage4_review/self_intersection.pyscript26.3 KB
forge/stage4_review/swept_arc_gate.pyscript14.3 KB
forge/stage4_review/turntable_gate.pyscript17.6 KB
forge/stage4_review/validate_render_profile.pyscript8.9 KB
forge/stage4_review/vertex_region_gate.pyscript20.3 KB
forge/stage4_review/vlm_gate.pyscript8.8 KB
forge/stage5_rig/CONTRACT_1.5.2.mdmarkdown3.6 KB
forge/stage5_rig/NOTES.mdmarkdown8.5 KB
forge/stage5_rig/__init__.pyscript302 B
forge/stage5_rig/action_design.pyscript88.2 KB
forge/stage5_rig/clip_features.pyscript33.2 KB
forge/stage5_rig/emit_animation_runtime.pyscript17.7 KB
forge/stage5_rig/emit_rig.pyscript17.6 KB
forge/stage5_rig/geodesic_skinning.pyscript23.0 KB
forge/stage5_rig/glb_rig_reference.pyscript58.8 KB
forge/stage5_rig/mesh_parity.pyscript36.7 KB
forge/stage5_rig/rig_gates.pyscript78.7 KB
forge/stage5_rig/rig_spec.pyscript6.4 KB
forge/stage5_rig/skin_conditioning.pyscript25.9 KB
forge/stage5_rig/validate_rig_payload.pyscript8.8 KB
forge/state.pyscript3.5 KB
forge/tests/fixtures/implicit_character_torso_limb.jsonconfig1.4 KB
forge/tests/fixtures/knife_review_scene.jsonconfig1.3 KB
forge/tests/fixtures/stand_proud_hair_on_head.jsonconfig3.0 KB
forge/tests/fixtures/subdivision_cage.jsonconfig812 B
forge/tests/fixtures/visual_hull_two_views.jsonconfig2.6 KB
forge/tests/showcase_test_support.pyscript698 B
forge/tests/test_action_design.pyscript37.3 KB
forge/tests/test_albedo_color_space.pyscript4.6 KB
forge/tests/test_analyze_texture.pyscript6.0 KB
forge/tests/test_attachment_anchor.pyscript8.2 KB

forge/_shared/jpeg.py

View on GitHub
#!/usr/bin/env python3
"""Baseline JPEG decoder in pure Python 3.10+ standard library.

Why this exists: every image-consuming script fell back to macOS `sips` for any
format that is not PNG, so a JPEG reference — the most common kind of reference
photo there is — failed hard on Linux and Windows, and in CI. This decodes
baseline JPEG directly so the pipeline behaves the same on every platform.

Scope is deliberately narrow and honest about it:
  * baseline sequential DCT (SOF0) and extended sequential (SOF1), 8-bit
  * grayscale (1 component) and YCbCr (3 components), any sampling factors
  * restart intervals
  * progressive (SOF2), arithmetic coding, 12-bit and CMYK raise a clear
    UnsupportedJpeg so callers can fall back rather than silently mis-decode

Returns the same shape as read_png(): (width, height, [(r, g, b, a), ...]).
"""
from __future__ import annotations

import struct
from math import cos, pi

__all__ = ["decode_jpeg", "is_jpeg", "UnsupportedJpeg"]


class UnsupportedJpeg(ValueError):
    """A JPEG this decoder deliberately does not handle (e.g. progressive)."""


SOI, EOI, SOS, DQT, DHT, DRI = 0xD8, 0xD9, 0xDA, 0xDB, 0xC4, 0xDD
SOF_BASELINE, SOF_EXTENDED, SOF_PROGRESSIVE = 0xC0, 0xC1, 0xC2

ZIGZAG = (
    0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
    12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
)

# IDCT[u][x] = C(u)/2 * cos((2x+1) u pi / 16); applying it on rows then columns
# yields the 1/4 scaling of the 2-D inverse DCT.
_IDCT = [
    [((0.353553390593273762 if u == 0 else 0.5) * cos((2 * x + 1) * u * pi / 16))
     for x in range(8)]
    for u in range(8)
]


def is_jpeg(data: bytes) -> bool:
    return len(data) >= 2 and data[0] == 0xFF and data[1] == SOI


class _BitReader:
    """MSB-first bit reader over entropy-coded data, unstuffing 0xFF 0x00."""

    __slots__ = ("data", "pos", "bits", "nbits")

    def __init__(self, data: bytes, pos: int) -> None:
        self.data = data
        self.pos = pos
        self.bits = 0
        self.nbits = 0

    def _fill(self) -> None:
        data = self.data
        while self.nbits <= 24:
            if self.pos >= len(data):
                self.bits = (self.bits << 8) | 0
                self.nbits += 8
                continue
            byte = data[self.pos]
            self.pos += 1
            if byte == 0xFF:
                nxt = data[self.pos] if self.pos < len(data) else 0
                if nxt == 0x00:
                    self.pos += 1
                elif 0xD0 <= nxt <= 0xD7:
                    # restart marker: stop feeding, sync() consumes it
                    self.pos -= 1
                    self.bits = (self.bits << 8) | 0
                    self.nbits += 8
                    continue
                else:
                    self.pos -= 1
                    self.bits = (self.bits << 8) | 0
                    self.nbits += 8
                    continue
            self.bits = (self.bits << 8) | byte
            self.nbits += 8

    def receive(self, length: int) -> int:
        if length == 0:
            return 0
        if self.nbits < length:
            self._fill()
        self.nbits -= length
        value = (self.bits >> self.nbits) & ((1 << length) - 1)
        self.bits &= (1 << self.nbits) - 1
        return value

    def bit(self) -> int:
        return self.receive(1)

    def sync_restart(self) -> None:
        """Consume an RSTn marker and drop partial bits."""
        self.bits = 0
        self.nbits = 0
        data = self.data
        while self.pos + 1 < len(data):
            if data[self.pos] == 0xFF and 0xD0 <= data[self.pos + 1] <= 0xD7:
                self.pos += 2
                return
            self.pos += 1


def _build_huffman(counts: bytes, symbols: bytes) -> dict[tuple[int, int], int]:
    """Map (bit-length, code) -> symbol. Canonical JPEG Huffman assignment."""
    table: dict[tuple[int, int], int] = {}
    code = 0
    index = 0
    for length in range(1, 17):
        for _ in range(counts[length - 1]):
            table[(length, code)] = symbols[index]
            index += 1
            code += 1
        code <<= 1
    return table


def _decode_huffman(reader: _BitReader, table: dict[tuple[int, int], int]) -> int:
    code = 0
    for length in range(1, 17):
        code = (code << 1) | reader.bit()
        symbol = table.get((length, code))
        if symbol is not None:
            return symbol
    raise ValueError("invalid Huffman code in entropy-coded data")


def _extend(value: int, length: int) -> int:
    """Convert an unsigned magnitude to its signed JPEG value."""
    if length == 0:
        return 0
    return value if value >= (1 << (length - 1)) else value - (1 << length) + 1


def _idct_2d(block: list[float]) -> list[float]:
    """Separable 8x8 inverse DCT. DC-only blocks short-circuit."""
    if not any(block[1:]):
        flat = block[0] * 0.125
        return [flat] * 64

    tmp = [0.0] * 64
    for y in range(8):
        row = y * 8
        coeffs = block[row:row + 8]
        if not any(coeffs[1:]):
            value = coeffs[0] * 0.353553390593273762
            for x in range(8):
                tmp[row + x] = value
            continue
        for x in range(8):
            total = 0.0
            for u in range(8):
                c = coeffs[u]
                if c:
                    total += c * _IDCT[u][x]
            tmp[row + x] = total

    out = [0.0] * 64
    for x in range(8):
        column = [tmp[y * 8 + x] for y in range(8)]
        if not any(column[1:]):
            value = column[0] * 0.353553390593273762
            for y in range(8):
                out[y * 8 + x] = value
            continue
        for y in range(8):
            total = 0.0
            for v in range(8):
                c = column[v]
                if c:
                    total += c * _IDCT[v][y]
            out[y * 8 + x] = total
    return out


def _axis_map(out_len: int, samp: int, samp_max: int, plane_len: int) -> list[tuple[int, int, float]]:
    """Per-output-pixel (low, high, fraction) for triangular chroma upsampling.

    Subsampled chroma samples sit at the centre of the luma pixels they cover, so
    output pixel x maps to chroma coordinate (x + 0.5) * samp/samp_max - 0.5.
    Nearest-neighbour replication instead of this interpolation is visible as
    banding on sharp colour edges (~30/255 against a libjpeg reference)."""
    scale = samp / samp_max
    mapping: list[tuple[int, int, float]] = []
    last = max(0, plane_len - 1)
    for x in range(out_len):
        coord = (x + 0.5) * scale - 0.5
        low = int(coord // 1)
        frac = coord - low
        if low < 0:
            low, frac = 0, 0.0
        high = low + 1
        if low > last:
            low = last
        if high > last:
            high = last
        mapping.append((low, high, frac))
    return mapping


def _bilinear(plane: list[float], row0: int, row1: int, yfrac: float,
              xmap: tuple[int, int, float]) -> float:
    x0, x1, xfrac = xmap
    top = plane[row0 + x0] + (plane[row0 + x1] - plane[row0 + x0]) * xfrac
    if yfrac == 0.0 and row0 == row1:
        return top
    bottom = plane[row1 + x0] + (plane[row1 + x1] - plane[row1 + x0]) * xfrac
    return top + (bottom - top) * yfrac


def _clamp(value: float) -> int:
    if value <= 0.0:
        return 0
    if value >= 255.0:
        return 255
    return int(value + 0.5)


def decode_jpeg(data: bytes) -> tuple[int, int, list[tuple[int, int, int, int]]]:
    """Decode baseline JPEG bytes to (width, height, RGBA pixel list)."""
    if not is_jpeg(data):
        raise ValueError("not a JPEG file")

    quant: dict[int, list[int]] = {}
    huff_dc: dict[int, dict[tuple[int, int], int]] = {}
    huff_ac: dict[int, dict[tuple[int, int], int]] = {}
    components: list[dict] = []
    width = height = 0
    restart_interval = 0
    scan_start = -1
    scan_components: list[dict] = []

    pos = 2
    while pos + 3 < len(data):
        if data[pos] != 0xFF:
            pos += 1
            continue
        marker = data[pos + 1]
        pos += 2
        if marker in (0x01, EOI) or 0xD0 <= marker <= 0xD7:
            continue
        if pos + 2 > len(data):
            break
        seg_len = struct.unpack(">H", data[pos:pos + 2])[0]
        segment = data[pos + 2:pos + seg_len]

        if marker == SOF_PROGRESSIVE:
            raise UnsupportedJpeg("progressive JPEG is not supported by this decoder")
        if marker in (0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF):
            raise UnsupportedJpeg(f"unsupported JPEG coding mode (SOF marker 0x{marker:02X})")

        if marker in (SOF_BASELINE, SOF_EXTENDED):
            precision = segment[0]
            if precision != 8:
                raise UnsupportedJpeg(f"only 8-bit JPEG is supported, got {precision}-bit")
            height, width = struct.unpack(">HH", segment[1:5])
            count = segment[5]
            if count not in (1, 3):
                raise UnsupportedJpeg(
                    f"only grayscale and YCbCr JPEG are supported, got {count} components"
                )
            components = []
            for i in range(count):
                cid, sampling, tq = segment[6 + i * 3:9 + i * 3]
                components.append({
                    "id": cid,
                    "h": sampling >> 4,
                    "v": sampling & 15,
                    "tq": tq,
                })
        elif marker == DQT:
            cursor = 0
            while cursor < len(segment):
                pq_tq = segment[cursor]
                cursor += 1
                precision, table_id = pq_tq >> 4, pq_tq & 15
                values = [0] * 64
                for i in range(64):
                    if precision:
                        values[ZIGZAG[i]] = struct.unpack(">H", segment[cursor:cursor + 2])[0]
                        cursor += 2
                    else:
                        values[ZIGZAG[i]] = segment[cursor]
                        cursor += 1
                quant[table_id] = values
        elif marker == DHT:
            cursor = 0
            while cursor < len(segment):
                tc_th = segment[cursor]
                cursor += 1
                counts = segment[cursor:cursor + 16]
                cursor += 16
                total = sum(counts)
                symbols = segment[cursor:cursor + total]
                cursor += total
                table = _build_huffman(counts, symbols)
                if tc_th >> 4:
                    huff_ac[tc_th & 15] = table
                else:
                    huff_dc[tc_th & 15] = table
        elif marker == DRI:
            restart_interval = struct.unpack(">H", segment[0:2])[0]
        elif marker == SOS:
            count = segment[0]
            scan_components = []
            for i in range(count):
                cid, tables = segment[1 + i * 2:3 + i * 2]
                for comp in components:
                    if comp["id"] == cid:
                        comp["dc"] = tables >> 4
                        comp["ac"] = tables & 15
                        scan_components.append(comp)
                        break
            scan_start = pos + seg_len
            break
        pos += seg_len

    if not components or width == 0 or height == 0:
        raise ValueError("JPEG is missing a frame header")
    if scan_start < 0:
        raise ValueError("JPEG is missing scan data")

    h_max = max(c["h"] for c in components)
    v_max = max(c["v"] for c in components)
    mcu_w, mcu_h = 8 * h_max, 8 * v_max
    mcus_x = (width + mcu_w - 1) // mcu_w
    mcus_y = (height + mcu_h - 1) // mcu_h

    for comp in components:
        comp["bw"] = mcus_x * comp["h"]
        comp["bh"] = mcus_y * comp["v"]
        comp["plane"] = [0] * (comp["bw"] * 8 * comp["bh"] * 8)
        comp["stride"] = comp["bw"] * 8
        comp["pred"] = 0

    reader = _BitReader(data, scan_start)
    block = [0.0] * 64
    mcu_index = 0

    for my in range(mcus_y):
        for mx in range(mcus_x):
            if restart_interval and mcu_index and mcu_index % restart_interval == 0:
                reader.sync_restart()
                for comp in components:
                    comp["pred"] = 0
            mcu_index += 1

            for comp in scan_components:
                qt = quant.get(comp["tq"])
                if qt is None:
                    raise ValueError("JPEG references an undefined quantization table")
                dc_table = huff_dc.get(comp["dc"])
                ac_table = huff_ac.get(comp["ac"])
                if dc_table is None or ac_table is None:
                    raise ValueError("JPEG references an undefined Huffman table")

                for by in range(comp["v"]):
                    for bx in range(comp["h"]):
                        for i in range(64):
                            block[i] = 0.0

                        t = _decode_huffman(reader, dc_table)
                        diff = _extend(reader.receive(t), t) if t else 0
                        comp["pred"] += diff
                        block[0] = float(comp["pred"] * qt[0])

                        k = 1
                        while k < 64:
                            rs = _decode_huffman(reader, ac_table)
                            run, size = rs >> 4, rs & 15
                            if size == 0:
                                if run == 15:
                                    k += 16
                                    continue
                                break
                            k += run
                            if k > 63:
                                break
                            zz = ZIGZAG[k]
                            block[zz] = float(_extend(reader.receive(size), size) * qt[zz])
                            k += 1

                        pixels = _idct_2d(block)
                        px0 = (mx * comp["h"] + bx) * 8
                        py0 = (my * comp["v"] + by) * 8
                        stride = comp["stride"]
                        plane = comp["plane"]
                        for y in range(8):
                            row = (py0 + y) * stride + px0
                            src = y * 8
                            for x in range(8):
                                plane[row + x] = pixels[src + x] + 128.0

    out: list[tuple[int, int, int, int]] = []
    if len(components) == 1:
        comp = components[0]
        plane, stride = comp["plane"], comp["stride"]
        for y in range(height):
            base = y * stride
            for x in range(width):
                grey = _clamp(plane[base + x])
                out.append((grey, grey, grey, 255))
        return width, height, out

    y_c, cb_c, cr_c = components[0], components[1], components[2]
    for comp in (y_c, cb_c, cr_c):
        comp["w"] = -(-width * comp["h"] // h_max)
        comp["h_px"] = -(-height * comp["v"] // v_max)
        comp["xmap"] = _axis_map(width, comp["h"], h_max, comp["w"])
        comp["ymap"] = _axis_map(height, comp["v"], v_max, comp["h_px"])

    y_plane, y_stride, y_xmap, y_ymap = (
        y_c["plane"], y_c["stride"], y_c["xmap"], y_c["ymap"])
    cb_plane, cb_stride, cb_xmap, cb_ymap = (
        cb_c["plane"], cb_c["stride"], cb_c["xmap"], cb_c["ymap"])
    cr_plane, cr_stride, cr_xmap, cr_ymap = (
        cr_c["plane"], cr_c["stride"], cr_c["xmap"], cr_c["ymap"])

    for y in range(height):
        yy0, yy1, yfr = y_ymap[y]
        cby0, cby1, cbyfr = cb_ymap[y]
        cry0, cry1, cryfr = cr_ymap[y]
        y_r0, y_r1 = yy0 * y_stride, yy1 * y_stride
        cb_r0, cb_r1 = cby0 * cb_stride, cby1 * cb_stride
        cr_r0, cr_r1 = cry0 * cr_stride, cry1 * cr_stride
        for x in range(width):
            luma = _bilinear(y_plane, y_r0, y_r1, yfr, y_xmap[x])
            cb = _bilinear(cb_plane, cb_r0, cb_r1, cbyfr, cb_xmap[x]) - 128.0
            cr = _bilinear(cr_plane, cr_r0, cr_r1, cryfr, cr_xmap[x]) - 128.0
            out.append((
                _clamp(luma + 1.402 * cr),
                _clamp(luma - 0.344136 * cb - 0.714136 * cr),
                _clamp(luma + 1.772 * cb),
                255,
            ))
    return width, height, out
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall