-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
2137 lines (2045 loc) · 73.2 KB
/
Copy pathmain.rs
File metadata and controls
2137 lines (2045 loc) · 73.2 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
use bevy::{
input::mouse::MouseMotion,
prelude::*,
window::{CursorGrabMode, WindowResolution},
};
use caw::prelude::*;
use core::f32;
use geom::{Circle, *};
use grid_2d::Coord;
use lazy_static::lazy_static;
use procgen::{FullMap, Map1, Map2};
use rand::{Rng, SeedableRng, rngs::StdRng};
use std::{
cmp::Ordering,
collections::{HashSet, VecDeque},
mem,
};
mod geom;
mod procgen;
mod rooms_and_corridors;
mod text;
const DISPLAY_WIDTH: f32 = 960.;
const DISPLAY_HEIGHT: f32 = 720.;
const TOP_LEFT_OFFSET: Vec2 = Vec2::new(-DISPLAY_WIDTH / 2., DISPLAY_HEIGHT / 2.);
const MAX_NUM_SAMPLES: usize = 6_000;
const SCALE: f32 = 20.;
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
struct HashableSeg {
start: (i32, i32),
end: (i32, i32),
}
impl HashableSeg {
fn from_seg(seg: Seg2) -> Self {
Self {
start: (seg.start.x as i32, seg.start.y as i32),
end: (seg.end.x as i32, seg.end.y as i32),
}
}
fn to_seg(self) -> Seg2 {
Seg2 {
start: Vec2::new(self.start.0 as f32, self.start.1 as f32),
end: Vec2::new(self.end.0 as f32, self.end.1 as f32),
}
}
}
#[derive(Clone)]
struct SceneTracer {
scene: Sig<SigVar<RenderedScene>>,
buf: Vec<Vec2>,
index: usize,
rng: StdRng,
}
const SCREEN_RIGHT: Seg2 = Seg2 {
start: Vec2::new(DISPLAY_WIDTH / 2., DISPLAY_HEIGHT / 2.),
end: Vec2::new(DISPLAY_WIDTH / 2., -DISPLAY_HEIGHT / 2.),
};
const SCREEN_BOTTOM: Seg2 = Seg2 {
start: Vec2::new(DISPLAY_WIDTH / 2., -DISPLAY_HEIGHT / 2.),
end: Vec2::new(-DISPLAY_WIDTH / 2., -DISPLAY_HEIGHT / 2.),
};
const SCREEN_LEFT: Seg2 = Seg2 {
start: Vec2::new(-DISPLAY_WIDTH / 2., -DISPLAY_HEIGHT / 2.),
end: Vec2::new(-DISPLAY_WIDTH / 2., DISPLAY_HEIGHT / 2.),
};
const SCREEN_TOP: Seg2 = Seg2 {
start: Vec2::new(-DISPLAY_WIDTH / 2., DISPLAY_HEIGHT / 2.),
end: Vec2::new(DISPLAY_WIDTH / 2., DISPLAY_HEIGHT / 2.),
};
fn clip_seg_within_display(mut s: Seg2) -> Seg2 {
let pad = 20.;
if let Some(clip) = s.intersect(&(SCREEN_LEFT.add_vec(Vec2::new(-pad, 0.)))) {
*s.with_x_min() = clip;
}
if let Some(clip) = s.intersect(&(SCREEN_RIGHT.add_vec(Vec2::new(pad, 0.)))) {
*s.with_x_max() = clip;
}
if let Some(clip) = s.intersect(&(SCREEN_BOTTOM.add_vec(Vec2::new(0., -pad)))) {
*s.with_y_min() = clip;
}
if let Some(clip) = s.intersect(&(SCREEN_TOP.add_vec(Vec2::new(0., pad)))) {
*s.with_y_max() = clip;
}
s
}
impl SigT for SceneTracer {
type Item = Vec2;
fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
self.buf.clear();
let scene: RenderedScene = self.scene.sample(ctx).iter().next().unwrap();
if scene.world.is_empty() {
self.buf.resize(ctx.num_samples, Vec2::ZERO);
} else {
while self.buf.len() < ctx.num_samples {
let mut start = true;
let rendered_world_seg = scene.world[self.index % scene.world.len()];
let thickness = if rendered_world_seg.mid_depth > 20. {
0.0
} else {
2.0 / rendered_world_seg.mid_depth
}
.min(2.);
let num_reps = 6;
for i in 0..num_reps {
let seg = clip_seg_within_display(rendered_world_seg.projected_seg);
let mut v = if start { seg.start } else { seg.end };
if !(i == 0 || i == num_reps - 1) {
v += Vec2 {
x: (self.rng.random::<f32>() * 2.0 - 1.0),
y: (self.rng.random::<f32>() * 2.0 - 1.0),
} * thickness;
}
self.buf.push(v);
start = !start;
}
self.index += 1;
}
}
&self.buf
}
}
lazy_static! {
static ref ARTIFACT_1_LABEL: Vec<Vec2> = render_text("ORB OF ORDER", Vec2::ZERO, 2, 0.8);
static ref ARTIFACT_1_LABEL_WIDTH: f32 = {
ARTIFACT_1_LABEL
.iter()
.map(|v| v.x)
.max_by(|a, b| a.total_cmp(b))
.unwrap()
};
static ref ARTIFACT_2_LABEL: Vec<Vec2> = render_text("ORB OF HARMONY", Vec2::ZERO, 2, 0.8);
static ref ARTIFACT_2_LABEL_WIDTH: f32 = {
ARTIFACT_2_LABEL
.iter()
.map(|v| v.x)
.max_by(|a, b| a.total_cmp(b))
.unwrap()
};
static ref ARTIFACT_3_LABEL: Vec<Vec2> = render_text("ORB OF CHAOS", Vec2::ZERO, 2, 0.8);
static ref ARTIFACT_3_LABEL_WIDTH: f32 = {
ARTIFACT_3_LABEL
.iter()
.map(|v| v.x)
.max_by(|a, b| a.total_cmp(b))
.unwrap()
};
static ref END_DOORS_LABEL: Vec<Vec2> = render_text(
"THESE DOORS WILL OPEN WHEN THE THREE ORBS HAVE BEEN RETURNED",
Vec2::ZERO,
1,
0.8
);
static ref END_DOORS_LABEL_WIDTH: f32 = {
END_DOORS_LABEL
.iter()
.map(|v| v.x)
.max_by(|a, b| a.total_cmp(b))
.unwrap()
};
static ref EXIT_LABEL: Vec<Vec2> = render_text("THE END", Vec2::ZERO, 4, 0.8);
static ref EXIT_LABEL_WIDTH: f32 = {
EXIT_LABEL
.iter()
.map(|v| v.x)
.max_by(|a, b| a.total_cmp(b))
.unwrap()
};
static ref HEALTH_SYMBOL: Vec<Vec2> = render_text("h", Vec2::ZERO, 2, 1.);
}
#[derive(Clone)]
struct ObjectRenderer<O: SigT<Item = Option<RenderedObject>>> {
object: O,
buf: Vec<Vec2>,
sample_index: u64,
text_index: usize,
rng: StdRng,
}
impl<O: SigT<Item = Option<RenderedObject>>> ObjectRenderer<O> {
fn sample_artifact3(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, -0.5 * object.height);
for _ in 0..(ctx.num_samples / 2) {
let speed = 100.;
let r = self.rng.random::<f32>() * 2.0 - 1.0;
let dx = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).cos() * r;
let dy = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).sin() * r;
let delta = Vec2::new(dx, dy) * 0.5;
self.sample_index += 1;
let mut v = offset + delta * object.height;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
while self.buf.len() < ctx.num_samples {
let mut v = (ARTIFACT_3_LABEL[self.text_index % ARTIFACT_3_LABEL.len()]
- Vec2::new(*ARTIFACT_3_LABEL_WIDTH / 2., 0.))
* object.height
* 0.005
+ offset
+ Vec2::new(0., object.height * 0.7);
v.x = v.x.clamp(object.right, object.left);
self.text_index += 1;
self.buf.push(v);
}
}
fn sample_artifact2(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, -0.5 * object.height);
for _ in 0..(ctx.num_samples / 2) {
let speed = 100.;
let dx = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).cos();
let dy = ((speed * 90.01 * self.sample_index as f32) / ctx.sample_rate_hz).sin();
let delta = Vec2::new(dx, dy) * 0.5;
self.sample_index += 1;
let mut v = offset + delta * object.height;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
while self.buf.len() < ctx.num_samples {
let mut v = (ARTIFACT_2_LABEL[self.text_index % ARTIFACT_2_LABEL.len()]
- Vec2::new(*ARTIFACT_2_LABEL_WIDTH / 2., 0.))
* object.height
* 0.005
+ offset
+ Vec2::new(0., object.height * 0.7);
v.x = v.x.clamp(object.right, object.left);
self.text_index += 1;
self.buf.push(v);
}
}
fn sample_artifact1(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, -0.5 * object.height);
for _ in 0..(ctx.num_samples / 2) {
let speed = 100.;
let effect = ((speed * 2. * self.sample_index as f32) / ctx.sample_rate_hz).sin();
let dx = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).cos() * effect;
let dy = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).sin() * effect;
let delta = Vec2::new(dx, dy) * 0.5;
self.sample_index += 1;
let mut v = offset + delta * object.height;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
while self.buf.len() < ctx.num_samples {
let mut v = (ARTIFACT_1_LABEL[self.text_index % ARTIFACT_1_LABEL.len()]
- Vec2::new(*ARTIFACT_1_LABEL_WIDTH / 2., 0.))
* object.height
* 0.005
+ offset
+ Vec2::new(0., object.height * 0.7);
v.x = v.x.clamp(object.right, object.left);
self.text_index += 1;
self.buf.push(v);
}
}
fn sample_ghost(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, object.height * -0.2);
for i in 0..ctx.num_samples {
let random_01 = self.rng.random::<f32>();
let rect = move |l: f32, t: f32, w: f32, h: f32| {
Vec2::new(l, -t) + Vec2::new(w, h) * random_01
};
let v = match (i / 4) % 2 {
0 => rect(-0.5, 1., 1., 2.),
1 => rect(-0.25, -1.25, 0.5, 0.5),
_ => unreachable!(),
};
let mut v = v * object.height + offset;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
}
fn sample_weeping_angel(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, object.height * 1.4);
let head_size = 0.25;
let body_base = -2.2;
let wing_offset_y = -0.5;
for i in 0..ctx.num_samples {
let num_reps = 2;
let v = match (i / num_reps) % 7 {
0 => {
let angle = self.rng.random::<f32>() * f32::consts::PI * 2.0;
let dist = self.rng.random::<f32>() * head_size;
Vec2::new(angle.cos() * dist, angle.sin() * dist) * 2.
}
1 => Vec2::new(
(self.rng.random::<f32>() * 2.0 - 1.) * 1.0,
body_base + (self.rng.random::<f32>() * 2.0 - 1.0) * 1.0,
),
2 | 4 | 6 => {
let angle = self.rng.random::<f32>() * f32::consts::PI * 2.0;
let dist = self.rng.random::<f32>() * 0.2;
Vec2::new(angle.cos() * dist, angle.sin() * dist)
+ Vec2::new(0.0, wing_offset_y)
}
j @ (3 | 5) => {
let offset_x = if j == 3 { -1.0 } else { 1.0 } * 2.0;
Vec2::new(
offset_x + (self.rng.random::<f32>() * 2.0 - 1.) * 0.3,
wing_offset_y - 0.5 + (self.rng.random::<f32>() * 2.0 - 1.) * 0.3,
)
}
_ => unreachable!(),
};
let mut v = v * object.height + offset;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
}
fn sample_ghost_king(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, object.height * 1.8);
let head_size = 0.25;
let body_base = -2.2;
let wing_offset_y = -0.5;
for i in 0..ctx.num_samples {
let num_reps = 1;
let v = match (i / num_reps) % 7 {
0 => {
let angle = self.rng.random::<f32>() * f32::consts::PI * 2.0;
let dist = self.rng.random::<f32>() * head_size;
Vec2::new(angle.cos() * dist, angle.sin() * dist) * 2.
}
1 => Vec2::new(
(self.rng.random::<f32>() * 2.0 - 1.) * 1.0,
body_base + (self.rng.random::<f32>() * 2.0 - 1.0) * 1.0,
),
j @ (2 | 4 | 6) => {
let offset_x = if j == 2 {
-0.5
} else if j == 4 {
0.5
} else {
0.0
};
let angle = self.rng.random::<f32>() * f32::consts::PI * 2.0;
let dist = self.rng.random::<f32>() * 0.2;
Vec2::new(angle.cos() * dist, angle.sin() * dist)
+ Vec2::new(offset_x, wing_offset_y)
}
j @ (3 | 5) => {
let offset_x = if j == 3 { -1.0 } else { 1.0 } * 2.0;
Vec2::new(
offset_x + (self.rng.random::<f32>() * 2.0 - 1.) * 0.3,
wing_offset_y - 0.5 + (self.rng.random::<f32>() * 2.0 - 1.) * 0.2,
)
}
_ => unreachable!(),
};
let mut v = v * object.height + offset;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
}
fn sample_slug(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, object.height * -1.);
for i in 0..ctx.num_samples {
let num_reps = 16;
let delta = match (i / num_reps) % 4 {
j @ (0 | 2) => {
let (mul_x, mul_y, offset_x, offset_y) =
if (i % num_reps == 0) || (i % num_reps) == num_reps - 1 {
let left = (j == 0 && i % num_reps == 0)
|| (j == 2 && i % num_reps == num_reps - 1);
let offset_x = if left { -0.2 } else { 0.2 };
(0.01, 0.1, offset_x, 0.1)
} else {
(0.9, 0.5, 0.0, 0.0)
};
let random_x = self.rng.random::<f32>() * mul_x;
let random_y = self.rng.random::<f32>() * mul_y;
let speed = 100.;
let dx = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).cos()
* random_x
+ offset_x;
let mut dy = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz)
.sin()
* random_y
+ offset_y;
dy = dy.abs();
Vec2::new(dx, dy)
}
j @ (1 | 3) => {
let scale = if (i % num_reps == 0) || (i % num_reps) == num_reps - 1 {
0.01
} else {
0.1
};
let random_x = self.rng.random::<f32>() * 2. - 1.;
let random_y = self.rng.random::<f32>() * 2. - 1.;
let speed = 100.;
let dx = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).cos()
* scale
+ random_x * 0.05;
let dy = ((speed * 60. * self.sample_index as f32) / ctx.sample_rate_hz).sin()
* scale
+ random_y * 0.05;
let offset_x = if j == 1 { 0.5 } else { -0.5 };
Vec2::new(dx, dy) + Vec2::new(offset_x, 0.8)
}
_ => unreachable!(),
};
self.sample_index += 1;
let mut v = offset + delta * object.height;
v.x = v.x.clamp(object.right, object.left);
self.buf.push(v);
}
}
fn sample_health(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, -0.5 * object.height);
while self.buf.len() < ctx.num_samples {
let mut v = (HEALTH_SYMBOL[self.text_index % HEALTH_SYMBOL.len()]
- Vec2::new(-0.5, 0.))
* object.height
* 0.05
+ offset;
v.x = v.x.clamp(object.right, object.left);
self.text_index += 1;
self.buf.push(v);
}
}
fn sample_end_doors_label(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, 0.6 * object.height);
while self.buf.len() < ctx.num_samples {
let mut v = (END_DOORS_LABEL[self.text_index % END_DOORS_LABEL.len()]
- Vec2::new(*END_DOORS_LABEL_WIDTH / 2., 0.))
* object.height
* 0.005
+ offset
+ Vec2::new(0., object.height);
v.x = v.x.clamp(object.right, object.left);
self.text_index += 1;
self.buf.push(v);
}
}
fn sample_exit(&mut self, object: &RenderedObject, ctx: &SigCtx) {
let offset = Vec2::new(object.mid, 0.0);
while self.buf.len() < ctx.num_samples {
let mut v = (EXIT_LABEL[self.text_index % EXIT_LABEL.len()]
- Vec2::new(*EXIT_LABEL_WIDTH / 2., 0.))
* object.height
* 0.005
+ offset;
v.x = v.x.clamp(object.right, object.left);
self.text_index += 1;
self.buf.push(v);
}
}
}
impl<O: SigT<Item = Option<RenderedObject>>> SigT for ObjectRenderer<O> {
type Item = Vec2;
fn sample(&mut self, ctx: &SigCtx) -> impl Buf<Self::Item> {
self.buf.clear();
let object = self.object.sample(ctx).iter().next().unwrap();
if let Some(object) = object {
match object.typ {
ObjectType::Artifact1 => self.sample_artifact1(&object, ctx),
ObjectType::Artifact2 => self.sample_artifact2(&object, ctx),
ObjectType::Artifact3 => self.sample_artifact3(&object, ctx),
ObjectType::Ghost => self.sample_ghost(&object, ctx),
ObjectType::Slug => self.sample_slug(&object, ctx),
ObjectType::WeepingAngel => self.sample_weeping_angel(&object, ctx),
ObjectType::GhostKing => self.sample_ghost_king(&object, ctx),
ObjectType::Health => self.sample_health(&object, ctx),
ObjectType::EndDoorLabel => self.sample_end_doors_label(&object, ctx),
ObjectType::Exit => self.sample_exit(&object, ctx),
}
} else {
self.buf.resize(ctx.num_samples, Vec2::ZERO);
}
&self.buf
}
}
#[allow(clippy::too_many_arguments)]
fn sig(
scene: Sig<SigVar<RenderedScene>>,
dist_to_nearest_ghost: Sig<SigVar<f32>>,
player_alive: Sig<SigVar<bool>>,
player_damage: Sig<SigVar<bool>>,
door_opening: Sig<SigVar<bool>>,
win: Sig<SigVar<bool>>,
good: Sig<SigVar<bool>>,
player_damage_passive: Sig<SigVar<bool>>,
) -> StereoPair<SigBoxed<f32>> {
let get_nth_object = {
let scene = scene.clone();
move |i: usize| scene.map(move |scene| scene.objects.get(i).cloned())
};
let _num_visible_objects = {
let scene = scene.clone();
scene.map(move |scene| scene.objects.len()).shared()
};
let nth_object_exists_mul = |i| {
(get_nth_object.clone())(i)
.map(|o| if o.is_some() { 1. } else { 0. })
.shared()
};
let max_num_objects = 9;
Stereo::new_fn_channel(|channel| {
let scene_tracer = SceneTracer {
scene: scene.clone(),
buf: Vec::new(),
index: 0,
rng: StdRng::from_rng(&mut rand::rng()),
};
let base_scale = 0.;
let post_scale = 0.001;
let base = oscillator(Sine, 30.)
.reset_offset_01(channel.circle_phase_offset_01())
.build()
* base_scale;
let object_renderers = (0..max_num_objects)
.map(|i| {
Sig(ObjectRenderer {
object: (get_nth_object.clone())(i),
buf: Vec::new(),
sample_index: 0,
text_index: 0,
rng: StdRng::from_rng(&mut rand::rng()),
})
.shared()
})
.collect::<Vec<_>>();
let make_pulse = |i: usize| {
let obj_pulse_width = 0.1;
(oscillator(Pulse, 60.)
.pulse_width_01(obj_pulse_width)
.reset_offset_01(-obj_pulse_width * i as f32)
.build()
.signed_to_01()
.inv_01()
* nth_object_exists_mul(i))
.shared()
};
let object_pulses = (0..max_num_objects).map(make_pulse).collect::<Vec<_>>();
let object_pulse_sum = object_pulses.iter().cloned().sum::<Sig<_>>();
let world_pulse = (Sig(1.) - object_pulse_sum).shared();
let dim_of_channel = move |v: Vec2| match channel {
Channel::Left => v.x,
Channel::Right => v.y,
};
let world = base
.zip(scene_tracer.clone())
.map(move |(audio_sample, scene_sample)| dim_of_channel(scene_sample) + audio_sample);
let world = world * world_pulse.clone();
let objects = object_renderers
.into_iter()
.zip(object_pulses)
.map(|(object_renderer, object_pulse)| {
object_renderer.clone().map(dim_of_channel) * object_pulse.clone()
})
.sum::<Sig<_>>();
let ghost_noise_level = dist_to_nearest_ghost.clone().map(|d| {
let min = 8.;
if d > min { 0. } else { 0.03 * (min - d) / min }
});
let death_amp_env = (adsr_linear_01(player_alive.clone())
.attack_s(0.1)
.release_s(match channel {
Channel::Left => 2.0,
Channel::Right => 1.5,
})
.build()
+ 0.0001)
.map(|x| x.min(1.));
let win_amp_env = (adsr_linear_01(win.clone().map(|b| !b))
.attack_s(0.1)
.release_s(match channel {
Channel::Left => 2.0,
Channel::Right => 2.0,
})
.build()
+ 0.0001)
.map(|x| x.min(1.));
let damage_env = adsr_linear_01(Sig(player_damage.clone()))
.release_s(1.0)
.build();
let death_noise_env = adsr_linear_01(Sig(player_alive.clone().map(|b| !b)))
.attack_s(2.)
.build();
let door_opening_shake = noise::white()
.filter(sample_and_hold(periodic_trig_s(0.05).build()))
* adsr_linear_01(door_opening.clone()).build()
* 0.01;
let good_env = adsr_linear_01(Sig(good.clone()).gate_to_trig_rising_edge())
.release_s(1.)
.build();
let good_sig = oscillator(Sine, 20.0)
.reset_offset_01(channel.circle_phase_offset_01())
.build()
* good_env
* 0.05;
let player_damage_passive_env = adsr_linear_01(player_damage_passive.clone()).build();
let player_damage_passive_sig = noise::brown() * player_damage_passive_env * 0.01;
(((((world + objects) * post_scale)
+ door_opening_shake
+ good_sig
+ player_damage_passive_sig
+ (noise::brown() * ghost_noise_level)
+ (noise::brown() * damage_env * 0.05)
+ (noise::brown() * death_noise_env * 4.))
.clamp_symetric(3.)
/ SCALE)
* death_amp_env
* win_amp_env)
.boxed()
})
}
struct AudioState {
player: PlayerOwned,
rendered_scene: Sig<SigVar<RenderedScene>>,
dist_to_nearest_ghost: Sig<SigVar<f32>>,
player_alive: Sig<SigVar<bool>>,
player_damage: Sig<SigVar<bool>>,
door_opening: Sig<SigVar<bool>>,
win: Sig<SigVar<bool>>,
good: Sig<SigVar<bool>>,
player_damage_passive: Sig<SigVar<bool>>,
}
impl AudioState {
#[allow(clippy::too_many_arguments)]
fn new(
rendered_scene: Sig<SigVar<RenderedScene>>,
dist_to_nearest_ghost: Sig<SigVar<f32>>,
player_alive: Sig<SigVar<bool>>,
player_damage: Sig<SigVar<bool>>,
door_opening: Sig<SigVar<bool>>,
win: Sig<SigVar<bool>>,
good: Sig<SigVar<bool>>,
player_damage_passive: Sig<SigVar<bool>>,
) -> Self {
let player = Player::new()
.unwrap()
.into_owned_stereo(
sig(
rendered_scene.clone(),
dist_to_nearest_ghost.clone(),
player_alive.clone(),
player_damage.clone(),
door_opening.clone(),
win.clone(),
good.clone(),
player_damage_passive.clone(),
),
ConfigOwned {
system_latency_s: 0.0167,
visualization_data_policy: Some(VisualizationDataPolicy::All),
},
)
.unwrap();
Self {
player,
rendered_scene,
dist_to_nearest_ghost,
player_alive,
player_damage,
door_opening,
win,
good,
player_damage_passive,
}
}
fn tick(&mut self, scope_state: &mut ScopeState) {
self.player.with_visualization_data_and_clear(|data| {
for chunks in data.chunks_exact(2) {
let x = chunks[0];
let y = chunks[1];
scope_state.samples.push_back(Vec2::new(x, y));
}
});
while scope_state.samples.len() > MAX_NUM_SAMPLES {
scope_state.samples.pop_front();
}
}
}
#[derive(Resource)]
struct ScopeState {
samples: VecDeque<Vec2>,
}
impl ScopeState {
fn new() -> Self {
Self {
samples: VecDeque::new(),
}
}
}
fn setup_caw_player(world: &mut World) {
let rendered_scene = sig_var(RenderedScene::default());
let dist_to_nearest_ghost = sig_var(f32::INFINITY);
let player_alive = sig_var(true);
let player_damage = sig_var(true);
let door_opening = sig_var(true);
let win = sig_var(true);
let good = sig_var(true);
let player_damage_passive = sig_var(true);
world.insert_non_send_resource(AudioState::new(
rendered_scene,
dist_to_nearest_ghost,
player_alive,
player_damage,
door_opening,
win,
good,
player_damage_passive,
));
world.insert_resource(ScopeState::new());
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
}
fn caw_tick(
state: Res<State>,
mut audio_state: NonSendMut<AudioState>,
mut scope_state: ResMut<ScopeState>,
) {
audio_state.rendered_scene.0.set(state.render());
audio_state
.dist_to_nearest_ghost
.0
.set(state.distance_from_player_to_nearest_ghost());
audio_state.player_alive.0.set(state.player.alive);
audio_state.tick(&mut scope_state);
}
fn render_scope(scope_state: Res<ScopeState>, window: Query<&Window>, mut gizmos: Gizmos) {
let color = Vec3::new(0., 1., 0.);
let mut current_color = Vec3::ZERO;
let color_step = color / scope_state.samples.len() as f32;
let scale = window.single().width() * SCALE;
let mut samples_iter = scope_state.samples.iter().map(|sample| sample * scale);
let mut prev = if let Some(first) = samples_iter.next() {
first
} else {
return;
};
for sample in samples_iter {
current_color += color_step;
gizmos.line_2d(
prev,
sample,
Color::srgba(current_color.x, current_color.y, current_color.z, 0.2),
);
prev = sample;
}
}
#[derive(Debug, Default)]
struct Meter {
current: i32,
max: i32,
}
impl Meter {
fn incr(&mut self) {
self.current = (self.current + 1).min(self.max);
}
fn decr(&mut self) {
self.current = (self.current - 1).max(0);
}
fn is_max(&self) -> bool {
self.current == self.max
}
fn is_zero(&self) -> bool {
self.current == 0
}
}
#[derive(Debug, Default)]
struct PlayerCharacter {
position: Vec2,
facing_rad: f32,
alive: bool,
health: Meter,
iframes: u64,
}
impl PlayerCharacter {
// The unit of [by] is an angle such that 1. is a reasonable amount for a single button press.
// Positive values rotate to the right (clockwise looking down).
fn rotate(&mut self, by: f32) {
self.facing_rad += by * 0.005;
}
fn facing_vec2_normalized(&self) -> Vec2 {
let x = self.facing_rad.cos();
let y = self.facing_rad.sin();
Vec2 { x, y }
}
fn facing_vec2_normalized_rev(&self) -> Vec2 {
let Vec2 { x, y } = self.facing_vec2_normalized();
// cos is symetric and sin(-y) = -sin(y)
Vec2 { x, y: -y }
}
fn left90_rev(&self) -> Vec2 {
let Vec2 { x, y } = self.facing_vec2_normalized_rev();
Vec2 { x: -y, y: x }
}
fn right90(&self) -> Vec2 {
let Vec2 { x, y } = self.facing_vec2_normalized();
Vec2 { x: y, y: -x }
}
fn transform_abs_vec2_to_rel(&self, v: Vec2) -> Vec2 {
// rotate by a 90 degree rotated facing vector so that y+ is forward
self.left90_rev().rotate(v - self.position)
}
fn is_point_in_front_of(&self, v: Vec2) -> bool {
self.transform_abs_vec2_to_rel(v).y >= 0.
}
fn debug_linestrip(&self) -> Vec<Vec2> {
vec![
self.position,
self.position + self.facing_vec2_normalized() * 5.,
]
}
fn take_damage(&mut self) {
if self.iframes == 0 {
self.health.decr();
if self.health.is_zero() {
self.alive = false;
}
self.iframes = 180;
}
}
}
#[derive(Debug)]
struct ConnectedPoint {
point: Vec2,
neighbours: Vec<Vec2>,
}
enum ConnectedPointClassification {
Stop,
ContinueLeft,
ContinueRight,
}
impl ConnectedPoint {
fn vec_from_linestrip(linestrip: &[Vec2]) -> Vec<Self> {
if linestrip.is_empty() {
return Vec::new();
}
if linestrip.len() >= 3 && linestrip[0] == linestrip[linestrip.len() - 1] {
linestrip
.iter()
.enumerate()
.map(|(i, &point)| {
let neighbours = vec![
linestrip[if i == 0 { linestrip.len() - 2 } else { i - 1 }],
linestrip[if i == linestrip.len() - 1 { 1 } else { i + 1 }],
];
Self { point, neighbours }
})
.collect()
} else {
linestrip
.iter()
.enumerate()
.map(|(i, &point)| {
let mut neighbours = Vec::new();
if i > 0 {
neighbours.push(linestrip[i - 1]);
}
if i < linestrip.len() - 1 {
neighbours.push(linestrip[i + 1]);
}
Self { point, neighbours }
})
.collect()
}
}
// Does a ray cast from the eye to `self` stop at `self` or continue past it. Equivalent to
// testing whether all neighbouring points lie on the same side of the eye->self vector.
// Operates in screen space where the eye is at the origin and is looking in the (0, 1)
// direction.
fn classify_screen_space(&self) -> ConnectedPointClassification {
let eps = 0.0001;
let this_ratio = self.point.x / self.point.y;
if self
.neighbours
.iter()
.all(|n| (n.x / n.y) <= this_ratio + eps)
{
ConnectedPointClassification::ContinueRight
} else if self
.neighbours
.iter()
.all(|n| (n.x / n.y) >= this_ratio - eps)
{
ConnectedPointClassification::ContinueLeft
} else {
ConnectedPointClassification::Stop
}
}
}
#[allow(unused)]
#[derive(Clone, Copy, Debug)]
enum ObjectType {
EndDoorLabel,
Exit,
Artifact1,
Artifact2,
Artifact3,
Ghost,
Slug,
WeepingAngel,
GhostKing,
Health,
}
impl ObjectType {
fn radius(&self) -> f32 {
match self {
Self::EndDoorLabel => 2.,
Self::Exit => 0.5,
Self::Artifact1 => 0.5,
Self::Artifact2 => 0.5,
Self::Artifact3 => 0.5,
Self::Ghost => 0.5,
Self::GhostKing => 0.5,
Self::Slug => 0.5,
Self::WeepingAngel => 1.5,
Self::Health => 0.5,
}
}
fn player_collide_radius(&self) -> f32 {
match self {
Self::WeepingAngel => 0.5,
_ => self.radius(),
}
}
}
#[derive(Clone, Copy, Debug)]
struct Object {
typ: ObjectType,
position: Vec2,
}
#[derive(Clone, Copy, Debug)]
struct ProjectedObject {
typ: ObjectType,
occluded: bool,
screen_space_seg: Seg2,
screen_space_position: Vec2,
}
#[derive(Clone, Copy, Debug)]
struct RenderedObject {
typ: ObjectType,
left: f32,
right: f32,
mid: f32,
height: f32,
}
#[derive(Clone, Copy, Default, Debug)]
struct RenderedWorldSeg {
projected_seg: Seg2,
mid_depth: f32,
}
fn render_text(text: &str, screen_coord: Vec2, num_reps: usize, char_width: f32) -> Vec<Vec2> {
let kerning = 0.2;
let scale = 20.0;
text.chars()
.enumerate()
.flat_map(|(i, ch)| {
let shape = text::char_shape(ch);
let shape = shape
.iter()
.cycle()