OpenGlViewer.cpp 9.29 KB
Newer Older
Anakin's avatar
Anakin committed
1
#include "..\Header\OpenGlViewer.h"
2
#include <cmath>
Anakin's avatar
Anakin committed
3
#include <iostream>
4
#include <QMessageBox>
Anakin's avatar
Anakin committed
5

Anakin's avatar
Anakin committed
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

/////////////////////////////////////////////////////////////////////////
// Defined values

//opengl
#define DEFAULT_MAJOR_VERSION		4
#define DEFAULT_MINOR_VERSION		5
#define DEAFAULT_BACKGROUND			0.5000f, 0.8000f, 1.0000f, 0.0000f

//piplines
#define VERTEX_INDEX_XYZ		0
#define VERTEX_INDEX_UV			1

#define VERTEX_COMPONENTS_XYZ	3
#define VERTEX_COMPONENTS_UV	2

#define VERTEX_SIZE_XYZ			(sizeof(float) * VERTEX_COMPONENTS_XYZ)
#define VERTEX_SIZE_UV			(sizeof(float) * VERTEX_COMPONENTS_UV)

#define VERTEX_OFFSET_XYZ		0
#define VERTEX_OFFSET_UV		(VERTEX_SIZE_XYZ)


/////////////////////////////////////////////////////////////////////////
// public constructor/destructor
Anakin's avatar
Anakin committed
31 32 33 34 35

OpenGlViewer::OpenGlViewer(QWidget *parent)
	: QOpenGLWidget(parent)
{
	QSurfaceFormat format;
Anakin's avatar
Anakin committed
36
	format.setRenderableType(QSurfaceFormat::OpenGL);
37
	format.setSamples(4);
Anakin's avatar
Anakin committed
38
	format.setProfile(QSurfaceFormat::CompatibilityProfile);
Anakin's avatar
Anakin committed
39
	format.setVersion(DEFAULT_MAJOR_VERSION, DEFAULT_MINOR_VERSION);
Anakin's avatar
Anakin committed
40
	setFormat(format);
41 42

	//TODO: mouse, move, key, drag/drop, scroll, resize
Anakin's avatar
Anakin committed
43 44 45 46
}

OpenGlViewer::~OpenGlViewer()
{
47
	m_oglTexture->destroy();
Anakin's avatar
Anakin committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	m_vertexArray.destroy();
	m_vertexBuffer.destroy();
	delete m_program;

	deleteData();
}


/////////////////////////////////////////////////////////////////////////
// private functions

void OpenGlViewer::initializeGL()
{
	initializeOpenGLFunctions();
	printContextInformation();

64
	// set Background
Anakin's avatar
Anakin committed
65 66
	glClearColor(DEAFAULT_BACKGROUND);

67 68 69 70 71 72 73 74 75 76 77 78
	//TODO: z-order?

	// draw vertices only from one side
	glEnable(GL_CULL_FACE);

	// Create texture
	m_oglTexture = new QOpenGLTexture(QOpenGLTexture::Target2D);
	m_oglTexture->setWrapMode(QOpenGLTexture::Repeat);
	m_oglTexture->setMagnificationFilter(QOpenGLTexture::Linear);
	m_oglTexture->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear);

	// Create Shader
Anakin's avatar
Anakin committed
79 80 81 82 83 84
	m_program = new QOpenGLShaderProgram();
	m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/simple.vert");
	m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/simple.frag");
	m_program->link();
	m_program->bind();

85 86 87 88 89
	// get Uniform location
	//TODO: faster to give everything to shader and calculate there?
	m_uniformMVP = m_program->uniformLocation("MVP");

	// Create Vertex Buffer
Anakin's avatar
Anakin committed
90 91 92 93
	m_vertexBuffer.create();
	m_vertexBuffer.bind();
	m_vertexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw);

94
	// Create Vertex Array Object
Anakin's avatar
Anakin committed
95 96 97 98
	m_vertexArray.create();
	m_vertexArray.bind();
	m_program->enableAttributeArray(0);
	m_program->enableAttributeArray(1);
99 100
	m_program->setAttributeBuffer(VERTEX_INDEX_XYZ, GL_FLOAT, VERTEX_OFFSET_XYZ, VERTEX_COMPONENTS_XYZ, sizeof(Vertex));
	m_program->setAttributeBuffer(VERTEX_INDEX_UV, GL_FLOAT, VERTEX_OFFSET_UV, VERTEX_COMPONENTS_UV, sizeof(Vertex));
Anakin's avatar
Anakin committed
101

102
	// unbind everything
