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 SG_MATH_EXCEPTION_CLASH
35 #include <simgear/compiler.h>
36 #include <simgear/sg_inlines.h>
37 #include <simgear/io/sg_binobj.hxx>
41 #include <vector> // STL
42 #include <ctype.h> // isdigit()
44 #include <simgear/constants.h>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/math/point3d.hxx>
47 #include <simgear/math/polar3d.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/math/vector.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/misc/stopwatch.hxx>
53 #include <simgear/misc/texcoord.hxx>
55 #include <Main/globals.hxx>
56 #include <Main/fg_props.hxx>
57 #include <Time/light.hxx>
58 #include <Scenery/tileentry.hxx>
68 typedef vector < int > int_list;
69 typedef int_list::iterator int_list_iterator;
70 typedef int_list::const_iterator int_point_list_iterator;
73 static double normals[FG_MAX_NODES][3];
74 static double tex_coords[FG_MAX_NODES*3][3];
77 runway_lights_predraw (ssgEntity * e)
79 // Turn on lights only at night
80 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
81 return int(sun_angle > 90.0);
85 #define FG_TEX_CONSTANT 69.0
87 // Calculate texture coordinates for a given point.
88 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
91 // double tmplon, tmplat;
93 // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
94 // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
96 cp = Point3D( node[0] + ref.x(),
100 pp = sgCartToPolar3d(cp);
102 // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
103 // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
104 // cout << tmplon << " " << tmplat << endl;
106 pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
107 pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
109 if ( pp.x() < 0.0 ) {
110 pp.setx( pp.x() + 11.0 );
113 if ( pp.y() < 0.0 ) {
114 pp.sety( pp.y() + 11.0 );
117 // cout << pp << endl;
123 // Generate an ocean tile
124 bool fgGenTile( const string& path, SGBucket b,
126 double *bounding_radius,
127 ssgBranch* geometry )
131 ssgSimpleState *state = NULL;
133 geometry -> setName ( (char *)path.c_str() ) ;
135 double tex_width = 1000.0;
136 // double tex_height;
138 // find Ocean material in the properties list
139 newmat = material_lib.find( "Ocean" );
140 if ( newmat != NULL ) {
141 // set the texture width and height values for this
143 tex_width = newmat->get_xsize();
144 // tex_height = newmat->get_ysize();
147 state = newmat->get_state();
149 SG_LOG( SG_TERRAIN, SG_ALERT,
150 "Ack! unknown usemtl name = " << "Ocean"
154 // Calculate center point
155 double clon = b.get_center_lon();
156 double clat = b.get_center_lat();
157 double height = b.get_height();
158 double width = b.get_width();
160 *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
161 clat*SGD_DEGREES_TO_RADIANS,
163 // cout << "center = " << center << endl;;
165 // Caculate corner vertices
167 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
168 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
169 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
170 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
174 for ( i = 0; i < 4; ++i ) {
175 rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
176 geod[i].y() * SGD_DEGREES_TO_RADIANS,
180 Point3D cart[4], rel[4];
181 for ( i = 0; i < 4; ++i ) {
182 cart[i] = sgGeodToCart(rad[i]);
183 rel[i] = cart[i] - *center;
184 // cout << "corner " << i << " = " << cart[i] << endl;
187 // Calculate bounding radius
188 *bounding_radius = center->distance3D( cart[0] );
189 // cout << "bounding radius = " << t->bounding_radius << endl;
193 for ( i = 0; i < 4; ++i ) {
194 double length = cart[i].distance3D( Point3D(0.0) );
195 normals[i] = cart[i] / length;
196 // cout << "normal = " << normals[i] << endl;
199 // Calculate texture coordinates
200 point_list geod_nodes;
202 geod_nodes.reserve(4);
205 rectangle.reserve(4);
206 for ( i = 0; i < 4; ++i ) {
207 geod_nodes.push_back( geod[i] );
208 rectangle.push_back( i );
210 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
211 1000.0 / tex_width );
213 // Allocate ssg structure
214 ssgVertexArray *vl = new ssgVertexArray( 4 );
215 ssgNormalArray *nl = new ssgNormalArray( 4 );
216 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
217 ssgColourArray *cl = new ssgColourArray( 1 );
220 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
223 // sgVec3 *vtlist = new sgVec3 [ 4 ];
224 // t->vec3_ptrs.push_back( vtlist );
225 // sgVec3 *vnlist = new sgVec3 [ 4 ];
226 // t->vec3_ptrs.push_back( vnlist );
227 // sgVec2 *tclist = new sgVec2 [ 4 ];
228 // t->vec2_ptrs.push_back( tclist );
232 for ( i = 0; i < 4; ++i ) {
234 rel[i].x(), rel[i].y(), rel[i].z() );
238 normals[i].x(), normals[i].y(), normals[i].z() );
241 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
246 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
248 leaf->setState( state );
250 geometry->addKid( leaf );
256 static void random_pt_inside_tri( float *res,
257 float *n1, float *n2, float *n3 )
259 double a = sg_random();
260 double b = sg_random();
265 double c = 1 - a - b;
267 res[0] = n1[0]*a + n2[0]*b + n3[0]*c;
268 res[1] = n1[1]*a + n2[1]*b + n3[1]*c;
269 res[2] = n1[2]*a + n2[2]*b + n3[2]*c;
273 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
275 int num = leaf->getNumTriangles();
277 short int n1, n2, n3;
281 // generate a repeatable random seed
282 p1 = leaf->getVertex( 0 );
283 unsigned int seed = (unsigned int)(fabs(p1[0]*100));
286 for ( int i = 0; i < num; ++i ) {
287 leaf->getTriangle( i, &n1, &n2, &n3 );
288 p1 = leaf->getVertex(n1);
289 p2 = leaf->getVertex(n2);
290 p3 = leaf->getVertex(n3);
291 double area = sgTriArea( p1, p2, p3 );
292 double num = area / factor;
294 // generate a light point for each unit of area
295 while ( num > 1.0 ) {
296 random_pt_inside_tri( result, p1, p2, p3 );
297 lights->add( result );
300 // for partial units of area, use a zombie door method to
301 // create the proper random chance of a light being created
304 if ( sg_random() <= num ) {
305 // a zombie made it through our door
306 random_pt_inside_tri( result, p1, p2, p3 );
307 lights->add( result );
316 * User data for populating leaves when they come in range.
318 class LeafUserData : public ssgBase
330 void setup_triangle( int i );
335 * User data for populating triangles when they come in range.
337 class TriUserData : public ssgBase
346 FGNewMat::ObjectGroup * object_group;
348 LeafUserData * leafData;
351 void fill_in_triangle();
352 void add_object_to_triangle(FGNewMat::Object * object);
353 void makeWorldMatrix (sgMat4 ROT, double hdg_deg );
358 * Fill in a triangle with randomly-placed objects.
360 * This method is invoked by a callback when the triangle is in range
361 * but not yet populated.
365 void TriUserData::fill_in_triangle ()
367 // generate a repeatable random seed
370 int nObjects = object_group->get_object_count();
372 for (int i = 0; i < nObjects; i++) {
373 FGNewMat::Object * object = object_group->get_object(i);
374 double num = area / object->get_coverage_m2();
376 // place an object each unit of area
377 while ( num > 1.0 ) {
378 add_object_to_triangle(object);
381 // for partial units of area, use a zombie door method to
382 // create the proper random chance of an object being created
385 if ( sg_random() <= num ) {
386 // a zombie made it through our door
387 add_object_to_triangle(object);
393 void TriUserData::add_object_to_triangle (FGNewMat::Object * object)
395 // Set up the random heading if required.
397 if (object->get_heading_type() == FGNewMat::Object::HEADING_RANDOM)
398 hdg_deg = sg_random() * 360;
401 makeWorldMatrix(mat, hdg_deg);
403 ssgTransform * pos = new ssgTransform;
404 pos->setTransform(mat);
405 pos->addKid(object->get_random_model());
409 void TriUserData::makeWorldMatrix (sgMat4 mat, double hdg_deg )
412 mat[0][0] = leafData->sin_lat * leafData->cos_lon;
413 mat[0][1] = leafData->sin_lat * leafData->sin_lon;
414 mat[0][2] = -leafData->cos_lat;
417 mat[1][0] = -leafData->sin_lon;
418 mat[1][1] = leafData->cos_lon;
422 float sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
423 float cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
424 mat[0][0] = cos_hdg * leafData->sin_lat * leafData->cos_lon - sin_hdg * leafData->sin_lon;
425 mat[0][1] = cos_hdg * leafData->sin_lat * leafData->sin_lon + sin_hdg * leafData->cos_lon;
426 mat[0][2] = -cos_hdg * leafData->cos_lat;
429 mat[1][0] = -sin_hdg * leafData->sin_lat * leafData->cos_lon - cos_hdg * leafData->sin_lon;
430 mat[1][1] = -sin_hdg * leafData->sin_lat * leafData->sin_lon + cos_hdg * leafData->cos_lon;
431 mat[1][2] = sin_hdg * leafData->cos_lat;
435 mat[2][0] = leafData->cos_lat * leafData->cos_lon;
436 mat[2][1] = leafData->cos_lat * leafData->sin_lon;
437 mat[2][2] = leafData->sin_lat;
440 // translate to random point in triangle
442 random_pt_inside_tri(result, p1, p2, p3);
443 sgSubVec3(mat[3], result, center);
449 * SSG callback for an in-range triangle of randomly-placed objects.
451 * This pretraversal callback is attached to a branch that is traversed
452 * only when a triangle is in range. If the triangle is not currently
453 * populated with randomly-placed objects, this callback will populate
456 * @param entity The entity to which the callback is attached (not used).
457 * @param mask The entity's traversal mask (not used).
458 * @return Always 1, to allow traversal and culling to continue.
461 tri_in_range_callback (ssgEntity * entity, int mask)
463 TriUserData * data = (TriUserData *)entity->getUserData();
464 if (!data->is_filled_in) {
465 data->fill_in_triangle();
466 data->is_filled_in = true;
473 * SSG callback for an out-of-range triangle of randomly-placed objects.
475 * This pretraversal callback is attached to a branch that is traversed
476 * only when a triangle is out of range. If the triangle is currently
477 * populated with randomly-placed objects, the objects will be removed.
480 * @param entity The entity to which the callback is attached (not used).
481 * @param mask The entity's traversal mask (not used).
482 * @return Always 0, to prevent any further traversal or culling.
485 tri_out_of_range_callback (ssgEntity * entity, int mask)
487 TriUserData * data = (TriUserData *)entity->getUserData();
488 if (data->is_filled_in) {
489 data->branch->removeAllKids();
490 data->is_filled_in = false;
497 * ssgEntity with a dummy bounding sphere, to fool culling.
499 * This forces the in-range and out-of-range branches to be visited
500 * when appropriate, even if they have no children. It's ugly, but
501 * it works and seems fairly efficient (since branches can still
502 * be culled when they're out of the view frustum).
504 class DummyBSphereEntity : public ssgEntity
507 DummyBSphereEntity (float radius)
509 bsphere.setCenter(0, 0, 0);
510 bsphere.setRadius(radius);
512 virtual ~DummyBSphereEntity () {}
513 virtual void recalcBSphere () { bsphere_is_invalid = false; }
514 virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
515 virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
516 virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
517 virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
522 * Calculate the bounding radius of a triangle from its center.
524 * @param center The triangle center.
525 * @param p1 The first point in the triangle.
526 * @param p2 The second point in the triangle.
527 * @param p3 The third point in the triangle.
528 * @return The greatest distance any point lies from the center.
531 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
533 return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
534 sgDistanceSquaredVec3(center, p2),
535 sgDistanceSquaredVec3(center, p3) ) );
540 * Set up a triangle for randomly-placed objects.
542 * No objects will be added unless the triangle comes into range.
546 void LeafUserData::setup_triangle (int i )
549 leaf->getTriangle(i, &n1, &n2, &n3);
551 float * p1 = leaf->getVertex(n1);
552 float * p2 = leaf->getVertex(n2);
553 float * p3 = leaf->getVertex(n3);
555 // Set up a single center point for LOD
558 (p1[0] + p2[0] + p3[0]) / 3.0,
559 (p1[1] + p2[1] + p3[1]) / 3.0,
560 (p1[2] + p2[2] + p3[2]) / 3.0);
561 double area = sgTriArea(p1, p2, p3);
563 // maximum radius of an object from center.
564 double bounding_radius = get_bounding_radius(center, p1, p2, p3);
566 // Set up a transformation to the center
567 // point, so that everything else can
568 // be specified relative to it.
569 ssgTransform * location = new ssgTransform;
571 sgMakeTransMat4(TRANS, center);
572 location->setTransform(TRANS);
573 branch->addKid(location);
575 // Iterate through all the object types.
576 int num_groups = mat->get_object_group_count();
577 for (int j = 0; j < num_groups; j++) {
578 // Look up the random object.
579 FGNewMat::ObjectGroup * group = mat->get_object_group(j);
581 // Set up the range selector for the entire
582 // triangle; note that we use the object
583 // range plus the bounding radius here, to
584 // allow for objects far from the center.
585 float ranges[] = { 0,
586 group->get_range_m() + bounding_radius,
588 ssgRangeSelector * lod = new ssgRangeSelector;
589 lod->setRanges(ranges, 3);
590 location->addKid(lod);
592 // Create the in-range and out-of-range
594 ssgBranch * in_range = new ssgBranch;
595 ssgBranch * out_of_range = new ssgBranch;
597 // Set up the user data for if/when
598 // the random objects in this triangle
600 TriUserData * data = new TriUserData;
601 data->is_filled_in = false;
605 sgCopyVec3 (data->center, center);
607 data->object_group = group;
608 data->branch = in_range;
609 data->leafData = this;
610 data->seed = (unsigned int)(p1[0] * j);
612 // Set up the in-range node.
613 in_range->setUserData(data);
614 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
615 tri_in_range_callback);
616 lod->addKid(in_range);
618 // Set up the out-of-range node.
619 out_of_range->setUserData(data);
620 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
621 tri_out_of_range_callback);
622 out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
623 lod->addKid(out_of_range);
628 * SSG callback for an in-range leaf of randomly-placed objects.
630 * This pretraversal callback is attached to a branch that is
631 * traversed only when a leaf is in range. If the leaf is not
632 * currently prepared to be populated with randomly-placed objects,
633 * this callback will prepare it (actual population is handled by
634 * the tri_in_range_callback for individual triangles).
636 * @param entity The entity to which the callback is attached (not used).
637 * @param mask The entity's traversal mask (not used).
638 * @return Always 1, to allow traversal and culling to continue.
641 leaf_in_range_callback (ssgEntity * entity, int mask)
643 LeafUserData * data = (LeafUserData *)entity->getUserData();
645 if (!data->is_filled_in) {
646 // Iterate through all the triangles
647 // and populate them.
648 int num_tris = data->leaf->getNumTriangles();
649 for ( int i = 0; i < num_tris; ++i ) {
650 data->setup_triangle(i);
652 data->is_filled_in = true;
659 * SSG callback for an out-of-range leaf of randomly-placed objects.
661 * This pretraversal callback is attached to a branch that is
662 * traversed only when a leaf is out of range. If the leaf is
663 * currently prepared to be populated with randomly-placed objects (or
664 * is actually populated), the objects will be removed.
666 * @param entity The entity to which the callback is attached (not used).
667 * @param mask The entity's traversal mask (not used).
668 * @return Always 0, to prevent any further traversal or culling.
671 leaf_out_of_range_callback (ssgEntity * entity, int mask)
673 LeafUserData * data = (LeafUserData *)entity->getUserData();
674 if (data->is_filled_in) {
675 data->branch->removeAllKids();
676 data->is_filled_in = false;
683 * Randomly place objects on a surface.
685 * The leaf node provides the geometry of the surface, while the
686 * material provides the objects and placement density. Latitude
687 * and longitude are required so that the objects can be rotated
688 * to the world-up vector. This function does not actually add
689 * any objects; instead, it attaches an ssgRangeSelector to the
690 * branch with callbacks to generate the objects when needed.
692 * @param leaf The surface where the objects should be placed.
693 * @param branch The branch that will hold the randomly-placed objects.
694 * @param center The center of the leaf in FlightGear coordinates.
695 * @param material_name The name of the surface's material.
698 gen_random_surface_objects (ssgLeaf *leaf,
701 const string &material_name)
703 // If the surface has no triangles, return
705 int num_tris = leaf->getNumTriangles();
709 // Get the material for this surface.
710 FGNewMat * mat = material_lib.find(material_name);
712 SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
716 // If the material has no randomly-placed
717 // objects, return now.
718 if (mat->get_object_group_count() < 1)
721 // Calculate the geodetic centre of
722 // the tile, for aligning automatic
724 double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
725 Point3D geoc = sgCartToPolar3d(*center);
726 lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
727 sgGeocToGeod(geoc.lat(), geoc.radius(),
728 &lat_rad, &alt_m, &sl_radius_m);
729 lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
732 // max random object range: 20000m
733 float ranges[] = { 0, 20000, 1000000 };
734 ssgRangeSelector * lod = new ssgRangeSelector;
735 lod->setRanges(ranges, 3);
738 // Create the in-range and out-of-range
740 ssgBranch * in_range = new ssgBranch;
741 ssgBranch * out_of_range = new ssgBranch;
742 lod->addKid(in_range);
743 lod->addKid(out_of_range);
745 LeafUserData * data = new LeafUserData;
746 data->is_filled_in = false;
749 data->branch = in_range;
750 data->sin_lat = sin(lat_deg * SGD_DEGREES_TO_RADIANS);
751 data->cos_lat = cos(lat_deg * SGD_DEGREES_TO_RADIANS);
752 data->sin_lon = sin(lon_deg * SGD_DEGREES_TO_RADIANS);
753 data->cos_lon = cos(lon_deg * SGD_DEGREES_TO_RADIANS);
755 in_range->setUserData(data);
756 in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
757 out_of_range->setUserData(data);
758 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
759 leaf_out_of_range_callback);
761 ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
766 ////////////////////////////////////////////////////////////////////////
768 ////////////////////////////////////////////////////////////////////////
771 // Load an Ascii obj file
772 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
773 ssgVertexArray *lights, const bool is_base)
775 FGNewMat *newmat = NULL;
779 // sgVec3 approx_normal;
780 // double normal[3], scale = 0.0;
781 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
782 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
783 // GLint display_list = 0;
785 bool in_faces = false;
786 int vncount, vtcount;
787 int n1 = 0, n2 = 0, n3 = 0;
789 // int last1 = 0, last2 = 0;
794 double scenery_version = 0.0;
795 double tex_width = 1000.0, tex_height = 1000.0;
796 bool shared_done = false;
797 int_list fan_vertices;
798 int_list fan_tex_coords;
800 ssgSimpleState *state = NULL;
801 sgVec3 *vtlist, *vnlist;
804 ssgBranch *tile = new ssgBranch () ;
806 tile -> setName ( (char *)path.c_str() ) ;
808 // Attempt to open "path.gz" or "path"
809 sg_gzifstream in( path );
810 if ( ! in.is_open() ) {
811 SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
812 SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
819 shading = fgGetBool("/sim/rendering/shading");
827 t->bounding_radius = 0.0;
831 // StopWatch stopwatch;
832 // stopwatch.start();
834 // ignore initial comments and blank lines. (priming the pump)
835 // in >> skipcomment;
842 while ( in.get(c) && c != '\0' ) {
845 while ( ! in.eof() ) {
849 if ( in.get( c ) && c == '#' ) {
850 // process a comment line
852 // getline( in, line );
853 // cout << "comment = " << line << endl;
857 if ( token == "Version" ) {
858 // read scenery versions number
859 in >> scenery_version;
860 // cout << "scenery_version = " << scenery_version << endl;
861 if ( scenery_version > 0.4 ) {
862 SG_LOG( SG_TERRAIN, SG_ALERT,
863 "\nYou are attempting to load a tile format that\n"
864 << "is newer than this version of flightgear can\n"
865 << "handle. You should upgrade your copy of\n"
866 << "FlightGear to the newest version. For\n"
867 << "details, please see:\n"
868 << "\n http://www.flightgear.org\n" );
871 } else if ( token == "gbs" ) {
872 // reference point (center offset)
874 in >> t->center >> t->bounding_radius;
878 in >> junk1 >> junk2;
881 // cout << "center = " << center
882 // << " radius = " << t->bounding_radius << endl;
883 } else if ( token == "bs" ) {
884 // reference point (center offset)
888 in >> junk1 >> junk2;
889 } else if ( token == "usemtl" ) {
890 // material property specification
892 // if first usemtl with shared_done = false, then set
893 // shared_done true and build the ssg shared lists
894 if ( ! shared_done ) {
896 if ( (int)nodes.size() != vncount ) {
897 SG_LOG( SG_TERRAIN, SG_ALERT,
898 "Tile has mismatched nodes = " << nodes.size()
899 << " and normals = " << vncount << " : "
905 vtlist = new sgVec3 [ nodes.size() ];
906 t->vec3_ptrs.push_back( vtlist );
907 vnlist = new sgVec3 [ vncount ];
908 t->vec3_ptrs.push_back( vnlist );
909 tclist = new sgVec2 [ vtcount ];
910 t->vec2_ptrs.push_back( tclist );
912 for ( i = 0; i < (int)nodes.size(); ++i ) {
913 sgSetVec3( vtlist[i],
914 nodes[i][0], nodes[i][1], nodes[i][2] );
916 for ( i = 0; i < vncount; ++i ) {
917 sgSetVec3( vnlist[i],
922 for ( i = 0; i < vtcount; ++i ) {
923 sgSetVec2( tclist[i],
929 // display_list = xglGenLists(1);
930 // xglNewList(display_list, GL_COMPILE);
931 // printf("xglGenLists(); xglNewList();\n");
934 // scan the material line
937 // find this material in the properties list
939 newmat = material_lib.find( material );
940 if ( newmat == NULL ) {
941 // see if this is an on the fly texture
943 int pos = file.rfind( "/" );
944 file = file.substr( 0, pos );
945 // cout << "current file = " << file << endl;
948 // cout << "current file = " << file << endl;
949 if ( ! material_lib.add_item( file ) ) {
950 SG_LOG( SG_TERRAIN, SG_ALERT,
951 "Ack! unknown usemtl name = " << material
954 // locate our newly created material
955 newmat = material_lib.find( material );
956 if ( newmat == NULL ) {
957 SG_LOG( SG_TERRAIN, SG_ALERT,
958 "Ack! bad on the fly materia create = "
959 << material << " in " << path );
964 if ( newmat != NULL ) {
965 // set the texture width and height values for this
967 tex_width = newmat->get_xsize();
968 tex_height = newmat->get_ysize();
969 state = newmat->get_state();
970 coverage = newmat->get_light_coverage();
971 // cout << "(w) = " << tex_width << " (h) = "
972 // << tex_width << endl;
977 // unknown comment, just gobble the input until the
987 // cout << "token = " << token << endl;
989 if ( token == "vn" ) {
991 if ( vncount < FG_MAX_NODES ) {
992 in >> normals[vncount][0]
993 >> normals[vncount][1]
994 >> normals[vncount][2];
997 SG_LOG( SG_TERRAIN, SG_ALERT,
998 "Read too many vertex normals in " << path
999 << " ... dying :-(" );
1002 } else if ( token == "vt" ) {
1003 // vertex texture coordinate
1004 if ( vtcount < FG_MAX_NODES*3 ) {
1005 in >> tex_coords[vtcount][0]
1006 >> tex_coords[vtcount][1];
1009 SG_LOG( SG_TERRAIN, SG_ALERT,
1010 "Read too many vertex texture coords in " << path
1015 } else if ( token == "v" ) {
1017 if ( t->ncount < FG_MAX_NODES ) {
1018 /* in >> nodes[t->ncount][0]
1019 >> nodes[t->ncount][1]
1020 >> nodes[t->ncount][2]; */
1022 nodes.push_back(node);
1027 SG_LOG( SG_TERRAIN, SG_ALERT,
1028 "Read too many nodes in " << path
1029 << " ... dying :-(");
1032 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1033 // triangle fan, strip, or individual face
1034 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1036 fan_vertices.clear();
1037 fan_tex_coords.clear();
1040 // xglBegin(GL_TRIANGLE_FAN);
1043 fan_vertices.push_back( n1 );
1044 // xglNormal3dv(normals[n1]);
1045 if ( in.get( c ) && c == '/' ) {
1047 fan_tex_coords.push_back( tex );
1048 if ( scenery_version >= 0.4 ) {
1049 if ( tex_width > 0 ) {
1050 tclist[tex][0] *= (1000.0 / tex_width);
1052 if ( tex_height > 0 ) {
1053 tclist[tex][1] *= (1000.0 / tex_height);
1056 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1057 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1060 pp = local_calc_tex_coords(nodes[n1], center);
1062 // xglTexCoord2f(pp.x(), pp.y());
1063 // xglVertex3dv(nodes[n1].get_n());
1066 fan_vertices.push_back( n2 );
1067 // xglNormal3dv(normals[n2]);
1068 if ( in.get( c ) && c == '/' ) {
1070 fan_tex_coords.push_back( tex );
1071 if ( scenery_version >= 0.4 ) {
1072 if ( tex_width > 0 ) {
1073 tclist[tex][0] *= (1000.0 / tex_width);
1075 if ( tex_height > 0 ) {
1076 tclist[tex][1] *= (1000.0 / tex_height);
1079 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1080 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1083 pp = local_calc_tex_coords(nodes[n2], center);
1085 // xglTexCoord2f(pp.x(), pp.y());
1086 // xglVertex3dv(nodes[n2].get_n());
1088 // read all subsequent numbers until next thing isn't a number
1095 if ( ! isdigit(c) || in.eof() ) {
1100 fan_vertices.push_back( n3 );
1101 // cout << " triangle = "
1102 // << n1 << "," << n2 << "," << n3
1104 // xglNormal3dv(normals[n3]);
1105 if ( in.get( c ) && c == '/' ) {
1107 fan_tex_coords.push_back( tex );
1108 if ( scenery_version >= 0.4 ) {
1109 if ( tex_width > 0 ) {
1110 tclist[tex][0] *= (1000.0 / tex_width);
1112 if ( tex_height > 0 ) {
1113 tclist[tex][1] *= (1000.0 / tex_height);
1116 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1117 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1120 pp = local_calc_tex_coords(nodes[n3], center);
1122 // xglTexCoord2f(pp.x(), pp.y());
1123 // xglVertex3dv(nodes[n3].get_n());
1125 if ( (token == "tf") || (token == "f") ) {
1138 // build the ssg entity
1139 int size = (int)fan_vertices.size();
1140 ssgVertexArray *vl = new ssgVertexArray( size );
1141 ssgNormalArray *nl = new ssgNormalArray( size );
1142 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1143 ssgColourArray *cl = new ssgColourArray( 1 );
1146 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1151 for ( i = 0; i < size; ++i ) {
1152 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1155 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1158 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1162 ssgLeaf *leaf = NULL;
1163 if ( token == "tf" ) {
1166 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1167 } else if ( token == "ts" ) {
1170 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1171 } else if ( token == "f" ) {
1174 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1176 // leaf->makeDList();
1177 leaf->setState( state );
1179 tile->addKid( leaf );
1182 if ( coverage > 0.0 ) {
1183 if ( coverage < 10000.0 ) {
1184 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1185 << coverage << ", pushing up to 10000");
1188 gen_random_surface_points(leaf, lights, coverage);
1192 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in "
1193 << path << " = " << token );
1196 // eat white space before start of while loop so if we are
1197 // done with useful input it is noticed before hand.
1206 // stopwatch.stop();
1207 // SG_LOG( SG_TERRAIN, SG_DEBUG,
1208 // "Loaded " << path << " in "
1209 // << stopwatch.elapsedSeconds() << " seconds" );
1215 ssgLeaf *gen_leaf( const string& path,
1216 const GLenum ty, const string& material,
1217 const point_list& nodes, const point_list& normals,
1218 const point_list& texcoords,
1219 const int_list& node_index,
1220 const int_list& normal_index,
1221 const int_list& tex_index,
1222 const bool calc_lights, ssgVertexArray *lights )
1224 double tex_width = 1000.0, tex_height = 1000.0;
1225 ssgSimpleState *state = NULL;
1226 float coverage = -1;
1228 FGNewMat *newmat = material_lib.find( material );
1229 if ( newmat == NULL ) {
1230 // see if this is an on the fly texture
1232 string::size_type pos = file.rfind( "/" );
1233 file = file.substr( 0, pos );
1234 // cout << "current file = " << file << endl;
1237 // cout << "current file = " << file << endl;
1238 if ( ! material_lib.add_item( file ) ) {
1239 SG_LOG( SG_TERRAIN, SG_ALERT,
1240 "Ack! unknown usemtl name = " << material
1241 << " in " << path );
1243 // locate our newly created material
1244 newmat = material_lib.find( material );
1245 if ( newmat == NULL ) {
1246 SG_LOG( SG_TERRAIN, SG_ALERT,
1247 "Ack! bad on the fly material create = "
1248 << material << " in " << path );
1253 if ( newmat != NULL ) {
1254 // set the texture width and height values for this
1256 tex_width = newmat->get_xsize();
1257 tex_height = newmat->get_ysize();
1258 state = newmat->get_state();
1259 coverage = newmat->get_light_coverage();
1260 // cout << "(w) = " << tex_width << " (h) = "
1261 // << tex_width << endl;
1272 int size = node_index.size();
1274 SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1277 ssgVertexArray *vl = new ssgVertexArray( size );
1279 for ( i = 0; i < size; ++i ) {
1280 node = nodes[ node_index[i] ];
1281 sgSetVec3( tmp3, node[0], node[1], node[2] );
1287 ssgNormalArray *nl = new ssgNormalArray( size );
1288 if ( normal_index.size() ) {
1289 // object file specifies normal indices (i.e. normal indices
1291 for ( i = 0; i < size; ++i ) {
1292 normal = normals[ normal_index[i] ];
1293 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1297 // use implied normal indices. normal index = vertex index.
1298 for ( i = 0; i < size; ++i ) {
1299 normal = normals[ node_index[i] ];
1300 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1306 ssgColourArray *cl = new ssgColourArray( 1 );
1307 sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1310 // texture coordinates
1311 size = tex_index.size();
1313 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1315 texcoord = texcoords[ tex_index[0] ];
1316 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1317 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1318 if ( tex_width > 0 ) {
1319 tmp2[0] *= (1000.0 / tex_width);
1321 if ( tex_height > 0 ) {
1322 tmp2[1] *= (1000.0 / tex_height);
1325 } else if ( size > 1 ) {
1326 for ( i = 0; i < size; ++i ) {
1327 texcoord = texcoords[ tex_index[i] ];
1328 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1329 if ( tex_width > 0 ) {
1330 tmp2[0] *= (1000.0 / tex_width);
1332 if ( tex_height > 0 ) {
1333 tmp2[1] *= (1000.0 / tex_height);
1339 ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1341 // lookup the state record
1343 leaf->setState( state );
1345 if ( calc_lights ) {
1346 if ( coverage > 0.0 ) {
1347 if ( coverage < 10000.0 ) {
1348 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1349 << coverage << ", pushing up to 10000");
1352 gen_random_surface_points(leaf, lights, coverage);
1360 // Load an Binary obj file
1361 bool fgBinObjLoad( const string& path, const bool is_base,
1363 double *bounding_radius,
1364 ssgBranch* geometry,
1365 ssgBranch* rwy_lights,
1366 ssgVertexArray *ground_lights )
1369 bool use_random_objects =
1370 fgGetBool("/sim/rendering/random-objects", true);
1372 if ( ! obj.read_bin( path ) ) {
1376 geometry->setName( (char *)path.c_str() );
1379 // reference point (center offset/bounding sphere)
1380 *center = obj.get_gbs_center();
1381 *bounding_radius = obj.get_gbs_radius();
1385 point_list const& nodes = obj.get_wgs84_nodes();
1386 point_list const& colors = obj.get_colors();
1387 point_list const& normals = obj.get_normals();
1388 point_list const& texcoords = obj.get_texcoords();
1393 group_list::size_type i;
1394 bool is_lighting = false;
1397 string_list const& pt_materials = obj.get_pt_materials();
1398 group_list const& pts_v = obj.get_pts_v();
1399 group_list const& pts_n = obj.get_pts_n();
1400 for ( i = 0; i < pts_v.size(); ++i ) {
1401 // cout << "pts_v.size() = " << pts_v.size() << endl;
1402 if ( pt_materials[i].substr(0, 3) == "RWY" ) {
1403 material = "LIGHTS";
1406 material = pt_materials[i];
1409 ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1410 nodes, normals, texcoords,
1411 pts_v[i], pts_n[i], tex_index,
1412 false, ground_lights );
1414 if ( is_lighting ) {
1419 leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1420 ssgRangeSelector * lod = new ssgRangeSelector;
1421 lod->setRanges(ranges, 2);
1423 rwy_lights->addKid(lod);
1425 geometry->addKid( leaf );
1429 // Put all randomly-placed objects under a separate branch
1430 // (actually an ssgRangeSelector) named "random-models".
1431 ssgBranch * random_object_branch = 0;
1432 if (use_random_objects) {
1433 float ranges[] = { 0, 20000 }; // Maximum 20km range for random objects
1434 ssgRangeSelector * object_lod = new ssgRangeSelector;
1435 object_lod->setRanges(ranges, 2);
1436 object_lod->setName("random-models");
1437 geometry->addKid(object_lod);
1438 random_object_branch = new ssgBranch;
1439 object_lod->addKid(random_object_branch);
1442 // generate triangles
1443 string_list const& tri_materials = obj.get_tri_materials();
1444 group_list const& tris_v = obj.get_tris_v();
1445 group_list const& tris_n = obj.get_tris_n();
1446 group_list const& tris_tc = obj.get_tris_tc();
1447 for ( i = 0; i < tris_v.size(); ++i ) {
1448 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, tri_materials[i],
1449 nodes, normals, texcoords,
1450 tris_v[i], tris_n[i], tris_tc[i],
1451 is_base, ground_lights );
1453 if (use_random_objects)
1454 gen_random_surface_objects(leaf, random_object_branch,
1455 center, tri_materials[i]);
1456 geometry->addKid( leaf );
1460 string_list const& strip_materials = obj.get_strip_materials();
1461 group_list const& strips_v = obj.get_strips_v();
1462 group_list const& strips_n = obj.get_strips_n();
1463 group_list const& strips_tc = obj.get_strips_tc();
1464 for ( i = 0; i < strips_v.size(); ++i ) {
1465 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, strip_materials[i],
1466 nodes, normals, texcoords,
1467 strips_v[i], strips_n[i], strips_tc[i],
1468 is_base, ground_lights );
1470 if (use_random_objects)
1471 gen_random_surface_objects(leaf, random_object_branch,
1472 center,strip_materials[i]);
1473 geometry->addKid( leaf );
1477 string_list const& fan_materials = obj.get_fan_materials();
1478 group_list const& fans_v = obj.get_fans_v();
1479 group_list const& fans_n = obj.get_fans_n();
1480 group_list const& fans_tc = obj.get_fans_tc();
1481 for ( i = 0; i < fans_v.size(); ++i ) {
1482 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, fan_materials[i],
1483 nodes, normals, texcoords,
1484 fans_v[i], fans_n[i], fans_tc[i],
1485 is_base, ground_lights );
1486 if (use_random_objects)
1487 gen_random_surface_objects(leaf, random_object_branch,
1488 center, fan_materials[i]);
1489 geometry->addKid( leaf );