-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathregions.py
More file actions
4377 lines (3531 loc) · 157 KB
/
Copy pathregions.py
File metadata and controls
4377 lines (3531 loc) · 157 KB
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
"""Objects representing regions in space.
Manipulations of polygons and line segments are done using the
`shapely <https://github.com/shapely/shapely>`_ package.
Manipulations of meshes is done using the
`trimesh <https://trimsh.org/>`_ package.
"""
from abc import ABC, abstractmethod
import itertools
import math
import random
import warnings
import fcl
import numpy
import scipy
import shapely
import shapely.geometry
from shapely.geometry import MultiPolygon
import shapely.ops
import trimesh
from trimesh.transformations import (
compose_matrix,
identity_matrix,
quaternion_matrix,
transform_points,
translation_matrix,
)
import trimesh.voxel
warnings.filterwarnings(
"ignore", module="trimesh"
) # temporarily suppress annoying warnings
from scenic.core.distributions import (
RejectionException,
Samplable,
distributionFunction,
distributionMethod,
needsLazyEvaluation,
needsSampling,
toDistribution,
)
from scenic.core.geometry import (
averageVectors,
cos,
findMinMax,
headingOfSegment,
hypot,
makeShapelyPoint,
plotPolygon,
pointIsInCone,
polygonUnion,
sin,
triangulatePolygon,
)
from scenic.core.lazy_eval import isLazy, valueInContext
from scenic.core.type_support import toOrientation, toScalar, toVector
from scenic.core.utils import (
cached,
cached_method,
cached_property,
findMeshInteriorPoint,
unifyMesh,
)
from scenic.core.vectors import (
Orientation,
OrientedVector,
Vector,
VectorDistribution,
VectorField,
)
###################################################################################################
# Abstract Classes and Utilities
###################################################################################################
class Region(Samplable, ABC):
"""An abstract base class for Scenic Regions"""
def __init__(self, name, *dependencies, orientation=None):
super().__init__(dependencies)
self.name = name
self.orientation = orientation
## Abstract Methods ##
@abstractmethod
def uniformPointInner(self):
"""Do the actual random sampling. Implemented by subclasses."""
pass
@abstractmethod
def containsPoint(self, point) -> bool:
"""Check if the `Region` contains a point. Implemented by subclasses."""
pass
@abstractmethod
def containsObject(self, obj) -> bool:
"""Check if the `Region` contains an :obj:`~scenic.core.object_types.Object`"""
pass
@abstractmethod
def containsRegionInner(self, reg, tolerance) -> bool:
"""Check if the `Region` contains a `Region`"""
pass
@abstractmethod
def distanceTo(self, point) -> float:
"""Distance to this region from a given point."""
pass
@abstractmethod
def projectVector(self, point, onDirection):
"""Returns point projected onto this region along onDirection."""
pass
@property
@abstractmethod
def AABB(self):
"""Axis-aligned bounding box for this `Region`."""
pass
## Overridable Methods ##
# The following methods can be overriden to get better performance or if the region
# has dependencies (in the case of sampleGiven).
@property
def dimensionality(self):
return None
@property
def size(self):
return None
def intersects(self, other, triedReversed=False) -> bool:
"""intersects(other)
Check if this `Region` intersects another.
"""
if triedReversed:
# Last ditch attempt. Try computing intersection and see if we get a
# fixed result back.
intersection = self.intersect(other)
if isinstance(intersection, IntersectionRegion):
raise NotImplementedError(
f"Cannot check intersection of {type(self).__name__} and {type(other).__name__}"
)
elif isinstance(intersection, EmptyRegion):
return False
else:
return True
else:
return other.intersects(self, triedReversed=True)
def intersect(self, other, triedReversed=False) -> "Region":
"""Get a `Region` representing the intersection of this one with another.
If both regions have a :term:`preferred orientation`, the one of ``self``
is inherited by the intersection.
"""
if triedReversed:
orientation = orientationFor(self, other, triedReversed)
return IntersectionRegion(self, other, orientation=orientation)
else:
return other.intersect(self, triedReversed=True)
def union(self, other, triedReversed=False) -> "Region":
"""Get a `Region` representing the union of this one with another.
Not supported by all region types.
"""
if triedReversed:
return UnionRegion(self, other)
else:
return other.union(self, triedReversed=True)
def difference(self, other) -> "Region":
"""Get a `Region` representing the difference of this one and another.
Not supported by all region types.
"""
if isinstance(other, EmptyRegion):
return self
elif isinstance(other, AllRegion):
return nowhere
return DifferenceRegion(self, other)
def sampleGiven(self, value):
return self
def _trueContainsPoint(self, point) -> bool:
"""Whether or not this region could produce point when sampled.
By default this method calls `containsPoint`, but should be overwritten if
`containsPoint` does not properly represent the points that can be sampled.
"""
return self.containsPoint(point)
## Generic Methods (not to be overriden by subclasses) ##
@cached_method
def containsRegion(self, reg, tolerance=0):
# Default behavior for AllRegion and EmptyRegion
if type(self) is AllRegion or type(reg) is EmptyRegion:
return True
if type(self) is EmptyRegion or type(reg) is AllRegion:
return False
# Fast checks based off of dimensionality and size
if self.dimensionality is not None and reg.dimensionality is not None:
# A lower dimensional region cannot contain a higher dimensional region.
if self.dimensionality < reg.dimensionality:
return False
if self.size is not None and reg.size is not None:
# A smaller region cannot contain a larger region of the
# same dimensionality.
if self.dimensionality == reg.dimensionality and self.size < reg.size:
return False
return self.containsRegionInner(reg, tolerance)
@staticmethod
def uniformPointIn(region, tag=None):
"""Get a uniform `Distribution` over points in a `Region`."""
return PointInRegionDistribution(region, tag=tag)
def __contains__(self, thing) -> bool:
"""Check if this `Region` contains an object or vector."""
from scenic.core.object_types import Object
if isinstance(thing, Object):
return self.containsObject(thing)
vec = toVector(thing, '"X in Y" with X not an Object or a vector')
return self.containsPoint(vec)
def orient(self, vec):
"""Orient the given vector along the region's orientation, if any."""
if self.orientation is None:
return vec
else:
return OrientedVector(vec.x, vec.y, vec.z, self.orientation[vec])
def __str__(self):
s = f"<{type(self).__name__}"
if self.name:
s += f" {self.name}"
return s + ">"
def __repr__(self):
s = f"<{type(self).__name__}"
if self.name:
s += f" {self.name}"
return s + f" at {hex(id(self))}>"
class PointInRegionDistribution(VectorDistribution):
"""Uniform distribution over points in a Region"""
def __init__(self, region, tag=None):
super().__init__(region)
self.region = region
self.tag = tag
def sampleGiven(self, value):
return value[self.region].uniformPointInner()
@property
def heading(self):
if self.region.orientation is not None:
return self.region.orientation[self]
else:
return 0
@property
def z(self) -> float:
# Simplify expression forest in some cases where z is known.
reg = self.region
if isinstance(reg, (GridRegion, PolylineRegion)):
return 0.0
if isinstance(reg, PolygonalRegion):
return reg.z
return super().z
def __repr__(self):
return f"PointIn({self.region!r})"
###################################################################################################
# Utility Regions and Functions
###################################################################################################
class AllRegion(Region):
"""Region consisting of all space."""
def intersect(self, other, triedReversed=False):
return other
def intersects(self, other, triedReversed=False):
return not isinstance(other, EmptyRegion)
def union(self, other, triedReversed=False):
return self
def uniformPointInner(self):
raise RuntimeError(f"Attempted to sample from everywhere (AllRegion)")
def containsPoint(self, point):
return True
def containsObject(self, obj):
return True
def containsRegionInner(self, reg, tolerance):
assert False
def distanceTo(self, point):
return 0
def projectVector(self, point, onDirection):
return point
@property
def AABB(self):
raise TypeError("AllRegion does not have a well defined AABB")
@property
def dimensionality(self):
return float("inf")
@property
def size(self):
return float("inf")
def __eq__(self, other):
return type(other) is AllRegion
def __hash__(self):
return hash(AllRegion)
class EmptyRegion(Region):
"""Region containing no points."""
def intersect(self, other, triedReversed=False):
return self
def intersects(self, other, triedReversed=False):
return False
def difference(self, other):
return self
def union(self, other, triedReversed=False):
return other
def uniformPointInner(self):
raise RejectionException(f"sampling empty Region")
def containsPoint(self, point):
return False
def containsObject(self, obj):
return False
def containsRegionInner(self, reg, tolerance):
assert False
def distanceTo(self, point):
return float("inf")
def projectVector(self, point, onDirection):
raise RejectionException("Projecting vector onto empty Region")
@property
def AABB(self):
raise TypeError("EmptyRegion does not have a well defined AABB")
@property
def dimensionality(self):
return 0
@property
def size(self):
return 0
def show(self, plt, style=None, **kwargs):
pass
def __eq__(self, other):
return type(other) is EmptyRegion
def __hash__(self):
return hash(EmptyRegion)
#: A `Region` containing all points.
#:
#: Points may not be sampled from this region, as no uniform distribution over it exists.
everywhere = AllRegion("everywhere")
#: A `Region` containing no points.
#:
#: Attempting to sample from this region causes the sample to be rejected.
nowhere = EmptyRegion("nowhere")
class IntersectionRegion(Region):
def __init__(self, *regions, orientation=None, sampler=None, name=None):
self.regions = tuple(regions)
if len(self.regions) < 2:
raise ValueError("tried to take intersection of fewer than 2 regions")
super().__init__(name, *self.regions, orientation=orientation)
self.sampler = sampler
def sampleGiven(self, value):
regs = [value[reg] for reg in self.regions]
# Now that regions have been sampled, attempt intersection again in the hopes
# there is a specialized sampler to handle it (unless we already have one)
if not self.sampler:
failed = False
intersection = regs[0]
for region in regs[1:]:
intersection = intersection.intersect(region)
if isinstance(intersection, IntersectionRegion):
failed = True
break
if not failed:
intersection.orientation = value[self.orientation]
return intersection
return IntersectionRegion(
*regs,
orientation=value[self.orientation],
sampler=self.sampler,
name=self.name,
)
def evaluateInner(self, context):
regs = (valueInContext(reg, context) for reg in self.regions)
orientation = valueInContext(self.orientation, context)
return IntersectionRegion(
*regs, orientation=orientation, sampler=self.sampler, name=self.name
)
def containsPoint(self, point):
return all(region.containsPoint(point) for region in self.footprint.regions)
def containsObject(self, obj):
return all(region.containsObject(obj) for region in self.footprint.regions)
def containsRegionInner(self, reg, tolerance):
return all(region.containsRegion(reg, tolerance) for region in self.regions)
def distanceTo(self, point):
raise NotImplementedError
def projectVector(self, point, onDirection):
raise NotImplementedError(
f'{type(self).__name__} does not yet support projection using "on"'
)
@property
def AABB(self):
raise NotImplementedError
@cached_property
def footprint(self):
return convertToFootprint(self)
def uniformPointInner(self):
sampler = self.sampler
if not sampler:
sampler = self.genericSampler
return self.orient(sampler(self))
@staticmethod
def genericSampler(intersection):
regs = intersection.regions
# Filter out all regions with known dimensionality greater than the minimum
known_dim_regions = [
r.dimensionality for r in regs if r.dimensionality is not None
]
min_dim = min(known_dim_regions) if known_dim_regions else float("inf")
sampling_regions = [
r for r in regs if r.dimensionality is None or r.dimensionality <= min_dim
]
# Try to sample a point from all sampling regions
num_regs_undefined = 0
for reg in sampling_regions:
try:
point = reg.uniformPointInner()
except UndefinedSamplingException:
num_regs_undefined += 1
continue
except RejectionException:
continue
if all(region._trueContainsPoint(point) for region in regs):
return point
# No points were successfully sampled.
# If all regions were undefined for sampling, raise the appropriate exception.
# Otherwise, reject.
if num_regs_undefined == len(sampling_regions):
# All regions do not support sampling, so the
# intersection doesn't either.
raise UndefinedSamplingException(
f"All regions in {sampling_regions}"
" do not support sampling, so the intersection doesn't either."
)
raise RejectionException(f"sampling intersection of Regions {regs}")
def __repr__(self):
return f"IntersectionRegion({self.regions!r})"
def sampleSurfaceInVolume(intersection):
"""Sample from the intersection of a MeshSurfaceRegion and a MeshVolumeRegion.
This is a specialized sampler for surface-volume intersections. It does not
compute an exact clipped surface; instead it filters surface triangles using
triangle/volume bounding-box overlap, samples a batch of points from the filtered
surface, and keeps the first point that lies inside the volume.
"""
regs = intersection.regions
if len(regs) != 2:
return IntersectionRegion.genericSampler(intersection)
regA, regB = regs
# Only handle the specific surface-volume case here; otherwise fall back
# to the generic intersection sampler.
if isinstance(regA, MeshSurfaceRegion) and isinstance(regB, MeshVolumeRegion):
surface, volume = regA, regB
elif isinstance(regB, MeshSurfaceRegion) and isinstance(regA, MeshVolumeRegion):
surface, volume = regB, regA
else:
return IntersectionRegion.genericSampler(intersection)
mesh = surface.mesh
if mesh.is_empty or len(mesh.faces) == 0:
raise RejectionException(f"sampling intersection of Regions {regs}")
vol_min, vol_max = volume.mesh.bounds
triangles = mesh.triangles
tri_mins = triangles.min(axis=1)
tri_maxs = triangles.max(axis=1)
# Keep only triangles whose axis-aligned bounding boxes overlap the
# volume's bounding box. This is a conservative coarse filter: it may keep
# triangles that do not actually intersect the volume, but should not throw
# away triangles that could.
mask = numpy.all(tri_maxs >= vol_min, axis=1) & numpy.all(tri_mins <= vol_max, axis=1)
if not numpy.any(mask):
raise RejectionException(f"sampling intersection of Regions {regs}")
filtered_mesh = mesh.copy(include_visual=False)
filtered_mesh.faces = filtered_mesh.faces[mask]
filtered_mesh.remove_unreferenced_vertices()
if filtered_mesh.is_empty or len(filtered_mesh.faces) == 0:
raise RejectionException(f"sampling intersection of Regions {regs}")
points, _ = trimesh.sample.sample_surface(filtered_mesh, 20)
pq = trimesh.proximity.ProximityQuery(volume.mesh)
signed_distances = pq.signed_distance(points)
inside = signed_distances >= -volume.tolerance
valid_points = points[inside]
if len(valid_points) > 0:
return Vector(*valid_points[0])
raise RejectionException(f"sampling intersection of Regions {regs}")
class UnionRegion(Region):
def __init__(self, *regions, orientation=None, sampler=None, name=None):
self.regions = tuple(regions)
if len(self.regions) < 2:
raise ValueError("tried to take union of fewer than 2 regions")
super().__init__(name, *self.regions, orientation=orientation)
self.sampler = sampler
def sampleGiven(self, value):
regs = [value[reg] for reg in self.regions]
# Now that regions have been sampled, attempt union again in the hopes
# there is a specialized sampler to handle it (unless we already have one)
if not self.sampler:
failed = False
union = regs[0]
for region in regs[1:]:
union = union.union(region)
if isinstance(union, UnionRegion):
failed = True
break
if not failed:
union.orientation = value[self.orientation]
return union
return UnionRegion(
*regs,
orientation=value[self.orientation],
sampler=self.sampler,
name=self.name,
)
def evaluateInner(self, context):
regs = (valueInContext(reg, context) for reg in self.regions)
orientation = valueInContext(self.orientation, context)
return UnionRegion(
*regs, orientation=orientation, sampler=self.sampler, name=self.name
)
def containsPoint(self, point):
return any(region.containsPoint(point) for region in self.footprint.regions)
def containsObject(self, obj):
raise NotImplementedError
def containsRegionInner(self, reg, tolerance):
raise NotImplementedError
def distanceTo(self, point):
raise NotImplementedError
def projectVector(self, point, onDirection):
raise NotImplementedError(
f'{type(self).__name__} does not yet support projection using "on"'
)
@property
def AABB(self):
raise NotImplementedError
@cached_property
def footprint(self):
return convertToFootprint(self)
def uniformPointInner(self):
sampler = self.sampler
if not sampler:
sampler = self.genericSampler
return self.orient(sampler(self))
@staticmethod
def genericSampler(union):
regs = union.regions
# Check that all regions have well defined dimensionality
if any(reg.dimensionality is None for reg in regs):
raise UndefinedSamplingException(
f"cannot sample union of Regions {regs} with " "undefined dimensionality"
)
# Filter out all regions with 0 probability
max_dim = max(reg.dimensionality for reg in regs)
large_regs = tuple(reg for reg in regs if reg.dimensionality == max_dim)
# Check that all large regions have well defined size
if any(reg.size is None or reg.size == float("inf") for reg in large_regs):
raise UndefinedSamplingException(
f"cannot sample union of Regions {regs} with " "ill-defined size"
)
# Pick a sample, weighted by region size
reg_sizes = tuple(reg.size for reg in large_regs)
target_reg = random.choices(large_regs, weights=reg_sizes)[0]
point = target_reg.uniformPointInner()
# Potentially reject based on containment of the sample
containment_count = sum(int(reg._trueContainsPoint(point)) for reg in regs)
if random.random() < 1 - 1 / containment_count:
raise RejectionException("rejected sample from UnionRegion")
return point
def __repr__(self):
return f"UnionRegion({self.regions!r})"
class DifferenceRegion(Region):
def __init__(self, regionA, regionB, sampler=None, name=None):
self.regionA, self.regionB = regionA, regionB
super().__init__(name, regionA, regionB, orientation=regionA.orientation)
self.sampler = sampler
def sampleGiven(self, value):
regionA, regionB = value[self.regionA], value[self.regionB]
# Now that regions have been sampled, attempt difference again in the hopes
# there is a specialized sampler to handle it (unless we already have one)
if not self.sampler:
diff = regionA.difference(regionB)
if not isinstance(diff, DifferenceRegion):
diff.orientation = value[self.orientation]
return diff
return DifferenceRegion(regionA, regionB, sampler=self.sampler, name=self.name)
def evaluateInner(self, context):
regionA = valueInContext(self.regionA, context)
regionB = valueInContext(self.regionB, context)
orientation = valueInContext(self.orientation, context)
return DifferenceRegion(
regionA,
regionB,
orientation=orientation,
sampler=self.sampler,
name=self.name,
)
def containsPoint(self, point):
return self.footprint.regionA.containsPoint(
point
) and not self.footprint.regionB.containsPoint(point)
def containsObject(self, obj):
return self.footprint.regionA.containsObject(
obj
) and not self.footprint.regionB.intersects(obj.occupiedSpace)
def containsRegionInner(self, reg, tolerance):
raise NotImplementedError
def distanceTo(self, point):
raise NotImplementedError
def projectVector(self, point, onDirection):
raise NotImplementedError(
f'{type(self).__name__} does not yet support projection using "on"'
)
@property
def AABB(self):
raise NotImplementedError
@cached_property
def footprint(self):
return convertToFootprint(self)
def uniformPointInner(self):
sampler = self.sampler
if not sampler:
sampler = self.genericSampler
return self.orient(sampler(self))
@staticmethod
def genericSampler(difference):
regionA, regionB = difference.regionA, difference.regionB
point = regionA.uniformPointInner()
if regionB._trueContainsPoint(point):
raise RejectionException(
f"sampling difference of Regions {regionA} and {regionB}"
)
return point
def __repr__(self):
return f"DifferenceRegion({self.regionA!r}, {self.regionB!r})"
def toPolygon(thing):
if needsSampling(thing):
return None
if hasattr(thing, "polygon"):
poly = thing.polygon
elif hasattr(thing, "polygons"):
poly = thing.polygons
elif hasattr(thing, "lineString"):
poly = thing.lineString
else:
return None
return poly
def regionFromShapelyObject(obj, orientation=None):
"""Build a 'Region' from Shapely geometry."""
assert obj.is_valid, obj
if obj.is_empty:
return nowhere
elif isinstance(obj, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)):
return PolygonalRegion(polygon=obj, orientation=orientation)
elif isinstance(obj, (shapely.geometry.LineString, shapely.geometry.MultiLineString)):
return PolylineRegion(polyline=obj, orientation=orientation)
elif isinstance(obj, shapely.geometry.MultiPoint):
points = [pt.coords[0] for pt in obj.geoms]
return PointSetRegion("PointSet", points, orientation=orientation)
elif isinstance(obj, shapely.geometry.Point):
return PointSetRegion("PointSet", obj.coords, orientation=orientation)
else:
raise TypeError(f"unhandled type of Shapely geometry: {obj}")
def orientationFor(first, second, reversed):
o1 = first.orientation
o2 = second.orientation
if reversed:
o1, o2 = o2, o1
if not o1:
o1 = o2
return o1
class UndefinedSamplingException(Exception):
pass
###################################################################################################
# 3D Regions
###################################################################################################
class SurfaceCollisionTrimesh(trimesh.Trimesh):
"""A Trimesh object that always returns non-convex.
Used so that fcl doesn't find collision without an actual surface
intersection.
"""
@property
def is_convex(self):
return False
class MeshRegion(Region):
"""Region given by a scaled, positioned, and rotated mesh.
This is an abstract class and cannot be instantiated directly. Instead a subclass should be used, like
`MeshVolumeRegion` or `MeshSurfaceRegion`.
The mesh is first placed so the origin is at the center of the bounding box (unless ``centerMesh`` is ``False``).
The mesh is scaled to ``dimensions``, translated so the center of the bounding box of the mesh is at ``positon``,
and then rotated to ``rotation``.
Meshes are centered by default (since ``centerMesh`` is true by default). If you disable this operation, do note
that scaling and rotation transformations may not behave as expected, since they are performed around the origin.
Args:
mesh: The base mesh for this MeshRegion.
name: An optional name to help with debugging.
dimensions: An optional 3-tuple, with the values representing width, length, height respectively.
The mesh will be scaled such that the bounding box for the mesh has these dimensions.
position: An optional position, which determines where the center of the region will be.
rotation: An optional Orientation object which determines the rotation of the object in space.
orientation: An optional vector field describing the preferred orientation at every point in
the region.
tolerance: Tolerance for internal computations.
centerMesh: Whether or not to center the mesh after copying and before transformations.
onDirection: The direction to use if an object being placed on this region doesn't specify one.
additionalDeps: Any additional sampling dependencies this region relies on.
"""
def __init__(
self,
mesh,
dimensions=None,
position=None,
rotation=None,
orientation=None,
tolerance=1e-6,
centerMesh=True,
onDirection=None,
name=None,
additionalDeps=[],
):
# Copy parameters
self._mesh = mesh
self.dimensions = None if dimensions is None else toVector(dimensions)
self.position = Vector(0, 0, 0) if position is None else toVector(position)
self.rotation = None if rotation is None else toOrientation(rotation)
self.orientation = None if orientation is None else toDistribution(orientation)
self.tolerance = tolerance
self.centerMesh = centerMesh
self.onDirection = onDirection
# Initialize superclass with samplables
super().__init__(
name,
self._mesh,
self.dimensions,
self.position,
self.rotation,
*additionalDeps,
orientation=orientation,
)
# If our region isn't fixed yet, then compute other values later
if isLazy(self):
return
if not isinstance(mesh, (trimesh.primitives.Primitive, trimesh.base.Trimesh)):
raise TypeError(
f"Got unexpected mesh parameter of type {type(mesh).__name__}"
)
# Apply scaling, rotation, and translation, if any
if self.rotation is not None:
angles = self.rotation._trimeshEulerAngles()
else:
angles = None
self._rigidTransform = compose_matrix(angles=angles, translate=self.position)
self.orientation = orientation
@classmethod
def fromFile(cls, path, unify=True, **kwargs):
"""Load a mesh region from a file, attempting to infer filetype and compression.
For example: "foo.obj.bz2" is assumed to be a compressed .obj file.
"foo.obj" is assumed to be an uncompressed .obj file. "foo" is an
unknown filetype, so unless a filetype is provided an exception will be raised.
Args:
path (str): Path to the file to import.
filetype (str): Filetype of file to be imported. This will be inferred if not provided.
The filetype must be one compatible with `trimesh.load`.
compressed (bool): Whether or not this file is compressed (with bz2). This will be inferred
if not provided.
binary (bool): Whether or not to open the file as a binary file.
unify (bool): Whether or not to attempt to unify this mesh.
kwargs: Additional arguments to the MeshRegion initializer.
"""
mesh = trimesh.load(path, force="mesh")
if unify and issubclass(cls, MeshVolumeRegion):
mesh = unifyMesh(mesh, verbose=True)
return cls(mesh=mesh, **kwargs)
## Lazy Construction Methods ##
def sampleGiven(self, value):
if isinstance(self, MeshVolumeRegion):
cls = MeshVolumeRegion
elif isinstance(self, MeshSurfaceRegion):
cls = MeshSurfaceRegion
else:
assert False
return cls(
mesh=value[self._mesh],
dimensions=value[self.dimensions],
position=value[self.position],
rotation=value[self.rotation],
orientation=(
True
if self.__dict__.get("_usingDefaultOrientation", False)
else value[self.orientation]
),
tolerance=self.tolerance,
centerMesh=self.centerMesh,
onDirection=self.onDirection,
name=self.name,
)
def evaluateInner(self, context):
if isinstance(self, MeshVolumeRegion):
cls = MeshVolumeRegion
elif isinstance(self, MeshSurfaceRegion):
cls = MeshSurfaceRegion
else:
assert False
mesh = valueInContext(self._mesh, context)
dimensions = valueInContext(self.dimensions, context)
position = valueInContext(self.position, context)
rotation = valueInContext(self.rotation, context)
orientation = (
True
if self.__dict__.get("_usingDefaultOrientation", False)
else valueInContext(self.orientation, context)
)
return cls(
mesh,
dimensions,
position,
rotation,
orientation,
tolerance=self.tolerance,
centerMesh=self.centerMesh,
onDirection=self.onDirection,
name=self.name,
)
## API Methods ##
@cached_property
@distributionFunction
def mesh(self):
mesh = self._mesh
# Convert/extract mesh
if isinstance(mesh, trimesh.primitives.Primitive):