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

122 lines
2.7 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 r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
impl Color {
pub const WHITE: Self = Self::new(1., 1., 1., 1.);
pub const BLACK: Self = Self::new(0., 0., 0., 1.);
pub const TRANSPARENT: Self = Self::new(0., 0., 0., 0.);
pub const RED: Self = Self::new(1., 0., 0., 1.);
pub const GREEN: Self = Self::new(0., 1., 0., 1.);
pub const BLUE: Self = Self::new(0., 0., 1., 1.);
pub const YELLOW: Self = Self::new(1., 1., 0., 1.);
pub const MAGENTA: Self = Self::new(1., 0., 1., 1.);
pub const CYAN: Self = Self::new(0., 1., 1., 1.);
pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
Self { r, g, b, a }
}
pub fn to_rgba_unmultiplied(&self) -> (u8, u8, u8, u8) {
let map = |c: f32| (c * 255.0).floor() as u8;
(map(self.r), map(self.g), map(self.b), map(self.a))
}
}
#[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 {
Self::new(other.x, other.y, other.z, other.w)
}
}
impl From<Color> for glam::Vec4 {
fn from(other: Color) -> Self {
let Color { r, g, b, a } = other;
Self::new(r, g, b, a)
}
}
}