-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
285 lines (279 loc) · 8.92 KB
/
index.ts
File metadata and controls
285 lines (279 loc) · 8.92 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
import { encodePNG } from '@img/png'
import type * as Types from '@app/Types.ts'
import Chart from '@app/Chart.ts'
import Renderer from '@app/Renderer.ts'
/**
* Renders chart to PNG file.
* @description Layout, GPU draw, PNG output.
* @param options - Chart configuration options
* @throws {Error} When canvas dimensions or series data are invalid
*/
export default async function (options: Types.ShadePlotOptions): Promise<void> {
const { canvas, series, layout = {}, output } = options
const { width, height, style } = canvas
const { showLegend = false, title, legendPosition = 'top-left' } = layout
if (width <= 0 || height <= 0) {
throw new Error(`canvas width and height must be greater than 0`)
}
if (series.length === 0) {
throw new Error(`series must not be empty`)
}
for (const seriesItem of series) {
if (seriesItem.data.length === 0) {
throw new Error(`series "${seriesItem.label}" data must not be empty`)
}
}
const isDark = style === 'dark'
const bgColor = isDark ? { r: 0.07, g: 0.07, b: 0.1, a: 1 } : { r: 0.97, g: 0.97, b: 0.97, a: 1 }
const axisColor = isDark ? '#4a4a5a' : '#b0b0b8'
const gridColor = isDark ? '#1e1e2a' : '#e0e0e8'
const labelColor = isDark ? '#9090a0' : '#505060'
const titleColor = isDark ? '#d0d0e0' : '#1a1a2e'
const gpuContext = await Renderer.createGpuContext(width, height)
const { device, texture } = gpuContext
const textureView = texture.createView()
const dataRange = Chart.computeDataRange(series)
const yTicks = Chart.buildTickValues(dataRange.minY, dataRange.maxY)
const xTicks = Chart.buildTickValues(
dataRange.minX,
dataRange.maxX,
[dataRange.dataMinX, dataRange.dataMaxX],
8
)
const maxYDigits = Math.max(
...yTicks.map((value) => String(Math.abs(Math.round(value))).length + (value < 0 ? 1 : 0))
)
const plotArea = Chart.computePlotArea(
width,
height,
showLegend,
legendPosition,
maxYDigits,
!!title
)
const lineUniforms = Chart.buildLineUniforms(width, height, plotArea, dataRange)
const encoder = device.createCommandEncoder()
Renderer.drawBackground(encoder, textureView, bgColor, 'clear')
const gridSegments = Chart.buildGridSegments(xTicks, yTicks, plotArea, dataRange)
Renderer.drawAxisLines(device, encoder, textureView, gridSegments, width, height, gridColor)
for (const seriesItem of series) {
const dataPoints = seriesItem.data
const lineWidth = seriesItem.line?.width ?? 2
const dashStyle = seriesItem.line?.dash ?? 'solid'
if (dashStyle === 'solid') {
Renderer.drawLines(
device,
encoder,
textureView,
dataPoints,
lineUniforms,
seriesItem.color,
lineWidth
)
} else {
const dashPixels = dashStyle === 'dash' ? 20 : 6
const gapPixels = dashStyle === 'dash' ? 10 : 6
const pixelPoints = dataPoints.map((point) => dataToPixel(point, plotArea, dataRange))
const dashedSegments = buildDashedSegments(pixelPoints, dashPixels, gapPixels)
for (const segment of dashedSegments) {
const dataSegment = segment.map((point) => pixelToData(point, plotArea, dataRange))
Renderer.drawLines(
device,
encoder,
textureView,
dataSegment,
lineUniforms,
seriesItem.color,
lineWidth
)
}
}
if (seriesItem.marker?.show) {
const markerSize = seriesItem.marker.size ?? 4
Renderer.drawMarkers(
device,
encoder,
textureView,
dataPoints,
lineUniforms,
seriesItem.color,
markerSize
)
}
}
const axisSegments = Chart.buildAxisSegments(plotArea)
Renderer.drawAxisLines(device, encoder, textureView, axisSegments, width, height, axisColor)
const tickSegments = Chart.buildTickSegments(xTicks, yTicks, plotArea, dataRange, height)
Renderer.drawAxisLines(device, encoder, textureView, tickSegments, width, height, axisColor)
const labelGlyphs = Chart.buildLabelGlyphs(
xTicks,
yTicks,
plotArea,
dataRange,
height,
maxYDigits
)
Renderer.drawDigits(device, encoder, textureView, labelGlyphs, width, height, labelColor)
if (title) {
const titleItem = Chart.buildTitleTextGlyphs(title, width, height, plotArea, titleColor)
Renderer.drawText(
device,
encoder,
textureView,
titleItem.glyphs,
width,
height,
titleItem.color
)
}
if (showLegend) {
const swatchItems = Chart.buildLegendSwatchSegments(series, width, height, plotArea)
for (const swatchItem of swatchItems) {
Renderer.drawAxisLines(
device,
encoder,
textureView,
swatchItem.segments,
width,
height,
swatchItem.color
)
}
const legendItems = Chart.buildLegendTextGlyphs(series, width, height, plotArea)
for (const legendItem of legendItems) {
Renderer.drawText(
device,
encoder,
textureView,
legendItem.glyphs,
width,
height,
legendItem.color
)
}
}
device.queue.submit([encoder.finish()])
const pixels = await Renderer.readPixels(gpuContext)
const pixelsBuffer = new ArrayBuffer(pixels.byteLength)
new Uint8Array(pixelsBuffer).set(pixels)
const png = await encodePNG(new Uint8ClampedArray(pixelsBuffer), {
width,
height,
compression: 0,
filter: 0,
interlace: 0
})
await Deno.writeFile(output, png)
}
/**
* Splits polyline into dash segments.
* @description Dash and gap sub-segments from points.
* @param points - Input polyline data points
* @param dashLength - Length of each dash in pixels
* @param gapLength - Length of each gap in pixels
* @returns Array of sub-segment point arrays
*/
function buildDashedSegments(
points: Array<{ x: number; y: number }>,
dashLength: number,
gapLength: number
): Array<Array<{ x: number; y: number }>> {
type Point = { x: number; y: number }
const result: Array<Array<Point>> = []
if (points.length < 2) {
return result
}
let isDrawing = true
let remainingLength = dashLength
let currentSegment: Array<Point> = [points[0] as Point]
for (let i = 0; i < points.length - 1; i++) {
const pointA = points[i] as Point
const pointB = points[i + 1] as Point
const deltaX = pointB.x - pointA.x
const deltaY = pointB.y - pointA.y
const segmentLength = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
if (segmentLength < 0.0001) {
continue
}
let walkedLength = 0
while (walkedLength < segmentLength - 0.0001) {
const stepSize = Math.min(remainingLength, segmentLength - walkedLength)
walkedLength += stepSize
remainingLength -= stepSize
const interpolationT = walkedLength / segmentLength
const interpolated: Point = {
x: pointA.x + interpolationT * deltaX,
y: pointA.y + interpolationT * deltaY
}
if (remainingLength <= 0.0001) {
if (isDrawing) {
currentSegment.push(interpolated)
if (currentSegment.length >= 2) {
result.push(currentSegment)
}
currentSegment = []
}
isDrawing = !isDrawing
remainingLength = isDrawing ? dashLength : gapLength
if (isDrawing) {
currentSegment.push(interpolated)
}
} else if (isDrawing) {
if (currentSegment.length === 0) {
currentSegment.push(interpolated)
}
}
}
if (isDrawing && walkedLength >= segmentLength - 0.0001) {
if (currentSegment.length === 0) {
currentSegment.push(pointB)
} else {
currentSegment.push(pointB)
}
}
}
if (isDrawing && currentSegment.length >= 2) {
result.push(currentSegment)
}
return result
}
/**
* Converts data point to pixel coords.
* @description Data space to pixel coordinates.
* @param point - Data point to convert
* @param plot - Computed plot area bounds
* @param range - Data range with axis limits
* @returns Pixel coordinate
*/
function dataToPixel(
point: { x: number; y: number },
plot: Types.PlotArea,
range: Types.DataRange
): { x: number; y: number } {
const normalizedX = (point.x - range.minX) / (range.maxX - range.minX)
const normalizedY = (point.y - range.minY) / (range.maxY - range.minY)
return {
x: plot.left + normalizedX * plot.width,
y: plot.top + (1 - normalizedY) * plot.height
}
}
/**
* Converts pixel to data coordinates.
* @description Pixel space to data coordinates.
* @param point - Pixel point to convert
* @param plot - Computed plot area bounds
* @param range - Data range with axis limits
* @returns Data coordinate
*/
function pixelToData(
point: { x: number; y: number },
plot: Types.PlotArea,
range: Types.DataRange
): { x: number; y: number } {
const normalizedX = (point.x - plot.left) / plot.width
const normalizedY = 1 - (point.y - plot.top) / plot.height
return {
x: range.minX + normalizedX * (range.maxX - range.minX),
y: range.minY + normalizedY * (range.maxY - range.minY)
}
}