-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhillshade.pde
99 lines (78 loc) · 2.65 KB
/
hillshade.pde
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
// based on hillshade.cpp by Matthew Perry
// http://perrygeo.googlecode.com/svn/trunk/demtools/hillshade.cpp
int[][] hillshade(int[][] elevations, float ewres, float nsres, int nXSize, int nYSize) {
int[][] shadeBuf = new int[nXSize][nYSize];
int nullValue = 0; // could be any number
float z = 1.0;
float scale = 1.0;
float az = 315-270;
float alt = 65.0;
float radiansToDegrees = 180.0 / 3.14159;
float degreesToRadians = 3.14159 / 180.0;
// tmp vars all used in for loop
float[] win = new float[9];
boolean containsNull;
float cang;
float x, y;
float slope, aspect;
for (int i = 0; i < nYSize; i++) {
for (int j = 0; j < nXSize; j++) {
containsNull = false;
// Exclude the edges
if (i == 0 || j == 0 || i == nYSize-1 || j == nXSize-1 )
{
// We are at the edge so write nullValue and move on
shadeBuf[j][i] = nullValue;
containsNull = true;
continue;
}
// Read in 3x3 window
/* ------------------------------------------
* Move a 3x3 window over each cell
* (where the cell in question is #4)
*
* 0 1 2
* 3 4 5
* 6 7 8
*/
win[0] = elevations[j-1][i-1];
win[1] = elevations[j ][i-1];
win[2] = elevations[j+1][i-1];
win[3] = elevations[j-1][i ];
win[4] = elevations[j ][i ];
win[5] = elevations[j+1][i ];
win[6] = elevations[j-1][i+1];
win[7] = elevations[j ][i+1];
win[8] = elevations[j+1][i+1];
if (containsNull) {
// We have nulls so write nullValue and move on
shadeBuf[j][i] = nullValue;
continue;
}
else {
// We have a valid 3x3 window.
/* ---------------------------------------
* Compute Hillshade
*/
// First Slope ...
x = ((z*win[0] + z*win[3] + z*win[3] + z*win[6]) -
(z*win[2] + z*win[5] + z*win[5] + z*win[8])) /
(8.0 * ewres * scale);
y = ((z*win[6] + z*win[7] + z*win[7] + z*win[8]) -
(z*win[0] + z*win[1] + z*win[1] + z*win[2])) /
(8.0 * nsres * scale);
slope = 90.0 - atan(sqrt(x*x + y*y))*radiansToDegrees;
// ... then aspect...
aspect = atan2(x, y);
// ... then the shade value
cang = sin(alt*degreesToRadians) * sin(slope*degreesToRadians) +
cos(alt*degreesToRadians) * cos(slope*degreesToRadians) *
cos((az-90.0)*degreesToRadians - aspect);
if (cang <= 0.0) cang = nullValue;
else cang = 255.0 * cang;
shadeBuf[j][i] = (int)cang;
}
}
}
return shadeBuf;
}