use crate::palette::{PaletteFamily, Theme};
use crate::particles::{Emitter, Particle};
use crate::placeholder::{
BASKET, BOOK_CLOSED, BUCKET, CAMP_STOVE, CAMPFIRE, CHESS_TABLE, CLAWD_PLACEHOLDER, COFFEE_MUG,
EASEL, FALLEN_HAT, GUITAR_REST, KITE_REST, LANTERN, LOG_SEAT, PICNIC_BASKET, PRACTICE_WALL,
PixelMap, SKIS_REST, SNOWMAN, SPELLBOOK, STONE_PILE, TELESCOPE,
};
use crate::recipe::TimeOfDay;
pub const ADVANCE_RATIO: f64 = 0.6;
pub const FONT_TO_CELL: f64 = 0.9;
pub const TARGET_ROWS: u32 = 108;
pub const MIN_CELL_W: u32 = 6;
pub const MIN_CELL_H: u32 = 11;
pub const CHARACTER_BOX: (u32, u32) = (19, 13);
pub const BANDS: u8 = 8;
const DITHER_WIDTH: f64 = 0.4;
const BAYER4: [[u8; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
pub struct GridSpec {
pub cols: u32,
pub rows: u32,
pub cell_w: u32,
pub cell_h: u32,
pub origin_x: u32,
pub origin_y: u32,
pub font_px: f64,
}
pub fn grid_spec(width: u32, height: u32) -> GridSpec {
let cell_h = ((f64::from(height) / f64::from(TARGET_ROWS)).round() as u32).max(MIN_CELL_H);
let font_px = f64::from(cell_h) * FONT_TO_CELL;
let cell_w = ((font_px * ADVANCE_RATIO).round() as u32).max(MIN_CELL_W);
let cols = width / cell_w;
let rows = height / cell_h;
GridSpec {
cols,
rows,
cell_w,
cell_h,
origin_x: (width - cols * cell_w) / 2,
origin_y: (height - rows * cell_h) / 2,
font_px,
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Cell {
pub glyph: u8,
pub shade: u8,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
pub struct Glow {
pub cx: f64,
pub cy: f64,
pub radius: f64,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
pub struct Lighting {
pub vignette_cx: f64,
pub vignette_cy: f64,
pub vignette_rx: f64,
pub vignette_ry: f64,
pub glow: Option<Glow>,
}
#[derive(Clone, Copy, Debug)]
pub struct RowTerms {
vy2: f64,
gy2: f64,
bayer_row: usize,
}
impl Lighting {
#[inline]
pub fn row_terms(&self, py: u32) -> RowTerms {
let y = f64::from(py) + 0.5;
let vy = (y - self.vignette_cy) / self.vignette_ry;
let gy2 = match self.glow {
Some(g) => {
let d = y - g.cy;
d * d
}
None => 0.0,
};
RowTerms {
vy2: vy * vy,
gy2,
bayer_row: (py & 3) as usize,
}
}
#[inline]
pub fn band_in_row(&self, rt: &RowTerms, px: u32) -> u8 {
let x = f64::from(px) + 0.5;
let vx = (x - self.vignette_cx) / self.vignette_rx;
let q = (vx * vx + rt.vy2).min(1.0);
let v = 1.0 - q;
let cv = 3.999 * v * v;
let c = match self.glow {
Some(g) => {
let dx = x - g.cx;
let r2 = (dx * dx + rt.gy2) / (g.radius * g.radius);
if r2 < 1.0 {
let t = 1.0 - r2;
cv + t * t * (7.999 - cv)
} else {
cv
}
}
None => cv,
};
let b = BAYER4[rt.bayer_row][(px & 3) as usize];
let d = ((f64::from(b) + 0.5) / 16.0 - 0.5) * DITHER_WIDTH;
(c + d).floor().clamp(0.0, f64::from(BANDS - 1)) as u8
}
pub fn fill_row(&self, py: u32, out: &mut [u8]) {
let rt = self.row_terms(py);
for (px, o) in out.iter_mut().enumerate() {
*o = self.band_in_row(&rt, px as u32);
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpriteKind {
Character,
Campfire,
LogSeat,
Telescope,
Lantern,
Spellbook,
CampStove,
CoffeeMug,
FallenHat,
BookClosed,
GuitarRest,
Bucket,
KiteRest,
StonePile,
Easel,
Snowman,
Basket,
PicnicBasket,
ChessTable,
PracticeWall,
SkisRest,
}
impl SpriteKind {
pub const BEFORE_CHARACTER: usize = 12;
pub const ALL: [SpriteKind; 21] = [
SpriteKind::Character,
SpriteKind::Campfire,
SpriteKind::LogSeat,
SpriteKind::Telescope,
SpriteKind::Lantern,
SpriteKind::Spellbook,
SpriteKind::CampStove,
SpriteKind::CoffeeMug,
SpriteKind::FallenHat,
SpriteKind::BookClosed,
SpriteKind::GuitarRest,
SpriteKind::Bucket,
SpriteKind::KiteRest,
SpriteKind::StonePile,
SpriteKind::Easel,
SpriteKind::Snowman,
SpriteKind::Basket,
SpriteKind::PicnicBasket,
SpriteKind::ChessTable,
SpriteKind::PracticeWall,
SpriteKind::SkisRest,
];
pub fn box_size(self) -> (u32, u32) {
match self {
SpriteKind::Character => CHARACTER_BOX,
other => (other.map().width, other.map().height),
}
}
pub fn map(self) -> &'static PixelMap {
match self {
SpriteKind::Character => &CLAWD_PLACEHOLDER,
SpriteKind::Campfire => &CAMPFIRE,
SpriteKind::LogSeat => &LOG_SEAT,
SpriteKind::Telescope => &TELESCOPE,
SpriteKind::Lantern => &LANTERN,
SpriteKind::Spellbook => &SPELLBOOK,
SpriteKind::CampStove => &CAMP_STOVE,
SpriteKind::CoffeeMug => &COFFEE_MUG,
SpriteKind::FallenHat => &FALLEN_HAT,
SpriteKind::BookClosed => &BOOK_CLOSED,
SpriteKind::GuitarRest => &GUITAR_REST,
SpriteKind::Bucket => &BUCKET,
SpriteKind::KiteRest => &KITE_REST,
SpriteKind::StonePile => &STONE_PILE,
SpriteKind::Easel => &EASEL,
SpriteKind::Snowman => &SNOWMAN,
SpriteKind::Basket => &BASKET,
SpriteKind::PicnicBasket => &PICNIC_BASKET,
SpriteKind::ChessTable => &CHESS_TABLE,
SpriteKind::PracticeWall => &PRACTICE_WALL,
SpriteKind::SkisRest => &SKIS_REST,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub enum Motion {
Stationary { x: i32 },
Pace {
x_min: i32,
x_max: i32,
period_ms: u64,
},
Fly {
x_min: i32,
x_max: i32,
period_ms: u64,
lift: i32,
bob: i32,
bob_ms: u64,
},
}
pub fn bob_offset(t_ms: u64, period_ms: u64, amp: i32) -> i32 {
let half = (period_ms / 2).max(1) as i64;
let p = (t_ms % (2 * half as u64)) as i64;
let q = p % half;
let v = 4 * q * (half - q) * i64::from(amp) / (half * half);
(if p < half { -v } else { v }) as i32
}
fn back_and_forth(x_min: i32, x_max: i32, period_ms: u64, t_ms: u64) -> (i32, bool) {
let span = i64::from(x_max - x_min);
let half = (period_ms / 2).max(1) as i64;
let ph = (t_ms % period_ms.max(1)) as i64;
if ph < half {
((i64::from(x_min) + span * ph / half) as i32, false)
} else {
((i64::from(x_max) - span * (ph - half) / half) as i32, true)
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct CharacterTrack {
pub y: i32,
pub scale: u32,
pub motion: Motion,
pub face_left: bool,
}
impl CharacterTrack {
pub fn at(&self, t_ms: u64) -> SpriteInstance {
let (x, y, mirror) = match self.motion {
Motion::Stationary { x } => (x, self.y, self.face_left),
Motion::Pace {
x_min,
x_max,
period_ms,
} => {
let (x, mirror) = back_and_forth(x_min, x_max, period_ms, t_ms);
(x, self.y, mirror)
}
Motion::Fly {
x_min,
x_max,
period_ms,
lift,
bob,
bob_ms,
} => {
let (x, mirror) = back_and_forth(x_min, x_max, period_ms, t_ms);
(x, self.y - lift + bob_offset(t_ms, bob_ms, bob), mirror)
}
};
SpriteInstance {
kind: SpriteKind::Character,
x,
y,
scale: self.scale,
mirror,
}
}
pub fn flies(&self) -> bool {
matches!(self.motion, Motion::Fly { .. })
}
pub fn x_range(&self) -> (i32, i32) {
match self.motion {
Motion::Stationary { x } => (x, x),
Motion::Pace { x_min, x_max, .. } | Motion::Fly { x_min, x_max, .. } => (x_min, x_max),
}
}
}
pub const HOLE: Cell = Cell {
glyph: crate::glyphs::EMPTY,
shade: 1,
};
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct ScrollLayer {
pub cols: u32,
pub turns: u32,
#[serde(skip)]
pub cells: Vec<Cell>,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Journey {
pub loop_ms: u64,
pub layers: Vec<ScrollLayer>,
pub ground: Vec<i32>,
pub feet_x: i32,
}
impl Journey {
pub fn offset_px(&self, i: usize, cell_w: u32, t_ms: u64) -> u32 {
let l = &self.layers[i];
let period = u64::from(l.cols) * u64::from(cell_w);
let t = t_ms % self.loop_ms.max(1);
((u64::from(l.turns) * period * t / self.loop_ms.max(1)) % period.max(1)) as u32
}
pub fn ground_at(&self, cell_w: u32, origin_x: u32, t_ms: u64) -> Option<i32> {
let last = self.layers.len().checked_sub(1)?;
let period = self.ground.len() as i64;
if period == 0 {
return None;
}
let off = i64::from(self.offset_px(last, cell_w, t_ms));
let x = (i64::from(self.feet_x) - i64::from(origin_x) + off).rem_euclid(period);
Some(self.ground[x as usize])
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpriteInstance {
pub kind: SpriteKind,
pub x: i32,
pub y: i32,
pub scale: u32,
pub mirror: bool,
}
impl SpriteInstance {
pub fn width(&self) -> u32 {
self.kind.box_size().0 * self.scale
}
pub fn height(&self) -> u32 {
self.kind.box_size().1 * self.scale
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct SceneGraph {
pub width: u32,
pub height: u32,
pub theme: Theme,
pub tod: TimeOfDay,
pub buddy: bool,
pub seed: u64,
#[serde(skip, default = "crate::palette::fallback_family")]
pub family: PaletteFamily,
pub grid: GridSpec,
#[serde(skip)]
pub cells: Vec<Cell>,
pub lighting: Lighting,
pub activity: Option<String>,
pub props: Vec<SpriteInstance>,
pub unattended: Vec<SpriteInstance>,
pub character: Option<CharacterTrack>,
pub emitters: Vec<Emitter>,
pub ground_y: i32,
pub t_hero_ms: u64,
pub loop_ms: u64,
#[serde(default)]
pub pace: u8,
#[serde(default)]
pub generator: u32,
#[serde(default)]
pub water: Option<(i32, i32)>,
#[serde(default)]
pub journey: Option<Journey>,
}
impl SceneGraph {
#[inline]
pub fn cell(&self, col: u32, row: u32) -> Cell {
self.cells[(row * self.grid.cols + col) as usize]
}
pub fn sprites_at(&self, t_ms: u64) -> Vec<SpriteInstance> {
let mut out = self.props.clone();
if self.buddy {
out.extend(self.character.map(|c| self.on_ground(c.at(t_ms), t_ms)));
} else {
out.extend_from_slice(&self.unattended);
}
out
}
pub fn on_ground(&self, mut s: SpriteInstance, t_ms: u64) -> SpriteInstance {
if let Some(j) = &self.journey
&& s.kind == SpriteKind::Character
&& let Some(y) = j.ground_at(self.grid.cell_w, self.grid.origin_x, t_ms)
{
s.y += y - self.ground_y;
}
s
}
pub fn particles_in_grid(&self, t_ms: u64) -> Vec<Particle> {
let g = &self.grid;
let (x0, y0) = (f64::from(g.origin_x), f64::from(g.origin_y));
let x1 = x0 + f64::from(g.cols * g.cell_w);
let y1 = y0 + f64::from(g.rows * g.cell_h);
self.emitters
.iter()
.flat_map(|e| e.sample(t_ms))
.filter(|p| p.x >= x0 && p.y >= y0 && p.x < x1 && p.y < y1)
.collect()
}
pub fn particles_at(&self, t_ms: u64) -> Vec<(u32, u32, Particle)> {
let g = &self.grid;
let mut out = Vec::new();
for e in &self.emitters {
for p in e.sample(t_ms) {
let cx = (p.x - f64::from(g.origin_x)) / f64::from(g.cell_w);
let cy = (p.y - f64::from(g.origin_y)) / f64::from(g.cell_h);
if cx < 0.0 || cy < 0.0 {
continue;
}
let (col, row) = (cx.floor() as u32, cy.floor() as u32);
if col < g.cols && row < g.rows {
out.push((col, row, p));
}
}
}
out
}
}