"""How frames travel to the page (the live demo's window format, pwm-live-drop livedrop/encode.py): a 16-byte header (magic b"PWMW", version, flags, frame count, first frame, point count; little endian), then the particles of every object on the table [frames, points, 3]: the first frame as uint16 in the table's BOX, then each frame's change from the one before as int16 (flags bit 1), on a grid 2^shift coarser (flags bits 4-7; shift 3 = 0.2 mm). For the Space the bytes are deflated (resting objects send zeros, which deflate all but removes) and sent as base64 text. """ import base64 import struct import zlib import numpy as np MAGIC = b"PWMW" VERSION = 1 HEADER = struct.Struct("<4sBBHII") # magic, version, flags, n_frames, first_frame, n_points LEVELS = 65535 DELTAS_FLAG = 2 SHIFT = 3 BOX = np.array([[-0.85, -0.85, -0.05], [0.85, 0.85, 1.0]]) # metres, the model's frame def quantize(frames, box=BOX): lo, hi = box return np.clip(np.round((np.asarray(frames, np.float64) - lo) / (hi - lo) * LEVELS), 0, LEVELS).astype(np.int32) def dequantize(q, box=BOX): lo, hi = box return lo + np.asarray(q, np.float64) / LEVELS * (hi - lo) def window_message(frames, first_frame, shift=SHIFT): """frames [L, N, 3] metres -> bytes.""" q = quantize(frames) >> shift L, N, _ = q.shape body = q[:1].astype(" base64 of the deflated window message.""" return base64.b64encode(zlib.compress(window_message(frames, first_frame), 6)).decode() def read_window(message): magic, version, flags, L, first, N = HEADER.unpack_from(message, 0) if magic != MAGIC or version != VERSION: raise ValueError("not a window message") raw = np.frombuffer(message, dtype="> 4) & 15 d = raw.view("> 1)).clip(0, LEVELS) return dict(first_frame=first, frames=dequantize(q), points=N) def read_frames_text(text): return read_window(zlib.decompress(base64.b64decode(text)))