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

mesh_boolean_convert.cc « intern « blenkernel « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 360c7da2ae21928ef6b763758745acdcaed85fec (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
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
/* SPDX-License-Identifier: GPL-2.0-or-later
 * Copyright 2001-2002 NaN Holding BV. All rights reserved. */

/** \file
 * \ingroup bke
 */

#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"

#include "BKE_attribute.hh"
#include "BKE_customdata.h"
#include "BKE_material.h"
#include "BKE_mesh.h"
#include "BKE_mesh_boolean_convert.hh"

#include "BLI_alloca.h"
#include "BLI_array.hh"
#include "BLI_float4x4.hh"
#include "BLI_math.h"
#include "BLI_math_vec_types.hh"
#include "BLI_mesh_boolean.hh"
#include "BLI_mesh_intersect.hh"
#include "BLI_span.hh"
#include "BLI_task.hh"
#include "BLI_virtual_array.hh"

namespace blender::meshintersect {

#ifdef WITH_GMP

constexpr int estimated_max_facelen = 100; /* Used for initial size of some Vectors. */

/* Snap entries that are near 0 or 1 or -1 to those values.
 * Sometimes Blender's rotation matrices for multiples of 90 degrees have
 * tiny numbers where there should be zeros. That messes makes some things
 * every so slightly non-coplanar when users expect coplanarity,
 * so this is a hack to clean up such matrices.
 * Would be better to change the transformation code itself.
 */
static float4x4 clean_transform(const float4x4 &mat)
{
  float4x4 cleaned;
  const float fuzz = 1e-6f;
  for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 4; j++) {
      float f = mat.values[i][j];
      if (fabsf(f) <= fuzz) {
        f = 0.0f;
      }
      else if (fabsf(f - 1.0f) <= fuzz) {
        f = 1.0f;
      }
      else if (fabsf(f + 1.0f) <= fuzz) {
        f = -1.0f;
      }
      cleaned.values[i][j] = f;
    }
  }
  return cleaned;
}

/* `MeshesToIMeshInfo` keeps track of information used when combining a number
 * of `Mesh`es into a single `IMesh` for doing boolean on.
 * Mostly this means keeping track of the index offsets for various mesh elements. */
class MeshesToIMeshInfo {
 public:
  /* The input meshes, */
  Span<const Mesh *> meshes;
  /* Numbering the vertices of the meshes in order of meshes,
   * at what offset does the vertex range for mesh[i] start? */
  Array<int> mesh_vert_offset;
  /* Similarly for edges of meshes. */
  Array<int> mesh_edge_offset;
  /* Similarly for polys of meshes. */
  Array<int> mesh_poly_offset;
  /* For each Mesh vertex in all the meshes (with concatenated indexing),
   * what is the IMesh Vert* allocated for it in the input IMesh? */
  Array<const Vert *> mesh_to_imesh_vert;
  /* Similarly for each Mesh poly. */
  Array<Face *> mesh_to_imesh_face;
  /* Transformation matrix to transform a coordinate in the corresponding
   * Mesh to the local space of the first Mesh. */
  Array<float4x4> to_target_transform;
  /* For each input mesh, whether or not their transform is negative. */
  Array<bool> has_negative_transform;
  /* For each input mesh, how to remap the material slot numbers to
   * the material slots in the first mesh. */
  Span<Array<short>> material_remaps;
  /* Total number of input mesh vertices. */
  int tot_meshes_verts;
  /* Total number of input mesh edges. */
  int tot_meshes_edges;
  /* Total number of input mesh polys. */
  int tot_meshes_polys;

  int input_mesh_for_imesh_vert(int imesh_v) const;
  int input_mesh_for_imesh_edge(int imesh_e) const;
  int input_mesh_for_imesh_face(int imesh_f) const;
  const MPoly *input_mpoly_for_orig_index(int orig_index,
                                          const Mesh **r_orig_mesh,
                                          int *r_orig_mesh_index,
                                          int *r_index_in_orig_mesh) const;
  const MVert *input_mvert_for_orig_index(int orig_index,
                                          const Mesh **r_orig_mesh,
                                          int *r_index_in_orig_mesh) const;
  const MEdge *input_medge_for_orig_index(int orig_index,
                                          const Mesh **r_orig_mesh,
                                          int *r_index_in_orig_mesh) const;
};

/* Given an index `imesh_v` in the `IMesh`, return the index of the
 * input `Mesh` that contained the `MVert` that it came from. */
int MeshesToIMeshInfo::input_mesh_for_imesh_vert(int imesh_v) const
{
  int n = int(mesh_vert_offset.size());
  for (int i = 0; i < n - 1; ++i) {
    if (imesh_v < mesh_vert_offset[i + 1]) {
      return i;
    }
  }
  return n - 1;
}

