1use re_agent::capability::{CapabilityRegistry, ToolSpec};
7use re_core::project::Project;
8use re_io;
9use serde_json::json;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use crate::project::{ProjectDoc, SharedProjectDoc};
14use crate::workspace::Workspace;
15
16#[derive(Debug)]
19pub struct ImportResult {
20 pub project: Project,
21 pub path: PathBuf,
22 pub meshes: usize,
23 pub materials: usize,
24 pub nodes: usize,
25 pub animations: usize,
26}
27
28pub fn import_gltf(path: impl AsRef<Path>) -> anyhow::Result<ImportResult> {
32 let path = path.as_ref().to_path_buf();
33 let project = re_io::import(&path).map_err(|e| anyhow::anyhow!("{e}"))?;
34 Ok(ImportResult {
35 meshes: project.library.meshes.len(),
36 materials: project.library.materials.len(),
37 nodes: project.scene.nodes.len(),
38 animations: project.library.animations.len(),
39 project,
40 path,
41 })
42}
43
44pub fn import_summary(r: &ImportResult) -> serde_json::Value {
45 json!({
46 "pfad": r.path,
47 "name": r.project.name,
48 "meshes": r.meshes,
49 "materialien": r.materials,
50 "knoten": r.nodes,
51 "animationen": r.animations,
52 })
53}
54
55fn import_into(
58 d: &SharedProjectDoc,
59 w: &Workspace,
60 path: &str,
61) -> Result<serde_json::Value, String> {
62 let path = w.resolve(path)?;
63 let r = import_gltf(&path).map_err(|e| e.to_string())?;
64 let summary = import_summary(&r);
65 let mut doc = d
66 .lock()
67 .map_err(|_| "Projekt-Sperre vergiftet".to_string())?;
68 *doc = ProjectDoc {
69 project: Some(r.project),
70 path: Some(r.path.clone()),
71 dirty: true,
72 };
73 Ok(json!({ "ok": true, "import": summary }))
74}
75
76pub fn register_import_tools(
77 reg: &mut CapabilityRegistry,
78 doc: SharedProjectDoc,
79 ws: Arc<Workspace>,
80) {
81 {
82 let d = doc.clone();
83 let w = ws.clone();
84 reg.register(
85 ToolSpec::new(
86 "import.gltf",
87 "glTF/glB importieren und als aktuelles Projekt laden (Workspace-intern)",
88 json!({ "typ": "object", "felder": { "path": { "typ": "string" } } }),
89 ),
90 move |args| {
91 let path = args
92 .get("path")
93 .and_then(|v| v.as_str())
94 .ok_or("Parameter 'path' fehlt")?;
95 import_into(&d, &w, path)
96 },
97 );
98 }
99 {
100 let d = doc.clone();
101 let w = ws.clone();
102 reg.register(
103 ToolSpec::new("import.obj", "Wavefront OBJ mit MTL-Material importieren und als aktuelles Projekt laden (Workspace-intern)", json!({ "typ": "object", "felder": { "path": { "typ": "string" } } })),
104 move |args| {
105 let path = args.get("path").and_then(|v| v.as_str()).ok_or("Parameter 'path' fehlt")?;
106 import_into(&d, &w, path)
107 },
108 );
109 }
110 {
111 let w = ws;
112 reg.register(
113 ToolSpec::new("import.preview", "Modell-Datei einlesen und Zähler liefern, ohne das Projekt zu ersetzen (Workspace-intern)", json!({ "typ": "object", "felder": { "path": { "typ": "string" } } })),
114 move |args| {
115 let path = args.get("path").and_then(|v| v.as_str()).ok_or("Parameter 'path' fehlt")?;
116 let path = w.resolve(path)?;
117 let r = import_gltf(path).map_err(|e| e.to_string())?;
118 Ok(import_summary(&r))
119 },
120 );
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use crate::register_project_tools;
128 use re_agent::CapabilityRegistry;
129 use re_core::primitives::{self, PrimitiveKind};
130 use re_core::project::Project;
131 use re_core::scene::NodeKind;
132 use re_core::transform::Transform;
133 use serde_json::json;
134 use std::fs;
135 use std::sync::Mutex;
136
137 fn make_and_export_gltf(dir: &std::path::Path) -> std::path::PathBuf {
138 let mut p = Project::new("imp");
139 let mesh = primitives::generate(PrimitiveKind::Box, 1.0, 1.0, 1);
140 let mid = p.library.add_mesh(mesh);
141 p.scene.insert(
142 None,
143 re_core::scene::Node {
144 name: "Cube".into(),
145 transform: Transform::default(),
146 kind: NodeKind::MeshInstance {
147 mesh: mid,
148 material: None,
149 skeleton_node: None,
150 },
151 ..Default::default()
152 },
153 );
154 let path = dir.join("demo.gltf");
155 re_io::export(&p, &path).expect("export");
156 path
157 }
158
159 #[test]
160 fn import_liefert_projekt_mit_zaehlern() {
161 let dir = std::env::temp_dir().join(format!("re_imp_{}", std::process::id()));
162 let _ = fs::remove_dir_all(&dir);
163 fs::create_dir_all(&dir).unwrap();
164 let path = make_and_export_gltf(&dir);
165 let r = import_gltf(&path).unwrap();
166 assert!(r.meshes >= 1);
167 assert!(r.nodes >= 1);
168 assert_eq!(r.project.name, "demo");
169 let _ = fs::remove_dir_all(&dir);
170 }
171
172 #[test]
173 fn capabilities_importieren_in_projekt() {
174 let dir = std::env::temp_dir().join(format!("re_imp2_{}", std::process::id()));
175 let _ = fs::remove_dir_all(&dir);
176 fs::create_dir_all(&dir).unwrap();
177 let path = make_and_export_gltf(&dir);
178 let ws = Arc::new(Workspace::new(&dir));
179 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
180 let mut reg = CapabilityRegistry::new();
181 register_import_tools(&mut reg, doc.clone(), ws.clone());
182 register_project_tools(&mut reg, doc.clone(), ws);
183 let res = reg.call("import.gltf", json!({ "path": path })).unwrap();
184 assert!(res["ok"].as_bool().unwrap());
185 assert!(res["import"]["meshes"].as_u64().unwrap() >= 1);
186 let info = reg.call("project.info", json!({})).unwrap();
187 assert!(info["geladen"].as_bool().unwrap());
188 assert!(info["dirty"].as_bool().unwrap());
189 let before = reg.call("project.info", json!({})).unwrap()["knoten"].clone();
191 reg.call("import.preview", json!({ "path": path })).unwrap();
192 let after = reg.call("project.info", json!({})).unwrap()["knoten"].clone();
193 assert_eq!(before, after);
194 let _ = fs::remove_dir_all(&dir);
195 }
196
197 #[test]
198 fn capability_importiert_obj_mit_mtl() {
199 let dir = std::env::temp_dir().join(format!("re_imp4_{}", std::process::id()));
200 let _ = fs::remove_dir_all(&dir);
201 fs::create_dir_all(&dir).unwrap();
202 fs::write(dir.join("m.mtl"), "newmtl Blau\nKd 0 0 1\nNs 50\n").unwrap();
203 fs::write(
204 dir.join("s.obj"),
205 "mtllib m.mtl\nusemtl Blau\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvn 0 0 1\nf 1//1 2//1 3//1\n",
206 )
207 .unwrap();
208 let ws = Arc::new(Workspace::new(&dir));
209 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
210 let mut reg = CapabilityRegistry::new();
211 register_import_tools(&mut reg, doc.clone(), ws.clone());
212 register_project_tools(&mut reg, doc.clone(), ws);
213 let res = reg.call("import.obj", json!({ "path": "s.obj" })).unwrap();
214 assert!(res["ok"].as_bool().unwrap());
215 assert_eq!(res["import"]["meshes"], json!(1));
216 assert_eq!(res["import"]["materialien"], json!(1), "MTL hängt am Mesh");
217 let info = reg.call("project.info", json!({})).unwrap();
218 assert!(info["geladen"].as_bool().unwrap());
219 assert!(reg.call("import.gltf", json!({ "path": "s.obj" })).is_ok());
222 let _ = fs::remove_dir_all(&dir);
223 }
224
225 #[test]
226 fn fehlende_datei_fehler() {
227 let dir = std::env::temp_dir().join(format!("re_imp3_{}", std::process::id()));
228 let _ = fs::remove_dir_all(&dir);
229 fs::create_dir_all(&dir).unwrap();
230 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
231 let mut reg = CapabilityRegistry::new();
232 register_import_tools(&mut reg, doc.clone(), Arc::new(Workspace::new(&dir)));
233 assert!(reg
234 .call("import.gltf", json!({ "path": "nope.gltf" }))
235 .is_err());
236 assert!(reg
237 .call("import.preview", json!({ "path": "nope.gltf" }))
238 .is_err());
239 assert!(reg
241 .call("import.preview", json!({ "path": "/etc/passwd" }))
242 .is_err());
243 assert!(reg
244 .call("import.gltf", json!({ "path": "../../geheim.gltf" }))
245 .is_err());
246 let _ = fs::remove_dir_all(&dir);
247 }
248}