use std::collections::HashMap;
use std::ops::Range;
const END: u16 = 0;
const SHOW_FRAME: u16 = 1;
const PLACE_OBJECT: u16 = 4;
const REMOVE_OBJECT: u16 = 5;
const DEFINE_BUTTON: u16 = 7;
const DEFINE_BUTTON_2: u16 = 34;
const PLACE_OBJECT_2: u16 = 26;
const REMOVE_OBJECT_2: u16 = 28;
const DEFINE_SHAPE_3: u16 = 32;
const DEFINE_SPRITE: u16 = 39;
const PLACE_OBJECT_3: u16 = 70;
const SYMBOL_CLASS: u16 = 76;
const LONG_TAG: u16 = 0x3F;
const PLACE_MOVES: u8 = 1;
const PLACE_NAMES_CHARACTER: u8 = 2;
const PLACE_CLIPS: u8 = 0x40;
const MOVE_TO: u32 = 0b00001;
const FILL_STYLE_0: u32 = 0b00010;
pub const HEADER_BYTES: usize = 8;
const WIDEST_FIELD_BITS: u32 = 31;
const WIDEST_EDGE_BITS: u32 = 17;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Point {
pub x: i32,
pub y: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Edge
{
Line(P),
Curve {
control: P,
to: P,
},
}
impl Edge {
pub fn points(self) -> [P; 2] {
match self {
Self::Line(to) => [to, to],
Self::Curve { control, to } => [control, to],
}
}
pub fn map(self, place: impl Fn(P) -> Q) -> Edge {
match self {
Self::Line(to) => Edge::Line(place(to)),
Self::Curve { control, to } => Edge::Curve {
control: place(control),
to: place(to),
},
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Contour {
pub start: P,
pub edges: Vec>,
}
impl Contour {
pub fn points(&self) -> impl Iterator- + '_ {
std::iter::once(self.start).chain(self.edges.iter().flat_map(|edge| edge.points()))
}
pub fn map
(&self, place: impl Fn(P) -> Q) -> Contour {
Contour {
start: place(self.start),
edges: self.edges.iter().map(|edge| edge.map(&place)).collect(),
}
}
fn closed(&self) -> bool
where
P: PartialEq,
{
self.edges
.last()
.is_some_and(|edge| edge.points()[1] == self.start)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShapeBody {
id: u16,
bytes: Vec,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
Place(u16),
Mask(u16),
Replace(u16),
Modify,
Remove,
Unread,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Depth(pub u16);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Placement {
pub frame: u16,
pub depth: Depth,
pub change: Change,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Sprite {
pub id: u16,
pub placements: Vec,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Tag {
code: u16,
start: usize,
body: Range,
}
fn u16_at(bytes: &[u8], at: usize) -> Option {
Some(u16::from_le_bytes(*bytes.get(at..)?.first_chunk()?))
}
fn u32_at(bytes: &[u8], at: usize) -> Option {
Some(u32::from_le_bytes(*bytes.get(at..)?.first_chunk()?))
}
fn tags(bytes: &[u8], range: Range) -> Option> {
let mut found = Vec::new();
let mut at = range.start;
while at < range.end {
let head = u16_at(bytes, at)?;
let code = head >> 6;
let (body, len) = match head & LONG_TAG {
LONG_TAG => (
at.checked_add(6)?,
usize::try_from(u32_at(bytes, at.checked_add(2)?)?).ok()?,
),
short => (at.checked_add(2)?, usize::from(short)),
};
let end = body.checked_add(len).filter(|&end| end <= range.end)?;
found.push(Tag {
code,
start: at,
body: body..end,
});
if code == END {
break;
}
at = end;
}
Some(found)
}
fn placements(bytes: &[u8], tags: &[Tag]) -> Option> {
let mut found = Vec::new();
let mut frame = 0u16;
for tag in tags {
let body = bytes.get(tag.body.clone())?;
let (depth, change) = match tag.code {
SHOW_FRAME => {
frame = frame.saturating_add(1);
continue;
}
PLACE_OBJECT => (u16_at(body, 2)?, Change::Place(u16_at(body, 0)?)),
PLACE_OBJECT_2 => {
let flags = *body.first()?;
let moves = flags & PLACE_MOVES != 0;
let change = match (moves, flags & PLACE_NAMES_CHARACTER != 0) {
(false, true) if flags & PLACE_CLIPS != 0 => Change::Mask(u16_at(body, 3)?),
(false, true) => Change::Place(u16_at(body, 3)?),
(true, true) => Change::Replace(u16_at(body, 3)?),
(_, false) => Change::Modify,
};
(u16_at(body, 1)?, change)
}
PLACE_OBJECT_3 => (u16_at(body, 2)?, Change::Unread),
REMOVE_OBJECT => (u16_at(body, 2)?, Change::Remove),
REMOVE_OBJECT_2 => (u16_at(body, 0)?, Change::Remove),
_ => continue,
};
found.push(Placement {
frame,
depth: Depth(depth),
change,
});
}
Some(found)
}
#[must_use]
pub fn names_movie(header: &[u8; HEADER_BYTES], len: usize) -> bool {
let [b'G', b'F', b'X', _, length @ ..] = *header else {
return false;
};
usize::try_from(u32::from_le_bytes(length)).is_ok_and(|length| length == len)
}
pub struct Movie<'a> {
bytes: &'a [u8],
first: usize,
tags: Vec,
shape_counts: HashMap,
}
impl<'a> Movie<'a> {
#[must_use]
pub fn parse(bytes: &'a [u8]) -> Option {
if !names_movie(bytes.first_chunk()?, bytes.len()) {
return None;
}
let field_bits = usize::from(bytes.get(8)? >> 3);
let first = 8 + (5 + 4 * field_bits).div_ceil(8) + 4;
let tags = tags(bytes, first..bytes.len())?;
let mut shape_counts = HashMap::new();
let shapes = tags.iter().filter(|tag| tag.code == DEFINE_SHAPE_3);
for id in shapes.filter_map(|tag| u16_at(bytes.get(tag.body.clone())?, 0)) {
*shape_counts.entry(id).or_insert(0) += 1;
}
Some(Self {
bytes,
first,
tags,
shape_counts,
})
}
fn bodies(&self, code: u16) -> impl Iterator- {
let bytes = self.bytes;
self.tags
.iter()
.filter(move |tag| tag.code == code)
.filter_map(move |tag| bytes.get(tag.body.clone()))
}
#[must_use]
pub fn shape_counts(&self) -> &HashMap {
&self.shape_counts
}
#[must_use]
pub fn defines_buttons(&self) -> bool {
self.tags
.iter()
.any(|tag| matches!(tag.code, DEFINE_BUTTON | DEFINE_BUTTON_2))
}
#[must_use]
pub fn timeline(&self) -> Option> {
placements(self.bytes, &self.tags)
}
#[must_use]
pub fn sprites(&self) -> Option> {
self.bodies(DEFINE_SPRITE)
.map(|body| {
let own = tags(body, 4..body.len())?;
Some(Sprite {
id: u16_at(body, 0)?,
placements: placements(body, &own)?,
})
})
.collect()
}
#[must_use]
pub fn classes(&self) -> Option> {
let mut found = Vec::new();
for body in self.bodies(SYMBOL_CLASS) {
let mut rest = body.get(2..)?;
for _ in 0..u16_at(body, 0)? {
let id = u16_at(rest, 0)?;
let named = rest.get(2..)?;
let end = named.iter().position(|&byte| byte == 0)?;
found.push((id, named.get(..end)?));
rest = named.get(end + 1..)?;
}
}
Some(found)
}
#[must_use]
pub fn replace_shapes(&self, bodies: &[ShapeBody]) -> Option> {
let counts = &self.shape_counts;
let mut by_id = HashMap::with_capacity(bodies.len());
for body in bodies {
if counts.get(&body.id) != Some(&1) || by_id.insert(body.id, body).is_some() {
return None;
}
}
let mut out = Vec::with_capacity(self.bytes.len());
out.extend(self.bytes.get(..self.first)?);
for tag in &self.tags {
let id = (tag.code == DEFINE_SHAPE_3)
.then(|| u16_at(self.bytes.get(tag.body.clone())?, 0))
.flatten();
match id.and_then(|id| by_id.get(&id)) {
Some(body) => {
out.extend(((DEFINE_SHAPE_3 << 6) | LONG_TAG).to_le_bytes());
out.extend(u32::try_from(body.bytes.len()).ok()?.to_le_bytes());
out.extend(&body.bytes);
}
None => out.extend(self.bytes.get(tag.start..tag.body.end)?),
}
}
let len = u32::try_from(out.len()).ok()?.to_le_bytes();
out.get_mut(4..8)?.copy_from_slice(&len);
Some(out)
}
}
struct Bits {
bytes: Vec,
free: u32,
}
impl Bits {
fn put(&mut self, value: u32, count: u32) {
for bit in (0..count).rev() {
if self.free == 0 {
self.bytes.push(0);
self.free = 8;
}
self.free -= 1;
if let Some(last) = self.bytes.last_mut() {
*last |= u8::from((value >> bit) & 1 == 1) << self.free;
}
}
}
fn signed(&mut self, value: i32, count: u32) {
self.put(value.cast_unsigned(), count);
}
}
fn field_bits(values: &[i32]) -> u32 {
values
.iter()
.map(|&value| 33 - (value ^ (value >> 31)).leading_zeros())
.max()
.unwrap_or(1)
}
fn delta(from: Point, to: Point) -> Option<[i32; 2]> {
Some([to.x.checked_sub(from.x)?, to.y.checked_sub(from.y)?])
}
#[must_use]
pub fn shape(id: u16, rgba: [u8; 4], contours: &[Contour]) -> Option {
if !contours.iter().all(Contour::closed) {
return None;
}
let points = || contours.iter().flat_map(Contour::points);
let bounds = [
points().map(|p| p.x).min().unwrap_or(0),
points().map(|p| p.x).max().unwrap_or(0),
points().map(|p| p.y).min().unwrap_or(0),
points().map(|p| p.y).max().unwrap_or(0),
];
let mut bits = Bits {
bytes: id.to_le_bytes().to_vec(),
free: 0,
};
let count = field_bits(&bounds);
if count > WIDEST_FIELD_BITS {
return None;
}
bits.put(count, 5);
for value in bounds {
bits.signed(value, count);
}
bits.free = 0;
bits.bytes.extend([1, 0]);
bits.bytes.extend(rgba);
bits.bytes.extend([0, 0x10]);
for (index, contour) in contours.iter().enumerate() {
let first = index == 0;
bits.put(0, 1);
bits.put(
if first {
FILL_STYLE_0 | MOVE_TO
} else {
MOVE_TO
},
5,
);
let count = field_bits(&[contour.start.x, contour.start.y]);
bits.put(count, 5);
bits.signed(contour.start.x, count);
bits.signed(contour.start.y, count);
if first {
bits.put(1, 1);
}
let mut at = contour.start;
for edge in &contour.edges {
let (line, curve);
let (straight, deltas, to): (bool, &[i32], Point) = match *edge {
Edge::Line(to) => {
line = delta(at, to)?;
if line == [0, 0] {
continue;
}
(true, &line, to)
}
Edge::Curve { control, to } => {
let ([cx, cy], [x, y]) = (delta(at, control)?, delta(control, to)?);
curve = [cx, cy, x, y];
(false, &curve, to)
}
};
let count = field_bits(deltas).max(2);
if count > WIDEST_EDGE_BITS {
return None;
}
bits.put(if straight { 0b11 } else { 0b10 }, 2);
bits.put(count - 2, 4);
if straight {
bits.put(1, 1);
}
for &value in deltas {
bits.signed(value, count);
}
at = to;
}
}
bits.put(0, 6);
Some(ShapeBody {
id,
bytes: bits.bytes,
})
}