/* Given an index `imesh_e` used as an original index in the `IMesh`,
 * return the index of the input `Mesh` that contained the `MVert` that it came from. */
int MeshesToIMeshInfo::input_mesh_for_imesh_edge(int imesh_e) const
{
  int n = int(mesh_edge_offset.size());
  for (int i = 0; i < n - 1; ++i) {
    if (imesh_e < mesh_edge_offset[i + 1]) {
      return i;
    }
  }
  return n - 1;
}

/* Given an index `imesh_f` in the `IMesh`, return the index of the
 * input `Mesh` that contained the `MPoly` that it came from. */
int MeshesToIMeshInfo::input_mesh_for_imesh_face(int imesh_f) const
{
  int n = int(mesh_poly_offset.size());
  for (int i = 0; i < n - 1; ++i) {
    if (imesh_f < mesh_poly_offset[i + 1]) {
      return i;
    }
  }
  return n - 1;
}

/* Given an index of an original face in the `IMesh`, find out the input
 * `Mesh` that it came from and return it in `*r_orig_mesh`,
 * and also return the index of that `Mesh` in  `*r_orig_mesh_index`.
 * Finally, return the index of the corresponding `MPoly` in that `Mesh`
 * in `*r_index_in_orig_mesh`. */
const MPoly *MeshesToIMeshInfo::input_mpoly_for_orig_index(int orig_index,
                                                           const Mesh **r_orig_mesh,
                                                           int *r_orig_mesh_index,
                                                           int *r_index_in_orig_mesh) const
{
  int orig_mesh_index = input_mesh_for_imesh_face(orig_index);
  BLI_assert(0 <= orig_mesh_index && orig_mesh_index < meshes.size());
  const Mesh *me = meshes[orig_mesh_index];
  const Span<MPoly> polys = me->polys();
  int index_in_mesh = orig_index - mesh_poly_offset[orig_mesh_index];
  BLI_assert(0 <= index_in_mesh && index_in_mesh < me->totpoly);
  const MPoly *mp = &polys[index_in_mesh];
  if (r_orig_mesh) {
    *r_orig_mesh = me;
  }
  if (r_orig_mesh_index) {
    *r_orig_mesh_index = orig_mesh_index;
  }
  if (r_index_in_orig_mesh) {
    *r_index_in_orig_mesh = index_in_mesh;
  }
  return mp;
}

/* Given an index of an original vertex in the `IMesh`, find out the input
 * `Mesh` that it came from and return it in `*r_orig_mesh`.
 * Also find the index of the `MVert` in that `Mesh` and return it in
 * `*r_index_in_orig_mesh`. */
const MVert *MeshesToIMeshInfo::input_mvert_for_orig_index(int orig_index,
                                                           const Mesh **r_orig_mesh,
                                                           int *r_index_in_orig_mesh) const
{
  int orig_mesh_index = input_mesh_for_imesh_vert(orig_index);
  BLI_assert(0 <= orig_mesh_index && orig_mesh_index < meshes.size());
  const Mesh *me = meshes[orig_mesh_index];
  const Span<MVert> verts = me->verts();
  int index_in_mesh = orig_index - mesh_vert_offset[orig_mesh_index];
  BLI_assert(0 <= index_in_mesh && index_in_mesh < me->totvert);
  const MVert *mv = &verts[index_in_mesh];
  if (r_orig_mesh) {
    *r_orig_mesh = me;
  }
  if (r_index_in_orig_mesh) {
    *r_index_in_orig_mesh = index_in_mesh;
  }
  return mv;
}

/* Similarly for edges. */
const MEdge *MeshesToIMeshInfo::input_medge_for_orig_index(int orig_index,
                                                           const Mesh **r_orig_mesh,
                                                           int *r_index_in_orig_mesh) const
{
  int orig_mesh_index = input_mesh_for_imesh_edge(orig_index);
  BLI_assert(0 <= orig_mesh_index && orig_mesh_index < meshes.size());
  const Mesh *me = meshes[orig_mesh_index];
  const Span<MEdge> edges = me->edges();
  int index_in_mesh = orig_index - mesh_edge_offset[orig_mesh_index];
  BLI_assert(0 <= index_in_mesh && index_in_mesh < me->totedge);
  const MEdge *medge = &edges[index_in_mesh];
  if (r_orig_mesh) {
    *r_orig_mesh = me;
  }
  if (r_index_in_orig_mesh) {
    *r_index_in_orig_mesh = index_in_mesh;
  }
  return medge;
}

