github.com/richardwilkes/toolbox@v1.121.0/xmath/geom/poly/scan_beam_tree.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package poly 11 12 import "golang.org/x/exp/constraints" 13 14 type scanBeamTree[T constraints.Float] struct { 15 root *scanBeamNode[T] 16 entries int 17 } 18 19 type scanBeamNode[T constraints.Float] struct { 20 y T 21 less *scanBeamNode[T] 22 more *scanBeamNode[T] 23 } 24 25 func (s *scanBeamTree[T]) add(y T) { 26 s.addToScanBeamTreeAt(&s.root, y) 27 } 28 29 func (s *scanBeamTree[T]) addToScanBeamTreeAt(node **scanBeamNode[T], y T) { 30 switch { 31 case *node == nil: 32 *node = &scanBeamNode[T]{y: y} 33 s.entries++ 34 case (*node).y > y: 35 s.addToScanBeamTreeAt(&(*node).less, y) 36 case (*node).y < y: 37 s.addToScanBeamTreeAt(&(*node).more, y) 38 default: 39 } 40 } 41 42 func (s *scanBeamTree[T]) buildScanBeamTable() []T { 43 table := make([]T, s.entries) 44 if s.root != nil { 45 s.root.buildScanBeamTableEntries(0, table) 46 } 47 return table 48 } 49 50 func (sbt *scanBeamNode[T]) buildScanBeamTableEntries(index int, table []T) int { 51 if sbt.less != nil { 52 index = sbt.less.buildScanBeamTableEntries(index, table) 53 } 54 table[index] = sbt.y 55 index++ 56 if sbt.more != nil { 57 index = sbt.more.buildScanBeamTableEntries(index, table) 58 } 59 return index 60 }