-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathearthwidget.cpp
More file actions
253 lines (212 loc) · 7.89 KB
/
earthwidget.cpp
File metadata and controls
253 lines (212 loc) · 7.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// earthwidget.cpp
#include "earthwidget.h"
#include <QMouseEvent>
#include <QTimer>
#include <QPainter>
#include <QtMath>
#include <qimagereader.h>
EarthWidget::EarthWidget(QWidget *parent)
: QOpenGLWidget(parent)
, camera(EARTH_RADIUS)
, isMousePressed(false)
, isAnimating(true)
, selectedSatelliteId(-1)
, rotationAngle(0.0f)
{
QImageReader::setAllocationLimit(0);
setupSurfaceFormat();
setFocusPolicy(Qt::StrongFocus);
setUpdateBehavior(QOpenGLWidget::NoPartialUpdate);
earthRenderer = new EarthRenderer(EARTH_RADIUS);
satelliteRenderer = new SatelliteRenderer();
trajectoryRenderer = new TrajectoryRenderer();
fpsRenderer = new FPSRenderer();
satelliteInfoRenderer = new SatelliteInfoRenderer();
animationTimer = new QTimer(this);
connect(animationTimer, &QTimer::timeout, [this]() {
if (isAnimating) {
rotationAngle += 1.0f;
update();
}
});
animationTimer->start(16);
}
EarthWidget::~EarthWidget()
{
makeCurrent();
delete earthRenderer;
delete satelliteRenderer;
delete trajectoryRenderer;
delete fpsRenderer;
delete satelliteInfoRenderer;
doneCurrent();
}
void EarthWidget::setupSurfaceFormat()
{
// Установка формата OpenGL
QSurfaceFormat format;
format.setVersion(3, 3); // Используем OpenGL 3.3
format.setProfile(QSurfaceFormat::CoreProfile);
format.setDepthBufferSize(24);
format.setStencilBufferSize(8);
format.setSamples(4); // Мультисэмплинг
setFormat(format);
QSurfaceFormat::setDefaultFormat(format);
}
void EarthWidget::initializeGL()
{
// Убедитесь, что контекст OpenGL активен
makeCurrent();
// Инициализируем базовые функции OpenGL для каждого рендерера
if (!earthRenderer->init() ||
!satelliteRenderer->init() ||
!trajectoryRenderer->init()) {
qDebug() << "Failed to initialize OpenGL functions for renderers";
return;
}
// Теперь можно инициализировать рендереры
earthRenderer->initialize();
satelliteRenderer->initialize();
trajectoryRenderer->initialize();
// Настройка параметров рендеринга
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Включаем и настраиваем тест глубины
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS); // Добавлено: стандартная функция теста глубины
glDepthMask(GL_TRUE); // Добавлено: разрешаем запись в буфер глубины
// Включаем отсечение задних граней
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK); // Добавлено: отсекаем задние грани
glFrontFace(GL_CCW); // Добавлено: определяем порядок вершин для передней грани
glEnable(GL_MULTISAMPLE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void EarthWidget::resizeGL(int w, int h)
{
float aspect = float(w) / float(h ? h : 1);
projection.setToIdentity();
projection.perspective(45.0f, aspect, EARTH_RADIUS * 0.1f, EARTH_RADIUS * 100.0f);
}
void EarthWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
QMatrix4x4 viewMatrix = camera.getViewMatrix();
// Отрисовка 3D объектов
earthRenderer->render(projection, viewMatrix, model);
satelliteRenderer->render(projection, viewMatrix, model);
if (selectedSatelliteId != -1) {
trajectoryRenderer->render(projection, viewMatrix, model);
}
// Отрисовка 2D информации поверх 3D сцены
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// Отрисовка информации о выбранном спутнике
if (selectedSatelliteId != -1 && satellites.contains(selectedSatelliteId)) {
satelliteInfoRenderer->render(&painter, projection, viewMatrix, model,
satellites[selectedSatelliteId], size());
}
// Отрисовка FPS
fpsRenderer->render(painter, size());
painter.end();
fpsRenderer->update();
}
void EarthWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
isMousePressed = true;
lastMousePos = event->pos();
pickSatellite(event->pos());
satelliteRenderer->updateSatellites(satellites);
update();
}
}
void EarthWidget::mouseMoveEvent(QMouseEvent *event)
{
if (isMousePressed) {
QPoint delta = event->pos() - lastMousePos;
camera.rotate(delta.x() * 0.01f, delta.y() * 0.01f);
lastMousePos = event->pos();
update();
}
}
void EarthWidget::wheelEvent(QWheelEvent *event)
{
float zoomFactor = event->angleDelta().y() > 0 ? 0.9f : 1.1f;
camera.zoom(zoomFactor);
update();
}
void EarthWidget::addSatellite(int id, const QVector3D& position, const QString& info)
{
Satellite satellite(id, position, info);
satellites[id] = satellite;
satelliteRenderer->updateSatellites(satellites);
update();
}
void EarthWidget::updateSatellitePosition(int id, const QVector3D& newPosition,
const QVector<QVector3D>& trajectory,
const QVector<QVector3D>& futureTrajectory,
float angle)
{
static QTimer updateTimer;
static bool timerActive = false;
auto it = satellites.find(id);
if (it != satellites.end()) {
it->position = newPosition;
it->angle = angle;
if (id == selectedSatelliteId) {
if (!timerActive) {
timerActive = true;
updateTimer.singleShot(100, this, [this, trajectory, futureTrajectory]() {
trajectoryRenderer->setTrajectories(trajectory, futureTrajectory);
timerActive = false;
update();
});
}
}
satelliteRenderer->updateSatellites(satellites);
}
update();
}
bool EarthWidget::toggleEarthAnimation()
{
isAnimating = !isAnimating;
return isAnimating;
}
int EarthWidget::pickSatellite(const QPoint& mousePos)
{
float x = (2.0f * mousePos.x()) / width() - 1.0f;
float y = 1.0f - (2.0f * mousePos.y()) / height();
QVector4D rayClip(x, y, -1.0f, 1.0f);
QVector4D rayEye = projection.inverted() * rayClip;
rayEye.setZ(-1.0f);
rayEye.setW(0.0f);
QVector4D rayWorld4 = camera.getViewMatrix().inverted() * rayEye;
QVector3D rayWorld(rayWorld4.x(), rayWorld4.y(), rayWorld4.z());
rayWorld.normalize();
QVector3D rayOrigin = camera.getPosition();
float minDistance = std::numeric_limits<float>::max();
int closestSatelliteId = -1;
float pickRadius = EARTH_RADIUS * 0.1f;
for (const auto& satellite : satellites) {
QVector3D satPos = model * satellite.position;
QVector3D toSatellite = satPos - rayOrigin;
float projection = QVector3D::dotProduct(toSatellite, rayWorld);
if (projection < 0) continue;
QVector3D projectionPoint = rayOrigin + rayWorld * projection;
float distance = (satPos - projectionPoint).length();
if (distance < pickRadius && projection < minDistance) {
minDistance = projection;
closestSatelliteId = satellite.id;
}
}
if(selectedSatelliteId != closestSatelliteId && selectedSatelliteId != -1){
satellites[selectedSatelliteId].isSelected = false;
}
selectedSatelliteId = closestSatelliteId;
if(selectedSatelliteId != -1){
satellites[selectedSatelliteId].isSelected = true;
}
update(); // Убедитесь, что это вызывается
return closestSatelliteId;
}