Alireza Parvizimosaed Alireza Parvizimosaed - 4 months ago 23
C++ Question

How to merge two .obj files after texture mapping process?

After applying texture on 3D mesh, three files (including a .obj, .mtl and an atlas file) are generated. I have mapped textures on 2 objects and now I want to merge these objects together, but I do not know how to merge their files. Is there any method(not non free tool)?

Answer

The naive file merging for single object wavefront obj files is relatively easy:

  1. read first files into memory

    remember the number of entries of each table

  2. append the second file into memory (except faces)

  3. append faces of the second file into memory

    This is the only stuff that need to change a bit. All the indexes are from 1 so you need to add the size of each table from previous file to it. For example if first obj got 10 lines starting with v that means after appending the second obj will start referencing its points from 11 instead. so take each vertex index and add the size to it.

    The same goes for any info you got like normals, texture coords or what ever.

  4. save the whole thing as single obj file

Sorry I do not use the material extensions so I do not know the format and if any changes are needed inside mtl file too (but I do not think so).

If you want to have also the mesh updated (removing the invisible intersected part) then you need to use some geometry approach (not trivial problem).

Just to be sure here small example...

File1:

v -1.0 -1.0 -1.0 
v +1.0 -1.0 -1.0 
v +1.0 +1.0 -1.0 
v -1.0 +1.0 -1.0 
v -1.0 -1.0 +1.0 
v +1.0 -1.0 +1.0 
v +1.0 +1.0 +1.0 
v -1.0 +1.0 +1.0 

f 1 2 3 4 
f 5 6 7 8 
f 1 2 6 5 
f 2 3 7 6 
f 3 4 8 7 
f 4 1 5 8 

File2:

v -1.0 -1.0 +1.0 
v +1.0 -1.0 +1.0 
v +1.0 +1.0 +1.0 
v -1.0 +1.0 +1.0 
v -2.0 -2.0 +2.0 
v +2.0 -2.0 +2.0 
v +2.0 +2.0 +2.0 
v -2.0 +2.0 +2.0 

f 1 2 3 4 
f 5 6 7 8 
f 1 2 6 5 
f 2 3 7 6 
f 3 4 8 7 
f 4 1 5 8 

Merged:

v -1.0 -1.0 -1.0 
v +1.0 -1.0 -1.0 
v +1.0 +1.0 -1.0 
v -1.0 +1.0 -1.0 
v -1.0 -1.0 +1.0 
v +1.0 -1.0 +1.0 
v +1.0 +1.0 +1.0 
v -1.0 +1.0 +1.0 

v -1.0 -1.0 +1.0 
v +1.0 -1.0 +1.0 
v +1.0 +1.0 +1.0 
v -1.0 +1.0 +1.0 
v -2.0 -2.0 +2.0 
v +2.0 -2.0 +2.0 
v +2.0 +2.0 +2.0 
v -2.0 +2.0 +2.0 

f 1 2 3 4 
f 5 6 7 8 
f 1 2 6 5 
f 2 3 7 6 
f 3 4 8 7 
f 4 1 5 8 

f  9 10 11 12 
f 13 14 15 16 
f  9 10 14 13 
f 10 11 15 14 
f 11 12 16 15 
f 12  9 13 16

File1 has 8 vertexes so each vertex index in f from File2 is increased by 8. I did the whole example manually (including File1,2) so hope I did not make some silly mistake but the previews are OK so looks like not the case.

preview

If you want to eliminate duplicate entries (for space and speed) then you need to have reindexing table for each table and use it instead of just adding...