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/misc/sgstream.hxx>
51 #include <simgear/misc/stopwatch.hxx>
52 #include <simgear/misc/texcoord.hxx>
54 #include <Main/globals.hxx>
55 #include <Main/fg_props.hxx>
56 #include <Time/light.hxx>
57 #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];
76 runway_lights_predraw (ssgEntity * e)
78 // Turn on lights only at night
79 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
80 return int(sun_angle > 90.0);
84 #define FG_TEX_CONSTANT 69.0
86 // Calculate texture coordinates for a given point.
87 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
90 // double tmplon, tmplat;
92 // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
93 // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
95 cp = Point3D( node[0] + ref.x(),
99 pp = sgCartToPolar3d(cp);
101 // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
102 // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
103 // cout << tmplon << " " << tmplat << endl;
105 pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
106 pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
108 if ( pp.x() < 0.0 ) {
109 pp.setx( pp.x() + 11.0 );
112 if ( pp.y() < 0.0 ) {
113 pp.sety( pp.y() + 11.0 );
116 // cout << pp << endl;
122 // Generate an ocean tile
123 bool fgGenTile( const string& path, SGBucket b,
125 double *bounding_radius,
126 ssgBranch* geometry )
130 ssgSimpleState *state = NULL;
132 geometry -> setName ( (char *)path.c_str() ) ;
134 double tex_width = 1000.0;
135 // double tex_height;
137 // find Ocean material in the properties list
138 newmat = material_lib.find( "Ocean" );
139 if ( newmat != NULL ) {
140 // set the texture width and height values for this
142 tex_width = newmat->get_xsize();
143 // tex_height = newmat->get_ysize();
146 state = newmat->get_state();
148 SG_LOG( SG_TERRAIN, SG_ALERT,
149 "Ack! unknown usemtl name = " << "Ocean"
153 // Calculate center point
154 double clon = b.get_center_lon();
155 double clat = b.get_center_lat();
156 double height = b.get_height();
157 double width = b.get_width();
159 *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
160 clat*SGD_DEGREES_TO_RADIANS,
162 // cout << "center = " << center << endl;;
164 // Caculate corner vertices
166 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
167 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
168 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
169 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
173 for ( i = 0; i < 4; ++i ) {
174 rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
175 geod[i].y() * SGD_DEGREES_TO_RADIANS,
179 Point3D cart[4], rel[4];
180 for ( i = 0; i < 4; ++i ) {
181 cart[i] = sgGeodToCart(rad[i]);
182 rel[i] = cart[i] - *center;
183 // cout << "corner " << i << " = " << cart[i] << endl;
186 // Calculate bounding radius
187 *bounding_radius = center->distance3D( cart[0] );
188 // cout << "bounding radius = " << t->bounding_radius << endl;
192 for ( i = 0; i < 4; ++i ) {
193 double length = cart[i].distance3D( Point3D(0.0) );
194 normals[i] = cart[i] / length;
195 // cout << "normal = " << normals[i] << endl;
198 // Calculate texture coordinates
199 point_list geod_nodes;
203 for ( i = 0; i < 4; ++i ) {
204 geod_nodes.push_back( geod[i] );
205 rectangle.push_back( i );
207 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
208 1000.0 / tex_width );
210 // Allocate ssg structure
211 ssgVertexArray *vl = new ssgVertexArray( 4 );
212 ssgNormalArray *nl = new ssgNormalArray( 4 );
213 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
214 ssgColourArray *cl = new ssgColourArray( 1 );
217 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
220 // sgVec3 *vtlist = new sgVec3 [ 4 ];
221 // t->vec3_ptrs.push_back( vtlist );
222 // sgVec3 *vnlist = new sgVec3 [ 4 ];
223 // t->vec3_ptrs.push_back( vnlist );
224 // sgVec2 *tclist = new sgVec2 [ 4 ];
225 // t->vec2_ptrs.push_back( tclist );
229 for ( i = 0; i < 4; ++i ) {
231 rel[i].x(), rel[i].y(), rel[i].z() );
235 normals[i].x(), normals[i].y(), normals[i].z() );
238 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
243 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
245 leaf->setState( state );
247 geometry->addKid( leaf );
253 static void random_pt_inside_tri( float *res,
254 float *n1, float *n2, float *n3 )
258 double a = sg_random();
259 double b = sg_random();
264 double c = 1 - a - b;
266 sgScaleVec3( p1, n1, a );
267 sgScaleVec3( p2, n2, b );
268 sgScaleVec3( p3, n3, c );
270 sgAddVec3( res, p1, p2 );
271 sgAddVec3( res, p3 );
275 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
277 int num = leaf->getNumTriangles();
279 short int n1, n2, n3;
283 // generate a repeatable random seed
284 p1 = leaf->getVertex( 0 );
285 unsigned int seed = (unsigned int)p1[0];
288 for ( int i = 0; i < num; ++i ) {
289 leaf->getTriangle( i, &n1, &n2, &n3 );
290 p1 = leaf->getVertex(n1);
291 p2 = leaf->getVertex(n2);
292 p3 = leaf->getVertex(n3);
293 double area = sgTriArea( p1, p2, p3 );
294 double num = area / factor;
296 // generate a light point for each unit of area
297 while ( num > 1.0 ) {
298 random_pt_inside_tri( result, p1, p2, p3 );
299 lights->add( result );
302 // for partial units of area, use a zombie door method to
303 // create the proper random chance of a light being created
306 if ( sg_random() <= num ) {
307 // a zombie made it through our door
308 random_pt_inside_tri( result, p1, p2, p3 );
309 lights->add( result );
318 * Create a rotation matrix to align an object for the current lat/lon.
320 * By default, objects are aligned for the north pole. This code
321 * calculates a matrix to rotate them for the surface of the earth in
322 * the current location.
324 * TODO: there should be a single version of this method somewhere
325 * for all of SimGear.
327 * @param ROT The resulting rotation matrix.
328 * @param hdg_deg The object heading in degrees.
329 * @param lon_deg The longitude in degrees.
330 * @param lat_deg The latitude in degrees.
333 makeWorldUpRotationMatrix (sgMat4 ROT, double hdg_deg,
334 double lon_deg, double lat_deg)
336 SGfloat sin_lat = sin( lat_deg * SGD_DEGREES_TO_RADIANS );
337 SGfloat cos_lat = cos( lat_deg * SGD_DEGREES_TO_RADIANS );
338 SGfloat sin_lon = sin( lon_deg * SGD_DEGREES_TO_RADIANS );
339 SGfloat cos_lon = cos( lon_deg * SGD_DEGREES_TO_RADIANS );
340 SGfloat sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
341 SGfloat cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
343 ROT[0][0] = cos_hdg * sin_lat * cos_lon - sin_hdg * sin_lon;
344 ROT[0][1] = cos_hdg * sin_lat * sin_lon + sin_hdg * cos_lon;
345 ROT[0][2] = -cos_hdg * cos_lat;
348 ROT[1][0] = -sin_hdg * sin_lat * cos_lon - cos_hdg * sin_lon;
349 ROT[1][1] = -sin_hdg * sin_lat * sin_lon + cos_hdg * cos_lon;
350 ROT[1][2] = sin_hdg * cos_lat;
353 ROT[2][0] = cos_lat * cos_lon;
354 ROT[2][1] = cos_lat * sin_lon;
366 * Add an object to a random location inside a triangle.
368 * @param p1 The first vertex of the triangle.
369 * @param p2 The second vertex of the triangle.
370 * @param p3 The third vertex of the triangle.
371 * @param center The center of the triangle.
372 * @param lon_deg The longitude of the surface center, in degrees.
373 * @param lat_deg The latitude of the surface center, in degrees.
374 * @param object The randomly-placed object.
375 * @param branch The branch where the object should be added to the
379 add_object_to_triangle (sgVec3 p1, sgVec3 p2, sgVec3 p3, sgVec3 center,
380 double lon_deg, double lat_deg,
381 FGNewMat::Object * object, ssgBranch * branch)
383 // Set up the random heading if required.
385 if (object->get_heading_type() == FGNewMat::Object::HEADING_RANDOM)
386 hdg_deg = sg_random() * 360;
391 makeWorldUpRotationMatrix(ROT, hdg_deg, lon_deg, lat_deg);
393 random_pt_inside_tri(result, p1, p2, p3);
394 sgSubVec3(result, center);
396 sgMakeTransMat4(OBJ_pos, result);
397 sgCopyMat4(OBJ, ROT);
398 sgPostMultMat4(OBJ, OBJ_pos);
399 ssgTransform * pos = new ssgTransform;
400 pos->setTransform(OBJ);
401 pos->addKid(object->get_random_model());
407 * User data for populating triangles when they come in range.
409 class TriUserData : public ssgBase
416 FGNewMat::ObjectGroup * object_group;
425 * Fill in a triangle with randomly-placed objects.
427 * This method is invoked by a callback when the triangle is in range
428 * but not yet populated.
430 * @param p1 The first vertex of the triangle.
431 * @param p2 The second vertex of the triangle.
432 * @param p3 The third vertex of the triangle.
433 * @param mat The triangle's material.
434 * @param object_index The index of the random object in the triangle.
435 * @param branch The branch where the objects should be added.
436 * @param lon_deg The longitude of the surface center, in degrees.
437 * @param lat_deg The latitude of the surface center, in degrees.
440 fill_in_triangle (float * p1, float * p2, float * p3,
441 FGNewMat::ObjectGroup * object_group, ssgBranch * branch,
442 double lon_deg, double lat_deg, unsigned int seed)
444 // generate a repeatable random seed
447 int nObjects = object_group->get_object_count();
448 for (int i = 0; i < nObjects; i++) {
449 FGNewMat::Object * object = object_group->get_object(i);
452 (p1[0] + p2[0] + p3[0]) / 3.0,
453 (p1[1] + p2[1] + p3[1]) / 3.0,
454 (p1[2] + p2[2] + p3[2]) / 3.0);
455 double area = sgTriArea(p1, p2, p3);
456 double num = area / object->get_coverage_m2();
458 // place an object each unit of area
459 while ( num > 1.0 ) {
460 add_object_to_triangle(p1, p2, p3, center, lon_deg, lat_deg,
464 // for partial units of area, use a zombie door method to
465 // create the proper random chance of an object being created
468 if ( sg_random() <= num ) {
469 // a zombie made it through our door
470 add_object_to_triangle(p1, p2, p3, center, lon_deg, lat_deg,
478 * SSG callback for an in-range triangle of randomly-placed objects.
480 * This pretraversal callback is attached to a branch that is traversed
481 * only when a triangle is in range. If the triangle is not currently
482 * populated with randomly-placed objects, this callback will populate
485 * @param entity The entity to which the callback is attached (not used).
486 * @param mask The entity's traversal mask (not used).
487 * @return Always 1, to allow traversal and culling to continue.
490 tri_in_range_callback (ssgEntity * entity, int mask)
492 TriUserData * data = (TriUserData *)entity->getUserData();
493 if (!data->is_filled_in) {
494 fill_in_triangle(data->p1, data->p2, data->p3, data->object_group,
495 data->branch, data->lon_deg, data->lat_deg,
497 data->is_filled_in = true;
504 * SSG callback for an out-of-range triangle of randomly-placed objects.
506 * This pretraversal callback is attached to a branch that is traversed
507 * only when a triangle is out of range. If the triangle is currently
508 * populated with randomly-placed objects, the objects will be removed.
511 * @param entity The entity to which the callback is attached (not used).
512 * @param mask The entity's traversal mask (not used).
513 * @return Always 0, to prevent any further traversal or culling.
516 tri_out_of_range_callback (ssgEntity * entity, int mask)
518 TriUserData * data = (TriUserData *)entity->getUserData();
519 if (data->is_filled_in) {
520 data->branch->removeAllKids();
521 data->is_filled_in = false;
528 * Singleton ssgEntity with a dummy bounding sphere, to fool culling.
530 * This forces the in-range and out-of-range branches to be visited
531 * when appropriate, even if they have no children. It's ugly, but
532 * it works and seems fairly efficient (since branches can still
533 * be culled when they're out of the view frustum).
535 class DummyBSphereEntity : public ssgEntity
538 virtual ~DummyBSphereEntity () {}
539 virtual void recalcBSphere () { bsphere_is_invalid = false; }
540 virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
541 virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
542 virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
543 virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
544 static ssgEntity * get_entity ();
546 DummyBSphereEntity ()
548 bsphere.setCenter(0, 0, 0);
549 bsphere.setRadius(1000);
551 static DummyBSphereEntity * entity;
555 DummyBSphereEntity * DummyBSphereEntity::entity = 0;
559 * Ensure that only one copy of the dummy entity exists.
561 * @return The singleton copy of the DummyBSphereEntity.
564 DummyBSphereEntity::get_entity ()
567 entity = new DummyBSphereEntity;
575 * Calculate the bounding radius of a triangle from its center.
577 * @param center The triangle center.
578 * @param p1 The first point in the triangle.
579 * @param p2 The second point in the triangle.
580 * @param p3 The third point in the triangle.
581 * @return The greatest distance any point lies from the center.
584 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
586 return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
587 sgDistanceSquaredVec3(center, p2),
588 sgDistanceSquaredVec3(center, p3) ) );
593 * Set up a triangle for randomly-placed objects.
595 * No objects will be added unless the triangle comes into range.
597 * @param leaf The leaf containing the data for the terrain surface.
598 * @param tri_index The index of the triangle in the leaf.
599 * @param mat The material data for the triangle.
600 * @param branch The branch to which the randomly-placed objects
602 * @param lon_deg The longitude of the surface center, in degrees.
603 * @param lat_deg The latitude of the surface center, in degrees.
606 setup_triangle (float * p1, float * p2, float * p3,
607 FGNewMat * mat, ssgBranch * branch,
608 double lon_deg, double lat_deg)
610 // Set up a single center point for LOD
613 (p1[0] + p2[0] + p3[0]) / 3.0,
614 (p1[1] + p2[1] + p3[1]) / 3.0,
615 (p1[2] + p2[2] + p3[2]) / 3.0);
617 // maximum radius of an object from center.
618 double bounding_radius = get_bounding_radius(center, p1, p2, p3);
620 // Set up a transformation to the center
621 // point, so that everything else can
622 // be specified relative to it.
623 ssgTransform * location = new ssgTransform;
625 sgMakeTransMat4(TRANS, center);
626 location->setTransform(TRANS);
627 branch->addKid(location);
629 // Iterate through all the object types.
630 int num_groups = mat->get_object_group_count();
631 for (int i = 0; i < num_groups; i++) {
632 // Look up the random object.
633 FGNewMat::ObjectGroup * group = mat->get_object_group(i);
635 // Set up the range selector for the entire
636 // triangle; note that we use the object
637 // range plus the bounding radius here, to
638 // allow for objects far from the center.
640 group->get_range_m() + bounding_radius,
642 ssgRangeSelector * lod = new ssgRangeSelector;
643 lod->setRanges(ranges, 3);
644 location->addKid(lod);
646 // Create the in-range and out-of-range
648 ssgBranch * in_range = new ssgBranch;
649 ssgBranch * out_of_range = new ssgBranch;
651 // Set up the user data for if/when
652 // the random objects in this triangle
654 TriUserData * data = new TriUserData;
655 data->is_filled_in = false;
659 data->object_group = group;
660 data->branch = in_range;
661 data->lon_deg = lon_deg;
662 data->lat_deg = lat_deg;
663 data->seed = (unsigned int)(p1[0] * i);
665 // Set up the in-range node.
666 in_range->setUserData(data);
667 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
668 tri_in_range_callback);
669 lod->addKid(in_range);
671 // Set up the out-of-range node.
672 out_of_range->setUserData(data);
673 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
674 tri_out_of_range_callback);
675 out_of_range->addKid(DummyBSphereEntity::get_entity());
676 lod->addKid(out_of_range);
682 * User data for populating tiles when they come in range.
684 class TileUserData : public ssgBase
697 * SSG callback for an in-range tile of randomly-placed objects.
699 * This pretraversal callback is attached to a branch that is
700 * traversed only when a tile is in range. If the tile is not
701 * currently prepared to be populated with randomly-placed objects,
702 * this callback will prepare it (actual population is handled by
703 * the tri_in_range_callback for individual triangles).
705 * @param entity The entity to which the callback is attached (not used).
706 * @param mask The entity's traversal mask (not used).
707 * @return Always 1, to allow traversal and culling to continue.
710 tile_in_range_callback (ssgEntity * entity, int mask)
712 TileUserData * data = (TileUserData *)entity->getUserData();
714 if (!data->is_filled_in) {
715 // Iterate through all the triangles
716 // and populate them.
717 int num_tris = data->leaf->getNumTriangles();
718 for ( int i = 0; i < num_tris; ++i ) {
720 data->leaf->getTriangle(i, &n1, &n2, &n3);
721 setup_triangle(data->leaf->getVertex(n1),
722 data->leaf->getVertex(n2),
723 data->leaf->getVertex(n3),
724 data->mat, data->branch, data->lon_deg, data->lat_deg);
726 data->is_filled_in = true;
733 * SSG callback for an out-of-range tile of randomly-placed objects.
735 * This pretraversal callback is attached to a branch that is
736 * traversed only when a tile is out of range. If the tile is
737 * currently prepared to be populated with randomly-placed objects (or
738 * is actually populated), the objects will be removed.
740 * @param entity The entity to which the callback is attached (not used).
741 * @param mask The entity's traversal mask (not used).
742 * @return Always 0, to prevent any further traversal or culling.
745 tile_out_of_range_callback (ssgEntity * entity, int mask)
747 TileUserData * data = (TileUserData *)entity->getUserData();
748 if (data->is_filled_in) {
749 data->branch->removeAllKids();
750 data->is_filled_in = false;
757 * Randomly place objects on a surface.
759 * The leaf node provides the geometry of the surface, while the
760 * material provides the objects and placement density. Latitude
761 * and longitude are required so that the objects can be rotated
762 * to the world-up vector. This function does not actually add
763 * any objects; instead, it attaches an ssgRangeSelector to the
764 * branch with callbacks to generate the objects when needed.
766 * @param leaf The surface where the objects should be placed.
767 * @param branch The branch that will hold the randomly-placed objects.
768 * @param center The center of the tile in FlightGear coordinates.
769 * @param lon_deg The longitude of the surface center, in degrees.
770 * @param lat_deg The latitude of the surface center, in degrees.
771 * @param material_name The name of the surface's material.
774 gen_random_surface_objects (ssgLeaf *leaf,
777 const string &material_name)
779 // If the surface has no triangles, return
781 int num_tris = leaf->getNumTriangles();
785 // Get the material for this surface.
786 FGNewMat * mat = material_lib.find(material_name);
788 SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
792 // If the material has no randomly-placed
793 // objects, return now.
794 if (mat->get_object_group_count() < 1)
797 // Calculate the geodetic centre of
798 // the tile, for aligning automatic
800 double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
801 Point3D geoc = sgCartToPolar3d(*center);
802 lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
803 sgGeocToGeod(geoc.lat(), geoc.radius(),
804 &lat_rad, &alt_m, &sl_radius_m);
805 lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
808 // max random object range: 20000m
809 float ranges[] = {0, 20000, 1000000};
810 ssgRangeSelector * lod = new ssgRangeSelector;
811 lod->setRanges(ranges, 3);
814 // Create the in-range and out-of-range
816 ssgBranch * in_range = new ssgBranch;
817 ssgBranch * out_of_range = new ssgBranch;
818 lod->addKid(in_range);
819 lod->addKid(out_of_range);
821 TileUserData * data = new TileUserData;
822 data->is_filled_in = false;
825 data->branch = in_range;
826 data->lon_deg = lon_deg;
827 data->lat_deg = lat_deg;
829 in_range->setUserData(data);
830 in_range->setTravCallback(SSG_CALLBACK_PRETRAV, tile_in_range_callback);
831 out_of_range->setUserData(data);
832 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
833 tile_out_of_range_callback);
834 out_of_range->addKid(DummyBSphereEntity::get_entity());
839 ////////////////////////////////////////////////////////////////////////
841 ////////////////////////////////////////////////////////////////////////
844 // Load an Ascii obj file
845 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
846 ssgVertexArray *lights, const bool is_base)
848 FGNewMat *newmat = NULL;
852 // sgVec3 approx_normal;
853 // double normal[3], scale = 0.0;
854 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
855 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
856 // GLint display_list = 0;
858 bool in_faces = false;
859 int vncount, vtcount;
860 int n1 = 0, n2 = 0, n3 = 0;
862 // int last1 = 0, last2 = 0;
867 double scenery_version = 0.0;
868 double tex_width = 1000.0, tex_height = 1000.0;
869 bool shared_done = false;
870 int_list fan_vertices;
871 int_list fan_tex_coords;
873 ssgSimpleState *state = NULL;
874 sgVec3 *vtlist, *vnlist;
877 ssgBranch *tile = new ssgBranch () ;
879 tile -> setName ( (char *)path.c_str() ) ;
881 // Attempt to open "path.gz" or "path"
882 sg_gzifstream in( path );
883 if ( ! in.is_open() ) {
884 SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
885 SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
892 shading = fgGetBool("/sim/rendering/shading");
900 t->bounding_radius = 0.0;
904 // StopWatch stopwatch;
905 // stopwatch.start();
907 // ignore initial comments and blank lines. (priming the pump)
908 // in >> skipcomment;
915 while ( in.get(c) && c != '\0' ) {
918 while ( ! in.eof() ) {
923 if ( in.get( c ) && c == '#' ) {
924 // process a comment line
926 // getline( in, line );
927 // cout << "comment = " << line << endl;
931 if ( token == "Version" ) {
932 // read scenery versions number
933 in >> scenery_version;
934 // cout << "scenery_version = " << scenery_version << endl;
935 if ( scenery_version > 0.4 ) {
936 SG_LOG( SG_TERRAIN, SG_ALERT,
937 "\nYou are attempting to load a tile format that\n"
938 << "is newer than this version of flightgear can\n"
939 << "handle. You should upgrade your copy of\n"
940 << "FlightGear to the newest version. For\n"
941 << "details, please see:\n"
942 << "\n http://www.flightgear.org\n" );
945 } else if ( token == "gbs" ) {
946 // reference point (center offset)
948 in >> t->center >> t->bounding_radius;
952 in >> junk1 >> junk2;
955 // cout << "center = " << center
956 // << " radius = " << t->bounding_radius << endl;
957 } else if ( token == "bs" ) {
958 // reference point (center offset)
962 in >> junk1 >> junk2;
963 } else if ( token == "usemtl" ) {
964 // material property specification
966 // if first usemtl with shared_done = false, then set
967 // shared_done true and build the ssg shared lists
968 if ( ! shared_done ) {
970 if ( (int)nodes.size() != vncount ) {
971 SG_LOG( SG_TERRAIN, SG_ALERT,
972 "Tile has mismatched nodes = " << nodes.size()
973 << " and normals = " << vncount << " : "
979 vtlist = new sgVec3 [ nodes.size() ];
980 t->vec3_ptrs.push_back( vtlist );
981 vnlist = new sgVec3 [ vncount ];
982 t->vec3_ptrs.push_back( vnlist );
983 tclist = new sgVec2 [ vtcount ];
984 t->vec2_ptrs.push_back( tclist );
986 for ( i = 0; i < (int)nodes.size(); ++i ) {
987 sgSetVec3( vtlist[i],
988 nodes[i][0], nodes[i][1], nodes[i][2] );
990 for ( i = 0; i < vncount; ++i ) {
991 sgSetVec3( vnlist[i],
996 for ( i = 0; i < vtcount; ++i ) {
997 sgSetVec2( tclist[i],
1003 // display_list = xglGenLists(1);
1004 // xglNewList(display_list, GL_COMPILE);
1005 // printf("xglGenLists(); xglNewList();\n");
1008 // scan the material line
1011 // find this material in the properties list
1013 newmat = material_lib.find( material );
1014 if ( newmat == NULL ) {
1015 // see if this is an on the fly texture
1017 int pos = file.rfind( "/" );
1018 file = file.substr( 0, pos );
1019 // cout << "current file = " << file << endl;
1022 // cout << "current file = " << file << endl;
1023 if ( ! material_lib.add_item( file ) ) {
1024 SG_LOG( SG_TERRAIN, SG_ALERT,
1025 "Ack! unknown usemtl name = " << material
1026 << " in " << path );
1028 // locate our newly created material
1029 newmat = material_lib.find( material );
1030 if ( newmat == NULL ) {
1031 SG_LOG( SG_TERRAIN, SG_ALERT,
1032 "Ack! bad on the fly materia create = "
1033 << material << " in " << path );
1038 if ( newmat != NULL ) {
1039 // set the texture width and height values for this
1041 tex_width = newmat->get_xsize();
1042 tex_height = newmat->get_ysize();
1043 state = newmat->get_state();
1044 coverage = newmat->get_light_coverage();
1045 // cout << "(w) = " << tex_width << " (h) = "
1046 // << tex_width << endl;
1051 // unknown comment, just gobble the input until the
1061 // cout << "token = " << token << endl;
1063 if ( token == "vn" ) {
1065 if ( vncount < FG_MAX_NODES ) {
1066 in >> normals[vncount][0]
1067 >> normals[vncount][1]
1068 >> normals[vncount][2];
1071 SG_LOG( SG_TERRAIN, SG_ALERT,
1072 "Read too many vertex normals in " << path
1073 << " ... dying :-(" );
1076 } else if ( token == "vt" ) {
1077 // vertex texture coordinate
1078 if ( vtcount < FG_MAX_NODES*3 ) {
1079 in >> tex_coords[vtcount][0]
1080 >> tex_coords[vtcount][1];
1083 SG_LOG( SG_TERRAIN, SG_ALERT,
1084 "Read too many vertex texture coords in " << path
1089 } else if ( token == "v" ) {
1091 if ( t->ncount < FG_MAX_NODES ) {
1092 /* in >> nodes[t->ncount][0]
1093 >> nodes[t->ncount][1]
1094 >> nodes[t->ncount][2]; */
1096 nodes.push_back(node);
1101 SG_LOG( SG_TERRAIN, SG_ALERT,
1102 "Read too many nodes in " << path
1103 << " ... dying :-(");
1106 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1107 // triangle fan, strip, or individual face
1108 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1110 fan_vertices.clear();
1111 fan_tex_coords.clear();
1114 // xglBegin(GL_TRIANGLE_FAN);
1117 fan_vertices.push_back( n1 );
1118 // xglNormal3dv(normals[n1]);
1119 if ( in.get( c ) && c == '/' ) {
1121 fan_tex_coords.push_back( tex );
1122 if ( scenery_version >= 0.4 ) {
1123 if ( tex_width > 0 ) {
1124 tclist[tex][0] *= (1000.0 / tex_width);
1126 if ( tex_height > 0 ) {
1127 tclist[tex][1] *= (1000.0 / tex_height);
1130 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1131 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1134 pp = local_calc_tex_coords(nodes[n1], center);
1136 // xglTexCoord2f(pp.x(), pp.y());
1137 // xglVertex3dv(nodes[n1].get_n());
1140 fan_vertices.push_back( n2 );
1141 // xglNormal3dv(normals[n2]);
1142 if ( in.get( c ) && c == '/' ) {
1144 fan_tex_coords.push_back( tex );
1145 if ( scenery_version >= 0.4 ) {
1146 if ( tex_width > 0 ) {
1147 tclist[tex][0] *= (1000.0 / tex_width);
1149 if ( tex_height > 0 ) {
1150 tclist[tex][1] *= (1000.0 / tex_height);
1153 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1154 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1157 pp = local_calc_tex_coords(nodes[n2], center);
1159 // xglTexCoord2f(pp.x(), pp.y());
1160 // xglVertex3dv(nodes[n2].get_n());
1162 // read all subsequent numbers until next thing isn't a number
1169 if ( ! isdigit(c) || in.eof() ) {
1174 fan_vertices.push_back( n3 );
1175 // cout << " triangle = "
1176 // << n1 << "," << n2 << "," << n3
1178 // xglNormal3dv(normals[n3]);
1179 if ( in.get( c ) && c == '/' ) {
1181 fan_tex_coords.push_back( tex );
1182 if ( scenery_version >= 0.4 ) {
1183 if ( tex_width > 0 ) {
1184 tclist[tex][0] *= (1000.0 / tex_width);
1186 if ( tex_height > 0 ) {
1187 tclist[tex][1] *= (1000.0 / tex_height);
1190 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1191 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1194 pp = local_calc_tex_coords(nodes[n3], center);
1196 // xglTexCoord2f(pp.x(), pp.y());
1197 // xglVertex3dv(nodes[n3].get_n());
1199 if ( (token == "tf") || (token == "f") ) {
1212 // build the ssg entity
1213 int size = (int)fan_vertices.size();
1214 ssgVertexArray *vl = new ssgVertexArray( size );
1215 ssgNormalArray *nl = new ssgNormalArray( size );
1216 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1217 ssgColourArray *cl = new ssgColourArray( 1 );
1220 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1225 for ( i = 0; i < size; ++i ) {
1226 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1229 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1232 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1236 ssgLeaf *leaf = NULL;
1237 if ( token == "tf" ) {
1240 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1241 } else if ( token == "ts" ) {
1244 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1245 } else if ( token == "f" ) {
1248 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1250 // leaf->makeDList();
1251 leaf->setState( state );
1253 tile->addKid( leaf );
1256 if ( coverage > 0.0 ) {
1257 if ( coverage < 10000.0 ) {
1258 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1259 << coverage << ", pushing up to 10000");
1262 gen_random_surface_points(leaf, lights, coverage);
1266 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in "
1267 << path << " = " << token );
1270 // eat white space before start of while loop so if we are
1271 // done with useful input it is noticed before hand.
1280 // stopwatch.stop();
1281 // SG_LOG( SG_TERRAIN, SG_DEBUG,
1282 // "Loaded " << path << " in "
1283 // << stopwatch.elapsedSeconds() << " seconds" );
1289 ssgLeaf *gen_leaf( const string& path,
1290 const GLenum ty, const string& material,
1291 const point_list& nodes, const point_list& normals,
1292 const point_list& texcoords,
1293 const int_list node_index,
1294 const int_list normal_index,
1295 const int_list& tex_index,
1296 const bool calc_lights, ssgVertexArray *lights )
1298 double tex_width = 1000.0, tex_height = 1000.0;
1299 ssgSimpleState *state = NULL;
1300 float coverage = -1;
1302 FGNewMat *newmat = material_lib.find( material );
1303 if ( newmat == NULL ) {
1304 // see if this is an on the fly texture
1306 int pos = file.rfind( "/" );
1307 file = file.substr( 0, pos );
1308 // cout << "current file = " << file << endl;
1311 // cout << "current file = " << file << endl;
1312 if ( ! material_lib.add_item( file ) ) {
1313 SG_LOG( SG_TERRAIN, SG_ALERT,
1314 "Ack! unknown usemtl name = " << material
1315 << " in " << path );
1317 // locate our newly created material
1318 newmat = material_lib.find( material );
1319 if ( newmat == NULL ) {
1320 SG_LOG( SG_TERRAIN, SG_ALERT,
1321 "Ack! bad on the fly material create = "
1322 << material << " in " << path );
1327 if ( newmat != NULL ) {
1328 // set the texture width and height values for this
1330 tex_width = newmat->get_xsize();
1331 tex_height = newmat->get_ysize();
1332 state = newmat->get_state();
1333 coverage = newmat->get_light_coverage();
1334 // cout << "(w) = " << tex_width << " (h) = "
1335 // << tex_width << endl;
1346 int size = node_index.size();
1348 SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1351 ssgVertexArray *vl = new ssgVertexArray( size );
1353 for ( i = 0; i < size; ++i ) {
1354 node = nodes[ node_index[i] ];
1355 sgSetVec3( tmp3, node[0], node[1], node[2] );
1361 ssgNormalArray *nl = new ssgNormalArray( size );
1362 if ( normal_index.size() ) {
1363 // object file specifies normal indices (i.e. normal indices
1365 for ( i = 0; i < size; ++i ) {
1366 normal = normals[ normal_index[i] ];
1367 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1371 // use implied normal indices. normal index = vertex index.
1372 for ( i = 0; i < size; ++i ) {
1373 normal = normals[ node_index[i] ];
1374 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1380 ssgColourArray *cl = new ssgColourArray( 1 );
1381 sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1384 // texture coordinates
1385 size = tex_index.size();
1387 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1389 texcoord = texcoords[ tex_index[0] ];
1390 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1391 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1392 if ( tex_width > 0 ) {
1393 tmp2[0] *= (1000.0 / tex_width);
1395 if ( tex_height > 0 ) {
1396 tmp2[1] *= (1000.0 / tex_height);
1399 } else if ( size > 1 ) {
1400 for ( i = 0; i < size; ++i ) {
1401 texcoord = texcoords[ tex_index[i] ];
1402 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1403 if ( tex_width > 0 ) {
1404 tmp2[0] *= (1000.0 / tex_width);
1406 if ( tex_height > 0 ) {
1407 tmp2[1] *= (1000.0 / tex_height);
1413 ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1415 // lookup the state record
1417 leaf->setState( state );
1419 if ( calc_lights ) {
1420 if ( coverage > 0.0 ) {
1421 if ( coverage < 10000.0 ) {
1422 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1423 << coverage << ", pushing up to 10000");
1426 gen_random_surface_points(leaf, lights, coverage);
1434 // Load an Binary obj file
1435 bool fgBinObjLoad( const string& path, const bool is_base,
1437 double *bounding_radius,
1438 ssgBranch* geometry,
1439 ssgBranch* rwy_lights,
1440 ssgVertexArray *ground_lights )
1443 bool use_random_objects =
1444 fgGetBool("/sim/rendering/random-objects", true);
1446 if ( ! obj.read_bin( path ) ) {
1450 geometry->setName( (char *)path.c_str() );
1453 // reference point (center offset/bounding sphere)
1454 *center = obj.get_gbs_center();
1455 *bounding_radius = obj.get_gbs_radius();
1459 point_list nodes = obj.get_wgs84_nodes();
1460 point_list colors = obj.get_colors();
1461 point_list normals = obj.get_normals();
1462 point_list texcoords = obj.get_texcoords();
1464 string material, tmp_mat;
1465 int_list vertex_index;
1466 int_list normal_index;
1470 bool is_lighting = false;
1473 string_list pt_materials = obj.get_pt_materials();
1474 group_list pts_v = obj.get_pts_v();
1475 group_list pts_n = obj.get_pts_n();
1476 for ( i = 0; i < (int)pts_v.size(); ++i ) {
1477 // cout << "pts_v.size() = " << pts_v.size() << endl;
1478 tmp_mat = pt_materials[i];
1479 if ( tmp_mat.substr(0, 3) == "RWY" ) {
1480 material = "LIGHTS";
1485 vertex_index = pts_v[i];
1486 normal_index = pts_n[i];
1488 ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1489 nodes, normals, texcoords,
1490 vertex_index, normal_index, tex_index,
1491 false, ground_lights );
1493 if ( is_lighting ) {
1494 float ranges[] = { 0, 12000 };
1495 leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1496 ssgRangeSelector * lod = new ssgRangeSelector;
1497 lod->setRanges(ranges, 2);
1499 rwy_lights->addKid(lod);
1501 geometry->addKid( leaf );
1505 // generate triangles
1506 string_list tri_materials = obj.get_tri_materials();
1507 group_list tris_v = obj.get_tris_v();
1508 group_list tris_n = obj.get_tris_n();
1509 group_list tris_tc = obj.get_tris_tc();
1510 for ( i = 0; i < (int)tris_v.size(); ++i ) {
1511 material = tri_materials[i];
1512 vertex_index = tris_v[i];
1513 normal_index = tris_n[i];
1514 tex_index = tris_tc[i];
1515 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
1516 nodes, normals, texcoords,
1517 vertex_index, normal_index, tex_index,
1518 is_base, ground_lights );
1520 if (use_random_objects)
1521 gen_random_surface_objects(leaf, geometry, center, material);
1522 geometry->addKid( leaf );
1526 string_list strip_materials = obj.get_strip_materials();
1527 group_list strips_v = obj.get_strips_v();
1528 group_list strips_n = obj.get_strips_n();
1529 group_list strips_tc = obj.get_strips_tc();
1530 for ( i = 0; i < (int)strips_v.size(); ++i ) {
1531 material = strip_materials[i];
1532 vertex_index = strips_v[i];
1533 normal_index = strips_n[i];
1534 tex_index = strips_tc[i];
1535 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
1536 nodes, normals, texcoords,
1537 vertex_index, normal_index, tex_index,
1538 is_base, ground_lights );
1540 if (use_random_objects)
1541 gen_random_surface_objects(leaf, geometry, center, material);
1542 geometry->addKid( leaf );
1546 string_list fan_materials = obj.get_fan_materials();
1547 group_list fans_v = obj.get_fans_v();
1548 group_list fans_n = obj.get_fans_n();
1549 group_list fans_tc = obj.get_fans_tc();
1550 for ( i = 0; i < (int)fans_v.size(); ++i ) {
1551 material = fan_materials[i];
1552 vertex_index = fans_v[i];
1553 normal_index = fans_n[i];
1554 tex_index = fans_tc[i];
1555 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
1556 nodes, normals, texcoords,
1557 vertex_index, normal_index, tex_index,
1558 is_base, ground_lights );
1559 if (use_random_objects)
1560 gen_random_surface_objects(leaf, geometry, center, material);
1561 geometry->addKid( leaf );