murrelet_gpu 0.1.2

gpu functions for murrelet, a livecode framework
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
#![allow(dead_code)]
use std::{cell::RefCell, sync::Arc};

use bytemuck::{Pod, Zeroable};
use glam::{Mat4, Vec3};
use std::rc::Rc;

#[cfg(feature = "nannou")]
use wgpu_for_nannou as wgpu;

#[cfg(not(feature = "nannou"))]
use wgpu_for_latest as wgpu;

// some wgpu things
use wgpu::util::DeviceExt;
use wgpu::TextureDescriptor;

use crate::device_state::*;
use crate::gpu_livecode::{ControlGraphics, ControlGraphicsRef};
use crate::shader_str::{VERTEX_SHADER, VERTEX_SHADER_3D};

#[cfg(not(feature = "nannou"))]
pub const DEFAULT_TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
#[cfg(feature = "nannou")]
pub const DEFAULT_TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;

#[cfg(not(feature = "nannou"))]
pub const DEFAULT_LOADED_TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
#[cfg(feature = "nannou")]
pub const DEFAULT_LOADED_TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;

fn shader_from_path(device: &wgpu::Device, data: &str) -> wgpu::ShaderModule {
    device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("Shader"),
        source: wgpu::ShaderSource::Wgsl(data.into()),
    })
}

// for each vertex, this is what we'll pass in

#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Vertex {
    position: [f32; 3],
    normal: [f32; 3],
    face_pos: [f32; 2],
}

impl Vertex {
    pub fn new(position: [f32; 3], normal: [f32; 3], face_pos: [f32; 2]) -> Self {
        Self {
            position,
            normal,
            face_pos,
        }
    }
    pub fn pos(&self) -> [f32; 3] {
        self.position
    }

    pub fn pos_vec3(&self) -> Vec3 {
        glam::vec3(self.position[0], self.position[1], self.position[2])
    }
}

unsafe impl Zeroable for Vertex {}
unsafe impl Pod for Vertex {}

// in the default vertex shader, z is dropped
pub const VERTICES: [Vertex; 4] = [
    Vertex {
        position: [-1.0, 1.0, 0.0],
        normal: [0.0, 0.0, 0.0],
        face_pos: [1.0, 0.0],
    },
    Vertex {
        position: [-1.0, -1.0, 0.0],
        normal: [0.0, 0.0, 0.0],
        face_pos: [0.0, 0.0],
    },
    Vertex {
        position: [1.0, 1.0, 0.0],
        normal: [0.0, 0.0, 0.0],
        face_pos: [1.0, 1.0],
    },
    Vertex {
        position: [1.0, -1.0, 0.0],
        normal: [0.0, 0.0, 0.0],
        face_pos: [1.0, 0.0],
    },
];

// when you want to use vertices for real!!
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct VertexUniforms {
    view_proj: [[f32; 4]; 4],  // 4x4 matrix
    light_proj: [[f32; 4]; 4], // 4x4 matrix, to make the view of the light
}
impl VertexUniforms {
    fn from_mat4(view: Mat4, light: Mat4) -> Self {
        Self {
            view_proj: view.to_cols_array_2d(),
            light_proj: light.to_cols_array_2d(),
        }
    }

    fn identity() -> VertexUniforms {
        Self::from_mat4(Mat4::IDENTITY, Mat4::IDENTITY)
    }

    fn as_bytes(&self) -> &[u8] {
        bytemuck::bytes_of(self)
    }

    fn uniforms_size(&self) -> u64 {
        std::mem::size_of::<Self>() as wgpu::BufferAddress
    }

    fn write_buffer(&self, dest: &wgpu::Buffer, queue: &wgpu::Queue) {
        queue.write_buffer(dest, 0, self.as_bytes());
    }

    fn to_buffer(&self, device: &wgpu::Device) -> wgpu::Buffer {
        device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("view and light proj buffer for 3d vertex shader"),
            size: self.uniforms_size(),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        })
    }
}

pub struct Scene {
    view: VertexUniforms, // update this as needed
}

// this is the conf that you'll interface with
#[derive(Debug, Clone)]
pub struct Triangulate {
    vertices: Vec<Vertex>,
    order: Vec<u16>,
}

impl Triangulate {
    pub fn new() -> Self {
        Triangulate {
            vertices: vec![],
            order: vec![],
        }
    }

    pub fn vertices(&self) -> &[Vertex] {
        &self.vertices
    }

    pub fn add_vertex(&mut self, v: [f32; 3], n: [f32; 3], face_pos: [f32; 2]) -> u16 {
        let vv = Vertex::new(v, n, face_pos);
        self.vertices.push(vv);
        (self.vertices.len() - 1) as u16
    }

    // alternatively can add vertices and then add teh vec
    pub fn add_rect(&mut self, v: &[Vec3; 4], flip: bool) {
        let edge1 = v[0] - v[1];
        let edge2 = v[3] - v[1];
        let normal = edge1.cross(edge2).normalize().to_array();

        let v0 = self.add_vertex(v[0].to_array(), normal, [1.0, 0.0]);
        let v1 = self.add_vertex(v[1].to_array(), normal, [0.0, 0.0]);
        let v2 = self.add_vertex(v[2].to_array(), normal, [1.0, 1.0]);
        let v3 = self.add_vertex(v[3].to_array(), normal, [0.0, 1.0]);

        if !flip {
            self.order.extend([v0, v2, v1, v1, v2, v3])
        } else {
            self.order.extend([v0, v1, v2, v1, v3, v2])
        }
    }

