phosph-rs 0.4.0

Simple, pretty, multiplatform molecular viewer for chemists.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use bevy::color::Srgba;
use bevy::prelude::*;

use std::collections::HashMap;
use std::error::Error;

use crate::plugins::Element;

// === COMPONENTS (Pure Data) ===

#[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,
}

// === REPRESENTATION STRATEGY ===
// This is the key: representation is a molecule-level decision, not atom-level

#[derive(Component, Clone, Copy, PartialEq, Eq)]
pub enum RepresentationStyle {
    BallAndStick,
    Stick,
    Spacefill,
}

// Instead of AtomVisualStyle and BondVisualStyle separately,
// we have one unified representation that affects how we render everything

// === RENDERING COMPONENTS ===
// These are added by systems based on the representation

#[derive(Component)]
struct AtomMesh;

#[derive(Component)]
struct BondMesh;

// Marker component for the two half-bonds that make up a visual bond
#[derive(Component)]
struct HalfBond {
    parent_bond: Entity,
    /// Which atom this half-bond extends from
    source_atom: Entity,
}

// === PURE FUNCTIONS ===

/// Determine what should be visible for an atom in a given representation
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 => {
            // Only hydrogens get endcaps in stick mode
            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),
    }
}

/// Determine bond cylinder radius based on representation
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, // No bonds visible
    }
}

/// Calculate transform for a half-bond (from atom A toward atom B)
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();

    // If atom_radius is 0 (no visible sphere), extend bond to center
    // Otherwise, shorten the bond slightly to avoid z-fighting with atom sphere
    // Use a smaller offset (0.3 * radius) so bond extends deeper into sphere for better contact
    let offset = if atom_radius > 0.0 {
        atom_radius * 0.001
    } else {
        0.0
    };
    let half_length = (full_length / 2.0) - offset;

    // Position at quarter-point (center of the half-bond)
    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,
    )
}

/// Get material for an element
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()
    }
}

/// Check if two atoms should be bonded
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
    }
}

/// Calculate the translation needed to move a transition metal to the origin
fn center_molecule_on_metal(metal_position: Vec3) -> Vec3 {
    // Return the translation needed: negative of the metal position
    -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))
}

// === SYSTEMS ===

/// Load molecules from files
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(),
            };

            // Spawn all atoms for this molecule
            for (symbol, position) in atoms.iter() {
                let element = Element::new(symbol);

                commands.spawn((
                    Atom { element },
                    Transform::from_translation(*position),
                    molecule.clone(),
                    RepresentationStyle::Stick, // Default representation
                ));
            }

            println!("Loaded: {}", mol_name);
        }
    }
}

/// Detect bonds between atoms in the same molecule
fn detect_bonds(
    atoms: Query<(Entity, &Atom, &Transform, &Molecule), Added<Molecule>>,
    mut commands: Commands,
) {
    // Group atoms by molecule
    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));
    }

    // Detect bonds within each molecule
    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, // Inherits from molecule
                        Transform::default(),       // Parent needs a transform for children
                    ));
                }
            }
        }
    }
}

/// Center coordination complexes on their transition metal
/// If a molecule has exactly one transition metal, translate all atoms so the metal is at the origin
fn center_on_metal(
    atoms: Query<(Entity, &Atom, &Transform, &Molecule)>,
    mut transforms: Query<&mut Transform, (With<Atom>, Without<Molecule>)>,
) {
    // Group atoms by molecule, collecting only what we need (entity, is_metal, position)
    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,
            ));
    }

    // Process each molecule
    for (mol_name, atom_list) in molecules {
        // Count transition metals and get the position of the one metal (if exactly one)
        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;
            }
        }

        // Only center if exactly one transition metal found
        if metal_count == 1 {
            let translation = center_molecule_on_metal(metal_position);

            // Apply the translation to all atoms in this molecule
            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
            );
        }
    }
}

/// Render atoms based on the representation style
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 {
        // Remove old mesh if exists
        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,
            ));
        }
    }
}

