Debian Codegraph @

src/surfaceArea.c

raw symbols SCIP
1 #include <stdio.h>
2 #include <math.h>
3 #include <R.h>
4 #include "sp.h"
5
6 /*
7 Compute surface area, using method from:
8
9 Calculating Landscape Surface Area from Digital Elevation Models
10 Author(s): Jeff S. Jenness
11 Source: Wildlife Society Bulletin, Vol. 32, No. 3 (Autumn, 2004), pp. 829-839
12 Published by: Allen Press
13 Stable URL: http://www.jstor.org/stable/3784807
14
15 with edge adjustments.
16
17 (c) Barry Rowlingson 2010 <[email protected]>
18
19 */
20
21 double height(double *heights, int *nx, int i, int j){
22 return(heights[(i)+(*nx)*(j)]);
23 }
24
25 double triarea(double a, double b, double c){
26 /* triangle area given side lengths */
27 double s;
28 s=(a+b+c)/2.0;
29 return(sqrt(s*(s-a)*(s-b)*(s-c)));
30 }
31
32 void sarea(double *heights, int *nx, int *ny, double *w, double *h, double *sa, int *bycell){
33
34 /*
35 given an *nx by *ny matrix of *heights with single-cell edge border, compute
36 the surface area. If bycell==1, then return a matrix of individual cell
37 area estimates, otherwise add them all up and return the sum in *sa (allocated in R)
38 */
39
40 /* point values */
41 double z1,z2,z3;
42 /* side lengths */
43 double l1,l2,l3;
44
45 /* diagonal length */
46 double s2 = sqrt((*w)*(*w)+(*h)*(*h));
47
48 /* offsets to neighbours */
49 int dxv[]={-1,0,1,1,1,0,-1,-1,-1};
50 int dyv[]={-1,-1,-1,0,1,1,1,0,-1};
51
52 /* triangle side lengths */
53 /* first the radial sides */
54 double side[]={s2,*h,s2,*w,s2,*h,s2,*w,s2};
55 /* outer edges */
56 double l3v[]={*w,*w,*h,*h,*w,*w,*h,*h};
57
58 double cellArea;
59 int cellI;
60
61 if(*bycell==0){
62 *sa = 0.0;
63 }else{
64 cellI=0; /* saves us computing 2-d array indices */
65 }
66 for(int j=1;j<(*ny-1);j++){
67 for(int i=1;i<(*nx-1);i++){
68 z1 = height(heights,nx,i,j);
69 cellArea=0;
70 if(!ISNA(z1)){
71 for(int tri=0;tri<8;tri++){
72 z2=height(heights,nx,i+dxv[tri],j+dyv[tri]);
73 /* replace missing adjacent values with the current cell value */
74 if(ISNA(z2))z2=z1;
75 z3=height(heights,nx,i+dxv[tri+1],j+dyv[tri+1]);
76 if(ISNA(z3))z3=z1;
77 l1 = 0.5 * sqrt(side[tri]*side[tri]+(z1-z2)*(z1-z2));
78 l2 = 0.5 * sqrt(side[tri+1]*side[tri+1]+(z1-z3)*(z1-z3));
79 l3 = 0.5 * sqrt(l3v[tri]*l3v[tri]+(z2-z3)*(z2-z3));
80 cellArea += triarea(l1,l2,l3);
81 }
82 }
83 if(*bycell==0){
84 *sa += cellArea;
85 }else{
86 if(!ISNA(z1)){
87 sa[cellI]=cellArea;
88 }
89 cellI++;
90 }
91
92 }
93 }
94 }
95
96