    fn order(&self) -> &[u16] {
        &self.order
    }

    pub fn indices(&self) -> &[u16] {
        &self.order
    }
}

// this is the conf that you'll interface with
#[derive(Debug, Clone)]
pub struct InputVertexConf {
    is_3d: bool, // todo, maybe can simplify now that i have this, e.g. vs_mod
    vs_mod: &'static str,
    view: VertexUniforms,
    topology: wgpu::PrimitiveTopology,
    vertices: Vec<Vertex>,
    order: Vec<u16>,
}

impl InputVertexConf {
    pub fn buffer_slice(&self) -> &[u16] {
        self.order.as_slice()
    }

    pub fn from_triangulate(t: &Triangulate) -> Self {
        let mut c = Self::default();
        c.is_3d = true;
        c.vs_mod = VERTEX_SHADER_3D;
        c.vertices = t.vertices.clone();
        c.order = t.order.clone();
        c
    }

    pub fn set_view(mut self, view: Mat4, light: Mat4) -> Self {
        self.view = VertexUniforms::from_mat4(view, light);
        self
    }

    pub fn vs_mod(&self, device: &wgpu::Device) -> wgpu::ShaderModule {
        shader_from_path(device, self.vs_mod)
    }

    pub fn shadow_vs_mod(&self, device: &wgpu::Device) -> wgpu::ShaderModule {
        shader_from_path(
            device,
            "
@group(0) @binding(0) var<uniform> light_proj_view: mat4x4<f32>;

@vertex
fn main(@location(0) position: vec3<f32>) -> @builtin(position) vec4<f32> {
    return light_proj_view * vec4<f32>(position, 1.0);
}",
        )
    }

    pub fn with_custom_vertices(mut self, tri: &Triangulate) -> Self {
        self.vertices = tri.vertices.clone();
        self.topology = wgpu::PrimitiveTopology::TriangleList;
        self.order = tri.order.clone();
        self
    }

    pub fn indices(&self) -> u32 {
        self.order.len() as u32
    }

    pub fn default() -> Self {
        Self {
            vs_mod: VERTEX_SHADER,
            view: VertexUniforms::identity(),
            topology: wgpu::PrimitiveTopology::TriangleList,
            vertices: VERTICES.to_vec(),
            order: vec![0, 1, 2, 1, 3, 2],
            is_3d: false,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ShaderOptions {
    sampler_address_mode_u: wgpu::AddressMode,
    sampler_address_mode_v: wgpu::AddressMode,
    sampler_address_mode_w: wgpu::AddressMode,
    sampler_mag_filter: wgpu::FilterMode,
    sampler_min_filter: wgpu::FilterMode,
    sampler_mipmap_filter: wgpu::FilterMode,
}
impl ShaderOptions {
    pub fn new() -> ShaderOptions {
        ShaderOptions {
            sampler_address_mode_u: wgpu::AddressMode::ClampToBorder,
            sampler_address_mode_v: wgpu::AddressMode::ClampToBorder,
            sampler_address_mode_w: wgpu::AddressMode::ClampToBorder,
            sampler_mag_filter: wgpu::FilterMode::Nearest,
            sampler_min_filter: wgpu::FilterMode::Nearest,
            sampler_mipmap_filter: wgpu::FilterMode::Nearest,
        }
    }

    pub fn new_with_options(
        mag_filter: wgpu::FilterMode,
        address_mode: wgpu::AddressMode,
    ) -> ShaderOptions {
        ShaderOptions {
            sampler_address_mode_u: address_mode,
            sampler_address_mode_v: address_mode,
            sampler_address_mode_w: address_mode,
            sampler_mag_filter: mag_filter,
            sampler_min_filter: wgpu::FilterMode::Nearest,
            sampler_mipmap_filter: wgpu::FilterMode::Nearest,
        }
    }

    fn as_sampler_desc(&self) -> wgpu::SamplerDescriptor {
        wgpu::SamplerDescriptor {
            address_mode_u: self.sampler_address_mode_u,
            address_mode_v: self.sampler_address_mode_v,
            address_mode_w: self.sampler_address_mode_w,
            mag_filter: self.sampler_mag_filter,
            min_filter: self.sampler_min_filter,
            mipmap_filter: self.sampler_mipmap_filter,
            ..Default::default()
        }
    }

    fn with_mag_filter(mut self, filter: wgpu::FilterMode) -> Self {
        self.sampler_mag_filter = filter;
        self
    }

    fn with_min_filter(mut self, filter: wgpu::FilterMode) -> Self {
        self.sampler_min_filter = filter;
        self
    }

    fn with_mip_map_filter(mut self, filter: wgpu::FilterMode) -> Self {
        self.sampler_mipmap_filter = filter;
        self
    }

    fn with_address_mode(mut self, address_mode: wgpu::AddressMode) -> Self {
        self.sampler_address_mode_u = address_mode;
        self.sampler_address_mode_v = address_mode;
        self.sampler_address_mode_w = address_mode;
        self
    }
}
impl Default for ShaderOptions {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Copy, Clone)]
struct TextureCreator {
    format: wgpu::TextureFormat,
}

#[derive(Debug, Clone)]
pub struct GraphicsCreator {
    first_texture: TextureCreator,
    second_texture: Option<TextureCreator>,
    details: ShaderOptions,
    color_blend: wgpu::BlendComponent,
    dst_texture: TextureCreator,
    input_vertex: InputVertexConf, // defaults to the square
}
impl Default for GraphicsCreator {
    fn default() -> Self {
        GraphicsCreator {
            first_texture: TextureCreator {
                format: DEFAULT_TEXTURE_FORMAT,
            },
            second_texture: None,
            details: ShaderOptions::new_with_options(
                wgpu::FilterMode::Linear,
                wgpu::AddressMode::ClampToEdge,
            ),
            color_blend: wgpu::BlendComponent::REPLACE,
            dst_texture: TextureCreator {
                format: DEFAULT_TEXTURE_FORMAT,
            },
            input_vertex: InputVertexConf::default(),
        }
    }
}
impl GraphicsCreator {
    pub fn with_first_texture_format(mut self, format: wgpu::TextureFormat) -> Self {
        self.first_texture = TextureCreator { format };
        self
    }

    pub fn with_second_texture(mut self) -> Self {
        self.second_texture = Some(TextureCreator {
            format: DEFAULT_TEXTURE_FORMAT,
        });
        self
    }

    pub fn with_custom_triangle(mut self, t: &Triangulate) -> Self {
        self.input_vertex = InputVertexConf::from_triangulate(t);
        self
    }

    pub fn with_second_texture_format(mut self, format: wgpu::TextureFormat) -> Self {
        self.second_texture = Some(TextureCreator { format });
        self
    }

    pub fn with_dst_format(mut self, format: wgpu::TextureFormat) -> Self {
        self.dst_texture = TextureCreator { format };
        self
    }

    pub fn with_mag_filter(mut self, filter: wgpu::FilterMode) -> Self {
        self.details = self.details.with_mag_filter(filter);
        self
    }

    pub fn with_min_filter(mut self, filter: wgpu::FilterMode) -> Self {
        self.details = self.details.with_min_filter(filter);
        self
    }

    pub fn with_mip_map_filter(mut self, filter: wgpu::FilterMode) -> Self {
        self.details = self.details.with_mip_map_filter(filter);
        self
    }

    pub fn with_color_blend(mut self, blend: wgpu::BlendComponent) -> Self {
        self.color_blend = blend;
        self
    }

    pub fn with_address_mode(mut self, address: wgpu::AddressMode) -> Self {
        self.details = self.details.with_address_mode(address);
        self
    }

    pub fn to_graphics_ref<'a>(
        &self,
        c: &GraphicsWindowConf<'a>,
        name: &str,
        fs_shader: &str,
    ) -> GraphicsRef {
        if self.color_blend != wgpu::BlendComponent::REPLACE
            && self.dst_texture.format == wgpu::TextureFormat::Rgba32Float
        {
            panic!("can't blend with float32 textures");
        }

        GraphicsRef::new(name, c, fs_shader, self)
    }

    fn is_3d(&self) -> bool {
        self.input_vertex.is_3d
    }
}

#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct BasicUniform {
    dims: [f32; 4],
    more_info: [f32; 4],
    more_info_other: [f32; 4],
}