/**
 * Convert all of the meshes in `meshes` to an `IMesh` and return that.
 * All of the coordinates are transformed into the local space of the
 * first Mesh. To do this transformation, we also need the transformation
 * obmats corresponding to the Meshes, so they are in the `obmats` argument.
 * The 'original' indexes in the IMesh are the indexes you get by
 * a scheme that offsets each MVert, MEdge, and MPoly index by the sum of the
 * vertices, edges, and polys in the preceding Meshes in the mesh span.
 * The `*r_info class` is filled in with information needed to make the
 * correspondence between the Mesh MVerts/MPolys and the IMesh Verts/Faces.
 * All allocation of memory for the IMesh comes from `arena`.
 */
static IMesh meshes_to_imesh(Span<const Mesh *> meshes,
                             Span<const float4x4 *> obmats,
                             Span<Array<short>> material_remaps,
                             const float4x4 &target_transform,
                             IMeshArena &arena,
                             MeshesToIMeshInfo *r_info)
{
  int nmeshes = meshes.size();
  BLI_assert(nmeshes > 0);
  r_info->meshes = meshes;
  r_info->tot_meshes_verts = 0;
  r_info->tot_meshes_polys = 0;
  int &totvert = r_info->tot_meshes_verts;
  int &totedge = r_info->tot_meshes_edges;
  int &totpoly = r_info->tot_meshes_polys;
  for (const Mesh *me : meshes) {
    totvert += me->totvert;
    totedge += me->totedge;
    totpoly += me->totpoly;
  }

  /* Estimate the number of vertices and faces in the boolean output,
   * so that the memory arena can reserve some space. It is OK if these
   * estimates are wrong. */
  const int estimate_num_outv = 3 * totvert;
  const int estimate_num_outf = 4 * totpoly;
  arena.reserve(estimate_num_outv, estimate_num_outf);
  r_info->mesh_to_imesh_vert.reinitialize(totvert);
  r_info->mesh_to_imesh_face.reinitialize(totpoly);
  r_info->mesh_vert_offset.reinitialize(nmeshes);
  r_info->mesh_edge_offset.reinitialize(nmeshes);
  r_info->mesh_poly_offset.reinitialize(nmeshes);
  r_info->to_target_transform.reinitialize(nmeshes);
  r_info->has_negative_transform.reinitialize(nmeshes);
  r_info->material_remaps = material_remaps;
  int v = 0;
  int e = 0;
  int f = 0;

  /* Put these Vectors here, with a size unlikely to need resizing,
   * so that the loop to make new Faces will likely not need to allocate
   * over and over. */
  Vector<const Vert *, estimated_max_facelen> face_vert;
  Vector<int, estimated_max_facelen> face_edge_orig;

  /* To convert the coordinates of meshes 1, 2, etc. into the local space
   * of the target, multiply each transform by the inverse of the
   * target matrix. Exact Boolean works better if these matrices are 'cleaned'
   *  -- see the comment for the `clean_transform` function, above. */
  const float4x4 inv_target_mat = clean_transform(target_transform).inverted();

  /* For each input `Mesh`, make `Vert`s and `Face`s for the corresponding
   * `MVert`s and `MPoly`s, and keep track of the original indices (using the
   * concatenating offset scheme) inside the `Vert`s and `Face`s.
   * When making `Face`s, we also put in the original indices for `MEdge`s that
   * make up the `MPoly`s using the same scheme. */
  for (int mi : meshes.index_range()) {
    const Mesh *me = meshes[mi];
    r_info->mesh_vert_offset[mi] = v;
    r_info->mesh_edge_offset[mi] = e;
    r_info->mesh_poly_offset[mi] = f;
    /* Get matrix that transforms a coordinate in meshes[mi]'s local space
     * to the target space. */
    const float4x4 objn_mat = (obmats[mi] == nullptr) ? float4x4::identity() :
                                                        clean_transform(*obmats[mi]);
    r_info->to_target_transform[mi] = inv_target_mat * objn_mat;
    r_info->has_negative_transform[mi] = objn_mat.is_negative();

    /* All meshes 1 and up will be transformed into the local space of operand 0.
     * Historical behavior of the modifier has been to flip the faces of any meshes
     * that would have a negative transform if you do that. */
    bool need_face_flip = r_info->has_negative_transform[mi] != r_info->has_negative_transform[0];

    Vector<Vert *> verts(me->totvert);
    const Span<MVert> mesh_verts = me->verts();
    const Span<MPoly> polys = me->polys();
    const Span<MLoop> loops = me->loops();

    /* Allocate verts
     * Skip the matrix multiplication for each point when there is no transform for a mesh,
     * for example when the first mesh is already in the target space. (Note the logic
     * directly above, which uses an identity matrix with a null input transform). */
    if (obmats[mi] == nullptr) {
      threading::parallel_for(mesh_verts.index_range(), 2048, [&](IndexRange range) {
        float3 co;
        for (int i : range) {
          co = float3(mesh_verts[i].co);
          mpq3 mco = mpq3(co.x, co.y, co.z);
          double3 dco(mco[0].get_d(), mco[1].get_d(), mco[2].get_d());
          verts[i] = new Vert(mco, dco, NO_INDEX, i);
        }
      });
    }
    else {
      threading::parallel_for(mesh_verts.index_range(), 2048, [&](IndexRange range) {
        float3 co;
        for (int i : range) {
          co = r_info->to_target_transform[mi] * float3(mesh_verts[i].co);
          mpq3 mco = mpq3(co.x, co.y, co.z);
          double3 dco(mco[0].get_d(), mco[1].get_d(), mco[2].get_d());
          verts[i] = new Vert(mco, dco, NO_INDEX, i);
        }
      });
    }
    for (int i : mesh_verts.index_range()) {
      r_info->mesh_to_imesh_vert[v] = arena.add_or_find_vert(verts[i]);
      ++v;
    }

    for (const MPoly &poly : polys) {
      int flen = poly.totloop;
      face_vert.resize(flen);
      face_edge_orig.resize(flen);
      const MLoop *l = &loops[poly.loopstart];
      for (int i = 0; i < flen; ++i) {
        int mverti = r_info->mesh_vert_offset[mi] + l->v;
        const Vert *fv = r_info->mesh_to_imesh_vert[mverti];
        if (need_face_flip) {
          face_vert[flen - i - 1] = fv;
          int iedge = i < flen - 1 ? flen - i - 2 : flen - 1;
          face_edge_orig[iedge] = e + l->e;
        }
        else {
          face_vert[i] = fv;
          face_edge_orig[i] = e + l->e;
        }
        ++l;
      }
      r_info->mesh_to_imesh_face[f] = arena.add_face(face_vert, f, face_edge_orig);
      ++f;
    }
    e += me->totedge;
  }
  return IMesh(r_info->mesh_to_imesh_face);
}

