@@ -209,6 +209,9 @@ bool LoadObjAndConvert(float bmin[3], float bmax[3],
209209 printf (" # of materials = %d\n " , (int )materials.size ());
210210 printf (" # of shapes = %d\n " , (int )shapes.size ());
211211
212+ // Append `default` material
213+ materials.push_back (tinyobj::material_t ());
214+
212215 // Load diffuse textures
213216 {
214217 for (size_t m = 0 ; m < materials.size (); m++) {
@@ -248,24 +251,23 @@ bool LoadObjAndConvert(float bmin[3], float bmax[3],
248251
249252 {
250253 for (size_t s = 0 ; s < shapes.size (); s++) {
251- size_t current_material_id = 0 ;
252- if (shapes[s].mesh .material_ids .size () > 0 && shapes[s].mesh .material_ids .size () > s) {
253- // Base case
254- current_material_id = shapes[s].mesh .material_ids [s];
255- }
256254 DrawObject o;
257255 std::vector<float > vb; // pos(3float), normal(3float), color(3float)
258256 for (size_t f = 0 ; f < shapes[s].mesh .indices .size () / 3 ; f++) {
259257 tinyobj::index_t idx0 = shapes[s].mesh .indices [3 * f + 0 ];
260258 tinyobj::index_t idx1 = shapes[s].mesh .indices [3 * f + 1 ];
261259 tinyobj::index_t idx2 = shapes[s].mesh .indices [3 * f + 2 ];
262260
263- current_material_id = shapes[s].mesh .material_ids [f];
261+ int current_material_id = shapes[s].mesh .material_ids [f];
264262
265- if (current_material_id >= materials.size ()) {
266- std::cerr << " Invalid material index: " << current_material_id << std::endl;
263+ if ((current_material_id < 0 ) || (current_material_id >= static_cast <int >(materials.size ()))) {
264+ // Invaid material ID. Use default material.
265+ current_material_id = materials.size () - 1 ; // Default material is added to the last item in `materials`.
267266 }
268-
267+ // if (current_material_id >= materials.size()) {
268+ // std::cerr << "Invalid material index: " << current_material_id << std::endl;
269+ // }
270+ //
269271 float diffuse[3 ];
270272 for (size_t i = 0 ; i < 3 ; i++) {
271273 diffuse[i] = materials[current_material_id].diffuse [i];
@@ -364,7 +366,15 @@ bool LoadObjAndConvert(float bmin[3], float bmax[3],
364366
365367 o.vb = 0 ;
366368 o.numTriangles = 0 ;
367- o.material_id = current_material_id;
369+
370+ // OpenGL viewer does not support texturing with per-face material.
371+ if (shapes[s].mesh .material_ids .size () > 0 && shapes[s].mesh .material_ids .size () > s) {
372+ // Base case
373+ o.material_id = shapes[s].mesh .material_ids [s];
374+ } else {
375+ o.material_id = materials.size () - 1 ; // = ID for default material.
376+ }
377+
368378 if (vb.size () > 0 ) {
369379 glGenBuffers (1 , &o.vb );
370380 glBindBuffer (GL_ARRAY_BUFFER, o.vb );
0 commit comments