unsafe impl Zeroable for BasicUniform {}
unsafe impl Pod for BasicUniform {}

impl BasicUniform {
    fn empty_4() -> [f32; 4] {
        [0.0, 0.0, 0.0, 0.0]
    }

    pub fn from_empty() -> BasicUniform {
        BasicUniform {
            dims: BasicUniform::empty_4(),
            more_info: BasicUniform::empty_4(),
            more_info_other: BasicUniform::empty_4(),
        }
    }

    fn _dims_to_more_info(w: f32, h: f32) -> [f32; 4] {
        [w, h, 1.0 / w, 1.0 / h]
    }

    pub fn from_dims([w, h]: [u32; 2]) -> BasicUniform {
        let w_f32 = w as f32;
        let h_f32 = h as f32;
        let dims = BasicUniform::_dims_to_more_info(w_f32, h_f32);
        BasicUniform {
            dims,
            more_info: BasicUniform::empty_4(),
            more_info_other: BasicUniform::empty_4(),
        }
    }

    pub fn from_dims_and_more([w, h]: [u32; 2], more_info: [f32; 4]) -> BasicUniform {
        let w_f32 = w as f32;
        let h_f32 = h as f32;
        let dims = BasicUniform::_dims_to_more_info(w_f32, h_f32);
        BasicUniform {
            dims,
            more_info,
            more_info_other: BasicUniform::empty_4(),
        }
    }

    pub fn update_more_info(&mut self, more_info: [f32; 4]) {
        self.more_info = more_info
    }

    pub fn update_more_info_other(&mut self, more_info: [f32; 4]) {
        self.more_info_other = more_info
    }

    fn as_bytes(&self) -> &[u8] {
        bytemuck::bytes_of(self)
    }

    fn uniforms_size(&self) -> u64 {
        std::mem::size_of::<Self>() as wgpu::BufferAddress
    }

    fn to_buffer(&self, device: &wgpu::Device) -> wgpu::Buffer {
        device.create_buffer(&wgpu::BufferDescriptor {
            label: None,
            size: self.uniforms_size(),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        })
    }

    fn copy_to_buffer(
        &self,
        dest: &wgpu::Buffer,
        device: &wgpu::Device,
        encoder: &mut wgpu::CommandEncoder,
    ) {
        encoder.copy_buffer_to_buffer(&self.to_buffer(device), 0, dest, 0, self.uniforms_size());
    }
}

