1 // obj.cxx -- routines to handle "sorta" WaveFront .obj format files.
3 // Written by Curtis Olson, started October 1997.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #ifdef FG_MATH_EXCEPTION_CLASH
35 // #if defined ( __sun__ )
36 // extern "C" void *memmove(void *, const void *, size_t);
37 // extern "C" void *memset(void *, int, size_t);
40 #include <simgear/compiler.h>
44 #include <vector> // STL
45 #include <ctype.h> // isdigit()
47 #include <simgear/constants.h>
48 #include <simgear/debug/logstream.hxx>
49 #include <simgear/math/point3d.hxx>
50 #include <simgear/math/polar3d.hxx>
51 #include <simgear/math/sg_geodesy.hxx>
52 #include <simgear/math/sg_random.h>
53 #include <simgear/misc/fgstream.hxx>
54 #include <simgear/misc/stopwatch.hxx>
55 #include <simgear/misc/texcoord.hxx>
57 #include <Main/globals.hxx>
58 #include <Scenery/tileentry.hxx>
67 typedef vector < int > int_list;
68 typedef int_list::iterator int_list_iterator;
69 typedef int_list::const_iterator int_point_list_iterator;
72 static double normals[FG_MAX_NODES][3];
73 static double tex_coords[FG_MAX_NODES*3][3];
77 // given three points defining a triangle, calculate the normal
78 static void calc_normal(Point3D p1, Point3D p2,
79 Point3D p3, sgVec3 normal)
83 v1[0] = p2[0] - p1[0]; v1[1] = p2[1] - p1[1]; v1[2] = p2[2] - p1[2];
84 v2[0] = p3[0] - p1[0]; v2[1] = p3[1] - p1[1]; v2[2] = p3[2] - p1[2];
86 sgVectorProductVec3( normal, v1, v2 );
87 sgNormalizeVec3( normal );
89 // fgPrintf( FG_TERRAIN, FG_DEBUG, " Normal = %.2f %.2f %.2f\n",
90 // normal[0], normal[1], normal[2]);
95 #define FG_TEX_CONSTANT 69.0
97 // Calculate texture coordinates for a given point.
98 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
101 // double tmplon, tmplat;
103 // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
104 // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
106 cp = Point3D( node[0] + ref.x(),
110 pp = sgCartToPolar3d(cp);
112 // tmplon = pp.lon() * RAD_TO_DEG;
113 // tmplat = pp.lat() * RAD_TO_DEG;
114 // cout << tmplon << " " << tmplat << endl;
116 pp.setx( fmod(RAD_TO_DEG * FG_TEX_CONSTANT * pp.x(), 11.0) );
117 pp.sety( fmod(RAD_TO_DEG * FG_TEX_CONSTANT * pp.y(), 11.0) );
119 if ( pp.x() < 0.0 ) {
120 pp.setx( pp.x() + 11.0 );
123 if ( pp.y() < 0.0 ) {
124 pp.sety( pp.y() + 11.0 );
127 // cout << pp << endl;
133 // Generate a generic ocean tile on the fly
134 ssgBranch *fgGenTile( const string& path, FGTileEntry *t) {
137 ssgSimpleState *state = NULL;
139 ssgBranch *tile = new ssgBranch () ;
140 tile -> setName ( (char *)path.c_str() ) ;
142 double tex_width = 1000.0;
143 // double tex_height;
145 // find Ocean material in the properties list
146 newmat = material_lib.find( "Ocean" );
147 if ( newmat != NULL ) {
148 // set the texture width and height values for this
150 tex_width = newmat->get_xsize();
151 // tex_height = newmat->get_ysize();
154 state = newmat->get_state();
156 FG_LOG( FG_TERRAIN, FG_ALERT,
157 "Ack! unknown usemtl name = " << "Ocean"
161 // Calculate center point
162 SGBucket b = t->tile_bucket;
163 double clon = b.get_center_lon();
164 double clat = b.get_center_lat();
165 double height = b.get_height();
166 double width = b.get_width();
168 Point3D center = sgGeodToCart(Point3D(clon*DEG_TO_RAD,clat*DEG_TO_RAD,0.0));
170 // cout << "center = " << center << endl;;
172 // Caculate corner vertices
174 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
175 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
176 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
177 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
181 for ( i = 0; i < 4; ++i ) {
182 rad[i] = Point3D( geod[i].x() * DEG_TO_RAD, geod[i].y() * DEG_TO_RAD,
186 Point3D cart[4], rel[4];
188 for ( i = 0; i < 4; ++i ) {
189 cart[i] = sgGeodToCart(rad[i]);
190 rel[i] = cart[i] - center;
191 t->nodes.push_back( rel[i] );
192 // cout << "corner " << i << " = " << cart[i] << endl;
197 // Calculate bounding radius
198 t->bounding_radius = center.distance3D( cart[0] );
199 // cout << "bounding radius = " << t->bounding_radius << endl;
203 for ( i = 0; i < 4; ++i ) {
204 normals[i] = cart[i];
205 double length = normals[i].distance3D( Point3D(0.0) );
206 normals[i] /= length;
207 // cout << "normal = " << normals[i] << endl;
210 // Calculate texture coordinates
211 point_list geod_nodes;
213 for ( i = 0; i < 4; ++i ) {
214 geod_nodes.push_back( geod[i] );
218 for ( i = 0; i < 4; ++i ) {
219 rectangle.push_back( i );
221 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
222 1000.0 / tex_width );
224 // Allocate ssg structure
225 ssgVertexArray *vl = new ssgVertexArray( 4 );
226 ssgNormalArray *nl = new ssgNormalArray( 4 );
227 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
228 ssgColourArray *cl = new ssgColourArray( 1 );
231 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
234 // sgVec3 *vtlist = new sgVec3 [ 4 ];
235 // t->vec3_ptrs.push_back( vtlist );
236 // sgVec3 *vnlist = new sgVec3 [ 4 ];
237 // t->vec3_ptrs.push_back( vnlist );
238 // sgVec2 *tclist = new sgVec2 [ 4 ];
239 // t->vec2_ptrs.push_back( tclist );
243 for ( i = 0; i < 4; ++i ) {
245 rel[i].x(), rel[i].y(), rel[i].z() );
249 normals[i].x(), normals[i].y(), normals[i].z() );
252 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
257 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
259 leaf->setState( state );
261 tile->addKid( leaf );
262 // if ( globals->get_options()->get_clouds() ) {
263 // fgGenCloudTile(path, t, tile);
270 static float fgTriArea( sgVec3 p0, sgVec3 p1, sgVec3 p2 ) {
272 From comp.graph.algorithms FAQ
273 2A(P) = abs(N.(sum_{i=0}^{n-1}(v_i x v_{i+1})))
279 sgMakeNormal( norm, p0, p1, p2 );
286 for( int i=0; i<3; i++ ) {
288 sum[0] += (vv[i][1] * vv[ii][2] - vv[i][2] * vv[ii][1]) ;
289 sum[1] += (vv[i][2] * vv[ii][0] - vv[i][0] * vv[ii][2]) ;
290 sum[2] += (vv[i][0] * vv[ii][1] - vv[i][1] * vv[ii][0]) ;
293 return( sgAbs(sgScalarProductVec3( norm, sum )) * SG_HALF );
298 // this works too, but Norman claims fgTriArea() is more efficient :-)
299 static double triangle_area_3d( float *p1, float *p2, float *p3 ) {
300 // Heron's formula: A^2 = s(s-a)(s-b)(s-c) where A is the area,
301 // a,b,c are the side lengths, s=(a+b+c)/2. In R^3 you can compute
302 // the lengths of the sides with the distance formula, of course.
304 double a = sgDistanceVec3( p1, p2 );
305 double b = sgDistanceVec3( p2, p3 );
306 double c = sgDistanceVec3( p3, p1 );
308 double s = (a + b + c) / 2.0;
310 return sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
315 static void random_pt_inside_tri( float *res,
316 float *n1, float *n2, float *n3 )
320 double a = sg_random();
321 double b = sg_random();
326 double c = 1 - a - b;
328 sgScaleVec3( p1, n1, a );
329 sgScaleVec3( p2, n2, b );
330 sgScaleVec3( p3, n3, c );
332 sgAddVec3( res, p1, p2 );
333 sgAddVec3( res, p3 );
337 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
339 int num = leaf->getNumTriangles();
341 short int n1, n2, n3;
345 // generate a repeatable random seed
346 p1 = leaf->getVertex( 0 );
347 unsigned int *seed = (unsigned int *)p1;
350 for ( int i = 0; i < num; ++i ) {
351 leaf->getTriangle( i, &n1, &n2, &n3 );
352 p1 = leaf->getVertex(n1);
353 p2 = leaf->getVertex(n2);
354 p3 = leaf->getVertex(n3);
355 double area = fgTriArea( p1, p2, p3 );
356 double num = area / factor;
358 // generate a light point for each unit of area
359 while ( num > 1.0 ) {
360 random_pt_inside_tri( result, p1, p2, p3 );
361 lights->add( result );
364 // for partial units of area, use a zombie door method to
365 // create the proper random chance of a light being created
368 if ( sg_random() <= num ) {
369 // a zombie made it through our door
370 random_pt_inside_tri( result, p1, p2, p3 );
371 lights->add( result );
380 ssgBranch *fgObjLoad( const string& path, FGTileEntry *t,
381 ssgVertexArray *lights, const bool is_base)
383 FGNewMat *newmat = NULL;
387 // sgVec3 approx_normal;
388 // double normal[3], scale = 0.0;
389 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
390 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
391 // GLint display_list = 0;
393 bool in_faces = false;
394 int vncount, vtcount;
395 int n1 = 0, n2 = 0, n3 = 0;
397 // int last1 = 0, last2 = 0;
402 double scenery_version = 0.0;
403 double tex_width = 1000.0, tex_height = 1000.0;
404 bool shared_done = false;
405 int_list fan_vertices;
406 int_list fan_tex_coords;
408 ssgSimpleState *state = NULL;
409 sgVec3 *vtlist, *vnlist;
412 ssgBranch *tile = new ssgBranch () ;
414 tile -> setName ( (char *)path.c_str() ) ;
416 // Attempt to open "path.gz" or "path"
417 fg_gzifstream in( path );
418 if ( ! in.is_open() ) {
419 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << path );
420 FG_LOG( FG_TERRAIN, FG_ALERT, "default to ocean tile: " << path );
422 return fgGenTile( path, t );
425 shading = globals->get_options()->get_shading();
433 t->bounding_radius = 0.0;
440 // ignore initial comments and blank lines. (priming the pump)
441 // in >> skipcomment;
448 while ( in.get(c) && c != '\0' ) {
451 while ( ! in.eof() ) {
454 #if defined( macintosh ) || defined( _MSC_VER )
460 if ( in.get( c ) && c == '#' ) {
461 // process a comment line
463 // getline( in, line );
464 // cout << "comment = " << line << endl;
468 if ( token == "Version" ) {
469 // read scenery versions number
470 in >> scenery_version;
471 // cout << "scenery_version = " << scenery_version << endl;
472 if ( scenery_version > 0.4 ) {
473 FG_LOG( FG_TERRAIN, FG_ALERT,
474 "\nYou are attempting to load a tile format that\n"
475 << "is newer than this version of flightgear can\n"
476 << "handle. You should upgrade your copy of\n"
477 << "FlightGear to the newest version. For\n"
478 << "details, please see:\n"
479 << "\n http://www.flightgear.org\n" );
482 } else if ( token == "gbs" ) {
483 // reference point (center offset)
485 in >> t->center >> t->bounding_radius;
489 in >> junk1 >> junk2;
492 // cout << "center = " << center
493 // << " radius = " << t->bounding_radius << endl;
494 } else if ( token == "bs" ) {
495 // reference point (center offset)
499 in >> junk1 >> junk2;
500 } else if ( token == "usemtl" ) {
501 // material property specification
503 // if first usemtl with shared_done = false, then set
504 // shared_done true and build the ssg shared lists
505 if ( ! shared_done ) {
507 if ( (int)nodes.size() != vncount ) {
508 FG_LOG( FG_TERRAIN, FG_ALERT,
509 "Tile has mismatched nodes = " << nodes.size()
510 << " and normals = " << vncount << " : "
516 vtlist = new sgVec3 [ nodes.size() ];
517 t->vec3_ptrs.push_back( vtlist );
518 vnlist = new sgVec3 [ vncount ];
519 t->vec3_ptrs.push_back( vnlist );
520 tclist = new sgVec2 [ vtcount ];
521 t->vec2_ptrs.push_back( tclist );
523 for ( i = 0; i < (int)nodes.size(); ++i ) {
524 sgSetVec3( vtlist[i],
525 nodes[i][0], nodes[i][1], nodes[i][2] );
527 for ( i = 0; i < vncount; ++i ) {
528 sgSetVec3( vnlist[i],
533 for ( i = 0; i < vtcount; ++i ) {
534 sgSetVec2( tclist[i],
540 // display_list = xglGenLists(1);
541 // xglNewList(display_list, GL_COMPILE);
542 // printf("xglGenLists(); xglNewList();\n");
545 // scan the material line
548 // find this material in the properties list
550 newmat = material_lib.find( material );
551 if ( newmat == NULL ) {
552 // see if this is an on the fly texture
554 int pos = file.rfind( "/" );
555 file = file.substr( 0, pos );
556 cout << "current file = " << file << endl;
559 cout << "current file = " << file << endl;
560 if ( ! material_lib.add_item( file ) ) {
561 FG_LOG( FG_TERRAIN, FG_ALERT,
562 "Ack! unknown usemtl name = " << material
565 // locate our newly created material
566 newmat = material_lib.find( material );
567 if ( newmat == NULL ) {
568 FG_LOG( FG_TERRAIN, FG_ALERT,
569 "Ack! bad on the fly materia create = "
570 << material << " in " << path );
575 if ( newmat != NULL ) {
576 // set the texture width and height values for this
578 tex_width = newmat->get_xsize();
579 tex_height = newmat->get_ysize();
580 state = newmat->get_state();
581 coverage = newmat->get_light_coverage();
582 // cout << "(w) = " << tex_width << " (h) = "
583 // << tex_width << endl;
588 // unknown comment, just gobble the input until the
598 // cout << "token = " << token << endl;
600 if ( token == "vn" ) {
602 if ( vncount < FG_MAX_NODES ) {
603 in >> normals[vncount][0]
604 >> normals[vncount][1]
605 >> normals[vncount][2];
608 FG_LOG( FG_TERRAIN, FG_ALERT,
609 "Read too many vertex normals in " << path
610 << " ... dying :-(" );
613 } else if ( token == "vt" ) {
614 // vertex texture coordinate
615 if ( vtcount < FG_MAX_NODES*3 ) {
616 in >> tex_coords[vtcount][0]
617 >> tex_coords[vtcount][1];
620 FG_LOG( FG_TERRAIN, FG_ALERT,
621 "Read too many vertex texture coords in " << path
626 } else if ( token == "v" ) {
628 if ( t->ncount < FG_MAX_NODES ) {
629 /* in >> nodes[t->ncount][0]
630 >> nodes[t->ncount][1]
631 >> nodes[t->ncount][2]; */
633 nodes.push_back(node);
638 FG_LOG( FG_TERRAIN, FG_ALERT,
639 "Read too many nodes in " << path
640 << " ... dying :-(");
643 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
644 // triangle fan, strip, or individual face
645 // FG_LOG( FG_TERRAIN, FG_INFO, "new fan or strip");
647 fan_vertices.clear();
648 fan_tex_coords.clear();
651 // xglBegin(GL_TRIANGLE_FAN);
654 fan_vertices.push_back( n1 );
655 // xglNormal3dv(normals[n1]);
656 if ( in.get( c ) && c == '/' ) {
658 fan_tex_coords.push_back( tex );
659 if ( scenery_version >= 0.4 ) {
660 if ( tex_width > 0 ) {
661 tclist[tex][0] *= (1000.0 / tex_width);
663 if ( tex_height > 0 ) {
664 tclist[tex][1] *= (1000.0 / tex_height);
667 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
668 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
671 pp = local_calc_tex_coords(nodes[n1], center);
673 // xglTexCoord2f(pp.x(), pp.y());
674 // xglVertex3dv(nodes[n1].get_n());
677 fan_vertices.push_back( n2 );
678 // xglNormal3dv(normals[n2]);
679 if ( in.get( c ) && c == '/' ) {
681 fan_tex_coords.push_back( tex );
682 if ( scenery_version >= 0.4 ) {
683 if ( tex_width > 0 ) {
684 tclist[tex][0] *= (1000.0 / tex_width);
686 if ( tex_height > 0 ) {
687 tclist[tex][1] *= (1000.0 / tex_height);
690 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
691 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
694 pp = local_calc_tex_coords(nodes[n2], center);
696 // xglTexCoord2f(pp.x(), pp.y());
697 // xglVertex3dv(nodes[n2].get_n());
699 // read all subsequent numbers until next thing isn't a number
701 #if defined( macintosh ) || defined( _MSC_VER )
710 if ( ! isdigit(c) || in.eof() ) {
715 fan_vertices.push_back( n3 );
716 // cout << " triangle = "
717 // << n1 << "," << n2 << "," << n3
719 // xglNormal3dv(normals[n3]);
720 if ( in.get( c ) && c == '/' ) {
722 fan_tex_coords.push_back( tex );
723 if ( scenery_version >= 0.4 ) {
724 if ( tex_width > 0 ) {
725 tclist[tex][0] *= (1000.0 / tex_width);
727 if ( tex_height > 0 ) {
728 tclist[tex][1] *= (1000.0 / tex_height);
731 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
732 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
735 pp = local_calc_tex_coords(nodes[n3], center);
737 // xglTexCoord2f(pp.x(), pp.y());
738 // xglVertex3dv(nodes[n3].get_n());
740 if ( (token == "tf") || (token == "f") ) {
753 // build the ssg entity
754 int size = (int)fan_vertices.size();
755 ssgVertexArray *vl = new ssgVertexArray( size );
756 ssgNormalArray *nl = new ssgNormalArray( size );
757 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
758 ssgColourArray *cl = new ssgColourArray( 1 );
761 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
766 for ( i = 0; i < size; ++i ) {
767 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
770 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
773 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
777 ssgLeaf *leaf = NULL;
778 if ( token == "tf" ) {
781 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
782 } else if ( token == "ts" ) {
785 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
786 } else if ( token == "f" ) {
789 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
791 // leaf->makeDList();
792 leaf->setState( state );
794 tile->addKid( leaf );
797 if ( coverage > 0.0 ) {
798 if ( coverage < 10000.0 ) {
799 FG_LOG(FG_INPUT, FG_ALERT, "Light coverage is "
800 << coverage << ", pushing up to 10000");
803 gen_random_surface_points(leaf, lights, coverage);
805 // // generate lighting
806 // if ( material == "Urban" || material == "BuiltUpCover" ) {
807 // gen_random_surface_points( leaf, lights, 100000.0 );
808 // } else if ( material == "EvergreenBroadCover" ||
809 // material == "Default" || material == "Island" ||
810 // material == "SomeSort" ||
811 // material == "DeciduousBroadCover" ||
812 // material == "EvergreenNeedleCover" ||
813 // material == "DeciduousNeedleCover" ) {
814 // gen_random_surface_points( leaf, lights, 10000000.0 );
815 // } else if ( material == "Road") {
816 // gen_random_surface_points( leaf, lights, 10000.0);
817 // } else if ( material == "MixedForestCover" ) {
818 // gen_random_surface_points( leaf, lights, 5000000.0 );
819 // } else if ( material == "WoodedTundraCover" ||
820 // material == "BareTundraCover" ||
821 // material == "HerbTundraCover" ||
822 // material == "MixedTundraCover" ||
823 // material == "Marsh" ||
824 // material == "HerbWetlandCover" ||
825 // material == "WoodedWetlandCover" ) {
826 // gen_random_surface_points( leaf, lights, 20000000.0 );
827 // } else if ( material == "ShrubCover" ||
828 // material == "ShrubGrassCover" ) {
829 // gen_random_surface_points( leaf, lights, 4000000.0 );
830 // } else if ( material == "GrassCover" ||
831 // material == "SavannaCover" ) {
832 // gen_random_surface_points( leaf, lights, 4000000.0 );
833 // } else if ( material == "MixedCropPastureCover" ||
834 // material == "IrrCropPastureCover" ||
835 // material == "DryCropPastureCover" ||
836 // material == "CropGrassCover" ||
837 // material == "CropWoodCover" ) {
838 // gen_random_surface_points( leaf, lights, 2000000.0 );
842 FG_LOG( FG_TERRAIN, FG_WARN, "Unknown token in "
843 << path << " = " << token );
846 // eat white space before start of while loop so if we are
847 // done with useful input it is noticed before hand.
848 #if defined( macintosh ) || defined( _MSC_VER )
861 FG_LOG( FG_TERRAIN, FG_DEBUG,
862 "Loaded " << path << " in "
863 << stopwatch.elapsedSeconds() << " seconds" );
865 // Generate a cloud layer above the tiles
866 // if ( globals->get_options()->get_clouds() ) {
867 // fgGenCloudTile(path, t, tile);