]> git.mxchange.org Git - flightgear.git/blob - src/FDM/groundcache.cxx
3a944a42b5fda8007664d217ca30333621e22baf
[flightgear.git] / src / FDM / groundcache.cxx
1 // groundcache.cxx -- carries a small subset of the scenegraph near the vehicle
2 //
3 // Written by Mathias Froehlich, started Nov 2004.
4 //
5 // Copyright (C) 2004  Mathias Froehlich - Mathias.Froehlich@web.de
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #include <float.h>
25
26 #include <plib/sg.h>
27
28 #include <simgear/constants.h>
29 #include <simgear/debug/logstream.hxx>
30 #include <simgear/math/sg_geodesy.hxx>
31
32 #include <Main/globals.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scenery/tilemgr.hxx>
35 #include <AIModel/AICarrier.hxx>
36
37 #include "flight.hxx"
38 #include "groundcache.hxx"
39
40 FGGroundCache::FGGroundCache()
41 {
42   sgdSetVec3(cache_center, 0.0, 0.0, 0.0);
43   ground_radius = 0.0;
44   cache_ref_time = 0.0;
45   wire_id = 0;
46   sgdSetVec3(reference_wgs84_point, 0.0, 0.0, 0.0);
47   reference_vehicle_radius = 0.0;
48   found_ground = false;
49 }
50
51 FGGroundCache::~FGGroundCache()
52 {
53   cache_root.removeAllKids();
54 }
55
56 FGGroundCache::GroundProperty*
57 FGGroundCache::extractGroundProperty( ssgLeaf* l )
58 {
59   // FIXME: Do more ...
60   // Idea: have a get_globals() function which knows about that stuff.
61   // Or most propably read that from a configuration file,
62   // from property tree or whatever ...
63   
64   // Get ground dependent data.
65   GroundProperty *gp = new GroundProperty;
66   gp->wire_id = -1;
67   
68   FGAICarrierHardware *ud =
69     dynamic_cast<FGAICarrierHardware*>(l->getUserData());
70   if (ud) {
71     switch (ud->type) {
72     case FGAICarrierHardware::Wire:
73       gp->type = FGInterface::Wire;
74       gp->wire_id = ud->id;
75       break;
76     case FGAICarrierHardware::Catapult:
77       gp->type = FGInterface::Catapult;
78       break;
79     default:
80       gp->type = FGInterface::Solid;
81       break;
82     }
83
84     // Copy the velocity from the carrier class.
85     ud->carrier->getVelocityWrtEarth( gp->vel );
86   }
87
88   else {
89
90     // Initialize velocity field.
91     sgSetVec3( gp->vel, 0.0, 0.0, 0.0 );
92   }
93   
94   // Get the texture name and decide what ground type we have.
95   ssgState *st = l->getState();
96   if (st != NULL && st->isAKindOf(ssgTypeSimpleState())) {
97     ssgSimpleState *ss = (ssgSimpleState*)st;
98     SGPath fullPath( ss->getTextureFilename() ? ss->getTextureFilename(): "" );
99     string file = fullPath.file();
100     SGPath dirPath(fullPath.dir());
101     string category = dirPath.file();
102     
103     SG_LOG(SG_FLIGHT,SG_INFO,
104            "New triangle in cache: " << category << " " << file );
105     
106     if (category == "Runway")
107       gp->type = FGInterface::Solid;
108     else {
109       if (file == "asphault.rgb" || file == "airport.rgb")
110         gp->type = FGInterface::Solid;
111       else if (file == "water.rgb" || file == "water-lake.rgb")
112         gp->type = FGInterface::Water;
113       else if (file == "forest.rgb" || file == "cropwood.rgb")
114         gp->type = FGInterface::Forest;
115     }
116   }
117   
118   return gp;
119 }
120
121 // Test if the line given by the point on the line pt_on_line and the
122 // line direction dir intersects the sphere sp.
123 // Adapted from plib.
124 static bool
125 sgIsectSphereInfLine(const sgSphere *sp,
126                      const sgVec3 pt_on_line, const sgVec3 dir)
127 {
128   sgVec3 r ;
129   sgSubVec3 ( r, sp->getCenter(), pt_on_line ) ;
130
131   SGfloat projectedDistance = sgScalarProductVec3(r, dir);
132  
133   SGfloat dist = sgScalarProductVec3 ( r, r ) -
134     projectedDistance * projectedDistance; 
135
136   SGfloat radius = sp->getRadius();
137   return dist < radius*radius;
138 }
139
140 void
141 FGGroundCache::addAndFlattenLeaf(GLenum ty, ssgLeaf *l, ssgIndexArray *ia,
142                                  const sgMat4 xform)
143 {
144   // Extract data from the leaf which is just copied.
145   ssgVertexArray *va = ((ssgVtxTable *)l)->getVertices();
146   ssgNormalArray *na = ((ssgVtxTable *)l)->getNormals();
147   // Create a new leaf.
148   ssgVtxArray *vtxa = new ssgVtxArray( ty, va, na, 0, 0, ia );
149   // Clones data ...
150   vtxa->removeUnusedVertices();
151   // Apply transform. We won't store transforms in our cache.
152   vtxa->transform( xform );
153   // Check for magic texture names object names and such ...
154   GroundProperty *gp = extractGroundProperty( l );
155   // Assertation???
156   if ( !gp ) {
157     cerr << "Newly created cache leaf where userdata is not a Ground property!" << endl;
158   }
159   vtxa->setUserData( gp );
160   vtxa->setCullFace( l->getCullFace() );
161   
162   // Finally append to cache.
163   cache_root.addKid((ssgEntity*)vtxa);
164 }
165
166 void
167 FGGroundCache::putLineLeafIntoCache(const sgSphere *wsp, const sgMat4 xform,
168                                     ssgLeaf *l)
169 {
170   ssgIndexArray *ia = 0;
171   
172   // Lines must have special meanings.
173   // Wires and catapults are done with lines.
174   int nl = l->getNumLines();
175   for (int i = 0; i < nl; ++i) {
176     sgSphere tmp;
177     short v[2];
178     l->getLine(i, v, v+1 );
179     for (int k=0; k<2; ++k)
180       tmp.extend( l->getVertex( v[k] ) );
181     tmp.orthoXform(xform);
182     
183     if (wsp->intersects( &tmp )) {
184       if (ia == 0)
185         ia = new ssgIndexArray();
186         
187       ia->add( v[0] );
188       ia->add( v[1] );
189     }
190   }
191   if (!ia)
192     return;
193   
194   addAndFlattenLeaf(GL_LINES, l, ia, xform);
195 }
196
197 void
198 FGGroundCache::putSurfaceLeafIntoCache(const sgSphere *sp, const sgMat4 xform,
199                                        bool sphIsec, sgVec3 down, ssgLeaf *l)
200 {
201   ssgIndexArray *ia = 0;
202   
203   int nt = l->getNumTriangles();
204   for (int i = 0; i < nt; ++i) {
205     // Build up a sphere around that particular triangle-
206     sgSphere tmp;
207     short v[3];
208     l->getTriangle(i, v, v+1, v+2 );
209     for (int k=0; k<3; ++k)
210       tmp.extend( l->getVertex( v[k] ) );
211     tmp.orthoXform(xform);
212
213     // Check if the sphere around the vehicle intersects the sphere
214     // around that triangle. If so, put that triangle into the cache.
215     if (sphIsec && sp->intersects( &tmp )) {
216       if (ia == 0)
217         ia = new ssgIndexArray();
218       
219       ia->add( v[0] );
220       ia->add( v[1] );
221       ia->add( v[2] );
222     }
223     
224     // In case the cache is empty, we still provide agl computations.
225     // But then we use the old way of having a fixed elevation value for
226     // the whole lifetime of this cache.
227     if ( sgIsectSphereInfLine(&tmp, sp->getCenter(), down) ) {
228       sgVec3 tri[3];
229       for (int k=0; k<3; ++k) {
230         sgCopyVec3( tri[k], l->getVertex( v[k] ) );
231         sgXformPnt3( tri[k], xform );
232       }
233       
234       sgVec4 plane;
235       sgMakePlane( plane, tri[0], tri[1], tri[2]  );
236       sgVec3 ac_cent;
237       sgCopyVec3(ac_cent, sp->getCenter());
238       sgVec3 dst;
239       sgIsectInfLinePlane( dst, ac_cent, down, plane );
240       if ( sgPointInTriangle ( dst, tri ) ) {
241         found_ground = true;
242         sgdVec3 ddst;
243         sgdSetVec3(ddst, dst);
244         sgdAddVec3(ddst, cache_center);
245         double this_radius = sgdLengthVec3(ddst);
246         if (ground_radius < this_radius)
247           ground_radius = this_radius;
248       }
249     }
250   }
251   if (!ia)
252     return;
253   
254   addAndFlattenLeaf(GL_TRIANGLES, l, ia, xform);
255 }
256
257 // Here is the point where rotation should be handled
258 void
259 FGGroundCache::extractCacheRelativeVertex(double t, ssgVtxArray *va,
260                                           GroundProperty *gp,
261                                           short i, sgVec3 rel_pos,
262                                           sgdVec3 wgs84_vel)
263 {
264   sgCopyVec3( rel_pos, va->getVertex( i ) );
265   sgAddScaledVec3( rel_pos, gp->vel, t );
266
267   // Set velocity.
268   sgdSetVec3( wgs84_vel, gp->vel );
269 }
270
271 void
272 FGGroundCache::extractWgs84Vertex(double t, ssgVtxArray *va,
273                                   GroundProperty *gp, short i,
274                                   sgdVec3 wgs84_pos, sgdVec3 wgs84_vel)
275 {
276   sgVec3 rel_pos;
277   extractCacheRelativeVertex(t, va, gp, i, rel_pos, wgs84_vel);
278   sgdSetVec3( wgs84_pos, rel_pos );
279   sgdAddVec3( wgs84_pos, cache_center );
280 }
281
282
283 void
284 FGGroundCache::cache_fill(ssgBranch *branch, sgMat4 xform,
285                           sgSphere* sp, sgVec3 down, sgSphere* wsp)
286 {
287   // Travel through all kids.
288   ssgEntity *e;
289   for ( e = branch->getKid(0); e != NULL ; e = branch->getNextKid() ) {
290     if ( !( e->getTraversalMask() & SSGTRAV_HOT) )
291       continue;
292     if ( e->getBSphere()->isEmpty() )
293       continue;
294     
295     // Wee need to check further if either the sphere around the branch
296     // intersects the sphere around the aircraft or the line downwards from
297     // the aircraft intersects the branchs sphere.
298     sgSphere esphere = *(e->getBSphere());
299     esphere.orthoXform(xform);
300     bool wspIsec = wsp->intersects(&esphere);
301     bool downIsec = sgIsectSphereInfLine(&esphere, sp->getCenter(), down);
302     if (!wspIsec && !downIsec)
303       continue;
304       
305     // For branches collect up the transforms to reach that branch and
306     // call cache_fill recursively.
307     if ( e->isAKindOf( ssgTypeBranch() ) ) {
308       ssgBranch *b = (ssgBranch *)e;
309       if ( b->isAKindOf( ssgTypeTransform() ) ) {
310         // Collect up the transfors required to reach that part of
311         // the branch.
312         sgMat4 xform2;
313         sgMakeIdentMat4( xform2 );
314         ssgTransform *t = (ssgTransform*)b;
315         t->getTransform( xform2 );
316         sgPostMultMat4( xform2, xform );
317         cache_fill( b, xform2, sp, down, wsp );
318       } else
319         cache_fill( b, xform, sp, down, wsp );
320     }
321    
322     // For leafs, check each triangle for intersection.
323     // This will minimize the number of vertices/triangles in the cache.
324     else if (e->isAKindOf(ssgTypeLeaf())) {
325       // Since we reach that leaf if we have an intersection with the
326       // most propably bigger wire/catapult cache sphere, we need to check
327       // that here, if the smaller cache for the surface has a chance for hits.
328       // Also, if the spheres do not intersect compute a croase agl value
329       // by following the line downwards originating at the aircraft.
330       bool spIsec = sp->intersects(&esphere);
331       putSurfaceLeafIntoCache(sp, xform, spIsec, down, (ssgLeaf *)e);
332
333       // If we are here, we need to put all special hardware here into
334       // the cache.
335       if (wspIsec)
336         putLineLeafIntoCache(wsp, xform, (ssgLeaf *)e);
337     }
338   }
339 }
340
341 bool
342 FGGroundCache::prepare_ground_cache(double ref_time, const double pt[3],
343                                       double rad)
344 {
345   // Empty cache.
346   cache_root.removeAllKids();
347   ground_radius = 0.0;
348   found_ground = false;
349
350   // Store the parameters we used to build up that cache.
351   sgdCopyVec3(reference_wgs84_point, pt);
352   reference_vehicle_radius = rad;
353   // Store the time reference used to compute movements of moving triangles.
354   cache_ref_time = ref_time;
355
356   // The center of the cache.
357   sgdCopyVec3(cache_center, pt);
358   
359   sgVec3 zero;
360   sgZeroVec3(zero);
361   // Prepare sphere around the aircraft.
362   sgSphere acSphere;
363   acSphere.setRadius(rad);
364   acSphere.setCenter(zero);
365
366   // Prepare bigger sphere around the aircraft.
367   // This one is required for reliably finding wires we have caught but
368   // have already left the hopefully smaller sphere for the ground reactions.
369   const double max_wire_dist = 300.0;
370   sgSphere wireSphere;
371   wireSphere.setRadius(max_wire_dist < rad ? rad : max_wire_dist);
372   wireSphere.setCenter(zero);
373
374   // Down vector. Is used for croase agl computations when we are far enough
375   // from ground that we have an empty cache.
376   sgVec3 down;
377   sgSetVec3(down, -pt[0], -pt[1], -pt[2]);
378   sgNormalizeVec3(down);
379
380   // We need the offset to the scenery scenery center.
381   sgdVec3 doffset;
382   Point3D psc = globals->get_tile_mgr()->get_current_center();
383   sgdSetVec3(doffset, psc[0], psc[1], psc[2]);
384   sgdSubVec3(doffset, doffset, pt);
385
386   // We collaps all transforms we need to reach a particular leaf.
387   // The leafs itself will be then transformed later.
388   // So our cache is just flat.
389   // For leafs which are moving (carriers surface, etc ...)
390   // we will later store a speed in the GroundType class. We can then apply
391   // some translations to that nodes according to the time which has passed
392   // compared to that snapshot.
393   sgVec3 offset;
394   sgSetVec3(offset, doffset[0], doffset[1], doffset[2]);
395   sgMat4 xform;
396   sgMakeTransMat4(xform, offset);
397
398
399   // Walk the terrain branch for now.
400   ssgBranch *terrain = globals->get_scenery()->get_scene_graph();
401   cache_fill(terrain, xform, &acSphere, down, &wireSphere);
402
403   // some stats
404   SG_LOG(SG_FLIGHT,SG_INFO, "prepare_ground_cache(): ac radius = " << rad
405          << ", # leafs = " << cache_root.getNumKids()
406          << ", ground_radius = " << ground_radius );
407
408   // If the ground radius is still below 5e6 meters, then we do not yet have
409   // any scenery.
410   found_ground = found_ground && 5e6 < ground_radius;
411   if (!found_ground)
412     SG_LOG(SG_FLIGHT, SG_WARN, "prepare_ground_cache(): trying to build cache "
413            "without any scenery below the aircraft" );
414
415   return found_ground;
416 }
417
418 bool
419 FGGroundCache::is_valid(double *ref_time, double pt[3], double *rad)
420 {
421   sgdCopyVec3(pt, reference_wgs84_point);
422   *rad = reference_vehicle_radius;
423   *ref_time = cache_ref_time;
424   return found_ground;
425 }
426
427 double
428 FGGroundCache::get_cat(double t, const double dpt[3],
429                          double end[2][3], double vel[2][3])
430 {
431   // start with a distance of 1e10 meters...
432   double dist = 1e10;
433
434   // Time difference to the reference time.
435   t -= cache_ref_time;
436
437   // We know that we have a flat cache ...
438   ssgEntity *e;
439   for ( e = cache_root.getKid(0); e != NULL ; e = cache_root.getNextKid() ) {
440     // We just know that, because we build that ourselfs ...
441     ssgVtxArray *va = (ssgVtxArray *)e;
442     // Only lines are interresting ...
443     if (va->getPrimitiveType() != GL_LINES)
444       continue;
445     GroundProperty *gp = static_cast<GroundProperty*>(va->getUserData());
446     // Check if we have a catapult ...
447     if ( gp->type != FGInterface::Catapult )
448       continue;
449
450     int nl = va->getNumLines();
451     for (int i=0; i < nl; ++i) {
452       sgdLineSegment3 ls;
453       sgdVec3 lsVel[2];
454       short vi[2];
455       va->getLine(i, vi, vi+1 );
456       extractWgs84Vertex(t, va, gp, vi[0], ls.a, lsVel[0]);
457       extractWgs84Vertex(t, va, gp, vi[1], ls.b, lsVel[1]);
458       
459       double this_dist = sgdDistSquaredToLineSegmentVec3( ls, dpt );
460       if (this_dist < dist) {
461         dist = this_dist;
462         
463         // end[0] is the end where the cat starts.
464         // end[1] is the end where the cat ends.
465         // The carrier code takes care of that ordering.
466         sgdCopyVec3( end[0], ls.a );
467         sgdCopyVec3( end[1], ls.b );
468         sgdCopyVec3( vel[0], lsVel[0] );
469         sgdCopyVec3( vel[1], lsVel[1] );
470       }
471     }
472   }
473
474   // At the end take the root, we only computed squared distances ...
475   return sqrt(dist);
476 }
477
478 bool
479 FGGroundCache::get_agl(double t, const double dpt[3],
480                          double contact[3], double normal[3], double vel[3],
481                          int *type, double *loadCapacity,
482                          double *frictionFactor, double *agl)
483 {
484   bool ret = false;
485
486   *type = FGInterface::Unknown;
487 //   *agl = 0.0;
488   *loadCapacity = DBL_MAX;
489   *frictionFactor = 1.0;
490   sgdSetVec3( vel, 0.0, 0.0, 0.0 );
491   sgdSetVec3( contact, 0.0, 0.0, 0.0 );
492   sgdSetVec3( normal, 0.0, 0.0, 0.0 );
493
494   // Time difference to th reference time.
495   t -= cache_ref_time;
496
497   // The double valued point we start to search for intersection.
498   sgdVec3 tmp;
499   sgdSubVec3( tmp, dpt, cache_center );
500   sgVec3 pt;
501   sgSetVec3( pt, tmp );
502
503   // The search direction
504   sgVec3 dir;
505   sgSetVec3( dir, -dpt[0], -dpt[1], -dpt[2] );
506
507   // Initialize to something sensible
508   double sqdist = DBL_MAX;
509
510   // We know that we have a flat cache ...
511   // We just know that, because we build that ourselfs ...
512   ssgEntity *e;
513   for ( e = cache_root.getKid(0) ; e != NULL ; e = cache_root.getNextKid() ) {
514     // We just know that, because we build that ourselfs ...
515     ssgVtxArray *va = (ssgVtxArray *)e;
516     // AGL computations are done with triangle/surface leafs.
517     if (va->getPrimitiveType() != GL_TRIANGLES)
518       continue;
519     ssgBase *gpb = va->getUserData();
520     // Assertation???
521     if ( !gpb ) {
522       cerr << "Found cache leaf without userdata!" << endl;
523       continue;
524     }
525     GroundProperty *gp = static_cast<GroundProperty*>(gpb);
526
527     int nt = va->getNumTriangles();
528     for (int i=0; i < nt; ++i) {
529       short vi[3];
530       va->getTriangle( i, vi, vi+1, vi+2 );
531       
532       sgVec3 tri[3];
533       sgdVec3 dvel[3];
534       for (int k=0; k<3; ++k)
535         extractCacheRelativeVertex(t, va, gp, vi[k], tri[k], dvel[k]);
536       sgVec4 plane;
537       sgMakePlane( plane, tri[0], tri[1], tri[2] );
538       
539       // Check for intersection.
540       sgVec3 isecpoint;
541       if ( sgIsectInfLinePlane( isecpoint, pt, dir, plane ) &&
542            sgPointInTriangle3( isecpoint, tri ) ) {
543         // Only accept surfaces with the normal pointing upwards.
544         // For double sided surfaces flip the normal in this case.
545         float dirDot = sgScalarProductVec3(plane, dir);
546         if ( dirDot >= 0 && va->getCullFace() == 1 ) {
547           sgScaleVec4( plane, -1 );
548           dirDot = -dirDot;
549         }
550
551         // Check for the closest intersection point.
552         // FIXME: is this the right one?
553         double newSqdist = sgDistanceSquaredVec3( isecpoint, pt );
554         if ( newSqdist < sqdist && dirDot < 0 ) {
555           sqdist = newSqdist;
556           ret = true;
557           // Save the new potential intersection point.
558           sgdSetVec3( contact, isecpoint );
559           sgdAddVec3( contact, cache_center );
560           // The first three values in the vector are the plane normal.
561           sgdSetVec3( normal, plane );
562           // Remormalize that as double, else it *can* have surprising effects
563           // when used as plane normal together with a 6000000m offset in a
564           // plane equation.
565           sgdNormalizeVec3( normal );
566           // The velocity wrt earth.
567           /// FIXME: only true for non rotating objects!!!!
568           sgdCopyVec3( vel, dvel[0] );
569           // Save the ground type.
570           *type = gp->type;
571           // FIXME: figure out how to get that sign ...
572 //           *agl = sqrt(sqdist);
573           *agl = sgdLengthVec3( dpt ) - sgdLengthVec3( contact );
574 //           *loadCapacity = DBL_MAX;
575 //           *frictionFactor = 1.0;
576         }
577       }
578     }
579   }
580
581   if (ret)
582     return true;
583
584   // Whenever we did not have a ground triangle for the requested point,
585   // take the ground level we found during the current cache build.
586   // This is as good as what we had before for agl.
587   double r = sgdLengthVec3( dpt );
588   sgdCopyVec3( contact, dpt );
589   sgdScaleVec3( contact, ground_radius/r );
590   sgdCopyVec3( normal, dpt );
591   sgdNormaliseVec3( normal );
592   sgdSetVec3( vel, 0.0, 0.0, 0.0 );
593   
594   // The altitude is the distance of the requested point from the
595   // contact point.
596   *agl = sgdLengthVec3( dpt ) - sgdLengthVec3( contact );
597   *type = FGInterface::Unknown;
598   *loadCapacity = DBL_MAX;
599   *frictionFactor = 1.0;
600
601   return ret;
602 }
603
604 bool FGGroundCache::caught_wire(double t, const double cpt[4][3])
605 {
606   bool ret = false;
607
608   // Time difference to the reference time.
609   t -= cache_ref_time;
610
611   bool firsttime = true;
612   sgVec4 plane[2];
613   sgVec3 tri[2][3];
614
615   // We know that we have a flat cache ...
616   ssgEntity *e;
617   for ( e = cache_root.getKid(0); e != NULL ; e = cache_root.getNextKid() ) {
618     // We just know that, because we build that ourselfs ...
619     ssgVtxArray *va = (ssgVtxArray *)e;
620     // Only lines are interresting ...
621     if (va->getPrimitiveType() != GL_LINES)
622       continue;
623     GroundProperty *gp = static_cast<GroundProperty*>(va->getUserData());
624     // Check if we have a catapult ...
625     if ( gp->type != FGInterface::Wire )
626       continue;
627
628     // Lazy compute the values required for intersectiion tests.
629     // Since we normally do not have wires in the cache this is a
630     // huge benefit.
631     if (firsttime) {
632       firsttime = false;
633       sgVec3 pt[4];
634       for (int k=0; k<4; ++k) {
635         sgdVec3 tmp;
636         sgdSubVec3( tmp, cpt[k], cache_center );
637         sgSetVec3( pt[k], tmp );
638       }
639       sgMakePlane( plane[0], pt[0], pt[1], pt[2] );
640       sgCopyVec3( tri[0][0], pt[0] );
641       sgCopyVec3( tri[0][1], pt[1] );
642       sgCopyVec3( tri[0][2], pt[2] );
643       sgMakePlane( plane[1], pt[0], pt[2], pt[3] );
644       sgCopyVec3( tri[1][0], pt[0] );
645       sgCopyVec3( tri[1][1], pt[2] );
646       sgCopyVec3( tri[1][2], pt[3] );
647     }
648     
649     int nl = va->getNumLines();
650     for (int i=0; i < nl; ++i) {
651       short vi[2];
652       va->getLine(i, vi, vi+1 );
653       sgVec3 le[2];
654       sgdVec3 dummy;
655       extractCacheRelativeVertex(t, va, gp, vi[0], le[0], dummy);
656       extractCacheRelativeVertex(t, va, gp, vi[1], le[1], dummy);
657       
658       for (int k=0; k<2; ++k) {
659         sgVec3 isecpoint;
660         float isecval = sgIsectLinesegPlane( isecpoint, le[0], le[1], plane[k] );
661         
662         if ( 0.0 <= isecval && isecval <= 1.0 &&
663              sgPointInTriangle( isecpoint, tri[k] ) ) {
664           // Store the wire id.
665           wire_id = gp->wire_id;
666           ret = true;
667         }
668       }
669     }
670   }
671
672   return ret;
673 }
674
675 bool FGGroundCache::get_wire_ends(double t, double end[2][3], double vel[2][3])
676 {
677   // Fast return if we do not have an active wire.
678   if (wire_id < 0)
679     return false;
680
681   bool ret = false;
682
683   // Time difference to th reference time.
684   t -= cache_ref_time;
685
686   // We know that we have a flat cache ...
687   ssgEntity *e;
688   for ( e = cache_root.getKid(0); e != NULL ; e = cache_root.getNextKid() ) {
689     // We just know that, because we build that ourselfs ...
690     ssgVtxArray *va = (ssgVtxArray *)e;
691     // Only lines are interresting ...
692     if (va->getPrimitiveType() != GL_LINES)
693       continue;
694     GroundProperty *gp = static_cast<GroundProperty*>(va->getUserData());
695     // Check if we have a catapult ...
696     if ( gp->type != FGInterface::Wire )
697       continue;
698     if ( gp->wire_id != wire_id )
699       continue;
700
701     // Get the line ends, that are the wire endpoints.
702     short vi[2];
703     va->getLine(0, vi, vi+1 );
704     extractWgs84Vertex(t, va, gp, vi[0], end[0], vel[0]);
705     extractWgs84Vertex(t, va, gp, vi[1], end[1], vel[1]);
706
707     ret = true;
708   }
709
710   return ret;
711 }
712
713 void FGGroundCache::release_wire(void)
714 {
715   wire_id = -1;
716 }