pub struct UniformsPair {
    more_info: [f32; 4],
    more_info_other: [f32; 4],
}
impl UniformsPair {
    pub fn new(more_info: [f32; 4], more_info_other: [f32; 4]) -> UniformsPair {
        UniformsPair {
            more_info,
            more_info_other,
        }
    }
}

#[derive(Clone)]
pub struct GraphicsRef {
    pub graphics: Rc<RefCell<Graphics>>,
}

impl GraphicsRef {
    pub fn name(&self) -> String {
        self.graphics.borrow().name.clone()
    }

    pub fn more_info(&self) -> ([f32; 4], [f32; 4]) {
        (
            self.graphics.borrow().uniforms.more_info,
            self.graphics.borrow().uniforms.more_info_other,
        )
    }

    pub fn new_with_src<'a>(
        name: &str,
        c: &GraphicsWindowConf<'a>,
        fs_shader: &str,
        conf: &GraphicsCreator,
        assets: GraphicsAssets,
    ) -> Self {
        let graphics = Graphics::new_mut(
            name.to_string(),
            c,
            fs_shader,
            BasicUniform::from_dims(c.dims()),
            assets,
            conf.clone(),
        );
        Self { graphics }
    }

    pub fn new<'a>(
        name: &str,
        c: &GraphicsWindowConf<'a>,
        fs_shader: &str,
        conf: &GraphicsCreator,
    ) -> Self {
        Self::new_with_src(name, c, fs_shader, conf, GraphicsAssets::Nothing)
    }

    pub fn update_uniforms_other_tuple(
        &self,
        c: &GraphicsWindowConf,

        more_info: ([f32; 4], [f32; 4]),
    ) {
        let mut graphics_rc = self.graphics.borrow_mut();
        graphics_rc.update_uniforms_other_tuple(c, more_info)
    }

    pub fn render_to_view(&self, device: &DeviceState, view: &wgpu::TextureView) {
        self.graphics.borrow_mut().render(device, view)
    }

    pub fn render(&self, device: &DeviceState, other: &GraphicsRef) {
        let view = &other.graphics.borrow_mut().input_texture_view;
        self.graphics.borrow_mut().render(device, view)
    }

    pub fn render_2tex(&self, device_state: &DeviceState, other: &GraphicsRef) {
        let binding = other.graphics.borrow_mut();
        let view = binding.input_texture_view_other.as_ref().unwrap();
        self.graphics.borrow_mut().render(device_state, view)
    }

    pub fn update_uniforms(&self, c: &GraphicsWindowConf, more_info: [f32; 4]) {
        self.graphics.borrow_mut().update_uniforms(c, more_info)
    }

    pub fn update_uniforms_other(
        &self,
        c: &GraphicsWindowConf,
        more_info: [f32; 4],
        more_info_other: [f32; 4],
    ) {
        self.graphics
            .borrow_mut()
            .update_uniforms_other(c, more_info, more_info_other)
    }

    pub fn update_view(&self, c: &GraphicsWindowConf, view: Mat4, light: Mat4) {
        self.graphics.borrow_mut().update_view(c, view, light);
    }

    pub fn render_to_texture(&self, device_state: &DeviceState, texture: &wgpu::TextureView) {
        self.graphics.borrow_mut().render(device_state, texture)
    }

    pub fn input_texture_descriptor(&self) -> TextureDescriptor<'static> {
        self.graphics.borrow().texture_and_desc.desc.clone()
    }

    pub fn render_with_custom_bind_group(
        &self,
        device_state: &DeviceState,
        output_texture_view: &wgpu::TextureView,
        bind_group: &wgpu::BindGroup,
    ) {
        self.graphics.borrow().render_with_custom_bind_group(
            device_state,
            output_texture_view,
            bind_group,
        )
    }

    pub fn with_control_graphics<T>(
        &self,
        label: &'static str,
        control_graphic_fn: Arc<impl Fn(&T) -> Box<dyn ControlGraphics> + 'static>,
    ) -> GraphicsRefWithControlFn<T> {
        GraphicsRefWithControlFn {
            label,
            graphics: self.clone(),
            control_graphic_fn,
        }
    }

    pub fn graphics(&self) -> GraphicsRef {
        self.clone()
    }

    pub fn control_graphics_fn<GraphicsConf>(
        &self,
    ) -> Option<GraphicsRefWithControlFn<GraphicsConf>> {
        None
    }

    pub fn cam(&self) -> Mat4 {
        let col = self.graphics.borrow().conf.input_vertex.view.view_proj;
        Mat4::from_cols_array_2d(&col)
    }
}

#[derive(Clone)]
pub struct GraphicsRefWithControlFn<GraphicsConf> {
    pub label: &'static str,
    pub graphics: GraphicsRef,
    pub control_graphic_fn: Arc<dyn Fn(&GraphicsConf) -> Box<dyn ControlGraphics>>,
}

impl<GraphicsConf> GraphicsRefWithControlFn<GraphicsConf> {
    pub fn control_graphics(&self, conf: &GraphicsConf) -> Vec<ControlGraphicsRef> {
        let ctrl_graphics = (self.control_graphic_fn)(conf);

        ControlGraphicsRef::new(self.label, ctrl_graphics, Some(self.graphics.clone()))
    }

    pub fn graphics(&self) -> GraphicsRef {
        self.graphics.clone()
    }

