mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 22:33:08 +00:00
Export 3D Object: a textured face keeps its opacity in the texture
A face that is not opaque drew its texture over an opaque ground, and the material then applied the face's opacity to the whole texture, so an opaque graphic on a half-opaque face came out half opaque. - The texture draws the face's color at its opacity, so the graphics keep their own. - glTF's textured material takes its alpha from the texture (factor 1, BLEND), and USDA connects opacity to the UsdUVTexture's outputs:a. - OBJ writes <name>-texture-1-opacity.png, the texture's alpha as gray levels, for the MTL's map_d, and d 1 on textured materials.
This commit is contained in:
@@ -11,7 +11,7 @@ use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens,
|
||||
image_count, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
|
||||
image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
|
||||
};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _). Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
@@ -288,12 +288,12 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let parts =
|
||||
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
|
||||
let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
|
||||
let images = image_count(&pictures);
|
||||
let images = image_maps(&pictures);
|
||||
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
|
||||
let mut stem = base.clone();
|
||||
let mut k = 1;
|
||||
loop {
|
||||
let names = mesh_file_names(&stem, format, images).map_err(|e| bad(C, e))?;
|
||||
let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?;
|
||||
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ pub use load::{losses_summary, overwrite_losses};
|
||||
#[cfg(test)]
|
||||
pub(crate) use mesh3d::MAX_TEXTURE_PIXELS;
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label};
|
||||
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_count, mesh_file_names, mesh_files, textures};
|
||||
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
|
||||
@@ -60,23 +60,40 @@ fn obj_stem(stem: &str) -> String {
|
||||
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
|
||||
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
|
||||
fn texture_name(stem: &str, k: usize) -> String {
|
||||
let stem: String = stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect();
|
||||
format!("{stem}-texture-{}.png", k + 1)
|
||||
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format` with `images` textures: OBJ
|
||||
/// and USDA name a PNG file for each texture after them; glTF and USDZ hold theirs.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: usize) -> Result<Vec<String>, String> {
|
||||
let beside = |mut names: Vec<String>, stem: &str| {
|
||||
names.extend((0..images).map(|k| texture_name(stem, k)));
|
||||
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
|
||||
/// [`texture_name`] names the texture.
|
||||
fn opacity_name(stem: &str, k: usize) -> String {
|
||||
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
|
||||
}
|
||||
|
||||
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
|
||||
fn texture_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
|
||||
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
|
||||
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
|
||||
/// theirs.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
|
||||
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
|
||||
for (k, map) in images.iter().enumerate() {
|
||||
names.push(texture_name(stem, k));
|
||||
if maps && *map {
|
||||
names.push(opacity_name(stem, k));
|
||||
}
|
||||
}
|
||||
names
|
||||
};
|
||||
match format {
|
||||
"obj" => {
|
||||
let stem = obj_stem(stem);
|
||||
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem))
|
||||
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
|
||||
}
|
||||
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem)),
|
||||
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
|
||||
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
_ => {
|
||||
let key = "format";
|
||||
@@ -87,22 +104,26 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str, images: usize) -> Result
|
||||
|
||||
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
|
||||
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
|
||||
/// top).
|
||||
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Texture {
|
||||
pub png: Arc<Vec<u8>>,
|
||||
pub opacity: Option<Arc<Vec<u8>>>,
|
||||
pub uv: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// A distinct picture of a 3D object: the PNG and its opacity map.
|
||||
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
|
||||
|
||||
/// The distinct pictures of `textures` in order of first use, and the index among them of each
|
||||
/// part's (`None` for a part without one).
|
||||
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Arc<Vec<u8>>>, Vec<Option<usize>>) {
|
||||
let mut out: Vec<Arc<Vec<u8>>> = vec![];
|
||||
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
|
||||
let mut out: Vec<Picture> = vec![];
|
||||
let index = (0..parts)
|
||||
.map(|k| {
|
||||
let t = textures.get(k)?.as_ref()?;
|
||||
Some(out.iter().position(|p| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
|
||||
out.push(t.png.clone());
|
||||
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
|
||||
out.push((t.png.clone(), t.opacity.clone()));
|
||||
out.len() - 1
|
||||
}))
|
||||
})
|
||||
@@ -110,24 +131,27 @@ fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Arc<Vec<u8>>>, Vec
|
||||
(out, index)
|
||||
}
|
||||
|
||||
/// The number of distinct pictures of `textures` ([`mesh_file_names`]).
|
||||
pub(crate) fn image_count(textures: &[Option<Texture>]) -> usize {
|
||||
images(textures.len(), textures).0.len()
|
||||
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
|
||||
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
|
||||
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
|
||||
}
|
||||
|
||||
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
|
||||
/// OBJ with its MTL after it and the PNG files of `textures` last. `textures` holds the picture of
|
||||
/// each part that has one, in the order of `parts`.
|
||||
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
|
||||
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let (pictures, image) = images(parts.len(), textures);
|
||||
let names = mesh_file_names(stem, format, pictures.len())?;
|
||||
let scene = Scene { parts, textures, image: &image, pictures: &pictures };
|
||||
let (images, image) = images(parts.len(), textures);
|
||||
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
|
||||
let names = mesh_file_names(stem, format, &maps)?;
|
||||
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
|
||||
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
|
||||
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
|
||||
let bytes: Vec<Vec<u8>> = match format {
|
||||
"obj" => {
|
||||
let stem = obj_stem(stem);
|
||||
let (obj, mtl) = obj(&stem, &scene);
|
||||
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(pngs()).collect()
|
||||
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
|
||||
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
|
||||
}
|
||||
"gltf" => vec![gltf(stem, &scene).into_bytes()],
|
||||
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
|
||||
@@ -140,12 +164,14 @@ pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures
|
||||
Ok(names.into_iter().zip(bytes).collect())
|
||||
}
|
||||
|
||||
/// The parts of an object with their pictures: `image` is each part's index among `pictures`.
|
||||
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
|
||||
/// `maps` says for each picture whether it has an opacity map.
|
||||
struct Scene<'a> {
|
||||
parts: &'a [SolidMesh],
|
||||
textures: &'a [Option<Texture>],
|
||||
image: &'a [Option<usize>],
|
||||
pictures: &'a [Arc<Vec<u8>>],
|
||||
maps: &'a [bool],
|
||||
}
|
||||
|
||||
impl Scene<'_> {
|
||||
@@ -244,10 +270,14 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
}
|
||||
}
|
||||
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
|
||||
// A picture's opacity map holds the opacity, as gray levels.
|
||||
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
|
||||
let _ = writeln!(m, "illum 1");
|
||||
if let Some(i) = mat.image {
|
||||
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
|
||||
if scene.maps.get(i).copied().unwrap_or(false) {
|
||||
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
(o, m)
|
||||
@@ -306,8 +336,8 @@ fn gltf(stem: &str, scene: &Scene) -> String {
|
||||
"doubleSided": true,
|
||||
});
|
||||
if let Some(i) = mat.image {
|
||||
// The picture holds the color; the factor multiplies it.
|
||||
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, c[3]]);
|
||||
// The picture holds the color and the opacity; the factor multiplies them.
|
||||
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
|
||||
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
|
||||
}
|
||||
if c[3] < 1.0 {
|
||||
@@ -400,14 +430,20 @@ fn usda(stem: &str, scene: &Scene) -> String {
|
||||
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
|
||||
match mat.image {
|
||||
// The picture holds the color, and the opacity when the face is not opaque.
|
||||
Some(_) => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
|
||||
} else {
|
||||
let _ = writeln!(u, " float inputs:opacity = 1");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
let _ = writeln!(u, " float inputs:roughness = 1");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}");
|
||||
if let Some(i) = mat.image {
|
||||
@@ -418,7 +454,11 @@ fn usda(stem: &str, scene: &Scene) -> String {
|
||||
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
|
||||
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
|
||||
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
|
||||
let _ = writeln!(u, " float3 outputs:rgb\n }}");
|
||||
let _ = writeln!(u, " float3 outputs:rgb");
|
||||
if c[3] < 1.0 {
|
||||
let _ = writeln!(u, " float outputs:a");
|
||||
}
|
||||
let _ = writeln!(u, " }}");
|
||||
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
|
||||
let _ = writeln!(u, " string inputs:varname = \"st\"");
|
||||
@@ -438,7 +478,8 @@ fn usda(stem: &str, scene: &Scene) -> String {
|
||||
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
|
||||
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
|
||||
let mut renderer: Option<vectorcraft_render::Renderer> = None;
|
||||
// Each picture drawn: the part it was drawn for, its bounds, and the PNG (`None`: nothing drawn).
|
||||
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
|
||||
// (`None`: nothing drawn).
|
||||
let mut drawn: Vec<Drawn> = vec![];
|
||||
let mut out = vec![];
|
||||
for part in parts {
|
||||
@@ -467,16 +508,16 @@ pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &
|
||||
));
|
||||
}
|
||||
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
|
||||
Some(Arc::new(picture(doc, renderer, part.color, art, (frame, scale), (w, h))?))
|
||||
Some(picture(doc, renderer, part.color, art, (frame, scale), (w, h))?)
|
||||
}
|
||||
};
|
||||
drawn.push((part, frame, png.clone()));
|
||||
png
|
||||
}
|
||||
};
|
||||
out.push(png.map(|png| {
|
||||
out.push(png.map(|(png, opacity)| {
|
||||
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
|
||||
Texture { png, uv }
|
||||
Texture { png, opacity, uv }
|
||||
}));
|
||||
}
|
||||
Ok(out)
|
||||
@@ -498,16 +539,17 @@ fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
|
||||
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
|
||||
}
|
||||
|
||||
/// A picture [`textures`] drew: the part, the bounds and the PNG.
|
||||
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Arc<Vec<u8>>>);
|
||||
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
|
||||
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
|
||||
|
||||
/// Do `a` and `b` draw the same graphics on their face?
|
||||
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
|
||||
a.face == b.face && a.center == b.center && a.graphics == b.graphics
|
||||
}
|
||||
|
||||
/// `art` drawn over `color` (opaque) as a PNG of `w` × `h` pixels whose top left is `frame`'s top
|
||||
/// left, at `scale` pixels a point.
|
||||
/// `art` drawn over `color` (at its opacity) as a PNG of `w` × `h` pixels whose top left is `frame`'s
|
||||
/// top left, at `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not
|
||||
/// opaque.
|
||||
fn picture(
|
||||
doc: &Document,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
@@ -515,16 +557,27 @@ fn picture(
|
||||
art: Node,
|
||||
(frame, scale): (Rect, f64),
|
||||
(w, h): (u32, u32),
|
||||
) -> Result<Vec<u8>, String> {
|
||||
) -> Result<Picture, String> {
|
||||
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
|
||||
let reach = 2.0 / scale;
|
||||
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
|
||||
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
|
||||
let ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
|
||||
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
|
||||
ground.opacity = color[3];
|
||||
let group = Arc::new(Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]));
|
||||
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
|
||||
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
|
||||
renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?.to_png()
|
||||
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
|
||||
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
|
||||
let opacity = if alpha.iter().all(|a| *a == 255) {
|
||||
None
|
||||
} else {
|
||||
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
|
||||
let mut png = vec![];
|
||||
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
|
||||
Some(Arc::new(png))
|
||||
};
|
||||
Ok((Arc::new(drawn.to_png()?), opacity))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -107,8 +107,8 @@ fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
|
||||
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
|
||||
assert_eq!(mesh_file_names("Box #1", "obj", 0).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda", 0).unwrap(), ["Box #1.usda"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -125,8 +125,8 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
|
||||
#[test]
|
||||
fn an_unknown_format_is_refused() {
|
||||
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "", 0).is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj", 0).unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
assert!(mesh_file_names("Box", "", &[]).is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -140,7 +140,7 @@ fn prim_names_are_usd_identifiers() {
|
||||
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
|
||||
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
|
||||
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
|
||||
let texture = Texture { png: Arc::new(png.to_vec()), uv };
|
||||
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
|
||||
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
|
||||
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
|
||||
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 0.5\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
|
||||
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
|
||||
assert_eq!(mtl.matches("map_Kd").count(), 1);
|
||||
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
@@ -173,7 +173,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
|
||||
assert_eq!(first, [0.0, 1.0]);
|
||||
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 0.5]));
|
||||
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
|
||||
assert_eq!(g["textures"][0]["source"], 0);
|
||||
assert_eq!(g["samplers"][0]["wrapS"], 33071);
|
||||
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
|
||||
@@ -204,16 +204,46 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
|
||||
assert_eq!(&zip[data..data + png.len()], png.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
|
||||
let (parts, mut pictures) = textured(b"picture");
|
||||
if let Some(t) = pictures[1].as_mut() {
|
||||
t.opacity = Some(Arc::new(b"gray".to_vec()));
|
||||
}
|
||||
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
|
||||
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
|
||||
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
|
||||
assert_eq!(files[3].1, b"gray");
|
||||
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
|
||||
let mtl = text(&files, "My_Box.mtl");
|
||||
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
|
||||
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
|
||||
let material = &g["materials"][1];
|
||||
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
|
||||
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
|
||||
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
|
||||
let u = text(&usda, "Box.usda");
|
||||
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
|
||||
// An opaque textured face reads no opacity from its picture.
|
||||
let (_, plain) = textured(b"picture");
|
||||
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
|
||||
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
|
||||
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
|
||||
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
|
||||
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_sharing_a_picture_write_it_once() {
|
||||
let (mut parts, mut pictures) = textured(b"one");
|
||||
parts.push(square(BLUE));
|
||||
pictures.push(pictures[1].clone());
|
||||
assert_eq!(image_count(&pictures), 1);
|
||||
assert_eq!(image_maps(&pictures), [false]);
|
||||
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
|
||||
assert_eq!(files.len(), 3);
|
||||
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
|
||||
assert_eq!(mesh_file_names("Box", "usda", 2).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
|
||||
assert_eq!(mesh_file_names("A @b", "gltf", 2).unwrap(), ["A @b.gltf"]);
|
||||
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
|
||||
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
|
||||
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
|
||||
}
|
||||
|
||||
@@ -273,6 +273,31 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
|
||||
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_opaque_face_keeps_its_graphics_opaque_in_the_texture() {
|
||||
let (mut s, asset) = mapped("usda");
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let id = doc.asset(asset).unwrap().nodes[0];
|
||||
let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
// The graphic stays opaque where it covers the face, and the face around it is half opaque.
|
||||
let front = &out[1].1;
|
||||
assert_eq!(pixel(front, 64, 64), [255, 0, 0, 255]);
|
||||
let around = pixel(front, 2, 2);
|
||||
assert!(around[2] > 200 && (120..=135).contains(&around[3]), "{around:?}");
|
||||
let usda = String::from_utf8(out[0].1.clone()).unwrap();
|
||||
assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity");
|
||||
// An OBJ's opacity map has the alpha as gray levels.
|
||||
run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"}));
|
||||
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
|
||||
assert_eq!(out[3].0, "Box-texture-1-opacity.png");
|
||||
let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8();
|
||||
assert_eq!(gray.get_pixel(64, 64).0, [255]);
|
||||
assert!((120..=135).contains(&gray.get_pixel(2, 2).0[0]), "{:?}", gray.get_pixel(2, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() {
|
||||
let (mut s, asset) = mapped("obj");
|
||||
|
||||
+5
-2
@@ -8336,11 +8336,14 @@ page, those turned away from the viewer included, at the object's 3D rotation, y
|
||||
about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on.
|
||||
Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG
|
||||
texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own
|
||||
triangles with texture coordinates and a material that shows the texture. glTF embeds the PNG as a data URI
|
||||
triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity
|
||||
in the texture's alpha, and the graphics keep their own. glTF embeds the PNG as a data URI
|
||||
(`TEXCOORD_0`, `baseColorTexture`), USDZ stores it after the layer, USDA reads it through `primvars:st`, a
|
||||
`UsdPrimvarReader_float2` and a `UsdUVTexture` connected to the surface's `diffuseColor`, and OBJ gives `vt` coordinates
|
||||
and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `<name>-texture-1.png`, `-texture-2.png` and so on
|
||||
(whitespace, `#` and `@` become `_`). Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to
|
||||
(whitespace, `#` and `@` become `_`). USD reads a face's opacity from the texture's alpha (`outputs:a`), and an OBJ
|
||||
whose face is not opaque also gets `<name>-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`.
|
||||
Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to
|
||||
4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export
|
||||
draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not
|
||||
exported yet. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>)
|
||||
|
||||
Reference in New Issue
Block a user