/
qhull.coffee
796 lines (603 loc) · 19 KB
/
qhull.coffee
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
#### three.js boilerplate
#
# Just some generic setup to get a 3d fullscreen display
#
SHOW_STATS = false
if !Detector.webgl
Detector.addWebGLMessage()
init = ->
bgColor = 0xeeeeee
container = document.getElementById 'container'
camera = camera = new THREE.PerspectiveCamera(
27, window.innerWidth / window.innerHeight, 5, 5500
)
camera.position.z = 3750
scene = new THREE.Scene
scene.fog = new THREE.Fog bgColor, 3000, 5000
renderer = new THREE.WebGLRenderer antialias: true
renderer.setClearColor bgColor, 1
renderer.setSize window.innerWidth, window.innerHeight
container.appendChild renderer.domElement
if SHOW_STATS
stats = new Stats
stats.domElement.style.position = 'absolute'
stats.domElement.style.top = '0px'
stats.domElement.style.right = '0px'
container.appendChild stats.domElement
onWindowResize = ->
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize window.innerWidth, window.innerHeight
window.addEventListener 'resize', onWindowResize, false
sceneRoot = new THREE.Object3D
scene.add sceneRoot
controls = new THREE.OrbitControls camera
controls.noKeys = true
controls.noZoom = true
controls.noPan = true
window.sceneRoot = sceneRoot
window.renderer = renderer
window.camera = camera
window.controls = controls
window.scene = scene
window.stats = stats
init()
animate = ->
requestAnimationFrame animate
render()
window.stats?.update()
render = ->
window.renderer.render window.scene, window.camera
window.controls.addEventListener 'change', render
#### The Tracer
#
# A tracer option simply captures a list of scenes, consisting of faces, edges
# and points and provides methods for displaying these scenes by updating the
# ThreeJS scene graph and some DOM elements. Could be written much shorter.
# compensate for dynamic typing ;-)
isVector = (a) -> a instanceof THREE.Vector3
isFace = (t) -> t instanceof Face
class Tracer
COLOR_EDGE_START = new THREE.Color 0xff0000
COLOR_EDGE_END = new THREE.Color 0x0000ff
MATERIAL_PARTICLE_DEFAULT = new THREE.ParticleBasicMaterial {
color: 0x0000ff
size: 40
}
MATERIAL_PARTICLE_RED = new THREE.ParticleBasicMaterial {
color: 0xff0000
size: 80
}
MATERIAL_ARROW = new THREE.MeshBasicMaterial {
color: 0xff0000
}
MATERIAL_FACE_OUTER = new THREE.MeshBasicMaterial {
color: 0xffff00
transparent: true
opacity: .5
}
MATERIAL_FACE_INNER = new THREE.MeshBasicMaterial {
color: 0xff0088
transparent: true
opacity: .5
side: THREE.BackSide
}
MATERIAL_FACE_HIGHLIGHT = new THREE.MeshBasicMaterial {
color: 0xffff00
transparent: true
opacity: .75
}
MATERIAL_FACE_WIRE = new THREE.MeshBasicMaterial {
color: 0x888888
transparent: true
opacity: .5
wireframe: true
depthTest: false
}
MATERIAL_LINE = new THREE.LineBasicMaterial {
linewidth: 4,
vertexColors: THREE.VertexColors
}
constructor: ->
@scenes = []
@index = 0
@$subtitle = $('#subtitle')
@$el = $('#trace')
@$el.empty()
@$el.css
position: 'absolute'
bottom: '1em'
top: '0em'
left: '1em'
overflow: 'hidden'
# convert Quickhull vertices to ThreeJS vertices
getVertices: (vertices, options = {}) ->
if not _.all(vertices, isVector)
console.error "invalid vertex"
return
m = options.material or MATERIAL_PARTICLE_DEFAULT
g = new THREE.Geometry
g.vertices.push vertices...
new THREE.ParticleSystem g, m
# convert Quickhull edges to ThreeJS edges, color them as a gradient
# to detect discontinuities
getEdges: (edges, options = {}) ->
if not _.all(edges, ({a, b}) -> isVector(a) and isVector(b))
console.error "invalid edge"
return
obj = new THREE.Object3D
edges.forEach ({a, b}, i) ->
g = new THREE.Geometry
cA = COLOR_EDGE_START.clone().lerp(COLOR_EDGE_END, i / edges.length)
cB = COLOR_EDGE_START.clone().lerp(COLOR_EDGE_END, (i + 1) / edges.length)
g.vertices.push a, b
g.colors.push cA, cB
obj.add new THREE.Line g, MATERIAL_LINE
obj
# convert Quickhull faces to ThreeJS faces, color front and back diffrently
# to detect holes and faces with wrong orientation
getFaces: (faces, options = {}) ->
if not _.all(faces, isFace)
console.error "invalid face"
return
matOuter = options.materialOuter or MATERIAL_FACE_OUTER
matInner = options.materialInner or MATERIAL_FACE_INNER
matWire = options.materialWire or MATERIAL_FACE_WIRE
g = new THREE.Geometry
_.filter(faces, (f) -> not f.deleted).forEach (f) ->
if f.deleted then throw new Error "deleted face!"
n = g.vertices.length
g.vertices.push f.a, f.b, f.c
g.faces.push new THREE.Face3 n, n+1, n+2
obj = new THREE.Object3D
obj.add new THREE.Mesh g, matOuter
obj.add new THREE.Mesh g, matInner
obj.add new THREE.Mesh g, matWire
obj
# create a new scene object
trace: (message, options) ->
obj = new THREE.Object3D
{vertices, edges, faces,
hiVertices, hiEdges, hiFaces,
subtitle} = options
if vertices
obj.add @getVertices _.difference vertices, (hiVertices or [])
if edges
obj.add @getEdges _.difference edges, (hiEdges or [])
if faces
obj.add @getFaces _.difference faces, (hiFaces or [])
if hiVertices
obj.add @getVertices hiVertices, material: MATERIAL_PARTICLE_RED
if hiFaces
obj.add @getFaces hiFaces, materialOuter: MATERIAL_FACE_HIGHLIGHT
$el = $("<div>").append($("<span>").text "#{@scenes.length}. #{message}")
$el.css color: '#888'
@$el.append $el
@scenes.push {message, obj, $el, subtitle}
if @scenes.length == 2
@index = 0
@showScene()
showNext: ->
if @index < @scenes.length - 1
@index += 1
@showScene()
showPrev: ->
if @index > 0
@index -= 1
@showScene()
showFirst: ->
@index = 0
@showScene()
showLast: ->
@index = @scenes.length - 1
@showScene()
hideScene: ->
if @s
window.sceneRoot.remove @s.obj
@s.$el.css color: '#888'
@s.$el.find(".subtitle").hide()
showScene: ->
@hideScene()
@s = @scenes[@index]
if @s
window.sceneRoot.add @s.obj
@s.$el.css color: '#444'
@$subtitle.html @s.subtitle or ""
@scenes[Math.max @index - 10, 0].$el.get(0).scrollIntoView()
clear: ->
@hideScene()
## Quickhull
#### Tracer settings
config =
TRACE_INITIAL: true
TRACE_HORIZON: true
TRACE_MANY_HORIZON_PATHS: false
TRACE_HORIZON_STEP: false
TRACE_TERMINATE: false
TRACE_NEW_FACE_EACH: false
TRACE_NEW_FACES: true
#### Face Edge
#
# Represents an edge between two points of a hull face.
# Keeps track of the face as well as the face on the opposite side, which is
# needed when stitching up faces.
class FaceLink
constructor: (face, @a, @b) ->
@from = face
@to = null
reverseOf: ({a, b}) ->
(@a == b) and (@b == a)
#### Face
#
# Represents a hull face.
#
class Face
constructor: (@a, @b, @c) ->
@triangle = new THREE.Triangle a, b, c
@plane = @triangle.plane()
@links = [
@linkAB = new FaceLink @, @a, @b
@linkBC = new FaceLink @, @b, @c
@linkCA = new FaceLink @, @c, @a
]
@assignedPoints = []
@furthest = {point: null, distance: -Infinity}
@deleted = false
@visited = false
hasPoint: (point) ->
(point == @a) or (point == @b) or (point == @c)
distance: (point) ->
if @hasPoint point
0
else
@plane.distanceToPoint point
# normalLine: only needed for visualization
normalLine: ->
m = @triangle.midpoint()
n = @triangle.midpoint().add(
@triangle.normal().normalize().multiplyScalar(50))
{a: m, b: n}
visibleBy: (point) ->
@hasPoint(point) or (@distance(point) > 0)
connect: (otherFace, link, otherLink) ->
if not link.reverseOf otherLink
throw new Error "can't connect with non-reverse link"
link.to = otherFace
otherLink.to = @
link.inverse = otherLink
otherLink.inverse = link
assign: (point) ->
if @hasPoint point
true
else
d = @distance point
if d >= 0
@assignedPoints.push point
if d > @furthest.distance
@furthest.distance = d
@furthest.point = point
true
else
false
assignPoints = (faces, points) ->
points.forEach (p) ->
_.any faces, (f) -> f.assign p
checkFace = (f) ->
error = false
setError = (msg) ->
console.log msg
error = true
if f.deleted
return
f.links.forEach (l, j) ->
str = "f.links[#{j}]"
if l.horizon == true
setError "#{str}.horizon == true"
if l.from != f
setError "#{str}.from != f"
if l.inverse.to != f
setError "#{str}.inverse.to != f"
if l.inverse.a != l.b
setError "#{str}.inverse.a != l.b"
if l.inverse.b != l.a
setError "#{str}.inverse.b != l.a"
backLinks = _.pluck l.to.links, 'to'
if not _.contains backLinks, f
setError "no reflexive link", f, backLinks
if error then throw new Error "checkFace failed"
checkHorizon = (horizon) ->
_.every _.map horizon, (h, i) ->
next = horizon[(i + 1) % horizon.length]
if h.b != next.a
console.error "discontinuous horizon", h, next
false
else
true
checkHull = (tracer, hull, points) ->
valid = true
_.each hull, (f) ->
_.each points, (p) ->
if visible face, point
valid = false
tracer.trace "OUTSIDE POINT",
faces: [face]
vertices: [point]
valid
## The actual Quickhull solver
class QuickhullSolver
constructor: (@tracer) ->
@hull = []
# find some sane initial points
getInitialPoints: (points) ->
getattr = (a) -> (p) -> p[a]
pointsCopy = _.clone points
# find extreme points in each dimension
extremes = []
removeFromPoints = (point) ->
pointsCopy = _.without pointsCopy, point
point
extremes.push removeFromPoints(_.min pointsCopy, getattr 'x')
extremes.push removeFromPoints(_.min pointsCopy, getattr 'y')
extremes.push removeFromPoints(_.min pointsCopy, getattr 'z')
extremes.push removeFromPoints(_.max pointsCopy, getattr 'x')
extremes.push removeFromPoints(_.max pointsCopy, getattr 'y')
extremes.push removeFromPoints(_.max pointsCopy, getattr 'z')
cartesian = _.flatten(
(_.map extremes, (p1) -> _.map extremes, (p2) -> [p1, p2]), true
)
# find point combination with greatest distance
[m1, m2] = _.max cartesian, ([p1, p2]) ->
p1.distanceTo p2
# find point with greatest distance to those two points
m3 = _.max extremes, (p3) ->
q = p3.clone().sub(m1)
q.cross(m2).length()
[m1, m2, m3]
#### get convex hull of faces
getHull: (points) ->
@tracer.trace "quickhull start",
vertices: points
subtitle: $('#instructions').html()
[a, b, c] = @getInitialPoints points
f = new Face a, b, c
g = new Face a, c, b
# assign points to initial hull hull
assignPoints [f, g], points
# connect initial faces to each other
f.connect g, f.linkAB, g.linkCA
f.connect g, f.linkBC, g.linkBC
f.connect g, f.linkCA, g.linkAB
# basic hull
@hull = [f, g]
if config.TRACE_INITIAL
@tracer.trace "initial hull with normals",
faces: @hull
edges: _.map @hull, (f) -> f.normalLine()
vertices: points
hiVertices: [a, b, c]
#@ sanity check
@hull.forEach checkFace
# recursive algorithm implemented with own stack
stack = [g, f]
while face = stack.shift()
# skip faces that have been discarded
if not face.deleted
# try to expand the hull if face hasn't been deleted, add
# newly created faces to work queue
newFaces = @expandHull face
stack.push newFaces...
if checkHull @hull, points
console.log "checkHull successful"
@hull
#### expand hull by creating new faces and removing old ones
expandHull: (face) ->
# if the face has no points assigned, leave everything unchanged
if _.isEmpty face.assignedPoints
return
d = face.furthest.point
# find horizon and list of visited faces
{horizon, visited} = @getHorizon face, d
if not checkHorizon horizon
throw new Error "invalid horizon"
if config.TRACE_HORIZON
@tracer.trace "expand hull",
faces: visited
edges: horizon
vertices: face.assignedPoints
hiVertices: [d]
subtitle: "#{visited.length} faces visible from furthest point"
# Create new hull and reconnect faces properly. Because the horizon is
# continuous, all faces will have proper orientation.
newFaces = []
prev = null
horizon.forEach (link) =>
link.horizon = false # reset
{a, b} = link
f = new Face a, b, d
f.connect link.to, f.linkAB, link.inverse
if prev
prev.connect f, prev.linkBC, f.linkCA
prev = f
newFaces.push f
prev.connect newFaces[0], prev.linkBC, newFaces[0].linkCA
# re-assign points to newly created faces and delete visited faces
visited.forEach (f) ->
assignPoints newFaces, f.assignedPoints
f.assignedPoints = []
f.deleted = true
if config.TRACE_NEW_FACE_EACH
newFaces.forEach (f) ->
@tracer.trace "new face",
faces: [f]
vertices: f.assignedPoints
edges: [f.linkAB]
hiVertices: [d]
subtitle: """
new face from found horizon edge to furthest point,
#{f.assignedPoints.length} assigned points"""
if config.TRACE_NEW_FACES
@tracer.trace "new faces",
vertices: [d]
edges: horizon
faces: newFaces
subtitle: "#{newFaces.length} new faces along the found horizon"
# add new faces to hull
@hull.push newFaces...
totalFaces = _.filter(@hull, (h) -> not h.deleted)
@tracer.trace "new hull",
faces: @hull
hiFaces: newFaces
vertices: points
subtitle: "#{totalFaces.length} total hull faces"
@hull.forEach checkFace
newFaces
#### Find boundary between visible and invisible faces
# return as continuous list of FaceLinks creating a closed path
getHorizon: (face, point) ->
stack = [face]
visited = []
horizon = []
# Because FaceLinks are not necessarily found in a continuous order,
# maintain a list of paths and add newly found link to the start or end of
# an existing path or create a new one.
#
# There probably is a better way to do this.
mergePaths = (path, links) ->
if path.length == 0
path.push links...
return true
pathStart = _.first(path).a
pathEnd = _.last(path).b
linkStart = _.first(links).a
linkEnd = _.last(links).b
if linkStart == pathEnd
path.push links...
else if linkEnd == pathStart
path.unshift links...
else
return false
return true
horizonPaths = []
# if new link can't be merged with existing path, add new path
addHorizon = (link) =>
if not _.some(horizonPaths, (path) -> mergePaths path, [link])
horizonPaths.push [link]
if config.TRACE_HORIZON_STEP
@tracer.trace "found horizon edge",
faces: [link.from, link.to]
edges: [link]
vertices: [point]
subtitle: 'boundary between visible and invisible face'
# very rarely there are more than 2 paths to check
if config.TRACE_MANY_HORIZON_PATHS
if horizonPaths.length > 2
horizonPaths.forEach (links, i) ->
@tracer.trace "horizon path #{i}",
faces: _.map links, (l) -> l.from
edges: links
# graph search starting form passed face
while f = stack.pop()
f.visited = true
visited.push f
f.links.forEach (l, i) =>
l.horizon = not l.to.visibleBy(point)
if l.horizon
# if the face on the other side of the link is invisible, we have a
# horizon link
addHorizon l
else
# otherwise we might have a new face to expand the search to
if not l.to.visited
stack.push l.to
l.to.visited = true
# reset search state
visited.forEach (f) -> f.visited = false
# collapse horizon into single path
# strictly speaking this is not guaranteed to terminate but it does
horizon = []
while p = horizonPaths.pop()
mergePaths horizon, p
# return horizon and list of visited faces
{horizon, visited}
# end of core quickhull algorithm
## Put everything together
#### create random points
makePoints = (random, n) ->
s = 200.0
points = []
for [0..n]
vector = new THREE.Vector3(
random.gauss(), random.gauss(), random.gauss()
) until vector?.length() < 3
points.push vector.multiplyScalar(s)
points
#### handy method to debug certain cases
seed = null
#@ seed = 726
if seed == null
seed = (Math.random() * 10000).toFixed 0
console.log "seed", seed
random = new Random
random.seed seed
window.points = makePoints random, 1000
animate()
reset = (seed) ->
if seed then random.seed seed
window.points = makePoints random, 100
if window.tracer
window.tracer.clear()
window.tracer = new Tracer
window.solver = new QuickhullSolver window.tracer
window.solver.getHull window.points
#### Settings widget
$settings = $("#settings")
addSetting = (description, key) ->
changeKey = (key, value) ->
config[key] = value
reset seed
$checkbox = $("<input>", type: "checkbox")
.on('change', (e) -> changeKey key, $checkbox.prop 'checked')
$checkbox.prop 'checked', config[key]
$el = $("<div>").append $("<label>").text(description).append($checkbox)
$settings.append $el
addSetting 'show initial points', "TRACE_INITIAL"
addSetting 'show new horizon', "TRACE_HORIZON"
addSetting 'show horizon search step', "TRACE_HORIZON_STEP"
addSetting 'show new individual faces', "TRACE_NEW_FACE_EACH"
addSetting 'show new face group', "TRACE_NEW_FACES"
#### respond to user input
lastKey = null
onKeyDown = (e) ->
#@ console.log e.keyCode
KEY_LEFT = 37
KEY_RIGHT = 39
KEY_J = "J".charCodeAt 0
KEY_K = "K".charCodeAt 0
KEY_R = "R".charCodeAt 0
KEY_G = "G".charCodeAt 0
KEY_END = 35
KEY_START = 36
KEYS_PREV = [KEY_LEFT, KEY_K]
KEYS_NEXT = [KEY_RIGHT, KEY_J]
KEYS_END = [KEY_END]
KEYS_START = [KEY_START]
KEYS_RESET = [KEY_R]
if _.contains(KEYS_PREV, e.keyCode) then tracer.showPrev()
if _.contains(KEYS_NEXT, e.keyCode) then tracer.showNext()
if _.contains(KEYS_START, e.keyCode) then tracer.showFirst()
if _.contains(KEYS_END, e.keyCode) then tracer.showLast()
if _.contains(KEYS_RESET, e.keyCode) then reset()
if (e.keyCode == KEY_G)
if e.shiftKey
tracer.showLast()
else
tracer.showFirst()
lastKey = e
onMouseWheel = (e) ->
#@ console.log e
if e.originalEvent.wheelDeltaY < 0 then tracer.showNext()
if e.originalEvent.wheelDeltaY > 0 then tracer.showPrev()
$(window).on 'keydown', onKeyDown
$(window).on 'mousewheel', onMouseWheel
#### get it started
reset()