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;
424 * Fill in a triangle with randomly-placed objects.
426 * This method is invoked by a callback when the triangle is in range
427 * but not yet populated.
429 * @param p1 The first vertex of the triangle.
430 * @param p2 The second vertex of the triangle.
431 * @param p3 The third vertex of the triangle.
432 * @param mat The triangle's material.
433 * @param object_index The index of the random object in the triangle.
434 * @param branch The branch where the objects should be added.
435 * @param lon_deg The longitude of the surface center, in degrees.
436 * @param lat_deg The latitude of the surface center, in degrees.
439 fill_in_triangle (float * p1, float * p2, float * p3,
440 FGNewMat::ObjectGroup * object_group, ssgBranch * branch,
441 double lon_deg, double lat_deg)
443 // generate a repeatable random seed
444 sg_srandom((unsigned int)(p1[0]));
446 int nObjects = object_group->get_object_count();
447 for (int i = 0; i < nObjects; i++) {
448 FGNewMat::Object * object = object_group->get_object(i);
451 (p1[0] + p2[0] + p3[0]) / 3.0,
452 (p1[1] + p2[1] + p3[1]) / 3.0,
453 (p1[2] + p2[2] + p3[2]) / 3.0);
454 double area = sgTriArea(p1, p2, p3);
455 double num = area / object->get_coverage_m2();
457 // place an object each unit of area
458 while ( num > 1.0 ) {
459 add_object_to_triangle(p1, p2, p3, center, lon_deg, lat_deg,
463 // for partial units of area, use a zombie door method to
464 // create the proper random chance of an object being created
467 if ( sg_random() <= num ) {
468 // a zombie made it through our door
469 add_object_to_triangle(p1, p2, p3, center, lon_deg, lat_deg,
477 * SSG callback for an in-range triangle of randomly-placed objects.
479 * This pretraversal callback is attached to a branch that is traversed
480 * only when a triangle is in range. If the triangle is not currently
481 * populated with randomly-placed objects, this callback will populate
484 * @param entity The entity to which the callback is attached (not used).
485 * @param mask The entity's traversal mask (not used).
486 * @return Always 1, to allow traversal and culling to continue.
489 tri_in_range_callback (ssgEntity * entity, int mask)
491 TriUserData * data = (TriUserData *)entity->getUserData();
492 if (!data->is_filled_in) {
493 fill_in_triangle(data->p1, data->p2, data->p3, data->object_group,
494 data->branch, data->lon_deg, data->lat_deg);
495 data->is_filled_in = true;
502 * SSG callback for an out-of-range triangle of randomly-placed objects.
504 * This pretraversal callback is attached to a branch that is traversed
505 * only when a triangle is out of range. If the triangle is currently
506 * populated with randomly-placed objects, the objects will be removed.
509 * @param entity The entity to which the callback is attached (not used).
510 * @param mask The entity's traversal mask (not used).
511 * @return Always 0, to prevent any further traversal or culling.
514 tri_out_of_range_callback (ssgEntity * entity, int mask)
516 TriUserData * data = (TriUserData *)entity->getUserData();
517 if (data->is_filled_in) {
518 data->branch->removeAllKids();
519 data->is_filled_in = false;
526 * Singleton ssgEntity with a dummy bounding sphere, to fool culling.
528 * This forces the in-range and out-of-range branches to be visited
529 * when appropriate, even if they have no children. It's ugly, but
530 * it works and seems fairly efficient (since branches can still
531 * be culled when they're out of the view frustum).
533 class DummyBSphereEntity : public ssgEntity
536 virtual ~DummyBSphereEntity () {}
537 virtual void recalcBSphere () { bsphere_is_invalid = false; }
538 virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
539 virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
540 virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
541 virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
542 static ssgEntity * get_entity ();
544 DummyBSphereEntity ()
546 bsphere.setCenter(0, 0, 0);
547 bsphere.setRadius(1000);
549 static DummyBSphereEntity * entity;
553 DummyBSphereEntity * DummyBSphereEntity::entity = 0;
557 * Ensure that only one copy of the dummy entity exists.
559 * @return The singleton copy of the DummyBSphereEntity.
562 DummyBSphereEntity::get_entity ()
565 entity = new DummyBSphereEntity;
573 * Calculate the bounding radius of a triangle from its center.
575 * @param center The triangle center.
576 * @param p1 The first point in the triangle.
577 * @param p2 The second point in the triangle.
578 * @param p3 The third point in the triangle.
579 * @return The greatest distance any point lies from the center.
582 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
584 return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
585 sgDistanceSquaredVec3(center, p2),
586 sgDistanceSquaredVec3(center, p3) ) );
591 * Set up a triangle for randomly-placed objects.
593 * No objects will be added unless the triangle comes into range.
595 * @param leaf The leaf containing the data for the terrain surface.
596 * @param tri_index The index of the triangle in the leaf.
597 * @param mat The material data for the triangle.
598 * @param branch The branch to which the randomly-placed objects
600 * @param lon_deg The longitude of the surface center, in degrees.
601 * @param lat_deg The latitude of the surface center, in degrees.
604 setup_triangle (float * p1, float * p2, float * p3,
605 FGNewMat * mat, ssgBranch * branch,
606 double lon_deg, double lat_deg)
608 // Set up a single center point for LOD
611 (p1[0] + p2[0] + p3[0]) / 3.0,
612 (p1[1] + p2[1] + p3[1]) / 3.0,
613 (p1[2] + p2[2] + p3[2]) / 3.0);
615 // maximum radius of an object from center.
616 double bounding_radius = get_bounding_radius(center, p1, p2, p3);
618 // Set up a transformation to the center
619 // point, so that everything else can
620 // be specified relative to it.
621 ssgTransform * location = new ssgTransform;
623 sgMakeTransMat4(TRANS, center);
624 location->setTransform(TRANS);
625 branch->addKid(location);
627 // Iterate through all the object types.
628 int num_groups = mat->get_object_group_count();
629 for (int i = 0; i < num_groups; i++) {
630 // Look up the random object.
631 FGNewMat::ObjectGroup * group = mat->get_object_group(i);
633 // Set up the range selector for the entire
634 // triangle; note that we use the object
635 // range plus the bounding radius here, to
636 // allow for objects far from the center.
638 group->get_range_m() + bounding_radius,
640 ssgRangeSelector * lod = new ssgRangeSelector;
641 lod->setRanges(ranges, 3);
642 location->addKid(lod);
644 // Create the in-range and out-of-range
646 ssgBranch * in_range = new ssgBranch;
647 ssgBranch * out_of_range = new ssgBranch;
649 // Set up the user data for if/when
650 // the random objects in this triangle
652 TriUserData * data = new TriUserData;
653 data->is_filled_in = false;
657 data->object_group = group;
658 data->branch = in_range;
659 data->lon_deg = lon_deg;
660 data->lat_deg = lat_deg;
662 // Set up the in-range node.
663 in_range->setUserData(data);
664 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
665 tri_in_range_callback);
666 lod->addKid(in_range);
668 // Set up the out-of-range node.
669 out_of_range->setUserData(data);
670 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
671 tri_out_of_range_callback);
672 out_of_range->addKid(DummyBSphereEntity::get_entity());
673 lod->addKid(out_of_range);
679 * User data for populating tiles when they come in range.
681 class TileUserData : public ssgBase
694 * SSG callback for an in-range tile of randomly-placed objects.
696 * This pretraversal callback is attached to a branch that is
697 * traversed only when a tile is in range. If the tile is not
698 * currently prepared to be populated with randomly-placed objects,
699 * this callback will prepare it (actual population is handled by
700 * the tri_in_range_callback for individual triangles).
702 * @param entity The entity to which the callback is attached (not used).
703 * @param mask The entity's traversal mask (not used).
704 * @return Always 1, to allow traversal and culling to continue.
707 tile_in_range_callback (ssgEntity * entity, int mask)
709 TileUserData * data = (TileUserData *)entity->getUserData();
711 if (!data->is_filled_in) {
712 // Iterate through all the triangles
713 // and populate them.
714 int num_tris = data->leaf->getNumTriangles();
715 for ( int i = 0; i < num_tris; ++i ) {
717 data->leaf->getTriangle(i, &n1, &n2, &n3);
718 setup_triangle(data->leaf->getVertex(n1),
719 data->leaf->getVertex(n2),
720 data->leaf->getVertex(n3),
721 data->mat, data->branch, data->lon_deg, data->lat_deg);
723 data->is_filled_in = true;
730 * SSG callback for an out-of-range tile of randomly-placed objects.
732 * This pretraversal callback is attached to a branch that is
733 * traversed only when a tile is out of range. If the tile is
734 * currently prepared to be populated with randomly-placed objects (or
735 * is actually populated), the objects will be removed.
737 * @param entity The entity to which the callback is attached (not used).
738 * @param mask The entity's traversal mask (not used).
739 * @return Always 0, to prevent any further traversal or culling.
742 tile_out_of_range_callback (ssgEntity * entity, int mask)
744 TileUserData * data = (TileUserData *)entity->getUserData();
745 if (data->is_filled_in) {
746 data->branch->removeAllKids();
747 data->is_filled_in = false;
754 * Randomly place objects on a surface.
756 * The leaf node provides the geometry of the surface, while the
757 * material provides the objects and placement density. Latitude
758 * and longitude are required so that the objects can be rotated
759 * to the world-up vector. This function does not actually add
760 * any objects; instead, it attaches an ssgRangeSelector to the
761 * branch with callbacks to generate the objects when needed.
763 * @param leaf The surface where the objects should be placed.
764 * @param branch The branch that will hold the randomly-placed objects.
765 * @param center The center of the tile in FlightGear coordinates.
766 * @param lon_deg The longitude of the surface center, in degrees.
767 * @param lat_deg The latitude of the surface center, in degrees.
768 * @param material_name The name of the surface's material.
771 gen_random_surface_objects (ssgLeaf *leaf,
774 const string &material_name)
776 // If the surface has no triangles, return
778 int num_tris = leaf->getNumTriangles();
782 // Get the material for this surface.
783 FGNewMat * mat = material_lib.find(material_name);
785 SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
789 // If the material has no randomly-placed
790 // objects, return now.
791 if (mat->get_object_group_count() < 1)
794 // Calculate the geodetic centre of
795 // the tile, for aligning automatic
797 double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
798 Point3D geoc = sgCartToPolar3d(*center);
799 lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
800 sgGeocToGeod(geoc.lat(), geoc.radius(),
801 &lat_rad, &alt_m, &sl_radius_m);
802 lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
805 // max random object range: 20000m
806 float ranges[] = {0, 20000, 1000000};
807 ssgRangeSelector * lod = new ssgRangeSelector;
808 lod->setRanges(ranges, 3);
811 // Create the in-range and out-of-range
813 ssgBranch * in_range = new ssgBranch;
814 ssgBranch * out_of_range = new ssgBranch;
815 lod->addKid(in_range);
816 lod->addKid(out_of_range);
818 TileUserData * data = new TileUserData;
819 data->is_filled_in = false;
822 data->branch = in_range;
823 data->lon_deg = lon_deg;
824 data->lat_deg = lat_deg;
826 in_range->setUserData(data);
827 in_range->setTravCallback(SSG_CALLBACK_PRETRAV, tile_in_range_callback);
828 out_of_range->setUserData(data);
829 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
830 tile_out_of_range_callback);
831 out_of_range->addKid(DummyBSphereEntity::get_entity());
836 ////////////////////////////////////////////////////////////////////////
838 ////////////////////////////////////////////////////////////////////////
841 // Load an Ascii obj file
842 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
843 ssgVertexArray *lights, const bool is_base)
845 FGNewMat *newmat = NULL;
849 // sgVec3 approx_normal;
850 // double normal[3], scale = 0.0;
851 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
852 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
853 // GLint display_list = 0;
855 bool in_faces = false;
856 int vncount, vtcount;
857 int n1 = 0, n2 = 0, n3 = 0;
859 // int last1 = 0, last2 = 0;
864 double scenery_version = 0.0;
865 double tex_width = 1000.0, tex_height = 1000.0;
866 bool shared_done = false;
867 int_list fan_vertices;
868 int_list fan_tex_coords;
870 ssgSimpleState *state = NULL;
871 sgVec3 *vtlist, *vnlist;
874 ssgBranch *tile = new ssgBranch () ;
876 tile -> setName ( (char *)path.c_str() ) ;
878 // Attempt to open "path.gz" or "path"
879 sg_gzifstream in( path );
880 if ( ! in.is_open() ) {
881 SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
882 SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
889 shading = fgGetBool("/sim/rendering/shading");
897 t->bounding_radius = 0.0;
901 // StopWatch stopwatch;
902 // stopwatch.start();
904 // ignore initial comments and blank lines. (priming the pump)
905 // in >> skipcomment;
912 while ( in.get(c) && c != '\0' ) {
915 while ( ! in.eof() ) {
920 if ( in.get( c ) && c == '#' ) {
921 // process a comment line
923 // getline( in, line );
924 // cout << "comment = " << line << endl;
928 if ( token == "Version" ) {
929 // read scenery versions number
930 in >> scenery_version;
931 // cout << "scenery_version = " << scenery_version << endl;
932 if ( scenery_version > 0.4 ) {
933 SG_LOG( SG_TERRAIN, SG_ALERT,
934 "\nYou are attempting to load a tile format that\n"
935 << "is newer than this version of flightgear can\n"
936 << "handle. You should upgrade your copy of\n"
937 << "FlightGear to the newest version. For\n"
938 << "details, please see:\n"
939 << "\n http://www.flightgear.org\n" );
942 } else if ( token == "gbs" ) {
943 // reference point (center offset)
945 in >> t->center >> t->bounding_radius;
949 in >> junk1 >> junk2;
952 // cout << "center = " << center
953 // << " radius = " << t->bounding_radius << endl;
954 } else if ( token == "bs" ) {
955 // reference point (center offset)
959 in >> junk1 >> junk2;
960 } else if ( token == "usemtl" ) {
961 // material property specification
963 // if first usemtl with shared_done = false, then set
964 // shared_done true and build the ssg shared lists
965 if ( ! shared_done ) {
967 if ( (int)nodes.size() != vncount ) {
968 SG_LOG( SG_TERRAIN, SG_ALERT,
969 "Tile has mismatched nodes = " << nodes.size()
970 << " and normals = " << vncount << " : "
976 vtlist = new sgVec3 [ nodes.size() ];
977 t->vec3_ptrs.push_back( vtlist );
978 vnlist = new sgVec3 [ vncount ];
979 t->vec3_ptrs.push_back( vnlist );
980 tclist = new sgVec2 [ vtcount ];
981 t->vec2_ptrs.push_back( tclist );
983 for ( i = 0; i < (int)nodes.size(); ++i ) {
984 sgSetVec3( vtlist[i],
985 nodes[i][0], nodes[i][1], nodes[i][2] );
987 for ( i = 0; i < vncount; ++i ) {
988 sgSetVec3( vnlist[i],
993 for ( i = 0; i < vtcount; ++i ) {
994 sgSetVec2( tclist[i],
1000 // display_list = xglGenLists(1);
1001 // xglNewList(display_list, GL_COMPILE);
1002 // printf("xglGenLists(); xglNewList();\n");
1005 // scan the material line
1008 // find this material in the properties list
1010 newmat = material_lib.find( material );
1011 if ( newmat == NULL ) {
1012 // see if this is an on the fly texture
1014 int pos = file.rfind( "/" );
1015 file = file.substr( 0, pos );
1016 // cout << "current file = " << file << endl;
1019 // cout << "current file = " << file << endl;
1020 if ( ! material_lib.add_item( file ) ) {
1021 SG_LOG( SG_TERRAIN, SG_ALERT,
1022 "Ack! unknown usemtl name = " << material
1023 << " in " << path );
1025 // locate our newly created material
1026 newmat = material_lib.find( material );
1027 if ( newmat == NULL ) {
1028 SG_LOG( SG_TERRAIN, SG_ALERT,
1029 "Ack! bad on the fly materia create = "
1030 << material << " in " << path );
1035 if ( newmat != NULL ) {
1036 // set the texture width and height values for this
1038 tex_width = newmat->get_xsize();
1039 tex_height = newmat->get_ysize();
1040 state = newmat->get_state();
1041 coverage = newmat->get_light_coverage();
1042 // cout << "(w) = " << tex_width << " (h) = "
1043 // << tex_width << endl;
1048 // unknown comment, just gobble the input until the
1058 // cout << "token = " << token << endl;
1060 if ( token == "vn" ) {
1062 if ( vncount < FG_MAX_NODES ) {
1063 in >> normals[vncount][0]
1064 >> normals[vncount][1]
1065 >> normals[vncount][2];
1068 SG_LOG( SG_TERRAIN, SG_ALERT,
1069 "Read too many vertex normals in " << path
1070 << " ... dying :-(" );
1073 } else if ( token == "vt" ) {
1074 // vertex texture coordinate
1075 if ( vtcount < FG_MAX_NODES*3 ) {
1076 in >> tex_coords[vtcount][0]
1077 >> tex_coords[vtcount][1];
1080 SG_LOG( SG_TERRAIN, SG_ALERT,
1081 "Read too many vertex texture coords in " << path
1086 } else if ( token == "v" ) {
1088 if ( t->ncount < FG_MAX_NODES ) {
1089 /* in >> nodes[t->ncount][0]
1090 >> nodes[t->ncount][1]
1091 >> nodes[t->ncount][2]; */
1093 nodes.push_back(node);
1098 SG_LOG( SG_TERRAIN, SG_ALERT,
1099 "Read too many nodes in " << path
1100 << " ... dying :-(");
1103 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1104 // triangle fan, strip, or individual face
1105 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1107 fan_vertices.clear();
1108 fan_tex_coords.clear();
1111 // xglBegin(GL_TRIANGLE_FAN);
1114 fan_vertices.push_back( n1 );
1115 // xglNormal3dv(normals[n1]);
1116 if ( in.get( c ) && c == '/' ) {
1118 fan_tex_coords.push_back( tex );
1119 if ( scenery_version >= 0.4 ) {
1120 if ( tex_width > 0 ) {
1121 tclist[tex][0] *= (1000.0 / tex_width);
1123 if ( tex_height > 0 ) {
1124 tclist[tex][1] *= (1000.0 / tex_height);
1127 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1128 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1131 pp = local_calc_tex_coords(nodes[n1], center);
1133 // xglTexCoord2f(pp.x(), pp.y());
1134 // xglVertex3dv(nodes[n1].get_n());
1137 fan_vertices.push_back( n2 );
1138 // xglNormal3dv(normals[n2]);
1139 if ( in.get( c ) && c == '/' ) {
1141 fan_tex_coords.push_back( tex );
1142 if ( scenery_version >= 0.4 ) {
1143 if ( tex_width > 0 ) {
1144 tclist[tex][0] *= (1000.0 / tex_width);
1146 if ( tex_height > 0 ) {
1147 tclist[tex][1] *= (1000.0 / tex_height);
1150 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1151 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1154 pp = local_calc_tex_coords(nodes[n2], center);
1156 // xglTexCoord2f(pp.x(), pp.y());
1157 // xglVertex3dv(nodes[n2].get_n());
1159 // read all subsequent numbers until next thing isn't a number
1166 if ( ! isdigit(c) || in.eof() ) {
1171 fan_vertices.push_back( n3 );
1172 // cout << " triangle = "
1173 // << n1 << "," << n2 << "," << n3
1175 // xglNormal3dv(normals[n3]);
1176 if ( in.get( c ) && c == '/' ) {
1178 fan_tex_coords.push_back( tex );
1179 if ( scenery_version >= 0.4 ) {
1180 if ( tex_width > 0 ) {
1181 tclist[tex][0] *= (1000.0 / tex_width);
1183 if ( tex_height > 0 ) {
1184 tclist[tex][1] *= (1000.0 / tex_height);
1187 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1188 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1191 pp = local_calc_tex_coords(nodes[n3], center);
1193 // xglTexCoord2f(pp.x(), pp.y());
1194 // xglVertex3dv(nodes[n3].get_n());
1196 if ( (token == "tf") || (token == "f") ) {
1209 // build the ssg entity
1210 int size = (int)fan_vertices.size();
1211 ssgVertexArray *vl = new ssgVertexArray( size );
1212 ssgNormalArray *nl = new ssgNormalArray( size );
1213 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1214 ssgColourArray *cl = new ssgColourArray( 1 );
1217 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1222 for ( i = 0; i < size; ++i ) {
1223 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1226 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1229 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1233 ssgLeaf *leaf = NULL;
1234 if ( token == "tf" ) {
1237 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1238 } else if ( token == "ts" ) {
1241 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1242 } else if ( token == "f" ) {
1245 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1247 // leaf->makeDList();
1248 leaf->setState( state );
1250 tile->addKid( leaf );
1253 if ( coverage > 0.0 ) {
1254 if ( coverage < 10000.0 ) {
1255 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1256 << coverage << ", pushing up to 10000");
1259 gen_random_surface_points(leaf, lights, coverage);
1263 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in "
1264 << path << " = " << token );
1267 // eat white space before start of while loop so if we are
1268 // done with useful input it is noticed before hand.
1277 // stopwatch.stop();
1278 // SG_LOG( SG_TERRAIN, SG_DEBUG,
1279 // "Loaded " << path << " in "
1280 // << stopwatch.elapsedSeconds() << " seconds" );
1286 ssgLeaf *gen_leaf( const string& path,
1287 const GLenum ty, const string& material,
1288 const point_list& nodes, const point_list& normals,
1289 const point_list& texcoords,
1290 const int_list node_index,
1291 const int_list normal_index,
1292 const int_list& tex_index,
1293 const bool calc_lights, ssgVertexArray *lights )
1295 double tex_width = 1000.0, tex_height = 1000.0;
1296 ssgSimpleState *state = NULL;
1297 float coverage = -1;
1299 FGNewMat *newmat = material_lib.find( material );
1300 if ( newmat == NULL ) {
1301 // see if this is an on the fly texture
1303 int pos = file.rfind( "/" );
1304 file = file.substr( 0, pos );
1305 // cout << "current file = " << file << endl;
1308 // cout << "current file = " << file << endl;
1309 if ( ! material_lib.add_item( file ) ) {
1310 SG_LOG( SG_TERRAIN, SG_ALERT,
1311 "Ack! unknown usemtl name = " << material
1312 << " in " << path );
1314 // locate our newly created material
1315 newmat = material_lib.find( material );
1316 if ( newmat == NULL ) {
1317 SG_LOG( SG_TERRAIN, SG_ALERT,
1318 "Ack! bad on the fly material create = "
1319 << material << " in " << path );
1324 if ( newmat != NULL ) {
1325 // set the texture width and height values for this
1327 tex_width = newmat->get_xsize();
1328 tex_height = newmat->get_ysize();
1329 state = newmat->get_state();
1330 coverage = newmat->get_light_coverage();
1331 // cout << "(w) = " << tex_width << " (h) = "
1332 // << tex_width << endl;
1343 int size = node_index.size();
1345 SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1348 ssgVertexArray *vl = new ssgVertexArray( size );
1350 for ( i = 0; i < size; ++i ) {
1351 node = nodes[ node_index[i] ];
1352 sgSetVec3( tmp3, node[0], node[1], node[2] );
1358 ssgNormalArray *nl = new ssgNormalArray( size );
1359 if ( normal_index.size() ) {
1360 // object file specifies normal indices (i.e. normal indices
1362 for ( i = 0; i < size; ++i ) {
1363 normal = normals[ normal_index[i] ];
1364 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1368 // use implied normal indices. normal index = vertex index.
1369 for ( i = 0; i < size; ++i ) {
1370 normal = normals[ node_index[i] ];
1371 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1377 ssgColourArray *cl = new ssgColourArray( 1 );
1378 sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1381 // texture coordinates
1382 size = tex_index.size();
1384 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1386 texcoord = texcoords[ tex_index[0] ];
1387 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1388 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1389 if ( tex_width > 0 ) {
1390 tmp2[0] *= (1000.0 / tex_width);
1392 if ( tex_height > 0 ) {
1393 tmp2[1] *= (1000.0 / tex_height);
1396 } else if ( size > 1 ) {
1397 for ( i = 0; i < size; ++i ) {
1398 texcoord = texcoords[ tex_index[i] ];
1399 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1400 if ( tex_width > 0 ) {
1401 tmp2[0] *= (1000.0 / tex_width);
1403 if ( tex_height > 0 ) {
1404 tmp2[1] *= (1000.0 / tex_height);
1410 ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1412 // lookup the state record
1414 leaf->setState( state );
1416 if ( calc_lights ) {
1417 if ( coverage > 0.0 ) {
1418 if ( coverage < 10000.0 ) {
1419 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1420 << coverage << ", pushing up to 10000");
1423 gen_random_surface_points(leaf, lights, coverage);
1431 // Load an Binary obj file
1432 bool fgBinObjLoad( const string& path, const bool is_base,
1434 double *bounding_radius,
1435 ssgBranch* geometry,
1436 ssgBranch* rwy_lights,
1437 ssgVertexArray *ground_lights )
1440 bool use_random_objects =
1441 fgGetBool("/sim/rendering/random-objects", true);
1443 if ( ! obj.read_bin( path ) ) {
1447 geometry->setName( (char *)path.c_str() );
1450 // reference point (center offset/bounding sphere)
1451 *center = obj.get_gbs_center();
1452 *bounding_radius = obj.get_gbs_radius();
1456 point_list nodes = obj.get_wgs84_nodes();
1457 point_list colors = obj.get_colors();
1458 point_list normals = obj.get_normals();
1459 point_list texcoords = obj.get_texcoords();
1461 string material, tmp_mat;
1462 int_list vertex_index;
1463 int_list normal_index;
1467 bool is_lighting = false;
1470 string_list pt_materials = obj.get_pt_materials();
1471 group_list pts_v = obj.get_pts_v();
1472 group_list pts_n = obj.get_pts_n();
1473 for ( i = 0; i < (int)pts_v.size(); ++i ) {
1474 // cout << "pts_v.size() = " << pts_v.size() << endl;
1475 tmp_mat = pt_materials[i];
1476 if ( tmp_mat.substr(0, 3) == "RWY" ) {
1477 material = "LIGHTS";
1482 vertex_index = pts_v[i];
1483 normal_index = pts_n[i];
1485 ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1486 nodes, normals, texcoords,
1487 vertex_index, normal_index, tex_index,
1488 false, ground_lights );
1490 if ( is_lighting ) {
1491 float ranges[] = { 0, 12000 };
1492 leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1493 ssgRangeSelector * lod = new ssgRangeSelector;
1494 lod->setRanges(ranges, 2);
1496 rwy_lights->addKid(lod);
1498 geometry->addKid( leaf );
1502 // generate triangles
1503 string_list tri_materials = obj.get_tri_materials();
1504 group_list tris_v = obj.get_tris_v();
1505 group_list tris_n = obj.get_tris_n();
1506 group_list tris_tc = obj.get_tris_tc();
1507 for ( i = 0; i < (int)tris_v.size(); ++i ) {
1508 material = tri_materials[i];
1509 vertex_index = tris_v[i];
1510 normal_index = tris_n[i];
1511 tex_index = tris_tc[i];
1512 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
1513 nodes, normals, texcoords,
1514 vertex_index, normal_index, tex_index,
1515 is_base, ground_lights );
1517 if (use_random_objects)
1518 gen_random_surface_objects(leaf, geometry, center, material);
1519 geometry->addKid( leaf );
1523 string_list strip_materials = obj.get_strip_materials();
1524 group_list strips_v = obj.get_strips_v();
1525 group_list strips_n = obj.get_strips_n();
1526 group_list strips_tc = obj.get_strips_tc();
1527 for ( i = 0; i < (int)strips_v.size(); ++i ) {
1528 material = strip_materials[i];
1529 vertex_index = strips_v[i];
1530 normal_index = strips_n[i];
1531 tex_index = strips_tc[i];
1532 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
1533 nodes, normals, texcoords,
1534 vertex_index, normal_index, tex_index,
1535 is_base, ground_lights );
1537 if (use_random_objects)
1538 gen_random_surface_objects(leaf, geometry, center, material);
1539 geometry->addKid( leaf );
1543 string_list fan_materials = obj.get_fan_materials();
1544 group_list fans_v = obj.get_fans_v();
1545 group_list fans_n = obj.get_fans_n();
1546 group_list fans_tc = obj.get_fans_tc();
1547 for ( i = 0; i < (int)fans_v.size(); ++i ) {
1548 material = fan_materials[i];
1549 vertex_index = fans_v[i];
1550 normal_index = fans_n[i];
1551 tex_index = fans_tc[i];
1552 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
1553 nodes, normals, texcoords,
1554 vertex_index, normal_index, tex_index,
1555 is_base, ground_lights );
1556 if (use_random_objects)
1557 gen_random_surface_objects(leaf, geometry, center, material);
1558 geometry->addKid( leaf );