]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloudfield.cxx
Ganael Laplanche: fix include dependencies for FreeBSD support
[simgear.git] / simgear / scene / sky / cloudfield.cxx
1 // a layer of 3d clouds
2 //
3 // Written by Harald JOHNSEN, started April 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
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 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <osg/Fog>
28 #include <osg/Texture2D>
29 #include <osg/PositionAttitudeTransform>
30 #include <osg/Vec4f>
31 #include <osgSim/Impostor>
32
33 #include <simgear/compiler.h>
34
35 #include <simgear/math/sg_random.h>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/scene/util/SGSceneUserData.hxx>
38
39 #include <algorithm>
40 #include <vector>
41 #include <iostream>
42
43 using namespace std;
44
45 using std::vector;
46
47 //#include <simgear/environment/visual_enviro.hxx>
48 #include <simgear/scene/util/RenderConstants.hxx>
49 #include <simgear/scene/util/SGUpdateVisitor.hxx>
50 #include "sky.hxx"
51 #include "newcloud.hxx"
52 #include "cloudfield.hxx"
53
54 #if defined(__MINGW32__)
55 #define isnan(x) _isnan(x)
56 #endif
57
58 #if defined (__FreeBSD__)
59 #  if __FreeBSD_version < 500000
60      extern "C" {
61        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
62      }
63 #  endif
64 #endif
65
66 using namespace simgear;
67
68 float SGCloudField::fieldSize = 50000.0f;
69 double SGCloudField::timer_dt = 0.0;
70 float SGCloudField::view_distance = 20000.0f;
71 bool SGCloudField::wrap = true;
72 float SGCloudField::MAX_CLOUD_DEPTH = 2000.0f;
73 bool SGCloudField::use_impostors = false;
74 float SGCloudField::lod1_range = 8000.0f;
75 float SGCloudField::lod2_range = 4000.0f;
76 float SGCloudField::impostor_distance = 15000.0f;
77
78 int impostorcount = 0;
79 int lodcount = 0;
80 int cloudcount = 0;
81
82 SGVec3f SGCloudField::view_vec, SGCloudField::view_X, SGCloudField::view_Y;
83
84
85 // Reposition the cloud layer at the specified origin and orientation
86 bool SGCloudField::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
87                                double dt, int asl, float speed, float direction ) {
88     // Determine any movement of the placed clouds
89     if (placed_root->getNumChildren() == 0) return false;
90
91     SGVec3<double> cart;
92     SGGeod new_pos = SGGeod::fromRadFt(lon, lat, 0.0f);
93                             
94     SGGeodesy::SGGeodToCart(new_pos, cart);
95     osg::Vec3f osg_pos = toOsg(cart);
96     osg::Quat orient = toOsg(SGQuatd::fromLonLatRad(lon, lat) * SGQuatd::fromRealImag(0, SGVec3d(0, 1, 0)));
97     
98     // Always update the altitude transform, as this allows
99     // the clouds to rise and fall smoothly depending on environment updates.
100     altitude_transform->setPosition(osg::Vec3f(0.0f, 0.0f, (float) asl));
101     
102     // Similarly, always determine the effects of the wind
103     osg::Vec3f wind = osg::Vec3f(-cos((direction + 180)* SGD_DEGREES_TO_RADIANS) * speed * dt,
104                                  sin((direction + 180)* SGD_DEGREES_TO_RADIANS) * speed * dt,
105                                  0.0f);
106     osg::Vec3f windosg = field_transform->getAttitude() * wind;
107     field_transform->setPosition(field_transform->getPosition() + windosg);
108     
109     if (!wrap) {
110         // If we're not wrapping the cloudfield, then we make no effort to reposition
111         return false;
112     }
113         
114     if ((old_pos - osg_pos).length() > fieldSize*2) {
115         // Big movement - reposition centered to current location.
116         field_transform->setPosition(osg_pos);
117         field_transform->setAttitude(orient);
118         old_pos = osg_pos;
119     } else {        
120         osg::Quat fta =  field_transform->getAttitude();
121         osg::Quat ftainv = field_transform->getAttitude().inverse();
122         
123         // delta is the vector from the old position to the new position in cloud-coords
124         // osg::Vec3f delta = ftainv * (osg_pos - old_pos);
125         old_pos = osg_pos;
126                 
127         // Check if any of the clouds should be moved.
128         for(CloudHash::const_iterator itr = cloud_hash.begin(), end = cloud_hash.end();
129             itr != end;
130             ++itr) {
131               
132              osg::ref_ptr<osg::PositionAttitudeTransform> pat = itr->second;
133              osg::Vec3f currpos = field_transform->getPosition() + fta * pat->getPosition();
134                                       
135              // Determine the vector from the new position to the cloud in cloud-space.
136              osg::Vec3f w =  ftainv * (currpos - toOsg(cart));               
137               
138              // Determine a course if required. Note that this involves some axis translation.
139              float x = 0.0;
140              float y = 0.0;
141              if (w.x() >  0.6*fieldSize) { y =  fieldSize; }
142              if (w.x() < -0.6*fieldSize) { y = -fieldSize; }
143              if (w.y() >  0.6*fieldSize) { x = -fieldSize; }
144              if (w.y() < -0.6*fieldSize) { x =  fieldSize; }
145               
146              if ((x != 0.0) || (y != 0.0)) {
147                  removeCloudFromTree(pat);
148                  SGGeod p = SGGeod::fromCart(toSG(field_transform->getPosition() + 
149                                                   fta * pat->getPosition()));
150                  addCloudToTree(pat, p, x, y);                
151             }
152         }        
153     }
154     
155     // Render the clouds in order from farthest away layer to nearest one.
156     field_root->getStateSet()->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
157     return true;
158 }
159
160 SGCloudField::SGCloudField() :
161         field_root(new osg::Group),
162         field_transform(new osg::PositionAttitudeTransform),
163         altitude_transform(new osg::PositionAttitudeTransform)
164 {
165     old_pos = osg::Vec3f(0.0f, 0.0f, 0.0f);
166     field_root->addChild(field_transform.get());
167     field_root->setName("3D Cloud field root");
168     osg::StateSet *rootSet = field_root->getOrCreateStateSet();
169     rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
170     rootSet->setAttributeAndModes(getFog());
171     
172     field_transform->addChild(altitude_transform.get());
173     placed_root = new osg::Group();
174     altitude_transform->addChild(placed_root);
175     impostorcount = 0;
176     lodcount = 0;
177     cloudcount = 0;
178 }
179     
180 SGCloudField::~SGCloudField() {
181 }
182
183
184 void SGCloudField::clear(void) {
185
186     for(CloudHash::const_iterator itr = cloud_hash.begin(), end = cloud_hash.end();
187         itr != end;
188         ++itr) {
189         removeCloudFromTree(itr->second);
190     }
191     
192     cloud_hash.clear();
193 }
194
195 void SGCloudField::applyVisAndLoDRange(void)
196 {
197     for (unsigned int i = 0; i < placed_root->getNumChildren(); i++) {
198         osg::ref_ptr<osg::LOD> lodnode1 = (osg::LOD*) placed_root->getChild(i);
199         for (unsigned int j = 0; j < lodnode1->getNumChildren(); j++) {
200             lodnode1->setRange(j, 0.0f, lod1_range + lod2_range + view_distance + MAX_CLOUD_DEPTH);
201             osg::ref_ptr<osg::LOD> lodnode2 = (osg::LOD*) lodnode1->getChild(j);
202             for (unsigned int k = 0; k < lodnode2->getNumChildren(); k++) {
203                 lodnode2->setRange(k, 0.0f, view_distance + MAX_CLOUD_DEPTH);
204             }
205         }
206     }
207 }
208             
209 bool SGCloudField::addCloud(float lon, float lat, float alt, int index, osg::ref_ptr<EffectGeode> geode) {
210   return addCloud(lon, lat, alt, 0.0f, 0.0f, index, geode);
211 }
212
213 bool SGCloudField::addCloud(float lon, float lat, float alt, float x, float y, int index, osg::ref_ptr<EffectGeode> geode) {
214     // If this cloud index already exists, don't replace it.
215     if (cloud_hash[index]) return false;
216
217     osg::ref_ptr<osg::PositionAttitudeTransform> transform = new osg::PositionAttitudeTransform;
218
219     transform->addChild(geode.get());
220     addCloudToTree(transform, lon, lat, alt, x, y);
221     cloud_hash[index] = transform;
222     return true;
223 }
224
225 // Remove a give cloud from inside the tree, without removing it from the cloud hash
226 void SGCloudField::removeCloudFromTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform)
227 {
228     if (transform == 0)
229     {
230         // Ooops!
231         return;
232     }
233     osg::ref_ptr<osg::Group> lodnode = transform->getParent(0);
234     lodnode->removeChild(transform);
235     cloudcount--;
236
237     if (lodnode->getNumChildren() == 0) {
238         osg::ref_ptr<osg::Group> lodnode1 = lodnode->getParent(0);
239         osg::ref_ptr<osgSim::Impostor> impostornode = (osgSim::Impostor*) lodnode1->getParent(0);
240
241         lodnode1->removeChild(lodnode);
242         lodcount--;
243
244         if (lodnode1->getNumChildren() == 0) {
245           impostornode->removeChild(lodnode1);
246           placed_root->removeChild(impostornode);
247           impostorcount--;
248         }
249     }
250 }
251
252 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform,
253                                   float lon, float lat, float alt, float x, float y) {
254     
255     // Get the base position
256     SGGeod loc = SGGeod::fromDegFt(lon, lat, alt);
257     addCloudToTree(transform, loc, x, y);      
258 }
259
260
261 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform,
262                                   SGGeod loc, float x, float y) {
263         
264     float alt = loc.getElevationFt();
265     // Determine any shift by x/y
266     if ((x != 0.0f) || (y != 0.0f)) {
267         double crs = 90.0 - SG_RADIANS_TO_DEGREES * atan2(y, x); 
268         double dst = sqrt(x*x + y*y);
269         double endcrs;
270         
271         SGGeod base_pos = SGGeod::fromGeodFt(loc, 0.0f);            
272         SGGeodesy::direct(base_pos, crs, dst, loc, endcrs);
273     }
274     
275     // The direct call provides the position at 0 alt, so adjust as required.      
276     loc.setElevationFt(alt);    
277     addCloudToTree(transform, loc);    
278 }
279         
280         
281 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform, SGGeod loc) {        
282     // Work out where this cloud should go in OSG coordinates.
283     SGVec3<double> cart;
284     SGGeodesy::SGGeodToCart(loc, cart);
285     osg::Vec3f pos = toOsg(cart);
286
287
288     if (old_pos == osg::Vec3f(0.0f, 0.0f, 0.0f)) {
289         // First setup.
290         SGVec3<double> fieldcenter;
291         SGGeodesy::SGGeodToCart(SGGeod::fromDegFt(loc.getLongitudeDeg(), loc.getLatitudeDeg(), 0.0f), fieldcenter);
292         // Convert to the scenegraph orientation where we just rotate around
293         // the y axis 180 degrees.
294         osg::Quat orient = toOsg(SGQuatd::fromLonLatDeg(loc.getLongitudeDeg(), loc.getLatitudeDeg()) * SGQuatd::fromRealImag(0, SGVec3d(0, 1, 0)));
295         
296         osg::Vec3f osg_pos = toOsg(fieldcenter);            
297         
298         field_transform->setPosition(osg_pos);
299         field_transform->setAttitude(orient);
300         old_pos = osg_pos;
301     }
302     
303     // Convert position to cloud-coordinates
304     pos = pos - field_transform->getPosition();
305     pos = field_transform->getAttitude().inverse() * pos;    
306
307     // We have a two level dynamic quad tree which the cloud will be added
308     // to. If there are no appropriate nodes in the quad tree, they are
309     // created as required.
310     bool found = false;
311     osg::ref_ptr<osg::LOD> lodnode1;
312     osg::ref_ptr<osg::LOD> lodnode;
313     osg::ref_ptr<osgSim::Impostor> impostornode;
314
315     for (unsigned int i = 0; (!found) && (i < placed_root->getNumChildren()); i++) {
316         lodnode1 = (osg::LOD*) placed_root->getChild(i);
317         if ((lodnode1->getCenter() - pos).length2() < lod1_range*lod1_range) {
318           // New cloud is within RADIUS_LEVEL_1 of the center of the LOD node.
319           found = true;
320         }         
321     }
322
323     if (!found) {
324         if (use_impostors) {
325           impostornode = new osgSim::Impostor();
326           impostornode->setImpostorThreshold(impostor_distance);
327           //impostornode->setImpostorThresholdToBound();
328           //impostornode->setCenter(pos);                
329           placed_root->addChild(impostornode.get());
330           lodnode1 = (osg::ref_ptr<osg::LOD>) impostornode;
331         } else {
332           lodnode1 = new osg::LOD();
333           placed_root->addChild(lodnode1.get());
334         }
335         impostorcount++;
336     }
337
338     // Now check if there is a second level LOD node at an appropriate distance
339     found = false;
340     
341     for (unsigned int j = 0; (!found) && (j < lodnode1->getNumChildren()); j++) {      
342         lodnode = (osg::LOD*) lodnode1->getChild(j);
343         if ((lodnode->getCenter() - pos).length2() < lod2_range*lod2_range) {
344             // We've found the right leaf LOD node
345             found = true;
346         }
347     }
348
349     if (!found) {
350         // No suitable leaf node was found, so we need to add one.
351         lodnode = new osg::LOD();
352         lodnode1->addChild(lodnode, 0.0f, lod1_range + lod2_range + view_distance + MAX_CLOUD_DEPTH);
353         lodcount++;
354     } 
355     
356     transform->setPosition(pos);
357     lodnode->addChild(transform.get(), 0.0f, view_distance + MAX_CLOUD_DEPTH);
358     cloudcount++;
359     SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "Impostors: " << impostorcount <<
360                                      " LoD: " << lodcount << 
361                                      " Clouds: " << cloudcount);
362
363     lodnode->dirtyBound();
364     lodnode1->dirtyBound();
365     field_root->dirtyBound();
366 }
367         
368 bool SGCloudField::deleteCloud(int identifier) {
369     osg::ref_ptr<osg::PositionAttitudeTransform> transform = cloud_hash[identifier];
370     if (transform == NULL) return false;
371         
372     removeCloudFromTree(transform);
373     cloud_hash.erase(identifier);
374
375     return true;
376 }
377         
378 bool SGCloudField::repositionCloud(int identifier, float lon, float lat, float alt) {
379     return repositionCloud(identifier, lon, lat, alt, 0.0f, 0.0f);
380 }
381
382 bool SGCloudField::repositionCloud(int identifier, float lon, float lat, float alt, float x, float y) {
383     osg::ref_ptr<osg::PositionAttitudeTransform> transform = cloud_hash[identifier];
384     
385     if (transform == NULL) return false;
386
387     removeCloudFromTree(transform);
388     addCloudToTree(transform, lon, lat, alt, x, y);
389     return true;
390     }
391
392 bool SGCloudField::isDefined3D(void) {
393     return (cloud_hash.size() > 0);
394 }
395
396 SGCloudField::CloudFog::CloudFog() {
397     fog = new osg::Fog;
398     fog->setMode(osg::Fog::EXP2);
399     fog->setDataVariance(osg::Object::DYNAMIC);
400 }
401
402 void SGCloudField::updateFog(double visibility, const osg::Vec4f& color) {
403     const double sqrt_m_log01 = sqrt(-log(0.01));
404     osg::Fog* fog = CloudFog::instance()->fog.get();
405     fog->setColor(color);
406     fog->setDensity(sqrt_m_log01 / visibility);
407 }
408