Change table type of subplate_automation

This commit is contained in:
2026-06-27 10:37:45 +03:00
parent 74f01cf895
commit fabc03b701
5 changed files with 155 additions and 40 deletions
+18
View File
@@ -134,6 +134,24 @@ impl IntoImage for Table<Color> {
} }
} }
impl IntoImage for Table<u8> {
fn get_image_data(&self) -> Vec<u8> {
let mut data: Vec<u8> = vec![0; self.side * self.side * 4];
self.data
.iter()
.zip((0..self.data.len()).collect::<Vec<_>>())
.for_each(|(color, idx)| {
let idx = idx * 4;
data[idx] = *color;
data[idx + 1] = *color;
data[idx + 2] = *color;
data[idx + 3] = if *color != 0 { 255 } else { 0 };
});
data
}
}
impl<T: Clone> Index<usize> for Table<T> { impl<T: Clone> Index<usize> for Table<T> {
type Output = T; type Output = T;
+32 -9
View File
@@ -1,16 +1,15 @@
pub struct HexTable { pub struct HexTable {
len: usize, len: usize,
scale: f32,
} }
const VERTICAL_OFFSET: f32 = 0.866025; const VERTICAL_OFFSET: f32 = 0.866025;
impl HexTable { impl HexTable {
pub fn new(len: usize) -> Self{ pub fn new(len: usize, scale: f32) -> Self {
Self{ Self { len, scale }
len
}
} }
pub fn calculate(&self) -> Vec<(f32, f32)>{ pub fn calculate(&self) -> Vec<(f32, f32)> {
let mut vec = Vec::with_capacity(self.len * self.len); let mut vec = Vec::with_capacity(self.len * self.len);
let mut index = 0; let mut index = 0;
loop { loop {
@@ -18,14 +17,38 @@ impl HexTable {
let y = index / self.len; let y = index / self.len;
let y_point = y as f32 * VERTICAL_OFFSET; let y_point = y as f32 * VERTICAL_OFFSET;
if y_point as usize > self.len { if y_point as usize >= self.len {
break; break;
} }
let mut x_point = x as f32; let mut x_point = x as f32;
if y % 2 == 1 { x_point += 0.5; } if y % 2 == 1 {
vec.push((x_point, y_point)); x_point += 0.5;
}
vec.push((x_point * self.scale, y_point * self.scale));
index += 1; index += 1;
} }
vec vec
} }
}
pub fn around(&self, x: f32, y: f32) -> Vec<(f32, f32)> {
let around = vec![
(x + self.scale, y),
(x - self.scale, y),
(x + 0.5 * self.scale, y + VERTICAL_OFFSET * self.scale),
(x - 0.5 * self.scale, y + VERTICAL_OFFSET * self.scale),
(x + 0.5 * self.scale, y - VERTICAL_OFFSET * self.scale),
(x - 0.5 * self.scale, y - VERTICAL_OFFSET * self.scale),
];
around
.iter()
.filter(|(x, y)| {
*x >= 0.0
&& *x < self.scale * self.len as f32
&& *y >= 0.0
&& *y < self.scale * self.len as f32
})
.map(|(x, y)| (*x, *y))
.collect()
}
}
+1
View File
@@ -39,6 +39,7 @@ fn main() {
.add_systems(Update, subplate_automation::update_automation) .add_systems(Update, subplate_automation::update_automation)
.add_systems(Update, subplate_automation::update_automation_view) .add_systems(Update, subplate_automation::update_automation_view)
.add_systems(Update, subplate_automation::setup_hex_matrix) .add_systems(Update, subplate_automation::setup_hex_matrix)
.add_systems(Update, subplate_automation::update_hex_matrix_view)
.run(); .run();
} }
+2 -3
View File
@@ -64,8 +64,8 @@ pub fn update_automation(
if keys.just_pressed(KeyCode::Enter) { if keys.just_pressed(KeyCode::Enter) {
println!("Switching to SubPlateAutomation"); println!("Switching to SubPlateAutomation");
let mut new_table = Table::<Color>::new(Color::NONE, automation.world.side); let mut new_table = Table::<u8>::new(0, automation.world.side);
automation.world.convert_copy(&mut new_table, |value| { if value { Color::WHITE } else { Color::NONE} }); automation.world.convert_copy(&mut new_table, |value| { if value { u8::MAX } else { 0 } });
commands.entity(entity).remove::<PlateAutomation>().insert(SubPlateAutomation{ commands.entity(entity).remove::<PlateAutomation>().insert(SubPlateAutomation{
world: new_table world: new_table
}); });
@@ -104,6 +104,5 @@ impl PlateAutomation {
self.world.data = updated; self.world.data = updated;
println!("Time elapsed: {:?} ms", time.elapsed().as_millis());
} }
} }
+102 -28
View File
@@ -1,17 +1,15 @@
use crate::basic::{IntoImage, Table}; use crate::basic::{IntoImage, Table};
use crate::hex_table::HexTable; use crate::hex_table::HexTable;
use crate::{RECTANGLE_SIDE, SeededRng}; use crate::SeededRng;
use bevy::asset::{Assets, RenderAssetUsages}; use bevy::asset::{Assets, RenderAssetUsages};
use bevy::image::{BevyDefault, Image}; use bevy::image::{BevyDefault, Image};
use bevy::input::ButtonInput; use bevy::input::ButtonInput;
use bevy::math::Vec2; use bevy::prelude::{Color, Commands, Component, Entity, KeyCode, Query, Res, ResMut, Sprite, Text, With};
use bevy::prelude::{Color, Commands, Component, Entity, KeyCode, Query, Res, ResMut, Sprite, With};
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat}; use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
use bevy::tasks::futures_lite::StreamExt; use bevy::tasks::futures_lite::StreamExt;
use rand::RngExt; use rand::RngExt;
use rand_chacha::ChaCha8Rng; use rand_chacha::ChaCha8Rng;
use rayon::iter::IntoParallelIterator; use std::collections::HashMap;
use rayon::iter::ParallelIterator;
use std::time::Instant; use std::time::Instant;
pub fn update_automation_view( pub fn update_automation_view(
@@ -42,9 +40,10 @@ pub fn update_automation_view(
pub fn update_automation( pub fn update_automation(
mut query: Query<(&mut SubPlateAutomation, Entity)>, mut query: Query<(&mut SubPlateAutomation, Entity)>,
mut hex_query: Query<&HexMatrixBuild>,
mut seeded_rng: ResMut<SeededRng>, mut seeded_rng: ResMut<SeededRng>,
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
commands: Commands, mut commands: Commands,
) { ) {
if query.is_empty() { if query.is_empty() {
return; return;
@@ -60,17 +59,27 @@ pub fn update_automation(
if keys.just_pressed(KeyCode::AltLeft) { if keys.just_pressed(KeyCode::AltLeft) {
let random = &mut seeded_rng.0; let random = &mut seeded_rng.0;
automation.seed(random); for _ in 0..16 {
automation.seed(random);
}
} }
if keys.just_pressed(KeyCode::AltRight) { // if keys.just_pressed(KeyCode::AltRight) {
automation.smooth(); // automation.smooth();
// }
if keys.just_pressed(KeyCode::KeyS) {
automation.calculate_subplates(&mut commands);
}
if keys.just_pressed(KeyCode::KeyF) {
automation.calculate_front_lines(&mut commands, hex_query);
} }
} }
#[derive(Component)] #[derive(Component)]
pub struct SubPlateAutomation { pub struct SubPlateAutomation {
pub(crate) world: Table<Color>, pub(crate) world: Table<u8>,
} }
impl SubPlateAutomation { impl SubPlateAutomation {
@@ -79,7 +88,7 @@ impl SubPlateAutomation {
for index in 0..self.world.side * self.world.side { for index in 0..self.world.side * self.world.side {
let current_color = *self.world.get(index); let current_color = *self.world.get(index);
if current_color == Color::NONE || current_color != Color::WHITE { if current_color == 0 || current_color != u8::MAX {
continue; continue;
} }
@@ -91,7 +100,7 @@ impl SubPlateAutomation {
.world .world
.around_line(index) .around_line(index)
.iter() .iter()
.filter(|v| ***v != Color::WHITE && ***v != Color::NONE) .filter(|v| ***v != u8::MAX && ***v != 0)
.map(|color| (*color).clone()) .map(|color| (*color).clone())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -103,14 +112,13 @@ impl SubPlateAutomation {
self.world.set(index, color); self.world.set(index, color);
} }
println!("Time elapsed: {:?} ms", time.elapsed().as_millis());
} }
fn smooth(&mut self) { fn smooth(&mut self) {
let range = 0..self.world.side * self.world.side; let range = 0..self.world.side * self.world.side;
for index in range { for index in range {
let around = self.world.around_line(index); let around = self.world.around_line(index);
let mut counts: Vec<(Color, u8)> = vec![]; let mut counts: Vec<(u8, u8)> = vec![];
for p in around { for p in around {
for count_index in 0..counts.len() { for count_index in 0..counts.len() {
if counts[count_index].0 == *p { if counts[count_index].0 == *p {
@@ -129,15 +137,44 @@ impl SubPlateAutomation {
let len = (self.world.side * self.world.side) as f32; let len = (self.world.side * self.world.side) as f32;
loop { loop {
let index = (rng.random::<f32>() * len) as usize; let index = (rng.random::<f32>() * len) as usize;
if *self.world.get(index) == Color::NONE { if *self.world.get(index) == 0 {
continue; continue;
} }
self.world self.world
.set(index, Color::hsv(rng.random::<f32>() * 360.0, 1.0, 1.0)); .set(index, rng.random::<u8>());
break; break;
} }
} }
fn calculate_front_lines(&self, commands: &mut Commands, hex_query: Query<&HexMatrixBuild>) {
let generator = &hex_query.iter().next().unwrap().hex_matrix;
let all_points = generator.calculate();
let own_points = all_points.iter().map(|(x, y)| {
let x_table = *x as usize;
let y_table = *y as usize;
(*self.world.get_dim(x_table, y_table), x, y)
}).filter(|(v, _, _)| {
*v != 0
});
commands.spawn((HexMatrixRedrawRequest));
}
fn calculate_subplates(&self, commands: &mut Commands) {
let mut list : HashMap<u8, Vec<usize>> = HashMap::new();
self.world.iter().zip(0..self.world.data.len()).for_each(|(world, index)| {
if list.contains_key(world) {
list.get_mut(world).unwrap().push(index);
}
else {
list.insert(world.clone(), vec![index]);
}
});
println!("{:?}", list.iter().map(|(c, v)| (c.clone(), v.len())).collect::<Vec<_>>());
}
} }
pub fn setup_hex_matrix( pub fn setup_hex_matrix(
@@ -159,17 +196,13 @@ pub fn setup_hex_matrix(
let resolution = automation.world.side / 4; let resolution = automation.world.side / 4;
let generator = HexTable::new(resolution); let generator = HexTable::new(resolution, 4.0);
let mut table = Table::new(false, automation.world.side); let mut table = Table::new(false, automation.world.side);
generator.calculate().iter().for_each(|(x, y)| { generator.calculate().iter().for_each(|(x, y)| {
let x = (x * 4.0) as usize; let x = *x as usize;
let y = (y * 4.0) as usize; let y = *y as usize;
if x + y * table.side >= table.data.len() { if *automation.world.get_dim(x, y) == 0 {
return;
}
if *automation.world.get_dim(x, y) == Color::NONE {
return; return;
} }
@@ -195,17 +228,58 @@ pub fn setup_hex_matrix(
images.remove(sprite.image.id()); images.remove(sprite.image.id());
images.insert(sprite.image.id(), image).unwrap(); images.insert(sprite.image.id(), image).unwrap();
commands.spawn((HexMatrixBuild{ commands.spawn((HexMatrixBuild{
points: table points: table,
},)); hex_matrix: generator,
}));
} }
pub fn update_hex_matrix_view(
mut data_query: Query<&HexMatrixBuild>,
mut request_query: Query<Entity, With<HexMatrixRedrawRequest>>,
mut view_query: Query<&Sprite, With<HexMatrixView>>,
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
){
if request_query.is_empty() {
return;
}
let req = request_query.iter_mut().next().unwrap();
commands.entity(req).despawn();
println!("Update hex matrix view");
let table = data_query.iter_mut().next().unwrap();
let data = table.points.get_image_data();
let image = Image::new(
Extent3d {
width: table.points.side as u32,
height: table.points.side as u32,
depth_or_array_layers: 1,
},
TextureDimension::D2,
data,
TextureFormat::bevy_default(),
RenderAssetUsages::default(),
);
let sprite = view_query.iter().next().unwrap();
images.remove(sprite.image.id());
images.insert(sprite.image.id(), image).unwrap();
}
#[derive(Component)] #[derive(Component)]
pub struct HexMatrixRequest; pub struct HexMatrixRequest;
#[derive(Component)]
pub struct HexMatrixRedrawRequest;
#[derive(Component)] #[derive(Component)]
pub struct HexMatrixView; pub struct HexMatrixView;
#[derive(Component)] #[derive(Component)]
pub struct HexMatrixBuild{ pub struct HexMatrixBuild{
points: Table<bool> points: Table<bool>,
} hex_matrix: HexTable
}