root/OpenSceneGraph/trunk/examples/osggpx/osggpx.cpp @ 11160

Revision 11160, 19.0 kB (checked in by robert, 4 years ago)

Added an "-a" speed averager option and a "-o filename" output option.

Line 
1/* OpenSceneGraph example, osggpx.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#include <osg/Node>
20#include <osg/Geometry>
21#include <osg/Notify>
22#include <osg/MatrixTransform>
23#include <osg/Texture2D>
24#include <osg/DrawPixels>
25#include <osg/PolygonOffset>
26#include <osg/Geode>
27#include <osg/CoordinateSystemNode>
28
29#include <osgDB/Registry>
30#include <osgDB/ReadFile>
31#include <osgDB/FileUtils>
32#include <osgDB/FileNameUtils>
33#include <osgDB/XmlParser>
34
35#include <osgText/Text>
36
37#include <osgGA/TerrainManipulator>
38#include <osgViewer/Viewer>
39
40class TrackSegment : public osg::Object
41{
42public:
43    TrackSegment() {}
44
45    TrackSegment(const TrackSegment& ts, const osg::CopyOp=osg::CopyOp::SHALLOW_COPY) {}
46
47    META_Object(osg, TrackSegment)
48
49    struct TrackPoint
50    {
51        TrackPoint():
52            latitude(0.0),
53            longitude(0.0),
54            elevation(0.0),
55            time(0.0) {}
56
57        double latitude;
58        double longitude;
59        double elevation;
60        double time;
61    };
62
63    typedef std::vector< TrackPoint > TrackPoints;
64
65    void addTrackPoint(const TrackPoint& trackPoint) { _trackPoints.push_back(trackPoint); }
66
67    TrackPoints& getTrackPoints() { return _trackPoints; }
68    const TrackPoints& getTrackPoints() const { return _trackPoints; }
69
70protected:
71    virtual ~TrackSegment() {}
72
73    TrackPoints _trackPoints;
74};
75
76class Track : public osg::Object
77{
78public:
79    Track() {}
80
81    Track(const Track& track, const osg::CopyOp=osg::CopyOp::SHALLOW_COPY) {}
82
83    META_Object(osg, Track)
84
85    typedef std::vector< osg::ref_ptr<TrackSegment> > TrackSegments;
86
87    void addTrackSegment(TrackSegment* trackSegment) { _trackSegments.push_back(trackSegment); }
88
89    TrackSegments& getTrackSegments() { return _trackSegments; }
90    const TrackSegments& getTrackSegments() const { return _trackSegments; }
91
92protected:
93
94    virtual ~Track() {}
95
96    TrackSegments _trackSegments;
97};
98
99double convertTime(const std::string& timestr)
100{
101    osg::notify(osg::NOTICE)<<"       time = "<<timestr<<std::endl;
102    return 0;
103}
104
105Track* readTrack(const std::string& filename)
106{
107    std::string foundFilename = osgDB::findDataFile(filename);
108    if (foundFilename.empty()) return 0;
109
110    std::string ext = osgDB::getFileExtension(foundFilename);
111    if (ext!="gpx") return 0;
112
113    osgDB::XmlNode::Input input;
114    input.open(foundFilename);
115    input.readAllDataIntoBuffer();
116
117    osg::ref_ptr<osgDB::XmlNode> doc = new osgDB::XmlNode;
118    doc->read(input);
119
120    osgDB::XmlNode* root = 0;
121    for(osgDB::XmlNode::Children::iterator itr = doc->children.begin();
122        itr != doc->children.end() && !root;
123        ++itr)
124    {
125        if ((*itr)->name=="gpx") root = itr->get();
126    }
127
128    if (!root) return 0;
129
130    std::string latitude("lat");
131    std::string longitude("lon");
132
133    for(osgDB::XmlNode::Children::iterator itr = root->children.begin();
134        itr != root->children.end();
135        ++itr)
136    {
137        if ((*itr)->name=="trk")
138        {
139            osg::ref_ptr<Track> track = new Track;
140            track->setName(filename);
141
142            for(osgDB::XmlNode::Children::iterator citr = (*itr)->children.begin();
143                citr != (*itr)->children.end();
144                ++citr)
145            {
146                if ((*citr)->name=="trkseg")
147                {
148                    osg::ref_ptr<TrackSegment> trackSegment = new TrackSegment;
149                    for(osgDB::XmlNode::Children::iterator sitr = (*citr)->children.begin();
150                        sitr != (*citr)->children.end();
151                        ++sitr)
152                    {
153                        if ((*sitr)->name=="trkpt")
154                        {
155                            osgDB::XmlNode* trkpt = sitr->get();
156                            TrackSegment::TrackPoint point;
157                            bool valid = false;
158                            if (trkpt->properties.count(latitude)!=0)
159                            {
160                                valid = true;
161                                point.latitude = osg::asciiToDouble(trkpt->properties[latitude].c_str());
162                            }
163                            if (trkpt->properties.count(longitude)!=0)
164                            {
165                                valid = true;
166                                point.longitude = osg::asciiToDouble(trkpt->properties[longitude].c_str());
167                            }
168
169                            for(osgDB::XmlNode::Children::iterator pitr = trkpt->children.begin();
170                                pitr != trkpt->children.end();
171                                ++pitr)
172                            {
173                                if ((*pitr)->name=="ele") point.elevation = osg::asciiToDouble((*pitr)->contents.c_str());
174                                else if ((*pitr)->name=="time") point.time = convertTime((*pitr)->contents);
175                            }
176
177                            if (valid)
178                            {
179                                // osg::notify(osg::NOTICE)<<"  point.latitude="<<point.latitude<<", longitude="<<point.longitude<<", elev="<<point.elevation<<", time="<<point.time<<std::endl;
180                                trackSegment->addTrackPoint(point);
181                            }
182                        }
183                    }
184                    if (!trackSegment->getTrackPoints().empty())
185                    {
186                        track->addTrackSegment(trackSegment.get());
187                    }
188                }
189            }
190
191
192            return track.release();
193        }
194    }
195
196    return 0;
197}
198
199TrackSegment* computeSmoothedTrackSegment(TrackSegment* ts)
200{
201    if (!ts) return 0;
202
203    const TrackSegment::TrackPoints& orig_points = ts->getTrackPoints();
204
205    if (orig_points.size()>2)
206    {
207        // only do smoothing if we have more than two points.
208        osg::ref_ptr<TrackSegment> new_ts = new TrackSegment;
209
210        TrackSegment::TrackPoints& new_points = new_ts->getTrackPoints();
211        new_points.resize(orig_points.size());
212
213        new_points[0] = orig_points[0];
214        new_points[orig_points.size()-1] = orig_points[orig_points.size()-1];
215
216        for(unsigned int i=1; i<orig_points.size()-1; ++i)
217        {
218            new_points[i].latitude = (orig_points[i-1].latitude+orig_points[i].latitude+orig_points[i+1].latitude)/3.0;
219            new_points[i].longitude = (orig_points[i-1].longitude+orig_points[i].longitude+orig_points[i+1].longitude)/3.0;
220            new_points[i].elevation = (orig_points[i-1].elevation+orig_points[i].elevation+orig_points[i+1].elevation)/3.0;
221            new_points[i].time = (orig_points[i-1].time+orig_points[i].time+orig_points[i+1].time)/3.0;
222        }
223        return new_ts.release();
224    }
225    else
226    {
227        // we have two or less points and can't do smoothing, so will just return original TrackSegment
228        return ts;
229    }
230
231}
232
233TrackSegment* computeAveragedSpeedTrackSegment(TrackSegment* ts)
234{
235    if (!ts) return 0;
236
237    osg::ref_ptr<osg::EllipsoidModel> em = new osg::EllipsoidModel;
238    const TrackSegment::TrackPoints& orig_points = ts->getTrackPoints();
239
240    if (orig_points.size()>2)
241    {
242        // only do smoothing if we have more than two points.
243        osg::ref_ptr<TrackSegment> new_ts = new TrackSegment;
244
245
246        // compute overall distance
247        double total_distance = 0;
248        for(unsigned int i=1; i<orig_points.size()-1; ++i)
249        {
250            osg::Vec3d point_a, point_b;
251            em->convertLatLongHeightToXYZ(osg::DegreesToRadians(orig_points[i].latitude), osg::DegreesToRadians(orig_points[i].longitude), orig_points[i].elevation,
252                                          point_a.x(), point_a.y(), point_a.z());
253            em->convertLatLongHeightToXYZ(osg::DegreesToRadians(orig_points[i+1].latitude), osg::DegreesToRadians(orig_points[i+1].longitude), orig_points[i+1].elevation,
254                                          point_b.x(), point_b.y(), point_b.z());
255            total_distance += (point_b-point_a).length();
256        }
257
258        double total_time = orig_points[orig_points.size()-1].time - orig_points[0].time;
259        double average_speed = total_distance/total_time;
260
261        OSG_NOTICE<<"total_time = "<<total_time<<std::endl;
262        OSG_NOTICE<<"total_distance = "<<total_distance<<std::endl;
263        OSG_NOTICE<<"average_speed = "<<average_speed<<std::endl;
264
265        TrackSegment::TrackPoints& new_points = new_ts->getTrackPoints();
266        new_points.resize(orig_points.size());
267        new_points[0] = orig_points[0];
268
269        double accumulated_distance = 0.0;
270        for(unsigned int i=0; i<orig_points.size()-1; ++i)
271        {
272            osg::Vec3d point_a, point_b;
273            em->convertLatLongHeightToXYZ(osg::DegreesToRadians(orig_points[i].latitude), osg::DegreesToRadians(orig_points[i].longitude), orig_points[i].elevation,
274                                          point_a.x(), point_a.y(), point_a.z());
275            em->convertLatLongHeightToXYZ(osg::DegreesToRadians(orig_points[i+1].latitude), osg::DegreesToRadians(orig_points[i+1].longitude), orig_points[i+1].elevation,
276                                          point_b.x(), point_b.y(), point_b.z());
277
278            accumulated_distance += (point_b-point_a).length();
279
280            new_points[i+1] = orig_points[i+1];
281            new_points[i+1].time = accumulated_distance / average_speed;
282        }
283        return new_ts.release();
284    }
285    else
286    {
287        // we have two or less points and can't do smoothing, so will just return original TrackSegment
288        return ts;
289    }
290
291}
292
293Track* computeAveragedSpeedTrack(Track* track)
294{
295    osg::ref_ptr<Track> new_track = new Track;
296
297    for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
298        itr != track->getTrackSegments().end();
299        ++itr)
300    {
301        new_track->addTrackSegment(computeAveragedSpeedTrackSegment(itr->get()));
302    }
303
304    return new_track.release();
305}
306
307
308Track* computeSmoothedTrack(Track* track)
309{
310    osg::ref_ptr<Track> new_track = new Track;
311
312    for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
313        itr != track->getTrackSegments().end();
314        ++itr)
315    {
316        new_track->addTrackSegment(computeSmoothedTrackSegment(itr->get()));
317    }
318
319    return new_track.release();
320}
321
322osg::Node* createTrackModel(Track* track, const osg::Vec4& colour)
323{
324    osg::ref_ptr<osg::EllipsoidModel> em = new osg::EllipsoidModel;
325
326    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
327
328    for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
329        itr != track->getTrackSegments().end();
330        ++itr)
331    {
332        const TrackSegment::TrackPoints& points = (*itr)->getTrackPoints();
333        if (points.size()<2) continue;
334
335        osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
336        osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
337        geometry->setVertexArray(vertices.get());
338        vertices->resize(points.size());
339        for(unsigned int i=0; i<points.size(); ++i)
340        {
341            osg::Vec3d point;
342            em->convertLatLongHeightToXYZ(osg::DegreesToRadians(points[i].latitude), osg::DegreesToRadians(points[i].longitude), points[i].elevation,
343                                          point.x(), point.y(), point.z());
344
345           (*vertices)[i] = point;
346        }
347
348        osg::ref_ptr<osg::Vec4Array> colours = new osg::Vec4Array;
349        colours->push_back(colour);
350        geometry->setColorArray(colours.get());
351        geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
352
353        geometry->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, points.size()));
354
355        geode->addDrawable(geometry.get());
356    }
357
358    geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
359
360    return geode.release();
361}
362
363int main(int argv, char **argc)
364{
365    osg::ArgumentParser arguments(&argv, argc);
366
367    typedef std::list< osg::ref_ptr<Track> > Tracks;
368    Tracks tracks;
369
370    bool average = false;
371    while (arguments.read("-a") || arguments.read("--average")) average = true;
372
373    bool smooth = false;
374    while (arguments.read("-s") || arguments.read("--smooth")) smooth = true;
375
376    std::string outputFilename;
377    while (arguments.read("-o",outputFilename)) {}
378
379    std::string trackFilename;
380    while (arguments.read("-t",trackFilename))
381    {
382        osg::ref_ptr<Track> track = readTrack(trackFilename);
383        if (track.valid()) tracks.push_back(track.get());
384    }
385
386    osg::ref_ptr<osg::EllipsoidModel> em = new osg::EllipsoidModel;
387
388    osg::ref_ptr<osg::Group> group = new osg::Group;
389
390    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
391    if (loadedModel.valid()) group->addChild(loadedModel.get());
392
393    for(Tracks::iterator itr = tracks.begin();
394        itr != tracks.end();
395        ++itr)
396    {
397        Track* track = itr->get();
398
399        group->addChild(createTrackModel(track, osg::Vec4(1.0,1.0,1.0,1.0)));
400
401        // smooth the track
402        if (average)
403        {
404            for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
405                itr != track->getTrackSegments().end();
406                ++itr)
407            {
408                *itr = computeAveragedSpeedTrackSegment(itr->get());
409            }
410        }
411
412        // smooth the track
413        if (smooth)
414        {
415            for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
416                itr != track->getTrackSegments().end();
417                ++itr)
418            {
419                *itr = computeSmoothedTrackSegment(itr->get());
420            }
421
422            for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
423                itr != track->getTrackSegments().end();
424                ++itr)
425            {
426                *itr = computeSmoothedTrackSegment(itr->get());
427            }
428
429            for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
430                itr != track->getTrackSegments().end();
431                ++itr)
432            {
433                *itr = computeSmoothedTrackSegment(itr->get());
434            }
435
436            for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
437                itr != track->getTrackSegments().end();
438                ++itr)
439            {
440                *itr = computeSmoothedTrackSegment(itr->get());
441            }
442        }
443
444        double totalDistance = 0.0;
445        double totalAscent = 0.0;
446        double totalDescent = 0.0;
447
448        osg::notify(osg::NOTICE)<<"Track read "<<track->getName()<<std::endl;
449        for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
450            itr != track->getTrackSegments().end();
451            ++itr)
452        {
453            TrackSegment* ts = itr->get();
454
455            const TrackSegment::TrackPoints& points = ts->getTrackPoints();
456            if (points.size()>1)
457            {
458                TrackSegment::TrackPoints::iterator pitr = ts->getTrackPoints().begin();
459                osg::Vec3d previousPos;
460                double previousElevation = pitr->elevation;
461                em->convertLatLongHeightToXYZ(osg::DegreesToRadians(pitr->latitude), osg::DegreesToRadians(pitr->longitude), 0.0,
462                                              previousPos.x(), previousPos.y(), previousPos.z());
463                ++pitr;
464
465                for(;
466                    pitr != ts->getTrackPoints().end();
467                    ++pitr)
468                {
469                    osg::Vec3d newPos;
470                    double newElevation = pitr->elevation;
471                    em->convertLatLongHeightToXYZ(osg::DegreesToRadians(pitr->latitude), osg::DegreesToRadians(pitr->longitude), 0.0,
472                                                newPos.x(), newPos.y(), newPos.z());
473
474                    double distance = (newPos-previousPos).length();
475
476                    totalDistance += distance;
477                    if (newElevation>previousElevation) totalAscent += (newElevation-previousElevation);
478                    else totalDescent += (previousElevation-newElevation);
479
480                    osg::notify(osg::NOTICE)<<"     distance="<<distance<<", "<<newElevation-previousElevation<<std::endl;
481
482                    previousPos = newPos;
483                    previousElevation = newElevation;
484                }
485            }
486        }
487
488        double metersToFeet = 1 / 0.3048;
489        double metersToMiles = 1.0 / 1609.344;
490
491        osg::notify(osg::NOTICE)<<"totalDistance = "<<totalDistance<<"m, "<<totalDistance*metersToMiles<<" miles"<<std::endl;
492        osg::notify(osg::NOTICE)<<"totalAscent = "<<totalAscent<<"m, "<<totalAscent*metersToFeet<<"ft"<<std::endl;
493        osg::notify(osg::NOTICE)<<"totalDescent = "<<totalDescent<<"m, "<<totalDescent*metersToFeet<<"ft"<<std::endl;
494
495    }
496
497    if (!outputFilename.empty())
498    {
499        std::ofstream fout(outputFilename.c_str());
500
501        fout<<"<?xml version=\"1.0\" encoding=\"utf-8\"?><gpx version=\"1.0\" creator=\"osggpx\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/0\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">"<<std::endl;
502
503        for(Tracks::iterator itr = tracks.begin();
504            itr != tracks.end();
505            ++itr)
506        {
507            Track* track = itr->get();
508
509            fout<<"<trk>"<<std::endl;
510            fout<<"<desc>The track description</desc>"<<std::endl;
511            for(Track::TrackSegments::iterator itr = track->getTrackSegments().begin();
512                itr != track->getTrackSegments().end();
513                ++itr)
514            {
515                TrackSegment* ts = itr->get();
516                fout<<"<trkseg>"<<std::endl;
517
518                for(TrackSegment::TrackPoints::iterator pitr = ts->getTrackPoints().begin();
519                    pitr != ts->getTrackPoints().end();
520                    ++pitr)
521                {
522                    fout<<"<trkpt lat=\""<<pitr->latitude<<"\" lon=\""<<pitr->longitude<<"\">"<<std::endl;
523                    fout<<"<ele>"<<pitr->elevation<<"</ele>"<<std::endl;
524                    fout<<"<time>"<<pitr->time<<"</time>"<<std::endl;
525                    fout<<"</trkpt>"<<std::endl;
526                }
527
528                fout<<"</trkseg>"<<std::endl;
529
530            }
531            fout<<"</trk>"<<std::endl;
532        }
533        fout<<"</gpx>"<<std::endl;
534    }
535
536    osgViewer::Viewer viewer(arguments);
537    viewer.setCameraManipulator(new osgGA::TerrainManipulator);
538    viewer.setSceneData(group.get());
539    return viewer.run();
540
541}
Note: See TracBrowser for help on using the browser.