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