/// Render bonds based on representation style and update transforms
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 {
        // First, despawn any existing half-bonds for this bond
        for (half_entity, half_bond) in &half_bonds {
            if half_bond.parent_bond == entity {
                commands.entity(half_entity).despawn();
            }
        }
        // Get atom data
        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 {
            // Get atom radii for proper bond shortening
            // If atom is invisible (None), use 0.0 so bonds meet at center
            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);

            // Calculate transforms for two half-bonds
            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,
            );

            // Create materials based on atom colors
            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)
            };

            // Spawn two half-bond entities (NOT as children, but as independent entities)
            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,
                },
            ));

            // Mark bond as rendered
            commands.entity(entity).insert(BondMesh);
        } else {
            // Spacefill mode - remove bond mesh
            commands.entity(entity).remove::<BondMesh>();
        }
    }
}

/// Update bond transforms when atoms move
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;
        };

        // Get atom radii
        // If atom is invisible (None), use 0.0 so bonds meet at center
        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);

        // Calculate new transforms
        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,
        );

        // Find and update the two half-bonds belonging to this bond
        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) {
                    // Match the half-bond to the correct atom
                    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;
                    }
                }
            }
        }
    }
}

/// Toggle representation style (example: on spacebar)
// fn toggle_representation(
//     keyboard: Res<ButtonInput<KeyCode>>,
//     mut atoms: Query<&mut RepresentationStyle, With<Atom>>,
//     mut bonds: Query<&mut RepresentationStyle, (With<Bond>, Without<Atom>)>,
// ) {
//     if keyboard.just_pressed(KeyCode::Space) {
//         for mut style in &mut atoms {
//             *style = match *style {
//                 RepresentationStyle::BallAndStick => RepresentationStyle::Stick,
//                 RepresentationStyle::Stick => RepresentationStyle::Spacefill,
//                 RepresentationStyle::Spacefill => RepresentationStyle::BallAndStick,
//             };
//         }

//         // Keep bonds in sync
//         for mut style in &mut bonds {
//             *style = match *style {
//                 RepresentationStyle::BallAndStick => RepresentationStyle::Stick,
//                 RepresentationStyle::Stick => RepresentationStyle::Spacefill,
//                 RepresentationStyle::Spacefill => RepresentationStyle::BallAndStick,
//             };
//         }
//     }
// }

pub struct MoleculePlugin;

/// Resource to hold axes entity handle and visibility (toggleable via 'C')
#[derive(Resource, Default)]
pub struct AxesResource {
    pub entity: Option<Entity>,
    pub visible: bool,
}

/// Toggle axes visibility when user presses 'C'
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>>,
) {
    // Only act on the 'C' key press
    if !keyboard.just_pressed(KeyCode::KeyC) {
        return;
    }

    if axes_res.visible {
        // Despawn axes if present
        if let Some(ent) = axes_res.entity.take() {
            commands.entity(ent).despawn_recursive();
        }
        axes_res.visible = false;
        info!("Axes hidden");
    } else {
        // Spawn a parent entity for axes
        let parent = commands
            .spawn((
                Name::new("Axes"),
                Transform::default(),
                GlobalTransform::default(),
            ))
            .id();

        // Parameters for arrows
        let shaft_radius = 0.02f32;
        let shaft_length = 2.0f32;
        let tip_radius = 0.06f32;

        // Create shared meshes for shafts and tips (use existing helpers)
        let shaft_mesh = meshes.add(Cylinder::new(shaft_radius, shaft_length));
        let tip_mesh = meshes.add(Sphere::new(tip_radius));

        // X axis (red) - shaft aligned along +X
        let mat_x = materials.add(StandardMaterial {
            base_color: Color::srgb(1.0, 0.1, 0.1),
            unlit: true,
            ..Default::default()
        });
        // Shaft is created along Y by the Cylinder; rotate -90deg around Z to point along +X
        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,
            ));
        });

        // Y axis (green) - shaft along +Y (no rotation)
        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,
            ));
        });

        // Z axis (blue) - rotate shaft from Y to Z by +90deg about X
        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
            // Load molecules from command line at startup
            .add_systems(Startup, load_molecules)
            // Detect bonds after atoms are spawned, center on metal, then render immediately
            .add_systems(
                PostStartup,
                (detect_bonds, center_on_metal, render_atoms, render_bonds).chain(),
            )
            // Update systems run every frame to handle changes
            .add_systems(
                Update,
                (
                    render_atoms,
                    render_bonds,
                    update_bond_transforms,
                    // toggle_representation,
                    // Axis toggle input (press C to show/hide axes)
                    axes_toggle_system,
                ),
            )
            // Insert resource for axes state (default: hidden)
            .insert_resource(AxesResource::default());
    }
}