use bevy::color::Srgba;
use bevy::prelude::*;
use std::collections::HashMap;
use std::error::Error;
use crate::plugins::Element;
#[derive(Component, Debug, Clone)]
pub struct Atom {
pub element: Element,
}
#[derive(Component, Debug, Clone)]
pub struct Bond {
pub atom_a: Entity,
pub atom_b: Entity,
}
#[derive(Component, Clone)]
pub struct Molecule {
pub name: String,
}
#[derive(Component, Clone, Copy, PartialEq, Eq)]
pub enum RepresentationStyle {
BallAndStick,
Stick,
Spacefill,
}
#[derive(Component)]
struct AtomMesh;
#[derive(Component)]
struct BondMesh;
#[derive(Component)]
struct HalfBond {
parent_bond: Entity,
source_atom: Entity,
}
fn atom_visibility(style: RepresentationStyle, element: &Element) -> Option<f32> {
match style {
RepresentationStyle::BallAndStick => Some(element.covalent_radius.unwrap_or(100.0) * 0.002),
RepresentationStyle::Stick => {
if element.atomic_number == 1 || element.atomic_number == 6 {
Some(0.15)
} else {
Some(element.covalent_radius.unwrap_or(100.0) * 0.004)
}
}
RepresentationStyle::Spacefill => Some(element.covalent_radius.unwrap_or(170.0) * 0.002),
}
}
fn bond_radius(style: RepresentationStyle, is_metal_bond: bool) -> f32 {
match style {
RepresentationStyle::BallAndStick => {
if is_metal_bond {
0.10
} else {
0.15
}
}
RepresentationStyle::Stick => {
if is_metal_bond {
0.10
} else {
0.15
}
}
RepresentationStyle::Spacefill => 0.0, }
}
fn calculate_half_bond_transform(pos_a: Vec3, pos_b: Vec3, atom_radius: f32) -> (Transform, f32) {
let bond_vector = pos_b - pos_a;
let full_length = bond_vector.length();
let direction = bond_vector.normalize();
let offset = if atom_radius > 0.0 {
atom_radius * 0.001
} else {
0.0
};
let half_length = (full_length / 2.0) - offset;
let center = pos_a + direction * (offset + half_length / 2.0);
let rotation = if direction.dot(Vec3::Y).abs() > 0.99999 {
Quat::from_rotation_z(if direction.dot(Vec3::Y) > 0.0 {
0.0
} else {
std::f32::consts::PI
})
} else {
Quat::from_rotation_arc(Vec3::Y, direction)
};
(
Transform {
translation: center,
rotation,
scale: Vec3::ONE,
},
half_length,
)
}
fn get_element_material(element: &Element) -> StandardMaterial {
let hex = element
.hex_color
.as_ref()
.map(|s| s.as_str())
.unwrap_or("FFFFFF");
StandardMaterial {
base_color: Color::from(Srgba::hex(hex).unwrap_or(Srgba::WHITE)),
..default()
}
}
fn should_bond(element_a: &Element, element_b: &Element, distance: f32, tolerance: f32) -> bool {
if let (Some(r_a), Some(r_b)) = (element_a.covalent_radius, element_b.covalent_radius) {
let threshold = (r_a + r_b) / 100.0 * tolerance;
distance <= threshold
} else {
false
}
}
fn center_molecule_on_metal(metal_position: Vec3) -> Vec3 {
-metal_position
}
fn parse_xyz_file(path: &str) -> Result<(Vec<(String, Vec3)>, String), Box<dyn Error>> {
let content = std::fs::read_to_string(path)?;
let mut lines = content.lines();
let n_atoms: usize = lines
.next()
.ok_or_else(|| "Missing atom count".to_string())?
.parse()?;
let comment = lines
.next()
.ok_or_else(|| "Missing comment line".to_string())?
.to_string();
let atoms: Result<Vec<(String, Vec3)>, Box<dyn Error>> = lines
.take(n_atoms)
.map(|line| -> Result<(String, Vec3), Box<dyn Error>> {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 4 {
return Err("Invalid atom line".into());
}
let symbol = parts[0].to_string();
let x: f32 = parts[1].parse()?;
let y: f32 = parts[2].parse()?;
let z: f32 = parts[3].parse()?;
Ok((symbol, Vec3::new(x, y, z)))
})
.collect();
Ok((atoms?, comment))
}
fn load_molecules(mut commands: Commands) {
let args: Vec<String> = std::env::args().collect();
for path in args.iter().skip(1) {
if let Ok((atoms, comment)) = parse_xyz_file(path) {
let mol_name = if comment.is_empty() {
path.clone()
} else {
comment
};
let molecule = Molecule {
name: mol_name.clone(),
};
for (symbol, position) in atoms.iter() {
let element = Element::new(symbol);
commands.spawn((
Atom { element },
Transform::from_translation(*position),
molecule.clone(),
RepresentationStyle::Stick, ));
}
println!("Loaded: {}", mol_name);
}
}
}
fn detect_bonds(
atoms: Query<(Entity, &Atom, &Transform, &Molecule), Added<Molecule>>,
mut commands: Commands,
) {
let mut molecules: HashMap<String, Vec<(Entity, &Atom, &Transform)>> = HashMap::new();
for (entity, atom, transform, molecule) in &atoms {
molecules
.entry(molecule.name.clone())
.or_insert_with(Vec::new)
.push((entity, atom, transform));
}
for (mol_name, atom_list) in molecules {
for i in 0..atom_list.len() {
for j in (i + 1)..atom_list.len() {
let (entity_a, atom_a, transform_a) = atom_list[i];
let (entity_b, atom_b, transform_b) = atom_list[j];
let distance = transform_a.translation.distance(transform_b.translation);
if should_bond(&atom_a.element, &atom_b.element, distance, 1.2) {
commands.spawn((
Bond {
atom_a: entity_a,
atom_b: entity_b,
},
Molecule {
name: mol_name.clone(),
},
RepresentationStyle::Stick, Transform::default(), ));
}
}
}
}
}
fn center_on_metal(
atoms: Query<(Entity, &Atom, &Transform, &Molecule)>,
mut transforms: Query<&mut Transform, (With<Atom>, Without<Molecule>)>,
) {
let mut molecules: HashMap<String, Vec<(Entity, bool, Vec3)>> = HashMap::new();
for (entity, atom, transform, molecule) in &atoms {
molecules
.entry(molecule.name.clone())
.or_insert_with(Vec::new)
.push((
entity,
atom.element.is_transition_metal(),
transform.translation,
));
}
for (mol_name, atom_list) in molecules {
let mut metal_count = 0;
let mut metal_position = Vec3::ZERO;
for (_, is_metal, position) in &atom_list {
if *is_metal {
metal_count += 1;
metal_position = *position;
}
}
if metal_count == 1 {
let translation = center_molecule_on_metal(metal_position);
for (entity, _, _) in atom_list {
if let Ok(mut transform) = transforms.get_mut(entity) {
transform.translation += translation;
}
}
info!(
"Centered coordination complex '{}' on transition metal at origin",
mol_name
);
}
}
}
fn render_atoms(
query: Query<
(Entity, &Atom, &RepresentationStyle),
Or<(Added<Atom>, Changed<RepresentationStyle>)>,
>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for (entity, atom, style) in &query {
commands
.entity(entity)
.remove::<(Mesh3d, MeshMaterial3d<StandardMaterial>, AtomMesh)>();
if let Some(radius) = atom_visibility(*style, &atom.element) {
let mesh = Sphere::new(radius);
let hex = atom
.element
.hex_color
.as_ref()
.map(|s| s.as_str())
.unwrap_or("FFFFFF");
let material = StandardMaterial {
base_color: Color::from(Srgba::hex(hex).unwrap_or(Srgba::WHITE)),
..default()
};
commands.entity(entity).insert((
Mesh3d(meshes.add(mesh)),
MeshMaterial3d(materials.add(material)),
AtomMesh,
));
}
}
}
fn render_bonds(
bonds: Query<
(Entity, &Bond, &RepresentationStyle),
Or<(Added<Bond>, Changed<RepresentationStyle>)>,
>,
half_bonds: Query<(Entity, &HalfBond)>,
atoms: Query<(&Atom, &Transform)>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for (entity, bond, style) in &bonds {
for (half_entity, half_bond) in &half_bonds {
if half_bond.parent_bond == entity {
commands.entity(half_entity).despawn();
}
}
let Ok((atom_a, transform_a)) = atoms.get(bond.atom_a) else {
continue;
};
let Ok((atom_b, transform_b)) = atoms.get(bond.atom_b) else {
continue;
};
let is_metal = atom_a.element.is_metal() || atom_b.element.is_metal();
let radius = bond_radius(*style, is_metal);
if radius > 0.0 {
let radius_a = atom_visibility(*style, &atom_a.element).unwrap_or(0.0);
let radius_b = atom_visibility(*style, &atom_b.element).unwrap_or(0.0);
let (transform_half_a, length_a) = calculate_half_bond_transform(
transform_a.translation,
transform_b.translation,
radius_a,
);
let (transform_half_b, length_b) = calculate_half_bond_transform(
transform_b.translation,
transform_a.translation,
radius_b,
);
let material_a = if is_metal && atom_a.element.is_metal() {
StandardMaterial {
base_color: Color::srgba_u8(144, 108, 250, 245),
alpha_mode: AlphaMode::Blend,
..default()
}
} else {
get_element_material(&atom_a.element)
};
let material_b = if is_metal && atom_b.element.is_metal() {
StandardMaterial {
base_color: Color::srgba_u8(144, 108, 250, 245),
alpha_mode: AlphaMode::Blend,
..default()
}
} else {
get_element_material(&atom_b.element)
};
commands.spawn((
Mesh3d(meshes.add(Cylinder::new(radius, length_a.max(0.01)))),
MeshMaterial3d(materials.add(material_a)),
transform_half_a,
HalfBond {
parent_bond: entity,
source_atom: bond.atom_a,
},
));
commands.spawn((
Mesh3d(meshes.add(Cylinder::new(radius, length_b.max(0.01)))),
MeshMaterial3d(materials.add(material_b)),
transform_half_b,
HalfBond {
parent_bond: entity,
source_atom: bond.atom_b,
},
));
commands.entity(entity).insert(BondMesh);
} else {
commands.entity(entity).remove::<BondMesh>();
}
}
}
fn update_bond_transforms(
bonds: Query<(Entity, &Bond, &RepresentationStyle), With<BondMesh>>,
half_bonds: Query<(Entity, &HalfBond)>,
atoms: Query<(&Atom, &Transform), (With<Atom>, Without<Bond>)>,
mut transforms: Query<&mut Transform, Without<Atom>>,
) {
for (bond_entity, bond, style) in &bonds {
let Ok((atom_a, transform_a)) = atoms.get(bond.atom_a) else {
continue;
};
let Ok((atom_b, transform_b)) = atoms.get(bond.atom_b) else {
continue;
};
let radius_a = atom_visibility(*style, &atom_a.element).unwrap_or(0.0);
let radius_b = atom_visibility(*style, &atom_b.element).unwrap_or(0.0);
let (transform_half_a, _) = calculate_half_bond_transform(
transform_a.translation,
transform_b.translation,
radius_a,
);
let (transform_half_b, _) = calculate_half_bond_transform(
transform_b.translation,
transform_a.translation,
radius_b,
);
for (half_entity, half_bond) in &half_bonds {
if half_bond.parent_bond == bond_entity {
if let Ok(mut t) = transforms.get_mut(half_entity) {
if half_bond.source_atom == bond.atom_a {
*t = transform_half_a;
} else if half_bond.source_atom == bond.atom_b {
*t = transform_half_b;
}
}
}
}
}
}
pub struct MoleculePlugin;
#[derive(Resource, Default)]
pub struct AxesResource {
pub entity: Option<Entity>,
pub visible: bool,
}
fn axes_toggle_system(
keyboard: Res<ButtonInput<KeyCode>>,
mut commands: Commands,
mut axes_res: ResMut<AxesResource>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
if !keyboard.just_pressed(KeyCode::KeyC) {
return;
}
if axes_res.visible {
if let Some(ent) = axes_res.entity.take() {
commands.entity(ent).despawn_recursive();
}
axes_res.visible = false;
info!("Axes hidden");
} else {
let parent = commands
.spawn((
Name::new("Axes"),
Transform::default(),
GlobalTransform::default(),
))
.id();
let shaft_radius = 0.02f32;
let shaft_length = 2.0f32;
let tip_radius = 0.06f32;
let shaft_mesh = meshes.add(Cylinder::new(shaft_radius, shaft_length));
let tip_mesh = meshes.add(Sphere::new(tip_radius));
let mat_x = materials.add(StandardMaterial {
base_color: Color::srgb(1.0, 0.1, 0.1),
unlit: true,
..Default::default()
});
let shaft_x_tf = Transform::from_translation(Vec3::new(shaft_length / 2.0, 0.0, 0.0))
* Transform::from_rotation(Quat::from_rotation_z(-std::f32::consts::FRAC_PI_2));
let tip_x_tf =
Transform::from_translation(Vec3::new(shaft_length + tip_radius * 0.5, 0.0, 0.0));
commands.entity(parent).with_children(|parent| {
parent.spawn((
Mesh3d(shaft_mesh.clone()),
MeshMaterial3d(mat_x.clone()),
Name::new("Axis X Shaft"),
shaft_x_tf,
));
parent.spawn((
Mesh3d(tip_mesh.clone()),
MeshMaterial3d(mat_x.clone()),
Name::new("Axis X Tip"),
tip_x_tf,
));
});
let mat_y = materials.add(StandardMaterial {
base_color: Color::srgb(0.1, 1.0, 0.1),
unlit: true,
..Default::default()
});
let shaft_y_tf = Transform::from_translation(Vec3::new(0.0, shaft_length / 2.0, 0.0));
let tip_y_tf =
Transform::from_translation(Vec3::new(0.0, shaft_length + tip_radius * 0.5, 0.0));
commands.entity(parent).with_children(|parent| {
parent.spawn((
Mesh3d(shaft_mesh.clone()),
MeshMaterial3d(mat_y.clone()),
Name::new("Axis Y Shaft"),
shaft_y_tf,
));
parent.spawn((
Mesh3d(tip_mesh.clone()),
MeshMaterial3d(mat_y.clone()),
Name::new("Axis Y Tip"),
tip_y_tf,
));
});
let mat_z = materials.add(StandardMaterial {
base_color: Color::srgb(0.1, 0.1, 1.0),
unlit: true,
..Default::default()
});
let shaft_z_tf = Transform::from_translation(Vec3::new(0.0, 0.0, shaft_length / 2.0))
* Transform::from_rotation(Quat::from_rotation_x(std::f32::consts::FRAC_PI_2));
let tip_z_tf =
Transform::from_translation(Vec3::new(0.0, 0.0, shaft_length + tip_radius * 0.5));
commands.entity(parent).with_children(|parent| {
parent.spawn((
Mesh3d(shaft_mesh.clone()),
MeshMaterial3d(mat_z.clone()),
Name::new("Axis Z Shaft"),
shaft_z_tf,
));
parent.spawn((
Mesh3d(tip_mesh.clone()),
MeshMaterial3d(mat_z.clone()),
Name::new("Axis Z Tip"),
tip_z_tf,
));
});
axes_res.entity = Some(parent);
axes_res.visible = true;
info!("Axes shown");
}
}
impl Plugin for MoleculePlugin {
fn build(&self, app: &mut App) {
app
.add_systems(Startup, load_molecules)
.add_systems(
PostStartup,
(detect_bonds, center_on_metal, render_atoms, render_bonds).chain(),
)
.add_systems(
Update,
(
render_atoms,
render_bonds,
update_bond_transforms,
axes_toggle_system,
),
)
.insert_resource(AxesResource::default());
}
}