use ggez::event;
use ggez::graphics::{self, Color};
use ggez::timer;
use ggez::{Context, GameResult};
use glam::*;
use oorandom::Rand32;
use std::env;
use std::f32::consts::PI;
use std::path;
const TWO_PI: f32 = 2.0 * PI;
struct MainState {
mesh_batch: graphics::MeshBatch,
}
impl MainState {
fn new(ctx: &mut Context) -> GameResult<MainState> {
let mut rng = Rand32::new(12345);
let mesh = graphics::MeshBuilder::new()
.circle(
graphics::DrawMode::stroke(4.0),
Vec2::new(0.0, 0.0),
8.0,
1.0,
(0, 0, 255).into(),
)?
.line(
&[Vec2::new(0.0, 0.0), Vec2::new(8.0, 0.0)],
2.0,
(255, 255, 0).into(),
)?
.build(ctx)?;
let mut mesh_batch = graphics::MeshBatch::new(mesh)?;
let items_x = (graphics::drawable_size(ctx).0 / 16.0) as u32;
let items_y = (graphics::drawable_size(ctx).1 / 16.0) as u32;
for x in 1..items_x {
for y in 1..items_y {
let x = x as f32;
let y = y as f32;
let p = graphics::DrawParam::new()
.dest(Vec2::new(x * 16.0, y * 16.0))
.rotation(rng.rand_float() * TWO_PI);
mesh_batch.add(p);
}
}
mesh_batch.get_instance_params_mut();
let s = MainState { mesh_batch };
Ok(s)
}
}
impl event::EventHandler<ggez::GameError> for MainState {
#[allow(clippy::needless_range_loop)]
fn update(&mut self, ctx: &mut Context) -> GameResult {
if timer::ticks(ctx) % 100 == 0 {
println!("Delta frame time: {:?} ", timer::delta(ctx));
println!("Average FPS: {}", timer::fps(ctx));
}
let delta_time = (timer::duration_to_f64(timer::delta(ctx)) * 1000.0) as f32;
let instances = self.mesh_batch.get_instance_params_mut();
for i in 0..50 {
if let graphics::Transform::Values {
ref mut rotation, ..
} = instances[i].trans
{
if (i % 2) == 0 {
*rotation += 0.001 * TWO_PI * delta_time;
if *rotation > TWO_PI {
*rotation -= TWO_PI;
}
} else {
*rotation -= 0.001 * TWO_PI * delta_time;
if *rotation < 0.0 {
*rotation += TWO_PI;
}
}
}
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
graphics::clear(ctx, Color::BLACK);
self.mesh_batch.flush_range(ctx, graphics::MeshIdx(0), 50)?;
self.mesh_batch.draw(ctx, graphics::DrawParam::default())?;
graphics::present(ctx)?;
Ok(())
}
}
pub fn main() -> GameResult {
let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let mut path = path::PathBuf::from(manifest_dir);
path.push("resources");
path
} else {
path::PathBuf::from("./resources")
};
let cb = ggez::ContextBuilder::new("spritebatch", "ggez").add_resource_path(resource_dir);
let (mut ctx, event_loop) = cb.build()?;
let state = MainState::new(&mut ctx)?;
event::run(ctx, event_loop, state)
}