Files
tect_gen/src/subplate_automation.rs
T

395 lines
12 KiB
Rust
Raw Normal View History

2026-07-03 10:16:36 +03:00
use crate::collision_world::{CollisionBody, CollisionWorld};
2026-06-22 11:37:35 +03:00
use crate::hex_table::HexTable;
2026-06-28 22:33:01 +03:00
use crate::table::{IntoImage, Table};
2026-07-03 10:34:32 +03:00
use crate::{Moving, SeededRng, RECTANGLE_SIDE};
2026-07-03 10:16:36 +03:00
use bevy::asset::{Assets, RenderAssetUsages};
2026-06-28 22:33:01 +03:00
use bevy::image::Image;
2026-06-18 20:51:09 +03:00
use bevy::input::ButtonInput;
2026-07-03 10:16:36 +03:00
use bevy::prelude::*;
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
2026-06-22 11:37:35 +03:00
use rand::RngExt;
2026-06-18 20:51:09 +03:00
use rand_chacha::ChaCha8Rng;
2026-06-27 10:37:45 +03:00
use std::collections::HashMap;
2026-06-18 20:51:09 +03:00
pub fn update_automation_view(
2026-06-29 01:29:58 +03:00
query: Single<(&Sprite, &SubPlateAutomation)>,
request: Single<(&ViewRedrawRequest, Entity)>,
2026-06-18 20:51:09 +03:00
mut images: ResMut<Assets<Image>>,
2026-06-29 01:29:58 +03:00
mut commands: Commands,
2026-06-18 20:51:09 +03:00
) {
2026-06-29 01:29:58 +03:00
let (sprite, automation) = query.into_inner();
2026-06-28 22:33:01 +03:00
let image = automation.world.get_image_data();
2026-06-18 20:51:09 +03:00
images.insert(sprite.image.id(), image).unwrap();
2026-06-29 01:29:58 +03:00
commands.entity(request.into_inner().1).despawn();
2026-06-18 20:51:09 +03:00
}
pub fn update_automation(
2026-06-28 22:33:01 +03:00
query: Single<(&mut SubPlateAutomation, Entity)>,
2026-07-03 10:16:36 +03:00
mut hex_query: Single<&mut HexMatrixBuild>,
2026-06-18 20:51:09 +03:00
mut seeded_rng: ResMut<SeededRng>,
keys: Res<ButtonInput<KeyCode>>,
2026-06-27 10:37:45 +03:00
mut commands: Commands,
2026-07-03 10:16:36 +03:00
mut images: ResMut<Assets<Image>>,
2026-07-06 15:28:25 +03:00
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
2026-06-18 20:51:09 +03:00
) {
2026-07-03 10:16:36 +03:00
let (mut automation, entity) = query.into_inner();
2026-06-18 20:51:09 +03:00
if keys.just_pressed(KeyCode::Space) || keys.all_pressed([KeyCode::Space, KeyCode::ShiftLeft]) {
let random = &mut seeded_rng.0;
2026-06-29 01:29:58 +03:00
automation.next(random);
2026-06-29 13:13:17 +03:00
commands.spawn(ViewRedrawRequest);
2026-06-18 20:51:09 +03:00
}
if keys.just_pressed(KeyCode::AltLeft) {
let random = &mut seeded_rng.0;
2026-07-03 10:16:36 +03:00
for i in 1..=16 {
automation.seed(random, i * 8);
2026-06-27 10:37:45 +03:00
}
2026-06-29 01:29:58 +03:00
2026-06-29 13:13:17 +03:00
commands.spawn(ViewRedrawRequest);
2026-06-27 10:37:45 +03:00
}
2026-06-29 01:29:58 +03:00
if keys.just_pressed(KeyCode::AltRight) {
automation.smooth();
2026-06-29 13:13:17 +03:00
commands.spawn(ViewRedrawRequest);
2026-06-29 01:29:58 +03:00
}
2026-06-27 10:37:45 +03:00
if keys.just_pressed(KeyCode::KeyS) {
2026-06-29 13:13:17 +03:00
automation.calculate_subplates();
2026-06-18 20:51:09 +03:00
}
2026-06-27 10:37:45 +03:00
if keys.just_pressed(KeyCode::KeyF) {
2026-07-03 10:16:36 +03:00
automation.calculate_front_lines(&mut commands, &mut hex_query, &automation);
}
2026-06-29 01:29:58 +03:00
2026-07-03 10:16:36 +03:00
if keys.just_pressed(KeyCode::Enter) {
2026-07-03 10:40:37 +03:00
commands.entity(entity).despawn();
2026-07-06 15:28:25 +03:00
create_collision_world(commands, &automation, &hex_query, images, meshes, materials);
2026-06-18 20:51:09 +03:00
}
}
2026-07-03 10:16:36 +03:00
fn create_collision_world(
mut commands: Commands,
query: &Mut<SubPlateAutomation>,
hex_query: &Single<&mut HexMatrixBuild>,
mut images: ResMut<Assets<Image>>,
2026-07-06 15:28:25 +03:00
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
2026-07-03 10:16:36 +03:00
) {
println!("Switching to CollisionAutomation");
let mut colors = query.world.data.clone();
colors.sort();
colors.dedup();
colors.remove(0);
let mut territories = vec![Vec::<(usize, usize)>::new(); colors.len()];
let mut borders = vec![Vec::<Vec2>::new(); colors.len()];
for x in 0..query.world.side {
for y in 0..query.world.side {
let color = *query.world.get_dim(x, y);
if color == 0 {
continue;
}
let index = colors.iter().position(|v| *v == color).unwrap();
territories[index].push((x, y));
}
}
for x in 0..hex_query.hex_matrix.dimensions.0 {
for y in 0..hex_query.hex_matrix.dimensions.1 {
let color = *query.world.get_dim(x, y);
if color == 0 {
continue;
}
let index = colors.iter().position(|v| *v == color).unwrap();
let coordinates = hex_query.hex_matrix.get_offset_of(x, y);
borders[index].push(Vec2::new(coordinates.0, coordinates.1));
}
}
2026-07-03 10:34:32 +03:00
let view_offset = query.world.side as f32 / 2.0;
2026-07-03 10:16:36 +03:00
let plates_data = territories
.iter()
.map(|v| {
let center = v
.iter()
2026-07-06 15:28:25 +03:00
.map(|(x, y)| Vec2::new(*x as f32 - view_offset, -(*y as f32) + view_offset))
2026-07-03 10:16:36 +03:00
.collect::<Vec<_>>()
.into_iter()
.sum::<Vec2>()
/ v.len() as f32;
let xs = v.iter().map(|(x, y)| *x).collect::<Vec<_>>();
let ys = v.iter().map(|(x, y)| *y).collect::<Vec<_>>();
let max_x = *xs.iter().max().unwrap();
let max_y = *ys.iter().max().unwrap();
let min_x = *xs.iter().min().unwrap();
let min_y = *ys.iter().min().unwrap();
let mut image = Image::new_fill(
Extent3d {
width: (max_x - min_x) as u32 + 1,
height: (max_y - min_y) as u32 + 1,
depth_or_array_layers: 1,
},
TextureDimension::D2,
&[0, 0, 0, 0],
TextureFormat::Rgba8UnormSrgb,
RenderAssetUsages::default(),
);
let size = image.size();
v.into_iter().for_each(|(x, y)| {
let position = ((*x - min_x) as u32, (*y - min_y) as u32);
image
.set_color_at(position.0, position.1, Color::WHITE)
.unwrap();
});
2026-07-03 10:40:37 +03:00
let image_offset = Vec2::new(min_x as f32 + size.x as f32 / 2.0 - view_offset, - (min_y as f32) - size.y as f32 / 2.0 + view_offset);
2026-07-06 15:28:25 +03:00
(v.len(), image_offset, image, center - image_offset)
2026-07-03 10:16:36 +03:00
})
.collect::<Vec<_>>();
let mut world = CollisionWorld { bodies: vec![] };
2026-07-06 15:28:25 +03:00
let center_color = materials.add(Color::srgb_u8(63,0,255));
let center_shape = meshes.add(Circle::new(5.0));
2026-07-03 10:16:36 +03:00
let mut parts = Vec::with_capacity(plates_data.len());
for index in 0..plates_data.len() {
let (mass, center, image, offset) = plates_data.get(index).unwrap();
let image_handle = images.add(image.clone());
2026-07-06 15:28:25 +03:00
let view_id = commands
2026-07-03 10:16:36 +03:00
.spawn((
Sprite::from_image(image_handle),
))
.id();
2026-07-06 15:28:25 +03:00
let mass_id = commands
.spawn((
Transform::from_xyz(offset.x, offset.y, 2.0),
Mesh2d(center_shape.clone()),
MeshMaterial2d(center_color.clone()),
))
.id();
2026-07-03 10:16:36 +03:00
2026-07-03 10:40:37 +03:00
let mut entity = commands.spawn((Transform::from_xyz(center.x, center.y, 0.0),));
2026-07-06 15:28:25 +03:00
entity.add_child(view_id);
entity.add_child(mass_id);
2026-07-03 10:16:36 +03:00
let entity_id = entity.id();
parts.push(entity_id);
let col_body = CollisionBody {
value: colors[index],
position: *center,
border: borders[index].clone(),
forces: vec![],
mass: *mass as f32,
};
world.bodies.push(col_body);
}
2026-07-06 15:28:25 +03:00
let scale = RECTANGLE_SIDE / query.world.side as f32;
let presentation = commands.spawn((Transform{
2026-07-03 10:34:32 +03:00
translation: Vec3::ZERO,
rotation: Quat::default(),
scale: vec3(scale, scale, 1.0),
2026-07-06 15:28:25 +03:00
})).add_children(parts.as_slice()).id();
commands.spawn((Transform::default(), Moving)).add_child(presentation);
2026-07-03 10:16:36 +03:00
}
2026-06-18 20:51:09 +03:00
#[derive(Component)]
pub struct SubPlateAutomation {
2026-06-27 10:37:45 +03:00
pub(crate) world: Table<u8>,
2026-06-18 20:51:09 +03:00
}
impl SubPlateAutomation {
fn next(&mut self, rng: &mut ChaCha8Rng) {
2026-06-18 21:46:47 +03:00
2026-06-18 20:51:09 +03:00
for index in 0..self.world.side * self.world.side {
let current_color = *self.world.get(index);
2026-06-27 10:37:45 +03:00
if current_color == 0 || current_color != u8::MAX {
2026-06-18 20:51:09 +03:00
continue;
}
2026-06-22 11:37:35 +03:00
if rng.random::<f32>() < 0.8 {
2026-06-18 20:51:09 +03:00
continue;
}
2026-06-22 11:37:35 +03:00
let around = self
.world
.around_line(index)
.iter()
2026-06-27 10:37:45 +03:00
.filter(|v| ***v != u8::MAX && ***v != 0)
2026-06-22 11:37:35 +03:00
.map(|color| (*color).clone())
.collect::<Vec<_>>();
2026-06-18 20:51:09 +03:00
if around.len() == 0 {
continue;
}
let color = around[rng.random_range(0..around.len())];
self.world.set(index, color);
}
2026-06-29 01:29:58 +03:00
2026-07-03 10:40:37 +03:00
// println!("Done in {} mcs", time.elapsed().as_micros());
2026-06-18 21:46:47 +03:00
}
fn smooth(&mut self) {
let range = 0..self.world.side * self.world.side;
2026-06-22 11:37:35 +03:00
for index in range {
2026-06-18 21:46:47 +03:00
let around = self.world.around_line(index);
2026-06-27 10:37:45 +03:00
let mut counts: Vec<(u8, u8)> = vec![];
2026-06-18 21:46:47 +03:00
for p in around {
for count_index in 0..counts.len() {
if counts[count_index].0 == *p {
counts[count_index].1 += 1;
2026-06-22 11:37:35 +03:00
continue;
2026-06-18 21:46:47 +03:00
}
}
counts.push((p.clone(), 1));
}
2026-06-22 11:37:35 +03:00
self.world
.set(index, counts.iter().max_by_key(|(_, c)| c).unwrap().0);
}
2026-06-18 20:51:09 +03:00
}
2026-07-03 10:16:36 +03:00
fn seed(&mut self, rng: &mut ChaCha8Rng, value: u8) {
2026-06-18 20:51:09 +03:00
let len = (self.world.side * self.world.side) as f32;
loop {
let index = (rng.random::<f32>() * len) as usize;
2026-06-27 10:37:45 +03:00
if *self.world.get(index) == 0 {
2026-06-18 20:51:09 +03:00
continue;
}
2026-07-03 10:16:36 +03:00
self.world.set(index, value);
2026-06-18 20:51:09 +03:00
break;
}
}
2026-06-27 10:37:45 +03:00
2026-06-28 22:33:01 +03:00
fn calculate_front_lines(
&self,
commands: &mut Commands,
2026-07-03 10:16:36 +03:00
mut hex_query: &mut Single<&mut HexMatrixBuild>,
2026-06-28 22:33:01 +03:00
automation: &SubPlateAutomation,
) {
let table = &mut hex_query.hex_matrix;
let mut table_copy = table.clone();
for x in 0..table.dimensions.0 {
for y in 0..table.dimensions.1 {
let color = *table.get_on_square_table(x, y, &automation.world);
table.set_dim(x, y, color);
}
}
2026-06-27 10:37:45 +03:00
2026-06-28 22:33:01 +03:00
for x in 0..table.dimensions.0 {
for y in 0..table.dimensions.1 {
let color = table.get_dim(x, y);
2026-07-03 10:16:36 +03:00
if *color == 0 {
continue;
}
2026-06-28 22:33:01 +03:00
let around = table.around(x, y);
if around.iter().all(|x1| *x1 == around[0]) {
table_copy.set_dim(x, y, 0);
2026-07-03 10:16:36 +03:00
} else {
table_copy.set_dim(x, y, *color);
2026-06-28 22:33:01 +03:00
}
}
}
hex_query.hex_matrix = table_copy;
2026-06-27 10:37:45 +03:00
2026-06-29 13:13:17 +03:00
commands.spawn(HexMatrixRedrawRequest);
2026-06-27 10:37:45 +03:00
}
2026-06-29 13:13:17 +03:00
fn calculate_subplates(&self) {
2026-06-28 22:33:01 +03:00
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<_>>()
);
2026-06-27 10:37:45 +03:00
}
2026-06-18 20:51:09 +03:00
}
2026-06-22 11:37:35 +03:00
pub fn setup_hex_matrix(
2026-06-29 13:16:27 +03:00
request_query: Single<(&HexMatrixRequest, Entity)>,
view_query: Single<&Sprite, With<HexMatrixView>>,
mut automation_query: Single<&SubPlateAutomation>,
2026-06-22 11:37:35 +03:00
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
) {
2026-06-29 13:16:27 +03:00
let entity = request_query.into_inner().1;
let automation = automation_query.into_inner();
2026-06-22 11:37:35 +03:00
commands.entity(entity).despawn();
println!("Seed hex matrix");
2026-07-03 10:16:36 +03:00
let resolution = automation.world.side / 4;
2026-06-22 11:37:35 +03:00
2026-07-03 10:16:36 +03:00
let hex_table = HexTable::new(resolution, 0, 4.0);
2026-06-22 11:37:35 +03:00
2026-06-28 22:33:01 +03:00
let image = hex_table.get_image_data();
2026-06-22 11:37:35 +03:00
2026-06-29 13:16:27 +03:00
let sprite = view_query.into_inner();
2026-06-22 11:37:35 +03:00
images.insert(sprite.image.id(), image).unwrap();
2026-07-03 10:16:36 +03:00
commands.spawn(HexMatrixBuild {
hex_matrix: hex_table,
});
2026-06-22 11:37:35 +03:00
}
2026-06-27 10:37:45 +03:00
pub fn update_hex_matrix_view(
2026-06-29 13:13:17 +03:00
data_query: Single<&HexMatrixBuild>,
request_query: Single<Entity, With<HexMatrixRedrawRequest>>,
view_query: Single<&Sprite, With<HexMatrixView>>,
2026-06-27 10:37:45 +03:00
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
2026-06-28 22:33:01 +03:00
) {
2026-06-29 13:13:17 +03:00
let req = request_query.into_inner();
2026-06-27 10:37:45 +03:00
commands.entity(req).despawn();
println!("Update hex matrix view");
2026-06-28 22:33:01 +03:00
let table = data_query.into_inner();
let image = table.hex_matrix.get_image_data();
2026-06-27 10:37:45 +03:00
2026-06-29 13:13:17 +03:00
let sprite = view_query.into_inner();
2026-06-27 10:37:45 +03:00
images.insert(sprite.image.id(), image).unwrap();
}
2026-06-22 11:37:35 +03:00
#[derive(Component)]
pub struct HexMatrixRequest;
2026-06-27 10:37:45 +03:00
#[derive(Component)]
pub struct HexMatrixRedrawRequest;
2026-06-29 01:29:58 +03:00
#[derive(Component)]
pub struct ViewRedrawRequest;
2026-06-22 11:37:35 +03:00
#[derive(Component)]
pub struct HexMatrixView;
#[derive(Component)]
2026-06-28 22:33:01 +03:00
pub struct HexMatrixBuild {
hex_matrix: HexTable<u8>,
}