This repository has been archived by the owner on May 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
graphics.cpp
1652 lines (1357 loc) · 37.1 KB
/
graphics.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
#include <iostream>
#include <algorithm>
#include <SDL.h>
using std::max;
using std::pair;
using std::swap;
using std::cout;
using std::cerr;
using std::endl;
const int WINDOW_WIDTH = 1440 / 2;
const int WINDOW_HEIGHT = 900 / 2;
const int MAX_CNT = 100;
enum ClPointType { LEFT, RIGHT, BEYOND, BEHIND, BETWEEN, ORIGN, DEST };
enum IntersectType { COLLINEAR, PARALLEL, SKEW, SKEW_CROSS, SKEW_NO_CROSS };
enum EType { TOUCHING, CROSS_LEFT, CROSS_RIGHT, INESSENTIAL };
enum PType { INSIDE, OUTSIDE }; // Внутри, снаружи
enum PolygonType1 { SIMPLE, COMPLEX }; // Простой (без самопересечений), сложный
enum PolygonType2 { CONVEX, CONCAVE }; // Выпуклый, невыпуклый
enum LineCapsType { FLAT, ROUND, SQUARE }; // Плоские, круглые, квадратные
struct Point
{
int x, y;
};
bool operator == (const Point p1, const Point p2)
{
return p1.x == p2.x && p1.y == p2.y;
}
struct Hatch
{
int count;
unsigned char h[MAX_CNT];
};
class Matrix
{
double m[4][4];
void check_index(int i, int j) const
{
if (i < 0 || j < 0 || i >= 4 || j >= 4)
{
cerr << "Error: Wrong matrix index (" << i << "," << j << ")" << endl;
exit(1);
}
}
public:
Matrix()
{
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
m[i][j] = 0.0;
}
double operator () (int i, int j) const { check_index(i,j); return m[i][j]; }
double & operator () (int i, int j) { check_index(i,j); return m[i][j]; }
Matrix operator * (const Matrix &mx) const
{
Matrix res;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
for (int k = 0; k < 4; k++)
res.m[i][j] += m[i][k] * mx.m[k][j];
return res;
}
Matrix & operator *= (const Matrix &mx) { *this = *this * mx; return *this; }
static const Matrix Diagonal()
{
Matrix res;
res.m[0][0] = 1.0;
res.m[1][1] = 1.0;
res.m[2][2] = 1.0;
res.m[3][3] = 1.0;
return res;
}
};
class Vector4
{
public:
double x, y, z, w;
Vector4(): x(0.0), y(0.0), z(0.0), w(1.0) { }
Vector4(double X, double Y, double Z): x(X), y(Y), z(Z), w(1.0) { }
Vector4(double X, double Y, double Z, double W): x(X), y(Y), z(Z), w(W) { }
Vector4 operator * (const Matrix &m) const
{
Vector4 r;
r.x = x * m(0,0) + y * m(1,0) + z * m(2,0) + w * m(3,0);
r.y = x * m(0,1) + y * m(1,1) + z * m(2,1) + w * m(3,1);
r.z = x * m(0,2) + y * m(1,2) + z * m(2,2) + w * m(3,2);
r.w = x * m(0,3) + y * m(1,3) + z * m(2,3) + w * m(3,3);
r.x /= r.w;
r.y /= r.w;
r.z /= r.w;
r.w = 1.0;
return r;
}
Vector4 & operator *= (const Matrix &m) { *this = *this * m; return *this; }
};
class Vector3
{
public:
double x, y, z;
Vector3(): x(0.0), y(0.0), z(0.0) { }
Vector3(double X, double Y, double Z): x(X), y(Y), z(Z) { }
Vector3(const Vector4 v4): x(v4.x / v4.w), y(v4.y / v4.w), z(v4.z / v4.w) { }
double Length() const { return sqrt(x*x + y*y + z*z); }
void Normalize() { *this /= Length(); }
Vector3 operator - () const { return Vector3(-x, -y, -z); }
Vector3 operator + (const Vector3 v) const { return Vector3(x + v.x, y + v.y, z + v.z); }
Vector3 operator - (const Vector3 v) const { return Vector3(x - v.x, y - v.y, z - v.z); }
double operator * (const Vector3 v) const { return x * v.x + y * v.y + z * v.z; }
Vector3 operator / (double k) const { return Vector3(x / k, y / k, z / k); }
Vector3 & operator /= (double k) { x /= k; y /= k; z /= k; return *this; }
Vector3 operator ^ (const Vector3 v) const
{
return Vector3(y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x);
}
};
class Polygon
{
int p_count;
Point p[MAX_CNT];
void check_index(int i) const
{
if (i < 0 || i >= p_count)
{
cerr << "Error: Wrong polygon index (" << i << ")" << endl;
exit(1);
}
}
public:
Polygon(int count = 0): p_count(count) { }
int count() const { return p_count; }
Point operator [] (int i) const { check_index(i); return p[i]; }
Point & operator [] (int i) { check_index(i); return p[i]; }
void operator += (Point new_p) { p[p_count++] = new_p; }
};
class RPP // Прямоугольный параллелепипед
{
public:
Vector4 a1, b1, c1, d1,
a2, b2, c2, d2;
RPP(double x, double y, double z)
{
a1 = Vector4(-x, -y, z);
b1 = Vector4(-x, y, z);
c1 = Vector4(-x, y, -z);
d1 = Vector4(-x, -y, -z);
a2 = Vector4( x, -y, z);
b2 = Vector4( x, y, z);
c2 = Vector4( x, y, -z);
d2 = Vector4( x, -y, -z);
}
void operator *= (const Matrix &m)
{
a1 *= m; b1 *= m; c1 *= m; d1 *= m;
a2 *= m; b2 *= m; c2 *= m; d2 *= m;
}
};
class RGBColor
{
public:
uint8_t r, g, b;
RGBColor(uint8_t red, uint8_t green, uint8_t blue)
: r(red), g(green), b(blue) { }
static const RGBColor White() { return RGBColor(0xFF, 0xFF, 0xFF); }
static const RGBColor Red() { return RGBColor(0xFF, 0x00, 0x00); }
static const RGBColor Green() { return RGBColor(0x00, 0xFF, 0x00); }
static const RGBColor Blue() { return RGBColor(0x00, 0x00, 0xFF); }
static const RGBColor Magenta() { return RGBColor(0xFF, 0x00, 0xFF); }
static const RGBColor Acid() { return RGBColor(0xC6, 0xFF, 0x00); }
static const RGBColor Gray(uint8_t w)
{
double wd = 0xFF / 100.0 * w;
int wi = int(0.5 + wd);
if (wi > 0xFF) wi = 0xFF;
return RGBColor(wi, wi, wi);
}
};
class SDL_class
{
SDL_Window *Window;
SDL_Renderer *Renderer;
public:
SDL_class(): Window(NULL), Renderer(NULL)
{
if (SDL_Init(SDL_INIT_VIDEO))
Error("Could not initialize SDL");
if (SDL_CreateWindowAndRenderer(0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP,
&Window, &Renderer))
Error("Could not create window and renderer");
if (SDL_RenderSetLogicalSize(Renderer, WINDOW_WIDTH, WINDOW_HEIGHT))
Error("Could not set logical size");
ClearScreen();
};
~SDL_class()
{
if (Renderer)
{
SDL_DestroyRenderer(Renderer);
Renderer = NULL;
}
if (Window)
{
SDL_DestroyWindow(Window);
Window = NULL;
}
SDL_Quit();
};
void SetPixel(int x, int y, const RGBColor &color = RGBColor::White())
{
if (SDL_SetRenderDrawColor(Renderer, color.r, color.g, color.b, 0xFF))
Error("Could not set color");
if (SDL_RenderDrawPoint(Renderer, x, y))
Error("Could not draw point");
};
void ClearScreen()
{
if (SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 0xFF))
Error("Could not set color");
if (SDL_RenderClear(Renderer))
Error("Could not clear render");
};
void UpdateScreen() { SDL_RenderPresent(Renderer); }
void Error(const char *msg)
{
cerr << "Error: " << msg << ": " << SDL_GetError() << endl;
exit(1);
};
};
typedef pair<Point, Point> PointPair;
typedef pair<Vector4, Vector4> V4Pair;
static SDL_class SDL;
static struct
{
const Vector3 center = Vector3(10, 10, 50);
const Vector3 top = Vector3(-10, -10, 200);
const int R = 100;
Matrix m_trans;
const V4Pair lines[6] = {
{{ -100, -10, 110 }, { 0, 0, 80 }}, // 1 сторона
{{ -100, 5, 110 }, { 100, 5, 90 }}, // 2 стороны
{{ 5, 15, 10 }, { 20, 25, 80 }}, // основание
{{ -100, 20, 110 }, { -10, -10, -10 }}, // сторона и основание
{{ -20, -20, 80 }, { 20, 20, 90 }}, // внутри
{{ 80, 80, 10 }, { 90, 90, 50 }} // снаружи
};
V4Pair res[6];
} test14_data;
// Переменные для анимации
static Matrix anim_rot, anim_proj;
// Helper function for Bezier_curve
int Dist(const Point p)
{
return abs(p.x) + abs(p.y);
}
// Linear interpolation of two values
double Mix(const double start, const double end, const double t)
{
return start + (end - start) * t;
}
unsigned long long Factorial(const int n)
{
unsigned long long res = 1;
for (int i = 2; i <= n; i++)
res *= i;
return res;
}
// Вычисление многочлена Бернштейна
double Bernstein(const int m, const int i, const double t)
{
return Factorial(m) / Factorial(i) / Factorial(m - i)
* pow(t, i) * pow(1 - t, m - i);
}
// Определение положения точки p относительно отрезка прямой p1-p2
ClPointType Classify(const Point p1, const Point p2, const Point p)
{
if (p == p1) return ORIGN;
if (p == p2) return DEST;
int ax = p2.x - p1.x,
ay = p2.y - p1.y,
bx = p.x - p1.x,
by = p.y - p1.y,
s = ax * by - bx * ay; // Псевдоскалярное произведение
if (0 > s) return LEFT; // Слева от прямой
if (0 < s) return RIGHT; // Справа от прямой
// Если s == 0, то p лежит на прямой.
if (0 > ax * bx || 0 > ay * by)
// Векторы p1-p2 и p1-p противонаправлены => p лежит за p1
return BEHIND;
if (ax * ax + ay * ay < bx * bx + by * by)
// Вектор p1-p длиннее p1-p2 => p лежит за p2
return BEYOND;
return BETWEEN; // p лежит между p1 и p2
}
// Определение точки пересечения прямых a-b и c-d
IntersectType Intersect(const Point a, const Point b,
const Point c, const Point d, double &t)
{
int nx = d.y - c.y,
ny = c.x - d.x;
int denom = nx * (b.x - a.x) + ny * (b.y - a.y);
if (0 == denom)
{
ClPointType type = Classify(c, d, a);
if (LEFT == type || RIGHT == type )
return PARALLEL;
else
return COLLINEAR;
}
double num = nx * (a.x - c.x) + ny * (a.y - c.y);
t = - num / denom;
return SKEW;
}
// Определение факта пересечения отрезков a-b и c-d
IntersectType Cross(const Point a, const Point b, const Point c, const Point d)
{
double tab = 0.0;
IntersectType type = Intersect(a, b, c, d, tab);
if (COLLINEAR == type || PARALLEL == type)
return type;
if (0.0 > tab || 1.0 < tab)
return SKEW_NO_CROSS;
double tcd = 0.0;
Intersect(c, d, b, a, tcd);
if (0.0 > tcd || 1.0 < tcd)
return SKEW_NO_CROSS;
return SKEW_CROSS;
}
// Классификация рёбер полигона
EType EdgeType(const Point p0, const Point p1, const Point a)
{
switch (Classify(p0, p1, a))
{
case LEFT:
if (a.y > p0.y && a.y <= p1.y)
return CROSS_LEFT;
else
return INESSENTIAL;
case RIGHT:
if (a.y > p1.y && a.y <= p0.y)
return CROSS_RIGHT;
else
return INESSENTIAL;
case BETWEEN:
case ORIGN:
case DEST:
return TOUCHING;
default:
return INESSENTIAL;
}
}
// Вычерчивание отрезка прямой линии толщиной в 1 пиксел
// (алгоритм Брезенхэма)
void Line_1px(const Point a, const Point b,
const RGBColor &color = RGBColor::White())
{
int x0 = a.x, y0 = a.y,
x1 = b.x, y1 = b.y;
bool xy = true;
if (abs(y1 - y0) > abs(x1 - x0))
{
swap(x0, y0);
swap(x1, y1);
xy = false;
}
if (y0 > y1)
{
swap(x0, x1);
swap(y0, y1);
}
int d = 0,
dx = abs(x1 - x0),
dy = abs(y1 - y0),
sx = (x0 > x1) ? -1 : 1,
x = x0,
y = y0;
if (xy) SDL.SetPixel(x, y, color);
else SDL.SetPixel(y, x, color);
while (x != x1)
{
x += sx;
d += 2 * dy;
if (d > dx)
{
y++;
d -= 2 * dx;
}
if (xy) SDL.SetPixel(x, y, color);
else SDL.SetPixel(y, x, color);
}
}
// Отрисовка полигона
void Polygon_stroke(const Polygon &p, const RGBColor &color = RGBColor::White())
{
for (int i = 0; p.count() > i; i++)
Line_1px(p[i], p[(1 + i) % p.count()], color);
}
// Определение типа полигона (простой / сложный)
PolygonType1 Polygon_type_1(const Polygon &p)
{
for (int i = 0; p.count() > i; i++)
for (int j = i; p.count() > j; j++)
if (j != i && j != (1 + i) % p.count()
&& (0 != i || j != p.count() - 1))
if (SKEW_CROSS == Cross(p[i], p[(1 + i) % p.count()],
p[j], p[(1 + j) % p.count()]))
return COMPLEX;
return SIMPLE;
}
// Определение типа полигона (выпуклый / невыпуклый)
PolygonType2 Polygon_type_2(const Polygon &p)
{
for (int i = 0; p.count() > i; i++)
{
int left = 0,
right = 0;
for (int j = 0; p.count() > j; j++)
if (j != i && j != (1 + i) % p.count())
{
if (LEFT == Classify(p[i], p[(1 + i) % p.count()], p[j]))
left++;
else
right++;
}
if (0 < left && 0 < right) return CONCAVE;
}
return CONVEX;
}
void Print_polygon_type(const Polygon &p)
{
cout << (SIMPLE == Polygon_type_1(p) ? "Простой " : "Сложный ")
<< (CONVEX == Polygon_type_2(p) ? "выпуклый" : "невыпуклый") << endl;
}
// Определение габаритного прямоугольника
PointPair overall_rectangle(const Polygon &p)
{
PointPair rect(p[0], p[0]);
for (int i = 1; p.count() > i; i++)
{
if (rect.first.x > p[i].x)
rect.first.x = p[i].x;
if (rect.first.y > p[i].y)
rect.first.y = p[i].y;
if (rect.second.x < p[i].x)
rect.second.x = p[i].x;
if (rect.second.y < p[i].y)
rect.second.y = p[i].y;
}
return rect;
}
// Правило even-odd
PType even_odd(const Polygon &p, const Point a)
{
int winding_number = 0;
for (int i = 0; p.count() > i; i++)
switch (EdgeType(p[i], p[(1 + i) % p.count()], a))
{
case TOUCHING:
return INSIDE;
case CROSS_LEFT:
case CROSS_RIGHT:
winding_number = 1 - winding_number;
case INESSENTIAL:
break;
}
return winding_number ? INSIDE : OUTSIDE;
}
// Правило non-zero winding
PType non_zero_winding(const Polygon &p, const Point a)
{
int winding_number = 0;
for (int i = 0; p.count() > i; i++)
switch (EdgeType(p[i], p[(1 + i) % p.count()], a))
{
case CROSS_LEFT:
winding_number++;
break;
case CROSS_RIGHT:
winding_number--;
break;
case TOUCHING:
case INESSENTIAL:
break;
}
return winding_number ? INSIDE : OUTSIDE;
}
// Заполнение полигона
void Polygon_fill(const Polygon &p, PType (*f)(const Polygon &, const Point),
const RGBColor &color = RGBColor::White())
{
PointPair rect = overall_rectangle(p);
for (int x = rect.first.x; rect.second.x >= x; x++)
for (int y = rect.first.y; rect.second.y >= y; y++)
if (INSIDE == (*f)(p, { x, y }))
SDL.SetPixel(x, y, color);
}
// Вычерчивание отрезка прямой линии произвольной толщины
void Line(const Point a, const Point b, const RGBColor &color = RGBColor::White(),
const int w = 1, const LineCapsType line_caps_type = FLAT)
{
if (1 == w)
return Line_1px(a, b, color);
int x0 = a.x, y0 = a.y,
x1 = b.x, y1 = b.y;
double m = w / 2;
int dx = x1 - x0,
dy = y1 - y0;
double len = sqrt(dx * dx + dy * dy);
int hx = int(0.5 + m * dy / len),
hy = int(0.5 + m * dx / len);
if (SQUARE == line_caps_type)
{
int hx = int(0.5 + m * dx / len),
hy = int(0.5 + m * dy / len);
x0 -= hx;
y0 -= hy;
x1 += hx;
y1 += hy;
}
if (ROUND == line_caps_type)
{
const int n = 16;
double a = M_PI / n;
int x = x0 - hx,
y = y0 + hy;
Polygon p(2 * n - 1);
for (int i = 0; i < n - 1; i++)
{
int xn = int(0.5 + x0 + (x - x0) * cos(a) + (y0 - y) * sin(a)),
yn = int(0.5 + y0 + (y - y0) * cos(a) + (x - x0) * sin(a));
p[i] = { xn, yn };
x = xn;
y = yn;
}
x = x1 + hx;
y = y1 - hy;
for (int i = n - 1; i < 2 * n - 1; i++)
{
int xn = int(0.5 + x1 + (x - x1) * cos(a) + (y1 - y) * sin(a)),
yn = int(0.5 + y1 + (y - y1) * cos(a) + (x - x1) * sin(a));
p[i] = { xn, yn };
x = xn;
y = yn;
}
Polygon_fill(p, even_odd, color);
}
else // FLAT or SQUARE
{
Polygon p(4);
p[0] = { x0 + hx, y0 - hy };
p[1] = { x0 - hx, y0 + hy };
p[2] = { x1 - hx, y1 + hy };
p[3] = { x1 + hx, y1 - hy };
Polygon_fill(p, even_odd, color);
}
Line(a, b, RGBColor::Red());
}
// Вычерчивание отрезка прямой линии штрихами
void Line(const Point a, const Point b, const Hatch &h,
const RGBColor &color = RGBColor::White(),
const int w = 1, const LineCapsType line_caps_type = FLAT)
{
int dx = b.x - a.x,
dy = b.y - a.y;
double len = sqrt(dx * dx + dy * dy),
hx = dx / len,
hy = dy / len;
int sum = 0;
for (int i = 0; i < h.count; i++)
sum += h.h[i];
int lines = int(len / sum);
int x = a.x,
y = a.y;
for (int i = 0; i < lines; i++)
for (int j = 0; j < h.count; j += 2)
{
double l_dx = 0.5 + h.h[j] * hx,
l_dy = 0.5 + h.h[j] * hy,
s_dx = h.h[1 + j] * hx,
s_dy = h.h[1 + j] * hy;
Point p1 = { x, y };
Point p2 = { int(x + l_dx), int(y + l_dy) };
Line(p1, p2, color, w, line_caps_type);
x += int(l_dx + s_dx);
y += int(l_dy + s_dy);
}
}
// Отсечение отрезка прямой выпуклым многоугольником
// (алгоритм Кируса-Бека)
void Clip_line(const Point &a, const Point &b, const Polygon &p)
{
double t0 = 0.0, t1 = 1.0;
for (int i = 0; p.count() > i; i++)
{
int nx = p[i].y - p[(1 + i) % p.count()].y,
ny = p[(1 + i) % p.count()].x - p[i].x;
int denom = nx * (b.x - a.x) + ny * (b.y - a.y);
if (0 != denom)
{
double num = nx * (a.x - p[i].x) + ny * (a.y - p[i].y);
double t = - num / denom;
if (0 < denom)
{
// Потенциально входящая точка
if (t > t0) t0 = t;
}
else
// Потенциально покидающая точка
if (t < t1) t1 = t;
}
else
// Отрезок a-b || грани многоугольника
if (LEFT == Classify(p[i], p[(1 + i) % p.count()], a))
// Отрезок a-b вне многоугольника
return;
}
if (t1 < t0)
return;
int x0 = 0.5 + Mix(a.x, b.x, t0),
y0 = 0.5 + Mix(a.y, b.y, t0),
x1 = 0.5 + Mix(a.x, b.x, t1),
y1 = 0.5 + Mix(a.y, b.y, t1);
Line({ x0, y0 }, { x1, y1 }, RGBColor::Red());
}
// Отсечение простого многоугольника выпуклым многоугольником
// (алгоритм Сазерлэнда-Ходжмана)
void Clip_polygon(const Polygon &p, const Polygon &clipper, Polygon &new_p)
{
Polygon old_p = p;
for (int i = 0; clipper.count() > i; i++)
{
new_p = 0;
Point e0 = clipper[i];
Point e1 = clipper[(1 + i) % clipper.count()];
for (int j = 0; old_p.count() > j; j++)
{
Point a = old_p[j];
Point b = old_p[(1 + j) % old_p.count()];
double t = 0.0;
IntersectType intersect = Intersect(a, b, e0, e1, t);
if ((SKEW == intersect) && (0.0 <= t) && (1.0 >= t))
new_p += { int(0.5 + Mix(a.x, b.x, t)),
int(0.5 + Mix(a.y, b.y, t)) };
if (RIGHT == Classify(e0, e1, b))
new_p += b;
}
old_p = new_p;
}
}
// Построение кривой Безье N-го порядка
void Bezier_curve(const Point b[], const int n = 3)
{
for (int i = 0; i < n; i++)
Line(b[i], b[1 + i], RGBColor::Red());
double step;
if (3 == n)
{
Point d0 = { b[0].x - 2 * b[1].x + b[2].x,
b[0].y - 2 * b[1].y + b[2].y };
Point d1 = { b[1].x - 2 * b[2].x + b[3].x,
b[1].y - 2 * b[2].y + b[3].y };
double d = max(Dist(d0), Dist(d1));
step = 1 / (1 + sqrt(3 * d));
}
else
step = 0.01;
Point R_prev = b[0];
for (double t = step; t < 1.0; t += step)
{
double Rx = 0.0, Ry = 0.0;
for (int i = 0; i <= n; i++)
{
double B = Bernstein(n, i, t);
Rx += B * b[i].x;
Ry += B * b[i].y;
}
Point R = { int(0.5 + Rx), int(0.5 + Ry) };
Line(R_prev, R);
R_prev = R;
}
Line(R_prev, b[n]);
}
// Вычисление 3D координат точки на кривой Безье 3-го порядка
void Bezier_coord(const Vector4 b[], const double t, Vector4 &res)
{
res = Vector4(0, 0, 0, 1);
for (int i = 0; i <= 3; i++)
{
double B = Bernstein(3, i, t);
res.x += B * b[i].x;
res.y += B * b[i].y;
res.z += B * b[i].z;
}
}
// Построение кубической B-сплайновой кривой
void B_spline(const Point p0, const Point p1, const Point p2, const Point p3)
{
Line(p0, p1, RGBColor::Red());
Line(p1, p2, RGBColor::Red());
Line(p2, p3, RGBColor::Red());
const double step = 0.03;
Point R_prev;
R_prev.x = int(0.5 + p0.x / 6.0 + 4.0 / 6 * p1.x + p2.x / 6.0);
R_prev.y = int(0.5 + p0.y / 6.0 + 4.0 / 6 * p1.y + p2.y / 6.0);
for (double t = step; t <= 1.0; t += step)
{
double k0 = (1 - t) * (1 - t) * (1 - t) / 6,
k1 = (3 * t * t * t - 6 * t * t + 4) / 6,
k2 = (-3 * t * t * t + 3 * t * t + 3 * t + 1) / 6,
k3 = t * t * t / 6;
double Rx = k0 * p0.x + k1 * p1.x + k2 * p2.x + k3 * p3.x,
Ry = k0 * p0.y + k1 * p1.y + k2 * p2.y + k3 * p3.y;
Point R = { int(0.5 + Rx), int(0.5 + Ry) };
Line(R_prev, R);
R_prev = R;
}
}
// Матрица перемещения
void MovementMatrix(const Vector3 &v, Matrix &m)
{
m = Matrix::Diagonal();
m(3,0) = v.x;
m(3,1) = v.y;
m(3,2) = v.z;
}
// Матрица поворота вокруг оси axis на угол angle (в радианах)
void RotationMatrix(const Vector3 &axis, const double angle, Matrix &m)
{
Vector3 norm_axis = axis;
norm_axis.Normalize();
double x = norm_axis.x,
y = norm_axis.y,
z = norm_axis.z,
c = cos(angle),
s = sin(angle);
m = Matrix::Diagonal();
m(0,0) = x * x + (1.0 - x * x) * c;
m(0,1) = x * y * (1.0 - c) + z * s;
m(0,2) = z * x * (1.0 - c) - y * s;
m(1,0) = x * y * (1.0 - c) - z * s;
m(1,1) = y * y + (1.0 - y * y) * c;
m(1,2) = y * z * (1.0 - c) + x * s;
m(2,0) = z * x * (1.0 - c) + y * s;
m(2,1) = y * z * (1.0 - c) - x * s;
m(2,2) = z * z + (1.0 - z * z) * c;
}
// Построение параллельной проекции повернутого параллелепипеда на плоскость Z=n
void ParallelProjectionMatrix(const double n, Matrix &m)
{
m(0,0) = 1.0;
m(1,1) = 1.0;
m(3,2) = n;
m(3,3) = 1.0;
}
// Построение одноточечной перспективной проекции повернутого параллелепипеда,
// центр проекции находится в точке [0, 0, k]
void PerspectiveProjectionMatrix(const double k, Matrix &m)
{
m(0,0) = 1.0;
m(1,1) = 1.0;
m(2,2) = 1.0;
m(2,3) = -1 / k;
m(3,3) = 1.0;
}
void Line_3D(const Vector4 &start, const Vector4 &end, const Matrix &proj,
const RGBColor &color = RGBColor::White())
{
Vector4 a = start * proj,
b = end * proj;
Point p1 = { int(0.5 + a.x), int(0.5 + a.y) },
p2 = { int(0.5 + b.x), int(0.5 + b.y) };
Line(p1, p2, color);
}
void RPP_Draw(RPP &rpp, const Matrix &p, const bool transparent = true,
const RGBColor &color = RGBColor::White())
{
Vector3 P(0, 0, -1 / p(2,3)),
a1 = rpp.a1, b1 = rpp.b1, c1 = rpp.c1, d1 = rpp.d1,
a2 = rpp.a2, b2 = rpp.b2, c2 = rpp.c2;
// Нормали к граням
Vector3 n_front = (a2 - a1) ^ (b2 - a1),
n_right = (b2 - b1) ^ (c1 - b1),
n_top = (a2 - b2) ^ (c2 - b2);
n_front.Normalize();
n_right.Normalize();
n_top.Normalize();
Vector3 n_back = -n_front,
n_left = -n_right,
n_bottom = -n_top;
// Front
if (transparent || 0 > ((a1 + b2) / 2 - P) * n_front)
{
Line_3D(rpp.a1, rpp.b1, p, color);
Line_3D(rpp.b1, rpp.b2, p, color);
Line_3D(rpp.b2, rpp.a2, p, color);
Line_3D(rpp.a2, rpp.a1, p, color);
}
// Right
if (transparent || 0 > ((b1 + c2) / 2 - P) * n_right)
{
Line_3D(rpp.b1, rpp.b2, p, color);
Line_3D(rpp.b2, rpp.c2, p, color);
Line_3D(rpp.c2, rpp.c1, p, color);
Line_3D(rpp.c1, rpp.b1, p, color);
}
// Top
if (transparent || 0 > ((a2 + c2) / 2 - P) * n_top)
{
Line_3D(rpp.a2, rpp.b2, p, color);
Line_3D(rpp.b2, rpp.c2, p, color);
Line_3D(rpp.c2, rpp.d2, p, color);
Line_3D(rpp.d2, rpp.a2, p, color);