-
Notifications
You must be signed in to change notification settings - Fork 47
/
LinesHelper.kt
398 lines (337 loc) · 15.3 KB
/
LinesHelper.kt
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
/*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.core.plot.base.geom.util
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.commons.intern.splitBy
import org.jetbrains.letsPlot.commons.intern.typedGeometry.algorithms.AdaptiveResampler.Companion.PIXEL_PRECISION
import org.jetbrains.letsPlot.commons.intern.typedGeometry.algorithms.AdaptiveResampler.Companion.resample
import org.jetbrains.letsPlot.commons.intern.typedGeometry.algorithms.splitRings
import org.jetbrains.letsPlot.commons.values.Colors.withOpacity
import org.jetbrains.letsPlot.core.commons.geometry.PolylineSimplifier.Companion.DOUGLAS_PEUCKER_PIXEL_THRESHOLD
import org.jetbrains.letsPlot.core.commons.geometry.PolylineSimplifier.Companion.douglasPeucker
import org.jetbrains.letsPlot.core.plot.base.*
import org.jetbrains.letsPlot.core.plot.base.aes.AesScaling
import org.jetbrains.letsPlot.core.plot.base.aes.AestheticsUtil
import org.jetbrains.letsPlot.core.plot.base.geom.util.GeomUtil.createPathGroups
import org.jetbrains.letsPlot.core.plot.base.render.svg.LinePath
import org.jetbrains.letsPlot.datamodel.svg.dom.SvgNode
open class LinesHelper(
pos: PositionAdjustment,
coord: CoordinateSystem,
ctx: GeomContext
) : GeomHelper(pos, coord, ctx) {
private var myAlphaEnabled = true
private var myResamplingEnabled = false
// Polar coordinate system with discrete X scale.
fun meetsRadarPlotReq(): Boolean {
return coord.isPolar && ctx.plotContext?.getScale(Aes.X)?.isContinuous != true
}
fun setAlphaEnabled(b: Boolean) {
this.myAlphaEnabled = b
}
fun setResamplingEnabled(resample: Boolean) {
this.myResamplingEnabled = resample
}
fun createLines(
dataPoints: Iterable<DataPointAesthetics>,
toLocation: (DataPointAesthetics) -> DoubleVector?
): List<LinePath> {
// draw line for each group
val pathDataByGroup = createPathDataByGroup(dataPoints, toLocation)
return renderPaths(pathDataByGroup.values, filled = false)
}
// TODO: filled parameter is always false
fun renderPaths(paths: Map<Int, List<PathData>>, filled: Boolean): List<LinePath> {
return renderPaths(paths.values.flatten(), filled)
}
// TODO: filled parameter is always false
private fun renderPaths(paths: Collection<PathData>, filled: Boolean): List<LinePath> {
return paths.map { path ->
val visualPath = douglasPeucker(path.coordinates, DOUGLAS_PEUCKER_PIXEL_THRESHOLD)
val element = when (filled) {
true -> LinePath.polygon(visualPath)
false -> LinePath.line(visualPath)
}
decorate(element, path.aes, filled)
element
}
}
fun createPathData(
dataPoints: Iterable<DataPointAesthetics>,
locationTransform: (DataPointAesthetics) -> DoubleVector? = GeomUtil.TO_LOCATION_X_Y,
closePath: Boolean = false,
): Map<Int, List<PathData>> {
val domainData = preparePathData(dataPoints, locationTransform, closePath)
return toClient(domainData)
}
fun createPolygon(
dataPoints: Iterable<DataPointAesthetics>,
locationTransform: (DataPointAesthetics) -> DoubleVector? = GeomUtil.TO_LOCATION_X_Y,
): List<Pair<SvgNode, PolygonData>> {
val domainPathData = createPathGroups(dataPoints, locationTransform, sorted = true, closePath = true).values
// split in domain space! after resampling coordinates may repeat and splitRings will return wrong results
val domainPolygonData = domainPathData
.map { splitRings(it.points) { p1, p2 -> p1.coord == p2.coord } }
.map { PolygonData(it) }
val clientPolygonData = domainPolygonData.map { polygon ->
polygon.rings
.map { resample(it) + it.last().let { (aes, coord) -> PathPoint(aes, toClient(coord, aes)!!) } }
.let { PolygonData(it) }
}
val svg = clientPolygonData.map { polygon ->
val element = polygon.coordinates
.map { douglasPeucker(it, DOUGLAS_PEUCKER_PIXEL_THRESHOLD) }
.let(::insertPathSeparators)
.let { LinePath.polygon(it) }
decorate(element, polygon.aes, filled = true)
element.rootGroup
}
return svg.zip(clientPolygonData)
}
private fun resample(linestring: List<PathPoint>): List<PathPoint> {
return linestring.windowed(size = 2)
.map { (p1, p2) -> p1.aes to resample(p1.coord, p2.coord, PIXEL_PRECISION) { p -> toClient(p, p1.aes) } }
.flatMap { (aes, coords) -> coords.map { PathPoint(aes, it) } }
}
// TODO: return list of PathData for consistency
fun createPathDataByGroup(
dataPoints: Iterable<DataPointAesthetics>,
toLocation: (DataPointAesthetics) -> DoubleVector?
): Map<Int, PathData> {
return createPathGroups(dataPoints, toClientLocation(toLocation), sorted = true, closePath = false)
}
fun createSteps(paths: Map<Int, PathData>, horizontalThenVertical: Boolean): List<LinePath> {
val linePaths = ArrayList<LinePath>()
// draw step for each group
paths.values.forEach { subPath ->
val points = subPath.coordinates
if (points.isNotEmpty()) {
val newPoints = ArrayList<DoubleVector>()
var prev: DoubleVector? = null
for (point in points) {
if (prev != null) {
val x = if (horizontalThenVertical) point.x else prev.x
val y = if (horizontalThenVertical) prev.y else point.y
newPoints.add(DoubleVector(x, y))
}
newPoints.add(point)
prev = point
}
val line = LinePath.line(newPoints)
decorate(line, subPath.aes, filled = false)
linePaths.add(line)
}
}
return linePaths
}
// TODO: inline. N.B.: for linear geoms, be careful with the closePath parameter
fun createBands(
dataPoints: Iterable<DataPointAesthetics>,
toLocationUpper: (DataPointAesthetics) -> DoubleVector?,
toLocationLower: (DataPointAesthetics) -> DoubleVector?,
simplifyBorders: Boolean = false
): List<LinePath> {
return renderBands(dataPoints, toLocationUpper, toLocationLower, simplifyBorders, closePath = false)
}
fun renderBands(
dataPoints: Iterable<DataPointAesthetics>,
toLocationUpper: (DataPointAesthetics) -> DoubleVector?,
toLocationLower: (DataPointAesthetics) -> DoubleVector?,
simplifyBorders: Boolean,
closePath: Boolean
): List<LinePath> {
val domainUpperPathData = preparePathData(dataPoints, toLocationUpper, closePath)
val domainLowerPathData = preparePathData(dataPoints, toLocationLower, closePath)
val domainBandsPathData = domainUpperPathData.mapValues { (group, upperPathData) ->
val lowerPathData = domainLowerPathData[group] ?: return@mapValues emptyList<PathData>()
if (upperPathData.isEmpty() || lowerPathData.isEmpty()) {
return@mapValues emptyList<PathData>()
}
require(upperPathData.size == lowerPathData.size) {
"Upper and lower path data should contain the same number of paths"
}
upperPathData
.zip(lowerPathData)
.map { (upperPath, lowerPath) -> PathData(upperPath.points + lowerPath.points.reversed()) }
}
val clientBandsPathData = toClient(domainBandsPathData)
return clientBandsPathData.values.flatten().mapNotNull { pathData ->
val points = pathData.coordinates
if (points.isNotEmpty()) {
val path = LinePath.polygon(
when {
simplifyBorders -> douglasPeucker(points, DOUGLAS_PEUCKER_PIXEL_THRESHOLD)
else -> points
}
)
decorateFillingPart(path, pathData.aes)
path
} else {
null
}
}
}
fun decorate(
path: LinePath,
p: DataPointAesthetics,
filled: Boolean,
strokeScaler: (DataPointAesthetics) -> Double = AesScaling::strokeWidth
) {
val stroke = p.color()
val strokeAlpha = AestheticsUtil.alpha(stroke!!, p)
path.color().set(withOpacity(stroke, strokeAlpha))
if (!AestheticsUtil.ALPHA_CONTROLS_BOTH && (filled || !myAlphaEnabled)) {
path.color().set(stroke)
}
if (filled) {
decorateFillingPart(path, p)
}
val size = strokeScaler(p)
path.width().set(size)
val lineType = p.lineType()
if (!(lineType.isBlank || lineType.isSolid)) {
path.dashArray().set(lineType.dashArray)
}
}
private fun decorateFillingPart(path: LinePath, p: DataPointAesthetics) {
val fill = p.fill()
val fillAlpha = AestheticsUtil.alpha(fill!!, p)
path.fill().set(withOpacity(fill, fillAlpha))
}
private fun preparePathData(
dataPoints: Iterable<DataPointAesthetics>,
locationTransform: (DataPointAesthetics) -> DoubleVector?,
closePath: Boolean
): Map<Int, List<PathData>> {
val domainPathData = createPathGroups(dataPoints, locationTransform, sorted = true, closePath = closePath)
return domainPathData.mapValues { (_, pathData) -> listOf(pathData) }
}
private fun toClient(domainPathData: Map<Int, List<PathData>>): Map<Int, List<PathData>> {
return when (myResamplingEnabled) {
true -> {
domainPathData
.mapValues { (_, groupPath) -> groupPath.flatMap(::splitByStyle) }
.let { interpolatePathData(it) }
.mapValues { (_, paths) -> paths.map { PathData(resample(it.points)) } }
}
false -> {
val clientPathData = domainPathData.mapValues { (_, groupPath) ->
groupPath.map { segment ->
// Note that PathPoint have to be recreated with the point aes, not with a segment aes
val points = segment.points.mapNotNull { p ->
toClient(p.coord, p.aes)
?.let { PathPoint(p.aes, coord = it) }
}
PathData(points)
}
}
val clientVariadicPathData =
clientPathData.mapValues { (_, pathData) -> pathData.flatMap(::splitByStyle) }
interpolatePathData(clientVariadicPathData)
}
}
}
companion object {
private fun insertPathSeparators(rings: Iterable<List<DoubleVector>>): List<DoubleVector?> {
val result = ArrayList<DoubleVector?>()
for (ring in rings) {
if (!result.isEmpty()) {
result.add(LinePath.END_OF_SUBPATH) // this is polygon's path separator understood by PathLine component
}
result.addAll(ring)
}
return result
}
fun splitByStyle(pathData: PathData): List<PathData> {
return pathData.points
.splitBy(
compareBy(
{ it.aes.size() },
{ it.aes.color()?.red },
{ it.aes.color()?.green },
{ it.aes.color()?.blue },
{ it.aes.color()?.alpha }
)
)
.map(::PathData)
}
private fun midPointsPathInterpolator(path: List<PathData>): List<PathData> {
if (path.size == 1) {
return path
}
val jointPoints = path
.windowed(size = 2, step = 1)
.map { (prevSubPath, nextSubPath) ->
val prevSubPathEnd = prevSubPath.coordinates.last()
val nextSubPathStart = nextSubPath.coordinates.first()
val midPoint = lerp(prevSubPathEnd, nextSubPathStart, 0.5)
midPoint
}
return path.mapIndexed { i, subPath ->
when (i) {
0 -> {
val rightJointPoint = subPath.points.last().copy(coord = jointPoints[i])
PathData(subPath.points + rightJointPoint)
}
path.lastIndex -> {
val leftJointPoint = subPath.points.first().copy(coord = jointPoints[i - 1])
PathData(listOf(leftJointPoint) + subPath.points)
}
else -> {
val leftJointPoint = subPath.points.first().copy(coord = jointPoints[i - 1])
val rightJointPoint = subPath.points.last().copy(coord = jointPoints[i])
PathData(listOf(leftJointPoint) + subPath.points + rightJointPoint)
}
}
}
}
private fun lerp(p1: DoubleVector, p2: DoubleVector, progress: Double): DoubleVector {
return p1.add(p2.subtract(p1).mul(progress))
}
fun interpolatePathData(variadicPath: Map<Int, List<PathData>>): Map<Int, List<PathData>> {
return variadicPath.mapValues { (_, pathSegments) -> midPointsPathInterpolator(pathSegments) }
}
}
}
data class PathData(
val points: List<PathPoint>
) {
init {
require(points.isNotEmpty()) { "PathData should contain at least one point" }
}
val aes: DataPointAesthetics by lazy(points.first()::aes) // decoration aes (only for color, fill, size, stroke)
val aesthetics by lazy { points.map(PathPoint::aes) }
val coordinates by lazy { points.map(PathPoint::coord) } // may contain duplicates, don't work well for polygon
}
data class PolygonData(
val rings: List<List<PathPoint>>
) {
init {
require(rings.isNotEmpty()) { "PolygonData should contain at least one ring" }
require(rings.all { it.size >= 3 }) { "PolygonData ring should contain at least 3 points" }
}
val aes: DataPointAesthetics by lazy( rings.first().first()::aes ) // decoration aes (only for color, fill, size, stroke)
val aesthetics by lazy { rings.map { ring -> ring.map { it.aes } } }
val coordinates by lazy { rings.map { ring -> ring.map { it.coord } } }
val flattenCoordinates by lazy { // guaranteed to have no duplicates on ends caused by resampling
val output = mutableListOf<DoubleVector>()
rings.forEach { ring ->
val firstPoint = ring.first().coord
val lastPoint = ring.last().coord
// trim duplications at start and end to make the ring detection work
output.add(firstPoint)
output.addAll(ring.asSequence().dropWhile { it.coord == firstPoint }.map { it.coord })
while (output.last() == lastPoint) {
output.removeLast()
}
output.add(lastPoint)
}
output
}
}
data class PathPoint(
val aes: DataPointAesthetics,
val coord: DoubleVector
)