obj2opengl: convert obj 3D models to arrays compatible with iPhone OpenGL ES

Whenever you want to use 3D objects modeled with a software such as Blender, 3ds Max or Cinema 4D in your iPhone Application or any other OpenGL project, you somehow have to make the designed data accessible to you program. To do this you can either load and interpret the files your models are saved into or you could directly provide the needed in-memory representation your program expects.

OBJ2OPENGL does the latter and acts as a converter from model files to C/C++ headers that describe vertices of the faces, normals and texture coordinates as simple arrays of floats.

Texturized and lighted 3D model with 8056 faces on the iPhone

Texturized and lighted 3D model with 8,056 faces on the iPhone

OBJ2OPENGL is a Perl script that reads a Wavefront OBJ file describing a 3D object and writes a C/C++ include file describing the object in a form suitable for use with OpenGL ES. It is compatible with Objective C and the libraries of the iPhone SDK.

The original idea and code base of this script comes from Margaret Geroch who kindly allowed me to enhance and republish this version. It now supports texture mapping and stored normals (instead of recalculating them). I have changed the structure of the generated arrays to work with glDrawArrays instead of glDrawElements. This is particularly needed for normals and textures where a vertex holds different information for some shapes. Also, this version includes several command line options to better control its behavior (such as scaling and moving the origin or setting the object’s and output file’s name).

If you can go with the defaults the conversion is as simple as

./obj2opengl.pl banana.obj

To include the converted object all you have to do is

// include generated arrays
#import "banana.h"

// set input data to arrays
glVertexPointer(3, GL_FLOAT, 0, bananaVerts);
glNormalPointer(GL_FLOAT, 0, bananaNormals);
glTexCoordPointer(2, GL_FLOAT, 0, bananaTexCoords);

// draw data
glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);

Examples

These are two models and generated sample output that is included in the provided archive:

Input Output Texture Vertices Faces
cube.obj cube.h 8 6
banana.obj banana.h banana.jpg 4,032 8,056

Downloads

Please use the comment function of this post to discuss any problems or noteworthy results accomplished with help of this script. I will read feature requests, too. Feedback is highly appreciated.

Support my Work

Writing an article like the one you have just read takes me quite an amount of my personal time. Way too often, I invest this time in different interests and decide against another blog post. On the other hand, you can motivate me with your feedback, your thoughts and your ideas. Please leave a comment below or flattr this post if you think it's worth it.

