## write an asymptote program for recreating a triangular mesh ## scene. Color and transparency are supported; mesh drawing, color2, ## and material properties are not currently supported. The loops ## could be vectorized but seem adequate for now. saveTrianglesAsASY <- function(scene, filename = "scene.asy") { scene <- misc3d:::colorScene(scene) triangles <- misc3d:::canonicalizeAndMergeScene(scene, "color", "color2", "alpha", "col.mesh", "fill", "smooth") ve <- misc3d:::t2ve(triangles) f <- file(filename, open = "w") on.exit(close(f)) ## write out header information and vertices cat("//generated by saveTrianglesAsASY\n\n", "import three;\n\n", "size(20cm);\n\n", "//currentprojection=perspective(250,-250,250);\n", "currentlight=Viewport;\n\n", "typedef path3[] trimesh;\n\n", "// Vertices\n", "triple[] V;\n", sep = "", file = f) nv <- ncol(ve$vb) x <- ve$vb[1,] y <- ve$vb[2,] z <- ve$vb[3,] for (i in 1 : nv) cat(sprintf("V[%d] = (%f, %f, %f);\n", i - 1, x[i], y[i], z[i]), file = f) ## write out the faces cat("\n", "guide3 triface_(int i, int j, int k) {\n", " guide3 gh; gh=V[i-1]--V[j-1]--V[k-1]--cycle;\n", " return gh;\n", "};\n\n", "// Faces\n", "trimesh F;\n", sep = "", file = f) nf <- ncol(ve$ib) v1 <- ve$ib[1,] v2 <- ve$ib[2,] v3 <- ve$ib[3,] for (i in 1 : nf) cat(sprintf("F[%d] = triface_(%d, %d, %d);\n", i - 1, v1[i], v2[i], v3[i]), file = f) ## write out color and transparency values cat("\n", "// Colors\n", "material M[];\n", sep = "", file = f) cols <- col2rgb(triangles$color) alpha <- triangles$alpha r <- cols[1,] g <- cols[2,] b <- cols[3,] if (any(alpha < 1)) for (i in 1 : nf) cat(sprintf("M[%d] = rgb(%f, %f, %f) + opacity(%f);\n", i - 1, r[i], g[i], b[i], alpha[i]), file = f) else for (i in 1 : nf) cat(sprintf("M[%d] = rgb(%f, %f, %f);\n", i - 1, r[i], g[i], b[i]), file = f) cat("\ndraw(surface(F), M);\n", file = f) invisible(NULL) }