use glfw::{Action, Context, MouseButton};
use std::collections::HashSet;
mod shader;
use shader as sdr;
mod texture;
mod objects;
use objects as obj;
pub type Rec = obj::Rec;
pub type Img = obj::Image;
pub type Text = obj::Text;
pub type KeyBoard = glfw::Key;
pub type Font = freetype::Face;
pub struct Gluie {
pub window: glfw::PWindow,
pub events: glfw::GlfwReceiver<(f64, glfw::WindowEvent)>,
pub glfw_init: glfw::Glfw,
event_buffer: Vec<glfw::WindowEvent>,
pub shape_shader: Option<u32>,
pub image_shader: Option<u32>,
pub font_shader: Option<u32>,
pub rec_uniform_window_size: i32,
pub rec_uniform_color: i32,
pub rec_uniform_cord: i32,
pub image_uniform_window_size: i32,
pub image_uniform_img: i32,
pub image_uniform_cord: i32,
pub font_uniform_window_size: i32,
pub font_uniform_color: i32,
pub font_uniform_cord: i32,
lib: freetype::Library,
input: std::rc::Rc<std::cell::RefCell<String>>,
pub font_size: u32,
pub font_texture_atlas: u32,
called_draw_rec: bool,
called_draw_img: bool,
called_draw_text: bool,
have_rec_shader: bool,
have_img_shader: bool,
have_text_shader: bool,
}
impl Gluie {
pub fn new(size: (u32, u32), name: &str) -> Gluie {
let mut glfw_init = glfw::init(glfw::fail_on_errors).unwrap();
let (mut window, events) = glfw_init
.create_window(size.0, size.1, name, glfw::WindowMode::Windowed)
.unwrap();
window.make_current();
glfw_init.set_swap_interval(glfw::SwapInterval::None);
window.set_key_polling(true);
gl::load_with(|symbol| {
window
.get_proc_address(symbol)
.map_or(std::ptr::null(), |p| p as *const _)
});
unsafe {
gl::Enable(gl::BLEND);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
}
Gluie {
window: window,
events: events,
event_buffer: Vec::new(),
glfw_init: glfw_init,
shape_shader: None,
image_shader: None,
font_shader: None,
rec_uniform_window_size: 0,
rec_uniform_color: 0,
rec_uniform_cord: 0,
image_uniform_window_size: 0,
image_uniform_img: 0,
image_uniform_cord: 0,
font_uniform_window_size: 0,
font_uniform_color: 0,
font_uniform_cord: 0,
lib: freetype::Library::init().unwrap(),
input: std::rc::Rc::new(std::cell::RefCell::new(String::new())),
font_size: 0,
font_texture_atlas: 0,
called_draw_rec: false,
called_draw_img: false,
called_draw_text: false,
have_rec_shader: false,
have_img_shader: false,
have_text_shader: false,
}
}
pub fn show(&mut self) {
self.window.swap_buffers();
}
pub fn click_exit(&self) -> bool {
for event in &self.event_buffer {
match event {
glfw::WindowEvent::Close => return true,
_ => {}
}
}
false
}
pub fn should_close(&self) -> bool{
self.window.should_close()
}
pub fn set_should_close(&mut self){
self.window.set_should_close(true);
}
pub fn resized(&self) -> bool {
for event in &self.event_buffer {
match event {
glfw::WindowEvent::Size(_, _) => return false,
_ => {}
}
}
true
}
pub fn flush_event(&mut self) {
self.event_buffer.clear();
self.glfw_init.poll_events();
for (_, event) in glfw::flush_messages(&self.events) {
self.event_buffer.push(event);
}
}
pub fn set_screen_color(&self, r: u8, g: u8, b: u8) {
unsafe {
gl::ClearColor(
(r as f32) / 255.0,
(g as f32) / 255.0,
(b as f32) / 255.0,
1.0,
);
gl::Clear(gl::COLOR_BUFFER_BIT);
};
}
pub fn window_size(&self) -> (u32, u32) {
let (x, y) = self.window.get_size();
(x as u32, y as u32)
}
pub fn set_window_size(&mut self, w: u32, h: u32) {
self.window.set_size(w as i32, h as i32);
}
pub fn update_view(&mut self) {
if self.resized() {
let (x, y) = self.window_size();
unsafe { gl::Viewport(0, 0, x as i32, y as i32) };
unsafe {
match self.shape_shader {
Some(d) => {
gl::UseProgram(d);
gl::Uniform2f(self.rec_uniform_window_size, x as f32, y as f32);
}
None => {}
}
match self.image_shader {
Some(d) => {
gl::UseProgram(d);
gl::Uniform2f(self.image_uniform_window_size, x as f32, y as f32);
}
None => {}
}
match self.font_shader {
Some(d) => {
gl::UseProgram(d);
gl::Uniform2f(self.font_uniform_window_size, x as f32, y as f32);
}
None => {}
}
};
}
}
pub fn mouse_cord(&self) -> (u32, u32) {
let (x, y) = self.window.get_cursor_pos();
(x as u32, y as u32)
}
pub fn mouse_button(&self, button: u8) -> bool {
let button = match button {
1 => MouseButton::Button1,
2 => MouseButton::Button2,
3 => MouseButton::Button3,
4 => MouseButton::Button4,
5 => MouseButton::Button5,
6 => MouseButton::Button6,
7 => MouseButton::Button7,
8 => MouseButton::Button8,
_ => return false,
};
self.window.get_mouse_button(button) == Action::Press
}
pub fn mouse_scroll(&self, x: &mut f32, y: &mut f32) {
for event in &self.event_buffer {
match event {
glfw::WindowEvent::Scroll(xoff, yoff) => {
*x = *xoff as f32;
*y = *yoff as f32;
return;
}
_ => {}
}
}
*x = 0.0;
*y = 0.0;
}
pub fn key_down(&self, keys: &mut HashSet<KeyBoard>) {
keys.clear();
for event in &self.event_buffer {
if let glfw::WindowEvent::Key(key, _, glfw::Action::Press, _) = *event {
keys.insert(key as KeyBoard);
}
}
}
pub fn key_repeat(&self, keys: &mut HashSet<KeyBoard>) {
keys.clear();
for event in &self.event_buffer {
if let glfw::WindowEvent::Key(key, _, glfw::Action::Repeat, _) = *event {
keys.insert(key as KeyBoard);
}
}
}
pub fn key_floud(&self, keys: &mut HashSet<KeyBoard>) {
for event in &self.event_buffer {
if let glfw::WindowEvent::Key(key, _, glfw::Action::Press, _) = *event {
keys.insert(key as KeyBoard);
}
}
}
pub fn key_user(&self, keys: &mut HashSet<KeyBoard>) {
keys.clear();
for event in &self.event_buffer {
if let glfw::WindowEvent::Key(key, _, glfw::Action::Press | glfw::Action::Repeat, _) =
*event
{
keys.insert(key as KeyBoard);
}
}
}
pub fn key_char_init(&mut self) {
let input_clone = std::rc::Rc::clone(&self.input);
self.window.set_char_callback(move |_, ch| {
input_clone.borrow_mut().push(ch);
});
}
pub fn key_char(&self) -> String {
let data = self.input.borrow().to_string();
self.input.borrow_mut().clear();
data
}
pub fn link_rec_shader(&mut self, vertex_source: &str, fragment_source: &str) -> Option<String> {
self.shape_shader = match sdr::create_program(vertex_source, fragment_source) {
Ok(data) => Some(data),
Err(e) => return Some(e),
};
self.rec_uniform_window_size = unsafe {
gl::GetUniformLocation(self.shape_shader.unwrap_unchecked(), c"winsize".as_ptr())
};
self.rec_uniform_color = unsafe {
gl::GetUniformLocation(self.shape_shader.unwrap_unchecked(), c"color".as_ptr())
};
self.rec_uniform_cord = unsafe {
gl::GetUniformLocation(self.shape_shader.unwrap_unchecked(), c"cord".as_ptr())
};
self.have_rec_shader = true;
None
}
pub fn build_rec(&self, x: u32, y: u32, w: u32, h: u32, r: u8, g: u8, b: u8) -> Rec {
let mut rec = obj::Rec::new(x, y, w, h, r, g, b);
rec.create_struct();
rec
}
pub fn change_rec_size(&self, w: u32, h: u32, rec: &mut Rec) {
rec.change_size(w, h);
}
pub fn change_rec_color(&self, r: u8, g: u8, b: u8, rec: &mut Rec){
rec.change_color(r, g, b);
}
pub fn change_rec_cords(&self, x: u32, y: u32, rec: &mut Rec){
rec.change_cord(x, y);
}
pub fn draw_rec(&mut self, object: &Rec) {
if !self.have_rec_shader{
return;
}
unsafe {
if !self.called_draw_rec{
gl::UseProgram(self.shape_shader.unwrap());
self.called_draw_img = false;
self.called_draw_text = false;
self.called_draw_rec = true;
}
gl::Uniform3ui(
self.rec_uniform_color,
object.mr as u32,
object.mg as u32,
object.mb as u32,
);
gl::Uniform2ui(
self.rec_uniform_cord,
object.mx,
object.my
);
gl::BindVertexArray(object.vao);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
}
}
pub fn mouse_hover_rec(&self, rec: &Rec) -> bool {
let (x, y) = self.mouse_cord();
if rec.mx <= x && rec.mx + rec.mw >= x && rec.my <= y && rec.my + rec.mh >= y {
return true;
}
false
}
pub fn mouse_click_rec(&self, rec: &Rec, button: u8) -> bool {
if self.mouse_hover_rec(rec) && self.mouse_button(button) {
return true;
}
false
}
pub fn link_img_shader(&mut self, vertex_source: &str, fragment_source: &str) -> Option<String> {
self.image_shader = match sdr::create_program(vertex_source, fragment_source) {
Ok(data) => Some(data),
Err(e) => return Some(e),
};
self.image_uniform_window_size = unsafe {
gl::GetUniformLocation(self.image_shader.unwrap_unchecked(), c"winsize".as_ptr())
};
self.image_uniform_img = unsafe {
gl::GetUniformLocation(self.image_shader.unwrap_unchecked(), c"image".as_ptr())
};
unsafe { gl::Uniform1i(self.image_uniform_img, 0); }
self.image_uniform_cord = unsafe {
gl::GetUniformLocation(self.image_shader.unwrap_unchecked(), c"cord".as_ptr())
};
self.have_img_shader = true;
None
}
pub fn build_img(
&self,
w: u32,
h: u32,
x: u32,
y: u32,
image: (Vec<u8>, u32, u32),
) -> Img {
let mut img = Img::new(w, h, x, y, image);
img.create_struct();
img
}
pub fn change_img_size(&self, w: u32, h: u32, img: &mut Img){
img.change_size(w, h);
}
pub fn change_img_img(&self, image: (Vec<u8>, u32, u32), img: &mut Img){
img.change_img(image);
}
pub fn change_img_cords(&self, x: u32, y: u32, img: &mut Img){
img.change_cord(x, y);
}
pub fn draw_img(&mut self, object: &Img) {
if !self.have_img_shader{
return;
}
unsafe {
if !self.called_draw_img{
gl::UseProgram(self.image_shader.unwrap_unchecked());
self.called_draw_img = true;
self.called_draw_text = false;
self.called_draw_rec = false;
}
gl::ActiveTexture(gl::TEXTURE0);
gl::BindTexture(gl::TEXTURE_2D, object.image);
gl::Uniform2ui(
self.image_uniform_cord,
object.mx,
object.my
);
gl::BindVertexArray(object.vao);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
}
}
pub fn mouse_hover_img(&self, img: &Img) -> bool {
let (x, y) = self.mouse_cord();
if img.mx <= x && img.mx + img.mw >= x && img.my <= y && img.my + img.mh >= y {
return true;
}
false
}
pub fn mouse_click_img(&self, img: &Img, button: u8) -> bool {
if self.mouse_hover_img(img) && self.mouse_button(button) {
return true;
}
false
}
pub fn link_font_shader(&mut self, vertex_source: &str, fragment_source: &str) -> Option<String> {
self.font_shader = match sdr::create_program(vertex_source, fragment_source) {
Ok(data) => Some(data),
Err(e) => return Some(e),
};
unsafe { gl::UseProgram(self.font_shader.unwrap_unchecked()) };
self.font_uniform_window_size = unsafe {
gl::GetUniformLocation(self.font_shader.unwrap_unchecked(), c"winsize".as_ptr())
};
self.font_uniform_color = unsafe {
gl::GetUniformLocation(self.font_shader.unwrap_unchecked(), c"color".as_ptr())
};
self.font_uniform_cord = unsafe {
gl::GetUniformLocation(self.font_shader.unwrap_unchecked(), c"cord".as_ptr())
};
let font_uniform_atlas = unsafe {
gl::GetUniformLocation(self.font_shader.unwrap_unchecked(), c"atlas".as_ptr())
};
self.have_text_shader = true;
texture::gen_texture(&mut self.font_texture_atlas);
unsafe{
gl::TexImage2D(
gl::TEXTURE_2D,
0,
gl::R8 as i32,
2048,
2048,
0,
gl::RED,
gl::UNSIGNED_BYTE,
std::ptr::null(),
);
gl::BindTexture(gl::TEXTURE_2D, self.font_texture_atlas);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_MIN_FILTER,
gl::NEAREST as i32,
);
gl::TexParameteri(
gl::TEXTURE_2D,
gl::TEXTURE_MAG_FILTER,
gl::NEAREST as i32,
);
}
unsafe { gl::Uniform1i(font_uniform_atlas, 0); }
None
}
pub fn load_font(&self, font_path: &str, size: u32) -> Font {
let face = self.lib.new_face(font_path, 0).unwrap();
face.set_pixel_sizes(0, size).unwrap();
face
}
pub fn build_char(&self, ch: char, font: &Font, x: u32, y: u32, r: u8, g: u8, b: u8) -> Text {
font.load_char(ch as usize, freetype::face::LoadFlag::RENDER)
.unwrap();
let glyph = font.glyph();
let bitmap = glyph.bitmap();
let aw = (glyph.advance().x >> 6) as u32;
let ah = (glyph.advance().y >> 6) as u32;
let w = bitmap.width() as usize;
let h = bitmap.rows() as usize;
let pitch = bitmap.pitch();
let stride = pitch.unsigned_abs() as usize;
let buffer = bitmap.buffer();
let mut pixels = vec![0u8; w * h];
for y in 0..h {
let src_y = if pitch >= 0 { y } else { h - 1 - y };
let src = src_y * stride;
pixels[y * w..(y + 1) * w].copy_from_slice(&buffer[src..src + w]);
}
let left = glyph.bitmap_left();
let size_metric = font.size_metrics();
let (mut text, uv1, uv2) = Text::new(
w as u32,
h as u32,
aw as u32,
ah as u32,
(x as i32 + left).max(0) as u32,
(y as i32 + (size_metric.unwrap().ascender >> 6) as i32 - glyph.bitmap_top()) as u32,
&pixels,
r,
g,
b,
ch,
self.font_texture_atlas,
(size_metric.unwrap().height >> 6) as u32
);
text.create_struct((uv1, uv2));
text
}
pub fn get_char_size(&self, ch: char, font: &Font) -> (u32, u32){
font.load_char(ch as usize, freetype::face::LoadFlag::RENDER)
.unwrap();
let glyph = font.glyph();
((glyph.advance().x >> 6) as u32, (glyph.advance().y >> 6) as u32)
}
pub fn change_text_color(&self, r: u8, g: u8, b: u8, text: &mut Text){
text.change_color(r, g, b);
}
pub fn change_text_cord(&self, x: u32, y: u32, text: &mut Text){
text.chage_cord(x, y);
}
pub fn draw_char(&mut self, object: &Text) {
if !self.have_text_shader{
return;
}
unsafe {
if !self.called_draw_text{
gl::UseProgram(self.font_shader.unwrap());
self.called_draw_img = false;
self.called_draw_text = true;
self.called_draw_rec = false;
}
gl::Uniform3ui(
self.font_uniform_color,
object.mr as u32,
object.mg as u32,
object.mb as u32,
);
gl::ActiveTexture(gl::TEXTURE0);
gl::BindTexture(gl::TEXTURE_2D, self.font_texture_atlas);
gl::Uniform2ui(
self.font_uniform_cord,
object.mx,
object.my
);
gl::BindVertexArray(object.vao);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
}
}
}
pub fn get_text_size(ch: &Text) -> (u32, u32) {
(ch.maw, ch.mah)
}
pub fn load_image(path: &str) -> Result<(Vec<u8>, u32, u32), String> {
let image = match image::open(path) {
Ok(data) => data,
Err(err) => return Err(err.to_string()),
}
.to_rgba8();
Ok((image.clone().into_raw(), image.width(), image.height()))
}
pub fn rec_basic_vertex() -> &'static str {
"
#version 330 core
layout(location = 0) in uvec2 structure;
uniform uvec2 cord;
uniform uvec3 color;
uniform vec2 winsize;
out vec3 aColor;
void main() {
uvec2 point = structure + cord;
vec2 pos = vec2(point) / winsize;
pos.y = 1.0 - pos.y;
gl_Position = vec4(pos * 2.0 - 1.0, 0.0, 1.0);
aColor = vec3(color) / 255.0;
}
"
}
pub fn rec_basic_fragment() -> &'static str {
"
#version 330 core
in vec3 aColor;
out vec4 color;
void main(){
color = vec4(aColor, 1);
}
"
}
pub fn img_basic_vertex() -> &'static str {
"
#version 330 core
layout(location = 0) in uvec2 structure;
layout(location = 1) in uvec2 uv;
uniform vec2 winsize;
uniform uvec2 cord;
out vec2 aUV;
void main(){
uvec2 point = cord + structure;
vec2 pos = vec2(point) / winsize;
pos.y = 1 - pos.y;
gl_Position = vec4(pos * vec2(2, 2) - vec2(1, 1), 0, 1);
aUV = vec2(uv);
}
"
}
pub fn img_basic_fragment() -> &'static str {
"
#version 330 core
in vec2 aUV;
uniform sampler2D image;
out vec4 color;
void main(){
color = texture(image, aUV);
}
"
}
pub fn font_basic_vertex() -> &'static str {
"
#version 330 core
layout(location = 0) in uvec2 structure;
layout(location = 1) in vec2 uv;
uniform vec2 winsize;
uniform uvec2 cord;
out vec2 aUV;
void main(){
uvec2 point = cord + structure;
vec2 pos = vec2(point) / winsize;
pos.y = 1 - pos.y;
gl_Position = vec4(pos * vec2(2, 2) - vec2(1, 1), 0, 1);
aUV = vec2(uv);
}
"
}
pub fn font_basic_fragment() -> &'static str {
"
#version 330 core
in vec2 aUV;
uniform sampler2D atlas;
uniform uvec3 color;
out vec4 acolor;
void main() {
float alpha = texture(atlas, aUV).r;
vec3 rgb = vec3(color) / 255.0;
acolor = vec4(rgb, alpha);
}
"
}