    pub fn control_graphics_fn(&self) -> Option<GraphicsRefWithControlFn<GraphicsConf>> {
        // Some(self.clone())
        let c = GraphicsRefWithControlFn {
            label: self.label,
            graphics: self.graphics.clone(),
            control_graphic_fn: self.control_graphic_fn.clone(),
        };
        Some(c)
    }
}

// for now this is just so nannou can create textures...
#[derive(Debug)]
pub struct TextureAndDesc {
    pub texture: Arc<wgpu::Texture>,
    pub desc: wgpu::TextureDescriptor<'static>,
}

pub struct TextureFor3d {
    shadow_pipeline: wgpu::RenderPipeline,
    depth_view: wgpu::TextureView,
    shadow_view: wgpu::TextureView,
    shadow_sampler: wgpu::Sampler,
    shadow_bind_group: wgpu::BindGroup,
    shadow_bind_group_layout: wgpu::BindGroupLayout,
}

// represents things needed to create a single texture... it's a bit of a mess
pub struct Graphics {
    name: String,
    conf: GraphicsCreator,
    bind_group: wgpu::BindGroup,
    vertex_buffers: VertexBuffers,
    render_pipeline: wgpu::RenderPipeline,
    pub uniforms: BasicUniform,
    pub uniforms_buffer: wgpu::Buffer, // used internally
    pub input_texture_view: wgpu::TextureView,
    pub input_texture_view_other: Option<wgpu::TextureView>,
    sampler: wgpu::Sampler,
    bind_group_layout: wgpu::BindGroupLayout,
    // i guess need this to create nannou texture
    pub texture_and_desc: TextureAndDesc,
    pub other_texture_and_desc: Option<TextureAndDesc>,
    textures_for_3d: Option<TextureFor3d>,
}

impl Graphics {
    pub fn update_uniforms(&mut self, c: &GraphicsWindowConf, more_info: [f32; 4]) {
        let queue = &c.device.queue();
        self.uniforms.more_info = more_info;

        // println!("{:?}", self.uniform.more_info);
        queue.write_buffer(&self.uniforms_buffer, 0, self.uniforms.as_bytes());
    }

    pub fn update_uniforms_other(
        &mut self,
        c: &GraphicsWindowConf,
        more_info: [f32; 4],
        more_info_other: [f32; 4],
    ) {
        let queue = &c.device.queue();
        self.uniforms.more_info = more_info;
        self.uniforms.more_info_other = more_info_other;

        // println!("{:?}", self.uniform.more_info);
        queue.write_buffer(&self.uniforms_buffer, 0, self.uniforms.as_bytes());
    }

    pub fn update_uniforms_other_tuple(
        &mut self,
        c: &GraphicsWindowConf,
        more_info: ([f32; 4], [f32; 4]),
    ) {
        let (more_info, more_info_other) = more_info;
        self.update_uniforms_other(c, more_info, more_info_other)
    }

    pub fn update_uniforms_pair(&mut self, c: &GraphicsWindowConf, more_info: UniformsPair) {
        let UniformsPair {
            more_info,
            more_info_other,
        } = more_info;
        self.update_uniforms_other(c, more_info, more_info_other)
    }

    // create a texture
    pub fn texture(
        dim: [u32; 2],
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
    ) -> TextureAndDesc {
        let desc = wgpu::TextureDescriptor {
            size: wgpu::Extent3d {
                width: dim[0],
                height: dim[1],
                depth_or_array_layers: 1,
            },
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            label: None,
            view_formats: &[],
        };

        TextureAndDesc {
            texture: Arc::new(device.create_texture(&desc)),
            desc,
        }
    }