Anakin's avatar
Anakin committed
103 104 105 106 107 108 109 110 111 112 113 114 115
	m_vertexArray.release();
	m_vertexBuffer.release();
	m_program->release();

}

void OpenGlViewer::paintGL()
{
	//TODO: paint here
	glClear(GL_COLOR_BUFFER_BIT);

	m_program->bind();
	m_vertexArray.bind();
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	m_oglTexture->bind();

	if (m_vModels != nullptr)
	{
		int tmp_offset(0);

		for (unsigned int modelIndex = 0; modelIndex < m_vModels->size(); modelIndex++)
		{
			// skip null, bones, shadowMesh, hidden things
			if (m_vModels->at(modelIndex)->type == null ||
				m_vModels->at(modelIndex)->type == bone ||
				m_vModels->at(modelIndex)->type == shadowMesh ||
				m_vModels->at(modelIndex)->renderFlags == 1)
				continue;

			for (auto& segmentIterator : m_vModels->at(modelIndex)->segmList)
			{
				// set the texture
134
				std::uint32_t tmp_textureIndex = segmentIterator->textureIndex >= m_vTextures->size() ? m_vTextures->size() - 1 : segmentIterator->textureIndex;
Anakin's avatar
Anakin committed
135 136 137 138 139 140 141 142 143 144

				if (m_oglTexture->isCreated())
				{
					m_oglTexture->destroy();
					m_oglTexture->create();
					m_oglTexture->setSize(m_vTextures->at(tmp_textureIndex)->width(), m_vTextures->at(tmp_textureIndex)->height());
					m_oglTexture->setData(*m_vTextures->at(tmp_textureIndex));
				}

				
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

				// give the MVP to the shader
				m_program->setUniformValue(m_uniformMVP, getMVPMatrix(modelIndex));

				// calculate the number of vertex
				unsigned int tmp_vertexCount(0);
				for (auto&it : segmentIterator->polyIndices)
					tmp_vertexCount += (it.size() - 2) * 3;

				glDrawArrays(GL_TRIANGLES, tmp_offset, tmp_vertexCount);

				// increase the offset
				tmp_offset += tmp_vertexCount;
			}
		}
	}
161

162
	m_oglTexture->release();
Anakin's avatar
Anakin committed
163 164
	m_vertexArray.release();
	m_program->release();
Anakin's avatar
Anakin committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
}

void OpenGlViewer::printContextInformation()
{
	QString glType;
	QString glVersion;
	QString glProfile;

	glType = (context()->isOpenGLES()) ? "OpenGL ES" : "OpenGL";
	glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));

#define CASE(c) case QSurfaceFormat::c: glProfile = #c; break
	switch (format().profile())
	{
		CASE(NoProfile);
		CASE(CoreProfile);
		CASE(CompatibilityProfile);
	}
#undef CASE

	std::cout << glType.toStdString() << " - " << glVersion.toStdString() << " (" << glProfile.toStdString() << ")";
Anakin's avatar
Anakin committed
186 187
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
QMatrix4x4 OpenGlViewer::getModelMatrix(unsigned int index) const
{
	QMatrix4x4 tmp_parent;

	for (unsigned int loop = 0; loop < m_vModels->size(); loop++)
	{
		if (!strcmp(m_vModels->at(index)->parent.c_str(), m_vModels->at(loop)->name.c_str()))
		{
			tmp_parent = getModelMatrix(loop);
			break;
		}
	}

	return tmp_parent * m_vModels->at(index)->m4x4Translation;
}

204 205
QMatrix4x4 OpenGlViewer::getMVPMatrix(unsigned int index) const
{
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
	QMatrix4x4 tmp_mvp;
	
	// projection
	tmp_mvp.perspective(m_fFOV, float(QWidget::width()) / float(QWidget::height()), m_fMinView, m_fMaxView);
	
	// view
	tmp_mvp.lookAt(QVector3D(m_fTranX, m_fTranY, m_fTranZ), QVector3D(m_fTranX, m_fTranY, m_fTranZ - 1), QVector3D(0, 0, 1));
	
	// user controlled rotation
	tmp_mvp.rotate(m_fRotX, QVector3D(1, 0, 0));
	tmp_mvp.rotate(m_fRotY, QVector3D(0, 1, 0));
	tmp_mvp.rotate(m_fRotZ, QVector3D(0, 0, 1));

	//scale to 1
	float maxExtent = std::max(std::max(m_sceneBoundings.extents[0], m_sceneBoundings.extents[1]), m_sceneBoundings.extents[2]);
	tmp_mvp.scale(1 / maxExtent); 

	// move to center
	tmp_mvp.translate(-m_sceneBoundings.center[0], -m_sceneBoundings.center[1], -m_sceneBoundings.center[2]);

	return tmp_mvp * getModelMatrix(index);
227 228
}

