-
Notifications
You must be signed in to change notification settings - Fork 339
Expand file tree
/
Copy pathBasicElevationModel.java
More file actions
2812 lines (2391 loc) · 112 KB
/
BasicElevationModel.java
File metadata and controls
2812 lines (2391 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2006-2009, 2017, 2020 United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA World Wind Java (WWJ) platform is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* NASA World Wind Java (WWJ) also contains the following 3rd party Open Source
* software:
*
* Jackson Parser – Licensed under Apache 2.0
* GDAL – Licensed under MIT
* JOGL – Licensed under Berkeley Software Distribution (BSD)
* Gluegen – Licensed under Berkeley Software Distribution (BSD)
*
* A complete listing of 3rd Party software notices and licenses included in
* NASA World Wind Java (WWJ) can be found in the WorldWindJava-v2.2 3rd-party
* notices and licenses PDF found in code directory.
*/
package gov.nasa.worldwind.terrain;
import com.jogamp.common.nio.Buffers;
import gov.nasa.worldwind.*;
import gov.nasa.worldwind.avlist.*;
import gov.nasa.worldwind.cache.*;
import gov.nasa.worldwind.data.*;
import gov.nasa.worldwind.event.BulkRetrievalListener;
import gov.nasa.worldwind.exception.WWRuntimeException;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.ogc.wms.WMSCapabilities;
import gov.nasa.worldwind.retrieve.*;
import gov.nasa.worldwind.util.*;
import org.w3c.dom.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.xml.xpath.XPath;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
// Implementation notes, not for API doc:
//
// Implements an elevation model based on a quad tree of elevation tiles. Meant to be subclassed by very specific
// classes, e.g. Earth/SRTM. A Descriptor passed in at construction gives the configuration parameters. Eventually
// Descriptor will be replaced by an XML configuration document.
//
// A "tile" corresponds to one tile of the data set, which has a corresponding unique row/column address in the data
// set. An inner class implements Tile. An inner class also implements TileKey, which is used to address the
// corresponding Tile in the memory cache.
// Clients of this class get elevations from it by first getting an Elevations object for a specific Sector, then
// querying that object for the elevation at individual lat/lon positions. The Elevations object captures information
// that is used to compute elevations. See in-line comments for a description.
//
// When an elevation tile is needed but is not in memory, a task is threaded off to find it. If it's in the file cache
// then it's loaded by the task into the memory cache. If it's not in the file cache then a retrieval is initiated by
// the task. The disk is never accessed during a call to getElevations(sector, resolution) because that method is
// likely being called when a frame is being rendered. The details of all this are in-line below.
/**
* @author Tom Gaskins
* @version $Id: BasicElevationModel.java 3425 2015-09-30 23:17:35Z dcollins $
*/
public class BasicElevationModel extends AbstractElevationModel implements BulkRetrievable
{
protected final LevelSet levels;
protected final double minElevation;
protected final double maxElevation;
protected String elevationDataType = AVKey.INT16;
protected String elevationDataByteOrder = AVKey.LITTLE_ENDIAN;
protected double detailHint = 0.0;
protected final Object fileLock = new Object();
protected java.util.concurrent.ConcurrentHashMap<TileKey, ElevationTile> levelZeroTiles =
new java.util.concurrent.ConcurrentHashMap<TileKey, ElevationTile>();
protected MemoryCache memoryCache;
protected int extremesLevel = -1;
protected boolean extremesCachingEnabled = true;
protected BufferWrapper extremes = null;
protected MemoryCache extremesLookupCache;
// Model resource properties.
protected static final int RESOURCE_ID_OGC_CAPABILITIES = 1;
protected String basicAuthorizationString;
public BasicElevationModel(AVList params)
{
if (params == null)
{
String message = Logging.getMessage("nullValue.ElevationModelConfigParams");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
String s = params.getStringValue(AVKey.BYTE_ORDER);
if (s != null)
this.setByteOrder(s);
Double d = (Double) params.getValue(AVKey.DETAIL_HINT);
if (d != null)
this.setDetailHint(d);
s = params.getStringValue(AVKey.DISPLAY_NAME);
if (s != null)
this.setName(s);
d = (Double) params.getValue(AVKey.ELEVATION_MIN);
this.minElevation = d != null ? d : 0;
d = (Double) params.getValue(AVKey.ELEVATION_MAX);
this.maxElevation = d != null ? d : 0;
Long lo = (Long) params.getValue(AVKey.EXPIRY_TIME);
if (lo != null)
params.setValue(AVKey.EXPIRY_TIME, lo);
d = (Double) params.getValue(AVKey.MISSING_DATA_SIGNAL);
if (d != null)
this.setMissingDataSignal(d);
d = (Double) params.getValue(AVKey.MISSING_DATA_REPLACEMENT);
if (d != null)
this.setMissingDataReplacement(d);
Boolean b = (Boolean) params.getValue(AVKey.NETWORK_RETRIEVAL_ENABLED);
if (b != null)
this.setNetworkRetrievalEnabled(b);
s = params.getStringValue(AVKey.DATA_TYPE);
if (s != null)
this.setElevationDataType(s);
s = params.getStringValue(AVKey.ELEVATION_EXTREMES_FILE);
if (s != null)
this.loadExtremeElevations(s);
b = (Boolean) params.getValue(AVKey.DELETE_CACHE_ON_EXIT);
if (b != null)
this.setValue(AVKey.DELETE_CACHE_ON_EXIT, true);
String basicAuthUsername = params.getStringValue(AVKey.BASIC_AUTH_USERNAME);
String basicAuthPassword = params.getStringValue(AVKey.BASIC_AUTH_PASSWORD);
if(basicAuthUsername != null && basicAuthPassword != null) {
basicAuthorizationString = Base64.getEncoder().encodeToString(
(basicAuthUsername + ":" + basicAuthPassword).getBytes());
}
// Set some fallback values if not already set.
setFallbacks(params);
this.levels = new LevelSet(params);
if (this.levels.getSector() != null && this.getValue(AVKey.SECTOR) == null)
this.setValue(AVKey.SECTOR, this.levels.getSector());
this.memoryCache = this.createMemoryCache(ElevationTile.class.getName());
this.setValue(AVKey.CONSTRUCTION_PARAMETERS, params.copy());
// If any resources should be retrieved for this ElevationModel, start a task to retrieve those resources, and
// initialize this ElevationModel once those resources are retrieved.
if (this.isRetrieveResources())
{
this.startResourceRetrieval();
}
}
public BasicElevationModel(Document dom, AVList params)
{
this(dom.getDocumentElement(), params);
}
public BasicElevationModel(Element domElement, AVList params)
{
this(getBasicElevationModelConfigParams(domElement, params));
}
public BasicElevationModel(String restorableStateInXml)
{
this(restorableStateToParams(restorableStateInXml));
RestorableSupport rs;
try
{
rs = RestorableSupport.parse(restorableStateInXml);
}
catch (Exception e)
{
// Parsing the document specified by stateInXml failed.
String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", restorableStateInXml);
Logging.logger().severe(message);
throw new IllegalArgumentException(message, e);
}
this.doRestoreState(rs, null);
}
@Override
public Object setValue(String key, Object value)
{
// Offer it to the level set
if (this.getLevels() != null)
this.getLevels().setValue(key, value);
return super.setValue(key, value);
}
@Override
public Object getValue(String key)
{
Object value = super.getValue(key);
return value != null ? value : this.getLevels().getValue(key); // see if the level set has it
}
protected static void setFallbacks(AVList params)
{
if (params.getValue(AVKey.TILE_WIDTH) == null)
params.setValue(AVKey.TILE_WIDTH, 150);
if (params.getValue(AVKey.TILE_HEIGHT) == null)
params.setValue(AVKey.TILE_HEIGHT, 150);
if (params.getValue(AVKey.FORMAT_SUFFIX) == null)
params.setValue(AVKey.FORMAT_SUFFIX, ".bil");
if (params.getValue(AVKey.NUM_LEVELS) == null)
params.setValue(AVKey.NUM_LEVELS, 2);
if (params.getValue(AVKey.NUM_EMPTY_LEVELS) == null)
params.setValue(AVKey.NUM_EMPTY_LEVELS, 0);
}
protected MemoryCache getMemoryCache()
{
return memoryCache;
}
protected MemoryCache createMemoryCache(String cacheName)
{
if (WorldWind.getMemoryCacheSet().containsCache(cacheName))
{
return WorldWind.getMemoryCache(cacheName);
}
else
{
long size = Configuration.getLongValue(AVKey.ELEVATION_TILE_CACHE_SIZE, 20000000L);
MemoryCache mc = new BasicMemoryCache((long) (0.85 * size), size);
mc.setName("Elevation Tiles");
WorldWind.getMemoryCacheSet().addCache(cacheName, mc);
return mc;
}
}
public LevelSet getLevels()
{
return this.levels;
}
protected Map<TileKey, ElevationTile> getLevelZeroTiles()
{
return levelZeroTiles;
}
protected int getExtremesLevel()
{
return extremesLevel;
}
protected BufferWrapper getExtremes()
{
return extremes;
}
/**
* Specifies the time of the elevation models's most recent dataset update, beyond which cached data is invalid. If
* greater than zero, the model ignores and eliminates any in-memory or on-disk cached data older than the time
* specified, and requests new information from the data source. If zero, the default, the model applies any expiry
* times associated with its individual levels, but only for on-disk cached data. In-memory cached data is expired
* only when the expiry time is specified with this method and is greater than zero. This method also overwrites the
* expiry times of the model's individual levels if the value specified to the method is greater than zero.
*
* @param expiryTime the expiry time of any cached data, expressed as a number of milliseconds beyond the epoch. The
* default expiry time is zero.
*
* @see System#currentTimeMillis() for a description of milliseconds beyond the epoch.
*/
public void setExpiryTime(long expiryTime) // Override this method to use intrinsic level-specific expiry times
{
super.setExpiryTime(expiryTime);
if (expiryTime > 0)
this.levels.setExpiryTime(expiryTime); // remove this in sub-class to use level-specific expiry times
}
public double getMaxElevation()
{
return this.maxElevation;
}
public double getMinElevation()
{
return this.minElevation;
}
public double getBestResolution(Sector sector)
{
if (sector == null)
return this.levels.getLastLevel().getTexelSize();
Level level = this.levels.getLastLevel(sector);
return level != null ? level.getTexelSize() : Double.MAX_VALUE;
}
public double getDetailHint(Sector sector)
{
return this.detailHint;
}
public void setDetailHint(double hint)
{
this.detailHint = hint;
}
public String getElevationDataType()
{
return this.elevationDataType;
}
public void setElevationDataType(String dataType)
{
if (dataType == null)
{
String message = Logging.getMessage("nullValue.DataTypeIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.elevationDataType = dataType;
}
public String getElevationDataByteOrder()
{
return this.elevationDataByteOrder;
}
public void setByteOrder(String byteOrder)
{
if (byteOrder == null)
{
String message = Logging.getMessage("nullValue.ByteOrderIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.elevationDataByteOrder = byteOrder;
}
public int intersects(Sector sector)
{
if (this.levels.getSector().contains(sector))
return 0;
return this.levels.getSector().intersects(sector) ? 1 : -1;
}
public boolean contains(Angle latitude, Angle longitude)
{
if (latitude == null || longitude == null)
{
String msg = Logging.getMessage("nullValue.AngleIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
return this.levels.getSector().contains(latitude, longitude);
}
@Override
public void setExtremesCachingEnabled(boolean enabled)
{
this.extremesCachingEnabled = enabled;
}
@Override
public boolean isExtremesCachingEnabled()
{
return this.extremesCachingEnabled;
}
//**************************************************************//
//******************** Elevation Tile Management *************//
//**************************************************************//
// Create the tile corresponding to a specified key.
protected ElevationTile createTile(TileKey key)
{
Level level = this.levels.getLevel(key.getLevelNumber());
// Compute the tile's SW lat/lon based on its row/col in the level's data set.
Angle dLat = level.getTileDelta().getLatitude();
Angle dLon = level.getTileDelta().getLongitude();
Angle latOrigin = this.levels.getTileOrigin().getLatitude();
Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
Angle minLatitude = ElevationTile.computeRowLatitude(key.getRow(), dLat, latOrigin);
Angle minLongitude = ElevationTile.computeColumnLongitude(key.getColumn(), dLon, lonOrigin);
Sector tileSector = new Sector(minLatitude, minLatitude.add(dLat), minLongitude, minLongitude.add(dLon));
return new ElevationTile(tileSector, level, key.getRow(), key.getColumn());
}
// Thread off a task to determine whether the file is local or remote and then retrieve it either from the file
// cache or a remote server.
protected void requestTile(TileKey key)
{
if (WorldWind.getTaskService().isFull())
return;
if (this.getLevels().isResourceAbsent(key))
return;
RequestTask request = new RequestTask(key, this);
WorldWind.getTaskService().addTask(request);
}
protected static class RequestTask implements Runnable
{
protected final BasicElevationModel elevationModel;
protected final TileKey tileKey;
protected RequestTask(TileKey tileKey, BasicElevationModel elevationModel)
{
this.elevationModel = elevationModel;
this.tileKey = tileKey;
}
public final void run()
{
if (Thread.currentThread().isInterrupted())
return; // the task was cancelled because it's a duplicate or for some other reason
try
{
// check to ensure load is still needed
if (this.elevationModel.areElevationsInMemory(this.tileKey))
return;
ElevationTile tile = this.elevationModel.createTile(this.tileKey);
final URL url = this.elevationModel.getDataFileStore().findFile(tile.getPath(), false);
if (url != null && !this.elevationModel.isFileExpired(tile, url,
this.elevationModel.getDataFileStore()))
{
if (this.elevationModel.loadElevations(tile, url))
{
this.elevationModel.levels.unmarkResourceAbsent(tile);
this.elevationModel.firePropertyChange(AVKey.ELEVATION_MODEL, null, this);
return;
}
else
{
// Assume that something's wrong with the file and delete it.
this.elevationModel.getDataFileStore().removeFile(url);
this.elevationModel.levels.markResourceAbsent(tile);
String message = Logging.getMessage("generic.DeletedCorruptDataFile", url);
Logging.logger().info(message);
}
}
this.elevationModel.downloadElevations(tile);
}
catch (Exception e)
{
String msg = Logging.getMessage("ElevationModel.ExceptionRequestingElevations",
this.tileKey.toString());
Logging.logger().log(java.util.logging.Level.FINE, msg, e);
}
}
public final boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final RequestTask that = (RequestTask) o;
//noinspection RedundantIfStatement
if (this.tileKey != null ? !this.tileKey.equals(that.tileKey) : that.tileKey != null)
return false;
return true;
}
public final int hashCode()
{
return (this.tileKey != null ? this.tileKey.hashCode() : 0);
}
public final String toString()
{
return this.tileKey.toString();
}
}
protected boolean isFileExpired(Tile tile, java.net.URL fileURL, FileStore fileStore)
{
if (!WWIO.isFileOutOfDate(fileURL, tile.getLevel().getExpiryTime()))
return false;
// The file has expired. Delete it.
fileStore.removeFile(fileURL);
String message = Logging.getMessage("generic.DataFileExpired", fileURL);
Logging.logger().fine(message);
return true;
}
// Reads a tile's elevations from the file cache and adds the tile to the memory cache.
protected boolean loadElevations(ElevationTile tile, java.net.URL url) throws Exception
{
BufferWrapper elevations = this.readElevations(url);
if (elevations == null || elevations.length() == 0)
return false;
tile.setElevations(elevations, this);
this.addTileToCache(tile, elevations);
return true;
}
protected void addTileToCache(ElevationTile tile, BufferWrapper elevations)
{
// Level 0 tiles are held in the model itself; other levels are placed in the memory cache.
if (tile.getLevelNumber() == 0)
this.levelZeroTiles.put(tile.getTileKey(), tile);
else
this.getMemoryCache().add(tile.getTileKey(), tile, elevations.getSizeInBytes());
}
protected boolean areElevationsInMemory(TileKey key)
{
// An elevation tile is considered to be in memory if it:
// * Exists in the memory cache.
// * Has non-null elevation data.
// * Has not exipired.
ElevationTile tile = this.getTileFromMemory(key);
return (tile != null && tile.getElevations() != null && !tile.isElevationsExpired());
}
protected ElevationTile getTileFromMemory(TileKey tileKey)
{
if (tileKey.getLevelNumber() == 0)
return this.levelZeroTiles.get(tileKey);
else
return (ElevationTile) this.getMemoryCache().getObject(tileKey);
}
// Read elevations from the file cache. Don't be confused by the use of a URL here: it's used so that files can
// be read using System.getResource(URL), which will draw the data from a jar file in the classpath.
protected BufferWrapper readElevations(URL url) throws Exception
{
try
{
if (url.getPath().endsWith("tif"))
return this.makeTiffElevations(url);
else
return this.makeBilElevations(url);
}
catch (Exception e)
{
Logging.logger().log(java.util.logging.Level.SEVERE,
"ElevationModel.ExceptionReadingElevationFile", url.toString());
throw e;
}
}
protected BufferWrapper makeBilElevations(URL url) throws IOException
{
ByteBuffer byteBuffer;
synchronized (this.fileLock)
{
byteBuffer = WWIO.readURLContentToBuffer(url);
}
// Setup parameters to instruct BufferWrapper on how to interpret the ByteBuffer.
AVList bufferParams = new AVListImpl();
bufferParams.setValue(AVKey.DATA_TYPE, this.elevationDataType);
bufferParams.setValue(AVKey.BYTE_ORDER, this.elevationDataByteOrder);
return BufferWrapper.wrap(byteBuffer, bufferParams);
}
protected BufferWrapper makeTiffElevations(URL url) throws IOException, URISyntaxException
{
File file = new File(url.toURI());
// Create a raster reader for the file type.
DataRasterReaderFactory readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent(
AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME);
DataRasterReader reader = readerFactory.findReaderFor(file, null);
if (reader == null)
{
String msg = Logging.getMessage("generic.UnknownFileFormatOrMatchingReaderNotFound", file.getPath());
Logging.logger().severe(msg);
throw new WWRuntimeException(msg);
}
// Read the file into the raster.
DataRaster[] rasters;
synchronized (this.fileLock)
{
rasters = reader.read(file, null);
}
if (rasters == null || rasters.length == 0)
{
String msg = Logging.getMessage("ElevationModel.CannotReadElevations", file.getAbsolutePath());
Logging.logger().severe(msg);
throw new WWRuntimeException(msg);
}
DataRaster raster = rasters[0];
// Request a sub-raster that contains the whole file. This step is necessary because only sub-rasters
// are reprojected (if necessary); primary rasters are not.
int width = raster.getWidth();
int height = raster.getHeight();
// Determine the sector covered by the elevations. This information is in the GeoTIFF file or auxiliary
// files associated with the elevations file.
final Sector sector = (Sector) raster.getValue(AVKey.SECTOR);
if (sector == null)
{
String msg = Logging.getMessage("DataRaster.MissingMetadata", AVKey.SECTOR);
Logging.logger().severe(msg);
throw new IllegalStateException(msg);
}
DataRaster subRaster = raster.getSubRaster(width, height, sector, raster);
// Verify that the sub-raster can create a ByteBuffer, then create one.
if (!(subRaster instanceof ByteBufferRaster))
{
String msg = Logging.getMessage("ElevationModel.CannotCreateElevationBuffer", file.getPath());
Logging.logger().severe(msg);
throw new WWRuntimeException(msg);
}
ByteBuffer elevations = ((ByteBufferRaster) subRaster).getByteBuffer();
// The sub-raster can now be disposed. Disposal won't affect the ByteBuffer.
subRaster.dispose();
// Setup parameters to instruct BufferWrapper on how to interpret the ByteBuffer.
AVList bufferParams = new AVListImpl();
bufferParams.setValues(raster.copy()); // copies params from avlist
String dataType = bufferParams.getStringValue(AVKey.DATA_TYPE);
if (WWUtil.isEmpty(dataType))
{
String msg = Logging.getMessage("DataRaster.MissingMetadata", AVKey.DATA_TYPE);
Logging.logger().severe(msg);
throw new IllegalStateException(msg);
}
BufferWrapper bufferWrapper = BufferWrapper.wrap(elevations, bufferParams);
// Tne primary raster can now be disposed.
raster.dispose();
return bufferWrapper;
}
protected static ByteBuffer convertImageToElevations(ByteBuffer buffer, String contentType) throws IOException
{
File tempFile = File.createTempFile("wwj-", WWIO.makeSuffixForMimeType(contentType));
try
{
WWIO.saveBuffer(buffer, tempFile);
BufferedImage image = ImageIO.read(tempFile);
ByteBuffer byteBuffer = Buffers.newDirectByteBuffer(image.getWidth() * image.getHeight() * 2);
byteBuffer.order(java.nio.ByteOrder.LITTLE_ENDIAN);
ShortBuffer bilBuffer = byteBuffer.asShortBuffer();
WritableRaster raster = image.getRaster();
int[] samples = new int[raster.getWidth() * raster.getHeight()];
raster.getSamples(0, 0, raster.getWidth(), raster.getHeight(), 0, samples);
for (int sample : samples)
{
bilBuffer.put((short) sample);
}
return byteBuffer;
}
finally
{
if (tempFile != null)
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
// *** Bulk download ***
// *** Bulk download ***
// *** Bulk download ***
/**
* Start a new {@link BulkRetrievalThread} that downloads all elevations for a given sector and resolution to the
* current WorldWind file cache, without downloading imagery already in the cache.
* <p>
* This method creates and starts a thread to perform the download. A reference to the thread is returned. To create
* a downloader that has not been started, construct a {@link BasicElevationModelBulkDownloader}.
* <p>
* Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in
* meters divided by the globe radius.
*
* @param sector the sector to download data for.
* @param resolution the target resolution, provided in radians of latitude per texel.
* @param listener an optional retrieval listener. May be null.
*
* @return the {@link BulkRetrievalThread} executing the retrieval or <code>null</code> if the specified sector does
* not intersect the elevation model bounding sector.
*
* @throws IllegalArgumentException if the sector is null or the resolution is less than zero.
* @see BasicElevationModelBulkDownloader
*/
public BulkRetrievalThread makeLocal(Sector sector, double resolution, BulkRetrievalListener listener)
{
return this.makeLocal(sector, resolution, null, listener);
}
/**
* Start a new {@link BulkRetrievalThread} that downloads all elevations for a given sector and resolution to a
* specified file store, without downloading imagery already in the file store.
* <p>
* This method creates and starts a thread to perform the download. A reference to the thread is returned. To create
* a downloader that has not been started, construct a {@link BasicElevationModelBulkDownloader}.
* <p>
* Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in
* meters divided by the globe radius.
*
* @param sector the sector to download data for.
* @param resolution the target resolution, provided in radians of latitude per texel.
* @param fileStore the file store in which to place the downloaded elevations. If null the current WorldWind file
* cache is used.
* @param listener an optional retrieval listener. May be null.
*
* @return the {@link BulkRetrievalThread} executing the retrieval or <code>null</code> if the specified sector does
* not intersect the elevation model bounding sector.
*
* @throws IllegalArgumentException if the sector is null or the resolution is less than zero.
* @see BasicElevationModelBulkDownloader
*/
public BulkRetrievalThread makeLocal(Sector sector, double resolution, FileStore fileStore,
BulkRetrievalListener listener)
{
Sector targetSector = sector != null ? getLevels().getSector().intersection(sector) : null;
if (targetSector == null)
return null;
// Args checked in downloader constructor
BasicElevationModelBulkDownloader thread =
new BasicElevationModelBulkDownloader(this, targetSector, resolution,
fileStore != null ? fileStore : this.getDataFileStore(), listener);
thread.setDaemon(true);
thread.start();
return thread;
}
/**
* Get the estimated size in bytes of the elevations not in the WorldWind file cache for the given sector and
* resolution.
* <p>
* Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in
* meters divided by the globe radius.
*
* @param sector the sector to estimate.
* @param resolution the target resolution, provided in radians of latitude per texel.
*
* @return the estimated size in bytes of the missing elevations.
*
* @throws IllegalArgumentException if the sector is null or the resolution is less than zero.
*/
public long getEstimatedMissingDataSize(Sector sector, double resolution)
{
return this.getEstimatedMissingDataSize(sector, resolution, null);
}
/**
* Get the estimated size in bytes of the elevations not in a specified file store for the given sector and
* resolution.
* <p>
* Note that the target resolution must be provided in radians of latitude per texel, which is the resolution in
* meters divided by the globe radius.
*
* @param sector the sector to estimate.
* @param resolution the target resolution, provided in radians of latitude per texel.
* @param fileStore the file store to examine. If null the current WorldWind file cache is used.
*
* @return the estimated size in bytes of the missing elevations.
*
* @throws IllegalArgumentException if the sector is null or the resolution is less than zero.
*/
public long getEstimatedMissingDataSize(Sector sector, double resolution, FileStore fileStore)
{
Sector targetSector = sector != null ? getLevels().getSector().intersection(sector) : null;
if (targetSector == null)
return 0;
// Args checked by downloader constructor
// Need a downloader to compute the missing data size.
BasicElevationModelBulkDownloader downloader = new BasicElevationModelBulkDownloader(this, targetSector,
resolution, fileStore != null ? fileStore : this.getDataFileStore(), null);
return downloader.getEstimatedMissingDataSize();
}
// *** Tile download ***
// *** Tile download ***
// *** Tile download ***
protected void downloadElevations(final Tile tile)
{
retrieveElevations(tile, new DownloadPostProcessor(tile, this));
}
protected void downloadElevations(final Tile tile, DownloadPostProcessor postProcessor)
{
retrieveElevations(tile, postProcessor);
}
protected void retrieveElevations(final Tile tile, DownloadPostProcessor postProcessor)
{
if (this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL) != null)
this.retrieveLocalElevations(tile, postProcessor);
else
// Assume it's remote, which handles the legacy cases.
this.retrieveRemoteElevations(tile, postProcessor);
}
protected void retrieveLocalElevations(Tile tile, DownloadPostProcessor postProcessor)
{
if (!WorldWind.getLocalRetrievalService().isAvailable())
return;
RetrieverFactory retrieverFactory = (RetrieverFactory) this.getValue(AVKey.RETRIEVER_FACTORY_LOCAL);
if (retrieverFactory == null)
return;
AVListImpl avList = new AVListImpl();
avList.setValue(AVKey.SECTOR, tile.getSector());
avList.setValue(AVKey.WIDTH, tile.getWidth());
avList.setValue(AVKey.HEIGHT, tile.getHeight());
avList.setValue(AVKey.FILE_NAME, tile.getPath());
Retriever retriever = retrieverFactory.createRetriever(avList, postProcessor);
WorldWind.getLocalRetrievalService().runRetriever(retriever, tile.getPriority());
}
protected void retrieveRemoteElevations(final Tile tile, DownloadPostProcessor postProcessor)
{
if (!this.isNetworkRetrievalEnabled())
{
this.getLevels().markResourceAbsent(tile);
return;
}
if (!WorldWind.getRetrievalService().isAvailable())
return;
java.net.URL url = null;
try
{
url = tile.getResourceURL();
if (WorldWind.getNetworkStatus().isHostUnavailable(url))
{
this.getLevels().markResourceAbsent(tile);
return;
}
}
catch (java.net.MalformedURLException e)
{
Logging.logger().log(java.util.logging.Level.SEVERE,
Logging.getMessage("TiledElevationModel.ExceptionCreatingElevationsUrl", url), e);
return;
}
if (postProcessor == null)
postProcessor = new DownloadPostProcessor(tile, this);
URLRetriever retriever = new HTTPRetriever(url, postProcessor);
retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy elevation models
if (WorldWind.getRetrievalService().contains(retriever))
return;
WorldWind.getRetrievalService().runRetriever(retriever, 0d);
}
protected static class DownloadPostProcessor extends AbstractRetrievalPostProcessor
{
protected final Tile tile;
protected final BasicElevationModel elevationModel;
protected final FileStore fileStore;
public DownloadPostProcessor(Tile tile, BasicElevationModel em)
{
this(tile, em, null);
}
public DownloadPostProcessor(Tile tile, BasicElevationModel em, FileStore fileStore)
{
//noinspection RedundantCast
super((AVList) em);
this.tile = tile;
this.elevationModel = em;
this.fileStore = fileStore;
}
protected FileStore getFileStore()
{
return this.fileStore != null ? this.fileStore : this.elevationModel.getDataFileStore();
}
@Override
protected boolean overwriteExistingFile()
{
return true;
}
@Override
protected void markResourceAbsent()
{
this.elevationModel.getLevels().markResourceAbsent(this.tile);
}
@Override
protected Object getFileLock()
{
return this.elevationModel.fileLock;
}
@Override
protected File doGetOutputFile()
{
return this.getFileStore().newFile(this.tile.getPath());
}
@Override
protected ByteBuffer handleSuccessfulRetrieval()
{
ByteBuffer buffer = super.handleSuccessfulRetrieval();
if (buffer != null)
{
// We've successfully cached data. Check whether there's a configuration file for this elevation model
// in the cache and create one if there isn't.
this.elevationModel.writeConfigurationFile(this.getFileStore());
// Fire a property change to denote that the model's backing data has changed.
this.elevationModel.firePropertyChange(AVKey.ELEVATION_MODEL, null, this);
}
return buffer;
}
@Override
protected ByteBuffer handleTextContent() throws IOException
{
this.markResourceAbsent();
return super.handleTextContent();
}
//
// @Override
// protected ByteBuffer handleImageContent() throws IOException
// {
// if (!this.getRetriever().getContentType().contains("tiff"))
// return super.handleImageContent();
//
// File tmpFile = WWIO.saveBufferToTempFile(this.getRetriever().getBuffer(), ".tif");
//
// DataRasterReaderFactory readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent(
// AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME);
// DataRasterReader reader = readerFactory.findReaderFor(tmpFile, null);
//
// // Before reading the raster, verify that the file contains elevations.
// AVList metadata = reader.readMetadata(tmpFile, null);