/* Copy vertex attributes, including customdata, from `orig_mv` to `mv`.
 * `mv` is in `dest_mesh` with index `mv_index`.
 * The `orig_mv` vertex came from Mesh `orig_me` and had index `index_in_orig_me` there. */
static void copy_vert_attributes(Mesh *dest_mesh,
                                 const Mesh *orig_me,
                                 int mv_index,
                                 int index_in_orig_me)
{
  /* For all layers in the orig mesh, copy the layer information. */
  CustomData *target_cd = &dest_mesh->vdata;
  const CustomData *source_cd = &orig_me->vdata;
  for (int source_layer_i = 0; source_layer_i < source_cd->totlayer; ++source_layer_i) {
    int ty = source_cd->layers[source_layer_i].type;
    /* The (first) CD_MVERT layer is the same as dest_mesh->vdata, so we've
     * already set the coordinate to the right value. */
    if (ty == CD_MVERT) {
      continue;
    }
    const char *name = source_cd->layers[source_layer_i].name;
    int target_layer_i = CustomData_get_named_layer_index(target_cd, ty, name);
    /* Not all layers were merged in target: some are marked CD_FLAG_NOCOPY
     * and some are not in the CD_MASK_MESH.vdata. */
    if (target_layer_i != -1) {
      CustomData_copy_data_layer(
          source_cd, target_cd, source_layer_i, target_layer_i, index_in_orig_me, mv_index, 1);
    }
  }
}

/* Similar to copy_vert_attributes but for poly attributes. */
static void copy_poly_attributes(Mesh *dest_mesh,
                                 MPoly *mp,
                                 const MPoly *orig_mp,
                                 const Mesh *orig_me,
                                 int mp_index,
                                 int index_in_orig_me,
                                 Span<short> material_remap,
                                 MutableSpan<int> dst_material_indices)
{
  const VArray<int> src_material_indices = orig_me->attributes().lookup_or_default<int>(
      "material_index", ATTR_DOMAIN_FACE, 0);
  const int src_index = src_material_indices[index_in_orig_me];
  if (material_remap.size() > 0 && material_remap.index_range().contains(src_index)) {
    dst_material_indices[mp_index] = material_remap[src_index];
  }
  else {
    dst_material_indices[mp_index] = src_index;
  }

  mp->flag = orig_mp->flag;
  CustomData *target_cd = &dest_mesh->pdata;
  const CustomData *source_cd = &orig_me->pdata;
  for (int source_layer_i = 0; source_layer_i < source_cd->totlayer; ++source_layer_i) {
    int ty = source_cd->layers[source_layer_i].type;
    if (ty == CD_MPOLY) {
      continue;
    }
    const char *name = source_cd->layers[source_layer_i].name;
    int target_layer_i = CustomData_get_named_layer_index(target_cd, ty, name);
    if (target_layer_i != -1) {
      CustomData_copy_data_layer(
          source_cd, target_cd, source_layer_i, target_layer_i, index_in_orig_me, mp_index, 1);
    }
  }
}

