Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A little bit QoL cleaning up... #84

Merged
merged 6 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 84 additions & 72 deletions inox2d/src/formats/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@ use glam::{vec2, vec3, Vec2};
use indextree::Arena;
use json::JsonValue;

use crate::math::interp::{InterpolateMode, UnknownInterpolateModeError};
use crate::math::interp::InterpolateMode;
use crate::math::matrix::{Matrix2d, Matrix2dFromSliceVecsError};
use crate::math::transform::TransformOffset;
use crate::mesh::{f32s_as_vec2s, Mesh};
use crate::node::data::{
BlendMode, Composite, Drawable, InoxData, Mask, MaskMode, ParamMapMode, Part, PhysicsModel, PhysicsProps,
SimplePhysics, UnknownBlendModeError, UnknownMaskModeError,
SimplePhysics,
};
use crate::node::tree::InoxNodeTree;
use crate::node::{InoxNode, InoxNodeUuid};
use crate::params::{AxisPoints, Binding, BindingValues, Param, ParamUuid};
use crate::physics::runge_kutta::PhysicsState;
use crate::puppet::{
Puppet, PuppetAllowedModification, PuppetAllowedRedistribution, PuppetAllowedUsers, PuppetMeta, PuppetPhysics,
PuppetUsageRights, UnknownPuppetAllowedModificationError, UnknownPuppetAllowedRedistributionError,
UnknownPuppetAllowedUsersError,
PuppetUsageRights,
};
use crate::texture::TextureId;

