gridviz 3.0.31 → 3.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,280 @@
1
+ //@ts-check
2
+ 'use strict'
3
+
4
+ import { Style } from '../core/Style.js'
5
+ import { cellsToGrid, cellsToMatrix } from '../utils/utils.js'
6
+ import { SquareColorCategoryWebGLStyle } from './SquareColorCategoryWebGLStyle.js'
7
+ //import { SquareColorWebGLStyle } from './SquareColorWebGLStyle.js'
8
+ import { extent } from 'd3-array'
9
+
10
+
11
+ //TODO:
12
+ // make faster algo by setting shades by sun ray
13
+ // diffusion effect ? based on distance to light (altitude - sun ray height)
14
+ // style with SquareColorWebGLStyle, improved version !
15
+
16
+ /**
17
+ * @module style
18
+ * @author Julien Gaffuri
19
+ */
20
+ export class ShadingRayStyle extends Style {
21
+ /** @param {object} opts */
22
+ constructor(opts) {
23
+ super(opts)
24
+ opts = opts || {}
25
+
26
+ this.elevation = opts.elevation //(c) => elevation
27
+
28
+ this.sunAzimuth = opts.sunAzimuth || (() => 2.356) //(r,z,vs)=>
29
+ this.sunAltitude = opts.sunAltitude || (() => 0.2) //(r,z,vs)=>
30
+
31
+ //this.alpha = opts.alpha || (() => 0.33) //(z,vs)
32
+ this.color = opts.color || (() => 'black') //(r,z,vs) => {}
33
+
34
+ this.undefinedValue = opts.undefinedValue || 0
35
+
36
+ //this.version = opts.version || 1
37
+ // used only for v2
38
+ //this.shadowProperty = opts.shadowProperty || "shadow"
39
+ }
40
+
41
+ /**
42
+ *
43
+ * @param {Array.<import("../core/Dataset.js").Cell>} cells
44
+ * @param {import("../core/GeoCanvas.js").GeoCanvas} geoCanvas
45
+ * @param {number} resolution
46
+ */
47
+ draw(cells, geoCanvas, resolution) {
48
+ //filter
49
+ if (this.filter) cells = cells.filter(this.filter)
50
+ if (cells.length == 0) return;
51
+
52
+ //
53
+ const z = geoCanvas.view.z
54
+
55
+ //get view scale
56
+ const viewScale = this.viewScale ? this.viewScale(cells, resolution, z) : undefined
57
+
58
+ //if (this.version == "1") {
59
+ //index cells by y and x
60
+ let m = cellsToMatrix(cells, resolution, c => this.elevation(c))
61
+ const x0 = m.x0, y0 = m.y0
62
+
63
+ // compute ray casting shadow
64
+ m = referenceShadow(
65
+ m,
66
+ resolution,
67
+ this.sunAzimuth(resolution, z, viewScale),
68
+ this.sunAltitude(resolution, z, viewScale),
69
+ this.undefinedValue);
70
+
71
+ // make cells
72
+ cells = []
73
+ for (let i = 0; i < m.length; i++) {
74
+ const row = m[i]
75
+ const y = y0 - i * resolution
76
+ for (let j = 0; j < row.length; j++) {
77
+ const sh = row[j]
78
+ if (!sh) continue
79
+ const c = { x: x0 + j * resolution, y: y }
80
+ //c[this.shadowProperty] = sh
81
+ cells.push(c)
82
+ }
83
+ }
84
+ //} else {
85
+ //clean previsouly computed shadows
86
+ /*for (let c of cells) delete c[this.shadowProperty]
87
+
88
+ //compute shading
89
+ referenceShadowV2(
90
+ cells,
91
+ resolution,
92
+ (c) => this.elevation(c),
93
+ this.shadowProperty,
94
+ this.sunAzimuth(resolution, z, viewScale),
95
+ this.sunAltitude(resolution, z, viewScale));
96
+
97
+ //keep only those with shadow
98
+ cells = cells.filter(c => c.shadow)*/
99
+ //}
100
+
101
+ //set style alpha and blend mode
102
+ //TODO: multiply by layer alpha ?
103
+ //geoCanvas.ctx.globalAlpha = s.alpha ? s.alpha(z) : 1.0
104
+ //if (s.blendOperation) geoCanvas.ctx.globalCompositeOperation = s.blendOperation(z)
105
+
106
+ //set affin transform to draw with geographical coordinates
107
+ //geoCanvas.setCanvasTransform()
108
+
109
+ //draw shadowed cells with webgl style
110
+ new SquareColorCategoryWebGLStyle({
111
+ code: () => "a",
112
+ color: { 'a': this.color(resolution, z, viewScale) },
113
+ //alpha: () => this.alpha(resolution, z, viewScale),
114
+ }).draw(cells, geoCanvas, resolution)
115
+
116
+ /*new SquareColorWebGLStyle({
117
+ filter: (c => c.shadow),
118
+ tFun: (c, r) => c.shadow, //1-Math.min(1, c.shadow / 10000),//c.shadow, //,
119
+ color: (t => "rgba(0,0,0," + t + ")"),
120
+ alpha: () => this.alpha(resolution, z, viewScale),
121
+ }).draw(cells, geoCanvas, resolution)*/
122
+
123
+ //draw style filter
124
+ //if (s.filterColor) s.drawFilter(geoCanvas)
125
+
126
+ //update legends
127
+ this.updateLegends({ style: this, resolution: resolution, z: z, viewScale: viewScale })
128
+ }
129
+ }
130
+
131
+
132
+
133
+
134
+ /**
135
+ * Ground-truth terrain shadow algorithm (ray-based)
136
+ * Trig-free with undefined handling
137
+ *
138
+ * @param {number[][]} elevation - DEM [row][col], may contain undefined
139
+ * @param {number} resolution
140
+ * @param {number} sunAzimuth - radians, clockwise from north (+Y)
141
+ * @param {number} sunAltitude - radians - solar elevation angle above the local horizontal plane
142
+ * @param {number|undefined} undefinedValue - The value to set for cells with no elevation value
143
+ * @returns {(number|undefined)[][]} shade. Height above ground where ray light can be reached.
144
+ */
145
+ function referenceShadow(
146
+ elevation,
147
+ resolution = 1000,
148
+ sunAzimuth = 2.356, // 2PI/3
149
+ sunAltitude = 0.15,
150
+ undefinedValue = undefined,
151
+ ) {
152
+ const rows = elevation.length;
153
+ const cols = elevation[0].length;
154
+
155
+ // Sun direction TOWARD the sun
156
+ const ux = Math.sin(sunAzimuth);
157
+ const uy = -Math.cos(sunAzimuth);
158
+ const tanAlt = Math.tan(sunAltitude);
159
+
160
+ //const diffAngle = 40 * Math.PI / 180 // 0.5 deg
161
+ //const tanTop = Math.tan(sunAltitude + diffAngle)
162
+ //const tanBottom = Math.tan(Math.max(sunAltitude - diffAngle, 0))
163
+ //const tanBottom = Math.tan(sunAltitude - diffAngle)
164
+
165
+ const shade = Array.from({ length: rows }, () => new Array(cols).fill(undefined));
166
+
167
+ for (let y0 = 0; y0 < rows; y0++) {
168
+ for (let x0 = 0; x0 < cols; x0++) {
169
+
170
+ const z0raw = elevation[y0][x0] || undefinedValue;
171
+ if (z0raw === undefined) continue;
172
+
173
+ // cast ray
174
+ let t = resolution;
175
+ while (true) {
176
+ const x = x0 - ux * t / resolution;
177
+ const y = y0 - uy * t / resolution;
178
+
179
+ const ix = Math.round(x);
180
+ const iy = Math.round(y);
181
+
182
+ if (ix < 0 || iy < 0 || ix >= cols || iy >= rows) break;
183
+
184
+ const zqraw = elevation[iy][ix] || undefinedValue;
185
+ if (zqraw === undefined) break; // transparent gap
186
+
187
+ //const deltaBottom = zqraw - z0raw - tanBottom * t;
188
+ //if (deltaBottom > 0) {
189
+ const delta = zqraw - z0raw - tanAlt * t;
190
+ if (delta > 0) {
191
+ shade[y0][x0] = 1 //Math.min(3000 / t, 1)
192
+ break;
193
+ /*}
194
+ //const deltaTop = zqraw - z0raw - tanTop * t;
195
+ //if (deltaTop > 0) {
196
+ // shade[y0][x0] = 0
197
+ // break;
198
+ //} else {
199
+ let r = 1 + delta / deltaBottom
200
+ if (r < 0) r = 0
201
+ if (r < 0 || r > 1) console.log(r)
202
+ shade[y0][x0] = shade[y0][x0] ? Math.max(shade[y0][x0], r) : r
203
+ //}*/
204
+ }
205
+ t += resolution;
206
+ }
207
+ }
208
+ }
209
+ return shade;
210
+ }
211
+
212
+
213
+
214
+
215
+ /**
216
+ * Ground-truth terrain shadow algorithm (ray-based)
217
+ * Trig-free with undefined handling
218
+ *
219
+ * @param {Array.<Cell>} cells - DEM [row][col], may contain undefined
220
+ * @param {number} resolution
221
+ * @param {Function} elevationFun
222
+ * @param {string} shadowProperty
223
+ * @param {number} sunAzimuth - radians, clockwise from north (+Y)
224
+ * @param {number} sunAltitude - radians - solar elevation angle above the local horizontal plane
225
+ */
226
+ function referenceShadowV2(
227
+ cells,
228
+ resolution = 1000,
229
+ elevationFun,
230
+ shadowProperty = "shadow",
231
+ sunAzimuth = 2.356, // 2PI/3
232
+ sunAltitude = 0.15
233
+ ) {
234
+
235
+ //get geo extent
236
+ const [minx, maxx] = extent(cells, c => c.x)
237
+ const [miny, maxy] = extent(cells, c => c.y)
238
+
239
+ //index cells by y and x
240
+ const ind = cellsToGrid(cells)
241
+
242
+ // Sun direction TOWARD the sun
243
+ const ux = Math.sin(sunAzimuth);
244
+ const uy = Math.cos(sunAzimuth);
245
+ const tanAlt = Math.tan(sunAltitude);
246
+
247
+ for (let y0 = miny; y0 <= maxy; y0 += resolution) {
248
+ const row = ind[y0]
249
+ if (!row) continue
250
+ for (let x0 = minx; x0 <= maxx; x0 += resolution) {
251
+ const cell0 = row[x0]
252
+ if (!cell0) continue
253
+ const z0raw = elevationFun(cell0);
254
+ if (z0raw === undefined) continue;
255
+
256
+ // ray
257
+ let t = resolution;
258
+ while (true) {
259
+ const y = y0 - Math.round(uy * t / resolution) * resolution;
260
+ if (!ind[y]) break; // transparent gap
261
+
262
+ const x = x0 + Math.round(ux * t / resolution) * resolution;
263
+ const cellq = ind[y][x];
264
+ if (!cellq) break; // transparent gap
265
+
266
+ const zqraw = elevationFun(cellq);
267
+ if (zqraw === undefined) break; // transparent gap
268
+
269
+ // the height above the ground where light ray can be reached
270
+ const delta = zqraw - z0raw - tanAlt * t;
271
+ if (delta > 0) {
272
+ cell0[shadowProperty] = delta
273
+ break;
274
+ }
275
+ t += resolution;
276
+ }
277
+ }
278
+ }
279
+ }
280
+
@@ -124,12 +124,17 @@ export class SideStyle extends Style {
124
124
  * @param {boolean} center Set to true so that the side coordinate are those of its center point rather than its left/bottom point (the side x,y coordinates are those of the left point for horizontal sides, and of the bottom point for vertical sides)
125
125
  * @returns { Array.<Side> }
126
126
  */
127
- static buildSides(cells, resolution, withHorizontal = true, withVertical = true, center = true) {
127
+ static buildSides(cells, resolution, withHorizontal = true, withVertical = true, center = true, eps = 0.01) {
128
128
  /** @type { Array.<Side> } */
129
129
  const sides = []
130
130
 
131
+ // half resolution
131
132
  const r2 = center ? resolution / 2 : 0
132
133
 
134
+ // epsilon
135
+ eps = resolution * eps
136
+ const abs = Math.abs
137
+
133
138
  //make horizontal sides
134
139
  //sort cells by x and y
135
140
  cells.sort((c1, c2) => (c2.x == c1.x ? c1.y - c2.y : c1.x - c2.x))
@@ -137,7 +142,7 @@ export class SideStyle extends Style {
137
142
  for (let i = 1; i < cells.length; i++) {
138
143
  let c2 = cells[i]
139
144
 
140
- if (c1.y + resolution == c2.y && c1.x == c2.x)
145
+ if (abs(c1.y + resolution - c2.y) < eps && abs(c1.x - c2.x) < eps)
141
146
  //cells in same column and touch along horizontal side
142
147
  //make shared side
143
148
  sides.push({
@@ -176,7 +181,7 @@ export class SideStyle extends Style {
176
181
  for (let i = 1; i < cells.length; i++) {
177
182
  let c2 = cells[i]
178
183
 
179
- if (c1.x + resolution == c2.x && c1.y == c2.y)
184
+ if (abs(c1.x + resolution - c2.x) < eps && abs(c1.y - c2.y) < eps)
180
185
  //cells in same row and touch along vertical side
181
186
  //make shared side
182
187
  sides.push({
@@ -10,6 +10,8 @@ import { SideStyle } from './SideStyle.js'
10
10
  * @typedef {function(Array.<Side>,number, number):*} SideViewScale */
11
11
 
12
12
  /**
13
+ * @see https://manifold.net/doc/mfd9/example__tanaka_contours.htm
14
+ *
13
15
  * @module style
14
16
  * @author Julien Gaffuri
15
17
  */
@@ -25,7 +27,7 @@ export class SideTanakaStyle extends Style {
25
27
 
26
28
  /** A function returning the width of a cell side, in geo unit
27
29
  * @type {function(Side, number, number, number, object):number} */
28
- this.width = opts.width || ((side, sideValue, resolution, z, sidesScale) => Math.abs(sideValue) * Math.min(2 * z, resolution / 3))
30
+ this.width = opts.width || ((side, sideValue, resolution, z, sidesScale) => Math.abs(sideValue) * z) //Math.min(2 * z, resolution / 3))
29
31
 
30
32
  /** A function returning the length of a cell side, in geo unit
31
33
  * @type {function(Side, number, number, object):number} */
@@ -141,7 +141,7 @@ export class SquareColorCategoryWebGLStyle extends Style {
141
141
  c = cells[i]
142
142
  const cat = this.code(c, resolution, z, viewScale)
143
143
  if (cat == undefined) {
144
- console.log('Unexpected category: ' + cat)
144
+ //console.log('Unexpected category: ' + cat)
145
145
  continue
146
146
  }
147
147
  const i_ = this.catToI[cat]
@@ -236,7 +236,7 @@ export class SquareColorCategoryWebGLStyle extends Style {
236
236
  geoCanvas.offscreenCtx.drawImage(canvas, 0, 0)
237
237
 
238
238
  //update legends
239
- this.updateLegends({ style: this, resolution: resolution, z: z })
239
+ this.updateLegends({ style: this, resolution: resolution, z: z, viewScale: viewScale })
240
240
  }
241
241
  }
242
242
 
@@ -151,6 +151,28 @@ export const viewScaleColorQuantile = (opts) => {
151
151
  }
152
152
  }
153
153
 
154
+
155
+ /**
156
+ * Generic function for view scale quantile classifier
157
+ *
158
+ * @param {{ valueFunction:function(import("../core/Dataset").Cell):number, classNumber?:number }} opts
159
+ * @returns {function(Array.<import("../core/Dataset").Cell>):ColorScale}
160
+ */
161
+ export const viewScaleQuantileClassifer = (opts) => {
162
+ const valueFunction = opts.valueFunction // the function that return the cell value from a cell
163
+ const classNumber = opts.classNumber || 12 // the class number
164
+
165
+ const scale = scaleQuantile().range(Array.from( { length: classNumber }, (_, i) => i ))
166
+ return (cells) => {
167
+ scale.domain(cells.map(valueFunction))
168
+ scale.breaks = scale.quantiles()
169
+ return scale
170
+ }
171
+ }
172
+
173
+
174
+
175
+
154
176
  /**
155
177
  * Combine view scale functions
156
178
  *
@@ -1,6 +1,8 @@
1
1
  //@ts-check
2
2
  'use strict'
3
3
 
4
+ import { min, max, extent } from 'd3-array'
5
+
4
6
  /**
5
7
  * Get the class id from a value and class break values
6
8
  *
@@ -25,6 +27,71 @@ export function nice(v, multiples = [8, 6, 5, 4, 2.5, 2]) {
25
27
  return v_
26
28
  }
27
29
 
30
+ /**
31
+ * A grid cell.
32
+ * @typedef {{x: number, y: number}} Cell */
33
+
34
+ /**
35
+ * Index cells by y and x
36
+ * @param {Array.<Cell>} cells
37
+ * @param {Function} [fun]
38
+ * @returns {Object}
39
+ */
40
+ export function cellsToGrid(cells, fun) {
41
+ /** @type {Object} */
42
+ const ind = {}
43
+ for (const cell of cells) {
44
+ let row = ind[cell.y]
45
+ if (!row) {
46
+ row = {}
47
+ ind[cell.y] = row
48
+ }
49
+ row[cell.x] = fun ? fun(cell) : cell
50
+ }
51
+ return ind
52
+ }
53
+
54
+
55
+
56
+ /**
57
+ * Cells to grid.
58
+ *
59
+ * @param {Array.<Cell>} cells
60
+ * @param {number} resolution
61
+ * @param {Function} [fun]
62
+ * @returns {Object}
63
+ * Grid[i][j] is the value for line i and column j.
64
+ * Numbered from top to bottom, from left to right.
65
+ * Properties x0 and y0 are the geo coordinates of the lower left corner of the top left cell.
66
+ * Properties minI, maxI, minJ, maxJ are the extent of the grid.
67
+ */
68
+ export function cellsToMatrix(cells, resolution, fun) {
69
+
70
+ // get cells extent
71
+ const [minx, maxx] = extent(cells, c => c.x)
72
+ const [miny, maxy] = extent(cells, c => c.y)
73
+
74
+ // get grid dimension
75
+ const rows = Math.ceil((maxy - miny) / resolution) + 1
76
+ const cols = Math.ceil((maxx - minx) / resolution) + 1
77
+
78
+ // make empty grid
79
+ const grid = Array.from({ length: rows }, () => new Array(cols).fill(undefined));
80
+ grid.x0 = minx
81
+ grid.y0 = maxy
82
+ grid.resolution = resolution
83
+
84
+ for (const c of cells) {
85
+ const i = Math.floor((maxy - c.y) / resolution)
86
+ const j = Math.floor((c.x - minx) / resolution)
87
+ const v = fun ? fun(c) : c
88
+ grid[i][j] = v
89
+ }
90
+ return grid
91
+ }
92
+
93
+
94
+
28
95
  /*
29
96
  //no longer used
30
97
  export function loadImage(src) {
@@ -1,66 +0,0 @@
1
- //@ts-check
2
- 'use strict'
3
-
4
-
5
- /**
6
- * @see https://manifold.net/doc/mfd9/example__tanaka_contours.htm
7
- *
8
- * @module style
9
- * @author Julien Gaffuri
10
- */
11
- export class TanakaStyle {
12
- /**
13
- * @param {function(import('../core/Dataset.js').Cell):number} value Function that returns the value of a cell
14
- * @param {Array.<number>} breaks The break values
15
- * @param {Array.<string>} colors The colors, one more than the break values
16
- * @param {object} opts
17
- * @returns {Array.<import("../core/Style.js").Style>}
18
- */
19
- static get(value, breaks, colors, opts = {}) {
20
- //shadow colors
21
- opts.colorDark = opts.colorDark || '#111'
22
- opts.colorBright = opts.colorBright || '#ddd'
23
-
24
- /** @type { function(number, number):number } */
25
- opts.width =
26
- opts.width ||
27
- ((sideValue, resolution, z) => {
28
- const minWG = 1 * z
29
- const maxWG = 4 * z
30
- const step = (maxWG - minWG) / 3
31
- return Math.min(minWG + (sideValue - 1) * step, maxWG)
32
- })
33
-
34
- //make classifier
35
- const classifier = clFun(breaks)
36
- //make colors table
37
- const colorsDict = {}
38
- for (let i = 0; i < colors.length; i++) colorsDict[i + ''] = colors[i]
39
-
40
- const cellStyle = new SquareColorCategoryWebGLStyle({
41
- code: (cell) => classifier(value(cell)),
42
- color: colorsDict,
43
- })
44
-
45
- const getSideValue = (side) => {
46
- const cl1 = side.c1 ? classifier(value(side.c1)) : -1
47
- const cl2 = side.c2 ? classifier(value(side.c2)) : -1
48
- return cl1 - cl2
49
- }
50
-
51
- /** The side style, for the shadow effect */
52
- const sideStyle = new SideStyle({
53
- //white or black, depending on orientation and value
54
- color: (side) => {
55
- const v = getSideValue(side)
56
- if (v === 0) return
57
- if (side.or === 'v') return v < 0 ? opts.colorBright : opts.colorDark
58
- return v < 0 ? opts.colorDark : opts.colorBright
59
- },
60
- //width depends on the value, that is the number of classes of difference
61
- width: (side, resolution, z) => opts.width(Math.abs(getSideValue(side)), resolution, z),
62
- })
63
-
64
- return [cellStyle, sideStyle]
65
- }
66
- }