/* Similar to copy_vert_attributes but for edge attributes. */
static void copy_edge_attributes(Mesh *dest_mesh,
                                 MEdge *medge,
                                 const MEdge *orig_medge,
                                 const Mesh *orig_me,
                                 int medge_index,
                                 int index_in_orig_me)
{
  medge->flag = orig_medge->flag;
  CustomData *target_cd = &dest_mesh->edata;
  const CustomData *source_cd = &orig_me->edata;
  for (int source_layer_i = 0; source_layer_i < source_cd->totlayer; ++source_layer_i) {
    int ty = source_cd->layers[source_layer_i].type;
    if (ty == CD_MEDGE) {
      continue;
    }
    const char *name = source_cd->layers[source_layer_i].name;
    int target_layer_i = CustomData_get_named_layer_index(target_cd, ty, name);
    if (target_layer_i != -1) {
      CustomData_copy_data_layer(
          source_cd, target_cd, source_layer_i, target_layer_i, index_in_orig_me, medge_index, 1);
    }
  }
}

/**
 * For #IMesh face `f`, with corresponding output Mesh poly `mp`,
 * where the original Mesh poly is `orig_mp`, coming from the Mesh
 * `orig_me`, which has index `orig_me_index` in `mim`:
 * fill in the `orig_loops` Array with corresponding indices of MLoops from `orig_me`
 * where they have the same start and end vertices; for cases where that is
 * not true, put -1 in the `orig_loops` slot.
 * For now, we only try to do this if `mp` and `orig_mp` have the same size.
 * Return the number of non-null MLoops filled in.
 */
static int fill_orig_loops(const Face *f,
                           const MPoly *orig_mp,
                           const Mesh *orig_me,
                           int orig_me_index,
                           MeshesToIMeshInfo &mim,
                           MutableSpan<int> r_orig_loops)
{
  r_orig_loops.fill(-1);
  const Span<MLoop> orig_loops = orig_me->loops();

  int orig_mplen = orig_mp->totloop;
  if (f->size() != orig_mplen) {
    return 0;
  }
  BLI_assert(r_orig_loops.size() == orig_mplen);
  /* We'll look for the case where the first vertex in f has an original vertex
   * that is the same as one in orig_me (after correcting for offset in mim meshes).
   * Then see that loop and any subsequent ones have the same start and end vertex.
   * This may miss some cases of partial alignment, but that's OK since discovering
   * aligned loops is only an optimization to avoid some re-interpolation.
   */
  int first_orig_v = f->vert[0]->orig;
  if (first_orig_v == NO_INDEX) {
    return 0;
  }
  /* It is possible that the original vert was merged with another in another mesh. */
  if (orig_me_index != mim.input_mesh_for_imesh_vert(first_orig_v)) {
    return 0;
  }
  int orig_me_vert_offset = mim.mesh_vert_offset[orig_me_index];
  int first_orig_v_in_orig_me = first_orig_v - orig_me_vert_offset;
  BLI_assert(0 <= first_orig_v_in_orig_me && first_orig_v_in_orig_me < orig_me->totvert);
  /* Assume all vertices in an mpoly are unique. */
  int offset = -1;
  for (int i = 0; i < orig_mplen; ++i) {
    int loop_i = i + orig_mp->loopstart;
    if (orig_loops[loop_i].v == first_orig_v_in_orig_me) {
      offset = i;
      break;
    }
  }
  if (offset == -1) {
    return 0;
  }
  int num_orig_loops_found = 0;
  for (int mp_loop_index = 0; mp_loop_index < orig_mplen; ++mp_loop_index) {
    int orig_mp_loop_index = (mp_loop_index + offset) % orig_mplen;
    const MLoop *l = &orig_loops[orig_mp->loopstart + orig_mp_loop_index];
    int fv_orig = f->vert[mp_loop_index]->orig;
    if (fv_orig != NO_INDEX) {
      fv_orig -= orig_me_vert_offset;
      if (fv_orig < 0 || fv_orig >= orig_me->totvert) {
        fv_orig = NO_INDEX;
      }
    }
    if (l->v == fv_orig) {
      const MLoop *lnext =
          &orig_loops[orig_mp->loopstart + ((orig_mp_loop_index + 1) % orig_mplen)];
      int fvnext_orig = f->vert[(mp_loop_index + 1) % orig_mplen]->orig;
      if (fvnext_orig != NO_INDEX) {
        fvnext_orig -= orig_me_vert_offset;
        if (fvnext_orig < 0 || fvnext_orig >= orig_me->totvert) {
          fvnext_orig = NO_INDEX;
        }
      }
      if (lnext->v == fvnext_orig) {
        r_orig_loops[mp_loop_index] = orig_mp->loopstart + orig_mp_loop_index;
        ++num_orig_loops_found;
      }
    }
  }
  return num_orig_loops_found;
}

