marble-machinations/src/util.rs

103 lines
2 KiB
Rust
Raw Normal View History

2024-10-04 21:20:53 +02:00
use raylib::prelude::*;
pub fn text_input(
d: &mut RaylibDrawHandle,
bounds: Rectangle,
text: &mut String,
is_selected: &mut bool,
) -> bool {
let mut changed = false;
let (bg, border) = if *is_selected {
(Color::DARKCYAN, Color::CYAN)
} else {
(Color::GRAY, Color::DIMGRAY)
};
d.draw_rectangle_rec(bounds, border);
d.draw_rectangle_rec(shrink_rec(bounds, 2.), bg);
d.draw_text(
text,
bounds.x as i32 + 4,
bounds.y as i32 + 4,
2024-10-05 15:19:27 +02:00
20,
2024-10-04 21:20:53 +02:00
Color::WHITE,
);
let mouse_pos = d.get_mouse_position();
if d.is_mouse_button_pressed(MouseButton::MOUSE_BUTTON_LEFT)
&& (bounds.check_collision_point_rec(mouse_pos) || *is_selected)
{
*is_selected = !*is_selected;
}
if *is_selected {
if d.is_key_pressed(KeyboardKey::KEY_ESCAPE) {
*is_selected = false;
}
2024-10-04 21:20:53 +02:00
if d.is_key_pressed(KeyboardKey::KEY_BACKSPACE) {
changed = true;
text.pop();
}
let char_code = unsafe { ffi::GetCharPressed() };
let c = if char_code > 0 {
char::from_u32(char_code as u32)
} else {
None
};
if let Some(c) = c {
changed = true;
text.push(c);
}
}
changed
}
2024-10-05 15:19:27 +02:00
pub fn texture_button<T>(
d: &mut RaylibDrawHandle,
pos: Vector2,
texture: Option<&Texture2D>,
option: T,
current: &mut T,
tex_size: f32,
border: f32,
// tooltip
) where
T: PartialEq,
{
let color = if &option == current {
Color::DARKCYAN
} else {
Color::GRAY
};
let bounds = Rectangle {
x: pos.x,
y: pos.y,
width: tex_size + border * 2.,
height: tex_size + border * 2.,
};
d.draw_rectangle_rec(bounds, color);
if let Some(texture) = texture {
d.draw_texture_ex(
texture,
pos + Vector2::new(border, border),
0.,
tex_size / texture.width as f32,
Color::WHITE,
);
}
let mouse_pos = d.get_mouse_position();
if d.is_mouse_button_pressed(MouseButton::MOUSE_BUTTON_LEFT)
&& bounds.check_collision_point_rec(mouse_pos)
{
*current = option;
}
}
2024-10-04 21:20:53 +02:00
pub fn shrink_rec(rec: Rectangle, a: f32) -> Rectangle {
Rectangle {
x: rec.x + a,
y: rec.y + a,
width: rec.width - a * 2.,
height: rec.height - a * 2.,
}
}