Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TriangleMesh.pm « Slic3r « lib - github.com/prusa3d/PrusaSlicer.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e0698b4a67e3b77747cefc5081a66e29163e86a5 (plain)
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
package Slic3r::TriangleMesh;
use Moo;

use List::Util qw(reduce min max);
use Slic3r::Geometry qw(X Y Z A B unscale same_point);
use Slic3r::Geometry::Clipper qw(union_ex);
use Storable;

# public
has 'vertices'      => (is => 'ro', required => 1);         # id => [$x,$y,$z]
has 'facets'        => (is => 'ro', required => 1);         # id => [ $v1_id, $v2_id, $v3_id ]

# private
has 'edges'         => (is => 'rw'); # id => [ $v1_id, $v2_id ]
has 'facets_edges'  => (is => 'rw'); # id => [ $e1_id, $e2_id, $e3_id ]
has 'edges_facets'  => (is => 'rw'); # id => [ $f1_id, $f2_id, (...) ]

use constant MIN => 0;
use constant MAX => 1;

use constant I_FMT              => 'ffllLllc';
use constant I_B                => 0;
use constant I_A_ID             => 1;
use constant I_B_ID             => 2;
use constant I_FACET_INDEX      => 3;
use constant I_PREV_FACET_INDEX => 4;
use constant I_NEXT_FACET_INDEX => 5;
use constant I_FACET_EDGE       => 6;

use constant FE_TOP             => 0;
use constant FE_BOTTOM          => 1;

sub analyze {
    my $self = shift;
    
    return if defined $self->edges;
    $self->edges([]);
    $self->facets_edges([]);
    $self->edges_facets([]);
    my %table = ();  # edge_coordinates => edge_id
    my $vertices = $self->vertices;  # save method calls
    
    for (my $facet_id = 0; $facet_id <= $#{$self->facets}; $facet_id++) {
        my $facet = $self->facets->[$facet_id];
        $self->facets_edges->[$facet_id] = [];
        
        # reorder vertices so that the first one is the one with lowest Z
        # this is needed to get all intersection lines in a consistent order
        # (external on the right of the line)
        {
            my $lowest_vertex_idx = reduce {
                $vertices->[ $facet->[$a] ][Z] < $vertices->[ $facet->[$b] ][Z] ? $a : $b
            } -3 .. -1;
            @$facet[-3..-1] = (@$facet[$lowest_vertex_idx..-1], @$facet[-3..($lowest_vertex_idx-1)]);
        }
        
        # ignore the normal if provided
        my @vertices = @$facet[-3..-1];
        
        foreach my $edge ($self->_facet_edges($facet_id)) {
            my $edge_coordinates = join ';', sort @$edge;
            my $edge_id = $table{$edge_coordinates};
            if (!defined $edge_id) {
                # Note that the order of vertices in $self->edges is *casual* because it is only
                # good for one of the two adjacent facets. For this reason, it must not be used
                # when dealing with single facets.
                push @{$self->edges}, $edge;
                $edge_id = $#{$self->edges};
                $table{$edge_coordinates} = $edge_id;
                $self->edges_facets->[$edge_id] = [];
            }
            
            push @{$self->facets_edges->[$facet_id]}, $edge_id;
            push @{$self->edges_facets->[$edge_id]}, $facet_id;
        }
    }
}

sub merge {
    my $class = shift;
    my @meshes = @_;
    
    my $vertices = [];
    my $facets = [];
    
    foreach my $mesh (@meshes) {
        my $v_offset = @$vertices;
        push @$vertices, @{$mesh->vertices};
        push @$facets, map {
            my $f = [@$_];
            $f->[$_] += $v_offset for -3..-1;
            $f;
        } @{$mesh->facets};
    }
    
    return $class->new(vertices => $vertices, facets => $facets);
}

sub clone {
  Storable::dclone($_[0])
}

sub _facet_edges {
    my $self = shift;
    my ($facet_id) = @_;
    
    my $facet = $self->facets->[$facet_id];
    return (
        [ $facet->[-3], $facet->[-2] ],
        [ $facet->[-2], $facet->[-1] ],
        [ $facet->[-1], $facet->[-3] ],
    );
}

