Texture Mapping not working with OBJ/MTL

Hi, I am a beginner in Three. Js. I have a MTL file like the following
newmtl unposedgament
ka 0.329412 0.223529 0.027451
kd 0.780392 0.568627 0.113725
ks 0.992157 0.941176 0.807843
illum 0
map_Ka unposedgament.jpg
map_Kd unposedgament.jpg
map_Ks unposedgament.jpg

But the problem is when I try meshlabjs.net it shows without texture but with depths.

But in three.js its just black no depth no texture just black. Someone told me its a material problem and some materials work and some dont

Can you tell me how to change the material of obj file and how to solve the texture problem.

Did you add a light to the scene?

1 Like

Yes the complete code is
import * as THREE from ‘…/build/three.module.js’;

		import { DDSLoader } from './jsm/loaders/DDSLoader.js';
		import { MTLLoader } from './jsm/loaders/MTLLoader.js';
		import { OBJLoader } from './jsm/loaders/OBJLoader.js';

		var container;

		var camera, scene, renderer;

		var mouseX = 0, mouseY = 0;

		var windowHalfX = window.innerWidth / 2;
		var windowHalfY = window.innerHeight / 2;


		init();
		animate();


		function init() {

			container = document.createElement( 'div' );
			document.body.appendChild( container );

			camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
			camera.position.z = 250;

			// scene

			scene = new THREE.Scene();

			var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
			scene.add( ambientLight );

			var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
			camera.add( pointLight );
			scene.add( camera );

			// model

			var onProgress = function ( xhr ) {

				if ( xhr.lengthComputable ) {

					var percentComplete = xhr.loaded / xhr.total * 100;
					console.log( Math.round( percentComplete, 2 ) + '% downloaded' );

				}

			};

			var onError = function () { };

			var manager = new THREE.LoadingManager();
			manager.addHandler( /\.dds$/i, new DDSLoader() );

			// comment in the following line and import TGALoader if your asset uses TGA textures
			// manager.addHandler( /\.tga$/i, new TGALoader() );

			new MTLLoader( manager )
				.setPath( 'models/obj/male02/' )
				.load( 'male02.mtl', function ( materials ) {

					materials.preload();

					new OBJLoader( manager )
						.setMaterials( materials )
						.setPath( 'models/obj/male02/' )
						.load( 'male02.obj', function ( object ) {

							object.position.y = - 95;
							scene.add( object );

						}, onProgress, onError );
                      new OBJLoader( manager )
						.setMaterials( materials )
						.setPath( 'models/obj/male02/' )
						.load( 'female02.obj', function ( object ) {

							object.position.y = - 95;
							scene.add( object );

						}, onProgress, onError );
				
				
				
				
				
				
				
				
				
				} );

@Lday Does it matter if i use the name unposedgament in .mtl file or i have to use only predefined names. I mean in the line newmtl unposedgament in my mtlfile number 1 line
can i use unposedgament name or I have to use something predefined

I super don’t know, I am also a newbie. The only other advice I would have would be that I have had an easier time exporting my mesh files as .glb so the mtl is packaged with the mesh. you can do this by opening your .obj in blender

1 Like

Same here. Hope someone helps. I have been trying it for hours but nothing yet

1 Like

What do you mean with “no depth”? Can you try to set the background color to white to check if you see at least the outline of the assets? You can do this like so:

scene.background = new THREE.Color( 0xffffff );

/cc

Yes I see the outline Its just means all I can see is black thing in the shape of the object I want but no texture and depths
By Depth I mean like you cant see for example the depth of your eye balls. Its just plain 2d black figure.

Then please share your entire code as a git repository so it’s possible to debug your app.

It goes like this
/initial code/
from github repo https://github.com/bharat-b7/MultiGarmentNetwork/dress_smpl.py


tgt_body = Mesh(smpl.r, smpl.f)

vert_inds = vert_indices[garment_type]
garment_unposed.set_texture_image(garment_tex)

and then i save garment_unposed.write_obj(“filename”) like this
garment_unposed = Mesh(filename=join(path, garment_type + ‘.obj’))

The commands Mesh and set_texture_image come from the github repo https://github.com/MPI-IS/mesh
Here if you go in mesh folder in the repo you will find mesh.py and texture.py

The write_obj is written as

if os.path.dirname(filename) and not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))

ff = -1 if flip_faces else 1

def write_face_to_obj_file(face_index, obj_file):
    vertex_indices = self.f[face_index][::ff] + 1

    if hasattr(self, 'ft'):
        texture_indices = self.ft[face_index][::ff] + 1
        if not hasattr(self, 'fn'):
            self.reset_face_normals()
        normal_indices = self.fn[face_index][::ff] + 1
        obj_file.write('f %d/%d/%d %d/%d/%d  %d/%d/%d\n' % tuple(
            np.array([vertex_indices, texture_indices, normal_indices]).T.flatten()))
    elif hasattr(self, 'fn'):
        normal_indices = self.fn[face_index][::ff] + 1
        obj_file.write('f %d//%d %d//%d  %d//%d\n' % tuple(np.array([vertex_indices, normal_indices]).T.flatten()))
    else:
        obj_file.write('f %d %d %d\n' % tuple(vertex_indices))

with open(filename, 'w') as fi:
    if comments is not None:
        if isinstance(comments, str):
            comments = [comments]
        for comment in comments:
            for line in comment.split("\n"):
                fi.write("# %s\n" % line)

    if hasattr(self, 'texture_filepath'):
        outfolder = os.path.dirname(filename)
        outbase = os.path.splitext(os.path.basename(filename))[0]
        mtlpath = outbase + '.mtl'
        fi.write('mtllib %s\n' % mtlpath)
        from shutil import copyfile
        texture_name = outbase + os.path.splitext(self.texture_filepath)[1]
        if os.path.abspath(self.texture_filepath) != os.path.abspath(os.path.join(outfolder, texture_name)):
            copyfile(self.texture_filepath, os.path.join(outfolder, texture_name))
        self.write_mtl(os.path.join(outfolder, mtlpath), outbase, texture_name)

    for r in self.v:
        fi.write('v %f %f %f\n' % (r[0], r[1], r[2]))

    if hasattr(self, 'fn') and hasattr(self, 'vn'):
        for r in self.vn:
            fi.write('vn %f %f %f\n' % (r[0], r[1], r[2]))

    if hasattr(self, 'ft'):
        for r in self.vt:
            if len(r) == 3:
                fi.write('vt %f %f %f\n' % (r[0], r[1], r[2]))
            else:
                fi.write('vt %f %f\n' % (r[0], r[1]))
    if hasattr(self, 'segm') and self.segm and not group:
        for p in self.segm.keys():
            fi.write('g %s\n' % p)
            for face_index in self.segm[p]:
                write_face_to_obj_file(face_index, fi)
    else:
        if hasattr(self, 'f'):
            for face_index in range(len(self.f)):
                write_face_to_obj_file(face_index, fi)

and write_mtl as
def write_mtl(self, path, material_name, texture_name):
“”“Material attribute file serialization”""
with open(path, ‘w’) as f:
f.write('newmtl s\n' material_name)
# copied from another obj, no idea about what it does
f.write(‘ka 0.329412 0.223529 0.027451\n’)
f.write(‘kd 0.780392 0.568627 0.113725\n’)
f.write(‘ks 0.992157 0.941176 0.807843\n’)
f.write(‘illum 0\n’)
f.write('map_Ka s\n' texture_name)
f.write('map_Kd s\n' texture_name)
f.write('map_Ks s\n' texture_name)

@Mugen87
my js code is
same from the examples of three.js for obj loader with mtl
just changed the the obj and mt files

Sorry, I don’t know what to do with your resources. I have asked you to share your code that shows the modified three.js example that loads your OBJ/MTL file.

@Mugen87
Thanks bro I got the issue end.
. The problem is that initially the material is
(Load obj from json)->Mesh material is MeshStandardMaterial->can change the texture by providing different texture map

(load obj from .obj file)->Mesh Material is MeshPhong-> When change to MeshStandard->nothing changes still black

any suggestions

@Mugen87 I am loading all the obj files in three.js editor