207 lines
7.3 KiB
Rust
207 lines
7.3 KiB
Rust
//! The scene document: what the Studio GUI and agents edit (scene.json),
|
|
//! and the prefab catalog that describes each object type.
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Map, Value};
|
|
|
|
fn one() -> u32 {
|
|
1
|
|
}
|
|
fn is_zero(v: &f64) -> bool {
|
|
*v == 0.0
|
|
}
|
|
fn is_false(v: &bool) -> bool {
|
|
!*v
|
|
}
|
|
|
|
/// A scene document: placed objects plus parameter values.
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
pub struct Doc {
|
|
#[serde(default = "one")]
|
|
pub version: u32,
|
|
/// Values for the project parameters (override the manifest defaults).
|
|
#[serde(default, skip_serializing_if = "Map::is_empty")]
|
|
pub cfg: Map<String, Value>,
|
|
#[serde(default)]
|
|
pub objects: Vec<Object>,
|
|
}
|
|
|
|
/// One placed object. Its prefab (`kind`) draws it around (x, y, z), turned
|
|
/// by `rot` degrees (multiples of 90), in its own coordinates.
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
pub struct Object {
|
|
pub id: String,
|
|
#[serde(rename = "type")]
|
|
pub kind: String,
|
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub x: f64,
|
|
#[serde(default)]
|
|
pub y: f64,
|
|
#[serde(default, skip_serializing_if = "is_zero")]
|
|
pub z: f64,
|
|
#[serde(default, skip_serializing_if = "is_zero")]
|
|
pub rot: f64,
|
|
/// Prefab properties; missing ones take the prefab defaults.
|
|
#[serde(default, skip_serializing_if = "Map::is_empty")]
|
|
pub props: Map<String, Value>,
|
|
/// Tooltip text.
|
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
|
pub info: String,
|
|
/// Label pinned above the object.
|
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
|
pub tag: String,
|
|
/// Levels the object shows on (empty: all).
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
pub levels: Vec<String>,
|
|
/// Outline or path in the object's own coordinates (areas, roads, fences).
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub pts: Option<Vec<[f64; 2]>>,
|
|
#[serde(default, skip_serializing_if = "is_false")]
|
|
pub hidden: bool,
|
|
#[serde(default, skip_serializing_if = "is_false")]
|
|
pub locked: bool,
|
|
}
|
|
|
|
/// One editable property of a prefab.
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
pub struct PropDef {
|
|
pub key: String,
|
|
/// float | int | bool | choice | text | material
|
|
#[serde(rename = "type", default = "default_kind")]
|
|
pub kind: String,
|
|
/// Default value (`def` in Rhai, where `default` is a reserved word).
|
|
#[serde(default, alias = "def")]
|
|
pub default: Value,
|
|
#[serde(default)]
|
|
pub label: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub min: Option<f64>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub max: Option<f64>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub step: Option<f64>,
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
pub choices: Vec<String>,
|
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
|
pub help: String,
|
|
}
|
|
|
|
fn default_kind() -> String {
|
|
"float".into()
|
|
}
|
|
|
|
/// An object type, read from the prefab's `meta_<type>()` function.
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
|
pub struct PrefabMeta {
|
|
#[serde(rename = "type", default)]
|
|
pub kind: String,
|
|
#[serde(default)]
|
|
pub label: String,
|
|
#[serde(default)]
|
|
pub category: String,
|
|
#[serde(default)]
|
|
pub icon: String,
|
|
#[serde(default)]
|
|
pub help: String,
|
|
/// How the Studio places it: "point" (click), "path" (click points).
|
|
#[serde(default = "default_shape")]
|
|
pub shape: String,
|
|
#[serde(default)]
|
|
pub props: Vec<PropDef>,
|
|
/// Module the prefab comes from ("isokit/site", "lib/kiosk.rhai").
|
|
#[serde(default)]
|
|
pub source: String,
|
|
}
|
|
|
|
fn default_shape() -> String {
|
|
"point".into()
|
|
}
|
|
|
|
impl PrefabMeta {
|
|
pub fn prop(&self, key: &str) -> Option<&PropDef> {
|
|
self.props.iter().find(|p| p.key == key)
|
|
}
|
|
|
|
/// Object props with the defaults filled in and numbers coerced to the
|
|
/// declared types.
|
|
pub fn resolve(&self, props: &Map<String, Value>) -> Map<String, Value> {
|
|
let mut out = props.clone();
|
|
for d in &self.props {
|
|
let v = out.get(&d.key).cloned().unwrap_or_else(|| d.default.clone());
|
|
let v = match (d.kind.as_str(), &v) {
|
|
("float", Value::Number(n)) => n.as_f64().map(Value::from).unwrap_or(v),
|
|
("float", Value::String(s)) => s.parse::<f64>().map(Value::from).unwrap_or(d.default.clone()),
|
|
("int", Value::Number(n)) => n.as_f64().map(|f| Value::from(f.round() as i64)).unwrap_or(v),
|
|
("int", Value::String(s)) => s.parse::<f64>().map(|f| Value::from(f.round() as i64)).unwrap_or(d.default.clone()),
|
|
("bool", Value::String(s)) => Value::Bool(matches!(s.as_str(), "true" | "1" | "yes" | "on")),
|
|
("bool", Value::Number(n)) => Value::Bool(n.as_f64().unwrap_or(0.0) != 0.0),
|
|
_ => v,
|
|
};
|
|
out.insert(d.key.clone(), v);
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
impl Doc {
|
|
pub fn get(&self, id: &str) -> Option<&Object> {
|
|
self.objects.iter().find(|o| o.id == id)
|
|
}
|
|
pub fn get_mut(&mut self, id: &str) -> Option<&mut Object> {
|
|
self.objects.iter_mut().find(|o| o.id == id)
|
|
}
|
|
/// A free id: `base`, `base-2`, `base-3`, ...
|
|
pub fn free_id(&self, base: &str) -> String {
|
|
let base: String = base
|
|
.chars()
|
|
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c.to_ascii_lowercase() } else { '-' })
|
|
.collect();
|
|
let base = if base.is_empty() { "obj".to_string() } else { base };
|
|
if self.get(&base).is_none() {
|
|
return base;
|
|
}
|
|
(2..).map(|i| format!("{base}-{i}")).find(|id| self.get(id).is_none()).unwrap()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn object_round_trips_compactly() {
|
|
let o: Object = serde_json::from_value(json!({"id": "t1", "type": "tree", "x": 3, "y": 4.5})).unwrap();
|
|
assert_eq!(o.kind, "tree");
|
|
let back = serde_json::to_value(&o).unwrap();
|
|
assert_eq!(back, json!({"id": "t1", "type": "tree", "x": 3.0, "y": 4.5}));
|
|
}
|
|
|
|
#[test]
|
|
fn defaults_and_coercion() {
|
|
let m = PrefabMeta {
|
|
props: vec![
|
|
PropDef { key: "r".into(), kind: "float".into(), default: json!(1.5), ..Default::default() },
|
|
PropDef { key: "n".into(), kind: "int".into(), default: json!(2), ..Default::default() },
|
|
PropDef { key: "on".into(), kind: "bool".into(), default: json!(false), ..Default::default() },
|
|
],
|
|
..Default::default()
|
|
};
|
|
let p = m.resolve(json!({"n": "3.6", "on": "yes"}).as_object().unwrap());
|
|
assert_eq!(p["r"], json!(1.5));
|
|
assert_eq!(p["n"], json!(4));
|
|
assert_eq!(p["on"], json!(true));
|
|
}
|
|
|
|
#[test]
|
|
fn free_ids() {
|
|
let mut d = Doc::default();
|
|
assert_eq!(d.free_id("Tree"), "tree");
|
|
d.objects.push(Object { id: "tree".into(), kind: "tree".into(), ..Default::default() });
|
|
d.objects.push(Object { id: "tree-2".into(), kind: "tree".into(), ..Default::default() });
|
|
assert_eq!(d.free_id("tree"), "tree-3");
|
|
}
|
|
}
|