-
Notifications
You must be signed in to change notification settings - Fork 145
/
fill.rs
3004 lines (2618 loc) · 98 KB
/
fill.rs
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::event_queue::*;
use crate::geom::LineSegment;
use crate::math::*;
use crate::monotone::*;
use crate::path::polygon::Polygon;
use crate::path::traits::{Build, PathBuilder};
use crate::path::{
builder::NoAttributes, AttributeStore, Attributes, EndpointId, FillRule, IdEvent, PathEvent,
PathSlice, PositionStore, Winding, NO_ATTRIBUTES,
};
use crate::{FillGeometryBuilder, Orientation, VertexId};
use crate::{
FillOptions, InternalError, SimpleAttributeStore, TessellationError, TessellationResult,
UnsupportedParamater, VertexSource,
};
use float_next_after::NextAfter;
use std::cmp::Ordering;
use std::f32::consts::FRAC_1_SQRT_2;
use std::mem;
use std::ops::Range;
#[cfg(debug_assertions)]
use std::env;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum Side {
Left,
Right,
}
impl Side {
pub fn opposite(self) -> Self {
match self {
Side::Left => Side::Right,
Side::Right => Side::Left,
}
}
pub fn is_left(self) -> bool {
self == Side::Left
}
pub fn is_right(self) -> bool {
self == Side::Right
}
}
type SpanIdx = i32;
type ActiveEdgeIdx = usize;
// It's a bit odd but this consistently performs a bit better than f32::max, probably
// because the latter deals with NaN.
#[inline(always)]
fn fmax(a: f32, b: f32) -> f32 {
if a > b {
a
} else {
b
}
}
fn slope(v: Vector) -> f32 {
v.x / (v.y.max(f32::MIN))
}
#[cfg(debug_assertions)]
macro_rules! tess_log {
($obj:ident, $fmt:expr) => (
if $obj.log {
println!($fmt);
}
);
($obj:ident, $fmt:expr, $($arg:tt)*) => (
if $obj.log {
println!($fmt, $($arg)*);
}
);
}
#[cfg(not(debug_assertions))]
macro_rules! tess_log {
($obj:ident, $fmt:expr) => {};
($obj:ident, $fmt:expr, $($arg:tt)*) => {};
}
#[derive(Copy, Clone, Debug)]
struct WindingState {
span_index: SpanIdx,
number: i16,
is_in: bool,
}
impl WindingState {
fn new() -> Self {
// The span index starts at -1 so that entering the first span (of index 0) increments
// it to zero.
WindingState {
span_index: -1,
number: 0,
is_in: false,
}
}
fn update(&mut self, fill_rule: FillRule, edge_winding: i16) {
self.number += edge_winding;
self.is_in = fill_rule.is_in(self.number);
if self.is_in {
self.span_index += 1;
}
}
}
struct ActiveEdgeScan {
vertex_events: Vec<(SpanIdx, Side)>,
edges_to_split: Vec<ActiveEdgeIdx>,
spans_to_end: Vec<SpanIdx>,
merge_event: bool,
split_event: bool,
merge_split_event: bool,
above: Range<ActiveEdgeIdx>,
winding_before_point: WindingState,
}
impl ActiveEdgeScan {
fn new() -> Self {
ActiveEdgeScan {
vertex_events: Vec::new(),
edges_to_split: Vec::new(),
spans_to_end: Vec::new(),
merge_event: false,
split_event: false,
merge_split_event: false,
above: 0..0,
winding_before_point: WindingState::new(),
}
}
fn reset(&mut self) {
self.vertex_events.clear();
self.edges_to_split.clear();
self.spans_to_end.clear();
self.merge_event = false;
self.split_event = false;
self.merge_split_event = false;
self.above = 0..0;
self.winding_before_point = WindingState::new();
}
}
#[derive(Copy, Clone, Debug)]
struct ActiveEdge {
from: Point,
to: Point,
winding: i16,
is_merge: bool,
from_id: VertexId,
src_edge: TessEventId,
range_end: f32,
}
#[test]
fn active_edge_size() {
// We want to be careful about the size of the struct.
assert_eq!(std::mem::size_of::<ActiveEdge>(), 32);
}
impl ActiveEdge {
#[inline(always)]
fn min_x(&self) -> f32 {
self.from.x.min(self.to.x)
}
#[inline(always)]
fn max_x(&self) -> f32 {
fmax(self.from.x, self.to.x)
}
}
impl ActiveEdge {
fn solve_x_for_y(&self, y: f32) -> f32 {
// Because of float precision hazard, solve_x_for_y can
// return something slightly out of the min/max range which
// causes the ordering to be inconsistent with the way the
// scan phase uses the min/max range.
LineSegment {
from: self.from,
to: self.to,
}
.solve_x_for_y(y)
.max(self.min_x())
.min(self.max_x())
}
}
struct ActiveEdges {
edges: Vec<ActiveEdge>,
}
struct Span {
/// We store `MonotoneTesselator` behind a `Box` for performance purposes.
/// For more info, see [Issue #621](https://github.com/nical/lyon/pull/621).
tess: Option<Box<MonotoneTessellator>>,
}
impl Span {
fn tess(&mut self) -> &mut MonotoneTessellator {
// this should only ever be called on a "live" span.
match self.tess.as_mut() {
None => {
debug_assert!(false);
unreachable!();
}
Some(tess) => tess,
}
}
}
struct Spans {
spans: Vec<Span>,
/// We store `MonotoneTesselator` behind a `Box` for performance purposes.
/// For more info, see [Issue #621](https://github.com/nical/lyon/pull/621).
#[allow(clippy::vec_box)]
pool: Vec<Box<MonotoneTessellator>>,
}
impl Spans {
fn begin_span(&mut self, span_idx: SpanIdx, position: &Point, vertex: VertexId) {
let mut tess = self
.pool
.pop()
.unwrap_or_else(|| Box::new(MonotoneTessellator::new()));
tess.begin(*position, vertex);
self.spans
.insert(span_idx as usize, Span { tess: Some(tess) });
}
fn end_span(
&mut self,
span_idx: SpanIdx,
position: &Point,
id: VertexId,
output: &mut dyn FillGeometryBuilder,
) {
let idx = span_idx as usize;
let span = &mut self.spans[idx];
if let Some(mut tess) = span.tess.take() {
tess.end(*position, id);
tess.flush(output);
// Recycle the allocations for future use.
self.pool.push(tess);
} else {
debug_assert!(false);
unreachable!();
}
}
fn merge_spans(
&mut self,
left_span_idx: SpanIdx,
current_position: &Point,
current_vertex: VertexId,
merge_position: &Point,
merge_vertex: VertexId,
output: &mut dyn FillGeometryBuilder,
) {
// \...\ /.
// \...x.. <-- merge vertex
// \./... <-- active_edge
// x.... <-- current vertex
let right_span_idx = left_span_idx + 1;
self.spans[left_span_idx as usize].tess().vertex(
*merge_position,
merge_vertex,
Side::Right,
);
self.spans[right_span_idx as usize].tess().vertex(
*merge_position,
merge_vertex,
Side::Left,
);
self.end_span(left_span_idx, current_position, current_vertex, output);
}
fn cleanup_spans(&mut self) {
// Get rid of the spans that were marked for removal.
self.spans.retain(|span| span.tess.is_some());
}
}
#[derive(Copy, Clone, Debug)]
struct PendingEdge {
to: Point,
sort_key: f32,
// Index in events.edge_data
src_edge: TessEventId,
winding: i16,
range_end: f32,
}
/// A Context object that can tessellate fill operations for complex paths.
///
/// <svg version="1.1" viewBox="0 0 400 200" height="200" width="400">
/// <g transform="translate(0,-852.36216)">
/// <path style="fill:#aad400;stroke:none;" transform="translate(0,852.36216)" d="M 20 20 L 20 180 L 180.30273 180 L 180.30273 20 L 20 20 z M 100 55 L 145 145 L 55 145 L 100 55 z "/>
/// <path style="fill:#aad400;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-" d="m 219.75767,872.36216 0,160.00004 160.30273,0 0,-160.00004 -160.30273,0 z m 80,35 45,90 -90,0 45,-90 z"/>
/// <path style="fill:none;stroke:#000000;stroke-linecap:round;stroke-linejoin:round;stroke-" d="m 220,1032.3622 35,-35.00004 125,35.00004 -35,-35.00004 35,-125 -80,35 -80,-35 35,125"/>
/// <circle r="5" cy="872.36218" cx="20" style="color:#000000;;fill:#ff6600;fill-;stroke:#000000;" />
/// <circle r="5" cx="180.10918" cy="872.61475" style="fill:#ff6600;stroke:#000000;"/>
/// <circle r="5" cy="1032.2189" cx="180.10918" style="fill:#ff6600;stroke:#000000;"/>
/// <circle r="5" cx="20.505075" cy="1032.4714" style="fill:#ff6600;stroke:#000000;"/>
/// <circle r="5" cy="907.21252" cx="99.802048" style="fill:#ff6600;stroke:#000000;"/>
/// <circle r="5" cx="55.102798" cy="997.36865" style="fill:#ff6600;stroke:#000000;"/>
/// <circle r="5" cy="997.62122" cx="145.25891" style="fill:#ff6600;stroke:#000000;"/>
/// </g>
/// </svg>
///
/// ## Overview
///
/// The most important structure is [`FillTessellator`](struct.FillTessellator.html).
/// It implements the path fill tessellation algorithm which is by far the most advanced
/// feature in all lyon crates.
///
/// The `FillTessellator` takes a description of the input path and
/// [`FillOptions`](struct.FillOptions.html) as input. The description of the path can be an
/// `PathEvent` iterator, or an iterator of `IdEvent` with an implementation of`PositionStore`
/// to retrieve positions form endpoint and control point ids, and optionally an `AttributeStore`
/// providing custom endpoint attributes that the tessellator can hand over to the geometry builder.
///
/// The output of the tessellator is produced by the
/// [`FillGeometryBuilder`](geometry_builder/trait.FillGeometryBuilder.html) (see the
/// [`geometry_builder` documentation](geometry_builder/index.html) for more details about
/// how tessellators produce their output geometry, and how to generate custom vertex layouts).
///
/// The [tessellator's wiki page](https://github.com/nical/lyon/wiki/Tessellator) is a good place
/// to learn more about how the tessellator's algorithm works. The source code also contains
/// inline documentation for the adventurous who want to delve into more details.
///
/// The tessellator does not handle `NaN` values in any of its inputs.
///
/// ## Associating custom attributes with vertices.
///
/// It is sometimes useful to be able to link vertices generated by the tessellator back
/// with the path's original data, for example to be able to add attributes that the tessellator
/// does not know about (vertex color, texture coordinates, etc.).
///
/// The fill tessellator has two mechanisms to help with these advanced use cases. One is
/// simple to use and one that, while more complicated to use, can cover advanced scenarios.
///
/// Before going delving into these mechanisms, it is important to understand that the
/// vertices generated by the tessellator don't always correspond to the vertices existing
/// in the original path.
/// - Self-intersections, for example, introduce a new vertex where two edges meet.
/// - When several vertices are at the same position, they are merged into a single vertex
/// from the point of view of the tessellator.
/// - The tessellator does not handle curves, and uses an approximation that introduces a
/// number of line segments and therefore endpoints between the original endpoints of any
/// quadratic or cubic bézier curve.
///
/// This complicates the task of adding extra data to vertices without loosing the association
/// during tessellation.
///
/// ### Vertex sources
///
/// This is the complicated, but most powerful mechanism. The tessellator keeps track of where
/// each vertex comes from in the original path, and provides access to this information via
/// an iterator of [`VertexSource`](enum.VertexSource.html) in `FillVertex::sources`.
///
/// It is most common for the vertex source iterator to yield a single `VertexSource::Endpoint`
/// source, which happens when the vertex directly corresponds to an endpoint of the original path.
/// More complicated cases can be expressed.
/// For example if a vertex is inserted at an intersection halfway in the edge AB and two thirds
/// of the way through edge BC, the source for this new vertex is `VertexSource::Edge { from: A, to: B, t: 0.5 }`
/// and `VertexSource::Edge { from: C, to: D, t: 0.666666 }` where A, B, C and D are endpoint IDs.
///
/// To use this feature, make sure to use `FillTessellator::tessellate_with_ids` instead of
/// `FillTessellator::tessellate`.
///
/// ### Interpolated float attributes
///
/// Having to iterate over potentially several sources for each vertex can be cumbersome, in addition
/// to having to deal with generating proper values for the attributes of vertices that were introduced
/// at intersections or along curves.
///
/// In many scenarios, vertex attributes are made of floating point numbers and the most reasonable
/// way to generate new attributes is to linearly interpolate these numbers between the endpoints
/// of the edges they originate from.
///
/// Custom endpoint attributes are represented as `&[f32]` slices accessible via
/// `FillVertex::interpolated_attributes`. All vertices, whether they originate from a single
/// endpoint or some more complex source, have exactly the same number of attributes.
/// Without having to know about the meaning of attributes, the tessellator can either
/// forward the slice of attributes from a provided `AttributeStore` when possible or
/// generate the values via linear interpolation.
///
/// To use this feature, make sure to use `FillTessellator::tessellate_path` or
/// `FillTessellator::tessellate_with_ids` instead of `FillTessellator::tessellate`.
///
/// Attributes are lazily computed when calling `FillVertex::interpolated_attributes`.
/// In other words they don't add overhead when not used, however it is best to avoid calling
/// interpolated_attributes several times per vertex.
///
/// # Examples
///
/// ```
/// # extern crate lyon_tessellation as tess;
/// # use tess::path::Path;
/// # use tess::path::builder::*;
/// # use tess::path::iterator::*;
/// # use tess::math::{Point, point};
/// # use tess::geometry_builder::{VertexBuffers, simple_builder};
/// # use tess::*;
/// # fn main() {
/// // Create a simple path.
/// let mut path_builder = Path::builder();
/// path_builder.begin(point(0.0, 0.0));
/// path_builder.line_to(point(1.0, 2.0));
/// path_builder.line_to(point(2.0, 0.0));
/// path_builder.line_to(point(1.0, 1.0));
/// path_builder.end(true);
/// let path = path_builder.build();
///
/// // Create the destination vertex and index buffers.
/// let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new();
///
/// {
/// let mut vertex_builder = simple_builder(&mut buffers);
///
/// // Create the tessellator.
/// let mut tessellator = FillTessellator::new();
///
/// // Compute the tessellation.
/// let result = tessellator.tessellate_path(
/// &path,
/// &FillOptions::default(),
/// &mut vertex_builder
/// );
/// assert!(result.is_ok());
/// }
///
/// println!("The generated vertices are: {:?}.", &buffers.vertices[..]);
/// println!("The generated indices are: {:?}.", &buffers.indices[..]);
///
/// # }
/// ```
///
/// ```
/// # extern crate lyon_tessellation as tess;
/// # use tess::path::Path;
/// # use tess::path::builder::*;
/// # use tess::path::iterator::*;
/// # use tess::math::{Point, point};
/// # use tess::geometry_builder::{VertexBuffers, simple_builder};
/// # use tess::*;
/// # fn main() {
/// // Create a path with three custom endpoint attributes.
/// let mut path_builder = Path::builder_with_attributes(3);
/// path_builder.begin(point(0.0, 0.0), &[0.0, 0.1, 0.5]);
/// path_builder.line_to(point(1.0, 2.0), &[1.0, 1.0, 0.1]);
/// path_builder.line_to(point(2.0, 0.0), &[1.0, 0.0, 0.8]);
/// path_builder.line_to(point(1.0, 1.0), &[0.1, 0.3, 0.5]);
/// path_builder.end(true);
/// let path = path_builder.build();
///
/// struct MyVertex {
/// x: f32, y: f32,
/// r: f32, g: f32, b: f32, a: f32,
/// }
/// // A custom vertex constructor, see the geometry_builder module.
/// struct Ctor;
/// impl FillVertexConstructor<MyVertex> for Ctor {
/// fn new_vertex(&mut self, mut vertex: FillVertex) -> MyVertex {
/// let position = vertex.position();
/// let attrs = vertex.interpolated_attributes();
/// MyVertex {
/// x: position.x,
/// y: position.y,
/// r: attrs[0],
/// g: attrs[1],
/// b: attrs[2],
/// a: 1.0,
/// }
/// }
/// }
///
/// // Create the destination vertex and index buffers.
/// let mut buffers: VertexBuffers<MyVertex, u16> = VertexBuffers::new();
///
/// {
/// // We use our custom vertex constructor here.
/// let mut vertex_builder = BuffersBuilder::new(&mut buffers, Ctor);
///
/// // Create the tessellator.
/// let mut tessellator = FillTessellator::new();
///
/// // Compute the tessellation. Here we use tessellate_with_ids
/// // which has a slightly more complicated interface. The provides
/// // the iterator as well as storage for positions and attributes at
/// // the same time.
/// let result = tessellator.tessellate_with_ids(
/// path.id_iter(), // Iterator over ids in the path
/// &path, // PositionStore
/// Some(&path), // AttributeStore
/// &FillOptions::default(),
/// &mut vertex_builder
/// );
/// assert!(result.is_ok());
/// }
///
/// # }
/// ```
pub struct FillTessellator {
current_position: Point,
current_vertex: VertexId,
current_event_id: TessEventId,
active: ActiveEdges,
edges_below: Vec<PendingEdge>,
fill_rule: FillRule,
orientation: Orientation,
tolerance: f32,
fill: Spans,
log: bool,
assume_no_intersection: bool,
attrib_buffer: Vec<f32>,
scan: ActiveEdgeScan,
events: EventQueue,
}
impl Default for FillTessellator {
fn default() -> Self {
Self::new()
}
}
impl FillTessellator {
/// Constructor.
pub fn new() -> Self {
#[cfg(debug_assertions)]
let log = env::var("LYON_FORCE_LOGGING").is_ok();
#[cfg(not(debug_assertions))]
let log = false;
FillTessellator {
current_position: point(f32::MIN, f32::MIN),
current_vertex: VertexId::INVALID,
current_event_id: INVALID_EVENT_ID,
active: ActiveEdges { edges: Vec::new() },
edges_below: Vec::new(),
fill_rule: FillRule::EvenOdd,
orientation: Orientation::Vertical,
tolerance: FillOptions::DEFAULT_TOLERANCE,
fill: Spans {
spans: Vec::new(),
pool: Vec::new(),
},
log,
assume_no_intersection: false,
attrib_buffer: Vec::new(),
scan: ActiveEdgeScan::new(),
events: EventQueue::new(),
}
}
/// Compute the tessellation from a path iterator.
pub fn tessellate(
&mut self,
path: impl IntoIterator<Item = PathEvent>,
options: &FillOptions,
output: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
let event_queue = std::mem::replace(&mut self.events, EventQueue::new());
let mut queue_builder = event_queue.into_builder(options.tolerance);
queue_builder.set_path(
options.tolerance,
options.sweep_orientation,
path.into_iter(),
);
self.events = queue_builder.build();
self.tessellate_impl(options, None, output)
}
/// Compute the tessellation using an iterator over endpoint and control
/// point ids, storage for the positions and, optionally, storage for
/// custom endpoint attributes.
pub fn tessellate_with_ids(
&mut self,
path: impl IntoIterator<Item = IdEvent>,
positions: &impl PositionStore,
custom_attributes: Option<&dyn AttributeStore>,
options: &FillOptions,
output: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
let event_queue = std::mem::replace(&mut self.events, EventQueue::new());
let mut queue_builder = event_queue.into_builder(options.tolerance);
queue_builder.set_path_with_ids(
options.tolerance,
options.sweep_orientation,
path.into_iter(),
positions,
);
self.events = queue_builder.build();
self.tessellate_impl(options, custom_attributes, output)
}
/// Compute the tessellation from a path slice.
///
/// The tessellator will internally only track vertex sources and interpolated
/// attributes if the path has interpolated attributes.
pub fn tessellate_path<'l>(
&'l mut self,
path: impl Into<PathSlice<'l>>,
options: &'l FillOptions,
builder: &'l mut dyn FillGeometryBuilder,
) -> TessellationResult {
let path = path.into();
if path.num_attributes() > 0 {
self.tessellate_with_ids(path.id_iter(), &path, Some(&path), options, builder)
} else {
self.tessellate(path.iter(), options, builder)
}
}
/// Tessellate a `Polygon`.
pub fn tessellate_polygon(
&mut self,
polygon: Polygon<Point>,
options: &FillOptions,
output: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
self.tessellate(polygon.path_events(), options, output)
}
/// Tessellate an axis-aligned rectangle.
pub fn tessellate_rectangle(
&mut self,
rect: &Box2D,
_options: &FillOptions,
output: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
crate::basic_shapes::fill_rectangle(rect, output)
}
/// Tessellate a circle.
pub fn tessellate_circle(
&mut self,
center: Point,
radius: f32,
options: &FillOptions,
output: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
crate::basic_shapes::fill_circle(center, radius, options, output)
}
/// Tessellate an ellipse.
pub fn tessellate_ellipse(
&mut self,
center: Point,
radii: Vector,
x_rotation: Angle,
winding: Winding,
options: &FillOptions,
output: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
let options = (*options).with_intersections(false);
let mut builder = self.builder(&options, output);
builder.add_ellipse(center, radii, x_rotation, winding);
builder.build()
}
/// Tessellate directly from a sequence of `PathBuilder` commands, without
/// creating an intermediate path data structure.
///
/// The returned builder implements the [`lyon_path::traits::PathBuilder`] trait,
/// is compatible with the all `PathBuilder` adapters.
/// It also has all requirements documented in `PathBuilder` (All sub-paths must be
/// wrapped in a `begin`/`end` pair).
///
/// # Example
///
/// ```rust
/// use lyon_tessellation::{FillTessellator, FillOptions};
/// use lyon_tessellation::geometry_builder::{simple_builder, VertexBuffers};
/// use lyon_tessellation::math::{Point, point};
///
/// let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new();
/// let mut vertex_builder = simple_builder(&mut buffers);
/// let mut tessellator = FillTessellator::new();
/// let options = FillOptions::default();
///
/// // Create a temporary builder (borrows the tessellator).
/// let mut builder = tessellator.builder(&options, &mut vertex_builder);
///
/// // Build the path directly in the tessellator, skipping an intermediate data
/// // structure.
/// builder.begin(point(0.0, 0.0));
/// builder.line_to(point(10.0, 0.0));
/// builder.line_to(point(10.0, 10.0));
/// builder.line_to(point(0.0, 10.0));
/// builder.end(true);
///
/// // Finish the tessellation and get the result.
/// let result = builder.build();
/// ```
///
/// [`lyon_path::traits::PathBuilder`]: https://docs.rs/lyon_path/*/lyon_path/traits/trait.PathBuilder.html
pub fn builder<'l>(
&'l mut self,
options: &'l FillOptions,
output: &'l mut dyn FillGeometryBuilder,
) -> NoAttributes<FillBuilder<'l>> {
NoAttributes::wrap(FillBuilder::new(0, self, options, output))
}
/// Tessellate directly from a sequence of `PathBuilder` commands, without
/// creating an intermediate path data structure.
///
/// Similar to `FillTessellator::builder` with custom attributes.
pub fn builder_with_attributes<'l>(
&'l mut self,
num_attributes: usize,
options: &'l FillOptions,
output: &'l mut dyn FillGeometryBuilder,
) -> FillBuilder<'l> {
FillBuilder::new(num_attributes, self, options, output)
}
fn tessellate_impl(
&mut self,
options: &FillOptions,
attrib_store: Option<&dyn AttributeStore>,
builder: &mut dyn FillGeometryBuilder,
) -> TessellationResult {
if options.tolerance.is_nan() || options.tolerance <= 0.0 {
return Err(TessellationError::UnsupportedParamater(
UnsupportedParamater::ToleranceIsNaN,
));
}
self.reset();
if let Some(store) = attrib_store {
self.attrib_buffer.resize(store.num_attributes(), 0.0);
} else {
self.attrib_buffer.clear();
}
self.fill_rule = options.fill_rule;
self.orientation = options.sweep_orientation;
self.tolerance = options.tolerance * 0.5;
self.assume_no_intersection = !options.handle_intersections;
builder.begin_geometry();
let mut scan = mem::replace(&mut self.scan, ActiveEdgeScan::new());
let result = self.tessellator_loop(attrib_store, &mut scan, builder);
mem::swap(&mut self.scan, &mut scan);
if let Err(e) = result {
tess_log!(self, "Tessellation failed with error: {}.", e);
builder.abort_geometry();
return Err(e);
}
if !self.assume_no_intersection {
debug_assert!(self.active.edges.is_empty());
debug_assert!(self.fill.spans.is_empty());
}
// There shouldn't be any span left after the tessellation ends.
// If for whatever reason (bug) there are, flush them so that we don't
// miss the triangles they contain.
for span in &mut self.fill.spans {
if let Some(tess) = span.tess.as_mut() {
tess.flush(builder);
}
}
self.fill.spans.clear();
builder.end_geometry();
Ok(())
}
/// Enable/disable some verbose logging during the tessellation, for
/// debugging purposes.
pub fn set_logging(&mut self, is_enabled: bool) {
#[cfg(debug_assertions)]
let forced = env::var("LYON_FORCE_LOGGING").is_ok();
#[cfg(not(debug_assertions))]
let forced = false;
self.log = is_enabled || forced;
}
#[cfg_attr(feature = "profiling", inline(never))]
fn tessellator_loop(
&mut self,
attrib_store: Option<&dyn AttributeStore>,
scan: &mut ActiveEdgeScan,
output: &mut dyn FillGeometryBuilder,
) -> Result<(), TessellationError> {
log_svg_preamble(self);
let mut _prev_position = point(f32::MIN, f32::MIN);
self.current_event_id = self.events.first_id();
while self.events.valid_id(self.current_event_id) {
self.initialize_events(attrib_store, output)?;
debug_assert!(is_after(self.current_position, _prev_position));
_prev_position = self.current_position;
if let Err(e) = self.process_events(scan, output) {
// Something went wrong, attempt to salvage the state of the sweep
// line
self.recover_from_error(e, output);
// ... and try again.
self.process_events(scan, output)?
}
#[cfg(debug_assertions)]
self.check_active_edges();
self.current_event_id = self.events.next_id(self.current_event_id);
}
Ok(())
}
fn initialize_events(
&mut self,
attrib_store: Option<&dyn AttributeStore>,
output: &mut dyn FillGeometryBuilder,
) -> Result<(), TessellationError> {
let current_event = self.current_event_id;
tess_log!(
self,
"\n\n<!-- event #{} -->",
current_event
);
self.current_position = self.events.position(current_event);
if self.current_position.x.is_nan() || self.current_position.y.is_nan() {
return Err(TessellationError::UnsupportedParamater(
UnsupportedParamater::PositionIsNaN,
));
}
let position = match self.orientation {
Orientation::Vertical => self.current_position,
Orientation::Horizontal => reorient(self.current_position),
};
self.current_vertex = output.add_fill_vertex(FillVertex {
position,
events: &self.events,
current_event,
attrib_store,
attrib_buffer: &mut self.attrib_buffer,
})?;
let mut current_sibling = current_event;
while self.events.valid_id(current_sibling) {
let edge = &self.events.edge_data[current_sibling as usize];
// We insert "fake" edges when there are end events
// to make sure we process that vertex even if it has
// no edge below.
if edge.is_edge {
let to = edge.to;
debug_assert!(is_after(to, self.current_position));
self.edges_below.push(PendingEdge {
to,
sort_key: slope(to - self.current_position), //.angle_from_x_axis().radians,
src_edge: current_sibling,
winding: edge.winding,
range_end: edge.range.end,
});
}
current_sibling = self.events.next_sibling_id(current_sibling);
}
Ok(())
}
/// An iteration of the sweep line algorithm.
#[cfg_attr(feature = "profiling", inline(never))]
fn process_events(
&mut self,
scan: &mut ActiveEdgeScan,
output: &mut dyn FillGeometryBuilder,
) -> Result<(), InternalError> {
tess_log!(self, "<!--");
tess_log!(
self,
" events at {:?} {:?} {} edges below",
self.current_position,
self.current_vertex,
self.edges_below.len(),
);
tess_log!(self, "edges below (initially): {:#?}", self.edges_below);
// Step 1 - Scan the active edge list, deferring processing and detecting potential
// ordering issues in the active edges.
self.scan_active_edges(scan)?;
// Step 2 - Do the necessary processing on edges that end at the current point.
self.process_edges_above(scan, output);
// Step 3 - Do the necessary processing on edges that start at the current point.
self.process_edges_below(scan);
// Step 4 - Insert/remove edges to the active edge as necessary and handle
// potential self-intersections.
self.update_active_edges(scan);
tess_log!(self, "-->");
#[cfg(debug_assertions)]
self.log_active_edges();
Ok(())
}
#[cfg(debug_assertions)]
fn log_active_edges(&self) {
tess_log!(self, r#"<g class="active-edges">"#);
tess_log!(
self,
r#"<path d="M 0 {} L 1000 {}" class="sweep-line"/>"#,
self.current_position.y,
self.current_position.y
);
tess_log!(self, "<!-- active edges: -->");
for e in &self.active.edges {
if e.is_merge {
tess_log!(
self,
r#" <circle cx="{}" cy="{}" r="3px" class="merge"/>"#,
e.from.x,
e.from.y
);
} else {
tess_log!(
self,
r#" <path d="M {:.5?} {:.5?} L {:.5?} {:.5?}" class="edge", winding="{:>2}"/>"#,
e.from.x,
e.from.y,
e.to.x,
e.to.y,
e.winding,
);
}
}
tess_log!(self, "<!-- spans: {}-->", self.fill.spans.len());
tess_log!(self, "</g>");
}
#[cfg(debug_assertions)]
fn check_active_edges(&self) {
let mut winding = WindingState::new();
for (idx, edge) in self.active.edges.iter().enumerate() {
winding.update(self.fill_rule, edge.winding);
if edge.is_merge {
assert!(self.fill_rule.is_in(winding.number));
} else {
assert!(
!is_after(self.current_position, edge.to),
"error at edge {}, position {:.6?} (current: {:.6?}",
idx,
edge.to,
self.current_position,
);