Expand All @@ -39,18 +38,18 @@ pub enum InoxParseError {
NoAlbedoTexture,
#[error(transparent)]
InvalidMatrix2dData(#[from] Matrix2dFromSliceVecsError),
#[error(transparent)]
UnknownBlendMode(#[from] UnknownBlendModeError),
#[error(transparent)]
UnknownMaskMode(#[from] UnknownMaskModeError),
#[error(transparent)]
UnknownInterpolateMode(#[from] UnknownInterpolateModeError),
#[error(transparent)]
UnknownPuppetAllowedUsers(#[from] UnknownPuppetAllowedUsersError),
#[error(transparent)]
UnknownPuppetAllowedRedistribution(#[from] UnknownPuppetAllowedRedistributionError),
#[error(transparent)]
UnknownPuppetAllowedModification(#[from] UnknownPuppetAllowedModificationError),
#[error("Unknown param map mode {0:?}")]
UnknownParamMapMode(String),
#[error("Unknown mask mode {0:?}")]
UnknownMaskMode(String),
#[error("Unknown interpolate mode {0:?}")]
UnknownInterpolateMode(String),
#[error("Unknown allowed users {0:?}")]
UnknownPuppetAllowedUsers(String),
#[error("Unknown allowed redistribution {0:?}")]
UnknownPuppetAllowedRedistribution(String),
#[error("Unknown allowed modification {0:?}")]
UnknownPuppetAllowedModification(String),
#[error("Expected even number of floats in list, got {0}")]
OddNumberOfFloatsInList(usize),
#[error("Expected 2 floats in list, got {0}")]
Expand All @@ -70,6 +69,13 @@ fn vals<T>(key: &str, res: InoxParseResult<T>) -> InoxParseResult<T> {
res.map_err(|e| e.nested(key))
}

fn as_nested_list(index: usize, val: &json::JsonValue) -> InoxParseResult<&[json::JsonValue]> {
match val {
json::JsonValue::Array(arr) => Ok(arr),
_ => Err(InoxParseError::JsonError(JsonError::ValueIsNotList(index.to_string()))),
}
}

fn default_deserialize_custom<T>(node_type: &str, _obj: &JsonObject) -> InoxParseResult<T> {
Err(InoxParseError::UnknownNodeType(node_type.to_owned()))
}
Expand Down Expand Up @@ -152,53 +158,47 @@ fn deserialize_composite(obj: &JsonObject) -> InoxParseResult<Composite> {
}

fn deserialize_simple_physics(obj: &JsonObject) -> InoxParseResult<SimplePhysics> {
let param = ParamUuid(obj.get_u32("param")?);

let model_type = match obj.get_str("model_type")? {
"Pendulum" => PhysicsModel::RigidPendulum(PhysicsState::default()),
"SpringPendulum" => PhysicsModel::SpringPendulum(PhysicsState::default()),
a => todo!("{}", a),
};

let map_mode = match obj.get_str("map_mode")? {
"AngleLength" => ParamMapMode::AngleLength,
"XY" => ParamMapMode::XY,
a => todo!("{}", a),
};

let local_only = obj.get_bool("local_only").unwrap_or_default();

let gravity = obj.get_f32("gravity")?;
let length = obj.get_f32("length")?;
let frequency = obj.get_f32("frequency")?;
let angle_damping = obj.get_f32("angle_damping")?;
let length_damping = obj.get_f32("length_damping")?;
let output_scale = obj.get_vec2("output_scale")?;

Ok(SimplePhysics {
param,
param: ParamUuid(obj.get_u32("param")?),

model_type,
map_mode,
model_type: match obj.get_str("model_type")? {
"Pendulum" => PhysicsModel::RigidPendulum(PhysicsState::default()),
"SpringPendulum" => PhysicsModel::SpringPendulum(PhysicsState::default()),
a => todo!("{}", a),
},
map_mode: match obj.get_str("map_mode")? {
"AngleLength" => ParamMapMode::AngleLength,
"XY" => ParamMapMode::XY,
unknown => return Err(InoxParseError::UnknownParamMapMode(unknown.to_owned())),
},

props: PhysicsProps {
gravity,
length,
frequency,
angle_damping,
length_damping,
output_scale,
gravity: obj.get_f32("gravity")?,
length: obj.get_f32("length")?,
frequency: obj.get_f32("frequency")?,
angle_damping: obj.get_f32("angle_damping")?,
length_damping: obj.get_f32("length_damping")?,
output_scale: obj.get_vec2("output_scale")?,
},

local_only,
local_only: obj.get_bool("local_only").unwrap_or_default(),

bob: Vec2::ZERO,
})
}

fn deserialize_drawable(obj: &JsonObject) -> InoxParseResult<Drawable> {
Ok(Drawable {
blend_mode: BlendMode::try_from(obj.get_str("blend_mode").unwrap_or_default()).unwrap_or_default(),
blend_mode: match obj.get_str("blend_mode")? {
"Normal" => BlendMode::Normal,
"Multiply" => BlendMode::Multiply,
"ColorDodge" => BlendMode::ColorDodge,
"LinearDodge" => BlendMode::LinearDodge,
"Screen" => BlendMode::Screen,
"ClipToLower" => BlendMode::ClipToLower,
"SliceFromLower" => BlendMode::SliceFromLower,
_ => BlendMode::default(),
},
tint: obj.get_vec3("tint").unwrap_or(vec3(1.0, 1.0, 1.0)),
screen_tint: obj.get_vec3("screenTint").unwrap_or(vec3(0.0, 0.0, 0.0)),
mask_threshold: obj.get_f32("mask_threshold").unwrap_or(0.5),
Expand Down Expand Up @@ -232,21 +232,21 @@ fn deserialize_mesh(obj: &JsonObject) -> InoxParseResult<Mesh> {
fn deserialize_mask(obj: &JsonObject) -> InoxParseResult<Mask> {
Ok(Mask {
source: InoxNodeUuid(obj.get_u32("source")?),
mode: MaskMode::try_from(obj.get_str("mode")?)?,
mode: match obj.get_str("mode")? {
"Mask" => MaskMode::Mask,
"DodgeMask" => MaskMode::Dodge,
unknown => return Err(InoxParseError::UnknownMaskMode(unknown.to_owned())),
},
})
}

fn deserialize_transform(obj: &JsonObject) -> InoxParseResult<TransformOffset> {
let translation = obj.get_vec3("trans")?;
let rotation = obj.get_vec3("rot")?;
let scale = obj.get_vec2("scale")?;
let pixel_snap = obj.get_bool("pixel_snap").unwrap_or_default();

Ok(TransformOffset::new()
.with_translation(translation)
.with_rotation(rotation)
.with_scale(scale)
.with_pixel_snap(pixel_snap))
Ok(TransformOffset {
translation: obj.get_vec3("trans")?,
rotation: obj.get_vec3("rot")?,
scale: obj.get_vec2("scale")?,
pixel_snap: obj.get_bool("pixel_snap").unwrap_or_default(),
})
}

fn deserialize_f32s(val: &[json::JsonValue]) -> Vec<f32> {
Expand Down Expand Up @@ -353,7 +353,11 @@ fn deserialize_binding(obj: &JsonObject) -> InoxParseResult<Binding> {
Ok(Binding {
node: InoxNodeUuid(obj.get_u32("node")?),
is_set: Matrix2d::from_slice_vecs(&is_set, true)?,
interpolate_mode: InterpolateMode::try_from(obj.get_str("interpolate_mode")?)?,
interpolate_mode: match obj.get_str("interpolate_mode")? {
"Linear" => InterpolateMode::Linear,
"Nearest" => InterpolateMode::Nearest,
a => return Err(InoxParseError::UnknownInterpolateMode(a.to_owned())),
},
values: deserialize_binding_values(obj.get_str("param_name")?, obj.get_list("values")?)?,
})
}
Expand Down Expand Up @@ -395,13 +399,6 @@ fn deserialize_inner_binding_values(values: &[JsonValue]) -> Result<Matrix2d<f32
Matrix2d::from_slice_vecs(&values, true)
}

fn as_nested_list(index: usize, val: &json::JsonValue) -> InoxParseResult<&[json::JsonValue]> {
match val {
json::JsonValue::Array(arr) => Ok(arr),
_ => Err(InoxParseError::JsonError(JsonError::ValueIsNotList(index.to_string()))),
}
}

fn deserialize_axis_points(vals: &[json::JsonValue]) -> InoxParseResult<AxisPoints> {
let x = deserialize_f32s(as_nested_list(0, &vals[0])?);
let y = deserialize_f32s(as_nested_list(1, &vals[1])?);
Expand Down Expand Up @@ -491,12 +488,27 @@ fn deserialize_puppet_meta(obj: &JsonObject) -> InoxParseResult<PuppetMeta> {

fn deserialize_puppet_usage_rights(obj: &JsonObject) -> InoxParseResult<PuppetUsageRights> {
Ok(PuppetUsageRights {
allowed_users: PuppetAllowedUsers::try_from(obj.get_str("allowed_users")?)?,
allowed_users: match obj.get_str("allowed_users")? {
"OnlyAuthor" => PuppetAllowedUsers::OnlyAuthor,
"OnlyLicensee" => PuppetAllowedUsers::OnlyLicensee,
"Everyone" => PuppetAllowedUsers::Everyone,
unknown => return Err(InoxParseError::UnknownPuppetAllowedUsers(unknown.to_owned())),
},
allow_violence: obj.get_bool("allow_violence")?,
allow_sexual: obj.get_bool("allow_sexual")?,
allow_commercial: obj.get_bool("allow_commercial")?,
allow_redistribution: PuppetAllowedRedistribution::try_from(obj.get_str("allow_redistribution")?)?,
allow_modification: PuppetAllowedModification::try_from(obj.get_str("allow_modification")?)?,
allow_redistribution: match obj.get_str("allow_redistribution")? {
"Prohibited" => PuppetAllowedRedistribution::Prohibited,
"ViralLicense" => PuppetAllowedRedistribution::ViralLicense,
"CopyleftLicense" => PuppetAllowedRedistribution::CopyleftLicense,
unknown => return Err(InoxParseError::UnknownPuppetAllowedRedistribution(unknown.to_owned())),
},
allow_modification: match obj.get_str("allow_modification")? {
"Prohibited" => PuppetAllowedModification::Prohibited,
"AllowPersonal" => PuppetAllowedModification::AllowPersonal,
"AllowRedistribute" => PuppetAllowedModification::AllowRedistribute,
unknown => return Err(InoxParseError::UnknownPuppetAllowedModification(unknown.to_owned())),
},
require_attribution: obj.get_bool("require_attribution")?,
})
}
15 changes: 0 additions & 15 deletions inox2d/src/math/interp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,6 @@ pub enum InterpolateMode {
// there's more but I'm not adding them for now.
}

#[derive(Debug, Clone, thiserror::Error)]
#[error("Unknown interpolate mode {0:?}")]
pub struct UnknownInterpolateModeError(String);

impl TryFrom<&str> for InterpolateMode {
type Error = UnknownInterpolateModeError;

fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"Linear" => Ok(InterpolateMode::Linear),
unknown => Err(UnknownInterpolateModeError(unknown.to_owned())),
}
}
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct InterpRange<T> {
pub beg: T,
Expand Down
24 changes: 0 additions & 24 deletions inox2d/src/math/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,6 @@ impl Default for TransformOffset {
}

impl TransformOffset {
pub fn new() -> Self {
Self::default()
}

pub fn with_translation(mut self, translation: Vec3) -> Self {
self.translation = translation;
self
}

pub fn with_rotation(mut self, rotation: Vec3) -> Self {
self.rotation = rotation;
self
}

pub fn with_scale(mut self, scale: Vec2) -> Self {
self.scale = scale;
self
}

pub fn with_pixel_snap(mut self, pixel_snap: bool) -> Self {
self.pixel_snap = pixel_snap;
self
}

pub fn to_matrix(&self) -> Mat4 {
Mat4::from_translation(self.translation)
* Mat4::from_quat(Quat::from_euler(
Expand Down
37 changes: 0 additions & 37 deletions inox2d/src/node/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,27 +46,6 @@ impl BlendMode {
];
}

#[derive(Debug, Clone, thiserror::Error)]
#[error("Unknown blend mode {0:?}")]
pub struct UnknownBlendModeError(String);

impl TryFrom<&str> for BlendMode {
type Error = UnknownBlendModeError;

fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"Normal" => Ok(BlendMode::Normal),
"Multiply" => Ok(BlendMode::Multiply),
"ColorDodge" => Ok(BlendMode::ColorDodge),
"LinearDodge" => Ok(BlendMode::LinearDodge),
"Screen" => Ok(BlendMode::Screen),
"ClipToLower" => Ok(BlendMode::ClipToLower),
"SliceFromLower" => Ok(BlendMode::SliceFromLower),
unknown => Err(UnknownBlendModeError(unknown.to_owned())),
}
}
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MaskMode {
/// The part should be masked by the drawables specified.
Expand All @@ -75,22 +54,6 @@ pub enum MaskMode {
Dodge,
}

#[derive(Debug, Clone, thiserror::Error)]
#[error("Unknown mask mode {0:?}")]
pub struct UnknownMaskModeError(String);

impl TryFrom<&str> for MaskMode {
type Error = UnknownMaskModeError;

fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"Mask" => Ok(MaskMode::Mask),
"DodgeMask" => Ok(MaskMode::Dodge),
unknown => Err(UnknownMaskModeError(unknown.to_owned())),
}
}
}

#[derive(Debug, Clone, PartialEq)]
pub struct Mask {
pub source: InoxNodeUuid,
Expand Down
2 changes: 1 addition & 1 deletion inox2d/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,4 +242,4 @@ impl Puppet {

Ok(())
}
}
}
Loading