feat(tahuantinsuyu): fase 3 — engine real contra eternal + rueda pintada en GPUI
Bridge a eternal-astrology prendido por default. `engine::compute(chart)` abre una EphemerisSession VSOP2013 (cacheada vía OnceLock global), traduce los Stored* del modelo a BirthData/ChartConfig de eternal, corre NatalChart::compute + find_aspects(modern_western) y devuelve un RenderModel con cuatro capas: SignDial, Houses, Bodies, Aspects. - tahuantinsuyu-engine: bridge.rs nuevo con map_house_system, map_zodiac (incl. 8 ayanamshas), map_body_set, body_symbol, aspect_kind_id. compute_mock se mantiene como fallback sin feature. Errores tipados (EngineError::Eternal). Test real verde con datos natales de demo. - tahuantinsuyu-canvas: rewrite con gpui::canvas() + PathBuilder. Pinta: sectores zodiacales coloreados por elemento (Fire/Earth/Air/ Water), anillos de sign-dial/houses/aspects, cusps zodiacales, cusps de casas (con énfasis para Asc/MC/Desc/IC), líneas radiales hasta el centro para los ejes, líneas de aspectos coloreadas por kind con opacidad por orb, dots de cuerpos. Glifos unicode (♈-♓ signos, ☉-♇ planetas, ☊☋⚷⚸ puntos) como divs absolutos sobre el canvas. Marcador ᴿ cuando retrógrado. Rotación canónica: Asc a las 9, casas crecen contrarreloj. - shell: ahora llama engine::compute() real y reporta errores por stderr sin caer la app. Datos sintetizados: ascendente, MC, descendente, IC; 12 cusps de casa según el sistema configurado; placements de los cuerpos del BodySet con sus longitudes zodiacales, casa y flag retrógrado; aspectos mayores con opacidad proporcional al orb. `cargo check` y `cargo test --features eternal-bridge` verdes. La fase 4 traerá el panel interactivo (jog-dial, toggles, sliders, atajos teclado). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -23,8 +23,9 @@ path = "../../../../../eternal/eternal-sky"
|
||||
optional = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# Activa el bridge real contra eternal-astrology. Sin este feature, la
|
||||
# engine sólo expone el RenderModel y mocks — útil para tests y para
|
||||
# compilar la UI antes de que eternal esté disponible.
|
||||
# El bridge real contra eternal-astrology está prendido por default
|
||||
# porque la app sin eternal no muestra cartas reales. Si necesitás
|
||||
# compilar sin eternal checked out (CI, builds aisladas), `--no-default-features`
|
||||
# lo apaga y `compute()` cae a `compute_mock()`.
|
||||
default = ["eternal-bridge"]
|
||||
eternal-bridge = ["dep:eternal-astrology", "dep:eternal-sky"]
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Bridge real: `tahuantinsuyu_model::Chart` → eternal_astrology → [`RenderModel`].
|
||||
//!
|
||||
//! La sesión de efemérides VSOP2013 es **compartida globalmente** vía
|
||||
//! `OnceLock` — abrirla cuesta unos cuantos ms (carga de las series en
|
||||
//! memoria), y como es read-only se puede leer en paralelo desde varios
|
||||
//! cómputos.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Instant;
|
||||
|
||||
use eternal_astrology::{
|
||||
find_aspects, Aspect, AspectKind as EAspectKind, BirthData, BodySet, ChartConfig,
|
||||
HouseSystem as EHouseSystem, NatalChart, OrbTable, Zodiac as EZodiac,
|
||||
};
|
||||
use eternal_sky::{Ayanamsha, Body, EphemerisSession, Instant as ESInstant, Observer, SessionConfig};
|
||||
|
||||
use tahuantinsuyu_model::{Chart, HouseSystem, StoredChartConfig, Zodiac};
|
||||
|
||||
use crate::{EngineError, Geometry, Glyph, Layer, LayerKind, LineSeg, RenderModel};
|
||||
|
||||
// =====================================================================
|
||||
// Sesión global cacheada
|
||||
// =====================================================================
|
||||
|
||||
static SESSION: OnceLock<EphemerisSession> = OnceLock::new();
|
||||
|
||||
fn session() -> Result<&'static EphemerisSession, EngineError> {
|
||||
if let Some(s) = SESSION.get() {
|
||||
return Ok(s);
|
||||
}
|
||||
let opened = EphemerisSession::open(SessionConfig::vsop2013())
|
||||
.map_err(|e| EngineError::Eternal(format!("EphemerisSession::open: {:?}", e)))?;
|
||||
// Si otro thread ya pobló la celda mientras abríamos, el set_once
|
||||
// falla silenciosamente — usamos el que quedó dentro.
|
||||
let _ = SESSION.set(opened);
|
||||
Ok(SESSION.get().expect("session was just set"))
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Traducciones Stored* → eternal
|
||||
// =====================================================================
|
||||
|
||||
fn map_house_system(h: HouseSystem) -> EHouseSystem {
|
||||
match h {
|
||||
HouseSystem::Placidus => EHouseSystem::Placidus,
|
||||
HouseSystem::Koch => EHouseSystem::Koch,
|
||||
HouseSystem::Regiomontanus => EHouseSystem::Regiomontanus,
|
||||
HouseSystem::Campanus => EHouseSystem::Campanus,
|
||||
HouseSystem::Porphyry => EHouseSystem::Porphyry,
|
||||
HouseSystem::Equal => EHouseSystem::Equal,
|
||||
HouseSystem::WholeSign => EHouseSystem::WholeSign,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_zodiac(z: Zodiac, ayanamsha_hint: Option<&str>) -> EZodiac {
|
||||
match z {
|
||||
Zodiac::Tropical => EZodiac::Tropical,
|
||||
Zodiac::Sidereal => {
|
||||
let mode = match ayanamsha_hint.unwrap_or("lahiri").to_ascii_lowercase().as_str() {
|
||||
"fagan_bradley" | "fagan-bradley" | "faganbradley" => Ayanamsha::FaganBradley,
|
||||
"raman" => Ayanamsha::Raman,
|
||||
"krishnamurti" => Ayanamsha::Krishnamurti,
|
||||
"de_luce" | "deluce" => Ayanamsha::DeLuce,
|
||||
"djwhal_khul" | "djwhalkhul" => Ayanamsha::DjwhalKhul,
|
||||
"ushashashi" => Ayanamsha::Ushashashi,
|
||||
"yukteshwar" => Ayanamsha::Yukteshwar,
|
||||
_ => Ayanamsha::Lahiri,
|
||||
};
|
||||
EZodiac::Sidereal(mode)
|
||||
}
|
||||
// Dracónico aún no soportado en eternal — caemos a tropical por
|
||||
// ahora; cuando eternal lo agregue, lo cableamos acá.
|
||||
Zodiac::Draconic => EZodiac::Tropical,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_body_set(cfg: &StoredChartConfig) -> BodySet {
|
||||
let mut bodies: Vec<Body> = Vec::new();
|
||||
for name in &cfg.bodies {
|
||||
if let Some(b) = map_body(name) {
|
||||
bodies.push(b);
|
||||
}
|
||||
}
|
||||
if bodies.is_empty() {
|
||||
// Default razonable si el config vino vacío.
|
||||
return BodySet::classical_modern();
|
||||
}
|
||||
let mut set = BodySet {
|
||||
bodies,
|
||||
include_south_node: cfg.include_south_node,
|
||||
};
|
||||
if cfg.include_lilith {
|
||||
set = set.with_lilith();
|
||||
}
|
||||
if cfg.include_main_belt_asteroids {
|
||||
set = set.with_main_belt_asteroids();
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
fn map_body(name: &str) -> Option<Body> {
|
||||
Some(match name.to_ascii_lowercase().as_str() {
|
||||
"sun" => Body::Sun,
|
||||
"moon" => Body::Moon,
|
||||
"mercury" => Body::Mercury,
|
||||
"venus" => Body::Venus,
|
||||
"mars" => Body::Mars,
|
||||
"jupiter" => Body::Jupiter,
|
||||
"saturn" => Body::Saturn,
|
||||
"uranus" => Body::Uranus,
|
||||
"neptune" => Body::Neptune,
|
||||
"pluto" => Body::Pluto,
|
||||
"mean_node" | "meannode" => Body::MeanNode,
|
||||
"true_node" | "truenode" => Body::TrueNode,
|
||||
"mean_lilith" | "lilith" => Body::MeanLilith,
|
||||
"true_lilith" => Body::TrueLilith,
|
||||
"ceres" => Body::Ceres,
|
||||
"pallas" => Body::Pallas,
|
||||
"juno" => Body::Juno,
|
||||
"vesta" => Body::Vesta,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn body_symbol(b: Body) -> &'static str {
|
||||
match b {
|
||||
Body::Sun => "sun",
|
||||
Body::Moon => "moon",
|
||||
Body::Mercury => "mercury",
|
||||
Body::Venus => "venus",
|
||||
Body::Mars => "mars",
|
||||
Body::Jupiter => "jupiter",
|
||||
Body::Saturn => "saturn",
|
||||
Body::Uranus => "uranus",
|
||||
Body::Neptune => "neptune",
|
||||
Body::Pluto => "pluto",
|
||||
Body::MeanNode => "north_node",
|
||||
Body::TrueNode => "north_node",
|
||||
Body::MeanLilith => "lilith",
|
||||
Body::TrueLilith => "lilith",
|
||||
Body::Ceres => "ceres",
|
||||
Body::Pallas => "pallas",
|
||||
Body::Juno => "juno",
|
||||
Body::Vesta => "vesta",
|
||||
Body::Chiron => "chiron",
|
||||
Body::Pholus => "chiron",
|
||||
Body::Eris => "chiron",
|
||||
Body::Sedna => "chiron",
|
||||
// `Body` es `#[non_exhaustive]` — cualquier cuerpo nuevo
|
||||
// upstream cae al símbolo de fallback hasta que lo cableemos.
|
||||
_ => "custom",
|
||||
}
|
||||
}
|
||||
|
||||
fn aspect_kind_id(k: EAspectKind) -> &'static str {
|
||||
match k {
|
||||
EAspectKind::Conjunction => "conjunction",
|
||||
EAspectKind::Opposition => "opposition",
|
||||
EAspectKind::Trine => "trine",
|
||||
EAspectKind::Square => "square",
|
||||
EAspectKind::Sextile => "sextile",
|
||||
EAspectKind::Quincunx => "quincunx",
|
||||
EAspectKind::SemiSextile => "semi_sextile",
|
||||
EAspectKind::SemiSquare => "semi_square",
|
||||
EAspectKind::Sesquiquadrate => "sesquiquadrate",
|
||||
EAspectKind::Quintile => "quintile",
|
||||
EAspectKind::BiQuintile => "biquintile",
|
||||
EAspectKind::Septile => "septile",
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// compute()
|
||||
// =====================================================================
|
||||
|
||||
pub fn compute(chart: &Chart) -> Result<RenderModel, EngineError> {
|
||||
let t0 = Instant::now();
|
||||
chart.validate()?;
|
||||
|
||||
let bd = &chart.birth_data;
|
||||
let instant = ESInstant::from_civil_local(
|
||||
bd.year,
|
||||
u8::try_from(bd.month).map_err(|_| {
|
||||
EngineError::Eternal(format!("mes fuera de u8: {}", bd.month))
|
||||
})?,
|
||||
u8::try_from(bd.day).map_err(|_| {
|
||||
EngineError::Eternal(format!("día fuera de u8: {}", bd.day))
|
||||
})?,
|
||||
u8::try_from(bd.hour).map_err(|_| {
|
||||
EngineError::Eternal(format!("hora fuera de u8: {}", bd.hour))
|
||||
})?,
|
||||
u8::try_from(bd.minute).map_err(|_| {
|
||||
EngineError::Eternal(format!("minuto fuera de u8: {}", bd.minute))
|
||||
})?,
|
||||
bd.second,
|
||||
bd.tz_offset_minutes,
|
||||
)
|
||||
.map_err(|e| EngineError::Eternal(format!("Instant::from_civil_local: {:?}", e)))?;
|
||||
|
||||
let observer = Observer::from_degrees(bd.latitude_deg, bd.longitude_deg, bd.altitude_m);
|
||||
|
||||
let mut birth_e = BirthData::new(instant, observer);
|
||||
if let Some(name) = &bd.subject_name {
|
||||
birth_e = birth_e.with_name(name.clone());
|
||||
}
|
||||
|
||||
let config_e = ChartConfig {
|
||||
house_system: map_house_system(chart.config.house_system),
|
||||
zodiac: map_zodiac(chart.config.zodiac, chart.config.ayanamsha.as_deref()),
|
||||
bodies: map_body_set(&chart.config),
|
||||
include_horizon: false,
|
||||
};
|
||||
|
||||
let session = session()?;
|
||||
let natal = NatalChart::compute(&birth_e, &config_e, session)
|
||||
.map_err(|e| EngineError::Eternal(format!("NatalChart::compute: {:?}", e)))?;
|
||||
|
||||
let aspects = find_aspects(&natal, &OrbTable::modern_western());
|
||||
|
||||
let render = build_render_model(chart, &natal, &aspects, t0);
|
||||
Ok(render)
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// NatalChart → RenderModel
|
||||
// =====================================================================
|
||||
|
||||
fn build_render_model(
|
||||
chart: &Chart,
|
||||
natal: &NatalChart,
|
||||
aspects: &[Aspect],
|
||||
started: Instant,
|
||||
) -> RenderModel {
|
||||
let ascendant_deg = natal.ascendant().longitude_deg() as f32;
|
||||
let midheaven_deg = natal.midheaven().longitude_deg() as f32;
|
||||
let descendant_deg = natal.descendant().longitude_deg() as f32;
|
||||
let imum_coeli_deg = natal.imum_coeli().longitude_deg() as f32;
|
||||
|
||||
// ─── Capa 0: Sign Dial ────────────────────────────────────────────
|
||||
let sign_dial = Layer {
|
||||
module_id: "natal".into(),
|
||||
kind: LayerKind::SignDial,
|
||||
ring: 1.0,
|
||||
z: 0,
|
||||
geometry: Geometry::Ring {
|
||||
cusps_deg: (0..12).map(|i| (i as f32) * 30.0).collect(),
|
||||
},
|
||||
glyphs: (0..12)
|
||||
.map(|i| Glyph {
|
||||
deg: (i as f32) * 30.0 + 15.0,
|
||||
symbol: ZODIAC_SYMBOLS[i].into(),
|
||||
annotation: None,
|
||||
retrograde: false,
|
||||
house: None,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
// ─── Capa 1: Houses ───────────────────────────────────────────────
|
||||
let cusps_deg: Vec<f32> = natal
|
||||
.houses
|
||||
.cusps
|
||||
.iter()
|
||||
.map(|c| c.to_degrees() as f32)
|
||||
.collect();
|
||||
let houses = Layer {
|
||||
module_id: "natal".into(),
|
||||
kind: LayerKind::Houses,
|
||||
ring: 0.86,
|
||||
z: 1,
|
||||
geometry: Geometry::Ring {
|
||||
cusps_deg: cusps_deg.clone(),
|
||||
},
|
||||
glyphs: cusps_deg
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| Glyph {
|
||||
deg: *c + 4.0,
|
||||
symbol: format!("h{}", i + 1),
|
||||
annotation: None,
|
||||
retrograde: false,
|
||||
house: Some((i as u8) + 1),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
// ─── Capa 2: Bodies ───────────────────────────────────────────────
|
||||
let body_glyphs: Vec<Glyph> = natal
|
||||
.placements
|
||||
.iter()
|
||||
.map(|p| Glyph {
|
||||
deg: p.longitude.longitude_deg() as f32,
|
||||
symbol: body_symbol(p.body).into(),
|
||||
annotation: Some(format!("{:.1}°", p.longitude.degree_in_sign_decimal())),
|
||||
retrograde: p.is_retrograde(),
|
||||
house: Some(p.house_number),
|
||||
})
|
||||
.collect();
|
||||
let bodies = Layer {
|
||||
module_id: "natal".into(),
|
||||
kind: LayerKind::Bodies,
|
||||
ring: 0.72,
|
||||
z: 2,
|
||||
geometry: Geometry::Points(
|
||||
natal
|
||||
.placements
|
||||
.iter()
|
||||
.map(|p| crate::PointMark {
|
||||
deg: p.longitude.longitude_deg() as f32,
|
||||
label: p.body.name().into(),
|
||||
tag: body_symbol(p.body).into(),
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
glyphs: body_glyphs,
|
||||
};
|
||||
|
||||
// ─── Capa 3: Aspects ──────────────────────────────────────────────
|
||||
let mut aspect_lines: Vec<LineSeg> = Vec::with_capacity(aspects.len());
|
||||
for a in aspects {
|
||||
// Solo los aspectos mayores se pintan en este pase — los menores
|
||||
// saturan visualmente. Fase 4 pondrá un toggle para mostrarlos.
|
||||
if !EAspectKind::MAJORS.contains(&a.kind) {
|
||||
continue;
|
||||
}
|
||||
let pa = natal.placement(a.a);
|
||||
let pb = natal.placement(a.b);
|
||||
if let (Some(pa), Some(pb)) = (pa, pb) {
|
||||
let opacity = orb_to_opacity(a.orb_abs_deg(), a.kind);
|
||||
aspect_lines.push(LineSeg {
|
||||
from_deg: pa.longitude.longitude_deg() as f32,
|
||||
to_deg: pb.longitude.longitude_deg() as f32,
|
||||
kind: aspect_kind_id(a.kind).into(),
|
||||
opacity,
|
||||
});
|
||||
}
|
||||
}
|
||||
let aspects_layer = Layer {
|
||||
module_id: "natal".into(),
|
||||
kind: LayerKind::Aspects,
|
||||
ring: 0.58,
|
||||
z: 3,
|
||||
geometry: Geometry::Lines(aspect_lines),
|
||||
glyphs: Vec::new(),
|
||||
};
|
||||
|
||||
let subtitle = chart
|
||||
.birth_data
|
||||
.birthplace_label
|
||||
.clone()
|
||||
.or_else(|| {
|
||||
Some(format!(
|
||||
"{:04}-{:02}-{:02} · lat {:+.2}° · lon {:+.2}°",
|
||||
chart.birth_data.year,
|
||||
chart.birth_data.month,
|
||||
chart.birth_data.day,
|
||||
chart.birth_data.latitude_deg,
|
||||
chart.birth_data.longitude_deg,
|
||||
))
|
||||
});
|
||||
|
||||
RenderModel {
|
||||
chart_id: chart.id,
|
||||
chart_kind: chart.kind,
|
||||
title: chart.label.clone(),
|
||||
subtitle,
|
||||
compute_ms: started.elapsed().as_millis() as u64,
|
||||
ascendant_deg,
|
||||
midheaven_deg,
|
||||
descendant_deg,
|
||||
imum_coeli_deg,
|
||||
layers: vec![sign_dial, houses, bodies, aspects_layer],
|
||||
}
|
||||
}
|
||||
|
||||
/// Mapea el orb absoluto a una opacidad — los aspectos más exactos se
|
||||
/// pintan más fuerte, los flojos casi se desvanecen.
|
||||
fn orb_to_opacity(orb_deg: f64, kind: EAspectKind) -> f32 {
|
||||
let max = match kind {
|
||||
EAspectKind::Conjunction | EAspectKind::Opposition => 8.0,
|
||||
EAspectKind::Trine | EAspectKind::Square => 7.0,
|
||||
EAspectKind::Sextile => 5.0,
|
||||
_ => 3.0,
|
||||
};
|
||||
let t = (1.0 - (orb_deg / max).min(1.0)).max(0.25);
|
||||
t as f32
|
||||
}
|
||||
|
||||
const ZODIAC_SYMBOLS: [&str; 12] = [
|
||||
"aries",
|
||||
"taurus",
|
||||
"gemini",
|
||||
"cancer",
|
||||
"leo",
|
||||
"virgo",
|
||||
"libra",
|
||||
"scorpio",
|
||||
"sagittarius",
|
||||
"capricorn",
|
||||
"aquarius",
|
||||
"pisces",
|
||||
];
|
||||
@@ -17,11 +17,10 @@
|
||||
//!
|
||||
//! ## Feature `eternal-bridge`
|
||||
//!
|
||||
//! - **off** (default): la engine sólo expone los tipos `RenderModel`,
|
||||
//! `Layer`, `Glyph`, etc. y un `compute_mock()` con un disco de
|
||||
//! prueba. Útil para la UI antes de que `eternal-astrology` compile.
|
||||
//! - **on**: agrega `compute(chart) -> RenderModel` con la pipeline
|
||||
//! real.
|
||||
//! - **on** (default): [`compute`] abre una `EphemerisSession` VSOP2013
|
||||
//! compartida y corre la pipeline real.
|
||||
//! - **off**: [`compute`] cae a [`compute_mock`] — útil para tests +
|
||||
//! builds sin eternal checked out.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(rust_2018_idioms)]
|
||||
@@ -31,41 +30,45 @@ use thiserror::Error;
|
||||
|
||||
pub use tahuantinsuyu_model::{Chart, ChartId, ChartKind};
|
||||
|
||||
#[cfg(feature = "eternal-bridge")]
|
||||
mod bridge;
|
||||
|
||||
// =====================================================================
|
||||
// RenderModel — lo que el canvas necesita pintar una capa
|
||||
// RenderModel — lo que el canvas necesita pintar
|
||||
// =====================================================================
|
||||
|
||||
/// Resultado agnóstico de un cómputo astrológico, listo para renderizar.
|
||||
/// Cada `Layer` es independiente — el canvas las apila por z-order.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RenderModel {
|
||||
/// Identidad estable de la carta a la que pertenece este render.
|
||||
pub chart_id: ChartId,
|
||||
/// Kind original — el canvas lo usa para títulos y ornamentos.
|
||||
pub chart_kind: ChartKind,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub subtitle: Option<String>,
|
||||
pub compute_ms: u64,
|
||||
|
||||
// ─── Ángulos del chart (grados eclípticos, 0..360) ───────────────
|
||||
/// Ascendente — punto fijo de rotación del lienzo. La rueda se gira
|
||||
/// de modo que el Asc cae a las 9 (lado izquierdo).
|
||||
pub ascendant_deg: f32,
|
||||
pub midheaven_deg: f32,
|
||||
pub descendant_deg: f32,
|
||||
pub imum_coeli_deg: f32,
|
||||
|
||||
/// Capas a pintar. Orden = z-order ascendente.
|
||||
pub layers: Vec<Layer>,
|
||||
/// Texto humano-legible breve. Ej. "Sergio · 14 mar 1987 · Caracas".
|
||||
pub title: String,
|
||||
/// Tiempo de cómputo en ms — métrica para diagnóstico.
|
||||
pub compute_ms: u64,
|
||||
}
|
||||
|
||||
/// Una capa visual. Cada módulo de astrología publica una o varias.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Layer {
|
||||
/// Identidad estable del módulo emisor ("natal", "transit", "uranian").
|
||||
pub module_id: String,
|
||||
/// Tipo de capa — controla cómo se compone con vecinas.
|
||||
pub kind: LayerKind,
|
||||
/// Radio normalizado [0, 1] sobre el lienzo. Permite stack de anillos.
|
||||
/// Radio normalizado [0, 1] sobre el lienzo — el canvas lo convierte
|
||||
/// a píxeles. Permite stack de anillos.
|
||||
pub ring: f32,
|
||||
/// Z-order absoluto (más alto = encima). Default 0.
|
||||
#[serde(default)]
|
||||
pub z: i32,
|
||||
/// Geometría: puntos, arcos, líneas.
|
||||
pub geometry: Geometry,
|
||||
/// Glifos simbólicos sobre la geometría (planetas, signos, casas).
|
||||
#[serde(default)]
|
||||
pub glyphs: Vec<Glyph>,
|
||||
}
|
||||
@@ -73,51 +76,36 @@ pub struct Layer {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum LayerKind {
|
||||
/// El anillo zodiacal de fondo (12 signos).
|
||||
SignDial,
|
||||
/// Las 12 cusps de casas + cuadrantes.
|
||||
Houses,
|
||||
/// Los planetas / cuerpos en sus posiciones.
|
||||
Bodies,
|
||||
/// Líneas de aspecto entre cuerpos.
|
||||
Aspects,
|
||||
/// Puntos arábigos / lots.
|
||||
Lots,
|
||||
/// Estrellas fijas como overlay.
|
||||
FixedStars,
|
||||
/// Puntos medios y simetría Uraniana.
|
||||
Midpoints,
|
||||
/// Anillo externo de tránsitos / progresiones / direcciones.
|
||||
Outer,
|
||||
/// Geometría libre — usa cuando una capa no encaja en las otras.
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// Geometría primitiva, agnóstica del renderer.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum Geometry {
|
||||
/// Sólo glifos posicionados — sin trazo de fondo.
|
||||
GlyphsOnly,
|
||||
/// Anillo dividido en sectores (zodíaco, casas).
|
||||
Ring {
|
||||
/// Divisiones en grados zodiacales [0, 360). El canvas pinta
|
||||
/// líneas radiales en cada uno.
|
||||
cusps_deg: Vec<f32>,
|
||||
},
|
||||
/// Conjunto de líneas (aspectos). Cada par = `(from_deg, to_deg)`.
|
||||
/// Anillo dividido en sectores. `cusps_deg` son los grados
|
||||
/// zodiacales donde van las divisiones radiales.
|
||||
Ring { cusps_deg: Vec<f32> },
|
||||
Lines(Vec<LineSeg>),
|
||||
/// Puntos sueltos con marcadores (lots, fixed stars).
|
||||
Points(Vec<PointMark>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LineSeg {
|
||||
/// Grados zodiacales del extremo "a".
|
||||
pub from_deg: f32,
|
||||
/// Grados zodiacales del extremo "b".
|
||||
pub to_deg: f32,
|
||||
/// Categoría simbólica (conjunction, trine, square…) — el theme
|
||||
/// resuelve el color.
|
||||
/// Categoría simbólica (`"conjunction"`, `"trine"`, …) — el theme la
|
||||
/// resuelve a color.
|
||||
pub kind: String,
|
||||
/// Opacidad sugerida [0, 1].
|
||||
pub opacity: f32,
|
||||
}
|
||||
|
||||
@@ -125,25 +113,20 @@ pub struct LineSeg {
|
||||
pub struct PointMark {
|
||||
pub deg: f32,
|
||||
pub label: String,
|
||||
/// Tag simbólico para que el theme elija color/glifo.
|
||||
pub tag: String,
|
||||
}
|
||||
|
||||
/// Glifo dibujable sobre una capa.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Glyph {
|
||||
/// Posición zodiacal en grados [0, 360).
|
||||
/// Grado eclíptico [0, 360).
|
||||
pub deg: f32,
|
||||
/// Glyph simbólico ("sun","moon","aries",…). El theme lo mapea a
|
||||
/// imagen o codepoint.
|
||||
/// Glyph simbólico — el theme/canvas lo mapea a unicode o imagen.
|
||||
/// Ej: `"sun"`, `"moon"`, `"aries"`, `"asc"`, `"mc"`.
|
||||
pub symbol: String,
|
||||
/// Texto secundario (ej. el grado dentro del signo).
|
||||
#[serde(default)]
|
||||
pub annotation: Option<String>,
|
||||
/// `true` si el cuerpo está retrógrado.
|
||||
#[serde(default)]
|
||||
pub retrograde: bool,
|
||||
/// Casa en la que cae (1..=12), si aplica.
|
||||
#[serde(default)]
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
@@ -158,29 +141,30 @@ pub enum EngineError {
|
||||
BridgeDisabled,
|
||||
#[error("model: {0}")]
|
||||
Model(#[from] tahuantinsuyu_model::ModelError),
|
||||
#[cfg(feature = "eternal-bridge")]
|
||||
#[error("eternal: {0}")]
|
||||
Eternal(String),
|
||||
#[error("kind {0:?} todavía no implementado")]
|
||||
UnsupportedKind(ChartKind),
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// API pública
|
||||
// =====================================================================
|
||||
|
||||
/// Computa el RenderModel real contra `eternal-astrology`. Requiere
|
||||
/// el feature `eternal-bridge`.
|
||||
#[cfg(feature = "eternal-bridge")]
|
||||
pub fn compute(_chart: &Chart) -> Result<RenderModel, EngineError> {
|
||||
// TODO: pipeline real — abrir `EphemerisSession`, traducir
|
||||
// `StoredBirthData → BirthData`, `StoredChartConfig → ChartConfig`,
|
||||
// correr `NatalChart::compute`, mapear a `Layer`s. Se cablea en la
|
||||
// fase 3 del plan.
|
||||
Err(EngineError::Eternal("pendiente fase 3".into()))
|
||||
/// Computa el RenderModel real contra eternal-astrology si el feature
|
||||
/// está prendido; sino cae al mock.
|
||||
pub fn compute(chart: &Chart) -> Result<RenderModel, EngineError> {
|
||||
#[cfg(feature = "eternal-bridge")]
|
||||
{
|
||||
bridge::compute(chart)
|
||||
}
|
||||
#[cfg(not(feature = "eternal-bridge"))]
|
||||
{
|
||||
Ok(compute_mock(chart))
|
||||
}
|
||||
}
|
||||
|
||||
/// Stub que devuelve un disco vacío de placeholder — sirve a la UI
|
||||
/// mientras la pipeline real no esté cableada. Usar en demos y
|
||||
/// desarrollo.
|
||||
/// Stub determinista — útil para tests + para la UI sin eternal.
|
||||
pub fn compute_mock(chart: &Chart) -> RenderModel {
|
||||
use std::time::Instant;
|
||||
let t0 = Instant::now();
|
||||
@@ -188,7 +172,7 @@ pub fn compute_mock(chart: &Chart) -> RenderModel {
|
||||
let sign_dial = Layer {
|
||||
module_id: "natal".into(),
|
||||
kind: LayerKind::SignDial,
|
||||
ring: 0.95,
|
||||
ring: 1.0,
|
||||
z: 0,
|
||||
geometry: Geometry::Ring {
|
||||
cusps_deg: (0..12).map(|i| (i as f32) * 30.0).collect(),
|
||||
@@ -207,9 +191,14 @@ pub fn compute_mock(chart: &Chart) -> RenderModel {
|
||||
RenderModel {
|
||||
chart_id: chart.id,
|
||||
chart_kind: chart.kind,
|
||||
layers: vec![sign_dial],
|
||||
title: chart.label.clone(),
|
||||
subtitle: chart.birth_data.birthplace_label.clone(),
|
||||
compute_ms: t0.elapsed().as_millis() as u64,
|
||||
ascendant_deg: 0.0,
|
||||
midheaven_deg: 270.0,
|
||||
descendant_deg: 180.0,
|
||||
imum_coeli_deg: 90.0,
|
||||
layers: vec![sign_dial],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,6 +217,10 @@ const ZODIAC_GLYPHS: [&str; 12] = [
|
||||
"pisces",
|
||||
];
|
||||
|
||||
// =====================================================================
|
||||
// Tests
|
||||
// =====================================================================
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -269,4 +262,16 @@ mod tests {
|
||||
assert!(matches!(model.layers[0].kind, LayerKind::SignDial));
|
||||
assert_eq!(model.layers[0].glyphs.len(), 12);
|
||||
}
|
||||
|
||||
#[cfg(feature = "eternal-bridge")]
|
||||
#[test]
|
||||
fn real_compute_natal_demo() {
|
||||
let model = compute(&sample_chart()).expect("compute con eternal");
|
||||
assert!(model.layers.iter().any(|l| matches!(l.kind, LayerKind::SignDial)));
|
||||
assert!(model.layers.iter().any(|l| matches!(l.kind, LayerKind::Houses)));
|
||||
assert!(model.layers.iter().any(|l| matches!(l.kind, LayerKind::Bodies)));
|
||||
// El Asc debe ser un grado válido.
|
||||
assert!(model.ascendant_deg.is_finite());
|
||||
assert!((0.0..360.0).contains(&model.ascendant_deg));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user