-
Notifications
You must be signed in to change notification settings - Fork 0
/
prog6.cxx
1553 lines (1389 loc) · 45.8 KB
/
prog6.cxx
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
#include <cassert>
#include <cstdio>
#include <memory>
#include <limits>
#include <span>
#include <thread>
#include <unordered_map>
#include <vector>
#include <asyncpp/generator.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GLFW/glfw3.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <pcg_random.hpp>
#include "averager.hxx"
#include "math.hxx"
#include "texture.hxx"
#include "shader.hxx"
#include "io.hxx"
#include "prog5/glshape.hxx"
#include "prog5/gpu.hxx"
#include "prog5/subspace.hxx"
#include "prog5/thing.hxx"
#include "prog5/universe.hxx"
#include "prog5/visual.hxx"
#include "iters.hxx"
#include "rand.hxx"
#define TEST 0
// #define debugf(...) printf(__VA_ARGS__)
#define debugf(...)
using namespace std::literals;
class TextureCubemap {
public:
static float linearize(const float channel) {
if (channel <= 0.04045f)
return channel / 12.92f;
return pow((channel + 0.055f) / 1.055f, 2.4f);
}
void load(int size, std::string const &basename) {
dim = size;
content.resize(6 * dim * dim);
for (int k = 0; k < 6; k++) {
png::image<png::rgba_pixel, png::solid_pixel_buffer<png::rgba_pixel>> image(basename + std::to_string(k) + ".png");
assert(image.get_width() == size && image.get_height() == size);
auto &&data = image.get_pixbuf().get_bytes();
const uint8_t *i_src = data.data();
vec4 *i_dest = content.data() + k * dim * dim;
for (int pix = 0; pix < dim * dim; pix++, i_src += 4, i_dest++) {
const ivec4 p_src(i_src[0], i_src[1], i_src[2], i_src[3]);
vec4 &p_dest = *i_dest;
vec4 pix_srgb = vec4(p_src) / 255.0f;
p_dest[0] = linearize(pix_srgb[0]);
p_dest[1] = linearize(pix_srgb[1]);
p_dest[2] = linearize(pix_srgb[2]);
p_dest[3] = pix_srgb[3];
}
}
}
void to_gl_texture_layer(TextureID texture, int layer) {
for (int k = 0; k < 6; k++)
glTextureSubImage3D(texture, 0, 0, 0, 6 * layer + k, dim, dim, 1, GL_RGBA, GL_FLOAT, content.data() + k * dim * dim);
}
vec3 sample(vec3 dir) const {
const vec3 adir = abs(dir);
const float *v = glm::value_ptr(adir);
const int dir_index = std::max_element(v, v + 3) - v;
int face_index = 2 * dir_index;
if (dir[dir_index] < 0)
++face_index;
dir /= v[dir_index];
vec2 uv;
switch(face_index) {
case 0: uv = {-dir.z, -dir.y}; break; // +x
case 1: uv = {dir.z, -dir.y}; break; // -x
case 2: uv = {dir.x, dir.z}; break; // +y
case 3: uv = {dir.x, -dir.z}; break; // -y
case 4: uv = {dir.x, -dir.y}; break; // +z
case 5: uv = {-dir.x, -dir.y}; break; // -z
default: abort();
}
uv = 0.5f + 0.5f * uv;
ivec2 tc = floor(float(dim) * uv);
tc = clamp(tc, 0, dim - 1);
return content[dim * dim * face_index + dim * tc.y + tc.x];
}
private:
int dim;
std::vector<vec4> content;
};
TextureCubemap skybox;
TextureCubemap t_planet_1;
TextureCubemap t_planet_2;
struct Params {
float outer_radius = 5.0f;
float inner_radius = 4.0f;
float outer_half_length = 1500.0f;
float inner_half_length = 100.0f;
float inner_pad = 0.25f;
};
struct Coefs {
float x1, y1, x2, y2;
float x0, y0, w;
Coefs(Params const ¶ms) {
static constexpr float eps = 1e-3;
x2 = params.inner_half_length;
y2 = params.outer_half_length;
x1 = params.inner_half_length * (1.0f - params.inner_pad);
if (y2 - x2 < eps) {
if (y2 - x2 < -eps)
throw "Invalid channel properties";
x1 = y1 = x2 = y2;
x0 = y0 = w = std::numeric_limits<float>::signaling_NaN();
return;
}
y1 = x1 * (x1 - x2 + 2*y2) / (x1 + x2);
x0 = 0.5 * (sqr(x2) + sqr(x1) - 2 * x2 * y2) / (x2 - y2);
y0 = y2 - 0.25 * (sqr(x2) - sqr(x1)) / (x2 - y2);
w = (x2 - y2) / (sqr(x2) - sqr(x1));
}
};
static constexpr float eps = 1e-4;
enum class Side {
Outside = 1,
Inside = -1,
};
struct CylinderDist {
float cap, side;
};
static CylinderDist cylinderDist(Ray from, float halflength, float radius, Side side = Side::Outside) {
CylinderDist dist{std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()};
{ // Крышки цилиндра
const float d = -int(side) * sign(from.dir.x) * halflength - from.pos.x;
const float t = d / from.dir.x;
const vec3 p = from.pos + t * from.dir;
if (t > 0.0f && length(vec2{p.y, p.z}) <= radius)
dist.cap = t - eps;
}
{ // Боковая стенка цилиндра
const vec2 pos = {from.pos.y, from.pos.z};
const vec2 dir = {from.dir.y, from.dir.z}; // не единичный!
const float t_center = -dot(pos, dir);
const float scale = dot(dir, dir);
const float off = sqr(radius) - dot(pos, pos);
if (const float d2 = sqr(t_center) + scale * off; d2 >= 0.0f) {
const float t_diff = std::sqrt(d2);
const float t = (t_center - int(side) * t_diff) / scale;
if (t >= -eps) {
vec3 p = from.pos + t * from.dir;
if (abs(p.x) <= halflength)
dist.side = t - eps;
}
}
}
return dist;
}
class InwardsBoundary final: public SubspaceBoundaryEx {
public:
Params const ¶ms;
Subspace *side;
Subspace *channel;
InwardsBoundary(Params &_params): params(_params) {}
BoundaryPoint findBoundary(Ray from) const override {
auto dists = cylinderDist(from, params.outer_half_length, params.outer_radius);
float dist = min(dists.cap, dists.side);
if (!std::isfinite(dist))
return {{nullptr, from.pos, from.pos, mat3(1)}, dist};
const vec3 pos = from.pos + dist * from.dir;
return {leave({pos, from.dir}), 0.0};
}
std::vector<Transition> findOverlaps(vec3 pos, float max_distance) const override {
std::vector<Transition> overlaps;
if (length(pos.x) <= params.outer_half_length + max_distance && length(vec2{pos.y, pos.z}) <= params.outer_radius + max_distance) {
if (length(vec2{pos.y, pos.z}) - max_distance <= params.inner_radius) {
assert(abs(pos.x) >= params.outer_half_length);
vec3 into = pos;
into.x -= copysign(params.outer_half_length - params.inner_half_length, pos.x);
overlaps.push_back({channel, pos, into, mat3(1)});
}
if (length(vec2{pos.y, pos.z}) + max_distance >= params.inner_radius) {
overlaps.push_back({side, pos, pos, mat3(1)});
}
}
return overlaps;
}
bool contains(vec3 point) const override {
return length(point.x) > params.outer_half_length || length(vec2{point.y, point.z}) > params.outer_radius;
}
Transition leave(Ray at) const override {
vec3 pos = at.pos;
if (length(vec2{pos.y, pos.z}) < params.inner_radius) {
vec3 into = pos;
into.x -= copysign(params.outer_half_length - params.inner_half_length, pos.x);
return {channel, pos, into, mat3(1)};
} else {
return {side, pos, pos, mat3(1)};
}
}
};
class ChannelBoundary final: public SubspaceBoundaryEx {
public:
Params const ¶ms;
Subspace *outer;
Subspace *side;
ChannelBoundary(Params &_params): params(_params) {}
BoundaryPoint findBoundary(Ray from) const override {
auto dist = cylinderDist(from, params.inner_half_length, params.inner_radius, Side::Inside);
const vec3 pos = from.pos + min(dist.cap, dist.side) * from.dir;
vec3 into = pos;
if (dist.cap <= dist.side) {
into.x += copysign(params.outer_half_length - params.inner_half_length, pos.x);
return {{outer, pos, into, mat3(1)}, dist.cap};
} else {
Coefs cs(params);
float m = 1.0f;
if (abs(pos.x) < cs.x1) {
into.x *= cs.y1 / cs.x1;
m = cs.y1 / cs.x1;
} else if (abs(pos.x) < cs.x2) {
m = 2 * cs.w * (abs(pos.x) - cs.x0);
into.x = copysign(cs.y0 + cs.w * sqr(abs(pos.x) - cs.x0), pos.x);
} else {
into.x += copysign(cs.y2 - cs.x2, pos.x);
}
return {{side, pos, into, diagonal(m, 1)}, dist.side};
}
}
std::vector<Transition> findOverlaps(vec3 pos, float max_distance) const override {
std::vector<Transition> overlaps;
if (abs(pos.x) + max_distance >= params.inner_half_length) {
vec3 into = pos;
into.x += copysign(params.outer_half_length - params.inner_half_length, pos.x);
overlaps.push_back({outer, pos, into, mat3(1)});
}
if (length(vec2{pos.y, pos.z}) + max_distance >= params.inner_radius) {
Coefs cs(params);
vec3 into = pos;
float m = 1.0f;
if (abs(pos.x) < cs.x1) {
into.x *= cs.y1 / cs.x1;
m = cs.y1 / cs.x1;
} else if (abs(pos.x) < cs.x2) {
m = 2 * cs.w * (abs(pos.x) - cs.x0);
into.x = copysign(cs.y0 + cs.w * sqr(abs(pos.x) - cs.x0), pos.x);
} else {
into.x += copysign(cs.y2 - cs.x2, pos.x);
}
overlaps.push_back({side, pos, into, diagonal(m, 1)});
}
return overlaps;
}
bool contains(vec3 point) const override {
return length(point.x) < params.inner_half_length && length(vec2{point.y, point.z}) < params.inner_radius;
}
Transition leave(Ray at) const override {
const vec3 pos = at.pos;
vec3 into = pos;
if (length(pos.x) <= params.inner_half_length || length(vec2{pos.y, pos.z}) <= params.inner_radius) {
into.x += copysign(params.outer_half_length - params.inner_half_length, pos.x);
return {outer, pos, into, mat3(1)};
} else {
Coefs cs(params);
float m = 1.0f;
if (abs(pos.x) < cs.x1) {
into.x *= cs.y1 / cs.x1;
m = cs.y1 / cs.x1;
} else if (abs(pos.x) < cs.x2) {
m = 2 * cs.w * (abs(pos.x) - cs.x0);
into.x = copysign(cs.y0 + cs.w * sqr(abs(pos.x) - cs.x0), pos.x);
} else {
into.x += copysign(cs.y2 - cs.x2, pos.x);
}
return {side, pos, into, diagonal(m, 1)};
}
}
};
class ChannelMetric: public RiemannMetric<3> {
public:
Params const ¶ms;
ChannelMetric(Params &_params): params(_params) {}
decomp halfmetric(vec3 pos) const noexcept override {
Coefs cs(params);
float x = pos.x;
float dx = 1.0f;
if (abs(x) < cs.y1) {
dx = cs.x1 / cs.y1;
} else if (abs(x) < cs.y2) {
x = copysign(cs.x0 + sqrt((abs(x) - cs.y0) / cs.w), x);
dx /= -2 * cs.w * (abs(x) - cs.x0);
}
return {mat3(1.0f), {dx, 1.0f, 1.0f}};
}
};
class ChannelSideMetric: public ChannelMetric {
using ChannelMetric::ChannelMetric;
decomp halfmetric(vec pos) const noexcept override {
auto g = ChannelMetric::halfmetric(pos);
float c = clamp((params.outer_radius - length(vec2{pos.y, pos.z})) / (params.outer_radius - params.inner_radius), 0.0f, 1.0f);
c = smoothstep(c);
return {g.ortho, mix(vec3(1.0f), g.diag, c)};
}
};
class SideBoundary: public SwitchMap {
public:
Params const ¶ms;
Subspace *outer;
Subspace *channel;
SideBoundary(Params &_params): params(_params) {}
bool contains(vec3 point) const override {
float r = length(vec2{point.y, point.z});
return abs(point.x) <= params.outer_half_length + eps && r <= params.outer_radius + eps && r >= params.inner_radius - eps;
}
Transition leave(const Ray at) const override {
vec3 pos = at.pos;
vec3 dir = at.dir;
Coefs cs(params);
if (length(vec2{pos.y, pos.z}) >= params.inner_radius)
return {outer, pos, pos, mat3(1)};
if (abs(pos.x) >= params.outer_half_length && sign(dir.x) == sign(pos.x))
return {outer, pos, pos, mat3(1)};
float m = 1.0f;
if (abs(pos.x) < cs.y1) {
pos.x *= cs.x1 / cs.y1;
m = cs.x1 / cs.y1;
} else if (abs(pos.x) < cs.y2) {
pos.x = copysign(sqrt((abs(pos.x) - cs.y0) / cs.w) - cs.x0, pos.x);
m = 1 / (2 * cs.w * (abs(pos.x) - cs.x0));
} else {
pos.x -= copysign(cs.y2 - cs.x2, pos.x);
}
return {channel, at.pos, pos, diagonal(m, 1.0f)};
}
};
void test() {
}
class ChannelVisual: public SpaceVisual {
public:
Params const ¶ms;
ChannelVisual(vec3 color, Params &_params): SpaceVisual(color), params(_params) {}
vec3 where(vec3 pos) const override {
Coefs cs(params);
if (abs(pos.x) < cs.x1) {
pos.x *= cs.y1 / cs.x1;
} else if (abs(pos.x) < cs.x2) {
pos.x = copysign(cs.y0 + cs.w * sqr(abs(pos.x) - cs.x0), pos.x);
} else {
pos.x += copysign(cs.y2 - cs.x2, pos.x);
}
return pos;
}
mat3 jacobi(vec3 pos) const override {
Coefs cs(params);
if (abs(pos.x) < cs.x1) {
return diagonal(cs.y1 / cs.x1, 1.0f);
} else if (abs(pos.x) < cs.x2) {
return diagonal(2 * cs.w * (abs(pos.x) - cs.x0), 1.0f);
} else {
return mat3(1.0f);
}
}
};
class PreviewableThing: public Thing {
public:
virtual void preview(SpaceVisual const *visual) const = 0;
};
class Sphere: public PreviewableThing {
public:
float radius;
Sphere() = default;
Sphere(uint32_t _id, float _radius, ThingySubspace const *space, vec3 pos) {
id = _id;
radius = _radius;
loc = {
space,
pos,
mat3(1.0f),
};
}
ThingHit hit(Ray ray) const override {
const vec3 rel = -ray.pos;
const float t_center = -dot(ray.pos, ray.dir);
const float d2 = dot(rel, rel) - sqr(t_center);
if (d2 > sqr(radius))
return {};
const float t_diff = std::sqrt(sqr(radius) - d2);
const float t_near = t_center - t_diff;
const float t_far = t_center + t_diff;
if (t_near < -eps)
return {};
auto pos = ray.pos + t_near * ray.dir;
return {pos, t_near, pos / radius};
}
float getRadius() const noexcept final override {
return radius;
}
void preview(SpaceVisual const *visual) const override {
ellipsoid(visual, loc.pos, radius * loc.rot);
}
};
asyncpp::generator<std::pair<vec3, vec3>> edges(std::vector<vec3> const &points) {
vec3 a = points.back();
for (vec3 b: points) {
co_yield {a, b};
a = b;
}
}
vec3 dirToColor(vec3 dir) {
vec3 v = mat3(1, -1, -1, -1, 1, -1, -1, -1, 1) * dir;
return .5f + .5f * v / max(abs(v));
}
class Mesh: public PreviewableThing {
public:
Mesh(uint32_t _id, std::vector<vec3> _points, std::vector<ivec3> _tris, ThingySubspace const *space, vec3 pos) {
id = _id;
loc = {
space,
pos,
mat3(1.0f),
};
points = std::move(_points);
tris = std::move(_tris);
assert(points.size() >= 4);
for (vec3 p: points)
radius = max(radius, length(p));
}
ThingHit hit(Ray ray) const override {
float min_dist = std::numeric_limits<float>::infinity();
vec3 normal = {};
for (ivec3 tri: tris) {
vec3 a = points[tri.x];
vec3 b = points[tri.y];
vec3 c = points[tri.z];
vec3 n = cross(b - a, c - a);
vec3 rel_a = a - ray.pos;
vec3 rel_b = b - ray.pos;
vec3 rel_c = c - ray.pos;
mat3 rel = transpose(mat3{
cross(rel_b, rel_c),
cross(rel_c, rel_a),
cross(rel_a, rel_b),
});
vec3 flags = rel * ray.dir;
if (all(lessThanEqual(flags, vec3(0.0f)))) {
float k = dot(a, n); // a⋅n = b⋅n = c⋅n
float dist = (k - dot(ray.pos, n)) / dot(ray.dir, n);
if (dist < -eps)
continue;
if (dist >= min_dist)
continue;
min_dist = dist; // Для выпуклого контура можно было бы сразу `return dist`.
normal = n;
}
}
return {ray.pos + min_dist * ray.dir, min_dist, normalize(normal)};
}
float getRadius() const noexcept final override {
return radius;
}
void preview(SpaceVisual const *visual) const override {
glEnable(GL_DEPTH_TEST);
glBegin(GL_TRIANGLES);
for (ivec3 tri: tris) {
vec3 a = loc.pos + loc.rot * points[tri.x];
vec3 b = loc.pos + loc.rot * points[tri.y];
vec3 c = loc.pos + loc.rot * points[tri.z];
vec3 n = normalize(cross(b - a, c - a));
glColor3fv(value_ptr(dirToColor(n)));
glVertex3fv(value_ptr(visual->where(a)));
glVertex3fv(value_ptr(visual->where(b)));
glVertex3fv(value_ptr(visual->where(c)));
}
glEnd();
glDisable(GL_DEPTH_TEST);
}
private:
std::vector<vec3> points;
std::vector<ivec3> tris;
float radius = 0.0f;
};
using std::shared_ptr, std::make_shared;
double t_frozen = 0.0;
double t_offset = 0.0;
bool active = true;
double rt_time = 0.0;
int rt_rays = 0;
class EmptyBoundary final: public SubspaceBoundaryEx {
public:
BoundaryPoint findBoundary(Ray from) const override {
return {{nullptr, from.pos, from.pos, mat3(1)}, INFINITY};
}
std::vector<Transition> findOverlaps(vec3 pos, float max_distance) const override {
return {};
}
bool contains(vec3 point) const override {
return true;
}
Transition leave(Ray at) const override {
abort();
}
};
class MyUniverse: public Universe {
public:
Params params;
ThingySubspace outer, channel;
GpuRiemannSubspace side;
ChannelSideMetric side_metric{params};
SideBoundary sbnd{params};
InwardsBoundary ibnd{params};
ChannelBoundary cbnd{params};
EmptyBoundary bnd;
public:
MyUniverse() {
side.metric = &side_metric;
side.map = &sbnd;
ibnd.side = &side;
ibnd.channel = &channel;
cbnd.outer = &outer;
cbnd.side = &side;
sbnd.outer = &outer;
sbnd.channel = &channel;
outer.boundary = &ibnd;
// outer.boundary = &bnd;
channel.boundary = &cbnd;
thingySpaces.push_back(&outer);
thingySpaces.push_back(&channel);
}
};
MyUniverse uni;
const float off = 2.5f;
const float A = uni.params.inner_half_length + off;
const float omega = 1.0f;
const float a = .3f, b = 0.5f * a;
Sphere spheres[] = {
{1, 1000.0f, &uni.outer, {0.0f, -5000.0f, 0.0f}},
{1, 350.0f, &uni.outer, {(-uni.params.outer_half_length - 420.0f), 120.0f, 0.0f}},
{1, 200.0f, &uni.outer, {(uni.params.outer_half_length + 320.0f), -100.0f, 0.0f}},
// {0.25f, &uni.outer, {-(uni.params.outer_half_length + off), -0.5f, 0.0f}},
// {0.10f, &uni.outer, {-(uni.params.outer_half_length + off), 0.0f, 0.0f}},
};
Mesh meshes[] = {
{
2,
{{-a, -a, 0.f}, {0.f, -0.500f * a, 0.f}, {a, -a, 0.f}, {0.f, 1.414f * a, 0.f}, {0.f, -a, -0.500f * a}, {0.f, -a, 0.500f * a}},
{{0, 5, 3}, {5, 2, 3}, {2, 4, 3}, {4, 0, 3}, {5, 0, 1}, {2, 5, 1}, {4, 2, 1}, {0, 4, 1}},
&uni.outer, {-(uni.params.outer_half_length + off + 5), -2.5f, 0.0f},
},
{
2,
{{-a, -a, 0.f}, {0.f, -0.500f * a, 0.f}, {a, -a, 0.f}, {0.f, 1.414f * a, 0.f}, {0.f, -a, -0.500f * a}, {0.f, -a, 0.500f * a}},
// {{0, 5, 3}, {5, 2, 3}, {5, 0, 1}, {2, 5, 1}}, // верхняя половина — для тестирования
{{0, 5, 3}, {5, 2, 3}, {2, 4, 3}, {4, 0, 3}, {5, 0, 1}, {2, 5, 1}, {4, 2, 1}, {0, 4, 1}},
&uni.outer, {-(uni.params.outer_half_length + off), -1.0f, 0.0f}
},
{
0,
{{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}},
{{0, 1, 2}, {1, 3, 2}, {0, 2, 4}, {2, 6, 4}, {0, 4, 1}, {1, 4, 5}, {5, 6, 7}, {4, 6, 5}, {3, 5, 7}, {1, 5, 3}, {3, 7, 6}, {2, 3, 6}},
&uni.outer, {-(uni.params.outer_half_length + off + 4), 3.0f, 0.0f}
},
};
Thing *me = &meshes[0];
struct Material {
TextureCubemap *texture;
vec3 color;
float roughness;
vec3 emission;
};
Material metal = {
.texture = nullptr,
.color{0.5f, 0.5f, 0.5f},
.roughness = 0.1f,
.emission{},
};
Material sun = {
.texture = nullptr,
.color{},
.roughness{},
.emission{10.0f, 10.0f, 10.0f},
};
Material planet_1 = {
.texture = &t_planet_1,
.color{1.0f, 1.0f, 1.0f},
.roughness = -1.0f,
.emission{0.04f, 0.03f, 0.02f},
};
Material planet_2 = {
.texture = &t_planet_2,
.color{1.0f, 1.0f, 1.0f},
.roughness = -1.0f,
.emission{0.04f, 0.04f, 0.03f},
};
std::unordered_map<const Thing *, const Material *> materials = {
{&spheres[0], &sun},
{&spheres[1], &planet_1},
{&spheres[2], &planet_2},
{&meshes[0], &metal},
{&meshes[1], &metal},
{&meshes[2], &metal},
};
void init() {
for (auto &sphere: spheres)
uni.things.push_back(&sphere);
for (auto &th: meshes)
uni.things.push_back(&th);
for (auto &th: uni.things)
th->loc.rot = mat3(1.0f);
}
namespace settings {
float rays = 240;
int refine = 1;
int trace_limit = 10;
bool show_frame = false;
bool show_previews = false;
bool physical_acceleration = false;
bool mouse_control = false;
bool jet_control = false;
float movement_acceleration = 6.0f;
vec3 movement_speed = {1.0f, 6.0f, 1.0f};
vec3 rotation_speed = {2.5f, 2.5f, 0.5f};
}
bool scale_space = false;
/// Поворот на углы @p angle (yaw, pitch, roll — рысканье, тангаж, крен).
///
/// Направления осей:
/// * X — вправо
/// * Y — вперёд
/// * Z — вверх
///
/// Положительные повороты:
/// * рысканье (X) — влево
/// * тангаж (Y) — вниз
/// * крен (Z) — против часовой
mat3 rotate(vec3 angle) {
vec3 s = sin(angle), c = cos(angle);
mat3 yaw = {
c.x, s.x, 0,
-s.x, c.x, 0,
0, 0, 1,
};
mat3 pitch = {
1, 0, 0,
0, c.y, -s.y,
0, s.y, c.y,
};
mat3 roll = {
c.z, 0, s.z,
0, 1, 0,
-s.z, 0, c.z,
};
return yaw * pitch * roll;
}
/// Возвращает форму окна (x/y = ширина/высота, x⋅y = 1)
vec2 getWinShape(GLFWwindow *wnd) {
ivec2 size;
glfwGetWindowSize(wnd, &size.x, &size.y);
vec2 v = vec2(size);
return sqrt(vec2{v.x / v.y, v.y / v.x});
}
void update(GLFWwindow *wnd) {
static double t0 = 0.0;
double t = active ? glfwGetTime() - t_offset : t_frozen;
float dt = active ? t - t0 : 0.0;
t0 = t;
vec3 mov{0.0f};
vec3 rot{0.0f};
static vec3 v = {0.0f, 0.0f, 0.0f};
ivec2 wsize;
dvec2 mouse;
glfwGetCursorPos(wnd, &mouse.x, &mouse.y);
glfwGetWindowSize(wnd, &wsize.x, &wsize.y);
if (settings::mouse_control) {
vec2 ctl = clamp(2.0f * vec2(mouse) / vec2(wsize) - 1.0f, -1.0f, 1.0f);
rot.x = -ctl.x;
rot.y = ctl.y;
} else {
if (glfwGetKey(wnd, GLFW_KEY_LEFT) == GLFW_PRESS) rot.x += 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_RIGHT) == GLFW_PRESS) rot.x -= 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_UP) == GLFW_PRESS) rot.y -= 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_DOWN) == GLFW_PRESS) rot.y += 1.0f;
}
if (glfwGetKey(wnd, GLFW_KEY_W) == GLFW_PRESS) mov.y += 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_S) == GLFW_PRESS) mov.y -= 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_A) == GLFW_PRESS) mov.x -= 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_D) == GLFW_PRESS) mov.x += 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_Q) == GLFW_PRESS) rot.z += 1.0f;
if (glfwGetKey(wnd, GLFW_KEY_E) == GLFW_PRESS) rot.z -= 1.0f;
mat3 rmat = rotate(dt * settings::rotation_speed * rot);
if (settings::physical_acceleration) {
v += dt * settings::movement_acceleration * mov;
v = transpose(rmat) * v;
} else if (settings::jet_control) {
v += dt * settings::movement_acceleration * mov;
v = clamp(v, -settings::movement_speed, settings::movement_speed);
} else {
v = settings::movement_speed * mov;
}
me->rotate(rmat);
auto loc = me->loc;
try {
me->move(dt * v);
} catch (char const *) {
me->loc = loc;
v = {};
}
if (scale_space) {
static float x = 1.0f;
static float v = 0.0f;
v -= dt * omega * omega * x;
x += dt * v;
uni.params.inner_half_length = 3.0f + 2.0f * x;
uni.params.inner_pad = 0.25f;
}
try {
uni.updateCaches();
} catch (char const *) {
me->loc = loc;
v = {};
}
}
using ProgramID = GLuint;
namespace prog {
ProgramID quad;
ProgramID uv_quad;
}
namespace comp {
ProgramID side;
}
namespace tex {
TextureID objs;
}
void load_shaders() {
prog::quad = link_program({
compile_shader(GL_VERTEX_SHADER, read_file("empty.v.glsl")),
compile_shader(GL_GEOMETRY_SHADER, read_file("screen_quad.g.glsl")),
compile_shader(GL_FRAGMENT_SHADER, read_file("simple.f.glsl")),
});
prog::uv_quad = link_program({
compile_shader(GL_VERTEX_SHADER, read_file("empty.v.glsl")),
compile_shader(GL_GEOMETRY_SHADER, read_file("screen_quad.g.glsl")),
compile_shader(GL_FRAGMENT_SHADER, read_file("screen_quad_cube.f.glsl")),
});
comp::side = link_program({
compile_shader(GL_COMPUTE_SHADER, read_file("riemann.c.glsl")),
compile_shader(GL_COMPUTE_SHADER, read_file("dmetric.c.glsl")),
compile_shader(GL_COMPUTE_SHADER, read_file("side.c.glsl")),
});
}
void load_textures() {
unsigned size = 1024;
glCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &tex::objs);
// glTextureStorage3D(tex::objs, int(std::log2(size) + 1.5), GL_RGBA8, size, size, 6*4); // 8bpc is too little for linear RGB
glTextureStorage3D(tex::objs, int(std::log2(size) + 1.5), GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, size, size, 6*4);
skybox.load(size, "space");
skybox.to_gl_texture_layer(tex::objs, 0);
t_planet_1.load(2048, "jupiter");
t_planet_2.load(2048, "venus");
// load_cube_texture_layer(tex::objs, 0, "grid");
// load_cube_texture_layer(tex::objs, 1, "jupiter");
// load_cube_texture_layer(tex::objs, 2, "saturn");
// load_cube_texture_layer(tex::objs, 3, "venus");
glGenerateTextureMipmap(tex::objs);
glTextureParameteri(tex::objs, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTextureParameteri(tex::objs, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
glm::vec3 sample(glm::vec3 dir) {
return skybox.sample(dir);
}
struct VisualTraceResult {
Ray incident;
vec3 normal;
Subspace const *space = nullptr;
Thing const *thing = nullptr;
};
std::vector<VisualTraceResult> trace(std::vector<TrackPoint> rays) {
std::vector<VisualTraceResult> result(rays.size());
struct Batch {
std::vector<int> indices;
std::vector<Ray> rays;
};
std::unordered_map<Subspace const *, Batch> batches;
for (auto &&[at, pt]: enumerate(rays)) {
Batch &batch = batches[pt.space];
batch.indices.push_back(at);
batch.rays.push_back(pt);
}
for (int n = 0; !batches.empty(); n++) {
if (n >= settings::trace_limit) {
fprintf(stderr, "Warning: tracing loop aborted with %zu batches still pending\n", batches.size());
break;
}
std::unordered_map<Subspace const *, Batch> new_batches;
for (auto &&[space, batch]: batches) {
assert(batch.indices.size() == batch.rays.size());
auto results = space->trace(batch.rays);
auto flat = dynamic_cast<ThingySubspace const *>(space);
assert(results.size() == batch.rays.size());
for (int k = 0; k < batch.rays.size(); k++) {
const int at = batch.indices[k];
auto const &traced = results[k];
if (flat) {
if (auto t = flat->traceToThing(batch.rays[k]); t.thing) {
result[at] = {
.incident = t.incident,
.normal = t.normal,
.space = space,
.thing = t.thing,
};
continue;
}
}
if (traced.to.space) {
Batch &batch = new_batches[traced.to.space];
batch.indices.push_back(at);
batch.rays.push_back(traced.to);
} else {
result[at] = {
.incident = traced.end,
.space = space,
.thing = nullptr,
};
}
}
}
batches = std::move(new_batches);
}
return result;
}
static void show_texture(const void *data, ivec2 size, GLenum filter, auto prepare) {
TextureID texture = 0;
glCreateTextures(GL_TEXTURE_2D, 1, &texture);
glTextureParameteri(texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTextureParameteri(texture, GL_TEXTURE_MAG_FILTER, filter);
glTextureStorage2D(texture, 1, GL_RGBA16F, size.x, size.y);
glTextureSubImage2D(texture, 0, 0, 0, size.x, size.y, GL_RGBA, GL_FLOAT, data);
prepare(texture);
glDrawArrays(GL_POINTS, 0, 1);
glDeleteTextures(1, &texture);
}
static const int thread_count = std::thread::hardware_concurrency();
static std::vector<GLFWwindow *> background_contexts;
static void parallel(auto fn) {
std::thread ths[thread_count];
for (int th = 0; th < thread_count; th++)
ths[th] = std::thread([&, th] () {
glfwMakeContextCurrent(background_contexts[th]);
fn(th);
glfwMakeContextCurrent(nullptr);
});
for (int th = 0; th < thread_count; th++)
ths[th].join();
};
std::uint64_t rseeder() {
return glfwGetTimerValue();
}
struct RenderParams {
vec2 shape;
ivec2 ihalfsize;
ivec2 ifinesize;
ivec2 isize() const noexcept { return 2 * ihalfsize; }
int pixels() const noexcept { return 4 * ihalfsize.x * ihalfsize.y; }
int finepixels() const noexcept { return ifinesize.x * ifinesize.y; }
RenderParams(vec2 in_shape) {
shape = in_shape;
ihalfsize = settings::rays * shape;
ifinesize = 2 * settings::refine * ihalfsize;
}
};
class Renderer {
public:
Renderer(vec2 shape) :
p(shape)
{
colors.resize(p.pixels(), {0, 0, 0, 1});
}
virtual ~Renderer() = default;
virtual void render() = 0;
protected:
struct ColorTraceJob {
int pixel_index;
vec3 weight;
};
struct Batch {
std::vector<TrackPoint> trace_jobs;
std::vector<ColorTraceJob> job_infos;
Batch() = default;
Batch(int expected_size) {