]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/SGOceanTile.cxx
Fixes for headless mode.
[simgear.git] / simgear / scene / tgdb / SGOceanTile.cxx
1 /* -*-c++-*-
2  *
3  * Copyright (C) 2006-2007 Mathias Froehlich, Tim Moore
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18  * MA 02110-1301, USA.
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #  include <simgear_config.h>
24 #endif
25
26 #include "SGOceanTile.hxx"
27
28 #include <math.h>
29 #include <simgear/compiler.h>
30
31 #include <osg/Geode>
32 #include <osg/Geometry>
33 #include <osg/MatrixTransform>
34 #include <osg/StateSet>
35
36 #include <simgear/bucket/newbucket.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/math/sg_types.hxx>
39 #include <simgear/misc/texcoord.hxx>
40 #include <simgear/scene/material/Effect.hxx>
41 #include <simgear/scene/material/EffectGeode.hxx>
42 #include <simgear/scene/material/mat.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44
45 #include <simgear/scene/util/VectorArrayAdapter.hxx>
46
47 using namespace simgear;
48 // Ocean tile with curvature and apron to hide cracks. The cracks are
49 // mostly with adjoining coastal tiles that assume a flat ocean
50 // between corners of a tile; they also hide the micro cracks between
51 // adjoining ocean tiles. This is probably over-engineered, but it
52 // serves as a testbed for some things that will come later.
53
54 // Helper class for building and accessing the mesh. The layout of the
55 // points in the mesh is a little wacky. First is the bottom row of
56 // the points for the apron. Next is the left apron point, the points
57 // in the mesh, and the right apron point, for each of the rows of the
58 // mesh; the points for the top apron come last. This order should
59 // help with things like vertex caching in the OpenGL driver, though
60 // it may be superfluous for such a small mesh.
61 namespace
62 {
63 class OceanMesh {
64 public:
65     OceanMesh(int latP, int lonP):
66         latPoints(latP),
67         lonPoints(lonP),
68         geoPoints(latPoints * lonPoints + 2 * (lonPoints + latPoints)),
69         geod_nodes(latPoints * lonPoints),
70         vl(new osg::Vec3Array(geoPoints)),
71         nl(new osg::Vec3Array(geoPoints)),
72         tl(new osg::Vec2Array(geoPoints)),
73         vlArray(*vl, lonPoints + 2, lonPoints, 1),
74         nlArray(*nl, lonPoints + 2, lonPoints, 1),
75         tlArray(*tl, lonPoints + 2, lonPoints, 1)
76     {
77         int numPoints = latPoints * lonPoints;
78         geod = new SGGeod[numPoints];
79         normals = new SGVec3f[numPoints];
80         rel = new SGVec3d[numPoints];
81     }
82     
83     ~OceanMesh()
84     {
85         delete[] geod;
86         delete[] normals;
87         delete[] rel;
88     }
89     
90     const int latPoints, lonPoints;
91     const int geoPoints;
92     SGGeod* geod;
93     SGVec3f* normals;
94     SGVec3d* rel;
95
96     std::vector<SGGeod> geod_nodes;
97
98     osg::Vec3Array* vl;
99     osg::Vec3Array* nl;
100     osg::Vec2Array* tl;
101     VectorArrayAdapter<osg::Vec3Array> vlArray;
102     VectorArrayAdapter<osg::Vec3Array> nlArray;
103     VectorArrayAdapter<osg::Vec2Array> tlArray;
104
105     void calcMesh(const SGVec3d& cartCenter, const SGQuatd& orient,
106                   double clon, double clat,
107                   double height, double width, double tex_width);
108     void calcApronPt(int latIdx, int lonIdx, int latInner, int lonInner,
109                      int destIdx, double tex_width);
110     void calcApronPts(double tex_width);
111     
112 };
113 }
114
115 void OceanMesh::calcMesh(const SGVec3d& cartCenter, const SGQuatd& orient,
116                          double clon, double clat,
117                          double height, double width, double tex_width)
118 {
119     // Calculate vertices. By splitting the tile up into 4 quads on a
120     // side we avoid curvature-of-the-earth problems; the error should
121     // be less than .5 meters.
122     double longInc = width * .25;
123     double latInc = height * .25;
124     double startLat = clat - height * .5;
125     double startLon = clon - width * .5;
126     for (int j = 0; j < latPoints; j++) {
127         double lat = startLat + j * latInc;
128         for (int i = 0; i < lonPoints; i++) {
129             int index = (j * lonPoints) + i;
130             geod[index] = SGGeod::fromDeg(startLon + i * longInc, lat);
131             SGVec3d cart = SGVec3d::fromGeod(geod[index]);
132             rel[index] = orient.transform(cart - cartCenter);
133             normals[index] = toVec3f(orient.transform(normalize(cart)));
134         }
135     }
136     
137     // Calculate texture coordinates
138     typedef std::vector<SGGeod> GeodVector;
139     
140     GeodVector geod_nodes(latPoints * lonPoints);
141     VectorArrayAdapter<GeodVector> geodNodesArray(geod_nodes, lonPoints);
142     int_list rectangle(latPoints * lonPoints);
143     VectorArrayAdapter<int_list> rectArray(rectangle, lonPoints);
144     for (int j = 0; j < latPoints; j++) {
145         for (int i = 0; i < lonPoints; i++) {
146             int index = (j * lonPoints) + i;
147             geodNodesArray(j, i) = geod[index];
148             rectArray(j, i) = index;
149         }
150     }
151     
152     typedef std::vector<SGVec2f> Vec2Array;
153     Vec2Array texs = sgCalcTexCoords( clat, geod_nodes, rectangle, 
154                                        1000.0 / tex_width );
155                                 
156                                        
157     VectorArrayAdapter<Vec2Array> texsArray(texs, lonPoints);
158   
159     for (int j = 0; j < latPoints; j++) {
160         for (int i = 0; i < lonPoints; ++i) {
161             int index = (j * lonPoints) + i;
162             vlArray(j, i) = toOsg(rel[index]);
163             nlArray(j, i) = toOsg(normals[index]);
164             tlArray(j, i) = toOsg(texsArray(j, i));
165         }
166     }
167
168 }
169
170 // Apron points. For each point on the edge we'll go 150
171 // metres "down" and 40 metres "out" to create a nice overlap. The
172 // texture should be applied according to this dimension. The
173 // normals of the apron polygons will be the same as the those of
174 // the points on the edge to better disguise the apron.
175 void OceanMesh::calcApronPt(int latIdx, int lonIdx, int latInner, int lonInner,
176                             int destIdx, double tex_width)
177 {
178     static const float downDist = 150.0f;
179     static const float outDist = 40.0f;
180     // Get vector along edge, in the right direction to make a cross
181     // product with the normal vector that will point out from the
182     // mesh.
183     osg::Vec3f edgePt = vlArray(latIdx, lonIdx);
184     osg::Vec3f edgeVec;
185     if (lonIdx == lonInner) {   // bottom or top edge
186         if (lonIdx > 0)
187             edgeVec = vlArray(latIdx, lonIdx - 1) - edgePt;
188         else
189             edgeVec = edgePt - vlArray(latIdx, lonIdx + 1);
190         if (latIdx > latInner)
191             edgeVec = -edgeVec;  // Top edge
192     } else {                     // right or left edge
193         if (latIdx > 0)
194             edgeVec = edgePt - vlArray(latIdx - 1, lonIdx);
195         else
196             edgeVec = vlArray(latIdx + 1, lonIdx) - edgePt;
197         if (lonIdx > lonInner)  // right edge
198             edgeVec = -edgeVec;
199     }
200     edgeVec.normalize();
201     osg::Vec3f outVec = nlArray(latIdx, lonIdx) ^ edgeVec;
202     (*vl)[destIdx]
203         = edgePt - nlArray(latIdx, lonIdx) * downDist + outVec * outDist;
204     (*nl)[destIdx] = nlArray(latIdx, lonIdx);
205     static const float apronDist
206         = sqrtf(downDist * downDist  + outDist * outDist);
207     float texDelta = apronDist / tex_width;
208     if (lonIdx == lonInner) {
209         if (latIdx > latInner)
210             (*tl)[destIdx]
211                 = tlArray(latIdx, lonIdx) + osg::Vec2f(0.0f, texDelta);
212         else
213             (*tl)[destIdx]
214                 = tlArray(latIdx, lonIdx) - osg::Vec2f(0.0f, texDelta);
215     } else {
216         if (lonIdx > lonInner)
217             (*tl)[destIdx]
218                 = tlArray(latIdx, lonIdx) + osg::Vec2f(texDelta, 0.0f);
219         else
220             (*tl)[destIdx]
221                 = tlArray(latIdx, lonIdx) - osg::Vec2f(texDelta, 0.0f);
222     }
223 }
224
225 void OceanMesh::calcApronPts(double tex_width)
226 {
227     for (int i = 0; i < lonPoints; i++)
228         calcApronPt(0, i, 1, i, i, tex_width);
229     int topApronOffset = latPoints + (2 + lonPoints) * latPoints;
230     for (int i = 0; i < lonPoints; i++)
231         calcApronPt(latPoints - 1, i, latPoints - 2, i,
232                     i + topApronOffset, tex_width);
233     for (int i = 0; i < latPoints; i++) {
234         calcApronPt(i, 0, i, 1, lonPoints + i * (lonPoints + 2), tex_width);
235         calcApronPt(i, lonPoints - 1, i, lonPoints - 2,
236                     lonPoints + i * (lonPoints + 2) + 1 + lonPoints, tex_width);
237     }
238 }
239
240 namespace
241 {
242 // Enter the vertices of triangles that fill one row of the
243 // mesh. The vertices are entered in counter-clockwise order.
244 void fillDrawElementsRow(int width, short row0Start, short row1Start,
245                          osg::DrawElementsUShort::vector_type::iterator&
246                          elements)
247 {
248     short row0Idx = row0Start;
249     short row1Idx = row1Start;
250     for (int i = 0; i < width - 1; i++, row0Idx++, row1Idx++) {
251         *elements++ = row0Idx;
252         *elements++ = row0Idx + 1;
253         *elements++ = row1Idx;
254         *elements++ = row1Idx;
255         *elements++ = row0Idx + 1;
256         *elements++ = row1Idx + 1;
257     }
258 }
259
260 void fillDrawElementsWithApron(short height, short width,
261                                osg::DrawElementsUShort::vector_type::iterator
262                                elements)
263 {
264     // First apron row
265     fillDrawElementsRow(width, 0, width + 1, elements);
266     for (short i = 0; i < height - 1; i++)
267         fillDrawElementsRow(width + 2, width + i * (width + 2),
268                             width + (i + 1) * (width + 2),
269                             elements);
270     // Last apron row
271     short topApronBottom = width + (height - 1) * (width + 2) + 1;
272     fillDrawElementsRow(width, topApronBottom, topApronBottom + width + 1,
273                         elements);
274 }
275 }
276
277 osg::Node* SGOceanTile(const SGBucket& b, SGMaterialLib *matlib, int latPoints, int lonPoints)
278 {
279     Effect *effect = 0;
280
281     double tex_width = 1000.0;
282   
283     // find Ocean material in the properties list
284     SGMaterial *mat = matlib->find( "Ocean" );
285     if ( mat != NULL ) {
286         // set the texture width and height values for this
287         // material
288         tex_width = mat->get_xsize();
289     
290         // set OSG State
291         effect = mat->get_effect();
292     } else {
293         SG_LOG( SG_TERRAIN, SG_ALERT, "Ack! unknown use material name = Ocean");
294     }
295     OceanMesh grid(latPoints, lonPoints);
296     // Calculate center point
297     SGVec3d cartCenter = SGVec3d::fromGeod(b.get_center());
298     SGGeod geodPos = SGGeod::fromCart(cartCenter);
299     SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
300
301     double clon = b.get_center_lon();
302     double clat = b.get_center_lat();
303     double height = b.get_height();
304     double width = b.get_width();
305
306     grid.calcMesh(cartCenter, hlOr, clon, clat, height, width, tex_width);
307     grid.calcApronPts(tex_width);
308   
309     osg::Vec4Array* cl = new osg::Vec4Array;
310     cl->push_back(osg::Vec4(1, 1, 1, 1));
311   
312     osg::Geometry* geometry = new osg::Geometry;
313     geometry->setVertexArray(grid.vl);
314     geometry->setNormalArray(grid.nl);
315     geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
316     geometry->setColorArray(cl);
317     geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
318     geometry->setTexCoordArray(0, grid.tl);
319
320     // Allocate the indices for triangles in the mesh and the apron
321     osg::DrawElementsUShort* drawElements
322         = new osg::DrawElementsUShort(GL_TRIANGLES,
323                                       6 * ((latPoints - 1) * (lonPoints + 1)
324                                            + 2 * (latPoints - 1)));
325     fillDrawElementsWithApron(latPoints, lonPoints, drawElements->begin());
326     geometry->addPrimitiveSet(drawElements);
327
328     EffectGeode* geode = new EffectGeode;
329     geode->setName("Ocean tile");
330     geode->setEffect(effect);
331     geode->addDrawable(geometry);
332     geode->runGenerators(geometry);
333
334     osg::MatrixTransform* transform = new osg::MatrixTransform;
335     transform->setName("Ocean");
336     transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
337                          osg::Matrix::translate(toOsg(cartCenter)));
338     transform->addChild(geode);
339   
340     return transform;
341 }