use std::str::FromStr;
use anyhow::Result;
use derive_docs::stdlib;
use kcmc::{
coord::{Axis, AxisDirectionPair, Direction, System},
each_cmd as mcmd,
format::InputFormat,
ok_response::OkModelingCmdResponse,
shared::FileImportFormat,
units::UnitLength,
websocket::OkWebSocketResponseData,
ImportFile, ModelingCmd,
};
use kittycad_modeling_cmds as kcmc;
use crate::{
errors::{KclError, KclErrorDetails},
executor::{ExecState, ImportedGeometry, KclValue},
fs::FileSystem,
std::Args,
};
const ZOO_COORD_SYSTEM: System = System {
forward: AxisDirectionPair {
axis: Axis::Y,
direction: Direction::Negative,
},
up: AxisDirectionPair {
axis: Axis::Z,
direction: Direction::Positive,
},
};
#[derive(serde :: Serialize, serde :: Deserialize, PartialEq, Debug, Clone, schemars :: JsonSchema)]
#[cfg_attr(feature = "tabled", derive(tabled::Tabled))]
#[serde(tag = "type")]
pub enum ImportFormat {
#[serde(rename = "fbx")]
Fbx {},
#[serde(rename = "gltf")]
Gltf {},
#[serde(rename = "obj")]
Obj {
coords: Option<System>,
units: UnitLength,
},
#[serde(rename = "ply")]
Ply {
coords: Option<System>,
units: UnitLength,
},
#[serde(rename = "sldprt")]
Sldprt {},
#[serde(rename = "step")]
Step {},
#[serde(rename = "stl")]
Stl {
coords: Option<System>,
units: UnitLength,
},
}
impl From<ImportFormat> for InputFormat {
fn from(format: ImportFormat) -> Self {
match format {
ImportFormat::Fbx {} => InputFormat::Fbx(Default::default()),
ImportFormat::Gltf {} => InputFormat::Gltf(Default::default()),
ImportFormat::Obj { coords, units } => InputFormat::Obj(kcmc::format::obj::import::Options {
coords: coords.unwrap_or(ZOO_COORD_SYSTEM),
units,
}),
ImportFormat::Ply { coords, units } => InputFormat::Ply(kcmc::format::ply::import::Options {
coords: coords.unwrap_or(ZOO_COORD_SYSTEM),
units,
}),
ImportFormat::Sldprt {} => InputFormat::Sldprt(kcmc::format::sldprt::import::Options {
split_closed_faces: false,
}),
ImportFormat::Step {} => InputFormat::Step(kcmc::format::step::import::Options {
split_closed_faces: false,
}),
ImportFormat::Stl { coords, units } => InputFormat::Stl(kcmc::format::stl::import::Options {
coords: coords.unwrap_or(ZOO_COORD_SYSTEM),
units,
}),
}
}
}
pub async fn import(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
let (file_path, options): (String, Option<ImportFormat>) = args.get_import_data()?;
let imported_geometry = inner_import(file_path, options, args).await?;
Ok(KclValue::ImportedGeometry(imported_geometry))
}
#[stdlib {
name = "import",
tags = [],
}]
async fn inner_import(
file_path: String,
options: Option<ImportFormat>,
args: Args,
) -> Result<ImportedGeometry, KclError> {
if file_path.is_empty() {
return Err(KclError::Semantic(KclErrorDetails {
message: "No file path was provided.".to_string(),
source_ranges: vec![args.source_range],
}));
}
if !args.ctx.fs.exists(&file_path, args.source_range).await? {
return Err(KclError::Semantic(KclErrorDetails {
message: format!("File `{}` does not exist.", file_path),
source_ranges: vec![args.source_range],
}));
}
let ext_format = get_import_format_from_extension(file_path.split('.').last().ok_or_else(|| {
KclError::Semantic(KclErrorDetails {
message: format!("No file extension found for `{}`", file_path),
source_ranges: vec![args.source_range],
})
})?)
.map_err(|e| {
KclError::Semantic(KclErrorDetails {
message: e.to_string(),
source_ranges: vec![args.source_range],
})
})?;
let format = if let Some(options) = options {
let format: InputFormat = options.into();
validate_extension_format(ext_format, format.clone()).map_err(|e| {
KclError::Semantic(KclErrorDetails {
message: e.to_string(),
source_ranges: vec![args.source_range],
})
})?;
format
} else {
ext_format
};
let file_contents = args.ctx.fs.read(&file_path, args.source_range).await.map_err(|e| {
KclError::Semantic(KclErrorDetails {
message: e.to_string(),
source_ranges: vec![args.source_range],
})
})?;
let file_name = std::path::Path::new(&file_path)
.file_name()
.map(|p| p.to_string_lossy().to_string())
.ok_or_else(|| {
KclError::Semantic(KclErrorDetails {
message: format!("Could not get the file name from the path `{}`", file_path),
source_ranges: vec![args.source_range],
})
})?;
let mut import_files = vec![kcmc::ImportFile {
path: file_name.to_string(),
data: file_contents.clone(),
}];
if let InputFormat::Gltf(..) = format {
if !file_contents.starts_with(b"glTF") {
let json = gltf_json::Root::from_slice(&file_contents).map_err(|e| {
KclError::Semantic(KclErrorDetails {
message: e.to_string(),
source_ranges: vec![args.source_range],
})
})?;
for buffer in json.buffers.iter() {
if let Some(uri) = &buffer.uri {
if !uri.starts_with("data:") {
let bin_path = std::path::Path::new(&file_path)
.parent()
.map(|p| p.join(uri))
.map(|p| p.to_string_lossy().to_string())
.ok_or_else(|| {
KclError::Semantic(KclErrorDetails {
message: format!("Could not get the parent path of the file `{}`", file_path),
source_ranges: vec![args.source_range],
})
})?;
let bin_contents = args.ctx.fs.read(&bin_path, args.source_range).await.map_err(|e| {
KclError::Semantic(KclErrorDetails {
message: e.to_string(),
source_ranges: vec![args.source_range],
})
})?;
import_files.push(ImportFile {
path: uri.to_string(),
data: bin_contents,
});
}
}
}
}
}
if args.ctx.is_mock {
return Ok(ImportedGeometry {
id: uuid::Uuid::new_v4(),
value: import_files.iter().map(|f| f.path.to_string()).collect(),
meta: vec![args.source_range.into()],
});
}
let id = uuid::Uuid::new_v4();
let resp = args
.send_modeling_cmd(
id,
ModelingCmd::from(mcmd::ImportFiles {
files: import_files.clone(),
format,
}),
)
.await?;
let OkWebSocketResponseData::Modeling {
modeling_response: OkModelingCmdResponse::ImportFiles(imported_files),
} = &resp
else {
return Err(KclError::Engine(KclErrorDetails {
message: format!("ImportFiles response was not as expected: {:?}", resp),
source_ranges: vec![args.source_range],
}));
};
Ok(ImportedGeometry {
id: imported_files.object_id,
value: import_files.iter().map(|f| f.path.to_string()).collect(),
meta: vec![args.source_range.into()],
})
}
fn get_import_format_from_extension(ext: &str) -> Result<InputFormat> {
let format = match FileImportFormat::from_str(ext) {
Ok(format) => format,
Err(_) => {
if ext == "stp" {
FileImportFormat::Step
} else if ext == "glb" {
FileImportFormat::Gltf
} else {
anyhow::bail!("unknown source format for file extension: {}. Try setting the `--src-format` flag explicitly or use a valid format.", ext)
}
}
};
let ul = UnitLength::Millimeters;
match format {
FileImportFormat::Step => Ok(InputFormat::Step(kcmc::format::step::import::Options {
split_closed_faces: false,
})),
FileImportFormat::Stl => Ok(InputFormat::Stl(kcmc::format::stl::import::Options {
coords: ZOO_COORD_SYSTEM,
units: ul,
})),
FileImportFormat::Obj => Ok(InputFormat::Obj(kcmc::format::obj::import::Options {
coords: ZOO_COORD_SYSTEM,
units: ul,
})),
FileImportFormat::Gltf => Ok(InputFormat::Gltf(kcmc::format::gltf::import::Options {})),
FileImportFormat::Ply => Ok(InputFormat::Ply(kcmc::format::ply::import::Options {
coords: ZOO_COORD_SYSTEM,
units: ul,
})),
FileImportFormat::Fbx => Ok(InputFormat::Fbx(kcmc::format::fbx::import::Options {})),
FileImportFormat::Sldprt => Ok(InputFormat::Sldprt(kcmc::format::sldprt::import::Options {
split_closed_faces: false,
})),
}
}
fn validate_extension_format(ext: InputFormat, given: InputFormat) -> Result<()> {
if let InputFormat::Stl(_) = ext {
if let InputFormat::Stl(_) = given {
return Ok(());
}
}
if let InputFormat::Obj(_) = ext {
if let InputFormat::Obj(_) = given {
return Ok(());
}
}
if let InputFormat::Ply(_) = ext {
if let InputFormat::Ply(_) = given {
return Ok(());
}
}
if ext == given {
return Ok(());
}
anyhow::bail!(
"The given format does not match the file extension. Expected: `{}`, Given: `{}`",
get_name_of_format(ext),
get_name_of_format(given)
)
}
fn get_name_of_format(type_: InputFormat) -> &'static str {
match type_ {
InputFormat::Fbx(_) => "fbx",
InputFormat::Gltf(_) => "gltf",
InputFormat::Obj(_) => "obj",
InputFormat::Ply(_) => "ply",
InputFormat::Sldprt(_) => "sldprt",
InputFormat::Step(_) => "step",
InputFormat::Stl(_) => "stl",
}
}