Skip to content

Instantly share code, notes, and snippets.

@jlliu
Created December 8, 2019 18:12
Show Gist options
  • Save jlliu/1bbef66defe799382bec8552a1c1d707 to your computer and use it in GitHub Desktop.
Save jlliu/1bbef66defe799382bec8552a1c1d707 to your computer and use it in GitHub Desktop.
How to use obj files with webgl-bj-loader.js
//Step 1: Import js file into the head of index.html:
<script src="https://cdn.jsdelivr.net/npm/webgl-obj-loader@2.0.6/dist/webgl-obj-loader.min.js"></script>
//Step 2: Download any OBJ files and copy the contents of each one as a variable in the JS code (use a separate file for neatness)
var starData = `
# Blender v2.69 (sub 0) OBJ File: '20facestar.blend'
# www.blender.org
mtllib 20facestar.mtl
o Mesh_Mesh.015
v 0.951056 0.000000 0.309017
v -0.000001 0.000000 1.000000
v -0.951057 0.000000 0.309016
v -0.587784 0.000000 -0.809018
....(etc)`
//Step 3: Call this
var obj_mesh = new OBJ.Mesh(starData);
var createObjectVertices = function(meshObj){
var a = [];
for (var i = 0; i < meshObj.indices.length; i++){
// We will have to change this function to include more vertices if we're going to do bump mapping
const NUM_COMPONENTS_FOR_VERTS = 3;
var elementIdx = meshObj.indices[i]; // e.g. 38
var thisIndex = meshObj.indices[i];
var x = meshObj.vertices[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 0]
var y = meshObj.vertices[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 1]
var z = meshObj.vertices[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 2]
a.push(x); a.push(y); a.push(z);
var n_x = meshObj.vertexNormals[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 0]
var n_y = meshObj.vertexNormals[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 1]
var n_z = meshObj.vertexNormals[(elementIdx * NUM_COMPONENTS_FOR_VERTS) + 2]
a.push(n_x); a.push(n_y); a.push(n_z);
var u = meshObj.vertices[(elementIdx * 2) + 0]
var v = meshObj.vertices[(elementIdx * 2) + 1]
a.push(u); a.push(v);
}
return a;
}
let obj_vertices = createObjectVertices(obj_mesh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment