Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

7.4 KB
Raw Blame
//! Identification colours, independent of materials and appearances.

use crate::Document;

/// Automatic colours select this palette in creation order; cycling uses the same order.
/// Colors are generated by picking colors on a color wheel, with 0.9 brightness and 0.8 saturation.
/// First pass is 3 colors, 120 huedegrees from each other. Second pass starts with 60 degrees from
/// the first one. Then third and fourth pass fill 60 and 30 degrees gaps between already generated
/// colors of the palette.
pub const PALETTE: [[u8; 3]; 24] = [
    [230, 161, 92],
    [92, 230, 161],
    [161, 92, 230],
    [161, 230, 92],
    [92, 161, 230],
    [230, 92, 161],
    [230, 230, 92],
    [92, 230, 92],
    [92, 230, 230],
    [92, 92, 230],
    [230, 92, 230],
    [230, 92, 92],
    [230, 195, 92],
    [195, 230, 92],
    [126, 230, 92],
    [92, 230, 126],
    [92, 230, 195],
    [92, 195, 230],
    [92, 126, 230],
    [126, 92, 230],
    [195, 92, 230],
    [230, 92, 195],
    [230, 92, 126],
    [230, 126, 92],
];

/// Select a colour in creation order, wrapping at the end of the palette.
pub fn automatic_color(index: u64) -> [u8; 3] {
    PALETTE.get((index % PALETTE.len() as u64) as usize).copied().unwrap_or([230, 161, 92])
}

pub fn next_color(color: [u8; 3]) -> [u8; 3] {
    let index = PALETTE.iter().position(|c| *c == color).map_or(0, |i| (i + 1) % PALETTE.len());
    PALETTE.get(index).copied().unwrap_or([230, 161, 92])
}

impl Document {
    pub fn component_identification_color(&self, id: u64) -> [u8; 3] {
        self.components.iter().enumerate().find(|(_, c)| c.id == id).map_or_else(
            || automatic_color(0),
            |(position, c)| c.identification_color.unwrap_or_else(|| automatic_color(c.identification_color_index.unwrap_or(position as u64))),
        )
    }

    /// Fill older records in stored order and repair stale counters without changing saved indices.
    pub(crate) fn normalise_component_color_indices(&mut self) -> crate::Result<()> {
        let mut next = self.next_component_color_index;
        for component in &self.components {
            if let Some(index) = component.identification_color_index {
                next = next.max(index.checked_add(1).ok_or_else(|| crate::DocError::Invalid("component colour sequence exhausted".into()))?);
            }
        }
        for component in &mut self.components {
            if component.identification_color_index.is_none() {
                let following = next.checked_add(1).ok_or_else(|| crate::DocError::Invalid("component colour sequence exhausted".into()))?;
                component.identification_color_index = Some(next);
                next = following;
            }
        }
        self.next_component_color_index = next;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn old_components_default_to_stable_colors_and_overrides_round_trip() {
        let mut doc = Document::default();
        let id = doc.add_component(Some("Part"), 0).unwrap();
        let automatic = doc.component_identification_color(id);
        let mut legacy: serde_json::Value = serde_json::from_str(&doc.to_json()).unwrap();
        legacy["components"][0].as_object_mut().unwrap().remove("identification_color");
        if let Some(pending) = legacy.get_mut("format_pending").and_then(|v| v.as_array_mut()) {
            pending.retain(|name| name != "component-identification-colors");
        }
        let restored = Document::from_json(&legacy.to_string()).unwrap();
        assert_eq!(restored.component_identification_color(id), automatic);
        assert_eq!(restored.components[0].identification_color, None);
        let override_color = next_color(automatic);
        assert_ne!(override_color, automatic);
        doc.components[0].identification_color = Some(override_color);
        doc.components[0].name = "Renamed".into();
        let saved = Document::from_json(&doc.to_json()).unwrap();
        assert_eq!(saved.component_identification_color(id), override_color);
        assert_eq!(saved.components[0].identification_color, Some(override_color));
    }

    #[test]
    fn creation_order_wraps_and_survives_deletion_reordering_and_reopening() {
        let mut doc = Document::default();
        let mut ids = Vec::new();
        for index in 0..25 {
            // IDs also belong to occurrences, so their numeric values are not colour indices.
            let id = doc.add_component(None, 0).unwrap();
            assert_eq!(doc.component_identification_color(id), PALETTE[index % PALETTE.len()]);
            ids.push(id);
        }
        let retained = ids[1];
        doc.components.retain(|c| c.id != ids[0]);
        doc.occurrences.retain(|o| o.component != ids[0]);
        doc.components.reverse();
        let mut restored = Document::from_json(&doc.to_json()).unwrap();
        assert_eq!(restored.component_identification_color(retained), PALETTE[1]);
        let next = restored.add_component(None, 0).unwrap();
        assert_eq!(restored.component_identification_color(next), PALETTE[1]);
        assert_eq!(restored.next_component_color_index, 26);
    }

    #[test]
    fn legacy_order_and_overrides_are_preserved_and_stale_counters_repaired() {
        let mut doc = Document::default();
        let first = doc.add_component(None, 0).unwrap();
        let second = doc.add_component(None, first).unwrap();
        doc.components[1].identification_color = Some([1, 2, 3]);
        let mut json: serde_json::Value = serde_json::from_str(&doc.to_json()).unwrap();
        json.as_object_mut().unwrap().remove("next_component_color_index");
        for component in json["components"].as_array_mut().unwrap() {
            component.as_object_mut().unwrap().remove("identification_color_index");
        }
        if let Some(pending) = json.get_mut("format_pending").and_then(|v| v.as_array_mut()) {
            pending.retain(|name| name != "sequential-component-colors");
        }
        let mut restored = Document::from_json(&json.to_string()).unwrap();
        assert_eq!(restored.components[0].identification_color_index, Some(0));
        assert_eq!(restored.components[1].identification_color_index, Some(1));
        assert_eq!(restored.component_identification_color(first), PALETTE[0]);
        assert_eq!(restored.component_identification_color(second), [1, 2, 3]);
        let third = restored.add_component(None, 0).unwrap();
        assert_eq!(restored.component_identification_color(third), PALETTE[2]);
        restored.next_component_color_index = 0;
        let mut repaired = Document::from_json(&restored.to_json()).unwrap();
        let fourth = repaired.add_component(None, 0).unwrap();
        assert_eq!(repaired.component_identification_color(fourth), PALETTE[3]);
        let mut hostile: serde_json::Value = serde_json::from_str(&repaired.to_json()).unwrap();
        hostile["components"][0]["identification_color_index"] = u64::MAX.into();
        assert!(Document::from_json(&hostile.to_string()).is_err());
    }

    #[test]
    fn cycling_visits_every_palette_color_and_wraps() {
        let original = automatic_color(123);
        let mut seen = std::collections::BTreeSet::new();
        let mut color = original;
        for _ in 0..PALETTE.len() {
            assert!(seen.insert(color));
            color = next_color(color);
        }
        assert_eq!(color, original);
        assert_eq!(automatic_color(0), PALETTE[0]);
        assert_eq!(automatic_color(1), PALETTE[1]);
        assert_eq!(automatic_color(24), PALETTE[0]);
    }
}