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
| #include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
////////////////////////////////////////////////////////////////////////////////
#include <cmath>
namespace math
{
// тут минимально необходимая математика
struct vec3; // 3-х компонентный вектор
struct vec4; // 4-х компонентный вектор
struct mat4; // матрица 4x4
struct vec3
{
vec3() = default;
vec3(float x, float y, float z) : data{ x, y, z } {}
float data[3]{};
float& operator[](size_t i) { return data[i]; }
const float& operator[](size_t i) const { return data[i]; }
};
vec3 operator+(const vec3& lh, const vec3& rh);
vec3 operator*(const vec3& lh, float rh);
float dot(const vec3& lh, const vec3& rh); // скалярное произведение
vec3 cross(const vec3& lh, const vec3& rh); // векторное произведение
vec3 normalize(const vec3& v); // нормализация вектора
struct vec4
{
vec4() = default;
vec4(float x, float y, float z, float w) : data{ x, y, z, w } {}
vec4(const vec3& v) : data{ v[0], v[1], v[2] } {}
float data[4]{};
float& operator[](size_t i) { return data[i]; }
const float& operator[](size_t i) const { return data[i]; }
};
vec4 operator+(const vec4& lh, const vec4& rh);
vec4 operator*(const vec4& lh, float rh);
struct mat4
{
vec4 data[4]{};
vec4& operator[](size_t i) { return data[i]; }
const vec4& operator[](size_t i) const { return data[i]; }
};
mat4 identity(); // единичная матрица
mat4 operator*(const mat4& lh, const mat4& rh);
vec4 operator*(const mat4& lh, const vec4& rh);
mat4 translate(const mat4& m, float x, float y, float z); // перенос
mat4 rotate(const mat4& m, float angle, float ax, float ay, float az); // поворот
mat4 scale(const mat4& m, float fx, float fy, float fz); // масштабирование
mat4 perspective(float fov, float ratio, float z_near, float z_far); // матрица перспективной проекции
constexpr float quat_pi(); // pi / 4
constexpr float half_pi(); // pi / 2
constexpr float pi(); // pi
constexpr float two_pi(); // 2 * pi
constexpr float dgs_rad(); // pi / 180 (1 градус в радианах)
constexpr float radians(float deg); // перевод градусов в радианы
}
////////////////////////////////////////////////////////////////////////////////
// примитивная камера
struct Camera
{
Camera(float aspect); // aspect - соотношение сторон экрана
void yaw(float angle); // рыскание
void pitch(float angle); // тангаж
const math::mat4& get_view(); // матрица вида
const math::mat4& get_proj(); // матрица проекции
private:
// для оптимизации
void update(); // обновление матрицы (та самая LookAt)
void change(); // установка флага обновления
private:
float m_yaw; // угол рыскания
float m_pitch; // угол тангажа
math::mat4 m_view; // матрица вида
math::mat4 m_proj; // матрица проекции
bool need_update; // флаг обновления
};
////////////////////////////////////////////////////////////////////////////////
// Bounding box модели
struct Bbox
{
math::vec4 min; // минимальные x,y,z координаты вершин модели
math::vec4 max; // максимальные x,y,z координаты вершин модели
};
////////////////////////////////////////////////////////////////////////////////
// 3D куб
struct Cube
{
Cube();
void set_pos(const math::vec3& pos);
void set_color(const math::vec3& color);
void draw(sf::Shader& shader, Camera& cam);
Bbox get_local_bounds();
const math::mat4& get_transform(); // матрица модели
private:
static void init(); // инициализация массива вершин
static void draw(
sf::Shader& shader, // шейдер
const math::mat4& mvp, // итоговая матрица преобразований (ModelViewProjection)
const math::vec3& color); // цвет модели
private:
math::mat4 m_model; // матрица модели
math::vec3 m_color; // цвет куба
static bool ready; // статус инициализации
static const float vertices[]; // массив вершин
};
////////////////////////////////////////////////////////////////////////////////
// вершинный шейдер
static const std::string vert = R"(
uniform mat4 u_MVP;
void main()
{
gl_Position = u_MVP * gl_Vertex;
}
)";
// фрагментный шейдер
static const std::string frag = R"(
uniform vec3 u_color;
void main()
{
gl_FragColor = vec4(u_color, 1);
}
)";
////////////////////////////////////////////////////////////////////////////////
std::vector<Cube> generate(); // генерация массива кубиков
// САМАЯ ВАЖНАЯ ФУНКЦИЯ - проверка пересечения луча взгляда с bounding box модели
bool test_ray_intersection(
const Bbox& bb, // bounding box в локальных координатах
const math::mat4& view, // матрица вида
const math::mat4& model); // матрица модели
////////////////////////////////////////////////////////////////////////////////
int main()
{
//настраиваем контекст
sf::ContextSettings ctx_sets;
ctx_sets.depthBits = 24;
// размеры экрана(окна)
int width = 1600;
int height = 900;
// создаём окно
sf::RenderWindow window(sf::VideoMode(width, height), "test", sf::Style::Close, ctx_sets);
window.setVerticalSyncEnabled(true); // vSync
window.setMouseCursorGrabbed(true); // лочим курсор в окне
window.setMouseCursorVisible(false); // прячем курсор
// позиция курсора
sf::Vector2i cursor_pos = sf::Mouse::getPosition();
// маркер прицела
sf::RectangleShape cross(sf::Vector2f(10, 10));
cross.setOrigin(5, 5);
cross.setPosition(width / 2.0f, height / 2.0f);
// инициализируем OpenGL
window.setActive(true);
glClearColor(0.1f, 0.5f, 0.8f, 1.0f);
glEnable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glViewport(0, 0, width, height);
window.setActive(false);
Camera cam(float(width) / height); // камера
constexpr float mouse_sense = 0.2f; // чувствительность мыши
// массив объектов(кубов)
std::vector<Cube> objects = generate();
// инициализируем шейдер
sf::Shader shader;
if (!shader.loadFromMemory(vert, frag))
{
return 1;
}
// основной цикл
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
else if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Escape)
{
window.close();
}
}
}
// обрабатывем управление камерой
const sf::Vector2i pos = sf::Mouse::getPosition();
cam.yaw(math::radians(mouse_sense * (pos.x - cursor_pos.x)));
cam.pitch(math::radians(mouse_sense * (cursor_pos.y - pos.y)));
cursor_pos = pos;
// тестируем пересечение луча взгляда с объектами
for (auto&& obj : objects)
{
if (test_ray_intersection(obj.get_local_bounds(), cam.get_view(), obj.get_transform()))
obj.set_color(math::vec3(0, 1, 0)); // зелёный, если попали
else
obj.set_color(math::vec3(1, 0, 0)); // красный - мимо
}
// отрисовка кубов
window.setActive(true);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
for (auto&& obj : objects)
{
obj.draw(shader, cam);
}
window.setActive(false);
// отрисовка перекрестия прицела
window.pushGLStates();
window.draw(cross);
window.popGLStates();
window.display();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
namespace math
{
vec3 operator+(const vec3 & lh, const vec3 & rh)
{
return
{
lh[0] + rh[0],
lh[1] + rh[1],
lh[2] + rh[2]
};
}
vec3 operator*(const vec3 & lh, float rh)
{
return
{
lh[0] * rh,
lh[1] * rh,
lh[2] * rh
};
}
float dot(const vec3& lh, const vec3& rh)
{
return lh[0] * rh[0] + lh[1] * rh[1] + lh[2] * rh[2];
}
vec3 cross(const vec3 & lh, const vec3 & rh)
{
return
{
lh[1] * rh[2] - rh[1] * lh[2],
lh[2] * rh[0] - rh[2] * lh[0],
lh[0] * rh[1] - rh[0] * lh[1]
};
}
vec3 normalize(const vec3 & v)
{
return v * (1 / std::sqrt(dot(v, v)));
}
vec4 operator+(const vec4& lh, const vec4& rh)
{
return
{
lh[0] + rh[0],
lh[1] + rh[1],
lh[2] + rh[2],
lh[3] + rh[3]
};
}
vec4 operator*(const vec4& lh, float rh)
{
return
{
lh[0] * rh,
lh[1] * rh,
lh[2] * rh,
lh[3] * rh
};
}
mat4 identity()
{
mat4 result;
result[0][0] = result[1][1] = result[2][2] = result[3][3] = 1;
return result;
}
mat4 operator*(const mat4& lh, const mat4& rh)
{
const vec4 A0 = lh[0];
const vec4 A1 = lh[1];
const vec4 A2 = lh[2];
const vec4 A3 = lh[3];
const vec4 B0 = rh[0];
const vec4 B1 = rh[1];
const vec4 B2 = rh[2];
const vec4 B3 = rh[3];
mat4 result;
result[0] = A0 * B0[0] + A1 * B0[1] + A2 * B0[2] + A3 * B0[3];
result[1] = A0 * B1[0] + A1 * B1[1] + A2 * B1[2] + A3 * B1[3];
result[2] = A0 * B2[0] + A1 * B2[1] + A2 * B2[2] + A3 * B2[3];
result[3] = A0 * B3[0] + A1 * B3[1] + A2 * B3[2] + A3 * B3[3];
return result;
}
vec4 operator*(const mat4& lh, const vec4& rh)
{
const vec4 A = lh[0] * rh[0] + lh[1] * rh[1];
const vec4 B = lh[2] * rh[2] + lh[3] * rh[3];
return A + B;
}
mat4 translate(const mat4& m, float x, float y, float z)
{
mat4 result = m;
result[3] = m[0] * x + m[1] * y + m[2] * z + m[3];
return result;
}
mat4 rotate(const mat4& m, float angle, float ax, float ay, float az)
{
const float cosa = std::cos(angle);
const float sina = std::sin(angle);
const vec4 axis = normalize({ ax, ay, az });
const vec4 temp = axis * (1 - cosa);
mat4 rotate;
rotate[0][0] = cosa + temp[0] * axis[0];
rotate[0][1] = temp[0] * axis[1] + sina * axis[2];
rotate[0][2] = temp[0] * axis[2] - sina * axis[1];
rotate[1][0] = temp[1] * axis[0] - sina * axis[2];
rotate[1][1] = cosa + temp[1] * axis[1];
rotate[1][2] = temp[1] * axis[2] + sina * axis[0];
rotate[2][0] = temp[2] * axis[0] + sina * axis[1];
rotate[2][1] = temp[2] * axis[1] - sina * axis[0];
rotate[2][2] = cosa + temp[2] * axis[2];
mat4 result;
result[0] = m[0] * rotate[0][0] + m[1] * rotate[0][1] + m[2] * rotate[0][2];
result[1] = m[0] * rotate[1][0] + m[1] * rotate[1][1] + m[2] * rotate[1][2];
result[2] = m[0] * rotate[2][0] + m[1] * rotate[2][1] + m[2] * rotate[2][2];
result[3] = m[3];
return result;
}
mat4 scale(const mat4& m, float fx, float fy, float fz)
{
mat4 result;
result[0] = m[0] * fx;
result[1] = m[1] * fy;
result[2] = m[2] * fz;
result[3] = m[3];
return result;
}
mat4 perspective(float fov, float ratio, float z_near, float z_far)
{
const float tan_hf = std::tan(fov / 2);
mat4 result;
result[0][0] = 1 / (ratio * tan_hf);
result[1][1] = 1 / tan_hf;
result[2][2] = -(z_far + z_near) / (z_far - z_near);
result[2][3] = -1;
result[3][2] = -(2 *z_far * z_near) / (z_far - z_near);
return result;
}
constexpr float quat_pi()
{
return 0.7853981634f;
}
constexpr float half_pi()
{
return 1.5707963268f;
}
constexpr float pi()
{
return 3.1415926536f;
}
constexpr float two_pi()
{
return 6.2831853072f;
}
constexpr float dgs_rad()
{
return 0.01745329252f;
}
constexpr float radians(float deg)
{
return deg * dgs_rad();
}
}
////////////////////////////////////////////////////////////////////////////////
Camera::Camera(float ratio)
: m_yaw(-math::half_pi())
, m_pitch()
, m_view(math::identity())
, m_proj(math::perspective(math::radians(45), ratio, 0.1f, 100.0f))
, need_update(true)
{
}
void Camera::yaw(float angle)
{
static constexpr float max_yaw = math::two_pi();
m_yaw += angle;
if (m_yaw < -max_yaw)
m_yaw += max_yaw;
else if (m_yaw > max_yaw)
m_yaw -= max_yaw;
change();
}
void Camera::pitch(float angle)
{
static constexpr float max_pitch = math::quat_pi() - math::dgs_rad();
m_pitch += angle;
if (m_pitch < -max_pitch)
m_pitch = -max_pitch;
else if (m_pitch > max_pitch)
m_pitch = max_pitch;
change();
}
const math::mat4 & Camera::get_view()
{
update();
return m_view;
}
const math::mat4& Camera::get_proj()
{
return m_proj;
}
void Camera::update()
{
if (need_update)
{
need_update = false;
math::vec3 front
{
std::cos(m_pitch) * std::cos(m_yaw),
std::sin(m_pitch),
std::cos(m_pitch) * std::sin(m_yaw)
};
front = normalize(front);
const math::vec3 side = normalize(cross(front, math::vec3{ 0, 1, 0 }));
const math::vec3 up = normalize(cross(side, front));
m_view[0][0] = side[0];
m_view[1][0] = side[1];
m_view[2][0] = side[2];
m_view[0][1] = up[0];
m_view[1][1] = up[1];
m_view[2][1] = up[2];
m_view[0][2] = -front[0];
m_view[1][2] = -front[1];
m_view[2][2] = -front[2];
}
}
void Camera::change()
{
if (!need_update)
need_update = true;
}
////////////////////////////////////////////////////////////////////////////////
bool Cube::ready = false;
const float Cube::vertices[] =
{
-1, -1, -1,
-1, 1, -1,
-1, -1, 1,
-1, -1, 1,
-1, 1, -1,
-1, 1, 1,
1, -1, -1,
1, 1, -1,
1, -1, 1,
1, -1, 1,
1, 1, -1,
1, 1, 1,
-1, -1, -1,
1, -1, -1,
-1, -1, 1,
-1, -1, 1,
1, -1, -1,
1, -1, 1,
-1, 1, -1,
1, 1, -1,
-1, 1, 1,
-1, 1, 1,
1, 1, -1,
1, 1, 1,
-1, -1, -1,
1, -1, -1,
-1, 1, -1,
-1, 1, -1,
1, -1, -1,
1, 1, -1,
-1, -1, 1,
1, -1, 1,
-1, 1, 1,
-1, 1, 1,
1, -1, 1,
1, 1, 1
};
Cube::Cube()
: m_model(math::identity())
, m_color(1, 0, 0)
{
}
void Cube::set_pos(const math::vec3 & pos)
{
m_model = math::translate(math::identity(), pos[0], pos[1], pos[2]);
}
void Cube::set_color(const math::vec3 & color)
{
m_color = color;
}
void Cube::draw(sf::Shader & shader, Camera & cam)
{
const math::mat4 mvp = cam.get_proj() * cam.get_view() * m_model;
draw(shader, mvp, m_color);
}
Bbox Cube::get_local_bounds()
{
const math::vec4 min(-1, -1, -1, 1);
const math::vec4 max( 1, 1, 1, 1);
return { min, max };
}
const math::mat4 & Cube::get_transform()
{
return m_model;
}
void Cube::init()
{
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 3 * sizeof(float), vertices);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
ready = true;
}
void Cube::draw(sf::Shader& shader, const math::mat4& mvp, const math::vec3& color)
{
if (!ready) init();
sf::Shader::bind(&shader);
shader.setUniform("u_MVP", sf::Glsl::Mat4(&mvp[0][0]));
shader.setUniform("u_color", sf::Glsl::Vec3(color[0], color[1], color[2]));
glDrawArrays(GL_TRIANGLES, 0, 36);
sf::Shader::bind(nullptr);
}
////////////////////////////////////////////////////////////////////////////////
std::vector<Cube> generate()
{
std::vector<Cube> result;
const float offset = 6;
for (int x = -1; x <= 1; ++x)
{
for (int y = -1; y <= 1; ++y)
{
for (int z = -1; z <= 1; ++z)
{
if (x == 0 && z == 0) continue;
result.push_back(Cube());
result.back().set_pos(math::vec3(offset * x, offset * y, offset * z));
}
}
}
return result;
}
bool test_ray_intersection(const Bbox & bb, const math::mat4 & view, const math::mat4 & model)
{
float t_min = 0.0f;
float t_max = 100000.0f;
const math::mat4 model_view = view * model;
const math::vec3 pos(model_view[3][0], model_view[3][1], model_view[3][2]); // направление на объект
const math::vec3 ray(0, 0, -1); // луч взгляда
{
const math::vec3 xaxis(model_view[0][0], model_view[0][1], model_view[0][2]); // ось X модели
const float e = math::dot(xaxis, pos);
const float f = -xaxis[2];
if (std::abs(f) > 0.001f)
{
float t1 = (e + bb.min[0]) / f; // пересечение с левой плоскостью
float t2 = (e + bb.max[0]) / f; // пересечение с правой плоскостью
if (t1 > t2) std::swap(t1, t2);
if (t2 < t_max)
t_max = t2;
if (t1 > t_min)
t_min = t1;
if (t_max < t_min)
return false; // луч не пересекает модель, если ближнее пересечение дальше дальнего
}
else
{ // лучь параллелен плоскостям
if (-e + bb.min[0] > 0.0f || -e + bb.max[0] < 0.0f)
return false;
}
}
{ // аналогично для оси Y
const math::vec3 yaxis(model_view[1][0], model_view[1][1], model_view[1][2]);
const float e = math::dot(yaxis, pos);
const float f = -yaxis[2];
if (std::abs(f) > 0.001f)
{
float t1 = (e + bb.min[1]) / f;
float t2 = (e + bb.max[1]) / f;
if (t1 > t2) std::swap(t1, t2);
if (t2 < t_max)
t_max = t2;
if (t1 > t_min)
t_min = t1;
if (t_min > t_max)
return false;
}
else
{
if (-e + bb.min[1] > 0.0f || -e + bb.max[1] < 0.0f)
return false;
}
}
{ // аналогично для оси Z
const math::vec3 zaxis(model_view[2][0], model_view[2][1], model_view[2][2]);
const float e = math::dot(zaxis, pos);
const float f = -zaxis[2];
if (std::abs(f) > 0.001f)
{
float t1 = (e + bb.min[2]) / f;
float t2 = (e + bb.max[2]) / f;
if (t1 > t2)
std::swap(t1, t2);
if (t2 < t_max)
t_max = t2;
if (t1 > t_min)
t_min = t1;
if (t_min > t_max)
return false;
}
else
{
if (-e + bb.min[2] > 0.0f || -e + bb.max[2] < 0.0f)
return false;
}
}
return true;
} |