Anakin's avatar
Anakin committed
229
void OpenGlViewer::deleteData()
Anakin's avatar
Anakin committed
230
{
231
	if (m_vModels != nullptr)
Anakin's avatar
Anakin committed
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
	{
		while (!m_vModels->empty())
		{
			// remove the last Model
			Model* modelVectorElement = m_vModels->back();
			m_vModels->pop_back();

			while (!modelVectorElement->segmList.empty())
			{
				// remove the last Segment
				Segment* segmentVectorElement = modelVectorElement->segmList.back();
				modelVectorElement->segmList.pop_back();

				// delete data from Segment
				delete[] segmentVectorElement->uv;
				delete[] segmentVectorElement->vertex;

				while (!segmentVectorElement->polyIndices.empty())
				{
					// clear the poly vector and remove it from the list
					segmentVectorElement->polyIndices.back().clear();
					segmentVectorElement->polyIndices.pop_back();
				}

				// delete the actual Segment
				delete segmentVectorElement;
			}

			// delete the actual Model
			delete modelVectorElement;
		}

		// delete the Model's Vector
		delete m_vModels;
	}
Anakin's avatar
Anakin committed
267

268
	if (m_vTextures != nullptr)
Anakin's avatar
Anakin committed
269
	{
270 271 272 273 274
		while (!m_vTextures->empty())
		{
			// remove the last texture
			QImage* cursor = m_vTextures->back();
			m_vTextures->pop_back();
Anakin's avatar
Anakin committed
275

276 277 278 279 280
			//delete image
			delete cursor;
		}
		// delete the Textrue's Vector
		delete m_vTextures;
Anakin's avatar
Anakin committed
281
	}
Anakin's avatar
Anakin committed
282 283 284
}


Anakin's avatar
Anakin committed
285 286
/////////////////////////////////////////////////////////////////////////
// public functions
Anakin's avatar
Anakin committed
287

288
void OpenGlViewer::setData(std::vector<Model*>* models, std::vector<QImage*>* textures, BoundingBox bbox)
Anakin's avatar
Anakin committed
289
{
290 291 292 293
	// new Data, so clean up the old things
	deleteData();

	// save the variables
Anakin's avatar
Anakin committed
294 295
	m_vModels = models;
	m_vTextures = textures;
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
	m_sceneBoundings = bbox;

	// collect vertex data of all models
	std::vector<Vertex> tmp_bufferData;

	for (auto& modIt : *m_vModels)		// for every model chunk
	{
		for (auto& segIt : modIt->segmList)		// for every cluster
		{
			for (auto& mshIt : segIt->polyIndices)		// for every polygon
			{
				if (mshIt.size() >= 3)		// multipoly
				{
					// for every triangle of the multi polygon
					for (unsigned int tri = 0; tri < mshIt.size() - 2; tri++)
					{
						// for every edge of the triangle
						for (int triEdge = 0; triEdge < 3; triEdge++)
						{
							Vertex tempVertex;
							// every edge has 3 coordinates
							for (int j = 0; j < 3; j++)
								tempVertex.position[j] = (GLfloat)segIt->vertex[mshIt[tri + triEdge - ((tri % 2) * (triEdge - 1) * 2)] * 3 + j];

							// and 2 UV
							if (segIt->uv == NULL)
							{
								tempVertex.uv[0] = 1.0;
								tempVertex.uv[1] = 1.0;
							}
							else
							{
								for (int j = 0; j < 2; j++)
									tempVertex.uv[j] = (GLfloat)segIt->uv[mshIt[tri + triEdge - ((tri % 2) * (triEdge - 1) * 2)] * 2 + j];
							}
							tmp_bufferData.push_back(tempVertex);
						}
					}
				}
				else	// this shouldn't happen (polygon with less then 3 vertex)
				{
					deleteData();

					QMessageBox msg(this);
					msg.addButton(QMessageBox::Ok);
					msg.setText("You have polygons with less then 3 vertices!");
					msg.setIcon(QMessageBox::Critical);
					msg.setWindowTitle("Open File Error");
					msg.exec();
					return;
				}
			}
		}
	}

Anakin's avatar
Anakin committed
351

352 353 354 355 356 357
	m_vertexBuffer.bind();
	m_vertexBuffer.allocate(tmp_bufferData.data(), sizeof(Vertex) * tmp_bufferData.size());
	m_vertexBuffer.release();

	tmp_bufferData.clear();
}