-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpu.cpp
1206 lines (1061 loc) · 32.2 KB
/
gpu.cpp
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
/*!
* @file
* @brief This file contains implementation of gpu
*
* @author Tomáš Milet, imilet@fit.vutbr.cz
*
* Implemented by: Jakub Antonín Štigler (xstigl00)
*/
#include <student/gpu.hpp>
#include <algorithm>
#include <iostream>
/* double is often used instead of float because float is not precise enough.
* Even though double is slower, it is still faster than float without the
* tricks that need the precision.
*/
// used to extract attributes for vertex shader for faster iteration
struct VExtAttrib {
inline VExtAttrib(const VertexAttrib *attributes, const Buffer *buffers);
inline void set_attrib(size_t index, Attribute *out_attribs) const;
// the actual indexes
size_t ind[maxAttributes];
// sizes of the data
size_t siz[maxAttributes];
// strides
size_t str[maxAttributes];
// the coresponding buffers
const char *arr[maxAttributes];
// number of attributes
size_t cnt;
};
// contains the points of the triangle and its precalculated edges
struct Triangle {
inline Triangle(glm::dvec4 a, glm::dvec4 b, glm::dvec4 c);
// does viewport transform
inline void to_viewport(size_t width, size_t height);
// the area and side vectors are precomputed optionally
inline double get_area();
inline bool is_backface() const;
inline glm::dvec4 &operator[](size_t ind);
inline const glm::dvec4 &operator[](size_t ind) const;
// points of the triangle
glm::dvec4 a;
glm::dvec4 b;
glm::dvec4 c;
// vectors of the triangle sides (in xy 2D)
// used in many formulas -> they are precomputed here
// ab = vector from a to b
// ...
glm::dvec2 ab;
glm::dvec2 bc;
glm::dvec2 ca;
// area of the triangle * 2 (may be negative)
double area;
};
// used to extract attributes for fragment shaders
// simillar to VExtAttrib
struct FExtAttrib {
inline FExtAttrib(const AttributeType *types);
inline void set_attrib(Attribute *out_attribs, glm::vec3 pbc) const;
inline void set_arrs(OutVertex *vout);
// lineary interpolates mi and pi into mi
inline void linear_clip(size_t mi, size_t pi, Triangle &t);
// copied attributes
size_t ind[maxAttributes];
size_t siz[maxAttributes];
const uint32_t *arr[maxAttributes];
size_t cnt;
// interpolated attributes
size_t iind[maxAttributes];
size_t isiz[maxAttributes];
float *iarr[3][maxAttributes];
size_t icnt;
};
// used for rasterizing triangles
struct Rasterizer {
inline Rasterizer(
const Triangle &t,
Frame &frame,
const Program &prog,
const ShaderInterface &si,
FExtAttrib &fat,
bool &failed
);
// evaluates the equations at the given point
inline void eval_at(const double x, const double y);
// changes the evaluated point by 1 in the x axis
inline void add_x();
// changes the evaluated point by -1 in the x axis
inline void sub_x();
// changes the evaluated point by 1 in the y axis
inline void add_y();
// calls fragment shader and draws the current point
inline void draw();
// returns true if the triangle should be drawn, the template parameter
// is used for optimization
inline bool should_draw() const;
inline void save_pos();
inline void load_pos();
// functions that draw lines from the current position
// they return true if they stop on pixel (not bounding box)
inline bool draw_right();
inline bool draw_left();
inline bool skip_right();
inline bool skip_left();
// move up with both px and pt, return true if this is outside of bounding
// box, if this returns false, px and pt are different
inline bool move_up();
// tirangle to draw
const Triangle &t;
// the shader program
const Program &prog;
// the constants for shader
const ShaderInterface &si;
// the extracted attributes
const FExtAttrib &fat;
// the frame buffer
Frame &frame;
// the current pixel (float coordinates)
glm::dvec2 pt;
// the current pixel (int coordinates)
// it is not synchronized with the pt, but should be when calling the draw
// function
glm::ivec2 px;
// the color buffer
uint32_t *color;
// values of triangle side equations of pt
// thans to the transformed side vectors of the triangle t
// these are also equal to the barycentric coordinates at poin pt
double abv;
double bcv;
double cav;
// save and restore variables
glm::dvec2 spt;
glm::ivec2 spx;
double sabv;
double sbcv;
double scav;
// bottom left bounding box coordinate
glm::ivec2 bl;
// top right bounding box coordinate
glm::ivec2 tr;
};
#define DRAW_INDEXER 0x1
#define DRAW_CULLING 0x2
// clears the color/depth buffer based on the command
static inline void gpu_clear(GPUMemory &mem, const ClearCommand &cmd);
// draws triangles based on the command (wrapper for the other gpu_draw)
static inline void gpu_draw(
GPUMemory &mem,
const DrawCommand &cmd,
uint32_t draw_id
);
/**
* @brief template fro drawing
*
* @param index type when using indexer
* @param flags used to enable some features (indexer culling)
*/
template<typename type, int flags>
static inline void gpu_draw(
GPUMemory &mem,
const DrawCommand &cmd,
const uint32_t draw_id
);
// craetes the Rasterizer and rasterizes the given triangle
static inline void rasterize(
Frame &frame,
Triangle t,
const Program &prog,
const ShaderInterface &si,
FExtAttrib &fat
);
static inline uint32_t to_rgba(glm::vec4 color);
static inline glm::vec4 from_rgba(const uint32_t color);
static inline void clip_near_and_rasterize(
Frame &frame,
Triangle t,
OutVertex *vert,
const Program &prog,
const ShaderInterface &si,
FExtAttrib &fat
);
static inline glm::vec4 get_near_clip(glm::vec4 a, glm::vec4 b);
//! [gpu_execute]
void gpu_execute(GPUMemory &mem, CommandBuffer &cb) {
uint32_t draw_id = UINT32_MAX;
for (size_t i = 0; i < cb.nofCommands; ++i) {
switch (cb.commands[i].type) {
case CommandType::CLEAR:
gpu_clear(mem, cb.commands[i].data.clearCommand);
break;
case CommandType::DRAW:
gpu_draw(mem, cb.commands[i].data.drawCommand, ++draw_id);
break;
default:
break;
}
}
}
//! [gpu_execute]
static inline void gpu_clear(GPUMemory &mem, const ClearCommand &cmd) {
if (cmd.clearColor) {
std::fill_n(
reinterpret_cast<uint32_t *>(mem.framebuffer.color),
mem.framebuffer.height * mem.framebuffer.width,
to_rgba(cmd.color)
);
}
if (cmd.clearDepth) {
std::fill_n(
mem.framebuffer.depth,
mem.framebuffer.height * mem.framebuffer.width,
cmd.depth
);
}
}
// wrapper for the template funciton
static inline void gpu_draw(
GPUMemory &mem,
const DrawCommand &cmd,
const uint32_t draw_id
) {
// here are determined things like whether the culling is enabled
// so that they can be used as a compile time if expression later in the
// code
if (cmd.vao.indexBufferID < 0) {
cmd.backfaceCulling
? gpu_draw<void, DRAW_CULLING>(mem, cmd, draw_id)
: gpu_draw<void, 0>(mem, cmd, draw_id);
return;
}
switch (cmd.vao.indexType) {
case IndexType::UINT8:
cmd.backfaceCulling
? gpu_draw<uint8_t, DRAW_INDEXER | DRAW_CULLING>(
mem,
cmd,
draw_id
) : gpu_draw<uint8_t, DRAW_INDEXER>(mem, cmd, draw_id);
return;
case IndexType::UINT16:
cmd.backfaceCulling
? gpu_draw<uint16_t, DRAW_INDEXER | DRAW_CULLING>(
mem,
cmd,
draw_id
) : gpu_draw<uint16_t, DRAW_INDEXER>(mem, cmd, draw_id);
return;
case IndexType::UINT32:
cmd.backfaceCulling
? gpu_draw<uint32_t, DRAW_INDEXER | DRAW_CULLING>(
mem,
cmd,
draw_id
) : gpu_draw<uint32_t, DRAW_INDEXER>(mem, cmd, draw_id);
return;
}
}
// use template for the draw function to avoid duplicate code but don't
// sacriface performance, flags indicate the compile-time features to turn on
template<typename type, int flags>
static void gpu_draw(
GPUMemory &mem,
const DrawCommand &cmd,
const uint32_t draw_id
) {
const Program &prog = mem.programs[cmd.programID];
InVertex in_vertex{
.gl_DrawID = draw_id
};
ShaderInterface si{
.uniforms = mem.uniforms,
.textures = mem.textures,
};
// this is left out when not using indexer
const type *indexer;
if constexpr(flags & DRAW_INDEXER) {
indexer = reinterpret_cast<const type *>(
reinterpret_cast<const char *>(
mem.buffers[cmd.vao.indexBufferID].data
) + cmd.vao.indexOffset
) - 1;
}
// extract attributes
VExtAttrib vat{ cmd.vao.vertexAttrib, mem.buffers };
FExtAttrib fat{ prog.vs2fs };
// start at 2 and search the vertices backwards to avoid checks that
// cmd.nofVertices is multiple of 3
for (size_t i = 2; i < cmd.nofVertices; i += 3) {
OutVertex triangle[3];
// run the vertex shader for 3 vertices
// j starts at 2 to ensure that the vertices are processed in order
for (size_t j = 2; j != SIZE_MAX; --j) {
// set the index based on whether to use indexer
if constexpr(flags & DRAW_INDEXER)
in_vertex.gl_VertexID = *++indexer;
else
in_vertex.gl_VertexID = i - j;
// run the vertex shader
vat.set_attrib(in_vertex.gl_VertexID, in_vertex.attributes);
prog.vertexShader(triangle[2 - j], in_vertex, si);
}
Triangle t{
triangle[0].gl_Position,
triangle[1].gl_Position,
triangle[2].gl_Position
};
// skip backface triangles if culling is enabled
if constexpr(flags & DRAW_CULLING) {
// area is negative when backface
if (t.is_backface())
continue;
}
clip_near_and_rasterize(mem.framebuffer, t, triangle, prog, si, fat);
}
}
inline VExtAttrib::VExtAttrib(
const VertexAttrib *attributes,
const Buffer *buffers
) : cnt(0) {
for (size_t i = 0; i < maxAttributes; ++i) {
// filter out unused attributes
if (attributes[i].type == AttributeType::EMPTY)
continue;
ind[cnt] = i;
// type % 8
siz[cnt] = static_cast<size_t>(attributes[i].type) & 7;
str[cnt] = attributes[i].stride;
arr[cnt] = reinterpret_cast<const char *>(
buffers[attributes[i].bufferID].data
) + attributes[i].offset;
++cnt;
}
}
inline void VExtAttrib::set_attrib(size_t index, Attribute *out_attribs) const {
for (size_t j = 0; j < cnt; ++j) {
auto attrib = reinterpret_cast<uint32_t *>(out_attribs + ind[j]);
auto a = reinterpret_cast<const uint32_t *>(arr[j] + (index * str[j]));
switch (siz[j]) {
case 4:
attrib[3] = a[3];
case 3:
attrib[2] = a[2];
case 2:
attrib[1] = a[1];
case 1:
attrib[0] = a[0];
default:
break;
}
}
}
static inline void rasterize(
Frame &frame,
Triangle t,
const Program &prog,
const ShaderInterface &si,
FExtAttrib &fat
) {
t.to_viewport(frame.width, frame.height);
// prepare for rasterization
bool failed;
Rasterizer fc{ t, frame, prog, si, fat, failed };
if (failed)
return;
// the following code is quite complicated, but the idea is simple
// when you rasterize the triangle you don't have to check every pixel
// when you already find one pixel with the triangle, you can jsut check
// the neighbouring pixels.
// this algorithm searches for the triangle from the bottom left and
// once it finds the triangle, it searches from left to right while
// staying inside the triangle:
// _________
// \<<<<<<<|
// \<>>>>>|
// \<<<<<|
// \<>>>|
// \<<<|
// \<>|
// \<|
// >>>>>>>\|
//
// in reality the algorithm is much more complicated because of all the
// edge cases (such as triangles that skip some lines):
// *
// **
// *
//
// *
//
// *
// comment legend:
// ? unknown position
// > < empty position traversed in direction
// * filled position
// + current filled position
// / current empty position
// . current unknown position
#define fc_move_up() if (!fc.move_up()) return
do {
do {
// ????????????
if (fc.should_draw() || fc.skip_right()) {
// >>>>*???????
fc.draw();
fc.draw_right();
// >>>>+++*----
fc_move_up();
// ???????.????
// >>>>****----
if (fc.should_draw()) {
fc.draw();
fc.save_pos();
fc.draw_right();
fc.load_pos();
fc.draw_left();
// --+*******--
// >>>>****----
break;
}
// ???????/????
// >>>>****----
fc.save_pos();
if (fc.skip_left()) {
fc.draw();
fc.draw_left();
// --+***<<----
// >>>>****----
break;
}
fc.load_pos();
// -------/????
// >>>>****----
if (fc.skip_right()) {
fc.draw();
fc.save_pos();
fc.draw_right();
fc.load_pos();
// ------->>+*-
// >>>>****----
break;
}
// ------->>>>/
// >>>>****----
fc_move_up();
// ???????????.
// ------->>>>/
// >>>>****----
if (fc.should_draw() || fc.skip_left()) {
fc.draw();
fc.draw_left();
// ----+***<<<<
// ------->>>>/
// >>>>****----
break;
}
// /<<<<<<<<<<<
// ------->>>>/
// >>>>****----
continue;
}
// >>>>>>>>>>>/
fc_move_up();
// ???????????.
// >>>>>>>>>>>>
if (fc.should_draw() || fc.skip_left()) {
fc.draw();
fc.draw_left();
// ----+***<<<<
// >>>>>>>>>>>>
break;
}
// /<<<<<<<<<<<
// >>>>>>>>>>>>
} while (fc.move_up());
// ----+***----
while (fc.move_up()) {
// ????.???????
// ----****----
if (fc.should_draw()) {
fc.draw();
fc.save_pos();
fc.draw_left();
fc.load_pos();
fc.draw_right();
// --******+???
// ----****----
continue;
} else {
// ????/???????
// ----****----
fc.save_pos();
if (!fc.skip_right()) {
fc.load_pos();
// ????/-------
// ----****----
if (fc.skip_left()) {
fc.draw();
fc.draw_left();
// -+*<<-------
// ----****----
continue;
}
// /<<<<-------
// ----****----
break;
}
// ---->>>+????
// ----****----
fc.draw();
fc.draw_right();
// ---->>>**+--
// ----****----
}
// ----***+----
fc_move_up();
// ???????.????
// ----****----
if (fc.should_draw()) {
fc.draw();
fc.save_pos();
fc.draw_right();
fc.load_pos();
fc.draw_left();
// --+*******--
// ----****----
continue;
}
// ???????/????
// ----****----
fc.save_pos();
if (!fc.skip_left()) {
fc.load_pos();
// -------/????
// ----****----
if (!fc.skip_right()) {
fc_move_up();
// ???????????.
// ------->>>>>
// ----****----
if (fc.should_draw() || fc.skip_left()) {
fc.draw();
fc.draw_left();
// ----+***<<<<
// ------->>>>>
// ----****----
continue;
}
// /<<<<<<<<<<<
// ------->>>>>
// ----****----
break;
}
// ------->>+??
// ----****----
fc.draw();
fc.save_pos();
fc.draw_right();
fc.load_pos();
// ------->>+*-
// ----****----
continue;
}
// ?????+<<----
// ----****----
fc.draw();
fc.draw_left();
// --+***<<----
// ----****----
}
} while (fc.move_up());
#undef fc_move_up
}
static inline uint32_t to_rgba(const glm::vec4 color) {
// the small value is added to avoid rounding errors and pass tests
const uint8_t comp[] = {
static_cast<uint8_t>((color.r + 0.000001) * 255),
static_cast<uint8_t>((color.g + 0.000001) * 255),
static_cast<uint8_t>((color.b + 0.000001) * 255),
static_cast<uint8_t>((color.a + 0.000001) * 255),
};
return *reinterpret_cast<const uint32_t *>(comp);
}
static inline glm::vec4 from_rgba(const uint32_t color) {
const uint8_t *comp = reinterpret_cast<const uint8_t *>(&color);
return glm::vec4{
comp[0] / 255.f,
comp[1] / 255.f,
comp[2] / 255.f,
comp[3] / 255.f,
};
}
/* (backface = clockwise, frontface = counterclockwise)
* The triangle explained:
* A_
* |\
* ab| \ca
* | \
* V-->\
* B bc C
*
* Counterclockwise vectors:
* ab = B - A
* bc = C - B
* ca = A - C
*
* The equation for line going through the sides of the triangles so that
* when a point is evaluated on their position, it is positive when inside
* the triangle (negative when the triangle is backface)
* AB: ab.x * (y - a.y) - ab.y * (x - a.x) = 0
* BC: bc.x * (y - b.y) - bc.y * (x - b.x) = 0
* CA: ca.x * (y - c.y) - bc.y * (x - c.x) = 0
*
* The magic behind the tirangle is that the side vectors are divided
* by the area. This simplifies almost every computation with the triangle.
* Namely the barycentric coordinates and it also removes the difference
* between backside and front side triangles so there doesn't need to be
* any special cases for the two types of triangles.
*/
inline Triangle::Triangle(glm::dvec4 a, glm::dvec4 b, glm::dvec4 c)
: a(a), b(b), c(c) {}
inline void Triangle::to_viewport(size_t width, size_t height) {
// transform division to multiplication
a.w = 1 / a.w;
b.w = 1 / b.w;
c.w = 1 / c.w;
// perspective division
a.x *= a.w;
a.y *= a.w;
a.z *= a.w;
b.x *= b.w;
b.y *= b.w;
b.z *= b.w;
c.x *= c.w;
c.y *= c.w;
c.z *= c.w;
double xm = width / 2.;
double ym = height / 2.;
// transform x and y
a.x = (a.x + 1) * xm;
a.y = (a.y + 1) * ym;
b.x = (b.x + 1) * xm;
b.y = (b.y + 1) * ym;
c.x = (c.x + 1) * xm;
c.y = (c.y + 1) * ym;
// update the sides
double am = 1 / get_area();
// transform the sides so that when calculating the value of the triangle
// side equations, it is equal to the barycentric coordinates
ab *= am;
bc *= am;
ca *= am;
}
inline double Triangle::get_area() {
/* This is derived from the fact that the area of parallelogram is:
* A_________D
* / /
* / /
* /________/
* B C
*
* the absolute value of determinant:
* ||A.x - B.x C.x - B.x||
* ||A.y - B.y C.y - B.y||
*
* And the area of triangle ABC is just half of this area. The differences
* are already precomputed:
* a.x - b.x = ab.x
* ...
*
* so:
* S = ||-ab.x -bc.x||
* ||-ab.y -bc.y||
* S = |(-ab.x) * (-bc.y) - (-ab.y) * (-bc.x)|
* S = |ab.x * bc.y - ab.y * bc.x|
*
* And when we know the orientation of the triangle, we cane eliminate the
* absolute value with condition:
* S = ab.x * bc.y - ab.y * bc.x when not backface
* S = ab.y * bc.x - ab.x * bc.y when backface
*
* And the area needs to be divided by 2 to get the area of the triangle
* and not the parallelogram. This is however not done becouse in other
* calculations the 2 calncels out.
*
* The cool part is that if we don't calculate the absolute value, the sign
* tells us whether the triangle is backface or not
*/
ab.x = b.x - a.x;
ab.y = b.y - a.y;
bc.x = c.x - b.x;
bc.y = c.y - b.y;
ca.x = a.x - c.x;
ca.y = a.y - c.y;
// recalculate the area
return area = ab.x * bc.y - ab.y * bc.x;
}
inline bool Triangle::is_backface() const {
double abx = b.x / b.w - a.x / a.w;
double aby = b.y / b.w - a.y / a.w;
double bcx = c.x / c.w - b.x / b.w;
double bcy = c.y / c.w - b.y / b.w;
return abx * bcy < aby * bcx;
}
inline glm::dvec4 &Triangle::operator[](size_t ind) {
return reinterpret_cast<glm::dvec4*>(this)[ind];
}
inline const glm::dvec4 &Triangle::operator[](size_t ind) const {
return reinterpret_cast<const glm::dvec4*>(this)[ind];
}
inline Rasterizer::Rasterizer(
const Triangle &t,
Frame &frame,
const Program &prog,
const ShaderInterface &si,
FExtAttrib &fat,
bool &failed
) : t(t),
prog(prog),
color(reinterpret_cast<uint32_t *>(frame.color)),
si(si),
frame(frame),
fat(fat)
{
failed = false;
// calculate bounding box
glm::dvec2 bl{ // bottom left
std::max(0., std::min({t.a.x, t.b.x, t.c.x})),
std::max(0., std::min({t.a.y, t.b.y, t.c.y})),
};
glm::dvec2 tr{ // top right
std::min<double>(frame.width - 1, std::max({t.a.x, t.b.x, t.c.x})),
std::min<double>(frame.height - 1, std::max({t.a.y, t.b.y, t.c.y})),
};
if (bl.x >= tr.x || bl.y >= tr.y) {
failed = true;
return;
}
// make it integers
this->bl = bl;
this->tr = tr;
//this->tr.x = std::ceil(tr.x);
//this->tr.y = std::ceil(tr.y);
px = bl;
// evaluate at initial (bottom left) position
eval_at(this->bl.x + .5, this->bl.y + .5);
}
inline void Rasterizer::eval_at(const double x, const double y) {
pt = glm::vec2{ x, y };
// the subtraction is reused so that the compiler may optimize it
abv = t.ab.x * (y - t.b.y) - t.ab.y * (x - t.b.x);
bcv = t.bc.x * (y - t.b.y) - t.bc.y * (x - t.b.x);
cav = 1 - abv - bcv;
}
/* these relations are derived from the side equations, example for side AB:
* f(x, y) = t.ab.x * (y - t.a.y) - t.ab.y * (x - t.a.x)
*
* Now change x by one:
* f(x + 1, y) = t.ab.x * (y - t.a.y) - t.ab.y * (x + 1 - t.a.x)
* f(x + 1, y) = t.ab.x * (y - t.a.y) - t.ab.y * (x - t.a.x) + (-t.ab.y)
* f(x + 1, y) = f(x, y) - t.ab.y
*
* The same can be done for f(x - 1, y), f(x, y + 1) and f(x, y - 1):
* f(x - 1, y) = f(x, y) + t.ab.y
* f(x, y + 1) = f(x, y) + t.ab.x
* f(x, y - 1) = f(x, y) - t.ab.x
*/
inline void Rasterizer::add_x() {
// update the point
pt.x += 1;
// update the sides
abv -= t.ab.y;
bcv -= t.bc.y;
cav -= t.ca.y;
}
inline void Rasterizer::sub_x() {
// update the point
pt.x -= 1;
// update point evaluation
abv += t.ab.y;
bcv += t.bc.y;
cav += t.ca.y;
}
inline void Rasterizer::add_y() {
// update the point
pt.y += 1;
// update point evaluation
abv += t.ab.x;
bcv += t.bc.x;
cav += t.ca.x;
}
inline void Rasterizer::draw() {
/*std::cout
<< "a: " << std::abs(ax - bcv)
<< " b: " << std::abs(ax - bcv)
<< " c: " << std::abs(ax - bcv) << std::endl;*/
InFragment in{
.gl_FragCoord{
(float)pt.x,
(float)pt.y,
(float)(t.a.z * bcv + t.b.z * cav + t.c.z * abv),
1.f,
},
};
size_t p = px.y * frame.width + px.x;
// get perspective adjusted coordinates
double s = 1 / (bcv * t.a.w + cav * t.b.w + abv * t.c.w);
glm::vec3 pbc{ (float)(bcv * t.a.w * s), (float)(cav * t.b.w * s), (float)(abv * t.c.w * s) };
fat.set_attrib(in.attributes, pbc);
// call the shader
OutFragment out;
prog.fragmentShader(out, in, si);
if (frame.depth[p] <= in.gl_FragCoord.z)
return;
auto col = glm::clamp(out.gl_FragColor, 0.f, 1.f);
if (col.a > .5f)
frame.depth[p] = in.gl_FragCoord.z;
color[p] = to_rgba(from_rgba(color[p]) * (1 - col.a) + col * col.a);
}
inline bool Rasterizer::should_draw() const {
return abv >= 0 && bcv >= 0 && cav >= 0;
}
inline void Rasterizer::save_pos() {
spt = pt;
spx = px;
sabv = abv;
sbcv = bcv;
scav = cav;
}
inline void Rasterizer::load_pos() {
pt = spt;
px = spx;
abv = sabv;
bcv = sbcv;
cav = scav;
}
// these funcions draw lines and ensure that both px and pt stay inside the
// bounding box of the triangle. They don't do anything with the current pixel
inline bool Rasterizer::draw_right() {
for (++px.x; px.x <= tr.x; ++px.x) {
add_x();
if (!should_draw())
return true;
draw();
}
--px.x;
return false;
}
inline bool Rasterizer::draw_left() {
for (--px.x; px.x >= bl.x; --px.x) {
sub_x();
if (!should_draw())
return true;
draw();
}
++px.x;
return false;
}
inline bool Rasterizer::skip_right() {
for (++px.x; px.x <= tr.x; ++px.x) {
add_x();
if (should_draw())
return true;
}
--px.x;
return false;
}
inline bool Rasterizer::skip_left() {
for (--px.x; px.x >= bl.x; --px.x) {
sub_x();
if (should_draw())
return true;
}
++px.x;
return false;
}
inline bool Rasterizer::move_up() {
if (++px.y > tr.y)
return false;
add_y();
return true;