kcl_lib/std/
polar.rs

1//! Functions related to polar coordinates.
2
3use anyhow::Result;
4use kcl_derive_docs::stdlib;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    errors::KclError,
10    execution::{ExecState, KclValue},
11    std::args::{Args, TyF64},
12};
13
14/// Data for polar coordinates.
15#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
16#[ts(export)]
17#[serde(rename_all = "camelCase")]
18pub struct PolarCoordsData {
19    /// The angle of the line (in degrees).
20    pub angle: f64,
21    /// The length of the line.
22    pub length: TyF64,
23}
24
25/// Convert from polar/sphere coordinates to cartesian coordinates.
26pub async fn polar(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
27    let data: PolarCoordsData = args.get_data()?;
28    let result = inner_polar(&data)?;
29
30    args.make_user_val_from_f64_array(result.to_vec(), &data.length.ty)
31}
32
33/// Convert polar/sphere (azimuth, elevation, distance) coordinates to
34/// cartesian (x/y/z grid) coordinates.
35///
36/// ```no_run
37/// exampleSketch = startSketchOn('XZ')
38///   |> startProfileAt([0, 0], %)
39///   |> line(end = polar({angle: 30, length: 5}), tag = $thing)
40///   |> line(end = [0, 5])
41///   |> line(end = [segEndX(thing), 0])
42///   |> line(end = [-20, 10])
43///   |> close()
44///  
45/// example = extrude(exampleSketch, length = 5)
46/// ```
47#[stdlib {
48    name = "polar",
49}]
50fn inner_polar(data: &PolarCoordsData) -> Result<[f64; 2], KclError> {
51    let angle = data.angle.to_radians();
52    let x = data.length.n * angle.cos();
53    let y = data.length.n * angle.sin();
54    Ok([x, y])
55}