add support for vectors as operands to math operations

This commit is contained in:
りき萌 2024-10-22 21:58:17 +02:00
parent 5b7d9586ea
commit 37c575748b
2 changed files with 131 additions and 14 deletions

View file

@ -178,6 +178,8 @@ macro_rules! def_fns {
}
pub mod fns {
use core::ops::{Add, Div, Mul, Sub};
use alloc::{format, vec::Vec};
use crate::{
@ -261,33 +263,48 @@ pub mod fns {
}
}
fn binary_math_op(
vm: &mut Vm,
args: FnArgs,
on_number_number: fn(f32, f32) -> f32,
on_vec_vec: fn(Vec4, Vec4) -> Vec4,
) -> Result<Value, Exception> {
static WRONG_ARG: &str = "arguments to binary math operators may be numbers, vecs, or rgba, and must be of the same type";
match args.get(vm, 0) {
Value::Number(x) => Ok(Value::Number(on_number_number(
x,
args.get_number(vm, 1, WRONG_ARG)?,
))),
Value::Vec4(x) => Ok(Value::Vec4(on_vec_vec(x, args.get_vec4(vm, 1, WRONG_ARG)?))),
Value::Rgba(x) => Ok(Value::Rgba(
on_vec_vec(x.into(), args.get_rgba(vm, 1, WRONG_ARG)?.into()).into(),
)),
_ => Err(vm.create_exception(WRONG_ARG)),
}
}
pub fn add(vm: &mut Vm, args: FnArgs) -> Result<Value, Exception> {
let a = args.get_number(vm, 0, "arguments to `+` must be numbers")?;
let b = args.get_number(vm, 1, "arguments to `+` must be numbers")?;
Ok(Value::Number(a + b))
binary_math_op(vm, args, <f32 as Add>::add, <Vec4 as Add>::add)
}
pub fn sub(vm: &mut Vm, args: FnArgs) -> Result<Value, Exception> {
let a = args.get_number(vm, 0, "arguments to `-` must be numbers")?;
let b = args.get_number(vm, 1, "arguments to `-` must be numbers")?;
Ok(Value::Number(a - b))
binary_math_op(vm, args, <f32 as Sub>::sub, <Vec4 as Sub>::sub)
}
pub fn mul(vm: &mut Vm, args: FnArgs) -> Result<Value, Exception> {
let a = args.get_number(vm, 0, "arguments to `*` must be numbers")?;
let b = args.get_number(vm, 1, "arguments to `*` must be numbers")?;
Ok(Value::Number(a * b))
binary_math_op(vm, args, <f32 as Mul>::mul, <Vec4 as Mul>::mul)
}
pub fn div(vm: &mut Vm, args: FnArgs) -> Result<Value, Exception> {
let a = args.get_number(vm, 0, "arguments to `/` must be numbers")?;
let b = args.get_number(vm, 1, "arguments to `/` must be numbers")?;
Ok(Value::Number(a / b))
binary_math_op(vm, args, <f32 as Div>::div, <Vec4 as Div>::div)
}
pub fn neg(vm: &mut Vm, args: FnArgs) -> Result<Value, Exception> {
let x = args.get_number(vm, 0, "`-` can only work with numbers")?;
Ok(Value::Number(-x))
match args.get(vm, 0) {
Value::Number(x) => Ok(Value::Number(-x)),
Value::Vec4(x) => Ok(Value::Vec4(-x)),
_ => Err(vm.create_exception("`-` can only work with numbers and vectors")),
}
}
#[inline(never)]