/* Fill `cos_2d` with the 2d coordinates found by projection MPoly `mp` along
 * its normal. Also fill in r_axis_mat with the matrix that does that projection.
 * But before projecting, also transform the 3d coordinate by multiplying by trans_mat.
 * `cos_2d` should have room for `mp->totloop` entries. */
static void get_poly2d_cos(const Mesh *me,
                           const MPoly *mp,
                           float (*cos_2d)[2],
                           const float4x4 &trans_mat,
                           float r_axis_mat[3][3])
{
  const Span<MVert> verts = me->verts();
  const Span<MLoop> loops = me->loops();
  const Span<MLoop> poly_loops = loops.slice(mp->loopstart, mp->totloop);

  /* Project coordinates to 2d in cos_2d, using normal as projection axis. */
  float axis_dominant[3];
  BKE_mesh_calc_poly_normal(mp, &loops[mp->loopstart], verts.data(), axis_dominant);
  axis_dominant_v3_to_m3(r_axis_mat, axis_dominant);
  for (const int i : poly_loops.index_range()) {
    float3 co = verts[poly_loops[i].v].co;
    co = trans_mat * co;
    mul_v2_m3v3(cos_2d[i], r_axis_mat, co);
  }
}

/* For the loops of `mp`, see if the face is unchanged from `orig_mp`, and if so,
 * copy the Loop attributes from corresponding loops to corresponding loops.
 * Otherwise, interpolate the Loop attributes in the face `orig_mp`. */
static void copy_or_interp_loop_attributes(Mesh *dest_mesh,
                                           const Face *f,
                                           MPoly *mp,
                                           const MPoly *orig_mp,
                                           const Mesh *orig_me,
                                           int orig_me_index,
                                           MeshesToIMeshInfo &mim)
{
  Array<int> orig_loops(mp->totloop);
  int norig = fill_orig_loops(f, orig_mp, orig_me, orig_me_index, mim, orig_loops);
  /* We may need these arrays if we have to interpolate Loop attributes rather than just copy.
   * Right now, trying Array<float[2]> complains, so declare cos_2d a different way. */
  float(*cos_2d)[2];
  Array<float> weights;
  Array<const void *> src_blocks_ofs;
  float axis_mat[3][3];
  if (norig != mp->totloop) {
    /* We will need to interpolate. Make `cos_2d` hold 2d-projected coordinates of `orig_mp`,
     * which are transformed into object 0's local space before projecting.
     * At this point we cannot yet calculate the interpolation weights, as they depend on
     * the coordinate where interpolation is to happen, but we can allocate the needed arrays,
     * so they don't have to be allocated per-layer. */
    cos_2d = (float(*)[2])BLI_array_alloca(cos_2d, orig_mp->totloop);
    weights = Array<float>(orig_mp->totloop);
    src_blocks_ofs = Array<const void *>(orig_mp->totloop);
    get_poly2d_cos(orig_me, orig_mp, cos_2d, mim.to_target_transform[orig_me_index], axis_mat);
  }
  CustomData *target_cd = &dest_mesh->ldata;
  const Span<MVert> dst_verts = dest_mesh->verts();
  const Span<MLoop> dst_loops = dest_mesh->loops();
  for (int i = 0; i < mp->totloop; ++i) {
    int loop_index = mp->loopstart + i;
    int orig_loop_index = norig > 0 ? orig_loops[i] : -1;
    const CustomData *source_cd = &orig_me->ldata;
    if (orig_loop_index == -1) {
      /* Will need interpolation weights for this loop's vertex's coordinates.
       * The coordinate needs to be projected into 2d,  just like the interpolating polygon's
       * coordinates were. The `dest_mesh` coordinates are already in object 0 local space. */
      float co[2];
      mul_v2_m3v3(co, axis_mat, dst_verts[dst_loops[loop_index].v].co);
      interp_weights_poly_v2(weights.data(), cos_2d, orig_mp->totloop, co);
    }
    for (int source_layer_i = 0; source_layer_i < source_cd->totlayer; ++source_layer_i) {
      int ty = source_cd->layers[source_layer_i].type;
      if (ty == CD_MLOOP) {
        continue;
      }
      const char *name = source_cd->layers[source_layer_i].name;
      int target_layer_i = CustomData_get_named_layer_index(target_cd, ty, name);
      if (target_layer_i == -1) {
        continue;
      }
      if (orig_loop_index != -1) {
        CustomData_copy_data_layer(
            source_cd, target_cd, source_layer_i, target_layer_i, orig_loop_index, loop_index, 1);
      }
      else {
        /* NOTE: although CustomData_bmesh_interp_n function has bmesh in its name, nothing about
         * it is BMesh-specific. We can't use CustomData_interp because it assumes that
         * all source layers exist in the dest.
         * A non bmesh version could have the benefit of not copying data into src_blocks_ofs -
         * using the contiguous data instead. TODO: add to the custom data API. */
        int target_layer_type_index = CustomData_get_named_layer(target_cd, ty, name);
        if (!CustomData_layer_has_interp(source_cd, source_layer_i)) {
          continue;
        }
        int source_layer_type_index = source_layer_i - source_cd->typemap[ty];
        BLI_assert(target_layer_type_index != -1 && source_layer_type_index >= 0);
        for (int j = 0; j < orig_mp->totloop; ++j) {
          src_blocks_ofs[j] = CustomData_get_n(
              source_cd, ty, orig_mp->loopstart + j, source_layer_type_index);
        }
        void *dst_block_ofs = CustomData_get_n(target_cd, ty, loop_index, target_layer_type_index);
        CustomData_bmesh_interp_n(target_cd,
                                  src_blocks_ofs.data(),
                                  weights.data(),
                                  nullptr,
                                  orig_mp->totloop,
                                  dst_block_ofs,
                                  target_layer_i);
      }
    }
  }
}

