Skip to content

Instantly share code, notes, and snippets.

@notlion
Created August 5, 2011 13:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notlion/1127492 to your computer and use it in GitHub Desktop.
Save notlion/1127492 to your computer and use it in GitHub Desktop.
Plask OBJ Loader
// Based on Dean McNamee's OBJ loader
// Modified to output triangles with texture coords
function loadOBJ(filename){
var filedata = fs.readFileSync(filename, 'utf8');
var lines = filedata.split('\n');
var tris = [ ];
var v = [ null, ]; // Verts, indexed from 1, so put in a filler.
var vt = [ null, ]; // Texture Coords, indexed from 1, so put in a filler.
var vn = [ null, ]; // Normals, indexed from 1, so put in a filler.
function splitFaceIndices(str) {
var pieces = str.split('/');
var obj = { v: parseInt(pieces[0]),
vt: parseInt(pieces[1]),
vn: parseInt(pieces[2]) };
return obj;
}
for (var k = 0, kl = lines.length; k < kl; ++k) {
var line = lines[k].trim();
if (line.length === 0 || line.substr(0, 1) === "#")
continue;
var pieces = line.split(/\s+/);
switch (pieces[0]) {
case 'v':
v.push({ x: parseFloat(pieces[1]),
y: parseFloat(pieces[2]),
z: parseFloat(pieces[3]) });
break;
case 'vn':
vn.push({ x: parseFloat(pieces[1]),
y: parseFloat(pieces[2]),
z: parseFloat(pieces[3]) });
break;
case 'vt':
vt.push({ x: parseFloat(pieces[1]),
y: parseFloat(pieces[2]) });
break; // Ignore texture coordinates.
case 'f':
var inds1 = splitFaceIndices(pieces[1]);
var indsi1 = splitFaceIndices(pieces[2]);
// We triangle all faces. This keeps the vertes ordering, always
// creating a triangle from the first vertex together with the next
// and previous vertex (indsi and indsi1).
for (var i = 3, il = pieces.length; i < il; ++i) {
var indsi = splitFaceIndices(pieces[i]);
tris.push([
{ v: new plask.Vec3(v[inds1.v].x, v[inds1.v].y, v[inds1.v].z),
vn: new plask.Vec3(vn[inds1.vn].x, vn[inds1.vn].y, vn[inds1.vn].z),
vt: new plask.Vec2(vt[inds1.vt].x, vt[inds1.vt].y) },
{ v: new plask.Vec3(v[indsi1.v].x, v[indsi1.v].y, v[indsi1.v].z),
vn: new plask.Vec3(vn[indsi1.vn].x, vn[indsi1.vn].y, vn[indsi1.vn].z),
vt: new plask.Vec2(vt[indsi1.vt].x, vt[indsi1.vt].y) },
{ v: new plask.Vec3(v[indsi.v].x, v[indsi.v].y, v[indsi.v].z),
vn: new plask.Vec3(vn[indsi.vn].x, vn[indsi.vn].y, vn[indsi.vn].z),
vt: new plask.Vec2(vt[indsi.vt].x, vt[indsi.vt].y) }
]);
indsi1 = indsi;
}
break;
default:
console.log('Unknown command: ' + pieces[0]);
break;
}
}
return tris;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment