]> git.mxchange.org Git - flightgear.git/blob - src/FDM/groundcache.cxx
871bb56eaf5ce41fd1fa953415affedac6be55ca
[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/sg_inlines.h>
29 #include <simgear/constants.h>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/math/sg_geodesy.hxx>
32
33 #include <Main/globals.hxx>
34 #include <Scenery/scenery.hxx>
35 #include <Scenery/tilemgr.hxx>
36 #include <AIModel/AICarrier.hxx>
37
38 #include "flight.hxx"
39 #include "groundcache.hxx"
40
41 // Specialized version of sgMultMat4 needed because of mixed matrix
42 // types
43 static inline void fgMultMat4(sgdMat4 dst, sgdMat4 m1, sgMat4 m2) {
44     for ( int j = 0 ; j < 4 ; j++ ) {
45         dst[0][j] = m2[0][0] * m1[0][j] +
46                     m2[0][1] * m1[1][j] +
47                     m2[0][2] * m1[2][j] +
48                     m2[0][3] * m1[3][j] ;
49
50         dst[1][j] = m2[1][0] * m1[0][j] +
51                     m2[1][1] * m1[1][j] +
52                     m2[1][2] * m1[2][j] +
53                     m2[1][3] * m1[3][j] ;
54
55         dst[2][j] = m2[2][0] * m1[0][j] +
56                     m2[2][1] * m1[1][j] +
57                     m2[2][2] * m1[2][j] +
58                     m2[2][3] * m1[3][j] ;
59
60         dst[3][j] = m2[3][0] * m1[0][j] +
61                     m2[3][1] * m1[1][j] +
62                     m2[3][2] * m1[2][j] +
63                     m2[3][3] * m1[3][j] ;
64     }
65 }
66
67 static inline bool fgdPointInTriangle( sgdVec3 point, sgdVec3 tri[3] )
68 {
69     sgdVec3 dif;
70
71     // Some tolerance in meters we accept a point to be outside of the triangle
72     // and still return that it is inside.
73     SGDfloat eps = 1e-2;
74     SGDfloat min, max;
75     // punt if outside bouding cube
76     SG_MIN_MAX3 ( min, max, tri[0][0], tri[1][0], tri[2][0] );
77     if( (point[0] < min - eps) || (point[0] > max + eps) )
78         return false;
79     dif[0] = max - min;
80
81     SG_MIN_MAX3 ( min, max, tri[0][1], tri[1][1], tri[2][1] );
82     if( (point[1] < min - eps) || (point[1] > max + eps) )
83         return false;
84     dif[1] = max - min;
85
86     SG_MIN_MAX3 ( min, max, tri[0][2], tri[1][2], tri[2][2] );
87     if( (point[2] < min - eps) || (point[2] > max + eps) )
88         return false;
89     dif[2] = max - min;
90
91     // drop the smallest dimension so we only have to work in 2d.
92     SGDfloat min_dim = SG_MIN3 (dif[0], dif[1], dif[2]);
93     SGDfloat x1, y1, x2, y2, x3, y3, rx, ry;
94     if ( fabs(min_dim-dif[0]) <= DBL_EPSILON ) {
95         // x is the smallest dimension
96         x1 = point[1];
97         y1 = point[2];
98         x2 = tri[0][1];
99         y2 = tri[0][2];
100         x3 = tri[1][1];
101         y3 = tri[1][2];
102         rx = tri[2][1];
103         ry = tri[2][2];
104     } else if ( fabs(min_dim-dif[1]) <= DBL_EPSILON ) {
105         // y is the smallest dimension
106         x1 = point[0];
107         y1 = point[2];
108         x2 = tri[0][0];
109         y2 = tri[0][2];
110         x3 = tri[1][0];
111         y3 = tri[1][2];
112         rx = tri[2][0];
113         ry = tri[2][2];
114     } else if ( fabs(min_dim-dif[2]) <= DBL_EPSILON ) {
115         // z is the smallest dimension
116         x1 = point[0];
117         y1 = point[1];
118         x2 = tri[0][0];
119         y2 = tri[0][1];
120         x3 = tri[1][0];
121         y3 = tri[1][1];
122         rx = tri[2][0];
123         ry = tri[2][1];
124     } else {
125         // all dimensions are really small so lets call it close
126         // enough and return a successful match
127         return true;
128     }
129
130     // check if intersection point is on the same side of p1 <-> p2 as p3
131     SGDfloat tmp = (y2 - y3);
132     SGDfloat tmpn = (x2 - x3);
133     int side1 = SG_SIGN (tmp * (rx - x3) + (y3 - ry) * tmpn);
134     int side2 = SG_SIGN (tmp * (x1 - x3) + (y3 - y1) * tmpn
135                          + side1 * eps * fabs(tmpn));
136     if ( side1 != side2 ) {
137         // printf("failed side 1 check\n");
138         return false;
139     }
140
141     // check if intersection point is on correct side of p2 <-> p3 as p1
142     tmp = (y3 - ry);
143     tmpn = (x3 - rx);
144     side1 = SG_SIGN (tmp * (x2 - rx) + (ry - y2) * tmpn);
145     side2 = SG_SIGN (tmp * (x1 - rx) + (ry - y1) * tmpn
146                      + side1 * eps * fabs(tmpn));
147     if ( side1 != side2 ) {
148         // printf("failed side 2 check\n");
149         return false;
150     }
151
152     // check if intersection point is on correct side of p1 <-> p3 as p2
153     tmp = (y2 - ry);
154     tmpn = (x2 - rx);
155     side1 = SG_SIGN (tmp * (x3 - rx) + (ry - y3) * tmpn);
156     side2 = SG_SIGN (tmp * (x1 - rx) + (ry - y1) * tmpn
157                      + side1 * eps * fabs(tmpn));
158     if ( side1 != side2 ) {
159         // printf("failed side 3  check\n");
160         return false;
161     }
162
163     return true;
164 }
165
166 // Test if the line given by the point on the line pt_on_line and the
167 // line direction dir intersects the sphere sp.
168 // Adapted from plib.
169 static inline bool
170 fgdIsectSphereInfLine(const sgdSphere& sp,
171                       const sgdVec3 pt_on_line, const sgdVec3 dir)
172 {
173   sgdVec3 r;
174   sgdSubVec3( r, sp.getCenter(), pt_on_line ) ;
175
176   SGDfloat projectedDistance = sgdScalarProductVec3(r, dir);
177  
178   SGDfloat dist = sgdScalarProductVec3 ( r, r ) -
179     projectedDistance * projectedDistance;
180
181   SGDfloat radius = sp.getRadius();
182   return dist < radius*radius;
183 }
184
185 FGGroundCache::FGGroundCache()
186 {
187   sgdSetVec3(cache_center, 0.0, 0.0, 0.0);
188   ground_radius = 0.0;
189   cache_ref_time = 0.0;
190   wire_id = 0;
191   sgdSetVec3(reference_wgs84_point, 0.0, 0.0, 0.0);
192   reference_vehicle_radius = 0.0;
193   found_ground = false;
194 }
195
196 FGGroundCache::~FGGroundCache()
197 {
198 }
199
200 FGGroundCache::GroundProperty
201 FGGroundCache::extractGroundProperty( ssgLeaf* l )
202 {
203   // FIXME: Do more ...
204   // Idea: have a get_globals() function which knows about that stuff.
205   // Or most propably read that from a configuration file,
206   // from property tree or whatever ...
207   
208   // Get ground dependent data.
209   GroundProperty gp;
210   gp.wire_id = -1;
211   
212   FGAICarrierHardware *ud =
213     dynamic_cast<FGAICarrierHardware*>(l->getUserData());
214   if (ud) {
215     switch (ud->type) {
216     case FGAICarrierHardware::Wire:
217       gp.type = FGInterface::Wire;
218       gp.wire_id = ud->id;
219       break;
220     case FGAICarrierHardware::Catapult:
221       gp.type = FGInterface::Catapult;
222       break;
223     default:
224       gp.type = FGInterface::Solid;
225       break;
226     }
227
228     // Copy the velocity from the carrier class.
229     ud->carrier->getVelocityWrtEarth( gp.vel );
230   }
231
232   else {
233
234     // Initialize velocity field.
235     sgSetVec3( gp.vel, 0.0, 0.0, 0.0 );
236   }
237   
238   // Get the texture name and decide what ground type we have.
239   ssgState *st = l->getState();
240   if (st != NULL && st->isAKindOf(ssgTypeSimpleState())) {
241     ssgSimpleState *ss = (ssgSimpleState*)st;
242     SGPath fullPath( ss->getTextureFilename() ? ss->getTextureFilename(): "" );
243     string file = fullPath.file();
244     SGPath dirPath(fullPath.dir());
245     string category = dirPath.file();
246     
247     if (category == "Runway")
248       gp.type = FGInterface::Solid;
249     else {
250       if (file == "asphault.rgb" || file == "airport.rgb")
251         gp.type = FGInterface::Solid;
252       else if (file == "water.rgb" || file == "water-lake.rgb")
253         gp.type = FGInterface::Water;
254       else if (file == "forest.rgb" || file == "cropwood.rgb")
255         gp.type = FGInterface::Forest;
256     }
257   }
258   
259   return gp;
260 }
261
262 void
263 FGGroundCache::putLineLeafIntoCache(const sgdSphere *wsp, const sgdMat4 xform,
264                                     ssgLeaf *l)
265 {
266   GroundProperty gp = extractGroundProperty(l);
267
268   // Lines must have special meanings.
269   // Wires and catapults are done with lines.
270   int nl = l->getNumLines();
271   for (int i = 0; i < nl; ++i) {
272     sgdSphere sphere;
273     sphere.empty();
274     sgdVec3 ends[2];
275     short v[2];
276     l->getLine(i, v, v+1 );
277     for (int k=0; k<2; ++k) {
278       sgdSetVec3(ends[k], l->getVertex(v[k]));
279       sgdXformPnt3(ends[k], xform);
280       sphere.extend(ends[k]);
281     }
282
283     if (wsp->intersects( &sphere )) {
284       if (gp.type == FGInterface::Wire) {
285         Wire wire;
286         sgdCopyVec3(wire.ends[0], ends[0]);
287         sgdCopyVec3(wire.ends[1], ends[1]);
288         sgdSetVec3(wire.velocity, gp.vel);
289         wire.wire_id = gp.wire_id;
290
291         wires.push_back(wire);
292       }
293       if (gp.type == FGInterface::Catapult) {
294         Catapult cat;
295         sgdCopyVec3(cat.start, ends[0]);
296         sgdCopyVec3(cat.end, ends[1]);
297         sgdSetVec3(cat.velocity, gp.vel);
298
299         catapults.push_back(cat);
300       }
301     }
302   }
303 }
304
305 void
306 FGGroundCache::putSurfaceLeafIntoCache(const sgdSphere *sp,
307                                        const sgdMat4 xform, bool sphIsec,
308                                        sgdVec3 down, ssgLeaf *l)
309 {
310   GroundProperty gp = extractGroundProperty(l);
311
312   int nt = l->getNumTriangles();
313   for (int i = 0; i < nt; ++i) {
314     Triangle t;
315     t.sphere.empty();
316     short v[3];
317     l->getTriangle(i, &v[0], &v[1], &v[2]);
318     for (int k = 0; k < 3; ++k) {
319       sgdSetVec3(t.vertices[k], l->getVertex(v[k]));
320       sgdXformPnt3(t.vertices[k], xform);
321       t.sphere.extend(t.vertices[k]);
322     }
323
324     sgdMakePlane(t.plane, t.vertices[0], t.vertices[1], t.vertices[2]);
325     SGDfloat dot = sgdScalarProductVec3(down, t.plane);
326     if (dot > 0) {
327       if (!l->getCullFace()) {
328         // Surface points downwards, ignore for altitude computations.
329         continue;
330       } else
331         sgdScaleVec4( t.plane, -1 );
332     }
333
334     // Check if the sphere around the vehicle intersects the sphere
335     // around that triangle. If so, put that triangle into the cache.
336     if (sphIsec && sp->intersects(&t.sphere)) {
337       sgdSetVec3(t.velocity, gp.vel);
338       t.type = gp.type;
339       triangles.push_back(t);
340     }
341     
342     // In case the cache is empty, we still provide agl computations.
343     // But then we use the old way of having a fixed elevation value for
344     // the whole lifetime of this cache.
345     if ( fgdIsectSphereInfLine(t.sphere, sp->getCenter(), down) ) {
346       sgdVec3 tmp;
347       sgdSetVec3(tmp, sp->center[0], sp->center[1], sp->center[2]);
348       sgdVec3 isectpoint;
349       if ( sgdIsectInfLinePlane( isectpoint, tmp, down, t.plane ) &&
350            fgdPointInTriangle( isectpoint, t.vertices ) ) {
351         found_ground = true;
352         sgdAddVec3(isectpoint, cache_center);
353         double this_radius = sgdLengthVec3(isectpoint);
354         if (ground_radius < this_radius)
355           ground_radius = this_radius;
356       }
357     }
358   }
359 }
360
361 inline void
362 FGGroundCache::velocityTransformTriangle(double dt,
363                                          FGGroundCache::Triangle& dst,
364                                          const FGGroundCache::Triangle& src)
365 {
366   sgdCopyVec3(dst.vertices[0], src.vertices[0]);
367   sgdCopyVec3(dst.vertices[1], src.vertices[1]);
368   sgdCopyVec3(dst.vertices[2], src.vertices[2]);
369
370   sgdCopyVec4(dst.plane, src.plane);
371   
372   sgdCopyVec3(dst.sphere.center, src.sphere.center);
373   dst.sphere.radius = src.sphere.radius;
374
375   sgdCopyVec3(dst.velocity, src.velocity);
376
377   dst.type = src.type;
378
379   if (dt*sgdLengthSquaredVec3(src.velocity) != 0) {
380     sgdAddScaledVec3(dst.vertices[0], src.velocity, dt);
381     sgdAddScaledVec3(dst.vertices[1], src.velocity, dt);
382     sgdAddScaledVec3(dst.vertices[2], src.velocity, dt);
383     
384     dst.plane[3] += dt*sgdScalarProductVec3(dst.plane, src.velocity);
385
386     sgdAddScaledVec3(dst.sphere.center, src.velocity, dt);
387   }
388 }
389
390 void
391 FGGroundCache::cache_fill(ssgBranch *branch, sgdMat4 xform,
392                           sgdSphere* sp, sgdVec3 down, sgdSphere* wsp)
393 {
394   // Travel through all kids.
395   ssgEntity *e;
396   for ( e = branch->getKid(0); e != NULL ; e = branch->getNextKid() ) {
397     if ( !(e->getTraversalMask() & SSGTRAV_HOT) )
398       continue;
399     if ( e->getBSphere()->isEmpty() )
400       continue;
401     
402     // We need to check further if either the sphere around the branch
403     // intersects the sphere around the aircraft or the line downwards from
404     // the aircraft intersects the branchs sphere.
405     sgdSphere esphere;
406     sgdSetVec3(esphere.center, e->getBSphere()->center);
407     esphere.radius = e->getBSphere()->radius;
408     esphere.orthoXform(xform);
409     bool wspIsec = wsp->intersects(&esphere);
410     bool downIsec = fgdIsectSphereInfLine(esphere, sp->getCenter(), down);
411     if (!wspIsec && !downIsec)
412       continue;
413
414     // For branches collect up the transforms to reach that branch and
415     // call cache_fill recursively.
416     if ( e->isAKindOf( ssgTypeBranch() ) ) {
417       ssgBranch *b = (ssgBranch *)e;
418       if ( b->isAKindOf( ssgTypeTransform() ) ) {
419         // Collect up the transfors required to reach that part of
420         // the branch.
421         sgMat4 xform2;
422         sgMakeIdentMat4( xform2 );
423         ssgTransform *t = (ssgTransform*)b;
424         t->getTransform( xform2 );
425         sgdMat4 xform3;
426         fgMultMat4(xform3, xform, xform2);
427         cache_fill( b, xform3, sp, down, wsp );
428       } else
429         cache_fill( b, xform, sp, down, wsp );
430     }
431    
432     // For leafs, check each triangle for intersection.
433     // This will minimize the number of vertices/triangles in the cache.
434     else if (e->isAKindOf(ssgTypeLeaf())) {
435       // Since we reach that leaf if we have an intersection with the
436       // most propably bigger wire/catapult cache sphere, we need to check
437       // that here, if the smaller cache for the surface has a chance for hits.
438       // Also, if the spheres do not intersect compute a croase agl value
439       // by following the line downwards originating at the aircraft.
440       bool spIsec = sp->intersects(&esphere);
441       putSurfaceLeafIntoCache(sp, xform, spIsec, down, (ssgLeaf *)e);
442
443       // If we are here, we need to put all special hardware here into
444       // the cache.
445       if (wspIsec)
446         putLineLeafIntoCache(wsp, xform, (ssgLeaf *)e);
447     }
448   }
449 }
450
451 bool
452 FGGroundCache::prepare_ground_cache(double ref_time, const double pt[3],
453                                     double rad)
454 {
455   // Empty cache.
456   ground_radius = 0.0;
457   found_ground = false;
458   triangles.resize(0);
459   catapults.resize(0);
460   wires.resize(0);
461
462   // Store the parameters we used to build up that cache.
463   sgdCopyVec3(reference_wgs84_point, pt);
464   reference_vehicle_radius = rad;
465   // Store the time reference used to compute movements of moving triangles.
466   cache_ref_time = ref_time;
467
468   // Decide where we put the scenery center.
469   Point3D old_cntr = globals->get_scenery()->get_center();
470   Point3D cntr(pt[0], pt[1], pt[2]);
471   // Only move the cache center if it is unaccaptable far away.
472   if (40*40 < old_cntr.distance3Dsquared(cntr))
473     globals->get_scenery()->set_center(cntr);
474   else
475     cntr = old_cntr;
476
477   // The center of the cache.
478   sgdSetVec3(cache_center, cntr[0], cntr[1], cntr[2]);
479   
480   sgdVec3 ptoff;
481   sgdSubVec3(ptoff, pt, cache_center);
482   // Prepare sphere around the aircraft.
483   sgdSphere acSphere;
484   acSphere.setRadius(rad);
485   acSphere.setCenter(ptoff);
486
487   // Prepare bigger sphere around the aircraft.
488   // This one is required for reliably finding wires we have caught but
489   // have already left the hopefully smaller sphere for the ground reactions.
490   const double max_wire_dist = 300.0;
491   sgdSphere wireSphere;
492   wireSphere.setRadius(max_wire_dist < rad ? rad : max_wire_dist);
493   wireSphere.setCenter(ptoff);
494
495   // Down vector. Is used for croase agl computations when we are far enough
496   // from ground that we have an empty cache.
497   sgdVec3 down;
498   sgdSetVec3(down, -pt[0], -pt[1], -pt[2]);
499   sgdNormalizeVec3(down);
500
501   // We collaps all transforms we need to reach a particular leaf.
502   // The leafs itself will be then transformed later.
503   // So our cache is just flat.
504   // For leafs which are moving (carriers surface, etc ...)
505   // we will later store a speed in the GroundType class. We can then apply
506   // some translations to that nodes according to the time which has passed
507   // compared to that snapshot.
508   sgdMat4 xform;
509   sgdMakeIdentMat4( xform );
510
511
512   // Walk the scene graph and extract solid ground triangles and carrier data.
513   ssgBranch *terrain = globals->get_scenery()->get_scene_graph();
514   cache_fill(terrain, xform, &acSphere, down, &wireSphere);
515
516   // some stats
517   SG_LOG(SG_FLIGHT,SG_INFO, "prepare_ground_cache(): ac radius = " << rad
518          << ", # triangles = " << triangles.size()
519          << ", # wires = " << wires.size()
520          << ", # catapults = " << catapults.size()
521          << ", ground_radius = " << ground_radius );
522
523   // If the ground radius is still below 5e6 meters, then we do not yet have
524   // any scenery.
525   found_ground = found_ground && 5e6 < ground_radius;
526   if (!found_ground)
527     SG_LOG(SG_FLIGHT, SG_WARN, "prepare_ground_cache(): trying to build cache "
528            "without any scenery below the aircraft" );
529
530   if (cntr != old_cntr)
531     globals->get_scenery()->set_center(old_cntr);
532
533   return found_ground;
534 }
535
536 bool
537 FGGroundCache::is_valid(double *ref_time, double pt[3], double *rad)
538 {
539   sgdCopyVec3(pt, reference_wgs84_point);
540   *rad = reference_vehicle_radius;
541   *ref_time = cache_ref_time;
542   return found_ground;
543 }
544
545 double
546 FGGroundCache::get_cat(double t, const double dpt[3],
547                        double end[2][3], double vel[2][3])
548 {
549   // start with a distance of 1e10 meters...
550   double dist = 1e10;
551
552   // Time difference to the reference time.
553   t -= cache_ref_time;
554
555   size_t sz = catapults.size();
556   for (size_t i = 0; i < sz; ++i) {
557     sgdLineSegment3 ls;
558     sgdCopyVec3(ls.a, catapults[i].start);
559     sgdCopyVec3(ls.b, catapults[i].end);
560
561     sgdAddVec3(ls.a, cache_center);
562     sgdAddVec3(ls.b, cache_center);
563
564     sgdAddScaledVec3(ls.a, catapults[i].velocity, t);
565     sgdAddScaledVec3(ls.b, catapults[i].velocity, t);
566     
567     double this_dist = sgdDistSquaredToLineSegmentVec3( ls, dpt );
568     if (this_dist < dist) {
569       SG_LOG(SG_FLIGHT,SG_INFO, "Found catapult "
570              << this_dist << " meters away");
571       dist = this_dist;
572         
573       // The carrier code takes care of that ordering.
574       sgdCopyVec3( end[0], ls.a );
575       sgdCopyVec3( end[1], ls.b );
576       sgdCopyVec3( vel[0], catapults[i].velocity );
577       sgdCopyVec3( vel[1], catapults[i].velocity );
578     }
579   }
580
581   // At the end take the root, we only computed squared distances ...
582   return sqrt(dist);
583 }
584
585 bool
586 FGGroundCache::get_agl(double t, const double dpt[3], double max_altoff,
587                        double contact[3], double normal[3], double vel[3],
588                        int *type, double *loadCapacity,
589                        double *frictionFactor, double *agl)
590 {
591   bool ret = false;
592
593   *type = FGInterface::Unknown;
594 //   *agl = 0.0;
595   *loadCapacity = DBL_MAX;
596   *frictionFactor = 1.0;
597   sgdSetVec3( vel, 0.0, 0.0, 0.0 );
598   sgdSetVec3( contact, 0.0, 0.0, 0.0 );
599   sgdSetVec3( normal, 0.0, 0.0, 0.0 );
600
601   // Time difference to th reference time.
602   t -= cache_ref_time;
603
604   // The double valued point we start to search for intersection.
605   sgdVec3 pt;
606   sgdSubVec3( pt, dpt, cache_center );
607
608   // The search direction
609   sgdVec3 dir;
610   sgdSetVec3( dir, -dpt[0], -dpt[1], -dpt[2] );
611   sgdNormaliseVec3( dir );
612
613   // Initialize to something sensible
614   double current_radius = 0.0;
615
616   size_t sz = triangles.size();
617   for (size_t i = 0; i < sz; ++i) {
618     Triangle triangle;
619     velocityTransformTriangle(t, triangle, triangles[i]);
620     if (!fgdIsectSphereInfLine(triangle.sphere, pt, dir))
621       continue;
622
623     // Check for intersection.
624     sgdVec3 isecpoint;
625     if ( sgdIsectInfLinePlane( isecpoint, pt, dir, triangle.plane ) &&
626          sgdPointInTriangle( isecpoint, triangle.vertices ) ) {
627       // Transform to the wgs system
628       sgdAddVec3( isecpoint, cache_center );
629       // compute the radius, good enough approximation to take the geocentric radius
630       SGDfloat radius = sgdLengthSquaredVec3(isecpoint);
631       if (current_radius < radius) {
632         // Compute the vector from pt to the intersection point ...
633         sgdVec3 off;
634         sgdSubVec3(off, pt, isecpoint);
635         // ... and check if it is too high or not
636         if (-max_altoff < sgdScalarProductVec3( off, dir )) {
637           current_radius = radius;
638           ret = true;
639           // Save the new potential intersection point.
640           sgdCopyVec3( contact, isecpoint );
641           // The first three values in the vector are the plane normal.
642           sgdCopyVec3( normal, triangle.plane );
643           // The velocity wrt earth.
644           /// FIXME: only true for non rotating objects!!!!
645           sgdCopyVec3( vel, triangle.velocity );
646           // Save the ground type.
647           *type = triangle.type;
648           // FIXME: figure out how to get that sign ...
649 //           *agl = sqrt(sqdist);
650           *agl = sgdLengthVec3( dpt ) - sgdLengthVec3( contact );
651 //           *loadCapacity = DBL_MAX;
652 //           *frictionFactor = 1.0;
653         }
654       }
655     }
656   }
657
658   if (ret)
659     return true;
660
661   // Whenever we did not have a ground triangle for the requested point,
662   // take the ground level we found during the current cache build.
663   // This is as good as what we had before for agl.
664   double r = sgdLengthVec3( dpt );
665   sgdCopyVec3( contact, dpt );
666   sgdScaleVec3( contact, ground_radius/r );
667   sgdCopyVec3( normal, dpt );
668   sgdNormaliseVec3( normal );
669   sgdSetVec3( vel, 0.0, 0.0, 0.0 );
670   
671   // The altitude is the distance of the requested point from the
672   // contact point.
673   *agl = sgdLengthVec3( dpt ) - sgdLengthVec3( contact );
674   *type = FGInterface::Unknown;
675   *loadCapacity = DBL_MAX;
676   *frictionFactor = 1.0;
677
678   return ret;
679 }
680
681 bool FGGroundCache::caught_wire(double t, const double pt[4][3])
682 {
683   size_t sz = wires.size();
684   if (sz == 0)
685     return false;
686
687   // Time difference to the reference time.
688   t -= cache_ref_time;
689
690   // Build the two triangles spanning the area where the hook has moved
691   // during the past step.
692   sgdVec4 plane[2];
693   sgdVec3 tri[2][3];
694   sgdMakePlane( plane[0], pt[0], pt[1], pt[2] );
695   sgdCopyVec3( tri[0][0], pt[0] );
696   sgdCopyVec3( tri[0][1], pt[1] );
697   sgdCopyVec3( tri[0][2], pt[2] );
698   sgdMakePlane( plane[1], pt[0], pt[2], pt[3] );
699   sgdCopyVec3( tri[1][0], pt[0] );
700   sgdCopyVec3( tri[1][1], pt[2] );
701   sgdCopyVec3( tri[1][2], pt[3] );
702
703   // Intersect the wire lines with each of these triangles.
704   // You have cautght a wire if they intersect.
705   for (size_t i = 0; i < sz; ++i) {
706     sgdVec3 le[2];
707     sgdCopyVec3(le[0], wires[i].ends[0]);
708     sgdCopyVec3(le[1], wires[i].ends[1]);
709
710     sgdAddVec3(le[0], cache_center);
711     sgdAddVec3(le[1], cache_center);
712
713     sgdAddScaledVec3(le[0], wires[i].velocity, t);
714     sgdAddScaledVec3(le[1], wires[i].velocity, t);
715     
716     for (int k=0; k<2; ++k) {
717       sgdVec3 isecpoint;
718       double isecval = sgdIsectLinesegPlane(isecpoint, le[0], le[1], plane[k]);
719       if ( 0.0 <= isecval && isecval <= 1.0 &&
720            sgdPointInTriangle( isecpoint, tri[k] ) ) {
721         SG_LOG(SG_FLIGHT,SG_INFO, "Caught wire");
722         // Store the wire id.
723         wire_id = wires[i].wire_id;
724         return true;
725       }
726     }
727   }
728
729   return false;
730 }
731
732 bool FGGroundCache::get_wire_ends(double t, double end[2][3], double vel[2][3])
733 {
734   // Fast return if we do not have an active wire.
735   if (wire_id < 0)
736     return false;
737
738   // Time difference to the reference time.
739   t -= cache_ref_time;
740
741   // Search for the wire with the matching wire id.
742   size_t sz = wires.size();
743   for (size_t i = 0; i < sz; ++i) {
744     if (wires[i].wire_id == wire_id) {
745       sgdCopyVec3(end[0], wires[i].ends[0]);
746       sgdCopyVec3(end[1], wires[i].ends[1]);
747       
748       sgdAddVec3(end[0], cache_center);
749       sgdAddVec3(end[1], cache_center);
750       
751       sgdAddScaledVec3(end[0], wires[i].velocity, t);
752       sgdAddScaledVec3(end[1], wires[i].velocity, t);
753       
754       sgdCopyVec3(vel[0], wires[i].velocity);
755       sgdCopyVec3(vel[1], wires[i].velocity);
756       return true;
757     }
758   }
759
760   return false;
761 }
762
763 void FGGroundCache::release_wire(void)
764 {
765   wire_id = -1;
766 }