use crate::paint::{BoxAreas, Position, PositionComponent, Rect};
use crate::style::{
LengthPercentage, POINTS_PER_PIXEL, Style, StyleError,
box_values::{length_percentage, unsupported},
calc::Kind,
component::Component,
grammar::Keyword,
units::Relative,
values::math,
};
use serde::Serialize;
pub(crate) type Matrix = [f32; 6];
pub(crate) type Matrix3d = [f32; 16];
pub(crate) const NOT_RENDERED: Matrix = [0.0; 6];
const IDENTITY: Matrix3d = [
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
];
const DIMENSION: usize = 4;
const W_FROM_X: usize = 3;
const W_FROM_Y: usize = 7;
const W_FROM_Z: usize = 11;
const W_CONSTANT: usize = 15;
const Z_FROM_X: usize = 2;
const Z_FROM_Y: usize = 6;
const Z_FROM_Z: usize = 10;
const Z_CONSTANT: usize = 14;
const TRANSLATION: std::ops::Range<usize> = 12..15;
const PROJECTION_TOLERANCE: f32 = 1.0e-6;
const MIN_PERSPECTIVE_PT: f32 = POINTS_PER_PIXEL;
const X_AXIS: [f32; 3] = [1.0, 0.0, 0.0];
const Y_AXIS: [f32; 3] = [0.0, 1.0, 0.0];
const Z_AXIS: [f32; 3] = [0.0, 0.0, 1.0];
const START: LengthPercentage = LengthPercentage::Percentage(0.0);
const CENTRE: LengthPercentage = LengthPercentage::Percentage(0.5);
const END: LengthPercentage = LengthPercentage::Percentage(1.0);
pub(crate) const INITIAL_ORIGIN: [LengthPercentage; 3] = [CENTRE, CENTRE, LengthPercentage::ZERO];
pub(crate) const INITIAL_PERSPECTIVE_ORIGIN: Position = [PositionComponent::CENTER; 2];
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub(crate) struct Rotation {
pub(crate) axis: [f32; 3],
pub(crate) angle: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[expect(
clippy::enum_variant_names,
reason = "variants name the CSS transform-box keywords"
)]
pub(crate) enum TransformBox {
ContentBox,
BorderBox,
FillBox,
StrokeBox,
#[default]
ViewBox,
}
impl TransformBox {
pub(super) fn from_component(value: &Component) -> Result<Self, StyleError> {
Ok(match value.keyword() {
Some(Keyword::ContentBox) => Self::ContentBox,
Some(Keyword::BorderBox) => Self::BorderBox,
Some(Keyword::FillBox) => Self::FillBox,
Some(Keyword::StrokeBox) => Self::StrokeBox,
Some(Keyword::ViewBox) => Self::ViewBox,
_ => return Err(unsupported(value)),
})
}
fn reference(self, boxes: &BoxAreas<Rect>) -> Rect {
match self {
Self::ContentBox | Self::FillBox => boxes.content,
Self::BorderBox | Self::StrokeBox | Self::ViewBox => boxes.border,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub(crate) enum TransformFunction {
Matrix(Matrix3d),
Translate([LengthPercentage; 3]),
}
fn multiply(m: &Matrix3d, n: &Matrix3d) -> Matrix3d {
std::array::from_fn(|index| {
let (column, row) = (index / DIMENSION, index % DIMENSION);
(0..DIMENSION)
.map(|k| m[k * DIMENSION + row] * n[column * DIMENSION + k])
.sum()
})
}
fn translation([x, y, z]: [f32; 3]) -> Matrix3d {
let mut m = IDENTITY;
m[TRANSLATION].copy_from_slice(&[x, y, z]);
m
}
fn perspective(depth: f32) -> Matrix3d {
let mut m = IDENTITY;
m[W_FROM_Z] = -1.0 / depth.max(MIN_PERSPECTIVE_PT);
m
}
fn linear(rows: [[f32; 3]; 3]) -> Matrix3d {
let mut m = IDENTITY;
for (row, values) in rows.iter().enumerate() {
for (column, &value) in values.iter().enumerate() {
m[column * DIMENSION + row] = value;
}
}
m
}
fn planar([a, b, c, d]: [f32; 4]) -> Matrix3d {
linear([[a, c, 0.0], [b, d, 0.0], [0.0, 0.0, 1.0]])
}
fn scaling(x: f32, y: f32, z: f32) -> Matrix3d {
linear([[x, 0.0, 0.0], [0.0, y, 0.0], [0.0, 0.0, z]])
}
fn rotation(axis: [f32; 3], angle: f32) -> Matrix3d {
let length = axis.iter().map(|v| v * v).sum::<f32>().sqrt();
if length == 0.0 {
return IDENTITY;
}
let [x, y, z] = axis.map(|v| v / length);
let (sin, cos) = angle.sin_cos();
let t = 1.0 - cos;
linear([
[t * x * x + cos, t * x * y - sin * z, t * x * z + sin * y],
[t * x * y + sin * z, t * y * y + cos, t * y * z - sin * x],
[t * x * z - sin * y, t * y * z + sin * x, t * z * z + cos],
])
}
pub(super) fn arguments(function: &Component) -> Vec<&Component> {
let mut output = Vec::new();
function
.arguments()
.iter()
.for_each(|item| collect_values(item, &mut output));
output
}
fn collect_values<'a>(component: &'a Component, output: &mut Vec<&'a Component>) {
match component {
Component::Group(items) => items.iter().for_each(|item| collect_values(item, output)),
Component::Slots(slots) => slots
.iter()
.flatten()
.for_each(|slot| collect_values(slot, output)),
Component::Reference(_, inner) => collect_values(inner, output),
Component::Delim(_) => {}
value => output.push(value),
}
}
fn values(value: &Component) -> Vec<&Component> {
let mut output = Vec::new();
collect_values(value, &mut output);
output
}
pub(super) fn number(value: &Component, relative: &Relative<'_>) -> Result<f32, StyleError> {
match value.unwrap() {
Component::Percentage(fraction) => Ok(*fraction),
Component::Math(source, Kind::Percentage, range) => {
Ok(
math(source, relative, Kind::Percentage, Some(Kind::Percentage))?
.resolve(0.0, *range),
)
}
other => crate::style::values::number(other, relative),
}
}
fn angle(value: &Component, relative: &Relative<'_>) -> Result<f32, StyleError> {
crate::style::values::angle(value, relative).map(f32::to_radians)
}
fn function(value: &Component, relative: &Relative<'_>) -> Result<TransformFunction, StyleError> {
let Component::Function(name, _) = value.unwrap() else {
return Err(unsupported(value));
};
let args = arguments(value);
let numbers = || {
args.iter()
.map(|arg| number(arg, relative))
.collect::<Result<Vec<_>, _>>()
};
Ok(TransformFunction::Matrix(match name {
Keyword::Matrix => {
let m = numbers()?;
let mut matrix = planar([m[0], m[1], m[2], m[3]]);
matrix[12] = m[4] * POINTS_PER_PIXEL;
matrix[13] = m[5] * POINTS_PER_PIXEL;
matrix
}
Keyword::Matrix3d => {
let mut m: Matrix3d = numbers()?.try_into().map_err(|_| unsupported(value))?;
for translation in &mut m[TRANSLATION] {
*translation *= POINTS_PER_PIXEL;
}
for w in [W_FROM_X, W_FROM_Y, W_FROM_Z] {
m[w] /= POINTS_PER_PIXEL;
}
m
}
Keyword::Translate | Keyword::Translate3d => {
let x = length_percentage(args[0], relative)?;
let y = args
.get(1)
.map(|arg| length_percentage(arg, relative))
.transpose()?
.unwrap_or(LengthPercentage::ZERO);
let z = args
.get(2)
.map(|arg| length_percentage(arg, relative))
.transpose()?
.unwrap_or(LengthPercentage::ZERO);
return Ok(TransformFunction::Translate([x, y, z]));
}
Keyword::Translatex | Keyword::Translatey | Keyword::Translatez => {
let mut offset = [LengthPercentage::ZERO; 3];
let axis = match name {
Keyword::Translatex => 0,
Keyword::Translatey => 1,
_ => 2,
};
offset[axis] = length_percentage(args[0], relative)?;
return Ok(TransformFunction::Translate(offset));
}
Keyword::Scale => {
let s = numbers()?;
scaling(s[0], *s.get(1).unwrap_or(&s[0]), 1.0)
}
Keyword::Scale3d => {
let s = numbers()?;
scaling(s[0], s[1], s[2])
}
Keyword::Scalex => scaling(number(args[0], relative)?, 1.0, 1.0),
Keyword::Scaley => scaling(1.0, number(args[0], relative)?, 1.0),
Keyword::Scalez => scaling(1.0, 1.0, number(args[0], relative)?),
Keyword::Rotate | Keyword::Rotatez => rotation(Z_AXIS, angle(args[0], relative)?),
Keyword::Rotatex => rotation(X_AXIS, angle(args[0], relative)?),
Keyword::Rotatey => rotation(Y_AXIS, angle(args[0], relative)?),
Keyword::Rotate3d => {
let axis = [
number(args[0], relative)?,
number(args[1], relative)?,
number(args[2], relative)?,
];
rotation(axis, angle(args[3], relative)?)
}
Keyword::Skew => {
let x = angle(args[0], relative)?.tan();
let y = args
.get(1)
.map(|arg| angle(arg, relative))
.transpose()?
.unwrap_or(0.0)
.tan();
planar([1.0, y, x, 1.0])
}
Keyword::Skewx => planar([1.0, 0.0, angle(args[0], relative)?.tan(), 1.0]),
Keyword::Skewy => planar([1.0, angle(args[0], relative)?.tan(), 0.0, 1.0]),
Keyword::Perspective => match args.first() {
Some(depth) if depth.keyword() != Some(Keyword::None) => {
perspective(crate::style::values::length(depth, relative)?)
}
_ => IDENTITY,
},
_ => return Err(unsupported(value)),
}))
}
pub(crate) fn transform(
value: &Component,
relative: &Relative<'_>,
) -> Result<Vec<TransformFunction>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(Vec::new());
}
let mut functions = Vec::new();
for item in value.items() {
let parsed = function(item, relative)?;
if let TransformFunction::Matrix(m) = &parsed
&& m.iter().any(|v| !v.is_finite())
{
return Err(format!("non-finite transform: {value}").into());
}
functions.push(parsed);
}
Ok(functions)
}
pub(crate) fn origin(
value: &Component,
relative: &Relative<'_>,
) -> Result<[LengthPercentage; 3], StyleError> {
let horizontal = |part: &Component| match part.keyword() {
Some(Keyword::Left) => Ok(START),
Some(Keyword::Center) => Ok(CENTRE),
Some(Keyword::Right) => Ok(END),
_ => length_percentage(part, relative),
};
let vertical = |part: &Component| match part.keyword() {
Some(Keyword::Top) => Ok(START),
Some(Keyword::Center) => Ok(CENTRE),
Some(Keyword::Bottom) => Ok(END),
_ => length_percentage(part, relative),
};
let Component::Group(parts) = value.unwrap() else {
return Ok(match value.keyword() {
Some(Keyword::Top | Keyword::Bottom) => {
[CENTRE, vertical(value)?, LengthPercentage::ZERO]
}
_ => [horizontal(value)?, CENTRE, LengthPercentage::ZERO],
});
};
let (x, y, depth) = match parts.as_slice() {
[Component::Slots(slots), depth] => (
slots[0].as_ref().ok_or_else(|| unsupported(value))?,
slots[1].as_ref().ok_or_else(|| unsupported(value))?,
depth,
),
[x, y, depth] => (x, y, depth),
_ => return Err(unsupported(value)),
};
let z = depth
.items()
.first()
.map(|z| length_percentage(z, relative))
.transpose()?
.unwrap_or(LengthPercentage::ZERO);
Ok([horizontal(x)?, vertical(y)?, z])
}
pub(crate) fn translate(
value: &Component,
relative: &Relative<'_>,
) -> Result<Option<[LengthPercentage; 3]>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(None);
}
let parts = values(value);
let offset = |index: usize| {
parts.get(index).map_or(Ok(LengthPercentage::ZERO), |part| {
length_percentage(part, relative)
})
};
Ok(Some([offset(0)?, offset(1)?, offset(2)?]))
}
pub(crate) fn rotate(
value: &Component,
relative: &Relative<'_>,
) -> Result<Option<Rotation>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(None);
}
let mut axis = Z_AXIS;
let mut vector = Vec::new();
let mut rotation = None;
for part in values(value) {
match (part.keyword(), part.unwrap()) {
(Some(Keyword::X), _) => axis = X_AXIS,
(Some(Keyword::Y), _) => axis = Y_AXIS,
(Some(Keyword::Z), _) => axis = Z_AXIS,
(_, Component::Angle(_) | Component::Math(_, Kind::Angle, _)) => {
rotation = Some(angle(part, relative)?);
}
_ => vector.push(crate::style::values::number(part, relative)?),
}
}
if let Ok(components) = <[f32; 3]>::try_from(vector.as_slice()) {
axis = components;
}
Ok(Some(Rotation {
axis,
angle: rotation.ok_or_else(|| unsupported(value))?,
}))
}
pub(crate) fn scale(
value: &Component,
relative: &Relative<'_>,
) -> Result<Option<[f32; 3]>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(None);
}
let factors = values(value)
.into_iter()
.map(|part| number(part, relative))
.collect::<Result<Vec<_>, _>>()?;
let x = *factors.first().ok_or_else(|| unsupported(value))?;
Ok(Some([
x,
factors.get(1).copied().unwrap_or(x),
factors.get(2).copied().unwrap_or(1.0),
]))
}
pub(crate) fn perspective_distance(
value: &Component,
relative: &Relative<'_>,
) -> Result<Option<f32>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(None);
}
crate::style::values::length(value, relative).map(Some)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub(crate) enum TransformStyle {
#[default]
Flat,
Preserve3d,
}
impl TransformStyle {
pub(super) fn from_component(value: &Component) -> Result<Self, StyleError> {
match value.keyword() {
Some(Keyword::Flat) => Ok(Self::Flat),
Some(Keyword::Preserve3d) => Ok(Self::Preserve3d),
_ => Err(unsupported(value)),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Parent3d {
pub(crate) perspective: Option<Matrix3d>,
pub(crate) preserves_3d: bool,
}
fn corners(rect: Rect) -> [[f32; 2]; 4] {
let [right, bottom] = [rect.x + rect.width, rect.y + rect.height];
[
[rect.x, rect.y],
[right, rect.y],
[right, bottom],
[rect.x, bottom],
]
}
fn project(m: &Matrix3d, reference: Rect, backface_hidden: bool) -> Result<Matrix, StyleError> {
if backface_hidden && m[Z_FROM_Z] < 0.0 {
return Ok(NOT_RENDERED);
}
let w = |[x, y]: [f32; 2]| m[W_FROM_X] * x + m[W_FROM_Y] * y + m[W_CONSTANT];
let depth = w([
reference.x + reference.width / 2.0,
reference.y + reference.height / 2.0,
]);
if corners(reference)
.into_iter()
.any(|corner| (w(corner) - depth).abs() > PROJECTION_TOLERANCE * depth.abs())
{
return Err(StyleError::Unsupported(format!(
"perspective projection varying across a {}pt by {}pt box: PDF content matrices are affine",
reference.width, reference.height
)));
}
if depth <= 0.0 {
return Ok(NOT_RENDERED);
}
Ok([m[0], m[1], m[4], m[5], m[12], m[13]].map(|value| value / depth))
}
fn stays_in_plane(m: &Matrix3d, reference: Rect) -> bool {
corners(reference).into_iter().all(|[x, y]| {
let depth = m[Z_FROM_X] * x + m[Z_FROM_Y] * y + m[Z_CONSTANT];
depth.abs() <= PROJECTION_TOLERANCE * x.abs().max(y.abs()).max(1.0)
})
}
impl Style {
pub(crate) fn is_transformed(&self) -> bool {
!self.transform.is_empty()
|| self.translate.is_some()
|| self.rotate.is_some()
|| self.scale.is_some()
}
pub(crate) fn has_transform_effects(&self) -> bool {
self.is_transformed()
|| self.perspective.is_some()
|| self.transform_style == TransformStyle::Preserve3d
}
pub(crate) fn preserves_3d(&self) -> bool {
self.transform_style == TransformStyle::Preserve3d
&& !self.is_scroll_container()
&& !self.is_grouped()
&& self.clip.is_none()
}
pub(crate) fn parent_3d(&self, boxes: &BoxAreas<Rect>) -> Option<Parent3d> {
let preserves_3d = self.preserves_3d();
let perspective = self.perspective.map(|depth| {
let reference = self.transform_box.reference(boxes);
let [x, y] = &self.perspective_origin;
let origin = [
reference.x + x.resolve(reference.width),
reference.y + y.resolve(reference.height),
0.0,
];
multiply(
&multiply(&translation(origin), &perspective(depth)),
&translation(origin.map(|v| -v)),
)
});
(perspective.is_some() || preserves_3d).then_some(Parent3d {
perspective,
preserves_3d,
})
}
fn transformation(&self, boxes: &BoxAreas<Rect>) -> Option<Matrix3d> {
if !self.is_transformed() {
return None;
}
let reference = self.transform_box.reference(boxes);
let resolve = |[x, y, z]: &[LengthPercentage; 3]| {
[
x.resolve(reference.width),
y.resolve(reference.height),
z.resolve(0.0),
]
};
let [x, y, z] = resolve(&self.transform_origin);
let origin = [reference.x + x, reference.y + y, z];
let Ok(composed) =
self.composed(|offset| Ok::<_, std::convert::Infallible>(resolve(offset)));
Some(multiply(
&multiply(&translation(origin), &composed),
&translation(origin.map(|v| -v)),
))
}
fn composed<E>(
&self,
resolve: impl Fn(&[LengthPercentage; 3]) -> Result<[f32; 3], E>,
) -> Result<Matrix3d, E> {
let mut result = IDENTITY;
if let Some(offset) = &self.translate {
result = multiply(&result, &translation(resolve(offset)?));
}
if let Some(Rotation { axis, angle }) = self.rotate {
result = multiply(&result, &rotation(axis, angle));
}
if let Some([x, y, z]) = self.scale {
result = multiply(&result, &scaling(x, y, z));
}
for function in &self.transform {
let step = match function {
TransformFunction::Matrix(m) => *m,
TransformFunction::Translate(offset) => translation(resolve(offset)?),
};
result = multiply(&result, &step);
}
Ok(result)
}
pub(crate) fn planar_transform(&self) -> Result<Option<Matrix>, StyleError> {
if !self.is_transformed() {
return Ok(None);
}
let length = |component: &LengthPercentage| match component {
LengthPercentage::Length(length) => Ok(*length),
_ => Err(StyleError::Unsupported(
"a translation by a percentage of the reference box on SVG content".into(),
)),
};
let m =
self.composed(|[x, y, z]| Ok::<_, StyleError>([length(x)?, length(y)?, length(z)?]))?;
if m[W_FROM_X] != 0.0 || m[W_FROM_Y] != 0.0 || m[W_CONSTANT] != 1.0 {
return Err(StyleError::Unsupported(
"a perspective transform on SVG content".into(),
));
}
Ok(Some([m[0], m[1], m[4], m[5], m[12], m[13]]))
}
pub(crate) fn transform_matrix(
&self,
boxes: &BoxAreas<Rect>,
parent: Option<&Parent3d>,
) -> Result<Option<Matrix>, StyleError> {
let Some(own) = self.transformation(boxes) else {
return Ok(None);
};
let reference = self.transform_box.reference(boxes);
if parent.is_some_and(|parent| parent.preserves_3d) && !stays_in_plane(&own, reference) {
return Err(StyleError::Unsupported(
"transform-style: preserve-3d with a child leaving its plane: depth-sorting \
intersecting planes is not implemented"
.into(),
));
}
let accumulated = match parent.and_then(|parent| parent.perspective) {
Some(perspective) => multiply(&perspective, &own),
None => own,
};
project(&accumulated, reference, self.backface_hidden).map(Some)
}
}