# This method is supposed to remove narrow triangles, but it actually doesn't 
# work much; I'm committing it for future reference but I'm going to remove it later.
# Note: a 'clean' method should actually take care of non-manifold facets and remove
# them.
sub clean {
    my $self = shift;
    
    # retrieve all edges shared by more than two facets;
    my @weird_edges = grep { @{$self->edge_facets->{$_}} != 2 } keys %{$self->edge_facets};
    
    # usually most of these facets are very narrow triangles whose two edges
    # are detected as collapsed, and thus added twice to the edge in edge_fasets table
    # let's identify these triangles
    my @narrow_facets_indexes = ();
    foreach my $edge_id (@weird_edges) {
        my %facet_count = ();
        $facet_count{$_}++ for @{$self->edge_facets->{$edge_id}};
        @{$self->edge_facets->{$edge_id}} = grep $facet_count{$_} == 1, keys %facet_count;
        push @narrow_facets_indexes, grep $facet_count{$_} > 1, keys %facet_count;
    }
    
    # remove identified narrow facets
    foreach my $facet_id (@narrow_facets_indexes) {last;
         splice @{$self->facets}, $facet_id, 1;
         splice @{$self->facets_edges}, $facet_id, 1;
         foreach my $facet_ides (values %{$self->edge_facets}) {
            @$facet_ides = map { $_ > $facet_id ? ($_-1) : $_ } @$facet_ides;
         }
    }
    
    Slic3r::debugf "%d narrow facets removed\n", scalar(@narrow_facets_indexes)
        if @narrow_facets_indexes;
}

sub check_manifoldness {
    my $self = shift;
    
    $self->analyze;
    
    # look for any edges not connected to exactly two facets
    my ($first_bad_edge_id) =
        grep { @{ $self->edges_facets->[$_] } != 2 } 0..$#{$self->edges_facets};
    if (defined $first_bad_edge_id) {
        warn sprintf "Warning: The input file contains a hole near edge %f,%f,%f-%f,%f,%f (not manifold). "
            . "You might want to repair it and retry, or to check the resulting G-code before printing anyway.\n",
            map @{$self->vertices->[$_]}, @{$self->edges->[$first_bad_edge_id]};
        return 0;
    }
    
    # empty the edges array as we don't really need it anymore
    @{$self->edges} = ();
    
    return 1;
}

sub unpack_line {
    my ($packed) = @_;
    
    my $data = [ unpack I_FMT, $packed ];
    splice @$data, 0, 2, [ @$data[0,1] ];
    $data->[$_] = undef for grep $data->[$_] == -1, I_A_ID, I_B_ID, I_FACET_EDGE, I_PREV_FACET_INDEX, I_NEXT_FACET_INDEX;
    return $data;
}

