Skip to content

Instantly share code, notes, and snippets.

@mekb-turtle
Last active July 11, 2022 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mekb-turtle/fa1f8392b5be5922c09f5e2cfeeca034 to your computer and use it in GitHub Desktop.
Save mekb-turtle/fa1f8392b5be5922c09f5e2cfeeca034 to your computer and use it in GitHub Desktop.
Script to convert Blender .obj file to raw triangles - https://github.com/mekb-turtle/render
#!/usr/bin/env node
const fs = require("fs");
const file = fs.readFileSync(process.argv[2]).toString().split("\n").filter(e => !e.startsWith("#")).map(e => e.replace(/\s+/g, " "));
const scale = parseFloat(process.argv[3] || "1");
const color = process.argv[4] || "0xFFFFFF";
let vertices = [];
let faces = [];
const triangle = (arr) => {
if (arr.length < 3) return [ arr ];
let z = [];
for (let j = 1; j < arr.length - 1; ++j) {
z.push([ arr[0], arr[j], arr[j+1] ]);
}
return z;
};
for (let i = 0; i < file.length; ++i) {
if (file[i].startsWith("v ")) {
vertices.push(file[i].split(" ").splice(1).map(e => parseFloat(e) * scale));
}
if (file[i].startsWith("f ")) {
faces.push(...triangle(file[i].split(" ").splice(1).map(e => parseInt(e.split("/")[0]))));
}
}
let z = faces.map(e => e.map(f => vertices[f-1]));
console.log(z.map(e => e.map(f => f.join(" ")).join(" ") + " " + color).join("\n"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment