Monday, March 26, 2012

[VolumetricLighting] convert obj to json

I modeled a gear in 3ds MAX (make sure it's centered at (0,0,0) ) and export it to obj format (triangle mesh).
I would like to load the gear model in my application. However, I only learned from the tutorial that we can parse JSON format (which is already written in JavaScript) in JavaScript:

  function loadModel() {  
   var request = new XMLHttpRequest();  
   request.open("GET", "model.json");  
   request.onreadystatechange = function() {  
    if (request.readyState == 4) {  
     handleLoadedModel(JSON.parse(request.responseText));  
    }  
   }  
   request.send();  
  }  
The above lines create a new XMLHttpRequest (comment: Chrome isn't happy with local request and keeps giving an "Cross origin requests are only supported for HTTP" error message.) and use it to load the file Teapot.json, and trigger an action that will convert the JSON text into the data we can use:
1:    var modelVertexPositionBuffer;  
2:    var modelVertexNormalBuffer;  
3:    var modelVertexTextureCoordBuffer;  
4:    var modelVertexIndexBuffer;  
5:    function handleLoadedModel(modelData) {  
6:      modelVertexNormalBuffer = gl.createBuffer();  
7:      gl.bindBuffer(gl.ARRAY_BUFFER, modelVertexNormalBuffer);  
8:      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.vertexNormals), gl.STATIC_DRAW);  
9:      modelVertexNormalBuffer.itemSize = 3;  
10:      modelVertexNormalBuffer.numItems = modelData.vertexNormals.length / 3;  
11:      modelVertexTextureCoordBuffer = gl.createBuffer();  
12:      gl.bindBuffer(gl.ARRAY_BUFFER, modelVertexTextureCoordBuffer);  
13:      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.vertexTextureCoords), gl.STATIC_DRAW);  
14:      modelVertexTextureCoordBuffer.itemSize = 2;  
15:      modelVertexTextureCoordBuffer.numItems = modelData.vertexTextureCoords.length / 2;  
16:      modelVertexPositionBuffer = gl.createBuffer();  
17:      gl.bindBuffer(gl.ARRAY_BUFFER, modelVertexPositionBuffer);  
18:      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.vertexPositions), gl.STATIC_DRAW);  
19:      modelVertexPositionBuffer.itemSize = 3;  
20:      modelVertexPositionBuffer.numItems = modelData.vertexPositions.length / 3;  
21:      modelVertexIndexBuffer = gl.createBuffer();  
22:      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, modelVertexIndexBuffer);  
23:      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(modelData.indices), gl.STREAM_DRAW);  
24:      modelVertexIndexBuffer.itemSize = 1;  
25:      modelVertexIndexBuffer.numItems = modelData.indices.length;  
26:    }  
So I'm searching for a method to convert obj to json. Attached is a python script that will do the job for us!
To use the script in windows, open a command line and cd to the dir where your obj file is located. Put this script in the same directory and type the following in the command line:

 python obj2json.py gear.obj > gear.json  

No comments: