canary-rs/crates/types/src/lib.rs

133 lines
3.1 KiB
Rust

// Copyright (c) 2022 Marceline Cramer
// SPDX-License-Identifier: Apache-2.0
#[macro_use]
extern crate num_derive;
use bytemuck::{Pod, Zeroable};
pub use num_traits;
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Pod, Zeroable)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Vec2 {
pub const INFINITY: Self = Self {
x: f32::INFINITY,
y: f32::INFINITY,
};
pub const NEG_INFINITY: Self = Self {
x: f32::NEG_INFINITY,
y: f32::NEG_INFINITY,
};
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct Color(pub u32);
impl Color {
pub const WHITE: Self = Self(0xffffffff);
pub const BLACK: Self = Self(0x000000ff);
pub const TRANSPARENT: Self = Self(0);
pub const RED: Self = Self(0xff0000ff);
pub const GREEN: Self = Self(0x00ff00ff);
pub const BLUE: Self = Self(0x0000ffff);
pub const YELLOW: Self = Self(0xffff00ff);
pub const MAGENTA: Self = Self(0xff00ffff);
pub const CYAN: Self = Self(0x00ffffff);
pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
Color(((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | (a as u32))
}
pub fn to_rgba_unmultiplied(&self) -> (u8, u8, u8, u8) {
(
(self.0 >> 24) as u8,
(self.0 >> 16) as u8,
(self.0 >> 8) as u8,
self.0 as u8,
)
}
pub fn alpha_multiply(&self, mul: u8) -> Self {
let a = self.0 as u8 as u16;
let multiplied = ((a * (mul as u16)) >> 8) as u8;
self.with_alpha(multiplied)
}
pub fn with_alpha(&self, alpha: u8) -> Self {
Self(self.0 & 0xffffff00 | alpha as u32)
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct MeshVertex {
pub position: Vec2,
pub color: Color,
}
pub type MeshIndex = u32;
#[derive(Copy, Clone, Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
pub enum CursorEventKind {
Hover = 0,
Select = 1,
Drag = 2,
Deselect = 3,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Pod, Zeroable)]
pub struct Rect {
pub bl: Vec2,
pub tr: Vec2,
}
impl Rect {
pub const NEG_INFINITY: Self = Self {
bl: Vec2::INFINITY,
tr: Vec2::NEG_INFINITY,
};
}
#[cfg(feature = "glam")]
mod glam_interop {
use super::*;
impl From<glam::Vec2> for Vec2 {
fn from(other: glam::Vec2) -> Self {
Self {
x: other.x,
y: other.y,
}
}
}
impl From<Vec2> for glam::Vec2 {
fn from(other: Vec2) -> Self {
Self::new(other.x, other.y)
}
}
impl From<glam::Vec4> for Color {
fn from(other: glam::Vec4) -> Self {
let map = |v: f32| (v * 255.0).floor() as u8;
Self::new(map(other.x), map(other.y), map(other.z), map(other.w))
}
}
impl From<Color> for glam::Vec4 {
fn from(other: Color) -> Self {
let (r, g, b, a) = other.to_rgba_unmultiplied();
let map = |v: u8| (v as f32) / 255.0;
Self::new(map(r), map(g), map(b), map(a))
}
}
}