-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathuser_objects.cc
More file actions
8508 lines (6848 loc) · 225 KB
/
user_objects.cc
File metadata and controls
8508 lines (6848 loc) · 225 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
// Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "user/user_objects.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <new>
#include <optional>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include "lodepng.h"
#include "cc/array_safety.h"
#include "engine/engine_passive.h"
#include "engine/engine_support.h"
#include <mujoco/mjspec.h>
#include <mujoco/mujoco.h>
#include "user/user_api.h"
#include "user/user_cache.h"
#include "user/user_model.h"
#include "user/user_resource.h"
#include "user/user_util.h"
namespace {
namespace mju = ::mujoco::util;
using mujoco::user::FilePath;
class PNGImage {
public:
static PNGImage Load(const mjCBase* obj, mjResource* resource,
LodePNGColorType color_type);
int Width() const { return width_; }
int Height() const { return height_; }
bool IsSRGB() const { return is_srgb_; }
std::byte operator[] (int i) const { return data_[i]; }
mjByteVec&& MoveData() && { return std::move(data_); }
private:
std::size_t Size() const {
return data_.size() + (3 * sizeof(int));
}
int width_;
int height_;
bool is_srgb_;
LodePNGColorType color_type_;
mjByteVec data_;
};
PNGImage PNGImage::Load(const mjCBase* obj, mjResource* resource,
LodePNGColorType color_type) {
PNGImage image;
image.color_type_ = color_type;
// open PNG resource
const unsigned char* buffer;
int nbuffer = mju_readResource(resource, (const void**) &buffer);
if (nbuffer < 0) {
throw mjCError(obj, "could not read PNG file '%s'", resource->name);
}
if (!nbuffer) {
throw mjCError(obj, "empty PNG file '%s'", resource->name);
}
// decode PNG from buffer
unsigned int w, h;
lodepng::State state;
state.info_raw.colortype = image.color_type_;
state.info_raw.bitdepth = 8;
unsigned char* data_ptr = nullptr;
unsigned err = lodepng_decode(&data_ptr, &w, &h, &state, buffer, nbuffer);
struct free_delete {
void operator()(unsigned char* ptr) const { std::free(ptr); }
};
std::unique_ptr<unsigned char, free_delete> data{data_ptr};
// check for errors
if (err) {
std::stringstream ss;
ss << "error decoding PNG file '" << resource->name << "': " << lodepng_error_text(err);
throw mjCError(obj, "%s", ss.str().c_str());
}
if (data) {
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
image.data_.insert(image.data_.end(),
reinterpret_cast<std::byte*>(data.get()),
reinterpret_cast<std::byte*>(&data.get()[buffersize]));
}
image.width_ = w;
image.height_ = h;
image.is_srgb_ = (state.info_png.srgb_defined == 1);
if (image.width_ <= 0 || image.height_ < 0) {
std::stringstream ss;
ss << "error decoding PNG file '" << resource->name << "': " << "dimensions are invalid";
throw mjCError(obj, "%s", ss.str().c_str());
}
return image;
}
// associate all child list elements with a frame and copy them to parent list, clear child list
template <typename T>
void MapFrame(std::vector<T*>& parent, std::vector<T*>& child,
mjCFrame* frame, mjCBody* parent_body) {
std::for_each(child.begin(), child.end(), [frame, parent_body](T* element) {
element->SetFrame(frame);
element->SetParent(parent_body);
});
parent.insert(parent.end(), child.begin(), child.end());
child.clear();
}
} // namespace
// utiility function for checking size parameters
static void checksize(double* size, mjtGeom type, mjCBase* object, const char* name, int id) {
// plane: handle infinite
if (type == mjGEOM_PLANE) {
if (size[2] <= 0) {
throw mjCError(object, "plane size(3) must be positive");
}
}
// regular geom
else {
for (int i=0; i < mjGEOMINFO[type]; i++) {
if (size[i] <= 0) {
throw mjCError(object, "size %d must be positive in geom", nullptr, i);
}
}
}
}
// error message for missing "limited" attribute
static void checklimited(
const mjCBase* obj,
bool autolimits, const char* entity, const char* attr, int limited, bool hasrange) {
if (!autolimits && limited == 2 && hasrange) {
std::stringstream ss;
ss << entity << " has `" << attr << "range` but not `" << attr << "limited`. "
<< "set the autolimits=\"true\" compiler option, specify `" << attr << "limited` "
<< "explicitly (\"true\" or \"false\"), or remove the `" << attr << "range` attribute.";
throw mjCError(obj, "%s", ss.str().c_str());
}
}
// returns true if limits should be active
static bool islimited(int limited, const double range[2]) {
if (limited == mjLIMITED_TRUE || (limited == mjLIMITED_AUTO && range[0] < range[1])) {
return true;
}
return false;
}
//------------------------- class mjCError implementation ------------------------------------------
// constructor
mjCError::mjCError(const mjCBase* obj, const char* msg, const char* str, int pos1, int pos2) {
char temp[600];
// init
warning = false;
if (obj || msg) {
mju::sprintf_arr(message, "Error");
} else {
message[0] = 0;
}
// construct error message
if (msg) {
if (str) {
mju::sprintf_arr(temp, msg, str, pos1, pos2);
} else {
mju::sprintf_arr(temp, msg, pos1, pos2);
}
mju::strcat_arr(message, ": ");
mju::strcat_arr(message, temp);
}
// append info from mjCBase element
if (obj) {
// with or without xml position
if (!obj->info.empty()) {
mju::sprintf_arr(temp, "Element name '%s', id %d, %s",
obj->name.c_str(), obj->id, obj->info.c_str());
} else {
mju::sprintf_arr(temp, "Element name '%s', id %d", obj->name.c_str(), obj->id);
}
// append to message
mju::strcat_arr(message, "\n");
mju::strcat_arr(message, temp);
}
}
//------------------ alternative orientation implementation ----------------------------------------
// compute frame orientation given alternative specifications
// used for geom, site, body and camera frames
const char* ResolveOrientation(double* quat, bool degree, const char* sequence,
const mjsOrientation& orient) {
double axisangle[4];
double xyaxes[6];
double zaxis[3];
double euler[3];
mjuu_copyvec(axisangle, orient.axisangle, 4);
mjuu_copyvec(xyaxes, orient.xyaxes, 6);
mjuu_copyvec(zaxis, orient.zaxis, 3);
mjuu_copyvec(euler, orient.euler, 3);
// set quat using axisangle
if (orient.type == mjORIENTATION_AXISANGLE) {
// convert to radians if necessary, normalize axis
if (degree) {
axisangle[3] = axisangle[3] / 180.0 * mjPI;
}
if (mjuu_normvec(axisangle, 3) < mjEPS) {
return "axisangle too small";
}
// construct quaternion
double ang2 = axisangle[3]/2;
quat[0] = cos(ang2);
quat[1] = sin(ang2)*axisangle[0];
quat[2] = sin(ang2)*axisangle[1];
quat[3] = sin(ang2)*axisangle[2];
}
// set quat using xyaxes
if (orient.type == mjORIENTATION_XYAXES) {
// normalize x axis
if (mjuu_normvec(xyaxes, 3) < mjEPS) {
return "xaxis too small";
}
// make y axis orthogonal to x axis, normalize
double d = mjuu_dot3(xyaxes, xyaxes+3);
xyaxes[3] -= xyaxes[0]*d;
xyaxes[4] -= xyaxes[1]*d;
xyaxes[5] -= xyaxes[2]*d;
if (mjuu_normvec(xyaxes+3, 3) < mjEPS) {
return "yaxis too small";
}
// compute and normalize z axis
double z[3];
mjuu_crossvec(z, xyaxes, xyaxes+3);
if (mjuu_normvec(z, 3) < mjEPS) {
return "cross(xaxis, yaxis) too small";
}
// convert frame into quaternion
mjuu_frame2quat(quat, xyaxes, xyaxes+3, z);
}
// set quat using zaxis
if (orient.type == mjORIENTATION_ZAXIS) {
if (mjuu_normvec(zaxis, 3) < mjEPS) {
return "zaxis too small";
}
mjuu_z2quat(quat, zaxis);
}
// handle euler
if (orient.type == mjORIENTATION_EULER) {
// convert to radians if necessary
if (degree) {
for (int i=0; i < 3; i++) {
euler[i] = euler[i] / 180.0 * mjPI;
}
}
// init
mjuu_setvec(quat, 1, 0, 0, 0);
// loop over euler angles, accumulate rotations
for (int i=0; i < 3; i++) {
double tmp[4], qrot[4] = {cos(euler[i]/2), 0, 0, 0};
double sa = sin(euler[i]/2);
// construct quaternion rotation
if (sequence[i] == 'x' || sequence[i] == 'X') {
qrot[1] = sa;
} else if (sequence[i] == 'y' || sequence[i] == 'Y') {
qrot[2] = sa;
} else if (sequence[i] == 'z' || sequence[i] == 'Z') {
qrot[3] = sa;
} else {
return "euler sequence can only contain x, y, z, X, Y, Z";
}
// accumulate rotation
if (sequence[i] == 'x' || sequence[i] == 'y' || sequence[i] == 'z') {
mjuu_mulquat(tmp, quat, qrot); // moving axes: post-multiply
} else {
mjuu_mulquat(tmp, qrot, quat); // fixed axes: pre-multiply
}
mjuu_copyvec(quat, tmp, 4);
}
// normalize, just in case
mjuu_normvec(quat, 4);
}
return 0;
}
//------------------------- class mjCBoundingVolumeHierarchy implementation ------------------------
// assign position and orientation
void mjCBoundingVolumeHierarchy::Set(double ipos_element[3], double iquat_element[4]) {
mjuu_copyvec(ipos_, ipos_element, 3);
mjuu_copyvec(iquat_, iquat_element, 4);
}
void mjCBoundingVolumeHierarchy::AllocateBoundingVolumes(int nleaf) {
nbvh_ = 0;
bvh_.clear();
child_.clear();
nodeid_.clear();
level_.clear();
bvleaf_.clear();
bvleaf_.reserve(nleaf);
}
void mjCBoundingVolumeHierarchy::RemoveInactiveVolumes(int nmax) {
bvleaf_.erase(bvleaf_.begin() + nmax, bvleaf_.end());
}
const mjCBoundingVolume*
mjCBoundingVolumeHierarchy::AddBoundingVolume(int id, int contype, int conaffinity,
const double* pos, const double* quat,
const double* aabb) {
bvleaf_.emplace_back(id, contype, conaffinity, pos, quat, aabb);
return &bvleaf_.back();
}
const mjCBoundingVolume*
mjCBoundingVolumeHierarchy::AddBoundingVolume(const int* id, int contype, int conaffinity,
const double* pos, const double* quat,
const double* aabb) {
bvleaf_.emplace_back(id, contype, conaffinity, pos, quat, aabb);
return &bvleaf_.back();
}
// create bounding volume hierarchy
void mjCBoundingVolumeHierarchy::CreateBVH() {
std::vector<BVElement> elements;
Make(elements);
MakeBVH(elements.begin(), elements.end());
}
void mjCBoundingVolumeHierarchy::Make(std::vector<BVElement>& elements) {
// precompute the positions of each element in the hierarchy's axes, and drop
// visual-only elements.
elements.reserve(bvleaf_.size());
double qinv[4] = {iquat_[0], -iquat_[1], -iquat_[2], -iquat_[3]};
for (int i = 0; i < bvleaf_.size(); i++) {
if (bvleaf_[i].Conaffinity() || bvleaf_[i].Contype()) {
BVElement element;
element.e = &bvleaf_[i];
double vert[3] = {element.e->Pos(0) - ipos_[0],
element.e->Pos(1) - ipos_[1],
element.e->Pos(2) - ipos_[2]};
mjuu_rotVecQuat(element.lpos, vert, qinv);
elements.push_back(std::move(element));
}
}
}
// compute bounding volume hierarchy
int mjCBoundingVolumeHierarchy::MakeBVH(
std::vector<BVElement>::iterator elements_begin,
std::vector<BVElement>::iterator elements_end, int lev) {
int nelements = elements_end - elements_begin;
if (nelements == 0) {
return -1;
}
constexpr double kMaxVal = std::numeric_limits<double>::max();
double AAMM[6] = {kMaxVal, kMaxVal, kMaxVal, -kMaxVal, -kMaxVal, -kMaxVal};
// inverse transformation
double qinv[4] = {iquat_[0], -iquat_[1], -iquat_[2], -iquat_[3]};
// accumulate AAMM over elements
for (auto element = elements_begin; element != elements_end; ++element) {
// transform element aabb to aamm format
double aamm[6] = {element->e->AABB(0) - element->e->AABB(3),
element->e->AABB(1) - element->e->AABB(4),
element->e->AABB(2) - element->e->AABB(5),
element->e->AABB(0) + element->e->AABB(3),
element->e->AABB(1) + element->e->AABB(4),
element->e->AABB(2) + element->e->AABB(5)};
// update node AAMM
for (int v=0; v < 8; v++) {
double vert[3], box[3];
vert[0] = (v&1 ? aamm[3] : aamm[0]);
vert[1] = (v&2 ? aamm[4] : aamm[1]);
vert[2] = (v&4 ? aamm[5] : aamm[2]);
// rotate to the body inertial frame if specified
if (element->e->Quat()) {
mjuu_rotVecQuat(box, vert, element->e->Quat());
box[0] += element->e->Pos(0) - ipos_[0];
box[1] += element->e->Pos(1) - ipos_[1];
box[2] += element->e->Pos(2) - ipos_[2];
mjuu_rotVecQuat(vert, box, qinv);
}
AAMM[0] = std::min(AAMM[0], vert[0]);
AAMM[1] = std::min(AAMM[1], vert[1]);
AAMM[2] = std::min(AAMM[2], vert[2]);
AAMM[3] = std::max(AAMM[3], vert[0]);
AAMM[4] = std::max(AAMM[4], vert[1]);
AAMM[5] = std::max(AAMM[5], vert[2]);
}
}
// inflate flat AABBs
for (int i = 0; i < 3; i++) {
if (std::abs(AAMM[i] - AAMM[i+3]) < mjEPS) {
AAMM[i + 0] -= mjEPS;
AAMM[i + 3] += mjEPS;
}
}
// store current index
int index = nbvh_++;
child_.push_back(-1);
child_.push_back(-1);
nodeid_.push_back(-1);
nodeidptr_.push_back(nullptr);
level_.push_back(lev);
// store bounding box of the current node
bvh_.push_back((AAMM[3] + AAMM[0]) / 2);
bvh_.push_back((AAMM[4] + AAMM[1]) / 2);
bvh_.push_back((AAMM[5] + AAMM[2]) / 2);
bvh_.push_back((AAMM[3] - AAMM[0]) / 2);
bvh_.push_back((AAMM[4] - AAMM[1]) / 2);
bvh_.push_back((AAMM[5] - AAMM[2]) / 2);
// leaf node, return
if (nelements == 1) {
child_[2*index + 0] = -1;
child_[2*index + 1] = -1;
nodeid_[index] = *elements_begin->e->Id();
nodeidptr_[index] = (int*)elements_begin->e->Id();
return index;
}
// find longest axis, by a margin of at least mjEPS, default to 0
int axis = 0;
double edges[3] = {AAMM[3] - AAMM[0], AAMM[4] - AAMM[1], AAMM[5] - AAMM[2]};
if (edges[1] >= edges[0] + mjEPS) axis = 1;
if (edges[2] >= edges[axis] + mjEPS) axis = 2;
// find median along the axis
auto compare = [&](const BVElement& e1, const BVElement& e2) {
if (std::abs(e1.lpos[axis] - e2.lpos[axis]) > mjEPS) {
return e1.lpos[axis] < e2.lpos[axis];
}
// comparing pointers gives a stable sort, because they both come from the same array
return e1.e < e2.e;
};
// note: nth_element performs a partial sort of elements
int m = nelements / 2;
std::nth_element(elements_begin, elements_begin + m, elements_end, compare);
// recursive calls
if (m > 0) {
child_[2*index + 0] = MakeBVH(elements_begin, elements_begin + m, lev + 1);
}
if (m != nelements) {
child_[2*index + 1] = MakeBVH(elements_begin + m, elements_end, lev + 1);
}
// SHOULD NOT OCCUR
if (child_[2*index + 0] == -1 && child_[2*index + 1] == -1) {
mju_error("this should have been a leaf, body=%s nelements=%d",
name_.c_str(), nelements);
}
if (lev > mjMAXTREEDEPTH) {
mju_warning("max tree depth exceeded in body=%s", name_.c_str());
}
return index;
}
//------------------------- class mjCOctree implementation --------------------------------------------
void mjCOctree::CopyLevel(int* level) const {
for (int i = 0; i < node_.size(); ++i) {
level[i] = node_[i].level;
}
}
void mjCOctree::CopyChild(int* child) const {
for (int i = 0; i < node_.size(); ++i) {
for (int j = 0; j < 8; ++j) {
child[i * 8 + j] = node_[i].child[j];
}
}
}
void mjCOctree::CopyAabb(mjtNum* aabb) const {
for (int i = 0; i < node_.size(); ++i) {
aabb[i * 6 + 0] = (node_[i].aamm[0] + node_[i].aamm[3]) / 2;
aabb[i * 6 + 1] = (node_[i].aamm[1] + node_[i].aamm[4]) / 2;
aabb[i * 6 + 2] = (node_[i].aamm[2] + node_[i].aamm[5]) / 2;
aabb[i * 6 + 3] = (node_[i].aamm[3] - node_[i].aamm[0]) / 2;
aabb[i * 6 + 4] = (node_[i].aamm[4] - node_[i].aamm[1]) / 2;
aabb[i * 6 + 5] = (node_[i].aamm[5] - node_[i].aamm[2]) / 2;
}
}
void mjCOctree::CopyCoeff(mjtNum* coeff) const {
for (int i = 0; i < node_.size(); ++i) {
for (int j = 0; j < 8; ++j) {
coeff[i * 8 + j] = node_[i].coeff[j];
}
}
}
void mjCOctree::SetFace(const std::vector<double>& vert, const std::vector<int>& face) {
for (int i = 0; i < face.size(); i += 3) {
std::array<double, 3> v0 = {vert[3*face[i+0]], vert[3*face[i+0]+1], vert[3*face[i+0]+2]};
std::array<double, 3> v1 = {vert[3*face[i+1]], vert[3*face[i+1]+1], vert[3*face[i+1]+2]};
std::array<double, 3> v2 = {vert[3*face[i+2]], vert[3*face[i+2]+1], vert[3*face[i+2]+2]};
face_.push_back({v0, v1, v2});
}
}
// TODO: use the same code as mjCBoundingVolumeHierarchy::Make()
void mjCOctree::Make(std::vector<Triangle>& elements) {
// rotate triangles to the body inertial frame
elements.assign(face_.size(), {{{0}}});
double qinv[4] = {iquat_[0], -iquat_[1], -iquat_[2], -iquat_[3]};
for (int i = 0; i < face_.size(); i++) {
for (int j = 0; j < 3; j++) {
double vert[3] = {face_[i][j][0] - ipos_[0],
face_[i][j][1] - ipos_[1],
face_[i][j][2] - ipos_[2]};
mjuu_rotVecQuat(elements[i][j].data(), vert, qinv);
}
}
}
void mjCOctree::CreateOctree(const double aamm[6]) {
double aabb[6] = {(aamm[0] + aamm[3]) / 2, (aamm[1] + aamm[4]) / 2, (aamm[2] + aamm[5]) / 2,
(aamm[3] - aamm[0]) / 2, (aamm[4] - aamm[1]) / 2, (aamm[5] - aamm[2]) / 2};
double box[6] = {aabb[0] - 1.1 * aabb[3], aabb[1] - 1.1 * aabb[4], aabb[2] - 1.1 * aabb[5],
aabb[0] + 1.1 * aabb[3], aabb[1] + 1.1 * aabb[4], aabb[2] + 1.1 * aabb[5]};
std::vector<Triangle> elements;
Make(elements);
std::vector<Triangle*> elements_ptrs(elements.size());
std::transform(elements.begin(), elements.end(), elements_ptrs.begin(),
[](Triangle& triangle) { return ▵ });
std::unordered_map<Point, int> vert_map;
MakeOctree(elements_ptrs, box, vert_map);
MarkHangingNodes();
}
namespace {
double pointBoxDistSq(const double* p, const mjtNum* aabb) {
double dist_sq = 0;
for (int i = 0; i < 3; ++i) {
double lo = aabb[i] - aabb[i + 3];
double hi = aabb[i] + aabb[i + 3];
if (p[i] < lo) {
dist_sq += (lo - p[i]) * (lo - p[i]);
} else if (p[i] > hi) {
dist_sq += (p[i] - hi) * (p[i] - hi);
}
}
return dist_sq;
}
// compute squared distance between point p and triangle (v0, v1, v2),
// and return barycentric coordinates (u,v) of the closest point
double pointTriDistSqWithUV(const double* p, const double* v0, const double* v1,
const double* v2, double& out_u, double& out_v) {
double ab[3] = {v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]};
double ac[3] = {v2[0] - v0[0], v2[1] - v0[1], v2[2] - v0[2]};
double ap[3] = {p[0] - v0[0], p[1] - v0[1], p[2] - v0[2]};
// the closest point on the triangle is determined by partitioning space into Voronoi regions
double d1 = ab[0]*ap[0] + ab[1]*ap[1] + ab[2]*ap[2];
double d2 = ac[0]*ap[0] + ac[1]*ap[1] + ac[2]*ap[2];
// region A (vertex v0)
if (d1 <= 0 && d2 <= 0) {
out_u = 0; out_v = 0;
return ap[0]*ap[0] + ap[1]*ap[1] + ap[2]*ap[2];
}
double bp[3] = {p[0] - v1[0], p[1] - v1[1], p[2] - v1[2]};
double d3 = ab[0]*bp[0] + ab[1]*bp[1] + ab[2]*bp[2];
double d4 = ac[0]*bp[0] + ac[1]*bp[1] + ac[2]*bp[2];
// region B (vertex v1)
if (d3 >= 0 && d4 <= d3) {
out_u = 1; out_v = 0;
return bp[0]*bp[0] + bp[1]*bp[1] + bp[2]*bp[2];
}
// region AB (edge v0-v1)
double vc = d1*d4 - d3*d2;
if (vc <= 0 && d1 >= 0 && d3 <= 0) {
double u = d1 / (d1 - d3);
out_u = u; out_v = 0;
double closest[3] = {v0[0] + u*ab[0], v0[1] + u*ab[1], v0[2] + u*ab[2]};
return (p[0]-closest[0])*(p[0]-closest[0]) +
(p[1]-closest[1])*(p[1]-closest[1]) +
(p[2]-closest[2])*(p[2]-closest[2]);
}
double cp[3] = {p[0] - v2[0], p[1] - v2[1], p[2] - v2[2]};
double d5 = ab[0]*cp[0] + ab[1]*cp[1] + ab[2]*cp[2];
double d6 = ac[0]*cp[0] + ac[1]*cp[1] + ac[2]*cp[2];
// region C (vertex v2)
if (d6 >= 0 && d5 <= d6) {
out_u = 0; out_v = 1;
return cp[0]*cp[0] + cp[1]*cp[1] + cp[2]*cp[2];
}
// region AC (edge v0-v2)
double vb = d5*d2 - d1*d6;
if (vb <= 0 && d2 >= 0 && d6 <= 0) {
double v = d2 / (d2 - d6);
out_u = 0; out_v = v;
double closest[3] = {v0[0] + v*ac[0], v0[1] + v*ac[1], v0[2] + v*ac[2]};
return (p[0]-closest[0])*(p[0]-closest[0]) +
(p[1]-closest[1])*(p[1]-closest[1]) +
(p[2]-closest[2])*(p[2]-closest[2]);
}
// region BC (edge v1-v2)
double va = d3*d6 - d5*d4;
if (va <= 0 && (d4 - d3) >= 0 && (d5 - d6) >= 0) {
double w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
out_u = 1 - w; out_v = w;
double bc[3] = {v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]};
double closest[3] = {v1[0] + w*bc[0], v1[1] + w*bc[1], v1[2] + w*bc[2]};
return (p[0]-closest[0])*(p[0]-closest[0]) +
(p[1]-closest[1])*(p[1]-closest[1]) +
(p[2]-closest[2])*(p[2]-closest[2]);
}
// region ABC (inside triangle)
double denom = 1.0 / (va + vb + vc);
double u = vb * denom;
double v = vc * denom;
out_u = u; out_v = v;
double closest[3] = {v0[0] + u*ab[0] + v*ac[0],
v0[1] + u*ab[1] + v*ac[1],
v0[2] + u*ab[2] + v*ac[2]};
return (p[0]-closest[0])*(p[0]-closest[0]) +
(p[1]-closest[1])*(p[1]-closest[1]) +
(p[2]-closest[2])*(p[2]-closest[2]);
}
// query BVH for closest face to point p, return distance, face index and barycentric coordinates
void queryClosestBVHWithFace(const mjtNum* bvh, const int* child, const int* nodeid,
const double* vert, const int* face, int node_idx,
const double* p, double& best_dist_sq,
int& best_face, double& best_u, double& best_v) {
const mjtNum* aabb = &bvh[node_idx * 6];
if (pointBoxDistSq(p, aabb) >= best_dist_sq) return;
int left = child[node_idx * 2];
int right = child[node_idx * 2 + 1];
if (left == -1 && right == -1) {
int fi = nodeid[node_idx];
if (fi >= 0) {
const double* v0 = vert + face[fi * 3 + 0] * 3;
const double* v1 = vert + face[fi * 3 + 1] * 3;
const double* v2 = vert + face[fi * 3 + 2] * 3;
double u, v;
double dist_sq = pointTriDistSqWithUV(p, v0, v1, v2, u, v);
if (dist_sq < best_dist_sq) {
best_dist_sq = dist_sq;
best_face = fi;
best_u = u;
best_v = v;
}
}
return;
}
if (left >= 0) {
queryClosestBVHWithFace(bvh, child, nodeid, vert, face, left, p,
best_dist_sq, best_face, best_u, best_v);
}
if (right >= 0) {
queryClosestBVHWithFace(bvh, child, nodeid, vert, face, right, p,
best_dist_sq, best_face, best_u, best_v);
}
}
double querySignedDistance(const mjtNum* bvh, const int* child, const int* nodeid,
int nbvh, const double* point,
const double* vert, const int* face) {
if (nbvh == 0) {
return 0;
}
double best_dist_sq = 1e20;
int best_face = -1;
double best_u = 0, best_v = 0;
queryClosestBVHWithFace(bvh, child, nodeid, vert, face, 0, point,
best_dist_sq, best_face, best_u, best_v);
double dist = std::sqrt(best_dist_sq);
double sign = 1.0;
if (best_face >= 0) {
const double* v0 = vert + face[best_face * 3 + 0] * 3;
const double* v1 = vert + face[best_face * 3 + 1] * 3;
const double* v2 = vert + face[best_face * 3 + 2] * 3;
double e1[3] = {v1[0]-v0[0], v1[1]-v0[1], v1[2]-v0[2]};
double e2[3] = {v2[0]-v0[0], v2[1]-v0[1], v2[2]-v0[2]};
double normal[3] = {
e1[1]*e2[2] - e1[2]*e2[1],
e1[2]*e2[0] - e1[0]*e2[2],
e1[0]*e2[1] - e1[1]*e2[0]
};
double closest[3] = {
v0[0] + best_u*(v1[0]-v0[0]) + best_v*(v2[0]-v0[0]),
v0[1] + best_u*(v1[1]-v0[1]) + best_v*(v2[1]-v0[1]),
v0[2] + best_u*(v1[2]-v0[2]) + best_v*(v2[2]-v0[2])
};
double u[3] = {point[0]-closest[0], point[1]-closest[1], point[2]-closest[2]};
double dot = u[0]*normal[0] + u[1]*normal[1] + u[2]*normal[2];
double normal_len = mjuu_normvec(normal, 3);
double eps = 1e-12 * normal_len * dist;
sign = (dot > eps) ? 1.0 : -1.0;
}
return sign * dist;
}
} // namespace
double mjCBoundingVolumeHierarchy::QuerySignedDistance(
const double* point, const double* vert, const int* face) const {
return querySignedDistance(bvh_.data(), child_.data(), nodeid_.data(),
nbvh_, point, vert, face);
}
void mjCOctree::ComputeSdfCoeffs(const double* vert, int nvert, const int* face, int nface,
const mjCBoundingVolumeHierarchy& tree) {
std::vector<double> coeffs(nvert_, 0.0);
std::vector<bool> processed(nvert_, false);
std::deque<int> queue;
if (NumNodes() > 0) {
queue.push_back(0);
}
while (!queue.empty()) {
int node_idx = queue.front();
queue.pop_front();
// compute SDF coefficients at the 8 vertices of the octree node
for (int j = 0; j < 8; ++j) {
int vert_id = VertId(node_idx, j);
if (processed[vert_id]) {
continue;
}
if (Hang(vert_id).empty()) {
// transform from octree frame (body inertial) back to mesh frame
double p_mesh[3];
mjuu_rotVecQuat(p_mesh, Vert(vert_id), iquat_);
p_mesh[0] += ipos_[0];
p_mesh[1] += ipos_[1];
p_mesh[2] += ipos_[2];
coeffs[vert_id] = tree.QuerySignedDistance(p_mesh, vert, face);
} else {
// hanging node: interpolate from parents
double sum_coeff = 0;
for (int dep_id : Hang(vert_id)) {
sum_coeff += coeffs[dep_id];
}
coeffs[vert_id] = sum_coeff / Hang(vert_id).size();
}
processed[vert_id] = true;
}
// add children to the queue
for (int child_idx : Children(node_idx)) {
if (child_idx != -1) {
queue.push_back(child_idx);
}
}
}
// optional Laplacian smoothing (smooths octree level transitions)
if (smoothing_iterations_ > 0) {
// build vertex neighbor graph from octree connectivity
std::vector<std::set<int>> neighbors(nvert_);
for (int i = 0; i < NumNodes(); ++i) {
static const int edges[12][2] = {
{0, 1}, {2, 3}, {4, 5}, {6, 7},
{0, 2}, {1, 3}, {4, 6}, {5, 7},
{0, 4}, {1, 5}, {2, 6}, {3, 7}
};
for (const auto& edge : edges) {
int v0 = VertId(i, edge[0]);
int v1 = VertId(i, edge[1]);
neighbors[v0].insert(v1);
neighbors[v1].insert(v0);
}
}
// apply Laplacian smoothing
const double alpha = 0.2;
std::vector<double> sdf_new(nvert_);
for (int iter = 0; iter < smoothing_iterations_; ++iter) {
for (int i = 0; i < nvert_; ++i) {
if (neighbors[i].empty()) {
sdf_new[i] = coeffs[i];
} else {
double avg = 0;
for (int j : neighbors[i]) avg += coeffs[j];
avg /= neighbors[i].size();
sdf_new[i] = (1 - alpha) * coeffs[i] + alpha * avg;
}
}
std::swap(coeffs, sdf_new);
}
}
// copy coefficients to the octree nodes
for (int i = 0; i < NumNodes(); ++i) {
for (int j = 0; j < 8; j++) {
AddCoeff(i, j, coeffs[VertId(i, j)]);
}
}
}
static double dot2(const double* a, const double* b) {
return a[0] * b[0] + a[1] * b[1];
}
// from M. Schwarz and H.-P. Seidel, "Fast Parallel Surface and Solid Voxelization on GPUs".
static bool boxTriangle(const Triangle& v, const double aamm[6]) {
// bounding box tests
for (int i = 0; i < 3; i++) {
if (v[0][i] < aamm[i] && v[1][i] < aamm[i] && v[2][i] < aamm[i]) {
return false;
}
int j = i + 3;
if (v[0][i] > aamm[j] && v[1][i] > aamm[j] && v[2][i] > aamm[j]) {
return false;
}
}
// test for triangle plane and box overlap
double n[3];
double e[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
e[i][j] = v[(i+1)%3][j] - v[i][j];
}
}
mjuu_crossvec(n, e[0], e[1]);
double size[3] = {aamm[3] - aamm[0], aamm[4] - aamm[1], aamm[5] - aamm[2]};
double c[3] = {n[0] > 0 ? size[0] : 0, n[1] > 0 ? size[1] : 0, n[2] > 0 ? size[2] : 0};
double c1[3] = {c[0] - v[0][0], c[1] - v[0][1], c[2] - v[0][2]};
double c2[3] = {size[0] - c[0] - v[0][0], size[1] - c[1] - v[0][1], size[2] - c[2] - v[0][2]};
if ((mjuu_dot3(n, aamm) + mjuu_dot3(n, c1)) * (mjuu_dot3(n, aamm) + mjuu_dot3(n, c2)) > 0) {
return false;
}
// test projection overlap
for (int a = 0; a < 3; a++) {
int b = (a + 1) % 3;
int c = (a + 2) % 3;
for (int i = 0; i < 3; i++) {
double sign = n[a] >= 0 ? 1 : -1;
double ne[2] = {-e[i][c] * sign, e[i][b] * sign};
double vi[2] = {v[i][b], v[i][c]};
double d = -dot2(ne, vi) + mju_max(0, size[b]*ne[0]) + mju_max(0, size[c]*ne[1]);
double p[2] = {aamm[b], aamm[c]};
if (dot2(ne, p) + d < 0) {
return false;
}
}
}
return true;
}
void mjCOctree::TaskToNode(const OctreeTask& task, OctNode& node,
std::unordered_map<Point, int>& vert_map) {
node.level = task.lev;
node.parent_index = task.parent_index;
node.child_slot = task.child_slot;
if (task.parent_index != -1) {
node_[task.parent_index].child[task.child_slot] = task.node_index;
const auto parent_aamm = node_[task.parent_index].aamm;
node.aamm[0] = task.child_slot & 1 ? (parent_aamm[3] + parent_aamm[0]) / 2 : parent_aamm[0];
node.aamm[1] = task.child_slot & 2 ? (parent_aamm[4] + parent_aamm[1]) / 2 : parent_aamm[1];
node.aamm[2] = task.child_slot & 4 ? (parent_aamm[5] + parent_aamm[2]) / 2 : parent_aamm[2];
node.aamm[3] = task.child_slot & 1 ? parent_aamm[3] : (parent_aamm[0] + parent_aamm[3]) / 2;
node.aamm[4] = task.child_slot & 2 ? parent_aamm[4] : (parent_aamm[1] + parent_aamm[4]) / 2;
node.aamm[5] = task.child_slot & 4 ? parent_aamm[5] : (parent_aamm[2] + parent_aamm[5]) / 2;
}
for (int i = 0; i < 8; i++) {
Point v = {{(i & 1) ? node.aamm[3] : node.aamm[0],
(i & 2) ? node.aamm[4] : node.aamm[1],
(i & 4) ? node.aamm[5] : node.aamm[2]}};
auto it = vert_map.find(v);
if (it != vert_map.end()) {