"""Parser for the binary DZGF payload returned by ``POST /geometry/frames``."""
from __future__ import annotations
import struct
from dataclasses import dataclass, field
from .exceptions import ServerResponseError
_MAGIC = b"DZGF"
# magic, version, numFrames, numVerts, numBones, flags, numSets, mismatches
# (the last two are reserved zeros in v1)
_HEADER = struct.Struct("<4s7I")
_FLAG_INDICES = 0x1
_FLAG_SETS = 0x2
Point = tuple[float, float, float]
[docs]
@dataclass(frozen=True)
class GeometryFrames:
"""Deformed figure vertices and bone origins for a list of frames.
Returned by :meth:`dazpy.DazClient.export_geometry_frames`.
Attributes:
frames: Frame numbers, in the order they were evaluated.
vertices: ``vertices[f][v]`` is the ``(x, y, z)`` position of vertex
*v* at ``frames[f]``.
bones: ``bones[f][b]`` is the world-space origin of ``bone_names[b]``
at ``frames[f]``.
bone_names: The bone names passed in the request, in payload order.
indices: Mesh vertex index of each returned vertex when a subset
(``indices`` or ``surfaces``) was requested, otherwise ``None``
(``vertices[f][v]`` is then mesh vertex *v*).
raw: The unparsed payload, e.g. for ``numpy.frombuffer``.
sets: Only with channel overrides (DZGF v2): one ``GeometryFrames``
per override set, in ``values`` row order, each holding that set's
per-frame ``vertices``/``bones``. The top-level ``vertices`` and
``bones`` are then empty.
restore_mismatches: Only with channel overrides: channel restores the
server could not verify afterwards (key count or value differ).
Should be 0; anything else means the scene may have changed.
"""
frames: list[int]
vertices: list[list[Point]]
bones: list[list[Point]]
bone_names: list[str] = field(default_factory=list)
indices: list[int] | None = None
raw: bytes = field(default=b"", repr=False)
sets: list[GeometryFrames] | None = field(default=None, repr=False)
restore_mismatches: int = 0
@property
def num_frames(self) -> int:
return len(self.frames)
@property
def num_vertices(self) -> int:
"""Vertices per frame (the subset size if a subset was requested)."""
if self.sets:
return self.sets[0].num_vertices
return len(self.vertices[0]) if self.vertices else 0
@property
def num_sets(self) -> int:
"""Override sets per frame (0 without channel overrides)."""
return len(self.sets) if self.sets else 0
def _require_single_set(self) -> None:
if self.sets:
raise ValueError("payload has override sets; use .sets[i].frame() / .sets[i].bone()")
[docs]
def frame(self, frame: int) -> list[Point]:
"""Vertices for frame number *frame* (not a list position)."""
self._require_single_set()
try:
return self.vertices[self.frames.index(frame)]
except ValueError:
raise KeyError(f"frame {frame} not in payload {self.frames}") from None
[docs]
def bone(self, name: str) -> list[Point]:
"""World-space origin of bone *name* for every frame, in frame order."""
self._require_single_set()
try:
b = self.bone_names.index(name)
except ValueError:
raise KeyError(f"bone {name!r} not in payload {self.bone_names}") from None
return [per_frame[b] for per_frame in self.bones]
def _points(data: bytes, offset: int, count: int) -> list[Point]:
flat = struct.unpack_from(f"<{count * 3}f", data, offset)
return [flat[i:i + 3] for i in range(0, len(flat), 3)]
[docs]
def parse_geometry_frames(data: bytes, bone_names: list[str] | None = None) -> GeometryFrames:
"""Decode a DZGF payload (see ``POST /geometry/frames`` in the README).
Args:
data: The raw response body.
bone_names: The ``bones`` list sent in the request, used to label the
bone section. Must match the payload's bone count when given.
Raises:
ServerResponseError: If the payload is truncated, has the wrong magic
or an unsupported version.
"""
def bad(msg: str) -> ServerResponseError:
return ServerResponseError(f"Invalid DZGF payload: {msg}", status_code=200,
error_code="INVALID_PAYLOAD")
if len(data) < _HEADER.size:
raise bad(f"{len(data)} bytes is shorter than the {_HEADER.size}-byte header")
magic, version, n_frames, n_verts, n_bones, flags, n_sets, mismatches = _HEADER.unpack_from(data, 0)
if magic != _MAGIC:
raise bad(f"magic {magic!r}, expected {_MAGIC!r}")
if version not in (1, 2):
raise bad(f"unsupported version {version}")
has_sets = bool(flags & _FLAG_SETS)
if (version == 2) != has_sets or (has_sets and n_sets < 1):
raise bad(f"version {version} with flags {flags:#x} and {n_sets} sets")
evals = n_sets if has_sets else 1
has_indices = bool(flags & _FLAG_INDICES)
expected = (_HEADER.size + 4 * n_frames + (4 * n_verts if has_indices else 0)
+ 12 * n_frames * evals * n_verts + 12 * n_frames * evals * n_bones)
if len(data) != expected:
raise bad(f"{len(data)} bytes, header implies {expected}")
if bone_names is not None and len(bone_names) != n_bones:
raise bad(f"{n_bones} bones in payload, {len(bone_names)} requested")
off = _HEADER.size
frames = list(struct.unpack_from(f"<{n_frames}i", data, off))
off += 4 * n_frames
indices = None
if has_indices:
indices = list(struct.unpack_from(f"<{n_verts}I", data, off))
off += 4 * n_verts
# Evaluation order is frame-major: verts[frame][set][vert], bones likewise.
vertices: list[list[list[Point]]] = [[] for _ in range(evals)]
for _ in range(n_frames):
for s in range(evals):
vertices[s].append(_points(data, off, n_verts))
off += 12 * n_verts
bones: list[list[list[Point]]] = [[] for _ in range(evals)]
for _ in range(n_frames):
for s in range(evals):
bones[s].append(_points(data, off, n_bones))
off += 12 * n_bones
names = list(bone_names) if bone_names is not None else []
raw = bytes(data)
if not has_sets:
return GeometryFrames(frames=frames, vertices=vertices[0], bones=bones[0],
bone_names=names, indices=indices, raw=raw)
sets = [GeometryFrames(frames=frames, vertices=vertices[s], bones=bones[s],
bone_names=names, indices=indices)
for s in range(evals)]
return GeometryFrames(frames=frames, vertices=[], bones=[], bone_names=names,
indices=indices, raw=raw, sets=sets,
restore_mismatches=mismatches)
def _channel_spec(spec) -> dict:
"""Validate one ``channels`` entry (see ``POST /geometry/frames``)."""
if not isinstance(spec, dict):
raise ValueError(f"channel spec must be a dict, got {spec!r}")
keys = set(spec)
if keys == {"morph"} or keys in ({"property"}, {"bone", "property"}, {"node", "property"}):
if not all(isinstance(v, str) and v for v in spec.values()):
raise ValueError(f"channel spec values must be non-empty strings: {spec!r}")
return dict(spec)
raise ValueError(
"channel spec must be {'morph': m}, {'property': p}, {'bone': b, 'property': p} "
f"or {{'node': n, 'property': p}}, got {spec!r}")
def geometry_frames_payload(
frames, node: str | None, indices, surfaces, bones, resolution: str, scene_update: bool,
channels=None, values=None, vertices: bool = True,
) -> dict:
"""Request body for ``POST /geometry/frames`` (shared by the sync and async clients)."""
frames = [int(f) for f in frames]
if not frames:
raise ValueError("frames must contain at least one frame number")
if resolution not in ("base", "current"):
raise ValueError(f"resolution must be 'base' or 'current', got {resolution!r}")
payload: dict = {"frames": frames}
if node is not None:
payload["node"] = node
if indices is not None:
payload["indices"] = [int(i) for i in indices]
if surfaces is not None:
payload["surfaces"] = list(surfaces)
if bones is not None:
payload["bones"] = list(bones)
if resolution != "base":
payload["resolution"] = resolution
if not scene_update:
payload["sceneUpdate"] = False
if not vertices:
if not bones:
raise ValueError("vertices=False needs bones")
if indices is not None or surfaces is not None:
raise ValueError("indices/surfaces need vertices=True")
payload["vertices"] = False
if (channels is None) != (values is None):
raise ValueError("channels and values must be given together")
if channels is not None:
specs = [_channel_spec(c) for c in channels]
rows = [[float(v) for v in row] for row in values]
if not specs or not rows:
raise ValueError("channels and values must not be empty")
for i, row in enumerate(rows):
if len(row) != len(specs):
raise ValueError(f"values[{i}] has {len(row)} entries, expected {len(specs)}")
payload["channels"] = specs
payload["values"] = rows
return payload