1use lensbench_core::mech::MechPart;
9use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use serde_json::{Map, Value};
12use std::borrow::Cow;
13
14#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Num(pub f64);
17
18impl Serialize for Num {
19 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
20 let x = self.0;
21 if x.is_finite() {
22 s.serialize_f64(x)
23 } else {
24 let t = if x.is_nan() {
25 "nan"
26 } else if x > 0.0 {
27 "inf"
28 } else {
29 "-inf"
30 };
31 let mut m = Map::new();
32 m.insert("$f".into(), Value::from(t));
33 m.serialize(s)
34 }
35 }
36}
37
38impl<'de> Deserialize<'de> for Num {
39 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
40 #[derive(Deserialize)]
41 #[serde(untagged)]
42 enum Raw {
43 N(f64),
44 F {
45 #[serde(rename = "$f")]
46 f: String,
47 },
48 }
49 match Raw::deserialize(d)
50 .map_err(|_| serde::de::Error::custom("a number or {\"$f\": \"inf\"} is needed"))?
51 {
52 Raw::N(x) => Ok(Num(x)),
53 Raw::F { f } => match f.as_str() {
54 "inf" => Ok(Num(f64::INFINITY)),
55 "-inf" => Ok(Num(f64::NEG_INFINITY)),
56 "nan" => Ok(Num(f64::NAN)),
57 t => Err(serde::de::Error::custom(format!(
58 "{{\"$f\": \"{t}\"}} (inf, -inf, nan)"
59 ))),
60 },
61 }
62 }
63}
64
65impl JsonSchema for Num {
66 fn schema_name() -> Cow<'static, str> {
67 "Num".into()
68 }
69 fn json_schema(_: &mut SchemaGenerator) -> Schema {
70 json_schema!({
71 "description": "数。JSON に書けない数は {\"$f\": \"inf\"}(-inf・nan も)",
72 "anyOf": [
73 {"type": "number"},
74 {
75 "type": "object",
76 "properties": {"$f": {"enum": ["inf", "-inf", "nan"]}},
77 "required": ["$f"],
78 "additionalProperties": false
79 }
80 ]
81 })
82 }
83}
84
85#[derive(Serialize, JsonSchema, Debug, Clone, PartialEq, Eq)]
87#[serde(untagged)]
88pub enum Ref {
89 Index(usize),
91 Name(String),
93}
94
95#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq, Eq)]
97#[serde(deny_unknown_fields)]
98pub struct BlockFace {
99 pub block: String,
101 pub surface: usize,
103 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
105 pub coordbrk: bool,
106 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
108 pub back: bool,
109 #[serde(default, skip_serializing_if = "is_zero")]
111 pub pass: usize,
112}
113
114fn is_zero(n: &usize) -> bool {
115 *n == 0
116}
117
118#[derive(Serialize, JsonSchema, Debug, Clone, PartialEq, Eq)]
120#[serde(untagged)]
121pub enum BlockRef {
122 Block(BlockFace),
124 Sys(Ref),
126}
127
128fn ref_of<E: serde::de::Error>(v: Value, surface: bool) -> Result<Ref, E> {
129 let msg = match (&v, surface) {
130 (Value::Number(n), true) => format!("surface number {n} (an integer 0 or more)"),
131 (Value::Number(n), false) => format!("item number {n} (an integer 0 or more)"),
132 (v, true) => format!("surface number or name needed ({v})"),
133 (v, false) => format!("item number or name needed ({v})"),
134 };
135 match v {
136 Value::Number(n) => n
137 .as_u64()
138 .map(|i| Ref::Index(i as usize))
139 .ok_or_else(|| E::custom(msg)),
140 Value::String(t) => Ok(Ref::Name(t)),
141 _ => Err(E::custom(msg)),
142 }
143}
144
145impl<'de> Deserialize<'de> for Ref {
146 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
147 ref_of(Value::deserialize(d)?, false)
148 }
149}
150
151impl<'de> Deserialize<'de> for BlockRef {
152 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
153 match Value::deserialize(d)? {
154 v @ Value::Object(_) => BlockFace::deserialize(v).map(BlockRef::Block).map_err(|e| {
155 serde::de::Error::custom(format!("block surface (block, surface): {e}"))
156 }),
157 v => ref_of(v, true).map(BlockRef::Sys).map_err(|e: D::Error| {
158 serde::de::Error::custom(format!(
159 "{e} (a block surface is written with block and surface)"
160 ))
161 }),
162 }
163 }
164}
165
166#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
168#[serde(deny_unknown_fields)]
169pub struct StopOp<S> {
170 pub surface: S,
171}
172
173#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
176#[serde(deny_unknown_fields, bound(deserialize = "S: Deserialize<'de>"))]
177pub struct MacroSolveOp<S> {
178 pub surface: S,
179 #[serde(rename = "macro")]
181 pub macro_ref: Ref,
182 pub what: String,
184}
185
186impl<S> MacroSolveOp<S> {
187 pub fn map<T, E>(
189 self,
190 mut f: impl FnMut(S) -> Result<Option<T>, E>,
191 ) -> Result<Option<MacroSolveOp<T>>, E> {
192 Ok(f(self.surface)?.map(|surface| MacroSolveOp {
193 surface,
194 macro_ref: self.macro_ref,
195 what: self.what,
196 }))
197 }
198}
199
200#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
202#[serde(deny_unknown_fields, bound(deserialize = "S: Deserialize<'de>"))]
203pub struct SolveOp<S> {
204 pub surface: S,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub kind: Option<String>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub value: Option<Num>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub other: Option<S>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub param: Option<Num>,
217 #[serde(rename = "macro", default, skip_serializing_if = "Option::is_none")]
219 pub macro_ref: Option<Ref>,
220}
221
222#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
224#[serde(deny_unknown_fields)]
225pub struct PickupOp<S> {
226 pub dst: S,
228 pub src: S,
230 pub what: String,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub scale: Option<Num>,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub offset: Option<Num>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub from: Option<String>,
241}
242
243impl<S> StopOp<S> {
244 pub fn map<T, E>(
246 self,
247 mut f: impl FnMut(S) -> Result<Option<T>, E>,
248 ) -> Result<Option<StopOp<T>>, E> {
249 Ok(f(self.surface)?.map(|surface| StopOp { surface }))
250 }
251}
252
253impl<S> SolveOp<S> {
254 pub fn map<T, E>(
256 self,
257 mut f: impl FnMut(S) -> Result<Option<T>, E>,
258 ) -> Result<Option<SolveOp<T>>, E> {
259 let Some(surface) = f(self.surface)? else {
260 return Ok(None);
261 };
262 let other = match self.other {
263 Some(o) => match f(o)? {
264 Some(o) => Some(o),
265 None => return Ok(None),
266 },
267 None => None,
268 };
269 Ok(Some(SolveOp {
270 surface,
271 kind: self.kind,
272 value: self.value,
273 other,
274 param: self.param,
275 macro_ref: self.macro_ref,
276 }))
277 }
278
279 pub fn is_curv(&self) -> bool {
281 lensbench_core::solves::solve_kind_parse(
282 self.kind.as_deref().unwrap_or("marginal_height"),
283 0.0,
284 0.0,
285 Some(0),
286 )
287 .is_ok_and(|k| k.is_curv())
288 }
289}
290
291impl<S> PickupOp<S> {
292 pub fn map<T, E>(
294 self,
295 mut f: impl FnMut(S) -> Result<Option<T>, E>,
296 ) -> Result<Option<PickupOp<T>>, E> {
297 let (Some(dst), Some(src)) = (f(self.dst)?, f(self.src)?) else {
298 return Ok(None);
299 };
300 Ok(Some(PickupOp {
301 dst,
302 src,
303 what: self.what,
304 scale: self.scale,
305 offset: self.offset,
306 from: self.from,
307 }))
308 }
309}
310
311#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default)]
313#[serde(rename_all = "lowercase")]
314pub enum SolveWhat {
315 #[default]
317 T,
318 C,
320}
321
322#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
324#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
325pub enum EditOp {
326 InsertSurface {
328 at: usize,
329 #[serde(default, skip_serializing_if = "Map::is_empty")]
330 surface: Map<String, Value>,
331 },
332 DeleteSurface { surface: Ref },
334 SetSurface {
336 surface: Ref,
337 fields: Map<String, Value>,
338 },
339 SetSurfaceType {
341 surface: Ref,
342 #[serde(rename = "type")]
343 typ: String,
344 },
345 SetMaterial { surface: Ref, material: String },
347 SetStop(StopOp<Ref>),
349 AddPickup(PickupOp<Ref>),
351 RemovePickup { dst: Ref, what: String },
353 AddSolve(SolveOp<Ref>),
355 AddMacroSolve(MacroSolveOp<Ref>),
357 RemoveSolve {
359 surface: Ref,
360 #[serde(default)]
361 what: SolveWhat,
362 },
363 SetSurfaceData {
367 surface: Ref,
368 data: Map<String, Value>,
369 },
370 SetParam { param: String, value: Num },
372 SetSystemData { data: Map<String, Value> },
374 DefineUnit {
376 name: String,
377 spans: Vec<[usize; 2]>,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pivot: Option<[Num; 3]>,
380 },
381 SetUnit {
383 unit: Ref,
384 #[serde(default, skip_serializing_if = "Option::is_none")]
385 name: Option<String>,
386 #[serde(default, skip_serializing_if = "Option::is_none")]
387 spans: Option<Vec<[usize; 2]>>,
388 #[serde(default, skip_serializing_if = "Option::is_none")]
389 pivot: Option<[Num; 3]>,
390 },
391 RemoveUnit { unit: Ref },
393 AddMech { part: MechPart },
395 SetMech { mech: Ref, part: Map<String, Value> },
397 RemoveMech { mech: Ref },
399 SetConfigCount { n: usize },
401 SetConfigRow { param: String, values: Vec<Num> },
403 SetConfigMaterials { param: String, names: Vec<String> },
405 SetConfigCoatings { param: String, names: Vec<String> },
407 AddConfigRow { param: String },
409 RemoveConfigRow { param: String },
411 SetConfig { k: usize },
413 InsertConfig {
415 at: usize,
416 #[serde(default, skip_serializing_if = "Option::is_none")]
417 from: Option<usize>,
418 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
419 pickup: bool,
420 },
421 RemoveConfig { k: usize },
423 SetConfigPickup {
426 param: String,
427 k: usize,
428 from: usize,
429 #[serde(default, skip_serializing_if = "Option::is_none")]
430 row: Option<String>,
431 #[serde(default, skip_serializing_if = "Option::is_none")]
432 scale: Option<Num>,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
434 offset: Option<Num>,
435 },
436 RemoveConfigPickup { param: String, k: usize },
438 MakeThermal {
441 temps: Vec<Num>,
442 #[serde(default, skip_serializing_if = "Vec::is_empty")]
443 pressures: Vec<Num>,
444 },
445}
446
447impl EditOp {
448 pub fn is_config(&self) -> bool {
450 use EditOp::*;
451 matches!(
452 self,
453 SetConfigCount { .. }
454 | SetConfigRow { .. }
455 | SetConfigMaterials { .. }
456 | SetConfigCoatings { .. }
457 | AddConfigRow { .. }
458 | RemoveConfigRow { .. }
459 | SetConfig { .. }
460 | InsertConfig { .. }
461 | RemoveConfig { .. }
462 | SetConfigPickup { .. }
463 | RemoveConfigPickup { .. }
464 | MakeThermal { .. }
465 )
466 }
467
468 pub fn name(&self) -> String {
470 serde_json::to_value(self)
471 .ok()
472 .and_then(|v| v["op"].as_str().map(str::to_string))
473 .unwrap_or_default()
474 }
475}
476
477#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
482#[serde(tag = "op", rename_all = "snake_case")]
483pub enum SurfaceOp {
484 SetStop(StopOp<BlockRef>),
486 AddSolve(SolveOp<BlockRef>),
488 AddMacroSolve(MacroSolveOp<BlockRef>),
490 AddPickup(PickupOp<BlockRef>),
492 RemoveSolve {
494 surface: BlockRef,
495 #[serde(default)]
496 what: SolveWhat,
497 },
498 RemovePickup { dst: BlockRef, what: String },
500}
501
502impl SurfaceOp {
503 pub fn to_edit<E>(
505 &self,
506 mut f: impl FnMut(BlockRef) -> Result<Option<Ref>, E>,
507 ) -> Result<Option<EditOp>, E> {
508 Ok(match self.clone() {
509 SurfaceOp::SetStop(o) => o.map(f)?.map(EditOp::SetStop),
510 SurfaceOp::AddSolve(o) => o.map(f)?.map(EditOp::AddSolve),
511 SurfaceOp::AddMacroSolve(o) => o.map(f)?.map(EditOp::AddMacroSolve),
512 SurfaceOp::AddPickup(o) => o.map(f)?.map(EditOp::AddPickup),
513 SurfaceOp::RemoveSolve { surface, what } => {
514 f(surface)?.map(|surface| EditOp::RemoveSolve { surface, what })
515 }
516 SurfaceOp::RemovePickup { dst, what } => {
517 f(dst)?.map(|dst| EditOp::RemovePickup { dst, what })
518 }
519 })
520 }
521
522 pub fn target_mut(&mut self) -> &mut BlockRef {
524 match self {
525 SurfaceOp::SetStop(x) => &mut x.surface,
526 SurfaceOp::AddSolve(x) => &mut x.surface,
527 SurfaceOp::AddMacroSolve(x) => &mut x.surface,
528 SurfaceOp::AddPickup(x) => &mut x.dst,
529 SurfaceOp::RemoveSolve { surface, .. } => surface,
530 SurfaceOp::RemovePickup { dst, .. } => dst,
531 }
532 }
533
534 pub fn stop_index(&self) -> Option<usize> {
536 match self {
537 SurfaceOp::SetStop(StopOp {
538 surface: BlockRef::Sys(Ref::Index(i)),
539 }) => Some(*i),
540 _ => None,
541 }
542 }
543
544 pub fn name(&self) -> &'static str {
546 match self {
547 SurfaceOp::SetStop(_) => "set_stop",
548 SurfaceOp::AddSolve(_) => "add_solve",
549 SurfaceOp::AddMacroSolve(_) => "add_macro_solve",
550 SurfaceOp::AddPickup(_) => "add_pickup",
551 SurfaceOp::RemoveSolve { .. } => "remove_solve",
552 SurfaceOp::RemovePickup { .. } => "remove_pickup",
553 }
554 }
555}