    fn _bind_group_layout(
        device: &wgpu::Device,
        has_second_texture: bool,
        multisampled: bool,
        is_3d: bool,
    ) -> wgpu::BindGroupLayout {
        let mut bind_group_offset = 0;

        let mut bind_group_layout_entries = Vec::new();
        bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
            binding: 0 as u32, // needs to line up with @group(0) @binding(1)
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                view_dimension: wgpu::TextureViewDimension::D2,
                multisampled,
            },
            count: None,
        });

        if has_second_texture {
            bind_group_offset += 1;
            bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                binding: 1 as u32, // needs to line up with @group(0) @binding(0)
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Texture {
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                    view_dimension: wgpu::TextureViewDimension::D2,
                    multisampled,
                },
                count: None,
            });
        }

        // next is the sampler
        bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
            binding: bind_group_offset + 1,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
            count: None,
        });

        // and finally the uniforms
        bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
            binding: bind_group_offset + 2,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        });

        if is_3d {
            // hrm, so hopefully won't have two inputs as well!

            // and finish up with vertex uniforms if we'll use them
            bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                binding: 3,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            });

            bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                binding: 4,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Texture {
                    multisampled: false,
                    view_dimension: wgpu::TextureViewDimension::D2,
                    sample_type: wgpu::TextureSampleType::Depth,
                },
                count: None,
            });

            bind_group_layout_entries.push(wgpu::BindGroupLayoutEntry {
                binding: 5,
                visibility: wgpu::ShaderStages::FRAGMENT,
                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
                count: None,
            });
        }

        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: None,
            entries: &bind_group_layout_entries,
        })
    }

    fn _sampler(device: &wgpu::Device, details: ShaderOptions) -> wgpu::Sampler {
        let sampler_desc = details.as_sampler_desc();
        let sampler = device.create_sampler(&sampler_desc);
        println!("sampler: {:?}, {:?}", sampler, sampler_desc);
        sampler
    }

    fn _bind_group(
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        input_texture_view: &wgpu::TextureView,
        input_texture_view_other: &Option<wgpu::TextureView>,
        initial_uniform_buffer: &wgpu::Buffer,
        initial_camera: Option<&wgpu::Buffer>,
        views_for_3d: &Option<TextureFor3d>,
        sampler: &wgpu::Sampler,
    ) -> wgpu::BindGroup {
        let mut entries = Vec::new();

        let mut binding_offset = 0;

        entries.push(wgpu::BindGroupEntry {
            binding: 0,
            resource: wgpu::BindingResource::TextureView(&input_texture_view),
        });
        if let Some(texture_view_other) = input_texture_view_other {
            entries.push(wgpu::BindGroupEntry {
                binding: 1,
                resource: wgpu::BindingResource::TextureView(&texture_view_other),
            });
            binding_offset += 1;
        }

        // next is the sampler
        entries.push(wgpu::BindGroupEntry {
            binding: binding_offset + 1,
            resource: wgpu::BindingResource::Sampler(&sampler),
        });

        entries.push(wgpu::BindGroupEntry {
            binding: binding_offset + 2,
            resource: initial_uniform_buffer.as_entire_binding(),
        });

        // if it's 3d, add the camera and light
        if let Some(cam) = initial_camera {
            assert!(binding_offset != 3); // shoulnd't have two texture for 3d!
            entries.push(wgpu::BindGroupEntry {
                binding: 3,
                resource: cam.as_entire_binding(),
            });

            // this should be set too, can make this nicer
            if let Some(v) = &views_for_3d {
                entries.push(wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::TextureView(&v.shadow_view),
                });

                entries.push(wgpu::BindGroupEntry {
                    binding: 5,
                    resource: wgpu::BindingResource::Sampler(&v.shadow_sampler),
                });
            }
        }

        let bf: wgpu::BindGroupDescriptor = wgpu::BindGroupDescriptor {
            label: None,
            layout,
            entries: &entries,
        };

        device.create_bind_group(&bf)
    }

    fn _render_pipeline(
        vertex_conf: &InputVertexConf,
        device: &wgpu::Device,
        bind_group_layout: &wgpu::BindGroupLayout,
        fs_mod: &wgpu::ShaderModule,
        dst_format: wgpu::TextureFormat,
    ) -> wgpu::RenderPipeline {
        let pipeline_layout = Graphics::_pipeline_layout(device, bind_group_layout);

        let vertex_buffer_layouts = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x2],
        };

        let primitive = wgpu::PrimitiveState {
            topology: vertex_conf.topology,
            cull_mode: None,
            // cull_mode: Some(wgpu::Face::Back),
            ..wgpu::PrimitiveState::default()
        };

        let color_state = vec![Some(wgpu::ColorTargetState {
            format: dst_format,
            blend: Some(wgpu::BlendState::REPLACE), //None,
            write_mask: wgpu::ColorWrites::ALL,
        })];

        let depth_stencil = if vertex_conf.is_3d {
            Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: Default::default(),
            })
        } else {
            None
        };

        let rp_desc = wgpu::RenderPipelineDescriptor {
            label: None,
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &vertex_conf.vs_mod(device),
                entry_point: "main",
                buffers: &[vertex_buffer_layouts.clone()],
                #[cfg(not(feature = "nannou"))]
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            primitive,
            depth_stencil,
            multisample: wgpu::MultisampleState::default(),
            fragment: Some(wgpu::FragmentState {
                module: &fs_mod,
                entry_point: "main",
                targets: &color_state,
                #[cfg(not(feature = "nannou"))]
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            multiview: None,
            // cache: None,
        };

        let main_pipeline = device.create_render_pipeline(&rp_desc);

        main_pipeline
    }

    fn _pipeline_layout(
        device: &wgpu::Device,
        bind_group_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::PipelineLayout {
        let desc = wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &[bind_group_layout],
            push_constant_ranges: &[],
        };
        device.create_pipeline_layout(&desc)
    }

    pub fn new_mut(
        name: String,
        c: &GraphicsWindowConf,
        fs_shader_data: &str,
        initial_uniform: BasicUniform,
        texture_src_path: GraphicsAssets,
        conf: GraphicsCreator,
    ) -> Rc<RefCell<Self>> {
        // todo, i used to have code here to check the conf's destination texture was okay

        let g = Graphics::new(
            name,
            c,
            fs_shader_data,
            initial_uniform,
            texture_src_path,
            conf,
        );

        Rc::new(RefCell::new(g))
    }

    pub fn new<'a>(
        name: String,
        c: &GraphicsWindowConf<'a>,
        fs_shader_data: &str,
        initial_uniform: BasicUniform,
        texture_src_path: GraphicsAssets,
        conf: GraphicsCreator,
    ) -> Self {
        let conf_c = conf.clone();
        let has_second_texture = conf.second_texture.is_some();
        let details = conf.details;
        let first_format = conf.first_texture.format;
        let second_format = conf.second_texture.map(|x| x.format);
        let dst_format = conf.dst_texture.format;

        let device = c.device.device();
        // todo, figure out msaa samples
        // let msaa_samples = 1;

        let fs_mod = shader_from_path(device, fs_shader_data);

        // make a bind group layout

        let first_texture_format = texture_src_path.to_format(first_format);
        let texture_and_desc = Graphics::texture(c.dims, device, first_texture_format);
        let input_texture = &texture_and_desc.texture;

        // maybe load the image source if we have one
        texture_src_path.maybe_load_texture(c.device, input_texture);

        let input_texture_view = input_texture.create_view(&Default::default());

        println!("input {:?}", input_texture_view);
        let (input_texture_view_other, other_texture_and_desc) = if has_second_texture {
            let other_texture = Graphics::texture(c.dims(), device, second_format.unwrap());
            println!("other texture view {:?}", &other_texture.texture);
            (
                Some(other_texture.texture.create_view(&Default::default())),
                Some(other_texture),
            )
        } else {
            (None, None)
        };
        println!("other input {:?}", input_texture_view_other);

        let sampler = Graphics::_sampler(device, details);
        let bind_group_layout = Graphics::_bind_group_layout(
            device,
            has_second_texture,
            false,
            conf.input_vertex.is_3d,
        );

        let initial_uniform_buffer = initial_uniform.to_buffer(device);

        let render_pipeline = Graphics::_render_pipeline(
            &conf.input_vertex,
            device,
            &bind_group_layout,
            &fs_mod,
            dst_format,
        );

        let vertex_buffers = VertexBuffers::from_conf(device, &conf.input_vertex);

        let textures_for_3d = if conf.input_vertex.is_3d {
            let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
                size: wgpu::Extent3d {
                    width: c.dims[0],
                    height: c.dims[1],
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Depth32Float,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                label: Some("Depth Texture"),
                view_formats: &[],
            });
            let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());

            let shadow_texture = device.create_texture(&wgpu::TextureDescriptor {
                size: wgpu::Extent3d {
                    width: c.dims[0],
                    height: c.dims[1],
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Depth32Float,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                label: Some("Shadow Texture"),
                view_formats: &[],
            });
            let shadow_view = shadow_texture.create_view(&wgpu::TextureViewDescriptor::default());

            let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("Shadow Sampler"),
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                address_mode_w: wgpu::AddressMode::ClampToEdge,
                mag_filter: wgpu::FilterMode::Linear, // make it smooth
                min_filter: wgpu::FilterMode::Linear,
                mipmap_filter: wgpu::FilterMode::Nearest,
                compare: Some(wgpu::CompareFunction::LessEqual), // for comparison!
                lod_min_clamp: 0.0,
                lod_max_clamp: 1.0,
                anisotropy_clamp: 1,
                border_color: Default::default(),
            });

            let shadow_bind_group_layout =
                device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                    entries: &[wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::VERTEX, // | wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Uniform,
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    }],
                    label: Some("Shadow Bind Group Layout"),
                });

            let shadow_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                layout: &shadow_bind_group_layout, // Matches the shadow pipeline layout
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: vertex_buffers.uniform.as_entire_binding(),
                }],
                label: Some("Shadow Bind Group"),
            });

            // needs to be same
            let vertex_buffer_layouts = wgpu::VertexBufferLayout {
                array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
                step_mode: wgpu::VertexStepMode::Vertex,
                attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x2],
            };

            let shadow_pipeline_layout =
                device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: Some("Shadow Pipeline Layout"),
                    bind_group_layouts: &[&shadow_bind_group_layout], // This must match the bind groups used
                    push_constant_ranges: &[],
                });
            let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                layout: Some(&shadow_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &conf.input_vertex.shadow_vs_mod(device),
                    entry_point: "main",
                    buffers: &[vertex_buffer_layouts],
                    #[cfg(not(feature = "nannou"))]
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: None,
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    cull_mode: None,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth32Float,
                    depth_write_enabled: true,
                    depth_compare: wgpu::CompareFunction::Less, // Closer depth wins
                    stencil: wgpu::StencilState::default(),
                    bias: Default::default(),
                }),
                multisample: wgpu::MultisampleState::default(),
                label: Some("shadow pipeline`"),
                multiview: None,
            });

            Some(TextureFor3d {
                depth_view,
                shadow_view,
                shadow_pipeline,
                shadow_sampler,
                shadow_bind_group,
                shadow_bind_group_layout,
            })
        } else {
            None
        };

        let bind_group = Graphics::_bind_group(
            device,
            &bind_group_layout,
            &input_texture_view,
            &input_texture_view_other,
            &initial_uniform_buffer,
            if conf.input_vertex.is_3d {
                Some(&vertex_buffers.uniform)
            } else {
                None
            },
            &textures_for_3d,
            &sampler,
        );

        Self {
            name,
            conf: conf_c,
            render_pipeline,
            bind_group,
            uniforms: initial_uniform,
            uniforms_buffer: initial_uniform_buffer,
            vertex_buffers,
            input_texture_view,
            input_texture_view_other,
            // things i might need to create custom bind groups later
            sampler,
            bind_group_layout,
            // things needed mostly for nannou right now..
            texture_and_desc,
            other_texture_and_desc,
            textures_for_3d,
        }
    }

    pub fn make_new_custom_bind_group(
        &self,
        device: &wgpu::Device,
        texture_view: &wgpu::TextureView,
    ) -> wgpu::BindGroup {
        println!("making custom {:?} {:?}", texture_view, self.sampler);

        Graphics::_bind_group(
            device,
            &self.bind_group_layout,
            texture_view,
            &self.input_texture_view_other, // i don't know what to do with this, leave it None or let there be one..
            &self.uniforms_buffer,
            if self.conf.input_vertex.is_3d {
                Some(&self.vertex_buffers.uniform)
            } else {
                None
            },
            &self.textures_for_3d,
            &self.sampler,
        )
    }

    pub fn depth_stencil_attachment(&self) -> Option<wgpu::RenderPassDepthStencilAttachment> {
        if let Some(TextureFor3d { depth_view, .. }) = &self.textures_for_3d {
            Some(wgpu::RenderPassDepthStencilAttachment {
                view: depth_view,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    #[cfg(feature = "nannou")]
                    store: true,
                    #[cfg(not(feature = "nannou"))]
                    store: wgpu::StoreOp::Store,
                }),
                stencil_ops: None,
            })
        } else {
            None
        }
    }

    pub fn render_with_custom_bind_group(
        &self,
        device_state: &DeviceState,
        output_texture_view: &wgpu::TextureView,
        bind_group: &wgpu::BindGroup,
    ) {
        let mut encoder = device_state
            .device()
            .create_command_encoder(&Default::default());

        {
            // do the shadow pass if needed
            if let Some(TextureFor3d {
                shadow_view,
                shadow_pipeline,
                shadow_bind_group,
                ..
            }) = &self.textures_for_3d
            {
                let mut shadow_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("Shadow Pass"),
                    color_attachments: &[],
                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                        view: &shadow_view,
                        depth_ops: Some(wgpu::Operations {
                            load: wgpu::LoadOp::Clear(1.0),
                            #[cfg(not(feature = "nannou"))]
                            store: wgpu::StoreOp::Store,
                            #[cfg(feature = "nannou")]
                            store: true,
                        }),
                        stencil_ops: None,
                    }),
                    #[cfg(not(feature = "nannou"))]
                    occlusion_query_set: Default::default(),
                    #[cfg(not(feature = "nannou"))]
                    timestamp_writes: Default::default(),
                });
                shadow_pass.set_pipeline(shadow_pipeline);
                shadow_pass.set_bind_group(0, &shadow_bind_group, &[]);
                shadow_pass.set_vertex_buffer(0, self.vertex_buffers.vertex.slice(..));
                shadow_pass.set_index_buffer(
                    self.vertex_buffers.index.slice(..),
                    wgpu::IndexFormat::Uint16,
                );
                shadow_pass.draw_indexed(0..self.conf.input_vertex.indices(), 0, 0..1);
                drop(shadow_pass);
            }

            let render_pass_desc = wgpu::RenderPassDescriptor {
                label: None,
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: output_texture_view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        #[cfg(not(feature = "nannou"))]
                        store: wgpu::StoreOp::Store,
                        #[cfg(feature = "nannou")]
                        store: true,
                    },
                })],
                #[cfg(not(feature = "nannou"))]
                occlusion_query_set: None,
                #[cfg(not(feature = "nannou"))]
                timestamp_writes: None,
                depth_stencil_attachment: self.depth_stencil_attachment(),
            };

            let mut rpass = encoder.begin_render_pass(&render_pass_desc);
            rpass.set_pipeline(&self.render_pipeline);
            rpass.set_bind_group(0, bind_group, &[]);
            rpass.set_vertex_buffer(0, self.vertex_buffers.vertex.slice(..));
            rpass.set_index_buffer(
                self.vertex_buffers.index.slice(..),
                wgpu::IndexFormat::Uint16,
            );
            rpass.draw_indexed(0..self.conf.input_vertex.indices(), 0, 0..1);
            drop(rpass);
        }

        device_state.queue().submit(Some(encoder.finish()));
    }

    pub fn render(&self, device: &DeviceState, output_texture_view: &wgpu::TextureView) {
        self.render_with_custom_bind_group(device, output_texture_view, &self.bind_group)
    }

    pub fn update_view(&self, c: &GraphicsWindowConf, view: Mat4, light: Mat4) {
        self.vertex_buffers.update_view(c, view, light);
    }
}

