/
Polygon.java
1487 lines (1258 loc) · 54.6 KB
/
Polygon.java
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 (C) 2011 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwind.render;
import com.sun.opengl.util.BufferUtil;
import gov.nasa.worldwind.*;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.cache.GpuResourceCache;
import gov.nasa.worldwind.exception.WWRuntimeException;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.geom.Box;
import gov.nasa.worldwind.globes.Globe;
import gov.nasa.worldwind.ogc.kml.impl.KMLExportUtil;
import gov.nasa.worldwind.terrain.Terrain;
import gov.nasa.worldwind.util.*;
import javax.media.opengl.GL;
import javax.media.opengl.glu.GLU;
import javax.xml.stream.*;
import java.io.*;
import java.nio.*;
import java.util.*;
/**
* /** A 3D polygon. The polygon may be complex with multiple internal but not intersecting contours.
* <p/>
* Polygons are safe to share among World Windows. They should not be shared among layers in the same World Window.
* <p/>
* In order to support simultaneous use of this shape with multiple globes (windows), this shape maintains a cache of
* data computed relative to each globe. During rendering, the data for the currently active globe, as indicated in the
* draw context, is made current. Subsequently called methods rely on the existence of this current data cache entry.
*
* @author tag
* @version $Id: Polygon.java 862 2012-10-23 19:02:35Z dcollins $
*/
public class Polygon extends AbstractShape
{
// TODO: Merge texture coordinates into the vertex+normal buffer rather than specifying them in a separate buffer.
// TODO: Tessellate polygon's interior to follow globe curvature when in ABSOLUTE altitude mode.
/**
* This class holds globe-specific data for this shape. It's managed via the shape-data cache in {@link
* gov.nasa.worldwind.render.AbstractShape.AbstractShapeData}.
*/
protected static class ShapeData extends AbstractShapeData implements Iterable<BoundaryInfo>
{
/** This class holds the per-globe data for this shape. */
protected List<BoundaryInfo> boundaries = new ArrayList<BoundaryInfo>();
/** The rotation matrix for this shape data. */
protected Matrix rotationMatrix; // will vary among globes
/**
* The vertex data buffer for this shape data. The first half contains vertex coordinates, the second half
* contains normals.
*/
protected FloatBuffer coordBuffer; // contains boundary vertices in first half and normals in second half
/** The slice of the <code>coordBuffer</code> that contains normals. */
protected FloatBuffer normalBuffer;
/** The index of the first normal in the <code>coordBuffer</code>. */
protected int normalBufferPosition;
/** This shape's tessellation indices. */
protected GLUTessellatorSupport.CollectIndexListsCallback cb; // the tessellated polygon indices
/**
* The indices identifying the cap vertices in a shape data's vertex buffer. Determined when this shape is
* tessellated, which occurs only once unless the shape's boundaries are re-specified.
*/
protected IntBuffer interiorIndicesBuffer;
/** Indicates whether a tessellation error occurred. No more attempts to tessellate will be made if set to true. */
protected boolean tessellationError = false; // set to true if the tessellator fails
/** Indicates whether the index buffer needs to be filled because a new buffer is used or some other reason. */
protected boolean refillIndexBuffer = true; // set to true if the index buffer needs to be refilled
/**
* Indicates whether the index buffer's VBO needs to be filled because a new buffer is used or some other
* reason.
*/
protected boolean refillIndexVBO = true; // set to true if the index VBO needs to be refilled
/**
* Construct a cache entry using the boundaries of this shape.
*
* @param dc the current draw context.
* @param shape this shape.
*/
public ShapeData(DrawContext dc, Polygon shape)
{
super(dc, shape.minExpiryTime, shape.maxExpiryTime);
if (shape.boundaries.size() < 1)
{
// add a placeholder for the outer boundary
this.boundaries.add(new BoundaryInfo(new ArrayList<Position>()));
return;
}
// Copy the shape's boundaries.
for (List<? extends Position> boundary : shape.boundaries)
{
this.boundaries.add(new BoundaryInfo(boundary));
}
}
/**
* Returns the boundary information for this shape data's outer boundary.
*
* @return this shape data's outer boundary info.
*/
protected BoundaryInfo getOuterBoundaryInfo()
{
return this.boundaries.get(0);
}
public Iterator<BoundaryInfo> iterator()
{
return this.boundaries.iterator();
}
/**
* Returns this shape data's rotation matrix, if there is one.
*
* @return this shape data's rotation matrix, or null if there isn't one.
*/
public Matrix getRotationMatrix()
{
return this.rotationMatrix;
}
/**
* Specifies this shape data's rotation matrix.
*
* @param matrix the new rotation matrix.
*/
public void setRotationMatrix(Matrix matrix)
{
this.rotationMatrix = matrix;
}
}
protected AbstractShapeData createCacheEntry(DrawContext dc)
{
return new ShapeData(dc, this);
}
/**
* Returns the current shape data cache entry.
*
* @return the current data cache entry.
*/
protected ShapeData getCurrent()
{
return (ShapeData) this.getCurrentData();
}
/** Holds information for each contour of the polygon. The vertex values are updated at every geometry regeneration. */
protected static class BoundaryInfo
{
/** The shape's boundary positions. */
protected List<? extends Position> positions;
/** The shape's computed vertices, arranged in one array. */
protected Vec4[] vertices; // TODO: eliminate need for this; use the vertex buffer instead
/** The shape's computed vertices, arranged in a buffer. */
protected FloatBuffer vertexBuffer; // vertices passed to OpenGL
/**
* Construct an instance for a specified boundary.
*
* @param positions the boundary positions.
*/
public BoundaryInfo(List<? extends Position> positions)
{
this.positions = positions;
}
}
/**
* This static hash map holds the vertex indices that define the shape's visual outline. The contents depend only on
* the number of locations in the source polygon, so they can be reused by all shapes with the same location count.
*/
protected static HashMap<Integer, IntBuffer> edgeIndexBuffers = new HashMap<Integer, IntBuffer>();
/** Indicates the number of vertices that must be present in order for VBOs to be used to render this shape. */
protected static final int VBO_THRESHOLD = Configuration.getIntegerValue(AVKey.VBO_THRESHOLD, 30);
/**
* The location of each vertex in this shape's boundaries. There is one list per boundary. There is always an entry
* for the outer boundary, but its list is empty if an outer boundary has not been specified.
*/
protected List<List<? extends Position>> boundaries; // the defining locations or positions of the boundary
/** The total number of positions in the entire polygon. */
protected int numPositions;
/** The image source for this shape's texture, if any. */
protected Object imageSource; // image source for the optional texture
/** If an image source was specified, this is the WWTexture form. */
protected WWTexture texture; // an optional texture for the base polygon
/** This shape's rotation, in degrees positive counterclockwise. */
protected Double rotation; // in degrees; positive is CCW
/** This shape's texture coordinates. */
protected FloatBuffer textureCoordsBuffer; // texture coords if texturing
// Fields used in intersection calculations
/** The terrain used in the most recent intersection calculations. */
protected Terrain previousIntersectionTerrain;
/** The globe state key for the globe used in the most recent intersection calculation. */
protected Object previousIntersectionGlobeStateKey;
/** The shape data used for the previous intersection calculation. */
protected ShapeData previousIntersectionShapeData;
/** Construct a polygon with an empty outer boundary. */
public Polygon()
{
this.boundaries = new ArrayList<List<? extends Position>>();
this.boundaries.add(new ArrayList<Position>()); // placeholder for outer boundary
}
/**
* Construct a polygon for a specified outer boundary.
*
* @param corners the list of locations defining the polygon.
*
* @throws IllegalArgumentException if the location list is null.
*/
public Polygon(Iterable<? extends Position> corners)
{
this(); // to initialize the instance
if (corners == null)
{
String message = Logging.getMessage("nullValue.PositionsListIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.setOuterBoundary(corners);
}
/**
* Construct a polygon for a specified list of outer-boundary positions.
*
* @param corners the list of positions -- latitude longitude and altitude -- defining the polygon. The current
* altitude mode determines whether the positions are considered relative to mean sea level (they are
* "absolute") or the ground elevation at the associated latitude and longitude.
*
* @throws IllegalArgumentException if the position list is null.
*/
public Polygon(Position.PositionList corners)
{
this(); // to initialize the boundaries
if (corners == null)
{
String message = Logging.getMessage("nullValue.PositionsListIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.setOuterBoundary(corners.list);
}
@Override
protected void initialize()
{
// Nothing unique to initialize in this class.
}
/** Void any computed data. Called when a factor affecting the computed data is changed. */
protected void reset()
{
// Assumes that the boundary lists have already been established.
for (List<? extends Position> boundary : this.boundaries)
{
if (boundary == null || boundary.size() < 3)
continue;
//noinspection StringEquality
if (WWMath.computeWindingOrderOfLocations(boundary) != AVKey.COUNTER_CLOCKWISE)
Collections.reverse(boundary);
}
this.numPositions = this.countPositions();
this.previousIntersectionShapeData = null;
this.previousIntersectionTerrain = null;
this.previousIntersectionGlobeStateKey = null;
super.reset(); // removes all shape-data cache entries
}
/**
* Counts the total number of positions in this shape, including all positions in all boundaries.
*
* @return the number of positions in this shape.
*/
protected int countPositions()
{
int count = 0;
for (List<? extends Position> boundary : this.boundaries)
{
count += boundary.size();
}
return count;
}
/**
* Returns the list of positions defining this polygon's outer boundary.
*
* @return this polygon's outer boundary positions. The list may be empty but will not be null.
*/
public Iterable<? extends LatLon> getOuterBoundary()
{
return this.outerBoundary();
}
/**
* Returns a reference to the outer boundary of this polygon.
*
* @return this polygon's outer boundary. The list may be empty but will not be null.
*/
protected List<? extends Position> outerBoundary()
{
return this.boundaries.get(0);
}
protected boolean isOuterBoundaryValid()
{
return this.boundaries.size() > 0 && this.boundaries.get(0).size() > 2;
}
/**
* Specifies the latitude, longitude and altitude of the outer boundary positions defining this polygon.
*
* @param corners this polygon's positions. A copy of the list is made and retained, and a duplicate of the first
* position is appended to the copy if the first and last positions are not identical.
*
* @throws IllegalArgumentException if the location list is null or contains fewer than three locations.
*/
public void setOuterBoundary(Iterable<? extends Position> corners)
{
if (corners == null)
{
String message = Logging.getMessage("nullValue.PositionsListIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.boundaries.set(0, this.fillBoundary(corners));
this.reset();
}
/**
* Copies a boundary's positions to this shape's internal boundary list. Closes the boundary if it's not already
* closed.
*
* @param corners the boundary's positions.
*
* @return a list of the boundary positions.
*/
protected List<? extends Position> fillBoundary(Iterable<? extends Position> corners)
{
ArrayList<Position> list = new ArrayList<Position>();
for (Position corner : corners)
{
if (corner != null)
list.add(corner);
}
if (list.size() < 3)
{
String message = Logging.getMessage("generic.InsufficientPositions");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
// Close the list if not already closed.
if (list.size() > 0 && !list.get(0).equals(list.get(list.size() - 1)))
list.add(list.get(0));
list.trimToSize();
return list;
}
/**
* Add an inner boundary to this polygon. A duplicate of the first position is appended to the list if the list's
* last position is not identical to the first.
*
* @param corners the new boundary positions. A copy of the list is created and retained, and a duplicate of the
* first position is added to the list if the first and last positions are not identical.
*
* @throws IllegalArgumentException if the location list is null or contains fewer than three locations.
*/
public void addInnerBoundary(Iterable<? extends Position> corners)
{
if (corners == null)
{
String message = Logging.getMessage("nullValue.PositionsListIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.boundaries.add(this.fillBoundary(corners));
this.reset();
}
/**
* Returns this shape's boundaries.
*
* @return this shape's boundaries.
*/
public List<List<? extends Position>> getBoundaries()
{
return this.boundaries;
}
/**
* Returns this polygon's texture image source.
*
* @return the texture image source, or null if no source has been specified.
*/
public Object getTextureImageSource()
{
return this.imageSource;
}
/**
* Get the texture applied to this polygon. The texture is loaded on a background thread. This method will return
* null until the texture has been loaded.
*
* @return the texture, or null if there is no texture or the texture is not yet available.
*/
protected WWTexture getTexture()
{
return this.texture;
}
/**
* Returns the texture coordinates for this polygon.
*
* @return the texture coordinates, or null if no texture coordinates have been specified.
*/
public float[] getTextureCoords()
{
if (this.textureCoordsBuffer == null)
return null;
float[] retCoords = new float[this.textureCoordsBuffer.limit()];
this.textureCoordsBuffer.get(retCoords, 0, retCoords.length);
return retCoords;
}
/**
* Specifies the texture to apply to this polygon.
*
* @param imageSource the texture image source. May be a {@link String} identifying a file path or URL, a {@link
* File}, or a {@link java.net.URL}.
* @param texCoords the (s, t) texture coordinates aligning the image to the polygon. There must be one texture
* coordinate pair, (s, t), for each polygon location in the polygon's outer boundary.
* @param texCoordCount the number of texture coordinates, (s, v) pairs, specified.
*
* @throws IllegalArgumentException if the image source is not null and either the texture coordinates are null or
* inconsistent with the specified texture-coordinate count, or there are fewer
* than three texture coordinate pairs.
*/
public void setTextureImageSource(Object imageSource, float[] texCoords, int texCoordCount)
{
if (imageSource == null)
{
this.texture = null;
this.textureCoordsBuffer = null;
return;
}
if (texCoords == null)
{
String message = Logging.getMessage("generic.ListIsEmpty");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (texCoordCount < 3 || texCoords.length < 2 * texCoordCount)
{
String message = Logging.getMessage("generic.InsufficientPositions");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.imageSource = imageSource;
this.texture = this.makeTexture(this.imageSource);
// Determine whether the tex-coord list needs to be closed.
boolean closeIt = texCoords[0] != texCoords[texCoordCount - 2] || texCoords[1] != texCoords[texCoordCount - 1];
int size = 2 * (texCoordCount + (closeIt ? 1 : 0));
if (this.textureCoordsBuffer == null || this.textureCoordsBuffer.capacity() < size)
{
this.textureCoordsBuffer = BufferUtil.newFloatBuffer(size);
}
else
{
this.textureCoordsBuffer.limit(this.textureCoordsBuffer.capacity());
this.textureCoordsBuffer.rewind();
}
for (int i = 0; i < 2 * texCoordCount; i++)
{
this.textureCoordsBuffer.put(texCoords[i]);
}
if (closeIt)
{
this.textureCoordsBuffer.put(this.textureCoordsBuffer.get(0));
this.textureCoordsBuffer.put(this.textureCoordsBuffer.get(1));
}
}
public Position getReferencePosition()
{
if (this.referencePosition != null)
return this.referencePosition;
if (this.outerBoundary().size() > 0)
this.referencePosition = this.outerBoundary().get(0);
return this.referencePosition;
}
/**
* Indicates the amount of rotation applied to this polygon.
*
* @return the rotation in degrees, or null if no rotation is specified.
*/
public Double getRotation()
{
return this.rotation;
}
/**
* Specifies the amount of rotation applied to this polygon. Positive rotation is counter-clockwise.
*
* @param rotation the amount of rotation to apply, in degrees, or null to apply no rotation.
*/
public void setRotation(Double rotation)
{
this.rotation = rotation;
this.reset();
}
public Extent getExtent(Globe globe, double verticalExaggeration)
{
// See if we've cached an extent associated with the globe.
Extent extent = super.getExtent(globe, verticalExaggeration);
if (extent != null)
return extent;
return super.computeExtentFromPositions(globe, verticalExaggeration, this.getOuterBoundary());
}
/**
* Computes the Cartesian extent of a polygon boundary.
*
* @param boundary The boundary to compute the extent for.
* @param refPoint the shape's reference point.
*
* @return the boundary's extent. Returns null if the boundary's vertices have not been computed.
*/
protected Extent computeExtent(BoundaryInfo boundary, Vec4 refPoint)
{
if (boundary == null || boundary.vertices == null)
return null;
// The bounding box is computed relative to the polygon's reference point, so it needs to be translated to
// model coordinates in order to indicate its model-coordinate extent.
Box boundingBox = Box.computeBoundingBox(Arrays.asList(boundary.vertices));
return boundingBox != null ? boundingBox.translate(refPoint) : null;
}
public Sector getSector()
{
if (this.sector == null && this.isOuterBoundaryValid())
this.sector = Sector.boundingSector(this.getOuterBoundary());
return this.sector;
}
protected boolean mustApplyTexture(DrawContext dc)
{
return this.getTexture() != null && this.textureCoordsBuffer != null;
}
protected boolean shouldUseVBOs(DrawContext dc)
{
return this.numPositions > VBO_THRESHOLD && super.shouldUseVBOs(dc);
}
protected boolean mustRegenerateGeometry(DrawContext dc)
{
if (this.getCurrent().coordBuffer == null)
return true;
if (dc.getVerticalExaggeration() != this.getCurrent().getVerticalExaggeration())
return true;
if (this.mustApplyLighting(dc, null) && this.getCurrent().normalBuffer == null)
return true;
if (this.getAltitudeMode() == WorldWind.ABSOLUTE
&& this.getCurrent().getGlobeStateKey() != null
&& this.getCurrent().getGlobeStateKey().equals(dc.getGlobe().getGlobeStateKey(dc)))
return false;
return super.mustRegenerateGeometry(dc);
}
public void render(DrawContext dc)
{
if (!this.isOuterBoundaryValid())
return;
super.render(dc);
}
protected boolean doMakeOrderedRenderable(DrawContext dc)
{
if (dc.getSurfaceGeometry() == null || !this.isOuterBoundaryValid())
return false;
this.getCurrent().setRotationMatrix(this.getRotation() != null ?
this.computeRotationMatrix(dc.getGlobe()) : null);
this.createMinimalGeometry(dc, this.getCurrent());
// If the shape is less that a pixel in size, don't render it.
if (this.getCurrent().getExtent() == null || dc.isSmall(this.getExtent(), 1))
return false;
if (!this.intersectsFrustum(dc))
return false;
this.createFullGeometry(dc, dc.getTerrain(), this.getCurrent(), true);
return true;
}
protected boolean isOrderedRenderableValid(DrawContext dc)
{
return this.getCurrent().coordBuffer != null && this.isOuterBoundaryValid();
}
protected OGLStackHandler beginDrawing(DrawContext dc, int attrMask)
{
OGLStackHandler ogsh = super.beginDrawing(dc, attrMask);
if (!dc.isPickingMode())
{
// Push an identity texture matrix. This prevents drawSides() from leaking GL texture matrix state. The
// texture matrix stack is popped from OGLStackHandler.pop(), in the finally block below.
ogsh.pushTextureIdentity(dc.getGL());
}
return ogsh;
}
protected void doDrawOutline(DrawContext dc)
{
if (this.shouldUseVBOs(dc))
{
int[] vboIds = this.getVboIds(dc);
if (vboIds != null)
this.doDrawOutlineVBO(dc, vboIds, this.getCurrent());
else
this.doDrawOutlineVA(dc, this.getCurrent());
}
else
{
this.doDrawOutlineVA(dc, this.getCurrent());
}
}
protected void doDrawOutlineVA(DrawContext dc, ShapeData shapeData)
{
GL gl = dc.getGL();
gl.glVertexPointer(3, GL.GL_FLOAT, 0, shapeData.coordBuffer.rewind());
if (!dc.isPickingMode() && this.mustApplyLighting(dc, null))
gl.glNormalPointer(GL.GL_FLOAT, 0, shapeData.normalBuffer.rewind());
int k = 0;
for (BoundaryInfo boundary : shapeData)
{
gl.glDrawArrays(GL.GL_LINE_STRIP, k, boundary.vertices.length);
k += boundary.vertices.length;
}
// // Diagnostic to show the normal vectors.
// if (this.mustApplyLighting(dc))
// dc.drawNormals(1000, this.boundarySet.coordBuffer, this.boundarySet.normalBuffer);
}
protected void doDrawOutlineVBO(DrawContext dc, int[] vboIds, ShapeData shapeData)
{
GL gl = dc.getGL();
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]);
gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0);
if (!dc.isPickingMode() && this.mustApplyLighting(dc, null))
gl.glNormalPointer(GL.GL_FLOAT, 0, 4 * shapeData.normalBufferPosition);
int k = 0;
for (BoundaryInfo boundary : shapeData)
{
// TODO: check use glMultiDrawArrays
gl.glDrawArrays(GL.GL_LINE_STRIP, k, boundary.vertices.length);
k += boundary.vertices.length;
}
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);
}
protected void doDrawInterior(DrawContext dc)
{
GL gl = dc.getGL();
if (!dc.isPickingMode() && mustApplyTexture(dc) && this.getTexture().bind(dc)) // bind initiates retrieval
{
this.getTexture().applyInternalTransform(dc);
gl.glTexCoordPointer(2, GL.GL_FLOAT, 0, this.textureCoordsBuffer.rewind());
dc.getGL().glEnable(GL.GL_TEXTURE_2D);
gl.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY);
}
else
{
dc.getGL().glDisable(GL.GL_TEXTURE_2D);
gl.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY);
}
if (this.shouldUseVBOs(dc))
{
int[] vboIds = this.getVboIds(dc);
if (vboIds != null)
this.doDrawInteriorVBO(dc, vboIds, this.getCurrent());
else
this.doDrawInteriorVA(dc, this.getCurrent());
}
else
{
this.doDrawInteriorVA(dc, this.getCurrent());
}
}
protected void doDrawInteriorVA(DrawContext dc, ShapeData shapeData)
{
GL gl = dc.getGL();
if (!dc.isPickingMode() && this.mustApplyLighting(dc, null))
gl.glNormalPointer(GL.GL_FLOAT, 0, shapeData.normalBuffer.rewind());
FloatBuffer vb = shapeData.coordBuffer;
gl.glVertexPointer(3, GL.GL_FLOAT, 0, vb.rewind());
IntBuffer ib = shapeData.interiorIndicesBuffer;
gl.glDrawElements(GL.GL_TRIANGLES, ib.limit(), GL.GL_UNSIGNED_INT, ib);
}
protected void doDrawInteriorVBO(DrawContext dc, int[] vboIds, ShapeData shapeData)
{
GL gl = dc.getGL();
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboIds[0]);
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, vboIds[1]);
gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0);
if (!dc.isPickingMode() && this.mustApplyLighting(dc, null))
gl.glNormalPointer(GL.GL_FLOAT, 0, 4 * shapeData.normalBufferPosition);
gl.glDrawElements(GL.GL_TRIANGLES, shapeData.interiorIndicesBuffer.limit(), GL.GL_UNSIGNED_INT, 0);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0);
}
protected Matrix computeRotationMatrix(Globe globe)
{
if (this.getRotation() == null)
return null;
Sector s = this.getSector();
if (s == null)
return null;
// Using the four corners of the sector to compute the rotation axis avoids any problems with dateline
// spanning polygons.
Vec4[] verts = s.computeCornerPoints(globe, 1);
Vec4 center = s.computeCenterPoint(globe, 1);
Matrix m1 = Matrix.fromTranslation(center.multiply3(-1));
Matrix m3 = Matrix.fromTranslation(center);
Vec4 normalVec = verts[2].subtract3(verts[0]).cross3(verts[3].subtract3(verts[1])).normalize3();
Matrix m2 = Matrix.fromAxisAngle(Angle.fromDegrees(this.getRotation()), normalVec);
return m3.multiply(m2).multiply(m1);
}
/**
* Compute enough geometry to determine this polygon's extent, reference point and eye distance.
* <p/>
* A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called.
*
* @param dc the current draw context.
* @param shapeData the current shape data for this shape.
*/
protected void createMinimalGeometry(DrawContext dc, ShapeData shapeData)
{
Matrix rotationMatrix = shapeData.getRotationMatrix();
Vec4 refPt = this.computeReferencePoint(dc.getTerrain(), rotationMatrix);
if (refPt == null)
return;
shapeData.setReferencePoint(refPt);
// Need only the outer-boundary vertices.
this.computeBoundaryVertices(dc.getTerrain(), shapeData.getOuterBoundaryInfo(),
shapeData.getReferencePoint(), rotationMatrix);
if (shapeData.getExtent() == null || this.getAltitudeMode() != WorldWind.ABSOLUTE)
shapeData.setExtent(this.computeExtent(shapeData.getOuterBoundaryInfo(),
shapeData.getReferencePoint()));
shapeData.setEyeDistance(this.computeEyeDistance(dc, shapeData));
shapeData.setGlobeStateKey(dc.getGlobe().getGlobeStateKey(dc));
shapeData.setVerticalExaggeration(dc.getVerticalExaggeration());
}
/**
* Computes the minimum distance between this polygon and the eye point.
* <p/>
* A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called.
*
* @param dc the draw context.
* @param shapeData the current shape data for this shape.
*
* @return the minimum distance from the shape to the eye point.
*/
protected double computeEyeDistance(DrawContext dc, ShapeData shapeData)
{
double minDistance = Double.MAX_VALUE;
Vec4 eyePoint = dc.getView().getEyePoint();
for (Vec4 point : shapeData.getOuterBoundaryInfo().vertices)
{
double d = point.add3(shapeData.getReferencePoint()).distanceTo3(eyePoint);
if (d < minDistance)
minDistance = d;
}
return minDistance;
}
protected Vec4 computeReferencePoint(Terrain terrain, Matrix rotationMatrix)
{
Position refPos = this.getReferencePosition();
if (refPos == null)
return null;
Vec4 refPt = terrain.getSurfacePoint(refPos.getLatitude(), refPos.getLongitude(), 0);
if (refPt == null)
return null;
return rotationMatrix != null ? refPt.transformBy4(rotationMatrix) : refPt;
}
/**
* Computes a shape's full geometry.
*
* @param dc the current draw context.
* @param terrain the terrain to use when computing the geometry.
* @param shapeData the current shape data for this shape.
* @param skipOuterBoundary true if outer boundaries vertices do not need to be calculated, otherwise false.
*/
protected void createFullGeometry(DrawContext dc, Terrain terrain, ShapeData shapeData,
boolean skipOuterBoundary)
{
this.createVertices(terrain, shapeData, skipOuterBoundary);
this.createGeometry(dc, shapeData);
if (this.mustApplyLighting(dc, null))
this.createNormals(shapeData);
else
shapeData.normalBuffer = null;
}
/**
* Computes the Cartesian vertices for this shape.
*
* @param terrain the terrain to use if the altitude mode is relative to the terrain.
* @param shapeData the current shape data for this shape.
* @param skipOuterBoundary if true, don't calculate the vertices for the outer boundary. This is used when the
* outer boundary vertices were computed as minimal geometry.
*/
protected void createVertices(Terrain terrain, ShapeData shapeData, boolean skipOuterBoundary)
{
for (BoundaryInfo boundary : shapeData)
{
if (boundary != shapeData.getOuterBoundaryInfo() || !skipOuterBoundary)
this.computeBoundaryVertices(terrain, boundary, shapeData.getReferencePoint(),
shapeData.getRotationMatrix());
}
}
/**
* Compute the vertices associated with a specified boundary.
*
* @param terrain the terrain to use when calculating vertices relative to the ground.
* @param boundary the boundary to compute vertices for.
* @param refPoint the reference point. Vertices are computed relative to this point, which is usually the
* shape's reference point.
* @param rotationMatrix the rotation matrix to apply to the vertices.
*/
protected void computeBoundaryVertices(Terrain terrain, BoundaryInfo boundary, Vec4 refPoint, Matrix rotationMatrix)
{
int n = boundary.positions.size();
Vec4[] boundaryVertices = new Vec4[n];
for (int i = 0; i < n; i++)
{
if (rotationMatrix == null)
boundaryVertices[i] = this.computePoint(terrain, boundary.positions.get(i)).subtract3(refPoint);
else
boundaryVertices[i] = this.computePoint(terrain, boundary.positions.get(i)).transformBy4(
rotationMatrix).subtract3(refPoint);
}
boundary.vertices = boundaryVertices;
}
/**
* Compute the cap geometry.
* <p/>
* A {@link gov.nasa.worldwind.render.AbstractShape.AbstractShapeData} must be current when this method is called.
*
* @param dc the current draw context.
* @param shapeData boundary vertices are calculated during {@link #createMinimalGeometry(DrawContext,
* gov.nasa.worldwind.render.Polygon.ShapeData)}).
*/
protected void createGeometry(DrawContext dc, ShapeData shapeData)
{
int size = this.numPositions * (this.mustApplyLighting(dc, null) ? 6 : 3);
if (shapeData.coordBuffer != null && shapeData.coordBuffer.capacity() >= size)
shapeData.coordBuffer.clear();
else
shapeData.coordBuffer = BufferUtil.newFloatBuffer(size);
// Capture the position position at which normals buffer starts (in case there are normals)
shapeData.normalBufferPosition = this.numPositions * 3;
// Fill the vertex buffer. Simultaneously create individual buffer slices for each boundary.
for (BoundaryInfo boundary : shapeData)
{
boundary.vertexBuffer = WWBufferUtil.copyArrayToBuffer(boundary.vertices, shapeData.coordBuffer.slice());
shapeData.coordBuffer.position(shapeData.coordBuffer.position() + boundary.vertexBuffer.limit());
}
if (shapeData.cb == null && !shapeData.tessellationError)
this.createTessllationGeometry(dc, shapeData);
if (shapeData.refillIndexBuffer)
this.generateInteriorIndices(shapeData);
}
/**
* Create this shape's vertex normals.
*
* @param shapeData the current shape data holding the vertex coordinates and in which the normal vectors are added.
* The normal vectors are appended to the vertex coordinates in the same buffer. The shape data's
* coordinate buffer must have sufficient capacity to hold the vertex normals.
*/
protected void createNormals(ShapeData shapeData)
{
shapeData.coordBuffer.position(shapeData.normalBufferPosition);
shapeData.normalBuffer = shapeData.coordBuffer.slice();
for (BoundaryInfo boundary : shapeData)
{
this.computeBoundaryNormals(boundary, shapeData.normalBuffer);
}
}