1use std::collections::{BTreeMap, BTreeSet};
11use std::io::Cursor;
12
13use vibe::Value;
14
15use crate::render::rdf_holograph::{
16 classify_resource_kind, display_local_name, fill_label_names, intern_kind, layout_nquins_into,
17 layout_placed_into, PlacedHolograph, RdfHolographScene,
18};
19use crate::sparql_library::rdf_formats::{parse_rdf, QuinCollector, RdfFormat};
20use crate::vibe_host::PoetSnapshot;
21use crate::{q_hash, NQuin};
22
23const RDF_TYPE: u64 = q_hash("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
24const FLAG_SUBJECT: u8 = 1;
25const FLAG_CLASS: u8 = 2;
26
27pub const CINEMA_GRAPH_VIBE: &str = include_str!("../../../../docs/vibe/cinema-graph.vibe");
30
31#[derive(Debug, Clone, Copy)]
33pub struct TheatreCamera {
34 pub yaw: f32,
35 pub pitch: f32,
36 pub zoom: f32,
37}
38
39impl Default for TheatreCamera {
40 fn default() -> Self {
41 Self {
42 yaw: 0.55,
43 pitch: 0.48,
44 zoom: 0.0,
45 }
46 }
47}
48
49pub type TheatreLayoutKind = &'static str;
51
52struct InternedRdf {
53 names: BTreeMap<u64, String>,
54 quoted: BTreeSet<u64>,
55}
56
57fn intern_names_from_rdf_text(payload: &str) -> InternedRdf {
58 let mut prefixes: BTreeMap<String, String> = BTreeMap::new();
59 let mut quoted: BTreeSet<u64> = BTreeSet::new();
60 for raw in payload.lines() {
61 let line = raw.trim();
62 let lower = line.to_ascii_lowercase();
63 let rest = if let Some(r) = lower.strip_prefix("@prefix ") {
64 &line[line.len() - r.len()..]
65 } else if let Some(r) = lower.strip_prefix("prefix ") {
66 &line[line.len() - r.len()..]
67 } else {
68 continue;
69 };
70 let Some((pfx, iri_part)) = rest.split_once(':') else {
71 continue;
72 };
73 let pfx = pfx.trim();
74 let Some(start) = iri_part.find('<') else {
75 continue;
76 };
77 let Some(end) = iri_part[start + 1..].find('>') else {
78 continue;
79 };
80 let iri = &iri_part[start + 1..start + 1 + end];
81 prefixes.insert(pfx.to_string(), iri.to_string());
82 }
83
84 let mut names: BTreeMap<u64, String> = BTreeMap::new();
85 let put = |map: &mut BTreeMap<u64, String>, lexical: &str| {
86 if lexical.is_empty() {
87 return;
88 }
89 let h = q_hash(lexical);
90 let local = display_local_name(lexical);
91 if local.is_empty() {
92 return;
93 }
94 map.entry(h).or_insert_with(|| local.chars().take(24).collect());
95 };
96
97 let bytes = payload.as_bytes();
98 let mut i = 0usize;
99 while i < bytes.len() {
100 let c = bytes[i];
101 if c == b'<' {
102 if let Some(rel) = payload[i + 1..].find('>') {
103 put(&mut names, &payload[i + 1..i + 1 + rel]);
104 i += rel + 2;
105 continue;
106 }
107 }
108 if c == b'"' {
109 if let Some(rel) = payload[i + 1..].find('"') {
110 let lex = &payload[i + 1..i + 1 + rel];
111 put(&mut names, lex);
112 if !lex.is_empty() {
113 quoted.insert(q_hash(lex));
114 }
115 i += rel + 2;
116 continue;
117 }
118 }
119 i += 1;
120 }
121
122 let mut token = String::new();
123 for ch in payload.chars() {
124 if ch.is_ascii_alphanumeric() || ch == '_' || ch == ':' || ch == '-' {
125 token.push(ch);
126 continue;
127 }
128 if let Some((pfx, local)) = token.split_once(':') {
129 if !pfx.is_empty()
130 && !local.is_empty()
131 && pfx != "http"
132 && pfx != "https"
133 && !pfx.starts_with('@')
134 {
135 if let Some(base) = prefixes.get(pfx) {
136 put(&mut names, &format!("{base}{local}"));
137 } else {
138 put(&mut names, local);
139 }
140 }
141 }
142 token.clear();
143 }
144 InternedRdf { names, quoted }
145}
146
147fn resource_records(quins: &[NQuin], intern: &InternedRdf) -> (Value, Value) {
148 let mut ids: BTreeMap<u64, (u32, u8)> = BTreeMap::new();
149 for q in quins {
150 let e = ids.entry(q.subject).or_insert((0, 0));
151 e.0 = e.0.saturating_add(1);
152 e.1 |= FLAG_SUBJECT;
153 let e = ids.entry(q.object).or_insert((0, 0));
154 e.0 = e.0.saturating_add(1);
155 if q.predicate == RDF_TYPE {
156 e.1 |= FLAG_CLASS;
157 }
158 }
159 let mut resources = Vec::with_capacity(ids.len());
160 for (id, (degree, flags)) in &ids {
161 let kind = classify_resource_kind(
162 *flags & FLAG_SUBJECT != 0,
163 *flags & FLAG_CLASS != 0,
164 *degree,
165 intern.quoted.contains(id),
166 );
167 let name = intern.names.get(id).cloned().unwrap_or_default();
168 let mut rec = BTreeMap::new();
169 rec.insert("id".into(), Value::U64(*id));
170 rec.insert("kind".into(), Value::String(kind.into()));
171 rec.insert("name".into(), Value::String(name));
172 rec.insert("degree".into(), Value::F64(*degree as f64));
173 resources.push(Value::Record(rec));
174 }
175 let mut triples = Vec::with_capacity(quins.len());
176 for q in quins {
177 let mut rec = BTreeMap::new();
178 rec.insert("subject".into(), Value::U64(q.subject));
179 rec.insert("predicate".into(), Value::U64(q.predicate));
180 rec.insert("object".into(), Value::U64(q.object));
181 rec.insert("is_type".into(), Value::Bool(q.predicate == RDF_TYPE));
182 rec.insert(
183 "name".into(),
184 Value::String(intern.names.get(&q.predicate).cloned().unwrap_or_default()),
185 );
186 triples.push(Value::Record(rec));
187 }
188 (Value::List(resources), Value::List(triples))
189}
190
191fn rec_f64(v: &Value, key: &str) -> f64 {
192 match v {
193 Value::Record(m) => match m.get(key) {
194 Some(Value::F64(n)) => *n,
195 Some(Value::I64(n)) => *n as f64,
196 Some(Value::U64(n)) => *n as f64,
197 _ => 0.0,
198 },
199 _ => 0.0,
200 }
201}
202
203fn rec_u64(v: &Value, key: &str) -> u64 {
204 match v {
205 Value::Record(m) => match m.get(key) {
206 Some(Value::U64(n)) => *n,
207 Some(Value::I64(n)) if *n >= 0 => *n as u64,
208 Some(Value::F64(n)) if *n >= 0.0 && n.fract() == 0.0 => *n as u64,
209 _ => 0,
210 },
211 _ => 0,
212 }
213}
214
215fn rec_bool(v: &Value, key: &str) -> bool {
216 match v {
217 Value::Record(m) => matches!(m.get(key), Some(Value::Bool(true))),
218 _ => false,
219 }
220}
221
222fn rec_str<'a>(v: &'a Value, key: &str) -> &'a str {
223 match v {
224 Value::Record(m) => match m.get(key) {
225 Some(Value::String(s)) => s.as_str(),
226 _ => "",
227 },
228 _ => "",
229 }
230}
231
232fn rec_list<'a>(v: &'a Value, key: &str) -> &'a [Value] {
233 match v {
234 Value::Record(m) => match m.get(key) {
235 Some(Value::List(xs)) => xs.as_slice(),
236 _ => &[],
237 },
238 _ => &[],
239 }
240}
241
242fn placed_from_record(v: &Value) -> PlacedHolograph {
243 let mut p = PlacedHolograph {
244 id: rec_u64(v, "id"),
245 kind: intern_kind(rec_str(v, "kind")),
246 degree: rec_f64(v, "degree") as u32,
247 position: [
248 rec_f64(v, "x") as f32,
249 rec_f64(v, "y") as f32,
250 rec_f64(v, "z") as f32,
251 ],
252 endpoint: [
253 rec_f64(v, "x2") as f32,
254 rec_f64(v, "y2") as f32,
255 rec_f64(v, "z2") as f32,
256 ],
257 scale: rec_f64(v, "scale") as f32,
258 is_type: rec_bool(v, "is_type"),
259 ..PlacedHolograph::default()
260 };
261 if p.scale <= 0.0 {
262 p.scale = match p.kind {
263 "class" => 0.46,
264 "literal" => 0.20,
265 "predicate" => 0.05,
266 "plane" => 0.85,
267 _ => 0.30,
268 };
269 }
270 p.set_name(rec_str(v, "name"));
271 p
272}
273
274fn camera_from_value(v: &Value) -> TheatreCamera {
275 let mut cam = TheatreCamera::default();
276 if matches!(v, Value::Record(_)) {
277 cam.yaw = rec_f64(v, "yaw") as f32;
278 cam.pitch = rec_f64(v, "pitch") as f32;
279 cam.zoom = rec_f64(v, "zoom") as f32;
280 }
281 cam
282}
283
284fn fill_scene_names(scene: &mut RdfHolographScene, names: &BTreeMap<u64, String>) {
285 fill_label_names(scene, |id| names.get(&id).map(String::as_str));
286}
287
288fn eval_construct_theatre(src: &str, resources: Value, triples: Value) -> Result<Value, String> {
289 let mut host = PoetSnapshot::default();
290 host.eval_fn(src, "construct_theatre", vec![resources, triples])
291 .map_err(|d| d.message)
292}
293
294pub fn layout_rdf_with_vibe_into(
298 content_type: &str,
299 payload: &str,
300 vibe_src: &str,
301 scene: &mut RdfHolographScene,
302) -> Result<(TheatreCamera, TheatreLayoutKind), &'static str> {
303 let format = RdfFormat::from_media_type(content_type)
304 .or_else(|| RdfFormat::from_str(content_type))
305 .ok_or("unsupported RDF Content-Type / format")?;
306 let mut collector = QuinCollector::new();
307 parse_rdf(format, Cursor::new(payload.as_bytes()), 0, &mut collector)
308 .map_err(|_| "rdf_holograph_parse_failed")?;
309 let quins = collector.as_slice();
310 if quins.is_empty() {
311 return Err("rdf_holograph_empty_graph");
312 }
313 let intern = intern_names_from_rdf_text(payload);
314 let (resources, triples) = resource_records(quins, &intern);
315 let src = if vibe_src.trim().is_empty() {
316 CINEMA_GRAPH_VIBE
317 } else {
318 vibe_src
319 };
320 match eval_construct_theatre(src, resources, triples) {
321 Ok(theatre) => {
322 let mut placed: Vec<PlacedHolograph> = Vec::new();
323 for key in ["nodes", "edges", "planes"] {
324 for item in rec_list(&theatre, key) {
325 placed.push(placed_from_record(item));
326 }
327 }
328 if placed.is_empty() {
329 layout_nquins_into(quins, scene);
330 fill_scene_names(scene, &intern.names);
331 scene.truncated = scene.truncated || collector.truncated;
332 return Ok((TheatreCamera::default(), "nquins"));
333 }
334 let triple_count = rec_list(&theatre, "edges").len() as u32;
335 layout_placed_into(&placed, triple_count.max(quins.len() as u32), scene);
336 fill_scene_names(scene, &intern.names);
337 scene.truncated = scene.truncated || collector.truncated;
338 let mut cam = camera_from_value(match &theatre {
339 Value::Record(m) => m.get("camera").unwrap_or(&Value::Null),
340 _ => &Value::Null,
341 });
342 if cam.yaw == 0.0 && cam.pitch == 0.0 {
343 cam = TheatreCamera::default();
344 }
345 Ok((cam, "vibe"))
346 }
347 Err(_) => {
348 layout_nquins_into(quins, scene);
349 fill_scene_names(scene, &intern.names);
350 scene.truncated = scene.truncated || collector.truncated;
351 Ok((TheatreCamera::default(), "nquins"))
352 }
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 const FOAF: &str = r#"@prefix foaf: <http://xmlns.com/foaf/0.1/> .
361@prefix ex: <http://ex/> .
362ex:alice foaf:knows ex:bob .
363ex:bob foaf:knows ex:carol .
364ex:carol foaf:knows ex:alice .
365ex:alice foaf:name "Alice" .
366"#;
367
368 #[test]
369 fn cinema_graph_vibe_parses_checks_and_evals() {
370 let prog = vibe::parse_program(CINEMA_GRAPH_VIBE)
371 .unwrap_or_else(|e| panic!("parse cinema-graph.vibe: {e}"));
372 vibe::check_program(&prog).unwrap_or_else(|e| panic!("check cinema-graph.vibe: {e}"));
373 let mut resources = Vec::new();
374 let mut rec = BTreeMap::new();
375 rec.insert("id".into(), Value::U64(1));
376 rec.insert("kind".into(), Value::String("instance".into()));
377 rec.insert("name".into(), Value::String("alice".into()));
378 rec.insert("degree".into(), Value::F64(1.0));
379 resources.push(Value::Record(rec));
380 let mut host = PoetSnapshot::default();
381 host.eval_fn(
382 CINEMA_GRAPH_VIBE,
383 "construct_theatre",
384 vec![Value::List(resources), Value::List(vec![])],
385 )
386 .unwrap_or_else(|e| panic!("eval construct_theatre: {e}"));
387 }
388
389 #[test]
390 fn intern_names_recovers_local_and_literal() {
391 let intern = intern_names_from_rdf_text(FOAF);
392 assert!(intern.names.values().any(|n| n == "alice"));
393 assert!(intern.names.values().any(|n| n == "Alice"));
394 assert!(intern.names.values().any(|n| n == "knows"));
395 assert!(intern.quoted.contains(&q_hash("Alice")));
396 assert!(!intern.quoted.contains(&q_hash("http://ex/alice")));
397 }
398
399 const STAR: &str = r#"@prefix ex: <http://ex/> .
400@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
401ex:nucleus rdf:type ex:Core .
402ex:nucleus ex:emits ex:photon .
403ex:nucleus ex:binds ex:electron .
404"#;
405
406 #[test]
407 fn cinema_vibe_star_types_iri_objects_as_instances() {
408 let mut scene = Box::new(RdfHolographScene::empty());
409 let (_, kind) =
410 layout_rdf_with_vibe_into("text/turtle", STAR, CINEMA_GRAPH_VIBE, &mut scene)
411 .expect("layout");
412 assert_eq!(kind, "vibe");
413 assert!(scene
414 .labels()
415 .iter()
416 .any(|l| l.name_str() == "electron" && l.kind == "instance"));
417 assert!(scene
418 .labels()
419 .iter()
420 .any(|l| l.name_str() == "Core" && l.kind == "class"));
421 assert!(scene.labels().iter().any(|l| l.kind == "plane"));
422 }
423
424 #[test]
425 fn cinema_vibe_places_foaf_as_named_graph() {
426 let mut scene = Box::new(RdfHolographScene::empty());
427 let (cam, kind) =
428 layout_rdf_with_vibe_into("text/turtle", FOAF, CINEMA_GRAPH_VIBE, &mut scene)
429 .expect("layout");
430 assert_eq!(kind, "vibe", "construct_theatre must author the theatre");
431 assert!(scene.node_count() >= 5);
432 assert!(scene.labels().iter().any(|l| l.name_str() == "alice"));
433 assert!(scene.labels().iter().any(|l| l.kind == "predicate"));
434 let resources: Vec<_> = scene
435 .labels()
436 .iter()
437 .filter(|l| l.kind != "predicate" && l.kind != "plane")
438 .collect();
439 assert!(resources.len() >= 3);
440 let mut min_sep = f32::MAX;
441 for i in 0..resources.len() {
442 for j in (i + 1)..resources.len() {
443 let d = (resources[i].position[0] - resources[j].position[0]).hypot(
444 (resources[i].position[2] - resources[j].position[2])
445 .hypot(resources[i].position[1] - resources[j].position[1]),
446 );
447 min_sep = min_sep.min(d);
448 }
449 }
450 assert!(min_sep > 0.35, "FOAF resources must sit apart (sep={min_sep})");
451 assert!(cam.yaw > 0.3 && cam.pitch > 0.3);
452 }
453}