]> git.mxchange.org Git - flightgear.git/blob - src/FDM/groundcache.cxx
3f1a396a0449078a037b898df8c985355ad253f5
[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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <float.h>
28
29 #include <plib/sg.h>
30 #include <osg/CullFace>
31 #include <osg/Drawable>
32 #include <osg/Geode>
33 #include <osg/Geometry>
34 #include <osg/TriangleFunctor>
35
36 #include <simgear/sg_inlines.h>
37 #include <simgear/constants.h>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/math/sg_geodesy.hxx>
40 #include <simgear/scene/material/mat.hxx>
41 #include <simgear/scene/material/matlib.hxx>
42 #include <simgear/scene/util/SGNodeMasks.hxx>
43
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <Scenery/tilemgr.hxx>
47 #include <AIModel/AICarrier.hxx>
48
49 #include "flight.hxx"
50 #include "groundcache.hxx"
51
52 static inline bool
53 fgdRayTriangle(SGVec3d& x, const SGVec3d& point, const SGVec3d& dir,
54                const SGVec3d v[3])
55 {
56   double eps = 1e-4;
57   // Method based on the observation that we are looking for a
58   // point x that can be expressed in terms of the triangle points
59   //  x = p_0 + \mu_1*(p_1 - p_0) + \mu_2*(p_2 - p_0)
60   // with 0 <= \mu_1, \mu_2 and \mu_1 + \mu_2 <= 1.
61   // OTOH it could be expressed in terms of the ray
62   //  x = point + \lambda*dir
63   // Now we can compute \mu_i and \lambda.
64   // define
65   SGVec3d d1 = v[1] - v[0];
66   SGVec3d d2 = v[2] - v[0];
67   SGVec3d b = point - v[0];
68   
69   // the vector in normal direction, but not normalized
70   SGVec3d d1crossd2 = cross(d1, d2);
71   
72   double denom = -dot(dir, d1crossd2);
73   double signDenom = copysign(1, denom);
74   // return if paralell ??? FIXME what if paralell and in plane?
75   // may be we are ok below than anyway??
76   // if (SGMiscd::abs(denom) <= SGLimitsd::min())
77   //   return false;
78   
79   // Now \lambda would read
80   //   lambda = 1/denom*dot(b, d1crossd2);
81   // To avoid an expensive division we multiply by |denom|
82   double lambdaDenom = signDenom*dot(b, d1crossd2);
83   if (lambdaDenom < 0)
84     return false;
85   // For line segment we would test against
86   // if (1 < lambda)
87   //   return false;
88   // with the original lambda. The multiplied test would read
89   // if (absDenom < lambdaDenom)
90   //   return false;
91
92   double absDenom = fabs(denom);
93   double absDenomEps = absDenom*eps;
94   
95   SGVec3d bcrossr = cross(b, dir);
96   // double mu1 = 1/denom*dot(d2, bcrossr);
97   double mu1 = signDenom*dot(d2, bcrossr);
98   if (mu1 < -absDenomEps)
99     return false;
100   // double mu2 = -1/denom*dot(d1, bcrossr);
101   // if (mu2 < -eps)
102   //   return false;
103   double mmu2 = signDenom*dot(d1, bcrossr);
104   if (mmu2 > absDenomEps)
105     return false;
106   
107   if (mu1 - mmu2 > absDenom + absDenomEps)
108     return false;
109
110   x = point;
111   // if we have survived here it could only happen with denom == 0
112   // that the point is already in plane. Then return the origin ...
113   if (SGLimitsd::min() < absDenom)
114     x += (lambdaDenom/absDenom)*dir;
115
116   return true;
117 }
118
119 static inline bool
120 fgdPointInTriangle( const SGVec3d& point, const SGVec3d tri[3] )
121 {
122     SGVec3d dif;
123
124     // Some tolerance in meters we accept a point to be outside of the triangle
125     // and still return that it is inside.
126     SGDfloat min, max;
127     // punt if outside bouding cube
128     SG_MIN_MAX3 ( min, max, tri[0][0], tri[1][0], tri[2][0] );
129     if( (point[0] < min) || (point[0] > max) )
130         return false;
131     dif[0] = max - min;
132
133     SG_MIN_MAX3 ( min, max, tri[0][1], tri[1][1], tri[2][1] );
134     if( (point[1] < min) || (point[1] > max) )
135         return false;
136     dif[1] = max - min;
137
138     SG_MIN_MAX3 ( min, max, tri[0][2], tri[1][2], tri[2][2] );
139     if( (point[2] < min) || (point[2] > max) )
140         return false;
141     dif[2] = max - min;
142
143     // drop the smallest dimension so we only have to work in 2d.
144     SGDfloat min_dim = SG_MIN3 (dif[0], dif[1], dif[2]);
145     SGDfloat x1, y1, x2, y2, x3, y3, rx, ry;
146     if ( fabs(min_dim-dif[0]) <= DBL_EPSILON ) {
147         // x is the smallest dimension
148         x1 = point[1];
149         y1 = point[2];
150         x2 = tri[0][1];
151         y2 = tri[0][2];
152         x3 = tri[1][1];
153         y3 = tri[1][2];
154         rx = tri[2][1];
155         ry = tri[2][2];
156     } else if ( fabs(min_dim-dif[1]) <= DBL_EPSILON ) {
157         // y is the smallest dimension
158         x1 = point[0];
159         y1 = point[2];
160         x2 = tri[0][0];
161         y2 = tri[0][2];
162         x3 = tri[1][0];
163         y3 = tri[1][2];
164         rx = tri[2][0];
165         ry = tri[2][2];
166     } else if ( fabs(min_dim-dif[2]) <= DBL_EPSILON ) {
167         // z is the smallest dimension
168         x1 = point[0];
169         y1 = point[1];
170         x2 = tri[0][0];
171         y2 = tri[0][1];
172         x3 = tri[1][0];
173         y3 = tri[1][1];
174         rx = tri[2][0];
175         ry = tri[2][1];
176     } else {
177         // all dimensions are really small so lets call it close
178         // enough and return a successful match
179         return true;
180     }
181
182     // check if intersection point is on the same side of p1 <-> p2 as p3
183     SGDfloat tmp = (y2 - y3);
184     SGDfloat tmpn = (x2 - x3);
185     int side1 = SG_SIGN (tmp * (rx - x3) + (y3 - ry) * tmpn);
186     int side2 = SG_SIGN (tmp * (x1 - x3) + (y3 - y1) * tmpn);
187     if ( side1 != side2 ) {
188         // printf("failed side 1 check\n");
189         return false;
190     }
191
192     // check if intersection point is on correct side of p2 <-> p3 as p1
193     tmp = (y3 - ry);
194     tmpn = (x3 - rx);
195     side1 = SG_SIGN (tmp * (x2 - rx) + (ry - y2) * tmpn);
196     side2 = SG_SIGN (tmp * (x1 - rx) + (ry - y1) * tmpn);
197     if ( side1 != side2 ) {
198         // printf("failed side 2 check\n");
199         return false;
200     }
201
202     // check if intersection point is on correct side of p1 <-> p3 as p2
203     tmp = (y2 - ry);
204     tmpn = (x2 - rx);
205     side1 = SG_SIGN (tmp * (x3 - rx) + (ry - y3) * tmpn);
206     side2 = SG_SIGN (tmp * (x1 - rx) + (ry - y1) * tmpn);
207     if ( side1 != side2 ) {
208         // printf("failed side 3  check\n");
209         return false;
210     }
211
212     return true;
213 }
214
215 // Test if the line given by the point on the line pt_on_line and the
216 // line direction dir intersects the sphere sp.
217 // Adapted from plib.
218 static inline bool
219 fgdIsectSphereInfLine(const SGVec3d& sphereCenter, double radius,
220                       const SGVec3d& pt_on_line, const SGVec3d& dir)
221 {
222   SGVec3d r = sphereCenter - pt_on_line;
223   double projectedDistance = dot(r, dir);
224   double dist = dot(r, r) - projectedDistance * projectedDistance;
225   return dist < radius*radius;
226 }
227
228 template<typename T>
229 class SGExtendedTriangleFunctor : public osg::TriangleFunctor<T> {
230 public:
231   // Ok, to be complete we should also implement the indexed variants
232   // For now this one appears to be enough ...
233   void drawArrays(GLenum mode, GLint first, GLsizei count)
234   {
235     if (_vertexArrayPtr==0 || count==0) return;
236
237     const osg::Vec3* vlast;
238     const osg::Vec3* vptr;
239     switch(mode) {
240     case(GL_LINES):
241       vlast = &_vertexArrayPtr[first+count];
242       for(vptr=&_vertexArrayPtr[first];vptr<vlast;vptr+=2)
243         this->operator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary);
244       break;
245     case(GL_LINE_STRIP):
246       vlast = &_vertexArrayPtr[first+count-1];
247       for(vptr=&_vertexArrayPtr[first];vptr<vlast;++vptr)
248         this->operator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary);
249       break;
250     case(GL_LINE_LOOP):
251       vlast = &_vertexArrayPtr[first+count-1];
252       for(vptr=&_vertexArrayPtr[first];vptr<vlast;++vptr)
253         this->operator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary);
254       this->operator()(_vertexArrayPtr[first+count-1],
255                        _vertexArrayPtr[first],_treatVertexDataAsTemporary);
256       break;
257     default:
258       osg::TriangleFunctor<T>::drawArrays(mode, first, count);
259       break;
260     }
261   }
262 protected:
263   using osg::TriangleFunctor<T>::_vertexArrayPtr;
264   using osg::TriangleFunctor<T>::_treatVertexDataAsTemporary;
265 };
266
267 class GroundCacheFillVisitor : public osg::NodeVisitor {
268 public:
269   
270   /// class to just redirect triangles to the GroundCacheFillVisitor
271   class GroundCacheFill {
272   public:
273     void setGroundCacheFillVisitor(GroundCacheFillVisitor* gcfv)
274     { mGroundCacheFillVisitor = gcfv; }
275     
276     void operator () (const osg::Vec3& v1, const osg::Vec3& v2,
277                       const osg::Vec3& v3, bool)
278     { mGroundCacheFillVisitor->addTriangle(v1, v2, v3); }
279
280     void operator () (const osg::Vec3& v1, const osg::Vec3& v2, bool)
281     { mGroundCacheFillVisitor->addLine(v1, v2); }
282     
283   private:
284     GroundCacheFillVisitor* mGroundCacheFillVisitor;
285   };
286
287
288   GroundCacheFillVisitor(FGGroundCache* groundCache,
289                          const SGVec3d& down, 
290                          const SGVec3d& cacheReference,
291                          double cacheRadius,
292                          double wireCacheRadius) :
293     osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
294     mGroundCache(groundCache)
295   {
296     setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
297     mDown = down;
298     mLocalDown = down;
299     sphIsec = true;
300     mBackfaceCulling = false;
301     mCacheReference = cacheReference;
302     mLocalCacheReference = cacheReference;
303     mCacheRadius = cacheRadius;
304     mWireCacheRadius = wireCacheRadius;
305
306     mTriangleFunctor.setGroundCacheFillVisitor(this);
307
308     mGroundProperty.wire_id = -1;
309     mGroundProperty.vel = SGVec3d(0, 0, 0);
310     mGroundProperty.rot = SGVec3d(0, 0, 0);
311     mGroundProperty.pivot = SGVec3d(0, 0, 0);
312   }
313
314   void updateCullMode(osg::StateSet* stateSet)
315   {
316     if (!stateSet)
317       return;
318
319     osg::StateAttribute* stateAttribute;
320     stateAttribute = stateSet->getAttribute(osg::StateAttribute::CULLFACE);
321     if (!stateAttribute)
322       return;
323     osg::CullFace* cullFace = static_cast<osg::CullFace*>(stateAttribute);
324     mBackfaceCulling = cullFace->getMode() == osg::CullFace::BACK;
325   }
326
327   bool enterBoundingSphere(const osg::BoundingSphere& bs)
328   {
329     if (!bs.valid())
330       return false;
331
332     SGVec3d cntr(osg::Vec3d(bs.center())*mLocalToGlobal);
333     double rc = bs.radius() + mCacheRadius;
334     // Ok, this node might intersect the cache. Visit it in depth.
335     double centerDist2 = distSqr(mCacheReference, cntr);
336     if (centerDist2 < rc*rc) {
337       sphIsec = true;
338     } else {
339       // Check if the down direction touches the bounding sphere of the node
340       // if so, do at least croase agl computations.
341       // Ther other thing is that we must check if we are in range of
342       // cats or wires
343       double rw = bs.radius() + mWireCacheRadius;
344       if (rw*rw < centerDist2 &&
345           !fgdIsectSphereInfLine(cntr, bs.radius(), mCacheReference, mDown))
346         return false;
347       sphIsec = false;
348     }
349
350     return true;
351   }
352
353   bool enterNode(osg::Node& node)
354   {
355     if (!enterBoundingSphere(node.getBound()))
356       return false;
357
358     updateCullMode(node.getStateSet());
359
360     FGGroundCache::GroundProperty& gp = mGroundProperty;
361     // get some material information for use in the gear model
362     gp.material = globals->get_matlib()->findMaterial(&node);
363     if (gp.material) {
364       gp.type = gp.material->get_solid() ? FGInterface::Solid : FGInterface::Water;
365       return true;
366     }
367     osg::Referenced* base = node.getUserData();
368     if (!base)
369       return true;
370     FGAICarrierHardware *ud =
371       dynamic_cast<FGAICarrierHardware*>(base);
372     if (!ud)
373       return true;
374
375     switch (ud->type) {
376     case FGAICarrierHardware::Wire:
377       gp.type = FGInterface::Wire;
378       gp.wire_id = ud->id;
379       break;
380     case FGAICarrierHardware::Catapult:
381       gp.type = FGInterface::Catapult;
382       break;
383     default:
384       gp.type = FGInterface::Solid;
385       break;
386     }
387     // Copy the velocity from the carrier class.
388     ud->carrier->getVelocityWrtEarth(gp.vel, gp.rot, gp.pivot);
389   
390     return true;
391   }
392
393   void fillWith(osg::Drawable* drawable)
394   {
395     bool oldSphIsec = sphIsec;
396     if (!enterBoundingSphere(drawable->getBound()))
397       return;
398
399     bool oldBackfaceCulling = mBackfaceCulling;
400     updateCullMode(drawable->getStateSet());
401
402     drawable->accept(mTriangleFunctor);
403
404     mBackfaceCulling = oldBackfaceCulling;
405     sphIsec = oldSphIsec;
406   }
407
408   virtual void apply(osg::Geode& geode)
409   {
410     bool oldBackfaceCulling = mBackfaceCulling;
411     bool oldSphIsec = sphIsec;
412     FGGroundCache::GroundProperty oldGp = mGroundProperty;
413     if (!enterNode(geode))
414       return;
415
416     for(unsigned i = 0; i < geode.getNumDrawables(); ++i)
417       fillWith(geode.getDrawable(i));
418     sphIsec = oldSphIsec;
419     mGroundProperty = oldGp;
420     mBackfaceCulling = oldBackfaceCulling;
421   }
422
423   virtual void apply(osg::Group& group)
424   {
425     bool oldBackfaceCulling = mBackfaceCulling;
426     bool oldSphIsec = sphIsec;
427     FGGroundCache::GroundProperty oldGp = mGroundProperty;
428     if (!enterNode(group))
429       return;
430     traverse(group);
431     sphIsec = oldSphIsec;
432     mBackfaceCulling = oldBackfaceCulling;
433     mGroundProperty = oldGp;
434   }
435
436   virtual void apply(osg::Transform& transform)
437   {
438     if (!enterNode(transform))
439       return;
440     bool oldBackfaceCulling = mBackfaceCulling;
441     bool oldSphIsec = sphIsec;
442     FGGroundCache::GroundProperty oldGp = mGroundProperty;
443     /// transform the caches center to local coords
444     osg::Matrix oldLocalToGlobal = mLocalToGlobal;
445     osg::Matrix oldGlobalToLocal = mGlobalToLocal;
446     transform.computeLocalToWorldMatrix(mLocalToGlobal, this);
447     transform.computeWorldToLocalMatrix(mGlobalToLocal, this);
448
449     SGVec3d oldLocalCacheReference = mLocalCacheReference;
450     mLocalCacheReference.osg() = mCacheReference.osg()*mGlobalToLocal;
451     SGVec3d oldLocalDown = mLocalDown;
452     mLocalDown.osg() = osg::Matrixd::transform3x3(mDown.osg(), mGlobalToLocal);
453
454     // walk the children
455     traverse(transform);
456
457     // Restore that one
458     mLocalDown = oldLocalDown;
459     mLocalCacheReference = oldLocalCacheReference;
460     mLocalToGlobal = oldLocalToGlobal;
461     mGlobalToLocal = oldGlobalToLocal;
462     sphIsec = oldSphIsec;
463     mBackfaceCulling = oldBackfaceCulling;
464     mGroundProperty = oldGp;
465   }
466   
467   void addTriangle(const osg::Vec3& v1, const osg::Vec3& v2,
468                    const osg::Vec3& v3)
469   {
470     SGVec3d v[3] = {
471       SGVec3d(v1),
472       SGVec3d(v2),
473       SGVec3d(v3)
474     };
475     
476     // a bounding sphere in the node local system
477     SGVec3d boundCenter = (1.0/3)*(v[0] + v[1] + v[2]);
478 #if 0
479     double boundRadius = std::max(norm1(v[0] - boundCenter),
480                                   norm1(v[1] - boundCenter));
481     boundRadius = std::max(boundRadius, norm1(v[2] - boundCenter));
482     // Ok, we take the 1-norm instead of the expensive 2 norm.
483     // Therefore we need that scaling factor - roughly sqrt(3)
484     boundRadius = 1.733*boundRadius;
485 #else
486     double boundRadius = std::max(distSqr(v[0], boundCenter),
487                                   distSqr(v[1], boundCenter));
488     boundRadius = std::max(boundRadius, distSqr(v[2], boundCenter));
489     boundRadius = sqrt(boundRadius);
490 #endif
491
492     // if we are not in the downward cylinder bail out
493     if (!fgdIsectSphereInfLine(boundCenter, boundRadius + mCacheRadius,
494                               mLocalCacheReference, mLocalDown))
495       return;
496
497     
498     // The normal and plane in the node local coordinate system
499     SGVec3d n = normalize(cross(v[1] - v[0], v[2] - v[0]));
500     if (0 < dot(mLocalDown, n)) {
501       if (mBackfaceCulling) {
502         // Surface points downwards, ignore for altitude computations.
503         return;
504       } else {
505         n = -n;
506         std::swap(v[1], v[2]);
507       }
508     }
509     
510     // Only check if the triangle is in the cache sphere if the plane
511     // containing the triangle is near enough
512     if (sphIsec && fabs(dot(n, v[0] - mLocalCacheReference)) < mCacheRadius) {
513       // Check if the sphere around the vehicle intersects the sphere
514       // around that triangle. If so, put that triangle into the cache.
515       double r2 = boundRadius + mCacheRadius;
516       if (distSqr(boundCenter, mLocalCacheReference) < r2*r2) {
517         FGGroundCache::Triangle t;
518         for (unsigned i = 0; i < 3; ++i)
519           t.vertices[i].osg() = v[i].osg()*mLocalToGlobal;
520         t.boundCenter.osg() = boundCenter.osg()*mLocalToGlobal;
521         t.boundRadius = boundRadius;
522         
523         SGVec3d tmp;
524         tmp.osg() = osg::Matrixd::transform3x3(n.osg(), mLocalToGlobal);
525         t.plane = SGVec4d(tmp[0], tmp[1], tmp[2], -dot(tmp, t.vertices[0]));
526         t.velocity = mGroundProperty.vel;
527         t.rotation = mGroundProperty.rot;
528         t.rotation_pivot = mGroundProperty.pivot - mGroundCache->cache_center;
529         t.type = mGroundProperty.type;
530         mGroundCache->triangles.push_back(t);
531       }
532     }
533     
534     // In case the cache is empty, we still provide agl computations.
535     // But then we use the old way of having a fixed elevation value for
536     // the whole lifetime of this cache.
537     SGVec4d plane = SGVec4d(n[0], n[1], n[2], -dot(n, v[0]));
538     SGVec3d isectpoint;
539
540     if (fgdRayTriangle(isectpoint, mLocalCacheReference, mLocalDown, v)) {
541       mGroundCache->found_ground = true;
542       isectpoint.osg() = isectpoint.osg()*mLocalToGlobal;
543       isectpoint += mGroundCache->cache_center;
544       double this_radius = length(isectpoint);
545       if (mGroundCache->ground_radius < this_radius)
546         mGroundCache->ground_radius = this_radius;
547     }
548   }
549   
550   void addLine(const osg::Vec3& v1, const osg::Vec3& v2)
551   {
552     SGVec3d gv1(osg::Vec3d(v1)*mLocalToGlobal);
553     SGVec3d gv2(osg::Vec3d(v2)*mLocalToGlobal);
554
555     SGVec3d boundCenter = 0.5*(gv1 + gv2);
556     double boundRadius = length(gv1 - boundCenter);
557
558     if (distSqr(boundCenter, mCacheReference)
559         < (boundRadius + mWireCacheRadius)*(boundRadius + mWireCacheRadius) ) {
560       if (mGroundProperty.type == FGInterface::Wire) {
561         FGGroundCache::Wire wire;
562         wire.ends[0] = gv1;
563         wire.ends[1] = gv2;
564         wire.velocity = mGroundProperty.vel;
565         wire.rotation = mGroundProperty.rot;
566         wire.rotation_pivot = mGroundProperty.pivot - mGroundCache->cache_center;
567         wire.wire_id = mGroundProperty.wire_id;
568
569         mGroundCache->wires.push_back(wire);
570       }
571       if (mGroundProperty.type == FGInterface::Catapult) {
572         FGGroundCache::Catapult cat;
573         // Trick to get the ends in the right order.
574         // Use the x axis in the original coordinate system. Choose the
575         // most negative x-axis as the one pointing forward
576         if (v1[0] < v2[0]) {
577           cat.start = gv1;
578           cat.end = gv2;
579         } else {
580           cat.start = gv2;
581           cat.end = gv1;
582         }
583         cat.velocity = mGroundProperty.vel;
584         cat.rotation = mGroundProperty.rot;
585         cat.rotation_pivot = mGroundProperty.pivot - mGroundCache->cache_center;
586
587         mGroundCache->catapults.push_back(cat);
588       }
589     }
590   }
591
592   SGExtendedTriangleFunctor<GroundCacheFill> mTriangleFunctor;
593   FGGroundCache* mGroundCache;
594   SGVec3d mCacheReference;
595   double mCacheRadius;
596   double mWireCacheRadius;
597   osg::Matrix mLocalToGlobal;
598   osg::Matrix mGlobalToLocal;
599   SGVec3d mDown;
600   SGVec3d mLocalDown;
601   SGVec3d mLocalCacheReference;
602   bool sphIsec;
603   bool mBackfaceCulling;
604   FGGroundCache::GroundProperty mGroundProperty;
605 };
606
607 FGGroundCache::FGGroundCache()
608 {
609   cache_center = SGVec3d(0, 0, 0);
610   ground_radius = 0.0;
611   cache_ref_time = 0.0;
612   wire_id = 0;
613   reference_wgs84_point = SGVec3d(0, 0, 0);
614   reference_vehicle_radius = 0.0;
615   found_ground = false;
616 }
617
618 FGGroundCache::~FGGroundCache()
619 {
620 }
621
622 inline void
623 FGGroundCache::velocityTransformTriangle(double dt,
624                                          FGGroundCache::Triangle& dst,
625                                          const FGGroundCache::Triangle& src)
626 {
627   dst = src;
628
629   if (fabs(dt*dot(src.velocity, src.velocity)) < SGLimitsd::epsilon())
630     return;
631
632   for (int i = 0; i < 3; ++i) {
633     SGVec3d pivotoff = src.vertices[i] - src.rotation_pivot;
634     dst.vertices[i] += dt*(src.velocity + cross(src.rotation, pivotoff));
635   }
636   
637   // Transform the plane equation
638   SGVec3d pivotoff, vel;
639   sgdSubVec3(pivotoff.sg(), dst.plane.sg(), src.rotation_pivot.sg());
640   vel = src.velocity + cross(src.rotation, pivotoff);
641   dst.plane[3] += dt*sgdScalarProductVec3(dst.plane.sg(), vel.sg());
642   
643   dst.boundCenter += dt*src.velocity;
644 }
645
646 bool
647 FGGroundCache::prepare_ground_cache(double ref_time, const SGVec3d& pt,
648                                     double rad)
649 {
650   // Empty cache.
651   ground_radius = 0.0;
652   found_ground = false;
653   triangles.resize(0);
654   catapults.resize(0);
655   wires.resize(0);
656
657   // Store the parameters we used to build up that cache.
658   reference_wgs84_point = pt;
659   reference_vehicle_radius = rad;
660   // Store the time reference used to compute movements of moving triangles.
661   cache_ref_time = ref_time;
662
663   // Get a normalized down vector valid for the whole cache
664   SGQuatd hlToEc = SGQuatd::fromLonLat(SGGeod::fromCart(pt));
665   down = hlToEc.rotate(SGVec3d(0, 0, 1));
666
667   // Decide where we put the scenery center.
668   SGVec3d old_cntr = globals->get_scenery()->get_center();
669   SGVec3d cntr(pt);
670   // Only move the cache center if it is unacceptable far away.
671   if (40*40 < distSqr(old_cntr, cntr))
672     globals->get_scenery()->set_center(cntr);
673   else
674     cntr = old_cntr;
675
676   // The center of the cache.
677   cache_center = cntr;
678   
679   // Prepare sphere around the aircraft.
680   SGVec3d ptoff = pt - cache_center;
681   double cacheRadius = rad;
682
683   // Prepare bigger sphere around the aircraft.
684   // This one is required for reliably finding wires we have caught but
685   // have already left the hopefully smaller sphere for the ground reactions.
686   const double max_wire_dist = 300.0;
687   double wireCacheRadius = max_wire_dist < rad ? rad : max_wire_dist;
688
689   // Walk the scene graph and extract solid ground triangles and carrier data.
690   GroundCacheFillVisitor gcfv(this, down, ptoff, cacheRadius, wireCacheRadius);
691   globals->get_scenery()->get_scene_graph()->accept(gcfv);
692
693   // some stats
694   SG_LOG(SG_FLIGHT,SG_DEBUG, "prepare_ground_cache(): ac radius = " << rad
695          << ", # triangles = " << triangles.size()
696          << ", # wires = " << wires.size()
697          << ", # catapults = " << catapults.size()
698          << ", ground_radius = " << ground_radius );
699
700   // If the ground radius is still below 5e6 meters, then we do not yet have
701   // any scenery.
702   found_ground = found_ground && 5e6 < ground_radius;
703   if (!found_ground)
704     SG_LOG(SG_FLIGHT, SG_WARN, "prepare_ground_cache(): trying to build cache "
705            "without any scenery below the aircraft" );
706
707   if (cntr != old_cntr)
708     globals->get_scenery()->set_center(old_cntr);
709
710   return found_ground;
711 }
712
713 bool
714 FGGroundCache::is_valid(double& ref_time, SGVec3d& pt, double& rad)
715 {
716   pt = reference_wgs84_point;
717   rad = reference_vehicle_radius;
718   ref_time = cache_ref_time;
719   return found_ground;
720 }
721
722 double
723 FGGroundCache::get_cat(double t, const SGVec3d& dpt,
724                        SGVec3d end[2], SGVec3d vel[2])
725 {
726   // start with a distance of 1e10 meters...
727   double dist = 1e10;
728
729   // Time difference to the reference time.
730   t -= cache_ref_time;
731
732   size_t sz = catapults.size();
733   for (size_t i = 0; i < sz; ++i) {
734     SGVec3d pivotoff, rvel[2];
735     pivotoff = catapults[i].start - catapults[i].rotation_pivot;
736     rvel[0] = catapults[i].velocity + cross(catapults[i].rotation, pivotoff);
737     pivotoff = catapults[i].end - catapults[i].rotation_pivot;
738     rvel[1] = catapults[i].velocity + cross(catapults[i].rotation, pivotoff);
739
740     SGVec3d thisEnd[2];
741     thisEnd[0] = cache_center + catapults[i].start + t*rvel[0];
742     thisEnd[1] = cache_center + catapults[i].end + t*rvel[1];
743
744     sgdLineSegment3 ls;
745     sgdCopyVec3(ls.a, thisEnd[0].sg());
746     sgdCopyVec3(ls.b, thisEnd[1].sg());
747     double this_dist = sgdDistSquaredToLineSegmentVec3( ls, dpt.sg() );
748
749     if (this_dist < dist) {
750       SG_LOG(SG_FLIGHT,SG_INFO, "Found catapult "
751              << this_dist << " meters away");
752       dist = this_dist;
753         
754       end[0] = thisEnd[0];
755       end[1] = thisEnd[1];
756       vel[0] = rvel[0];
757       vel[1] = rvel[1];
758     }
759   }
760
761   // At the end take the root, we only computed squared distances ...
762   return sqrt(dist);
763 }
764
765 bool
766 FGGroundCache::get_agl(double t, const SGVec3d& dpt, double max_altoff,
767                        SGVec3d& contact, SGVec3d& normal, SGVec3d& vel,
768                        int *type, const SGMaterial** material, double *agl)
769 {
770   bool ret = false;
771
772   *type = FGInterface::Unknown;
773 //   *agl = 0.0;
774   if (material)
775     *material = 0;
776   vel = SGVec3d(0, 0, 0);
777   contact = SGVec3d(0, 0, 0);
778   normal = SGVec3d(0, 0, 0);
779
780   // Time difference to th reference time.
781   t -= cache_ref_time;
782
783   // The double valued point we start to search for intersection.
784   SGVec3d pt = dpt - cache_center;
785   // shift the start of our ray by maxaltoff upwards
786   SGVec3d raystart = pt - max_altoff*down;
787
788   // Initialize to something sensible
789   double current_radius = 0.0;
790
791   size_t sz = triangles.size();
792   for (size_t i = 0; i < sz; ++i) {
793     Triangle triangle;
794     velocityTransformTriangle(t, triangle, triangles[i]);
795     if (!fgdIsectSphereInfLine(triangle.boundCenter, triangle.boundRadius, pt, down))
796       continue;
797
798     // Check for intersection.
799     SGVec3d isecpoint;
800     if (fgdRayTriangle(isecpoint, raystart, down, triangle.vertices)) {
801       // Compute the vector from pt to the intersection point ...
802       SGVec3d off = isecpoint - pt;
803       // ... and check if it is too high or not
804       // Transform to the wgs system
805       isecpoint += cache_center;
806       // compute the radius, good enough approximation to take the geocentric radius
807       double radius = dot(isecpoint, isecpoint);
808       if (current_radius < radius) {
809         current_radius = radius;
810         ret = true;
811         // Save the new potential intersection point.
812         contact = isecpoint;
813         // The first three values in the vector are the plane normal.
814         sgdCopyVec3( normal.sg(), triangle.plane.sg() );
815         // The velocity wrt earth.
816         SGVec3d pivotoff = pt - triangle.rotation_pivot;
817         vel = triangle.velocity + cross(triangle.rotation, pivotoff);
818         // Save the ground type.
819         *type = triangle.type;
820         *agl = dot(down, contact - dpt);
821         if (material)
822           *material = triangle.material;
823       }
824     }
825   }
826
827   if (ret)
828     return true;
829
830   // Whenever we did not have a ground triangle for the requested point,
831   // take the ground level we found during the current cache build.
832   // This is as good as what we had before for agl.
833   double r = length(dpt);
834   contact = dpt;
835   contact *= ground_radius/r;
836   normal = -down;
837   vel = SGVec3d(0, 0, 0);
838   
839   // The altitude is the distance of the requested point from the
840   // contact point.
841   *agl = dot(down, contact - dpt);
842   *type = FGInterface::Unknown;
843
844   return ret;
845 }
846
847 bool FGGroundCache::caught_wire(double t, const SGVec3d pt[4])
848 {
849   size_t sz = wires.size();
850   if (sz == 0)
851     return false;
852
853   // Time difference to the reference time.
854   t -= cache_ref_time;
855
856   // Build the two triangles spanning the area where the hook has moved
857   // during the past step.
858   SGVec4d plane[2];
859   SGVec3d tri[2][3];
860   sgdMakePlane( plane[0].sg(), pt[0].sg(), pt[1].sg(), pt[2].sg() );
861   tri[0][0] = pt[0];
862   tri[0][1] = pt[1];
863   tri[0][2] = pt[2];
864   sgdMakePlane( plane[1].sg(), pt[0].sg(), pt[2].sg(), pt[3].sg() );
865   tri[1][0] = pt[0];
866   tri[1][1] = pt[2];
867   tri[1][2] = pt[3];
868
869   // Intersect the wire lines with each of these triangles.
870   // You have caught a wire if they intersect.
871   for (size_t i = 0; i < sz; ++i) {
872     SGVec3d le[2];
873     for (int k = 0; k < 2; ++k) {
874       le[k] = wires[i].ends[k];
875       SGVec3d pivotoff = le[k] - wires[i].rotation_pivot;
876       SGVec3d vel = wires[i].velocity + cross(wires[i].rotation, pivotoff);
877       le[k] += t*vel + cache_center;
878     }
879     
880     for (int k=0; k<2; ++k) {
881       SGVec3d isecpoint;
882       double isecval = sgdIsectLinesegPlane(isecpoint.sg(), le[0].sg(),
883                                             le[1].sg(), plane[k].sg());
884       if ( 0.0 <= isecval && isecval <= 1.0 &&
885            fgdPointInTriangle( isecpoint, tri[k] ) ) {
886         SG_LOG(SG_FLIGHT,SG_INFO, "Caught wire");
887         // Store the wire id.
888         wire_id = wires[i].wire_id;
889         return true;
890       }
891     }
892   }
893
894   return false;
895 }
896
897 bool FGGroundCache::get_wire_ends(double t, SGVec3d end[2], SGVec3d vel[2])
898 {
899   // Fast return if we do not have an active wire.
900   if (wire_id < 0)
901     return false;
902
903   // Time difference to the reference time.
904   t -= cache_ref_time;
905
906   // Search for the wire with the matching wire id.
907   size_t sz = wires.size();
908   for (size_t i = 0; i < sz; ++i) {
909     if (wires[i].wire_id == wire_id) {
910       for (size_t k = 0; k < 2; ++k) {
911         SGVec3d pivotoff = end[k] - wires[i].rotation_pivot;
912         vel[k] = wires[i].velocity + cross(wires[i].rotation, pivotoff);
913         end[k] = cache_center + wires[i].ends[k] + t*vel[k];
914       }
915       return true;
916     }
917   }
918
919   return false;
920 }
921
922 void FGGroundCache::release_wire(void)
923 {
924   wire_id = -1;
925 }