]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/pt_lights.cxx
Put airport lights in RenderBin to enable glow
[simgear.git] / simgear / scene / tgdb / pt_lights.cxx
1 // pt_lights.cxx -- build a 'directional' light on the fly
2 //
3 // Written by Curtis Olson, started March 2002.
4 //
5 // Copyright (C) 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
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 <simgear_config.h>
25 #endif
26
27 #include "pt_lights.hxx"
28
29 #include <map>
30 #include <boost/tuple/tuple_comparison.hpp>
31
32 #include <osg/Array>
33 #include <osg/Geometry>
34 #include <osg/CullFace>
35 #include <osg/Geode>
36 #include <osg/MatrixTransform>
37 #include <osg/NodeCallback>
38 #include <osg/NodeVisitor>
39 #include <osg/Texture2D>
40 #include <osg/AlphaFunc>
41 #include <osg/BlendFunc>
42 #include <osg/TexEnv>
43 #include <osg/Sequence>
44 #include <osg/PolygonMode>
45 #include <osg/Fog>
46 #include <osg/FragmentProgram>
47 #include <osg/VertexProgram>
48 #include <osg/Point>
49 #include <osg/PointSprite>
50 #include <osg/Material>
51 #include <osg/Group>
52 #include <osg/StateSet>
53
54 #include <osgUtil/CullVisitor>
55
56 #include <OpenThreads/Mutex>
57 #include <OpenThreads/ScopedLock>
58
59 #include <simgear/math/sg_random.h>
60 #include <simgear/debug/logstream.hxx>
61 #include <simgear/scene/util/RenderConstants.hxx>
62 #include <simgear/scene/util/SGEnlargeBoundingBox.hxx>
63 #include <simgear/scene/util/OsgMath.hxx>
64 #include <simgear/scene/util/StateAttributeFactory.hxx>
65
66 #include <simgear/scene/material/Effect.hxx>
67 #include <simgear/scene/material/EffectGeode.hxx>
68 #include <simgear/scene/material/Technique.hxx>
69 #include <simgear/scene/material/Pass.hxx>
70
71 #include "SGVasiDrawable.hxx"
72
73 using OpenThreads::Mutex;
74 using OpenThreads::ScopedLock;
75
76 using namespace osg;
77 using namespace simgear;
78
79 static void
80 setPointSpriteImage(unsigned char* data, unsigned log2resolution,
81                     unsigned charsPerPixel)
82 {
83   int env_tex_res = (1 << log2resolution);
84   for (int i = 0; i < env_tex_res; ++i) {
85     for (int j = 0; j < env_tex_res; ++j) {
86       int xi = 2*i + 1 - env_tex_res;
87       int yi = 2*j + 1 - env_tex_res;
88       if (xi < 0)
89         xi = -xi;
90       if (yi < 0)
91         yi = -yi;
92       
93       xi -= 1;
94       yi -= 1;
95       
96       if (xi < 0)
97         xi = 0;
98       if (yi < 0)
99         yi = 0;
100       
101       float x = 1.5*xi/(float)(env_tex_res);
102       float y = 1.5*yi/(float)(env_tex_res);
103       //       float x = 2*xi/(float)(env_tex_res);
104       //       float y = 2*yi/(float)(env_tex_res);
105       float dist = sqrt(x*x + y*y);
106       float bright = SGMiscf::clip(255*(1-dist), 0, 255);
107       for (unsigned l = 0; l < charsPerPixel; ++l)
108         data[charsPerPixel*(i*env_tex_res + j) + l] = (unsigned char)bright;
109     }
110   }
111 }
112
113 static osg::Image*
114 getPointSpriteImage(int logResolution)
115 {
116   osg::Image* image = new osg::Image;
117   
118   osg::Image::MipmapDataType mipmapOffsets;
119   unsigned off = 0;
120   for (int i = logResolution; 0 <= i; --i) {
121     unsigned res = 1 << i;
122     off += res*res;
123     mipmapOffsets.push_back(off);
124   }
125   
126   int env_tex_res = (1 << logResolution);
127   
128   unsigned char* imageData = new unsigned char[off];
129   image->setImage(env_tex_res, env_tex_res, 1,
130                   GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, imageData,
131                   osg::Image::USE_NEW_DELETE);
132   image->setMipmapLevels(mipmapOffsets);
133   
134   for (int k = logResolution; 0 <= k; --k) {
135     setPointSpriteImage(image->getMipmapData(logResolution - k), k, 1);
136   }
137   
138   return image;
139 }
140
141 static Mutex lightMutex;
142
143 static osg::Texture2D*
144 gen_standard_light_sprite(void)
145 {
146   // Always called from when the lightMutex is already taken
147   static osg::ref_ptr<osg::Texture2D> texture;
148   if (texture.valid())
149     return texture.get();
150   
151   texture = new osg::Texture2D;
152   texture->setImage(getPointSpriteImage(6));
153   texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP);
154   texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP);
155   
156   return texture.get();
157 }
158
159 namespace
160 {
161 typedef boost::tuple<float, osg::Vec3, float, float, bool> PointParams;
162 typedef std::map<PointParams, ref_ptr<Effect> > EffectMap;
163
164 EffectMap effectMap;
165
166 ref_ptr<PolygonMode> polyMode = new PolygonMode(PolygonMode::FRONT,
167                                                 PolygonMode::POINT);
168 ref_ptr<PointSprite> pointSprite = new PointSprite;
169 }
170
171 Effect* getLightEffect(float size, const Vec3& attenuation,
172                        float minSize, float maxSize, bool directional)
173 {
174     PointParams pointParams(size, attenuation, minSize, maxSize, directional);
175     ScopedLock<Mutex> lock(lightMutex);
176     EffectMap::iterator eitr = effectMap.find(pointParams);
177     if (eitr != effectMap.end())
178         return eitr->second.get();
179     // Basic stuff; no sprite or attenuation support
180     Pass *basicPass = new Pass;
181     basicPass->setRenderBinDetails(POINT_LIGHTS_BIN, "RenderBin");
182     basicPass->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
183     StateAttributeFactory *attrFact = StateAttributeFactory::instance();
184     basicPass->setAttributeAndModes(attrFact->getStandardBlendFunc());
185     basicPass->setAttributeAndModes(attrFact->getStandardAlphaFunc());
186     if (directional) {
187         basicPass->setAttributeAndModes(attrFact->getCullFaceBack());
188         basicPass->setAttribute(polyMode.get());
189     }
190     Pass *attenuationPass = clone(basicPass, CopyOp::SHALLOW_COPY);
191     osg::Point* point = new osg::Point;
192     point->setMinSize(minSize);
193     point->setMaxSize(maxSize);
194     point->setSize(size);
195     point->setDistanceAttenuation(attenuation);
196     attenuationPass->setAttributeAndModes(point);
197     Pass *spritePass = clone(basicPass, CopyOp::SHALLOW_COPY);
198     spritePass->setTextureAttributeAndModes(0, pointSprite.get(),
199                                             osg::StateAttribute::ON);
200     Texture2D* texture = gen_standard_light_sprite();
201     spritePass->setTextureAttribute(0, texture);
202     spritePass->setTextureMode(0, GL_TEXTURE_2D,
203                                osg::StateAttribute::ON);
204     spritePass->setTextureAttribute(0, attrFact->getStandardTexEnv());
205     Pass *combinedPass = clone(spritePass, CopyOp::SHALLOW_COPY);
206     combinedPass->setAttributeAndModes(point);
207     Effect* effect = new Effect;
208     std::vector<std::string> parameterExtensions;
209
210     if (SGSceneFeatures::instance()->getEnablePointSpriteLights())
211     {
212         std::vector<std::string> combinedExtensions;
213         combinedExtensions.push_back("GL_ARB_point_sprite");
214         combinedExtensions.push_back("GL_ARB_point_parameters");
215         Technique* combinedTniq = new Technique;
216         combinedTniq->passes.push_back(combinedPass);
217         combinedTniq->setGLExtensionsPred(2.0, combinedExtensions);
218         effect->techniques.push_back(combinedTniq);
219         std::vector<std::string> spriteExtensions;
220         spriteExtensions.push_back(combinedExtensions.front());
221         Technique* spriteTniq = new Technique;
222         spriteTniq->passes.push_back(spritePass);
223         spriteTniq->setGLExtensionsPred(2.0, spriteExtensions);
224         effect->techniques.push_back(spriteTniq);
225         parameterExtensions.push_back(combinedExtensions.back());
226     }
227
228     Technique* parameterTniq = new Technique;
229     parameterTniq->passes.push_back(attenuationPass);
230     parameterTniq->setGLExtensionsPred(1.4, parameterExtensions);
231     effect->techniques.push_back(parameterTniq);
232     Technique* basicTniq = new Technique(true);
233     basicTniq->passes.push_back(basicPass);
234     effect->techniques.push_back(basicTniq);
235     effectMap.insert(std::make_pair(pointParams, effect));
236     return effect;
237 }
238
239
240 osg::Drawable*
241 SGLightFactory::getLightDrawable(const SGLightBin::Light& light)
242 {
243   osg::Vec3Array* vertices = new osg::Vec3Array;
244   osg::Vec4Array* colors = new osg::Vec4Array;
245
246   vertices->push_back(toOsg(light.position));
247   colors->push_back(toOsg(light.color));
248   
249   osg::Geometry* geometry = new osg::Geometry;
250   geometry->setVertexArray(vertices);
251   geometry->setNormalBinding(osg::Geometry::BIND_OFF);
252   geometry->setColorArray(colors);
253   geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
254
255   // Enlarge the bounding box to avoid such light nodes being victim to
256   // small feature culling.
257   geometry->setComputeBoundingBoxCallback(new SGEnlargeBoundingBox(1));
258   
259   osg::DrawArrays* drawArrays;
260   drawArrays = new osg::DrawArrays(osg::PrimitiveSet::POINTS,
261                                    0, vertices->size());
262   geometry->addPrimitiveSet(drawArrays);
263   return geometry;
264 }
265
266 osg::Drawable*
267 SGLightFactory::getLightDrawable(const SGDirectionalLightBin::Light& light)
268 {
269   osg::Vec3Array* vertices = new osg::Vec3Array;
270   osg::Vec4Array* colors = new osg::Vec4Array;
271
272   SGVec4f visibleColor(light.color);
273   SGVec4f invisibleColor(visibleColor[0], visibleColor[1],
274                          visibleColor[2], 0);
275   SGVec3f normal = normalize(light.normal);
276   SGVec3f perp1 = perpendicular(normal);
277   SGVec3f perp2 = cross(normal, perp1);
278   SGVec3f position = light.position;
279   vertices->push_back(toOsg(position));
280   vertices->push_back(toOsg(position + perp1));
281   vertices->push_back(toOsg(position + perp2));
282   colors->push_back(toOsg(visibleColor));
283   colors->push_back(toOsg(invisibleColor));
284   colors->push_back(toOsg(invisibleColor));
285   
286   osg::Geometry* geometry = new osg::Geometry;
287   geometry->setVertexArray(vertices);
288   geometry->setNormalBinding(osg::Geometry::BIND_OFF);
289   geometry->setColorArray(colors);
290   geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
291   // Enlarge the bounding box to avoid such light nodes being victim to
292   // small feature culling.
293   geometry->setComputeBoundingBoxCallback(new SGEnlargeBoundingBox(1));
294   
295   osg::DrawArrays* drawArrays;
296   drawArrays = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES,
297                                    0, vertices->size());
298   geometry->addPrimitiveSet(drawArrays);
299   return geometry;
300 }
301
302 namespace
303 {
304   ref_ptr<StateSet> simpleLightSS;
305 }
306 osg::Drawable*
307 SGLightFactory::getLights(const SGLightBin& lights, unsigned inc, float alphaOff)
308 {
309   if (lights.getNumLights() <= 0)
310     return 0;
311   
312   osg::Vec3Array* vertices = new osg::Vec3Array;
313   osg::Vec4Array* colors = new osg::Vec4Array;
314
315   for (unsigned i = 0; i < lights.getNumLights(); i += inc) {
316     vertices->push_back(toOsg(lights.getLight(i).position));
317     SGVec4f color = lights.getLight(i).color;
318     color[3] = SGMiscf::max(0, SGMiscf::min(1, color[3] + alphaOff));
319     colors->push_back(toOsg(color));
320   }
321   
322   osg::Geometry* geometry = new osg::Geometry;
323   
324   geometry->setVertexArray(vertices);
325   geometry->setNormalBinding(osg::Geometry::BIND_OFF);
326   geometry->setColorArray(colors);
327   geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
328   
329   osg::DrawArrays* drawArrays;
330   drawArrays = new osg::DrawArrays(osg::PrimitiveSet::POINTS,
331                                    0, vertices->size());
332   geometry->addPrimitiveSet(drawArrays);
333
334   {
335     ScopedLock<Mutex> lock(lightMutex);
336     if (!simpleLightSS.valid()) {
337       StateAttributeFactory *attrFact = StateAttributeFactory::instance();
338       simpleLightSS = new StateSet;
339       simpleLightSS->setRenderBinDetails(POINT_LIGHTS_BIN, "RenderBin");
340       simpleLightSS->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
341       simpleLightSS->setAttributeAndModes(attrFact->getStandardBlendFunc());
342       simpleLightSS->setAttributeAndModes(attrFact->getStandardAlphaFunc());
343     }
344   }
345   geometry->setStateSet(simpleLightSS.get());
346   return geometry;
347 }
348
349
350 osg::Drawable*
351 SGLightFactory::getLights(const SGDirectionalLightBin& lights)
352 {
353   if (lights.getNumLights() <= 0)
354     return 0;
355   
356   osg::Vec3Array* vertices = new osg::Vec3Array;
357   osg::Vec4Array* colors = new osg::Vec4Array;
358
359   for (unsigned i = 0; i < lights.getNumLights(); ++i) {
360     SGVec4f visibleColor(lights.getLight(i).color);
361     SGVec4f invisibleColor(visibleColor[0], visibleColor[1],
362                            visibleColor[2], 0);
363     SGVec3f normal = normalize(lights.getLight(i).normal);
364     SGVec3f perp1 = perpendicular(normal);
365     SGVec3f perp2 = cross(normal, perp1);
366     SGVec3f position = lights.getLight(i).position;
367     vertices->push_back(toOsg(position));
368     vertices->push_back(toOsg(position + perp1));
369     vertices->push_back(toOsg(position + perp2));
370     colors->push_back(toOsg(visibleColor));
371     colors->push_back(toOsg(invisibleColor));
372     colors->push_back(toOsg(invisibleColor));
373   }
374   
375   osg::Geometry* geometry = new osg::Geometry;
376   
377   geometry->setVertexArray(vertices);
378   geometry->setNormalBinding(osg::Geometry::BIND_OFF);
379   geometry->setColorArray(colors);
380   geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
381   
382   osg::DrawArrays* drawArrays;
383   drawArrays = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES,
384                                    0, vertices->size());
385   geometry->addPrimitiveSet(drawArrays);
386   return geometry;
387 }
388
389 static SGVasiDrawable*
390 buildVasi(const SGDirectionalLightBin& lights, const SGVec3f& up,
391        const SGVec4f& red, const SGVec4f& white)
392 {
393   unsigned count = lights.getNumLights();
394   if ( count == 4 ) {
395     SGVasiDrawable* drawable = new SGVasiDrawable(red, white);
396
397     // PAPI configuration
398     // papi D
399     drawable->addLight(lights.getLight(0).position,
400                        lights.getLight(0).normal, up, 3.5);
401     // papi C
402     drawable->addLight(lights.getLight(1).position,
403                        lights.getLight(1).normal, up, 3.167);
404     // papi B
405     drawable->addLight(lights.getLight(2).position,
406                        lights.getLight(2).normal, up, 2.833);
407     // papi A
408     drawable->addLight(lights.getLight(3).position,
409                        lights.getLight(3).normal, up, 2.5);
410     return drawable;
411
412   } else if (count == 6) {
413     SGVasiDrawable* drawable = new SGVasiDrawable(red, white);
414
415     // probably vasi, first 3 are downwind bar (2.5 deg)
416     for (unsigned i = 0; i < 3; ++i)
417       drawable->addLight(lights.getLight(i).position,
418                          lights.getLight(i).normal, up, 2.5);
419     // last 3 are upwind bar (3.0 deg)
420     for (unsigned i = 3; i < 6; ++i)
421       drawable->addLight(lights.getLight(i).position,
422                          lights.getLight(i).normal, up, 3.0);
423     return drawable;
424
425   } else if (count == 12) {
426     SGVasiDrawable* drawable = new SGVasiDrawable(red, white);
427     
428     // probably vasi, first 6 are downwind bar (2.5 deg)
429     for (unsigned i = 0; i < 6; ++i)
430       drawable->addLight(lights.getLight(i).position,
431                          lights.getLight(i).normal, up, 2.5);
432     // last 6 are upwind bar (3.0 deg)
433     for (unsigned i = 6; i < 12; ++i)
434       drawable->addLight(lights.getLight(i).position,
435                          lights.getLight(i).normal, up, 3.0);
436     return drawable;
437
438   } else {
439     // fail safe
440     SG_LOG(SG_TERRAIN, SG_ALERT,
441            "unknown vasi/papi configuration, count = " << count);
442     return 0;
443   }
444 }
445
446 osg::Drawable*
447 SGLightFactory::getVasi(const SGVec3f& up, const SGDirectionalLightBin& lights,
448                         const SGVec4f& red, const SGVec4f& white)
449 {
450   SGVasiDrawable* drawable = buildVasi(lights, up, red, white);
451   if (!drawable)
452     return 0;
453
454   osg::StateSet* stateSet = drawable->getOrCreateStateSet();
455   stateSet->setRenderBinDetails(POINT_LIGHTS_BIN, "RenderBin");
456   stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
457
458   osg::BlendFunc* blendFunc = new osg::BlendFunc;
459   stateSet->setAttribute(blendFunc);
460   stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
461   
462   osg::AlphaFunc* alphaFunc;
463   alphaFunc = new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01);
464   stateSet->setAttribute(alphaFunc);
465   stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
466
467   return drawable;
468 }
469
470 osg::Node*
471 SGLightFactory::getSequenced(const SGDirectionalLightBin& lights)
472 {
473   if (lights.getNumLights() <= 0)
474     return 0;
475
476   // generate a repeatable random seed
477   sg_srandom(unsigned(lights.getLight(0).position[0]));
478   float flashTime = 2e-2 + 5e-3*sg_random();
479   osg::Sequence* sequence = new osg::Sequence;
480   sequence->setDefaultTime(flashTime);
481   Effect* effect = getLightEffect(10.0f, osg::Vec3(1.0, 0.0001, 0.00000001),
482                                   6.0f, 10.0f, true);
483   for (int i = lights.getNumLights() - 1; 0 <= i; --i) {
484     EffectGeode* egeode = new EffectGeode;
485     egeode->setEffect(effect);
486     egeode->addDrawable(getLightDrawable(lights.getLight(i)));
487     sequence->addChild(egeode, flashTime);
488   }
489   sequence->addChild(new osg::Group, 1 + 1e-1*sg_random());
490   sequence->setInterval(osg::Sequence::LOOP, 0, -1);
491   sequence->setDuration(1.0f, -1);
492   sequence->setMode(osg::Sequence::START);
493   sequence->setSync(true);
494   return sequence;
495 }
496
497 osg::Node*
498 SGLightFactory::getOdal(const SGLightBin& lights)
499 {
500   if (lights.getNumLights() < 2)
501     return 0;
502
503   // generate a repeatable random seed
504   sg_srandom(unsigned(lights.getLight(0).position[0]));
505   float flashTime = 2e-2 + 5e-3*sg_random();
506   osg::Sequence* sequence = new osg::Sequence;
507   sequence->setDefaultTime(flashTime);
508   Effect* effect = getLightEffect(10.0f, osg::Vec3(1.0, 0.0001, 0.00000001),
509                                   6.0, 10.0, false);
510   // centerline lights
511   for (int i = lights.getNumLights() - 1; 2 <= i; --i) {
512     EffectGeode* egeode = new EffectGeode;
513     egeode->setEffect(effect);
514     egeode->addDrawable(getLightDrawable(lights.getLight(i)));
515     sequence->addChild(egeode, flashTime);
516   }
517   // runway end lights
518   osg::Group* group = new osg::Group;
519   for (unsigned i = 0; i < 2; ++i) {
520     EffectGeode* egeode = new EffectGeode;
521     egeode->setEffect(effect);
522     egeode->addDrawable(getLightDrawable(lights.getLight(i)));
523     group->addChild(egeode);
524   }
525   sequence->addChild(group, flashTime);
526
527   // add an extra empty group for a break
528   sequence->addChild(new osg::Group, 9 + 1e-1*sg_random());
529   sequence->setInterval(osg::Sequence::LOOP, 0, -1);
530   sequence->setDuration(1.0f, -1);
531   sequence->setMode(osg::Sequence::START);
532   sequence->setSync(true);
533
534   return sequence;
535 }