/**
 * Make sure that there are custom data layers in the target mesh
 * corresponding to all target layers in all of the operands after the first.
 * (The target should already have layers for those in the first operand mesh).
 * Edges done separately -- will have to be done later, after edges are made.
 */
static void merge_vertex_loop_poly_customdata_layers(Mesh *target, MeshesToIMeshInfo &mim)
{
  for (int mesh_index = 1; mesh_index < mim.meshes.size(); ++mesh_index) {
    const Mesh *me = mim.meshes[mesh_index];
    if (me->totvert) {
      CustomData_merge(
          &me->vdata, &target->vdata, CD_MASK_MESH.vmask, CD_SET_DEFAULT, target->totvert);
    }
    if (me->totloop) {
      CustomData_merge(
          &me->ldata, &target->ldata, CD_MASK_MESH.lmask, CD_SET_DEFAULT, target->totloop);
    }
    if (me->totpoly) {
      CustomData_merge(
          &me->pdata, &target->pdata, CD_MASK_MESH.pmask, CD_SET_DEFAULT, target->totpoly);
    }
  }
}

static void merge_edge_customdata_layers(Mesh *target, MeshesToIMeshInfo &mim)
{
  for (int mesh_index = 1; mesh_index < mim.meshes.size(); ++mesh_index) {
    const Mesh *me = mim.meshes[mesh_index];
    if (me->totedge) {
      CustomData_merge(
          &me->edata, &target->edata, CD_MASK_MESH.emask, CD_SET_DEFAULT, target->totedge);
    }
  }
}

/**
 * Convert the output IMesh im to a Blender Mesh,
 * using the information in mim to get all the attributes right.
 */