sub make_loops {
    my ($lines) = @_;
    my @lines = map unpack_line($_), @$lines;
    
    # remove tangent edges
    {
        for (my $i = 0; $i <= $#lines; $i++) {
            next unless defined $lines[$i] && defined $lines[$i][I_FACET_EDGE];
            # if the line is a facet edge, find another facet edge
            # having the same endpoints but in reverse order
            for (my $j = $i+1; $j <= $#lines; $j++) {
                next unless defined $lines[$j] && defined $lines[$j][I_FACET_EDGE];
                
                # are these facets adjacent? (sharing a common edge on this layer)
                if ($lines[$i][I_A_ID] == $lines[$j][I_B_ID] && $lines[$i][I_B_ID] == $lines[$j][I_A_ID]) {
                
                    # if they are both oriented upwards or downwards (like a 'V')
                    # then we can remove both edges from this layer since it won't 
                    # affect the sliced shape
                    if ($lines[$j][I_FACET_EDGE] == $lines[$i][I_FACET_EDGE]) {
                        $lines[$i] = undef;
                        $lines[$j] = undef;
                        last;
                    }
                    
                    # if one of them is oriented upwards and the other is oriented
                    # downwards, let's only keep one of them (it doesn't matter which
                    # one since all 'top' lines were reversed at slicing)
                    if ($lines[$i][I_FACET_EDGE] == FE_TOP && $lines[$j][I_FACET_EDGE] == FE_BOTTOM) {
                        $lines[$j] = undef;
                        last;
                    }
                }
                
            }
        }
    }
    
    @lines = grep $_, @lines;
    
    # count relationships
    my %prev_count = ();  # how many lines have the same prev_facet_index
    my %a_count    = ();  # how many lines have the same a_id
    foreach my $line (@lines) {
        if (defined $line->[I_PREV_FACET_INDEX]) {
            $prev_count{$line->[I_PREV_FACET_INDEX]}++;
        }
        if (defined $line->[I_A_ID]) {
            $a_count{$line->[I_A_ID]}++;
        }
    }
    
    foreach my $point_id (grep $a_count{$_} > 1, keys %a_count) {
        my @lines_starting_here = grep defined $_->[I_A_ID] && $_->[I_A_ID] == $point_id, @lines;
        Slic3r::debugf "%d lines start at point %d\n", scalar(@lines_starting_here), $point_id;
        
        # if two lines start at this point, one being a 'top' facet edge and the other being a 'bottom' one,
        # then remove the top one and those following it (removing the top or the bottom one is an arbitrary
        # choice)
        # The "// ''" on the next line avoids uninitialized value errors mentioned in issue #357 but these
        # errors occur on fixed models so the root cause still needs to be found
        if (@lines_starting_here == 2 && join('', sort map $_->[I_FACET_EDGE] // '', @lines_starting_here) eq FE_TOP.FE_BOTTOM) { #/
            my @to_remove = grep $_->[I_FACET_EDGE] == FE_TOP, @lines_starting_here;
            while (!grep defined $_->[I_B_ID] && $_->[I_B_ID] == $to_remove[-1]->[I_B_ID] && $_ ne $to_remove[-1], @lines) {
                push @to_remove, grep defined $_->[I_A_ID] && $_->[I_A_ID] == $to_remove[-1]->[I_B_ID], @lines;
            }
            my %to_remove = map {$_ => 1} @to_remove;
            @lines = grep !$to_remove{$_}, @lines;
        } else {
            Slic3r::debugf "  this shouldn't happen and should be further investigated\n";
            if (0) {
                require "Slic3r/SVG.pm";
                Slic3r::SVG::output("same_point.svg",
                    lines       => [ map $_->line, grep !defined $_->[I_FACET_EDGE], @lines ],
                    red_lines   => [ map $_->line, grep defined $_->[I_FACET_EDGE], @lines ],
                    #points      => [ $self->vertices->[$point_id] ],
                    no_arrows => 0,
                );
            }
        }
    }
    
    # optimization: build indexes of lines
    my %by_facet_index = map { $lines[$_][I_FACET_INDEX] => $_ }
        grep defined $lines[$_][I_FACET_INDEX],
        (0..$#lines);
    my %by_a_id = map { $lines[$_][I_A_ID] => $_ }
        grep defined $lines[$_][I_A_ID],
        (0..$#lines);
    
    my (@polygons, @failed_loops, %visited_lines) = ();
    my $slicing_errors = 0;
    CYCLE: for (my $i = 0; $i <= $#lines; $i++) {
        my $line = $lines[$i];
        next if $visited_lines{$line};
        my @points = ();
        my $first_facet_index = $line->[I_FACET_INDEX];
        
        do {
            my $next_line;
            if (defined $line->[I_NEXT_FACET_INDEX] && exists $by_facet_index{$line->[I_NEXT_FACET_INDEX]}) {
                $next_line = $lines[$by_facet_index{$line->[I_NEXT_FACET_INDEX]}];
            } elsif (defined $line->[I_B_ID] && exists $by_a_id{$line->[I_B_ID]}) {
                $next_line = $lines[$by_a_id{$line->[I_B_ID]}];
            } else {
                Slic3r::debugf "  line has no next_facet_index or b_id\n";
                $slicing_errors = 1;
                push @failed_loops, [@points] if @points;
                next CYCLE;
            }
            
            if (!$next_line || $visited_lines{$next_line}) {
                Slic3r::debugf "  failed to close this loop\n";
                $slicing_errors = 1;
                push @failed_loops, [@points] if @points;
                next CYCLE;
            } elsif (defined $next_line->[I_PREV_FACET_INDEX] && $next_line->[I_PREV_FACET_INDEX] != $line->[I_FACET_INDEX]) {
                Slic3r::debugf "  wrong prev_facet_index\n";
                $slicing_errors = 1;
                push @failed_loops, [@points] if @points;
                next CYCLE;
            } elsif (defined $next_line->[I_A_ID] && $next_line->[I_A_ID] != $line->[I_B_ID]) {
                Slic3r::debugf "  wrong a_id\n";
                $slicing_errors = 1;
                push @failed_loops, [@points] if @points;
                next CYCLE;
            }
            
            push @points, $next_line->[I_B];
            $visited_lines{$next_line} = 1;
            $line = $next_line;
        } while ($first_facet_index != $line->[I_FACET_INDEX]);
    
        push @polygons, Slic3r::Polygon->new(@points);
        Slic3r::debugf "  Discovered %s polygon of %d points\n",
            ($polygons[-1]->is_counter_clockwise ? 'ccw' : 'cw'), scalar(@points)
            if $Slic3r::debug;
    }
    
    # TODO: we should try to combine failed loops
    for (grep @$_ >= 3, @failed_loops) {
        push @polygons, Slic3r::Polygon->new(@$_);
        Slic3r::debugf "  Discovered failed %s polygon of %d points\n",
            ($polygons[-1]->is_counter_clockwise ? 'ccw' : 'cw'), scalar(@$_)
            if $Slic3r::debug;
    }
    
    return ($slicing_errors, [@polygons]);
}

sub rotate {
    my $self = shift;
    my ($deg, $center) = @_;
    return if $deg == 0;
    
    my $rad = Slic3r::Geometry::deg2rad($deg);
    
    # transform vertex coordinates
    foreach my $vertex (@{$self->vertices}) {
        @$vertex = (@{ +(Slic3r::Geometry::rotate_points($rad, $center, [ $vertex->[X], $vertex->[Y] ]))[0] }, $vertex->[Z]);
    }
}

sub scale {
    my $self = shift;
    my ($factor) = @_;
    return if $factor == 1;
    
    # transform vertex coordinates
    foreach my $vertex (@{$self->vertices}) {
        $vertex->[$_] *= $factor for X,Y,Z;
    }
}

sub move {
    my $self = shift;
    my (@shift) = @_;
    
    # transform vertex coordinates
    foreach my $vertex (@{$self->vertices}) {
        $vertex->[$_] += $shift[$_] || 0 for X,Y,Z;
    }
}

sub align_to_origin {
    my $self = shift;
    
    # calculate the displacements needed to 
    # have lowest value for each axis at coordinate 0
    my $bb = $self->bounding_box;
    $self->move(map -$bb->extents->[$_][MIN], X,Y,Z);
}

sub center_around_origin {
    my $self = shift;
    
    $self->move(map -$_, @{ $self->center });
}

sub center {
    my $self = shift;
    return $self->bounding_box->center;
}

sub duplicate {
    my $self = shift;
    my (@shifts) = @_;
    
    my @new_facets = ();
    foreach my $facet (@{$self->facets}) {
        # transform vertex coordinates
        my ($normal, @vertices) = @$facet;
        foreach my $shift (@shifts) {
            push @new_facets, [ $normal ];
            foreach my $vertex (@vertices) {
                push @{$self->vertices}, [ map $self->vertices->[$vertex][$_] + ($shift->[$_] || 0), (X,Y,Z) ];
                push @{$new_facets[-1]}, $#{$self->vertices};
            }
        }
    }
    push @{$self->facets}, @new_facets;
    $self->BUILD;
}

sub used_vertices {
    my $self = shift;
    return [ map $self->vertices->[$_], map @$_, @{$self->facets} ];
}

sub bounding_box {
    my $self = shift;
    return Slic3r::Geometry::BoundingBox->new_from_points_3D($self->used_vertices);
}

sub size {
    my $self = shift;
    return $self->bounding_box->size;
}

sub slice_facet {
    my $self = shift;
    my ($print_object, $facet_id) = @_;
    my @vertices = @{$self->facets->[$facet_id]}[-3..-1];
    Slic3r::debugf "\n==> FACET %d (%f,%f,%f - %f,%f,%f - %f,%f,%f):\n",
        $facet_id, map @{$self->vertices->[$_]}, @vertices
        if $Slic3r::debug;
    
    # find the vertical extents of the facet
    my @z = map $_->[Z], @{$self->vertices}[@vertices];
    my $min_z = min(@z);
    my $max_z = max(@z);
    Slic3r::debugf "z: min = %.0f, max = %.0f\n", $min_z, $max_z
        if $Slic3r::debug;
    
    if ($max_z == $min_z) {
        Slic3r::debugf "Facet is horizontal; ignoring\n";
        return;
    }
    
    # calculate the layer extents
    my ($min_layer, $max_layer) = $print_object->get_layer_range($min_z, $max_z);
    Slic3r::debugf "layers: min = %s, max = %s\n", $min_layer, $max_layer
        if $Slic3r::debug;
    
    my $lines = {};  # layer_id => [ lines ]
    for my $layer_id ($min_layer .. $max_layer) {
        my $layer = $print_object->layers->[$layer_id];
        $lines->{$layer_id} ||= [];
        push @{ $lines->{$layer_id} }, $self->intersect_facet($facet_id, $layer->slice_z);
    }
    return $lines;
}

sub intersect_facet {
    my $self = shift;
    my ($facet_id, $z) = @_;
    
    my @vertices_ids        = @{$self->facets->[$facet_id]}[-3..-1];
    my %vertices            = map { $_ => $self->vertices->[$_] } @vertices_ids;  # cache vertices
    my @edge_ids            = @{$self->facets_edges->[$facet_id]};
    my @edge_vertices_ids   = $self->_facet_edges($facet_id);
    
    my (@points, @intersection_points, @points_on_layer) = ();
        
    for my $e (0..2) {
        my ($a_id, $b_id)   = @{$edge_vertices_ids[$e]};
        my ($a, $b)         = @vertices{$a_id, $b_id};
        #printf "Az = %f, Bz = %f, z = %f\n", $a->[Z], $b->[Z], $z;
        
        if ($a->[Z] == $b->[Z] && $a->[Z] == $z) {
            # edge is horizontal and belongs to the current layer
            my $edge_type = (grep $vertices{$_}[Z] < $z, @vertices_ids) ? FE_TOP : FE_BOTTOM;
            if ($edge_type == FE_TOP) {
                ($a, $b) = ($b, $a);
                ($a_id, $b_id) = ($b_id, $a_id);
            }
            # We assume that this method is never being called for horizontal
            # facets, so no other edge is going to be on this layer.
            return pack I_FMT, (
                $b->[X], $b->[Y],       # I_B
                $a_id,                  # I_A_ID
                $b_id,                  # I_B_ID
                $facet_id,              # I_FACET_INDEX
                -1,                     # I_PREV_FACET_INDEX
                -1,                     # I_NEXT_FACET_INDEX
                $edge_type,             # I_FACET_EDGE
                
                # Unused data:
                # a             => [$a->[X], $a->[Y]],
            );
            #print "Horizontal edge at $z!\n";
            
        } elsif ($a->[Z] == $z) {
            #print "A point on plane $z!\n";
            push @points, [ $a->[X], $a->[Y], $a_id ];
            push @points_on_layer, $#points;
            
        } elsif ($b->[Z] == $z) {
            #print "B point on plane $z!\n";
            push @points, [ $b->[X], $b->[Y], $b_id ];
            push @points_on_layer, $#points;
            
        } elsif (($a->[Z] < $z && $b->[Z] > $z) || ($b->[Z] < $z && $a->[Z] > $z)) {
            # edge intersects the current layer; calculate intersection
            push @points, [
                $b->[X] + ($a->[X] - $b->[X]) * ($z - $b->[Z]) / ($a->[Z] - $b->[Z]),
                $b->[Y] + ($a->[Y] - $b->[Y]) * ($z - $b->[Z]) / ($a->[Z] - $b->[Z]),
                undef,
                $edge_ids[$e],
            ];
            push @intersection_points, $#points;
            #print "Intersects at $z!\n";
        }
    }
    
    if (@points_on_layer == 2 && @intersection_points == 1) {
        $points[ $points_on_layer[1] ] = undef;
        @points = grep $_, @points;
    }
    if (@points_on_layer == 2 && @intersection_points == 0) {
        if (same_point(map $points[$_], @points_on_layer)) {
            return ();
        }
    }
    
    if (@points) {
        
        # defensive programming:
        die "Facets must intersect each plane 0 or 2 times" if @points != 2;
        
        # connect points:
        my ($prev_facet_index, $next_facet_index) = (undef, undef);
        $prev_facet_index = +(grep $_ != $facet_id, @{$self->edges_facets->[$points[B][3]]})[0]
            if defined $points[B][3];
        $next_facet_index = +(grep $_ != $facet_id, @{$self->edges_facets->[$points[A][3]]})[0]
            if defined $points[A][3];
        
        return pack I_FMT, (
            $points[A][X], $points[A][Y],   # I_B
            $points[B][2] // -1,            # I_A_ID /
            $points[A][2] // -1,            # I_B_ID /
            $facet_id,                      # I_FACET_INDEX
            $prev_facet_index // -1,        # I_PREV_FACET_INDEX  /
            $next_facet_index // -1,        # I_NEXT_FACET_INDEX  /
            -1,                             # I_FACET_EDGE
        );
        #printf "  intersection points at z = %f: %f,%f - %f,%f\n", $z, map @$_, @intersection_points;
    }
    
    return ();
}

sub get_connected_facets {
    my $self = shift;
    my ($facet_id) = @_;
    
    my %facets = ();
    foreach my $edge_id (@{$self->facets_edges->[$facet_id]}) {
        $facets{$_} = 1 for @{$self->edges_facets->[$edge_id]};
    }
    delete $facets{$facet_id};
    return keys %facets;
}

sub split_mesh {
    my $self = shift;
    
    $self->analyze;
    
    my @meshes = ();
    
    # loop while we have remaining facets
    while (1) {
        # get the first facet
        my @facet_queue = ();
        my @facets = ();
        for (my $i = 0; $i <= $#{$self->facets}; $i++) {
            if (defined $self->facets->[$i]) {
                push @facet_queue, $i;
                last;
            }
        }
        last if !@facet_queue;
        
        while (defined (my $facet_id = shift @facet_queue)) {
            next unless defined $self->facets->[$facet_id];
            push @facets, map [ @$_ ], $self->facets->[$facet_id];
            push @facet_queue, $self->get_connected_facets($facet_id);
            $self->facets->[$facet_id] = undef;
        }
        
        my %vertices = map { $_ => 1 } map @$_[-3..-1], @facets;
        my @new_vertices = keys %vertices;
        my %new_vertices = map { $new_vertices[$_] => $_ } 0..$#new_vertices;
        foreach my $facet (@facets) {
            $facet->[$_] = $new_vertices{$facet->[$_]} for -3..-1;
        }
        push @meshes, Slic3r::TriangleMesh->new(
            facets => \@facets,
            vertices => [ map $self->vertices->[$_], keys %vertices ],
        );
    }
    
    return @meshes;
}

sub horizontal_projection {
    my $self = shift;
    
    my @f = ();
    foreach my $facet (@{$self->facets}) {
        push @f, Slic3r::Polygon->new(map [ @{$self->vertices->[$_]}[X,Y] ], @$facet);
    }
    
    my $scale_vector = Math::Clipper::integerize_coordinate_sets({ bits => 32 }, @f);
    $_->make_counter_clockwise for @f;  # do this after scaling, as winding order might change while doing that
    my $union = union_ex([ Slic3r::Geometry::Clipper::offset(\@f, 10000) ]);
    Math::Clipper::unscale_coordinate_sets($scale_vector, $_) for @$union;
    return $union;
}

1;