pub fn quick_texture(dims: [u32; 2], device: &wgpu::Device) -> TextureAndDesc {
    Graphics::texture(dims, device, DEFAULT_TEXTURE_FORMAT)
}

pub struct VertexBuffers {
    vertex: wgpu::Buffer,  // sets the vertices of the thing
    index: wgpu::Buffer,   // used with vertices to form triangles, using TriangleList primative
    uniform: wgpu::Buffer, // this we update to change the camera!
}

impl VertexBuffers {
    // inits them all
    fn from_conf(device: &wgpu::Device, conf: &InputVertexConf) -> Self {
        let vertex = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: None,
            contents: bytemuck::cast_slice(&conf.vertices[..]),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let order = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: None,
            contents: bytemuck::cast_slice(&conf.order[..]),
            usage: wgpu::BufferUsages::INDEX,
        });
        let uniform = conf.view.to_buffer(device);

        Self {
            vertex,
            index: order,
            uniform,
        }
    }
    fn update_view(&self, c: &GraphicsWindowConf, view: Mat4, light: Mat4) {
        let queue = c.device.queue();
        // self.conf.set_view(m); // hmm, running into borrow things here
        let v = VertexUniforms::from_mat4(view, light);

        // queue.write_buffer(&self.uniform, 0, v.as_bytes());
        v.write_buffer(&self.uniform, queue);
    }
}