frenchtoast747/webgl-obj-loader

loading multiple objects in a single scene?

venidev opened this issue · 1 comments

Hello ,

Is it possible to load multiple objects or multiple instances of same obj into the scene? how do i do it?

thanks
Veni

Yes it is completely possible.

This library also includes a simple utility function that will initialize the OBJ meshes into VBOs (Vertex Buffer Objects) that are stored on the graphics card. Once you initialize an OBJ mesh, the VBOs are then used when calling the drawElements function. I've updated the README to show the correct usage of the util function. At the start of your WebGL program initialize the buffers like this:

obj_utils.initMeshBuffers( gl, app.meshes.suzanne );

where gl is the webgl context variable and app.meshes.suzanne is the mesh created from the obj loader. After calling this util function, the mesh initializes a VBO and stores the vertexBuffer, textureBuffer, and normalBuffer onto the mesh object. In short, call initMeshBuffers with your mesh and use it in a function like this:

function drawObject( model ){
  /*
    Takes in a model that points to a mesh and draws the object on the scene.
    Assumes that the setMatrixUniforms function exists
    as well as the shaderProgram has a uniform attribute called "samplerUniform"
  */
  gl.bindBuffer(gl.ARRAY_BUFFER, model.vertexBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, model.mesh.vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ARRAY_BUFFER, model.textureBuffer);
  gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, model.mesh.textureBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ARRAY_BUFFER, model.normalBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, model.mesh.normalBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.mesh.indexBuffer);
  setMatrixUniforms(); // set up your uniforms here
  gl.drawElements(gl.TRIANGLES, model.indexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
}

Make sure setMatrixUniforms() is implemented to set up uniforms on a per-object basis. Otherwise, all you have to do is call drawObject( app.meshes.suzanne ); for each instance of the OBJ that you want.