Comments

  1. [...] rendering on the iPhone. Addressing your loading issue: There might be an alternative with obj2opengl. It’s a script that converts wavefront obj files (nearly any 3d modeler can export this) to C/C++ [...]

  2. magicboker says:

    It seems better to use triangle_strip instead of triange for reducing memory size.
    Could you please modify it?
    Thanks!

  3. Unfortunately, this script is generic and the OBJ file can be of any content. You might find this paper http://www.ics.uci.edu/~gopi/PAPERS/Sibgrapi06.pdf or this tool http://www.cs.sunysb.edu/~stripe/ helpful to understand the issue with strips in this case. Generally spoken: It is not possible to render arbitrary triangles as a single strip.

    When splitting into several strips the generated script has to do the rendering part to configure the input this the right order. With an increasing amount of OpenGL roundtrips this might lead into performance issues as well.

    Could you elaborate why memory size is a problem in your case?

  4. Dan Bliss says:

    I created a simple planet with a single texture in Blender. I exported as a obj file with UV. When I run the script the .h file it map the texture over each triangle instead of mapping it over the object once. Any thoughts?

  5. Hey Dan, could you please provide the OBJ file? I am going to look into this.

  6. Dan Bliss says:

    I found out the UV coords are not assigned automatically in Blender. In editmode press the U key and select “Sphere from View”. The Perl script works great.

  7. Dawit Thepchatree says:

    Hey there Heiko,

    I just came across this Perl script of yours (from dev forums), and it works great! I really like how you simplified things (very easy to use!) and made it cross-operational for many systems and platforms. :D

    One gripe though: my Silo 2 exported OBJ file isn’t showing up correctly for the iPhone OS. Some faces are gone. I think it has something to do with Silo 2′s Triangulate function. Otherwise, when I deal with simpler models, it works fine. :)

    Anyway, here’s the OBJ file:
    http://www.mediafire.com/?ykzyiwd2nde

    Thanks.

  8. Hey Dawit,

    thank you for your comment. Your exported obj file partly contains faces with 4 vertices each. Currently, this script has these known limitations, though: “This script expects and OBJ file consisting of vertices, texture coords and normals. Each face must contain exactly 3 vertices. The texture coords are two dimonsional.”

    Is it possible for you to export your model with triangles only?

  9. okfp says:

    Heiko,

    really amazing script. But I was trying to use to render your example in iphone simulator Xcode project. I don’t know where I failed but I didn’t see the bananas on the screen. I was trying to adjust glOrthof thinking should be big enough to see it, but doesn’t work. Could you please provide your sample Xcode project or how do you implent that?

    Thanks

  10. Hey okfp,

    as a starting point, use the GLGravity sample from the dev center and add the banana.h to the project. Now, replace the #import “teapot.h” in AppController.m with the banana.h and build the project. You will find to areas with errors, replace these lines with the ones given on top of the banana.h. First, replace the whole loop after “// Draw teapot” with the single glDrawArrays statement. Second, set the vertex and normal pointer as stated in the comments of banana.h. That’s it.

    I am sure you will find some sample code to learn the handling of textures, too.

  11. jason colburne says:

    this script should generate ansi c style comments (/* */) rather than c++ style to be more portable. just a suggestion =) trivial change

  12. Thank you for your suggestion, jason. I will implement this with the next iteration.

  13. Alex says:

    Please, include full xcode project
    i try create test app – but it not work

  14. Hey Alex, as stated in my comment http://www.heikobehrens.net/2009/08/27/obj2opengl/#comment-3460 above I used the GLGravity sample from Apple to produce the screenshot. Unfortunately, I cannot repost this code since it is protected by law. Feel free to ask any questions that arise following the steps I described on that comment, though.

  15. fx61803 says:

    mr. behrens,
    thanks for the converter, works like a charm!
    after initial obstacles where it was not able to generate correct header file caused by not having only triangles in the model I am now able to compile the model with xcode; brilliant!

    / the converter produces a weird bug when skipping number values and leaving only commas in the array definition when the model is not in expected format, I guess; however when I exported the same model with triangles only, it works perfectly /

    however, since I am a complete noob in this field I even don’t know if something like this makes sense, but is it possible to automatically apply a corresponding texture to a model defined like this in xcode? if so – how ? – does there exist a corresponding apple tutorial/concept which can be easily adopted for this ?
    thank you very much!
    r.

  16. Hey R,
    I am not completely sure what you are asking for. If your obj contains texture coordinates you can bin them using glTexCoordPointer as you can see in the generated comment of your .h file.

    Loading the corresponding image file is another story, though. If you are not familiar with OpenGL ES and texture mapping these links might be helpful:
    http://iphonedevelopment.blogspot.com/2009/05/opengl-es-from-ground-up-part-6_25.html
    http://web.me.com/smaurice/AppleCoder/iPhone_OpenGL/Entries/2009/4/1_OpenGL_ES_05_-_Texture_Mapping_Our_Square.html

  17. fx61803 says:

    Hello!
    thanks for the links, they’ve been helpful
    now, I couldn’t make the texturing of your banana to work, but it seems it required a call to
    glEnableClientState(GL_TEXTURE_COORD_ARRAY) after glTexCoordPointer(2, GL_FLOAT, 0, bananaTexCoords) to make it finally accept the texture
    I do not know how generic this might be and if it’s worth mentioning in generated header for example
    thanks!
    r.

  18. Ryan says:

    Great script! I’m just wondering how to use scaling options from the command line?

    Keep up the great work!

    Ryan

  19. ./obj2opengl.pl cube.txt -s 4
    does the trick. try
    ./obj2opengl.pl --help
    to learn more about the options.

  20. Ivan says:

    Sorry, I’m noob in mac, i have the next error:

    -bash: ./obj2opengl.pl: Permission denied

  21. Ryan says:

    Does anyone know of a good way to create simple bounding boxes using these .h files? Something as simple as creating a bounding rectangle using max and min z, x, and y values would do.

    Thanks!

  22. Ryan, you can easily iterate over the verts array and collect for each dimension the min and max values. But, adding this to the output of the script would be helpful, too. Thanks for your suggestion.

  23. Jace says:

    Hi,

    I wondered if you could help me. I created an object in Carrara 6 pro and exported to wavefont obj file. I ran your script and I got “Illegal division by zero at ./obj2opengl.pl line 294″ I checked this and it seemed to be related to scale, so i specified -noScale and it appeared to work. However upon further inspection the header file was in fact invalid and contained nothing like the expected format, instead just a copy of the original obj file. I’m new to all of this, so forgive my ignorance but do you have any idea what I’m doing wrong?

    Thanks in advance for any help

    Regards

  24. Hey Jace,

    could you please provide your obj file so I can try to reproduce your error?

  25. Niklas says:

    Hey, great script.

    I’m a complete newbie when it comes to open gl, so pardon my ignorance.

    But when I create a simple object with normals, and render it all, as per your examples. If I then place a light above the object, and then rotate say a cube. It seems to me that as the cube rotates around the axis, the backside of it becomes dark when facing the light, rather then the side facing away form the light becomes dark.

    Do I need to recalculate or transform the normals for the light to be correct?

    I’m doing a push and pop call, then translate the cube I’m drawing. I would have thought that the face facing the light would become lighter. Isn’t that what the normals are for?

  26. Hey Niklas,

    your are absolutely right. The normals will be transformed (even scaled) according to your matrix. If you are an iPhone developer have a look at the GLGravity example to learn about lights and OpenGL. Also, this tutorial seems to introduce lights and normals quite extensively: http://www.falloutsoftware.com/tutorials/gl/gl8.htm

  27. Niklas says:

    Hm, seem that I had forgotten to put in glMatrixMode(GL_MODELVIEW) after I set up the projection view port… So the light now seems to work…

  28. [...] obj2OpenGL – Heiko Behrens’ PERL script to convert *.obj (Alias Wavefront) to opengl. This is attractive because it loads data that OpenGL can render directly. Also it’s been designed with the iPhone/iTouch in mind. If I use this I still would like to write an automation to export my models from the blender file format to obj. It would be really nice if I could ‘press a button’ and get all my 3D files updated at once. I guess I should try this first… [...]

  29. iphone4 says:

    There is a typo:
    print OUTFILE “glTexCoordPointer(2, GL_FLOAT, 0, “.$object.”TexCoords);\n”
    if $numTextrue > 0;

    should be:
    print OUTFILE “glTexCoordPointer(2, GL_FLOAT, 0, “.$object.”TexCoords);\n”
    if $numTexture > 0;

    It stops glTexCoordPointer appearing in comment.

    Nice script though!

  30. Kjaerjakcajk says:

    Thanks for this, very helpful.

  31. Sergey Kopanev says:

    Thanks! Very nice script.

  32. Mirza Garibovic says:

    Hi Heiko,

    I made a small change to this so that it interleaves the vertex data in one contiguous array, according to http://developer.apple.com/iphone/library/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/Performance/Performance.html

    obj2opengl.pl:
    http://docs.google.com/leaf?id=0B3MMs33O0RexZDUzZDU1ZjItMjRlZi00OGQwLThkOTktN2RkYWM4MzNiMDM3&hl=en

    Example output (cube.h):
    http://docs.google.com/leaf?id=0B3MMs33O0RexMGY0YTI0NjAtY2E1MC00MGYwLWIxM2EtMGRmYzExMzE0ODUz&hl=en

    Example draw (note the required stride constant):

    glVertexPointer(3, GL_FLOAT, cubeStride, cubeVerts);

    glNormalPointer(GL_FLOAT, cubeStride, cubeNormals);

    glDrawArrays(GL_TRIANGLES, 0, cubeNumVerts);

  33. Sergey Kopanev says:

    Hello, all

    But what if the object 2 or more textures?
    thanks.

  34. Lisa Wilkinson says:

    Hi,

    I have been having problems getting the UV texture coordinates to work.
    Here is a screen shot of what it looks like in Maya: http://imgur.com/z2Ica.png
    and what it looks like on the iPhone: http://imgur.com/A1alQ.png

    Does anyone know how this could be fixed?
    Thanks in advance for any help

  35. Sergey, currently the script merges all groups into a single object and can handle only one texture.

  36. Hey Lisa, can you reproduce this error with a simpler example (e.g. a cube)? I am afraid the .obj file itself has some unexpected mappings.

  37. Lisa Wilkinson says:

    Here’s another example.
    Maya: http://imgur.com/PVYqa.png
    iPhone: http://imgur.com/FGcGs.png
    Texture: http://imgur.com/ivt5J.png

    and my code to draw it:

    glPushMatrix();
    glBindTexture(GL_TEXTURE_2D, textures[13]);
    glVertexPointer(3, GL_FLOAT, 0, cubeVerts);
    glTexCoordPointer(2, GL_FLOAT, 0, cubeTexCoords);
    glDrawArrays(GL_TRIANGLES, 0, cubeNumVerts);
    glPopMatrix();

  38. Sergey Kopanev says:

    Heiko,

    Thanks for answer. Do you have a plan make script working with some textures ?

  39. Sergey Kopanev says:

    Heiko,

    What is “Center” that script saying ?
    Center:

    I have two models and i have no success draw it correctly in space.
    I’ve tried glTranslatef to “Center” and glScalef by “Scale by” before rendering – but my models located in space at the wrong coordinates.

    How can I draw 2 models on their coordinates same as in 3dMax?

    thanks,

  40. Ty says:

    Heiko,

    I seem to be experiencing some problems converting Silo 2 .obj files to .h files with obj2opengl. The conversion appears to work and I am able to load the .h file on an iphone using GLGravity. But the iphone only seems to render the model partially, in a triangle pattern as indicated here: http://imgur.com/fGN8f.jpg

    I found another script, for blender, which enabled me to export solid models:
    http://iphonedevelopment.blogspot.com/2009/07/improved-blender-export.html

    But I would prefer to model in Silo. Blender makes my head heart. Any idea what’s going on here?

  41. Hey Lisa, Hey Ty,

    please provide the .obj file of the most simple version with errors you are converting from (e.g. a cube). I think, the format of the .obj file is slighty different from what the script expects.

  42. Ty says:

    Heiko,

    Thanks for getting back to me. Great little utility! I am really interested in figuring this out and appreciate you taking the time to look at it. I posted both a cube and sphere here: http://gist.github.com/333101

    Both models have the same visual artifact.

    cube.obj: http://gist.github.com/raw/333101/b24c888179d871c4355cbd54a21ad616b4afa3d1/cube.obj

    sphere.obj: http://gist.github.com/raw/333101/e2b4dc69df4f25bd0196817fc3f5d7ee5aec2b9a/sphere.obj

    I have tried dozens of models, all have the same issue. For what it is worth, Blender can’t open Silo .obj files, so perhaps Silo went off standard.

    Anyway, thanks again…. Wow, “Blender makes my head heart.” Apparently Blender makes me funny too.

  43. Ty says:

    Heiko et all,

    Last night at about 4AM, I think I figured this ‘bug’ out. Turns out it is not a ‘bug’ at all, and has nothing to do with the obj2opengl script.

    If you manipulate a mesh in Silo and try to export it as a .obj, Silo will export it as Quads, not Triangles. Before you export your model from Silo, you must select it and choose “Modify” -> “Triangulate” or [Control + Shift + T]. Once you do this, you can export your model from Silo, run obj2opengl and the iphone will render the .h properly.

    Thanks to Jeff LaMarche for confirming the solution. Hope this post saves someone a couple days.

    Thanks again Heiko, for such a great little script.

    best wishes to all,
    ty

  44. robert says:

    hi there.
    I am trying to implement your project into opengl under windows xp using visual studio 2008. I convert the .obj file, paste the code to draw the model and I include the .h file to my project. Project compiles but the model does not come up on-screen. Is there any way to make it working? Cheers!

  45. Hey Robert,

    great to see that someone even tries to use this for VS! Unfortunately, I cannot assist you without further information. Did you try to narrow this down already? How does a simple header file (e.g. the examples) behave? Are you able to visualize anything loaded via glVertexPointer? How do these arrays differ from those generated by obj2opengl?

  46. robert says:

    hi again. thanks fot quick respond
    It works! but without texture. I am using the banana example. I resolved the problem by enabling following:
    //enable vertex coordinate array when glDrawArrays is called
    glEnableClientState(GL_VERTEX_ARRAY);
    //enable normal array when glDrawArrays is called
    glEnableClientState(GL_NORMAL_ARRAY);
    //enable texture coordinate array when glDrawArrays is called
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    Do Yoy have any ide how to fix the texture?
    Cheers!

  47. Carlos Pinto says:

    Hey Heiko, I just wanted to say thanks for the very useful script, makes porting 3D models for iPhone development a breeze. Good Job.

    I do have one question though. If an object (3D object that is) was painted with some colors instead of using textures, is there any way to obtain the color data in the obj file and then be parsed to the C style arrays like your script does it?
    The color array that I am talking about would be used in the function: glColorPointer(…) of the OpenGL ES API’s.

    Please let me know either by email or directly in this blog.

    Thanks in advance.

  48. Carlos Pinto says:

    Hello Heiko,

    I was just writing back again in regards to my last post, to give you more specifics as to what would be useful to include in the script.

    The .obj file that was produced for my 3D model contains color shading information such as the one below since I did not use an actual texture:

    g pSphere1
    usemtl initialShadingGroup
    f 1//1 2//2 12//3 11//4
    f 2//5 3//6 13//7 12//8
    f 3//9 4//10 14//11 13//12
    f 4//13 5//14 15//15 14//16
    f 5//17 6//18 16//19 15//20
    ……

    So I was wondering if there would be any way to parse these values into the equivalent in OpenGL ES that the function glColorPointer(..) would be able to take.

    Thanks,

    Carlos.

  49. Hey Carlos,

    unfortunately, the script currently neither supports materials nor separate groups of faces. Both would be required to colorize your models. Sorry for that.

    If you come up with a workaround or a patched version of the script, feel free to post it here!

  50. Esther says:

    Hi everyone!

    First of all I want to apologize because of my bad English. Thank you so much for this amazing tool, it is being very useful for me.
    I have the same problem than Robert. It works but wthout texture, and I am working with the banana example and GLGravity project to be sure that I am not making mistakes, and nothing. Could you help me to solve that please? Thank you Heiko.

  51. Shashank says:

    Works like a charm..Thank you so much Heiko !!!

  52. Chris says:

    Quick question.

    What software do you all use to render the 3D images?

    Thanks

  53. Stuart Rubin says:

    Thanks for this great script! I have used it successfully to make some cool models for one of my apps: http://www.groggerfactory.com/

    But, now, about a year later, I am working on a new app / model, and am stuck! I have two objects in blender. We’ll call one the “Box” and one the “Frame”, which is basically a “fence” which is super-imposed around the edge of the “box”. I export each object separately into .obj files, and convert them into .h files, and I render both in a single OpenGL app.

    In Blender, these two objects basically occupy the same space. I want to render both objects, but with different material, texture properties, but both at the same time. The problem is, when I render them, one is skewed off axis! The “fence” does not surround the “box”; it’s off by about 30% in one direction. It’s also a little too big. They should be EXACTLY the same size and position.

    So, what’s wrong? I was trying to see if there was something funny with the centers, origins, etc., but I’m really not very proficient with Blender, and was not able to get anywhere.

    Any ideas?

    All help appreciated.

  54. Hey Stuart,
    I am glad you could use the script to successfully build your iPhone app! Regarding your problem: the script scales and moves the object such that it has a uniform size and rotates around its “center of mass” (well, sort of). Try the options -noScale and -noMove and let me know if this works for you.

  55. Stuart Rubin says:

    -noScale and -noMove did the trick! Heiko, you’re awesome. How do you have time to do “real work”? Thanks again.

  56. Priye Saurabh says:

    Hey Stuart,
    I have tried to convert some files they show division by zero error on unix cmd line
    and
    I have a .DAE file now in want to convert it into a file format containing vertex , normals and textures. Can you suggest me how can i procede.

  57. The scripts expect an OBJ file. Try to convert your DAE file to OBJ first.

  58. Priye Saurabh says:

    Hey Stuart.
    I have some obj files that i want to convert to files containing normals and vector cordinates, but on unix cmd line it shows divide by zero error This was my first query.
    Now i have some another .DAE files how can i convert to obj file.Is there any script for that.

  59. Priye Saurabh says:

    Hey Stuart,
    Can you tell about script which converts DAE file containing vertex,normal and texture array or give me some link

  60. Mauro says:

    Thanks Heiko! the script works very well with Blender and Xcode. My only truble is that only one banana is completely opaque end the other is semitransparent, can you give me a hint? (I think it’s a problem with the deep buffer but I don’t know how to solve it).
    Thanks again, have a good work.

  61. Arun says:

    Fantastic Work!

    I just loaded a few sample models from blender website into my simulator. Also scaled them. It was fun to see everything rotating randomly!

    Will make my own models and post back results here soon.

    Arun

  62. Tim Reaves says:

    Any plans to update this to work with ES 2.0?

  63. Hey Tim, I haven’t used this script for OpenGL ES 2.0 so far. Anyway, I could update the script according to your adjustments if you send me the modified output for the given examples (cube and banana).

  64. Simon Platten says:

    Great work, thank you, just started working with OpenGL ES, I exported a sphere from GMAX using a script, then ran your perl script to convert to header file. I am using Java and it complained about the vertex array, so I modifed the perl script lines: 469 to 471 inserting (float) before each value, then I could cut and past the entire array into my java class.

  65. NoSoloUnix says:

    Thanks!! It’s perfect!!!

  66. thomas says:

    Hi,
    Nice script !
    But I got difficulties to covert my own OBJ ; the model render is half-render on all of its surface :S kind strange. Have you got this situation sometimes ?
    I use OPENGL ES.

  67. Thomas, please have a look at your OBJ file. Could it be that your faces contain four instead of three vertices each? The script assumes triangles at the moment. Maybe you can force your exporter to provide the mesh in the expected format?

  68. thomas says:

    Sorry it s me again :D
    So I tried few things : on some models , I got a texture but completely inverted (same prob as Lisa) and on some models, I got a render with a triangle patern (same prob as TY but I’m on Blender and I m trying with Silo).
    By the way, I use OPENGL ES 2.0 so maybe it s the prob :S.

  69. thomas says:

    I figured out why there is a triangle pattern : some OBJ models are in quads (Blender can convert easily)
    I still have this texture problem and I try differents ways like changing the sphere from view but it didnt work.
    Thanks a lot for your help

  70. thomas says:

    Hi,
    I found something interesting : your script generates multiples doubles of textures coordonates. I Will try to remove all doublons.
    Is it normal ? Does it come from my OBJ ?
    Thanks

  71. Hey Thomas,

    can you provide a simple example of input and output so I can have a detailed look into your problem?

    Cheers,
    Heiko

  72. Thomas says:

    Ok,
    First I used the example with the teapot defined as:

    static const float teapotVertices[NUM_TEAPOT_OBJECT_VERTEX * 3]
    static const float teapotTexCoords[NUM_TEAPOT_OBJECT_VERTEX * 2]
    static const float teapotNormals[NUM_TEAPOT_OBJECT_VERTEX * 3]
    static const unsigned short teapotIndices[NUM_TEAPOT_OBJECT_INDEX]
    and loaded with glDrawElements();

    Then I tried to replace this model by new ones, I changed your script in order to get the indices but I always got this texture issue.
    My last thought was about glUniformMatrix4fv which may cause this problem.
    Otherwise I used OpenGL ES 2.0 on Android Platfrom
    Again thanks for your help.

  73. VansFannel says:

    Banana.h is 4.5MB. I think is so big for a iPhone development, isn’t it?

  74. admin says:

    Hey VansFannel,

    in ObjectiveC the .h and .m files are being compiled to binary code that typically is way smaller than the corresponding source code. For me, the banana builds to 1,5MB which is twice of the size of bananaNumVerts*3*sizeof(float)*(3+3+2). If you want to decrease this size I recommend to use smaller models or an external model file that is compressed and a parser that uncompresses the data while loading.

  75. VansFannel says:

    Hi Heiko,

    Thanks for your answer.

    Probably I will need to add more than one header file. And, what about RAM memory? Banana model has 24168 vertices. Are they so many?

    I’m only asking. I’m not sure if this is a problem or not.

    Thanks in advance.

  76. putiferio says:

    Beautiful!!!

  77. Valerie says:

    Worked Great! Thanks Heiko. I have a rocking chair obj model and it looks great. My problem is when testing it on the iPad device using accelerometer, it behaves kind of jerky. I’m not sure if this has something to do with the center mass or if there’s some way for me to adjust this. Any ideas?

  78. Hey Valerie, starting with the GLGravity sample I cannot see any differences between the iPhone and iPad. I am afraid, I cannot help you with that.

  79. Valerie says:

    Thanks for the reply Heiko. My .h file is 16mb. Do you think that’s a problem?

    I want to display my chair, having it rotate around for the user to view all sides. I want the user to be able to swipe it, in order to rotate it faster or in the other direction. I was just wondering if you think I’m heading in the right direction with your script? Logically I think it should be possible, but you’re the expert, so I thought I’d check with you. Should I be using a game engine instead?

    Anyway, with the use of your script (and glgravity) I’m actually able to see my model on the iphone/ipad. So thanks for everything!

  80. hellkero says:

    Hi,
    Thx, for great convert script. But i have some stupid question.
    How to run this script?
    i’m a windows user and never experienced with perl before, now i’m already installed apache 2.0 and ActivePerl 5.10 following this site..
    http://www.ricocheting.com/how-to-install-on-windows/perl

    pls, give any advice

    Thx.

  81. Following one of the hits for http://www.google.de/search?q=windows+run+perl+script it should be perl obj2opengl.pl

  82. Ahmed says:

    Hi Heiko, how r u ? great thanks for your great script :D
    i just want to draw simple sphere as planet with texture but when i tried to get .obj from 3ds max or blender and convert it …. the object didn’t appear perfect and also when put the texture it’s totally bad.
    please i want your advice (will be great to have sphere .obj or .h to use it)
    i am working in android 2.1 on HTC using opengl es 1.1

    Thanks in advance
    Ref3at

  83. Valerie says:

    Heiko, how do I code the banana.jpg texture to the model? Would you mind explaining or giving me a tip? Thanks!

  84. Hey Valerie, please have a look at the tutorials I mentioned in comment 3910

  85. Thank you for the kudos, Ahmend. Could you be a bit more specific on what exactly is “not perfect” and “totally bad” on your output? Then, does it work with the given examples?

  86. Ram says:

    Hi,
    Just dropping by to say that the instructions in http://heikobehrens.net/2009/08/27/obj2opengl/#comment-3460 works perfectly.

    thanks,
    Ram

  87. hellkero says:

    Hi, Heiko
    I got problem again, after browsed the path to script directory and try
    “perl obj2opengl.pl” it just show only

    “Usage:
    obj2opengl [option] file
    use -help or -man for further information”

    so i try again with “perl obj2opengl.pl mymodel.obj” and it came out with

    “Can’t open perl script “obj2opengl”: No such file or directory”

    Is it supposed to be like this?

  88. Tamil says:

    Thank you very much. This script saved a lot of time for me.

  89. thesimpsons666 says:

    Hey Heiko
    Thanks for the script. I have managed to get the CLGravity code to built with no errors but all I see is a white screen. not sure what im doing wrong.

    But anyway I have 12 models that I have made and want to put in a iPhone App. The models are in obj format but I need to get them into Xcode. How can I go about this?
    Is it simply a matter of using your script to convert my obj into a .h and the replacing (banana.h) with mymodelsname.h?

    Sorry about the noob questions but it’s my first attempt at anything like this.

  90. Hey,

    I recommend digging through the tutorials I mentioned before, to get familiar with OpenGL ES on iOS. Once you mastered these, you will understand that for OpenGL you need arrays of floats to manage your data. obj2opengl helps you to produce these arrays and stores them as static data in your header files. And yes, an Xcode project can contain many header files.

    Good luck!

  91. thesimpsons666 says:

    Hey Heiko

    Thanks for the reply. I have found a great blog at http://iphonedevelopment.blogspot.com/2009/06/using-3d-models-from-blender-in-opengl.html. Which says very similar things to you.

    I have found that blender and Cheetah 3d both export models (.obj) to .h files. What I can’t seem to figure out is how the textures are converted across. Are they in the .h file as well? The reason why I ask is some of my models are quite detailed (anatomy parts).

  92. sen says:

    I had obj file with me, i need to convert it to a header file , wat was the procedure to convert to headerfile

  93. assuming your obj file is called banana.obj and you are running a unix-like shell, it’s identical to what I wrote above: “./obj2opengl.pl banana.obj”. Have a look at the comments to understand how windows users using their shell.

  94. Grinneh says:

    Hey Heiko

    Firstly, I’ve given your converter a try, with the GLGravity code, replacing the lines you suggested. I can see the banana appear, however the texture on the banana is just yellow (no green/brown parts on the tips of the banana), it just seems like its not even drawing the texture onto it. I’m including the banana.h and banana.jpg in the project, is there something else that I needed to do?

    Also, I have my own obj model that I tried to use with the script. After converting it, I added it to the project, changed the lines of code, compiled and ran the program, but all I get is a black screen. I noticed as it was converting the model from .obj to .h it reported 0 normals, so I’m wondering if that has something to do with that.

    Thanks in advance for your advice!

  95. Grinneh, the code of the GLGravity example provided by Apple does not apply any textures. Please have a look at the tutorials I mentioned in the comments to learn more about texture mapping. Regarding your empty output I cannot say anything useful without more information. Could you provide your .obj file?

  96. Grinneh says:

    Hey Heiko,

    Yea, thanks for that, got the textures working for the banana. As with the obj file that was giving me issues. Here it is;

    http://rapidshare.com/files/447078607/foot.zip

    Just seems like the converter doesn’t like it.

    Thanks for the help

  97. sen says:

    I used ur perl script to do the headerfile, but the objects are very very less in size, and the header file size is 5.5mb, i want to increase the size of my object in the phone, can u help me

  98. Hey Sen,

    your questions regarding the header file size and scaling had already been discussed in the comments above. Let me know if you have specific questions that go beyond the answers provided.

  99. alex says:

    Sorry for the following trivial question .. but I am newbie in the opengl/3d world.

    Assuming I already make a 3d model using blender. How can I make the texture like the banana.jpg from my blender model?

  100. Textures are not produces from models inside of blender. Traditionally, one uses photographs or other 2D images to map them to your 3D models. I bet there’s plenty of information about texture production out there. Any 3D modeling book would be a good read, too. Hope that helps.

  101. jacks8x says:

    Hi, is it fine when working with 3ds max export file. i have a .obj file export from autodesk 3ds max and i use obj2opengl to convert this file to .h file, then i include this file to show the shape on iPhone, but the shape on iPhone and the shape on 3ds max is different

  102. I am glad the script could help you. Could you be more specific on how the shape differs from your expectation?

  103. jacks8x says:

    Thank u for answering me! I make a sphere from 3ds max, but in iPhone it like an oval, ellipse

  104. There are different possibilities why a sphere would be rendered asymmetrically. The script only takes care of the coordinates, though. Could you open a bug on github providing the actual .obj file and your output .h together with a screenshot? You didn’t play around with the script’s scale option, did you?

  105. sim says:

    i am using blender software, i want to create obj file which should contain
    vertices
    normals,
    texturecoordinates
    faces
    can u help me out bcoz when i am using 3d models from internet and converting to header file some of the above things are missing, please can u help me out, it is very important to me.

  106. Molma says:

    Hey im having a it of trouble trying to draw these vertex arrays..

    is there cetain things that i should enable?

    if so then what?

    also im wondering where i should put each function(initialize or main loop?)

  107. Molma says:

    hey when i render my image i get a badly scratchy looking model..

    anyone have this problem?

    http://img208.imageshack.us/i/glitcheo.jpg/

  108. sen says:

    I used ur perl script for generating header file, but the 3d model was not apperaing correctly had some holes in the object. how to render 3d object properly
    the header file contains these parameters
    glVertexPointer(3, GL_FLOAT, 0, clock_01_objVerts);
    glNormalPointer(GL_FLOAT, 0, clock_01_objNormals);
    glTexCoordPointer(2, GL_FLOAT, 0, clock_01_objTexCoords);

    glDrawArrays(GL_TRIANGLES, 0, clock_01_objNumVerts);

    plz suggest me,it will be helpful to me

  109. Hey Sim, could you be a bit more specific on what exactly is missing? Did you try to ask this question on one of the Blender forums?

  110. Hey Molma,

    regarding your texture question. It depends on your other drawing operations. I suggest you walk through one of the tutorials mentioned above. You sceenshot looks like the result of a model where faces are not built with triangles. Could you double check your .obj file please?

  111. Hey Sen,

    these holes could be a result of backface culling and/or missing faces. Could it be that your .obj file does not use triangles but strips or quads?

  112. sen says:

    obj files had taken from net and these are the

    3D Model Specifications

    Geometry:Polygonal
    Polygons: 127
    Vertices: 242
    Textures: Yes
    Materials: Yes
    Rigged: No
    Animated: No
    UV Mapped: Unknown
    Unwrapped UVs: Unknown\

    can u suggest me to render the object properly , it is very urgent to me.

  113. Sen, your response does not refer to my suggestions. If you do not know whether your .obj file contains quads or how the faces are oriented and didn’t produce the .obj file by yourself I recommend you to ask the designer who provided it to you to do so.

  114. sen says:

    Thank u, can u tell me what is the information i need to gather plz tell me briefly, it will help me.

  115. jacks8x says:

    I used opengl es template in Xcode to create a project, then i import sphere.h file which was created from your script and then followed the code you suggest,then the sphere became something like an egg (not sphere). But when i use another project (i found it on the internet but i don’t remember the site i found it) not opengl es template in Xcode and everything is ok. So I think maybe there is something wrong in the code??

  116. Molma says:

    hmm…if its the triangle problem then it might be the fact that i started out with squares and then changed them to triangles.

    im going to try the example out just to see what happens.

    also i did my model in blender if that helps

  117. Molma says:

    alright i just tried putting your banana into my project, its having the same effect….its probably the way i setup my code

    can you check this and see if you can point something out?

    http://pastebin.com/PSaL8TwA

  118. sen says:

    In the banana example i had seen many colors in that object like yellow, light black. in the similar way my obj file contains 3 colors, i created aheader file using ur perl script and included it in my application and it is not showing all the 3 colors can u help me out .

  119. Hey Sen, I am using a concept called “textures” with that examples. Have a look at the OpenGL Tutorials I referred to earlier to learn how those work. Good luck!

  120. sen says:

    In my 3d model, i used 3 cylinders with different colors for each cylinder, when i am rendering that 3d model into my phone, three colors are not appearing only one single color is appearing for whole 3d object. just i apply different colors to the different cylinder, i think it is not the texture how can i render into my phone, plz can u help me out

  121. Hey Sen, at the moment, the script only supports textures to color vertices. You could either use textures instead of solid colors or enhance its functionality. I’d be happy to pull your commit!

  122. dwi says:

    Hi Heiko
    I really appreciate your works.
    I’m an iphone developer , but I am very inexperienced in perl
    will you teach me how to use obj2opengl.pl step by step

    thank you

  123. Hey dwi, there’s no magic at all. Just execute the script from the command line as I wrote on this post. It might be necessary to add the execution flag to the script, though. Try chmod +x obj2opengl.pl to do so before running it.

  124. Rassall says:

    Hello,

    I am facing problem o run this perl scrip obj2openl.pl. I open my widnows xp command promt then go to the script (ob2opengl)directory. I write following command:

    perl obj2opengl.pl cube.obj

    But i Receiving two error

    error in option spec: “centre=f{3}”
    error in option spec: “ARRAY(01ad2c60)”

    I also try in cygwin to run this cript by follwing command:

    ./object2opengl.pl cube.obj

    but i got following error:

    bash:./obj2opengl.pl…….permission denied

    i hardly need obj converter to .h file for my 3d file.

    Any Idea how i can execuite this obj2opengl.pl script in my windows xp pc.

    thanks

    Rassall

  125. Hey Rassall, I cannot test the script on a windows machine at the moment. As a workaround, you could probably comment out the configuration of that parameter if you don’t rely on the -center argument.

  126. Molma says:

    hey i have been wondering, is there a way to make the compiling process quicker? im making a PC game, but the compiling takes about a minute and a half…is there a way to maybe skip the header reading?

  127. It might work out to put the arrays into a .c/.m file that’s been compiled only once and access their addresses via a function. Only this function prototype then remains in the .h file. Haven’t tried this out, though.

  128. Praveen says:

    Hi Heiko

    This is a beautiful script. Worked nicely. I am a bit confused because the script output for Vertices is different then the NumVerts variable that you generate for code.

    Haven’t looked at the codeas yet though but this is slightly confusing.

    Thanks a lot for the script though.

  129. Thank you for your feedback, Praveen. Could you be more specific on the difference beetween NumVerts and Vertices? Is the output wrong? What do you expect instead? Do the samples work for you? Could you provide a sample .obj I could test against? Feel add a new issue on GitHub or write another comment, here.

  130. Gyan says:

    hi heiko, i have problem to make a texture ( ex : banana.jpg ). what tools you use to make the this texture.png??

  131. Hey Gyan, this is actually real banana peel. Roll it out, take a picture and give it final touches in Photoshop – voilà!

  132. Rana says:

    Hey Heiko could u please tell me how to use your script as i’m a beginner and wanna use it

  133. Rana says:

    Hey does i-phone supports any 3D model format supports animation,,as i wanna load an animated model

  134. Hey Rana, if you want to google for it, the terms are “run perl shell script”. Also there are several answers on similar questions throughout the comments. Regarding animations: I am not aware of any file format the iOS SDK understands out of the box. Since the .OBJ file format handles static meshes only, the script obj2opengl.pl cannot help you with that either. On the other hand, there are plenty of feature-rich 3D libraries for iOS out there, some of them can handle animations, too.

  135. Kevien says:

    Hey,plz i cann’t load the texture and the link u loaded didn’t also load it,,would u plz load the code for texture u used

  136. Rana says:

    hey heiko i mapped the texture on the model but unfortunately it isn’t good as the texture doesn’t exactly match the vertices and i tried more than one model with different textures and still the same problems
    so any Ideas plz ?!

  137. Siva says:

    Hi Heiko..
    I tried with someOther obj files.. But the TextCoords always 0.. How To get The TextCoords ??

    Pls reply..

  138. Hey Siva, unfortunately I cannot offer any reasonable advices with just this information. Did you read the various comments on the post? Does it work with the sample models? Do you .obj faces consists of triangles, only? Did you double-check that your .obj file contains texture coordinates?

  139. Alex Egg says:

    I’m using this for Android opengl es 2.0 projects. Thanks for your work!

  140. Alex Egg says:

    It’s interesting how the output .h files grow in size so much -why is this. At some point if you have a large enough model is this method unpractical?

  141. Joey says:

    I am having a helluva time executing this script. I am running win7 64 bit and don’t know if that’s the problem or what but every time I attempt to execute this it just spits out about 80 errors and says obj2opengl.pl has to many errors.

    Any ideas?

  142. Hey Joey, without further information I have no clue either. Could you open a ticket at https://github.com/HBehrens/obj2opengl/issues/new and describe your error with log, and files if any in detail?

  143. Joey says:

    I posted the log I am getting with errors… https://github.com/HBehrens/obj2opengl/issues/1

  144. Rajesh says:

    Hi Heiko

    I am 3d modeler. and i wants to do some ar stuff for iphone.
    for that i need to export my 3ds max model to opengl code
    is it possible to export 3d model from 3ds max application
    how can i export. can u plz advise me step by step

    Please Reply

    Raj

  145. Pepe says:

    Hi,

    Where can I find more .obj models with a single texture image like the banana sample?

    Thanks.

  146. Hey Pepe, I do not have any recommendations regarding an online gallery of such models.

  147. Shaktising says:

    Hi Heiko,
    I m facing the same problem which JACE has faced. I am also getting the error “Illegal division by zero at ./obj2opengl.pl line 294″ when I tried to conver my obj models.
    If you want I can send the model to you.
    Pls reply.

  148. openGL says:

    Problem in OpenGL any one knows the solution for this
    -> I have created a tower of hanoi problem in 3D
    -> I am putting a disc on tower
    -> I able to see the disc not the tower the tower is going behind
    -> i dont know y it is going behind i have used glpush matrix and glpop matrix any one knows the solution
    Thank you in advance

  149. Nimesh says:

    Illegal division by zero at ./obj2opengl.pl line 294 Error:

    I have the same error as the other two guys:
    Here is how I created by Cube model:
    Open 3DSM -> new cube.
    Follow any tutorials to create texture.
    Export as .obj

  150. Leandro says:

    Hello, congratulations for the tutorial …. I would like to know where you bring that image banana.jpg worked and how to use it along with the texture coordinates.

  151. Simon says:

    Hi,
    I’m still playing with your script but I’d just like to say I think it’s very nice that you try to help almost every poster on this forum. Well done!
    And thank you for sharing your experiences and knowledge with everyone.
    Regards,
    Simon.

  152. Andy says:

    Hi,
    Do you have any version of obj2opengl.pl that could calculate indices (during conversion from obj to .h) so that I could use glDrawElements function?.

  153. Not at the moment, sorry. But feel free to fork it on GitHub.

  154. DivideByZero says:

    Sorry for the newbie question, but where should i say which is my .obj file. I went to the conclusion that its inside your script, but i can’t understand where.

    Thanks for help.

  155. Tanna says:

    hi,I‘m wonder that if the script can be used in windows ?If it can,does it need any configuration?I will be appreciate for your sharing!Thank you very much!

  156. Daniel S says:

    I just struggled for 2 days to get my textures to line up correctly… I discovered that if I flip the UV image vertically, when i apply the texture to the model it displays correctly. Im not sure why I need to do this. My process to get the textures to display correctly once it looks right in Blender is:
    1) Blender > UVMap> Save As Image
    2) Blender > File > Export > .obj
    3) Uncheck Write Materials (Not used)
    4) Check Include Normals & Triangulate Faces
    5) Export OBJ
    6) Run script
    7) Open Image in Photo Editing Software > Flip Image Vertically
    8) Use model as previously described

    Not sure if this will work for everyone but it worked for me. Good luck

  157. rimsan says:

    13mb output *h file :(

  158. Rimsan, The textual representation of these arrays (.h file) takes a lot more space then the compiled version. Did you compile that and measure the impact on the size of your binary?

  159. steve says:

    Very good Utility, I have adapted to create a delphi unit with a procedure call draw + Name just have to had unit to uses and then call procedure to draw object if you would like copy please contact me.

  160. steve says:

    I read the comment from earlier about Triangle’s corrupting. can you tell me if the problem was solved, because if i use two lists and place them together one will corrupt the other when moving away from them at an angle, put them away from each other no corruption, i am using a wheel and tyre, i have reduced size of wheel no collisions , i have also tried all culling, If You have any idea’s they will be welcome. I also reexported both obj’s to make sure they were triangles.

  161. steve says:

    I Have solved triangle problem, depth plane was set too low, my bad, wrote component to drop opengl panel on form and left setting at 0.00001; just posting this inccase anybody else has same problem.

  162. Hey Steve, if you did a fork on GitHub let me know where I can find your version.

  163. steve says:

    sorry dont have it on any sites, can email to you have called it obj2delphi.pl

  164. steve says:

    Hello agian Heiko, have been writing a Component in Delphi to load obj files exported from 3dmax, so far I have got it to load obj file and mtl file.

    it loads all the texture’s, I have got it to display the object and textures, but not any special stuff, Can you tell me where i Can get some good information on the obj file that a begginer can understand, I need to know what all the information is used for in Basic opengl.

  165. admin says:

    Hey Steve, I found this link to the file format specification a valuable resource. Good Luck!

  166. steve says:

    Thanks for quick reply, have got component to load object with multiple textures and colors, started on transparency, have put options to scale, rotate and translate so far will have good read of link many thanks.

  167. hayashi says:

    very good !

    Now,I’m trying to use it with QCAR(AR Utility on Android/iPhone) to change polygon data in Sample source,”Image Targets”.

    sample code in QCAR “Teapot.h” have 4 variables
    (teapotVertices/teapotTexCoords/teapotNormals/teapotIndices).
    but,”obj2opengl” outputs only 3variables(bananaVerts/bananaTexCoords/bananaNormals).

    how can i use obj2opengl for QCAR?
    i’m not good with OpenGL,and i know it’s not obj2opengl’s problem..

    from japan

  168. Hey hayashi, if I understand you currectly, you are referring to faces with fource vertices each (quads). I am afraid this skript cannot handle those (neither for input nor output).

  169. Donald says:

    Hi is there a possibility for you to help me, I am doing a C++ OpenGL Project, I tried numerous times to create a simple .obj loader. your script works perfectly but I want my C++ program to do what the script does.

  170. hayashi says:

    thanks ,i will try it.

  171. hayashi says:

    yes, HEIKO!

    i could change polygon data on QCAR sample “ImageTargets” using “banana.h”(sample code : obj2opengl)

    i must use glDrawArrays() instead of glDrawElements().that’s only.

    ——————–
    File:ImageTargets.cpp
    ——————–
    line:401-

    glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, bananaVerts);
    glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, bananaNormals);
    glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, bananaTexCoords);

    and

    line:417-

    //use glDrawArrays() instead of “glDrawElements”
    /*
    glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT,
    (const GLvoid*) &teapotIndices[0]);
    */
    glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);

    ——————–
    terminal:ndk-build -R
    eclipse: build -> clean

    thanks a lot.

  172. steve says:

    I Have started writing an app to create Delphi Units from obj files below is a link to demo of app so far

    whttp://www.freedrive.com/file/1580096

    also this is where i have posted script for delphi unit

    http://www.freedrive.com/file/1580099

  173. steve says:

    very sorry :

    Last post of convertor had international problems with decimal point.

    The app : http://www.freedrive.com/file/1580559

    have updated application now create’s a delphi unit that will load object file with all texture’s.
    the file has to be 3ds max triangle.

    you will need

    DglOpengl.pas : http://www.freedrive.com/file/1580561

    Textures : http://www.freedrive.com/file/1580562

  174. Sander Versluys says:

    @HAYASI

    I can’t seem to get QCAR sample working like you do. Would you be so kind to contact me through twitter and perhaps share you sample project with me?

    Nothing gets drawn even when using glDrawArrays, do i need some changes elsewhere?

    Thanks! ;)

    twitter.com/ifsorbuts

  175. Rodrigo says:

    hi Heiko, I m desperate, I have been doing a A.R project whit QCAR ,when use the banana example run ok, but when I try to use my own model doesnt show the texture(its a simple texture,I try an image,download texture,3ds texture, and nothing), only when use the banana texture in mi model work it, I did the model with 3ds max and blender and neither work it. I dont know how can I fix it , How do you do the 3d model with texture?, I hope you can help me you are my last hope jjeje

  176. Zhenxin says:

    I am a China Woman IOS developer and I am new in Opengl Game application.
    I have a lot of time to know how to get object -c header file (TexturedVertexData3D) from where. Can you help me how to get this where?

    For ex: I want to get following texture object – c header file to mapping.

    #import “OpenGLCommon.h”

    #pragma mark Pineapple

    static const TexturedVertexData3D PineappleVertexData[] = {
    {/*v:*/{-0.077927, -0.104604, 49.076447}, /*n:*/{0.000000, 0.174718, 0.984588}, /*t:*/{0.056455, 0.679422}},
    ….
    }

    #define kPineappleNumberOfVertices 402
    // Drawing Code:
    // glEnableClientState(GL_VERTEX_ARRAY);
    // glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    // glEnableClientState(GL_NORMAL_ARRAY);
    // glVertexPointer(3, GL_FLOAT, sizeof(TexturedVertexData3D), &PineappleVertexData[0].vertex);
    // glNormalPointer(GL_FLOAT, sizeof(TexturedVertexData3D), &PineappleVertexData[0].normal);
    // glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertexData3D), &PineappleVertexData[0].texCoord);
    // glDrawArrays(GL_TRIANGLES, 0, kBanana1NumberOfVertices);
    // glDisableClientState(GL_VERTEX_ARRAY);
    // glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    // glDisableClientState(GL_NORMAL_ARRAY);

    How to get this style header file. using what tool from where?
    And is this possible to get in Autodesk 3Ds Max?

    How to get .pvrtc file not pvr. I could PVRText Tool, TexturePack Tool, etcc. but this is not supported.

    Thanks.

    EveryOne!!!

  177. matt says:

    Sorry, complete noob to eclipse and java here. You mention “#import “banana.h”" That doesn’t appear to be correct syntax within eclipse. Maybe I just haven’t told the project where the banana.h file resides.

    Where does the header file go?

    Would I have to use the NDK to include the header?

    Thanks.

  178. Marius says:

    great man ! i ‘ve been searchin for something like this , i had a blender export script , that was creating a c header file but wasnt quite working for textures , or maybe i didnt got something working there but this after a few trials i got it working . Thanks a lot!!

  179. Hey Matt, the source coude you are looking at is not java but C/Objective-C for the iPhone. With some more experience it should be possible to port these to Java, though. Good luck!

  180. ALi says:

    Hi,
    I have same problem which Rassall have.
    Last time it was converting successfully , But now showing error on running the command “perl obj2poengl.pl cude.obj”

    Error:
    Error in option spec: “center=f(3)”
    Error in option spec: “ARRAY(0x100bb504)”

    Any help please…

  181. Taylor says:

    Could you make a tutorial on making a sphere in blender, exporting it to a .obj, and make it bounce in xcode? Ive been trying to make one but can’t seem to get it to work

  182. Daniele says:

    Hello,

    i had a model that was not triangulated. I imported the .obj in Blender and re-exported it to .obj with the “triangulate” option on. After that operation the model showed correctly but texture looked messed up. I tried to figure out what was happening looking at the script. I noticed that you flip the v coordinate when parsing the file. In my case that was a problem (don’t know why you were doing such a thing but i’m sure you have your reasons). I solved the issue by changing line 358:

    $y = 1 – $tokens[2];

    to

    $y = $tokens[2];

    Now everything renders correctly. Note that i had the same problem with your banana.h file (i used it “as-is” without importing/exporting with blender). I’m using these models with Qualcomm AR and the standard glDrawArrays call.

    Anyway great tool and thanks for making it free!

    DM

  183. Joseph Pan says:

    Really nice script. Thanks alot! I found that I have to add a line
    [code]glEnableClientState(GL_VERTEX_ARRAY);[/code]
    before I call glDrawArrays function. Otherwise I can see nothing on the screen.

  184. Heiko says:

    Just to tell you thank you

  185. Michael M says:

    Hi… would it be possible to publish the whole XCode project you used for the example above. I am having problems with the fact that the exported vertices seem to be normalised [0 ... 1] rather than hold their original values. I need to set up my display in a way that does not distort the objects.

    Thanks

  186. Shogo says:

    Hello…the script works well but there is a problem. I am using Visual Studio 2010. The exporter doesn’t write the decimal point when the number “doesn’t have one”. For example: the number 10.0f, your exporter writes it as 10f and VS2010 keeps giving me the error:

    syntax error : ‘bad suffix on number’

    As you can imagine it is quite annoying to go through all the vertices (that don’t have a decimal point) adding the decimal point so it compiles correctly.

    Is it possible that you could fix your exporter so it writes the numbers correctly with their decimal point.

    Eg.: write 10.0f instead of 10f.

  187. Shogo says:

    Sorry if my above comment doesn’t apply to the downloadable script. I’m refering to the online converter found here:
    http://www.jeffprod.com/obj2opengl.php?setlang=en

    Don’t know if that one is also mantained by you.

  188. Hey Shogo, struggling to find out what “F”s you were referring to, you already confirmed that you meant another script. Does the output of my script work for you? The float literals don’t have a “f” suffix so it might work for you. Can you confirm that?

  189. Tarun Karuturi says:

    This script works perfectly. You really are a lifesaver. Thanks a lot man!!!

  190. ALEX79 says:

    This is a very useful tool. Thanks very much!
    I’m a problem exporting object with this tool.
    I’m trying to obtain a smooth lightning effect on a solid with openGLES 2.0. I exported an .obj solid from blender and converted the obj file in C array of vertex and normal .Then I draw this data on my openGL ES app on iPhone. The problem is that the faces of the solid have a flat lightning (the same color for each face). I want a smooth effect without using per fragment lightning. I tried to increase the number of faces but with no results.
    Do you think that may is a problem on normal exporting?

  191. To do sth. light phong shading you have to write a specific shader.

  192. Kevin says:

    Do anyone know how to adapt the implementation to OpenGL 2.0? I think glVertexPointer(), glNormalPointer() and glTexCoordPointer() don’t work for 2.0. Xcode is complaining about those functions. Any ideas?

  193. Kevin, I am open to any improvements. Please file a pull request on GitHub if you made it work with OpenGL ES 2.

  194. Jayashree Panda says:

    It’s really too good and helped me a lot too.. But i want to extract color from object file.
    Can u pls mention how to modify the script.

  195. Vanshika says:

    Hi Heiko,

    Can we use python script for the same purpose??

    Thanks in advance.

  196. Sure, let me know once you have ported it to python and I’d be happy to share.

  197. Jayashree, have a look at the Wavefront OBJ Format specfication to understand materials but be warned: this script does not support materials at the moment. You not only have to modify the script, you have to think of a proper shader configuration for your OpenGL code as well.

  198. edadez says:

    Hi Heiko,
    thanks for share this.

    i import banana.h and set:
    glVertexPointer(3, GL_FLOAT, 0, bananaVerts);
    glNormalPointer(GL_FLOAT, 0, bananaNormals);
    glTexCoordPointer(2, GL_FLOAT, 0, bananaTexCoords);

    But this:
    “// draw data
    glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts); ”
    replace to this :
    “glDrawElements(GL_TRIANGLES, obj3D.numIndices, GL_UNSIGNED_SHORT, (const GLvoid*)obj3D.indices);”
    ??
    or just copy ?

    I ask you, because i try replace ‘teapot.h’ from QCAR sdk imageTarget example, but i dont see the banana :(

    Any idea ?
    thx for ‘u support

    Grettings for Chile,
    cya

  199. Hey edadez, I am not sure how your overall project looks like. Do you use OpenGL ES 1 on Objective-C?

  200. Jake says:

    What a fantastic script. You have just saved me so much time. Thanks so much for publishing it.

  201. Hugues says:

    Hi,

    Is there any recommendations and limits to know about loading/using 3D models on iOS? For example my first question would be about ‘size’ of the header file generated (and therefore level of details in the 3D model itself). Yesterday I tried this script for the first time, and the header file generated was about 25Mo. I did not have the time to load (try to load) this model yet, but I would love more information even before trying.

    Thanks for sharing!

  202. Deepak Senapati says:

    Hey Heiko, I am using eclipse with java to build an android project using opengl.
    I have to use a model which i drew using Blender 3d. I couldn’t find any software to do that, so i tried to extract the vertices and indices into arrays and draw them. The model which i got was very poor and doesn’t look like what i have made in Blender. there are no textures and other complications. its a simple model. Please help me out.

  203. Hey Hugues, as stated in one of my replies before: Those files will be compiled to binary data. Nevertheless, those models (and the amount of faces) appear pretty heavy to me. Did you benchmark anything meanwhile?

  204. Hey Deepak, I am not sure how I could help you with this. Even though I am glad you managed to use this script for your Android project I am not intending to do anything in that direction. Anyway, feel free to provide pull requests via GitHub. Good luck!

  205. figma says:

    Hello Heiko,

    thank you for the script it’s working very well. I’m just encountering some problems with an .obj file containg multiple objects/textures. As you pointed out the script only supports one object. I’ve been trying to find out how to create a texture like the banana texture for my object but it seems like I’m searching for the wrong key words as I was not able to find out what to do. Do you happen to know where I could find the required steps to create a .obj file with one object/texture from multiple objects?

  206. Hey figma, I am not aware of a simple tool to combine your textures. Often, this step is called “baking textures”. Hope this helps.

  207. Harsh Vardhan says:

    Hi Heiko,

    Thanks a lot for sharing the script. I have been stuck on the same thing for last 1 and half days, I try compiling your script with my triangulated 3dmodel.obj but I get this error:

    Illegal division by zero at ./obj2opengl.pl line 294.

    So I hard coded scalefac = 1 and commented out line 294. Then I tried ndk-build in ImageTarget folder after making changes in ImageTarget.cpp I get following in Terminal:

    Gdbserver : [arm-linux-androideabi-4.6] libs/armeabi/gdbserver
    Gdbsetup : libs/armeabi/gdb.setup
    Gdbserver : [arm-linux-androideabi-4.6] libs/armeabi-v7a/gdbserver
    Gdbsetup : libs/armeabi-v7a/gdb.setup
    Install : libImageTargets.so => libs/armeabi/libImageTargets.so
    Install : libQCAR.so => libs/armeabi/libQCAR.so
    Compile++ arm : ImageTargets <= ImageTargets.cpp
    In file included from jni/ImageTargets.cpp:45:0:
    jni/./posefour.h:33941:9: error: "vertices" is not a valid filename
    jni/./posefour.h:67851:9: error: "vertex" is not a valid filename
    jni/./posefour.h:135608:9: error: "faces" is not a valid filename
    jni/./posefour.h:169532:9: error: "vertices" is not a valid filename
    jni/./posefour.h:203442:9: error: "vertex" is not a valid filename
    jni/./posefour.h:271199:9: error: "faces" is not a valid filename
    In file included from jni/ImageTargets.cpp:15:0:
    /Users/harshvardhan/Documents/Work/app/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/jni.h:592:13: note: the mangling of 'va_list' has changed in GCC 4.4
    In file included from jni/ImageTargets.cpp:45:0:
    jni/./posefour.h:27:1: error: 'mtllib' was not declared in this scope
    jni/./posefour.h:27:8: error: expected '}' before 'posefour'
    jni/./posefour.h:27:8: error: expected ',' or ';' before 'posefour'
    jni/./posefour.h:135613:1: error: expected declaration before '}' token
    make: *** [obj/local/armeabi-v7a/objs-debug/ImageTargets/ImageTargets.o] Error 1

    Here link to my 3dModel Files:
    https://www.dropbox.com/sh/mz2ac79wnormm6d/zTHAem-y2W

    Thanks

  208. Hey Harsh, it seems you are suffering from this problem with your 3DS Max exporter. Anyway, I’ve updated the script to workaround negative indexes. Second, your file only has “CR” as linebreaks. Convert it to “LF” or “CR/LF” before running the script.

  209. Harsh Vardhan says:

    Thanks.

    I tried exporting the obj file with vertices and normal only, it still gives me the same .h file except that I am not getting any error on line 294.

    Should i detele gw_objexp.ini file in 3d Max..??

  210. Harsh, I have no idea regarding 3DS Max, but: with corrected line breaks (CR or CR/LF should work, see comment before) and the latest version of the script (download at GitHub, that now can handle negative indices) I got a header file without errors. Does this work for you?

  211. Tom Wang says:

    Hey Heiko,
    I found that the exported “*.h” file using “./obj2opengl.pl banana.obj” does not have vertex color informations.you said:
    “OBJ2OPENGL does the latter and acts as a converter from model files to C/C++ headers that describe vertices of the faces, normals and texture coordinates as simple arrays of floats.”
    so,how could I use vertex color information with “.obj” file.

  212. Harsh Vardhan says:

    Heiko I didn’t get any error in converting obj to h, but there still were invalid file reference error like:

    jni/./posefour.h:33941:9: error: “vertices” is not a valid filename

    jni/./posefour.h:67851:9: error: “vertex” is not a valid filename

    jni/./posefour.h:135608:9: error: “faces” is not a valid filename

    jni/./posefour.h:169532:9: error: “vertices” is not a valid filename

    jni/./posefour.h:203442:9: error: “vertex” is not a valid filename

    jni/./posefour.h:271199:9: error: “faces” is not a valid filename

    So I checked with my ads Max guy and he wasn’t converting the mesh into triangles. Once we did that it worked like charm..thanks for all your support. Really great help..:)

  213. Tom, the script does not handle material files. Nevertheless, you can use textures to color your mesh.

  214. Cassan Damien says:

    Hello,

    Thanks a lot for your script!
    I’m a beginner in xcode and opengl, trying to use the generated banana.h nto my iphone app.
    As the functions you use are deprecated, I’m trying to figure out what replaces them, well not so easy :)

    Bananas appear, but without any texture nor color.
    Here is my “drawInRect” code:

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, bananaVerts);

    glEnableVertexAttribArray(GLKVertexAttribNormal);
    glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 0, bananaNormals);

    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, bananaTexCoords);

    glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);

    glDisableVertexAttribArray(GLKVertexAttribPosition);
    glDisableVertexAttribArray(GLKVertexAttribNormal);
    glDisableVertexAttribArray(GLKVertexAttribPosition);

    Thanks a lot for your help!

    Damien

  215. Anil Unnikrishnan says:

    I’ve followed your steps to the word. I can load the obj but I cant get the texture to load.I’m getting a green banana on the screen without a texture.Here’s my code.

    - (void)drawView:(UIView *)theView
    {
    glColor4f(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glColor4f(0.0, 1.0, 0.0, 1.0);
    glTranslatef(-0.0, 0.0, -1.0);
    glRotatef(90.0,1.0,0.0,0.0);

    glVertexPointer(3, GL_FLOAT, 0, bananaVerts);
    glNormalPointer(GL_FLOAT, 0, bananaNormals);
    glTexCoordPointer(2, GL_FLOAT, 0, bananaTexCoords);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    }

    Please help.Thanks in advance.
    Anil

  216. Tuan Le says:

    I use OpenGL es 2.0, but i load wrong texture, i fixed it by replace this code in script, it is maybe useful for some one!
    find this code
    if ($line =~ /vt\s+.*/)
    {
    @tokens= split(‘ ‘, $line);
    $x = $tokens[1];
    $y = 1 – $tokens[2];
    $tx[$numTexture] = $x;
    $ty[$numTexture] = $y;

    $numTexture++;
    }
    replace $y = 1 – $tokens[2] -> $y = $tokens[2]

    sorry, i am not good at english

  217. Sky Wu says:

    Hello HEIKO BEHRENS
    I am SkyWu from taiwan. I am a student.
    We are working on QCAR educating program.
    We are using 3Dmax to make model, but we dont know how .obj file 2 .h file untill we find ur source.
    We might use ur website to teach other people how to .obj file 2 .h file.
    Could we use ur website in papere?
    Give me a hand.
    By Sky

  218. I am not sure if I understood you correctly, Sky. You are welcome to refer to this blog post in any publication if that is what you were asking for.

  219. Sky Wu says:

    YES I WANT to this blog post in any publication
    COULD I?

  220. Sure, that’s what I meant. If you could provide a link once it’s published I’d be more than happy. Good luck!

  221. Sky Wu says:

    HI HEIKO BEHRENS
    Could u teach me how to use .pl to change my .obj
    I am using Win7
    I dont know how to use it

Leave a Reply