static Mesh *imesh_to_mesh(IMesh *im, MeshesToIMeshInfo &mim)
{
  constexpr int dbg_level = 0;

  im->populate_vert();
  int out_totvert = im->vert_size();
  int out_totpoly = im->face_size();
  int out_totloop = 0;
  for (const Face *f : im->faces()) {
    out_totloop += f->size();
  }
  /* Will calculate edges later. */
  Mesh *result = BKE_mesh_new_nomain_from_template(
      mim.meshes[0], out_totvert, 0, 0, out_totloop, out_totpoly);

  merge_vertex_loop_poly_customdata_layers(result, mim);
  /* Set the vertex coordinate values and other data. */
  MutableSpan<MVert> verts = result->verts_for_write();
  for (int vi : im->vert_index_range()) {
    const Vert *v = im->vert(vi);
    if (v->orig != NO_INDEX) {
      const Mesh *orig_me;
      int index_in_orig_me;
      mim.input_mvert_for_orig_index(v->orig, &orig_me, &index_in_orig_me);
      copy_vert_attributes(result, orig_me, vi, index_in_orig_me);
    }
    MVert *mv = &verts[vi];
    copy_v3fl_v3db(mv->co, v->co);
  }

  /* Set the loopstart and totloop for each output poly,
   * and set the vertices in the appropriate loops. */
  bke::SpanAttributeWriter<int> dst_material_indices =
      result->attributes_for_write().lookup_or_add_for_write_only_span<int>("material_index",
                                                                            ATTR_DOMAIN_FACE);
  int cur_loop_index = 0;
  MutableSpan<MLoop> dst_loops = result->loops_for_write();
  MutableSpan<MPoly> dst_polys = result->polys_for_write();
  MLoop *l = dst_loops.data();
  for (int fi : im->face_index_range()) {
    const Face *f = im->face(fi);
    const Mesh *orig_me;
    int index_in_orig_me;
    int orig_me_index;
    const MPoly *orig_mp = mim.input_mpoly_for_orig_index(
        f->orig, &orig_me, &orig_me_index, &index_in_orig_me);
    MPoly *mp = &dst_polys[fi];
    mp->totloop = f->size();
    mp->loopstart = cur_loop_index;
    for (int j : f->index_range()) {
      const Vert *vf = f->vert[j];
      const int vfi = im->lookup_vert(vf);
      l->v = vfi;
      ++l;
      ++cur_loop_index;
    }

    copy_poly_attributes(result,
                         mp,
                         orig_mp,
                         orig_me,
                         fi,
                         index_in_orig_me,
                         (mim.material_remaps.size() > 0) ?
                             mim.material_remaps[orig_me_index].as_span() :
                             Span<short>(),
                         dst_material_indices.span);
    copy_or_interp_loop_attributes(result, f, mp, orig_mp, orig_me, orig_me_index, mim);
  }
  dst_material_indices.finish();

  /* BKE_mesh_calc_edges will calculate and populate all the
   * MEdges from the MPolys. */
  BKE_mesh_calc_edges(result, false, false);
  merge_edge_customdata_layers(result, mim);

  /* Now that the MEdges are populated, we can copy over the required attributes and custom layers.
   */
  MutableSpan<MEdge> edges = result->edges_for_write();
  for (int fi : im->face_index_range()) {
    const Face *f = im->face(fi);
    const MPoly *mp = &dst_polys[fi];
    for (int j : f->index_range()) {
      if (f->edge_orig[j] != NO_INDEX) {
        const Mesh *orig_me;
        int index_in_orig_me;
        const MEdge *orig_medge = mim.input_medge_for_orig_index(
            f->edge_orig[j], &orig_me, &index_in_orig_me);
        int e_index = dst_loops[mp->loopstart + j].e;
        MEdge *medge = &edges[e_index];
        copy_edge_attributes(result, medge, orig_medge, orig_me, e_index, index_in_orig_me);
      }
    }
  }

  if (dbg_level > 0) {
    BKE_mesh_validate(result, true, true);
  }
  return result;
}

#endif  // WITH_GMP

Mesh *direct_mesh_boolean(Span<const Mesh *> meshes,
                          Span<const float4x4 *> transforms,
                          const float4x4 &target_transform,
                          Span<Array<short>> material_remaps,
                          const bool use_self,
                          const bool hole_tolerant,
                          const int boolean_mode,
                          Vector<int> *r_intersecting_edges)
{
#ifdef WITH_GMP
  BLI_assert(meshes.size() == transforms.size());
  BLI_assert(material_remaps.size() == 0 || material_remaps.size() == meshes.size());
  if (meshes.size() <= 0) {
    return nullptr;
  }

  const int dbg_level = 0;
  if (dbg_level > 0) {
    std::cout << "\nDIRECT_MESH_INTERSECT, nmeshes = " << meshes.size() << "\n";
  }
  MeshesToIMeshInfo mim;
  IMeshArena arena;
  IMesh m_in = meshes_to_imesh(meshes, transforms, material_remaps, target_transform, arena, &mim);
  std::function<int(int)> shape_fn = [&mim](int f) {
    for (int mi = 0; mi < mim.mesh_poly_offset.size() - 1; ++mi) {
      if (f < mim.mesh_poly_offset[mi + 1]) {
        return mi;
      }
    }
    return int(mim.mesh_poly_offset.size()) - 1;
  };
  IMesh m_out = boolean_mesh(m_in,
                             static_cast<BoolOpType>(boolean_mode),
                             meshes.size(),
                             shape_fn,
                             use_self,
                             hole_tolerant,
                             nullptr,
                             &arena);
  if (dbg_level > 0) {
    std::cout << m_out;
    write_obj_mesh(m_out, "m_out");
  }

  Mesh *result = imesh_to_mesh(&m_out, mim);

  /* Store intersecting edge indices. */
  if (r_intersecting_edges != nullptr) {
    const Span<MPoly> polys = result->polys();
    const Span<MLoop> loops = result->loops();
    for (int fi : m_out.face_index_range()) {
      const Face &face = *m_out.face(fi);
      const MPoly &poly = polys[fi];
      for (int corner_i : face.index_range()) {
        if (face.is_intersect[corner_i]) {
          int e_index = loops[poly.loopstart + corner_i].e;
          r_intersecting_edges->append(e_index);
        }
      }
    }
  }

  return result;
#else   // WITH_GMP
  UNUSED_VARS(meshes,
              transforms,
              material_remaps,
              target_transform,
              use_self,
              hole_tolerant,
              boolean_mode,
              r_intersecting_edges);
  return nullptr;
#endif  // WITH_GMP
}

}  // namespace blender::meshintersect