src/gl/compiler.cpp

Fri, 07 Feb 2020 23:59:06 +0200

author
Teemu Piippo <teemu@hecknology.net>
date
Fri, 07 Feb 2020 23:59:06 +0200
changeset 51
1a9eac27698d
parent 50
0f80a2e5e42b
child 53
3af627f7a40f
permissions
-rw-r--r--

selection works now

/*
 *  LDForge: LDraw parts authoring CAD
 *  Copyright (C) 2013 - 2018 Teemu Piippo
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#define GL_GLEXT_PROTOTYPES
#include <GL/glu.h>
#include <GL/glext.h>
#include <QMessageBox>
#include "gl/compiler.h"
#include "documentmanager.h"
#include "invert.h"
#include "ring.h"

static const char* vertexShaderSource = R"(
#version 330 core

layout(location=0) in vec3 position;
layout(location=1) in vec4 color;
layout(location=2) in vec3 normal;
layout(location=3) in int id;
layout(location=4) in int selected;
out vec4 vColor;
out vec3 vFragPos;
out vec3 vNormal;
uniform mat4 modelMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform int fragmentStyle;
uniform vec3 selectedColor;
uniform int highlighted;

const int FRAGSTYLE_Normal = 0;
const int FRAGSTYLE_BfcGreen = 1;
const int FRAGSTYLE_BfcRed = 2;
const int FRAGSTYLE_Random = 3;
const int FRAGSTYLE_Id = 4;

void main()
{
	mat3 normalMatrix = transpose(inverse(mat3(modelMatrix)));
	vNormal = normalize(normalMatrix * normal);
	if (fragmentStyle == FRAGSTYLE_Id)
	{
		/* Calculate a color based from this index. This method caters for
		 * 16777216 objects. I don't think that will be exceeded anytime soon.
		 */
		int r = (id / 0x10000) % 0x100;
		int g = (id / 0x100) % 0x100;
		int b = id % 0x100;
		vColor = vec4(r / 255.0, g / 255.0, b / 255.0, 1.0);
	}
	else if (selected == 1)
	{
		vColor = vec4(selectedColor, 1.0);
	}
	else
	{
		if (fragmentStyle == FRAGSTYLE_BfcGreen)
		{
			vColor = vec4(0.2, 0.9, 0.2, 1.0);
		}
		else if (fragmentStyle == FRAGSTYLE_BfcRed)
		{
			vColor = vec4(0.9, 0.2, 0.2, 1.0);
		}
		else
		{
			vColor = color;
		}
		if (highlighted == id)
		{
			vColor = (vColor + vec4(selectedColor, 1.0) * 0.6) / 1.6;
		}
	}

	vFragPos = vec3(modelMatrix * vec4(position, 1.0));
	gl_Position = projectionMatrix * viewMatrix * vec4(vFragPos, 1.0);
}
)";

static const char* fragmentShaderSource = R"(
#version 330 core

in vec4 vColor;
in vec3 vFragPos;
in vec3 vNormal;
out vec4 fColor;
const vec3 lightPos = vec3(0.5, 0.5, 0.5);
const vec4 lightColor = vec4(1.0, 1.0, 1.0, 1.0);
const float ambientStrength = 0.7;
uniform bool useLighting;

void main()
{
	if (useLighting)
	{
		vec4 ambient = ambientStrength * lightColor;
		vec3 lightDirection = normalize(lightPos - vFragPos);
		vec4 diffuse = max(dot(vNormal, lightDirection), 0.0) * lightColor;
		fColor = (ambient + diffuse) * vColor;
	}
	else
	{
		fColor = vColor;
	}
}
)";

gl::Compiler::Compiler(const ldraw::ColorTable& colorTable, QObject* parent) :
	QObject{parent},
	colorTable{colorTable}
{
}

gl::Compiler::~Compiler()
{
}

void gl::Compiler::initialize()
{
	if (not this->initialized)
	{
		this->initializeOpenGLFunctions();
		for (int i = 0; i < gl::NUM_ARRAY_CLASSES; i += 1)
		{
			auto& object = this->glObjects[i];
			object.program = new QOpenGLShaderProgram;
			object.program->create();
			const bool vertexShaderCompiled = object.program->addShaderFromSourceCode(QOpenGLShader::Vertex, ::vertexShaderSource);
			QString log;
			if (not vertexShaderCompiled)
			{
				log += "\n" + tr("Vertex shader:") + "\n" + object.program->log();
			}
			const bool fragmentShaderCompiled = object.program->addShaderFromSourceCode(QOpenGLShader::Fragment, ::fragmentShaderSource);
			if (not fragmentShaderCompiled)
			{
				log += "\n" + tr("Fragment shader:") + "\n" + object.program->log();
			}
			if (not vertexShaderCompiled or not fragmentShaderCompiled)
			{
				QMessageBox::critical(nullptr, tr("Shader compile error"), tr("Could not compile shaders.") + "\n" + log);
				std::exit(-1);
			}
			object.program->link();
			object.program->bind();
			object.buffer.create();
			object.buffer.bind();
			object.buffer.setUsagePattern(QOpenGLBuffer::DynamicDraw);
			object.vertexArray.create();
			object.vertexArray.bind();
			for (int k : {0, 1, 2, 3, 4})
			{
				object.program->enableAttributeArray(k);
			}
			constexpr int stride = sizeof(gl::Vertex);
			object.program->setAttributeBuffer(0, GL_FLOAT, offsetof(gl::Vertex, position), 3, stride);
			object.program->setAttributeBuffer(1, GL_FLOAT, offsetof(gl::Vertex, color), 4, stride);
			object.program->setAttributeBuffer(2, GL_FLOAT, offsetof(gl::Vertex, normal), 3, stride);
			glVertexAttribIPointer(3, 1, GL_INT, stride, reinterpret_cast<void*>(offsetof(gl::Vertex, id)));
			glVertexAttribIPointer(4, 1, GL_INT, stride, reinterpret_cast<void*>(offsetof(gl::Vertex, selected)));
			object.vertexArray.release();
			object.buffer.release();
			object.program->release();
		}
		this->initialized = true;
	}
}

void gl::Compiler::build(Model* model, DocumentManager* context, const gl::RenderPreferences& preferences)
{
	this->boundingBox = {};
	std::vector<gl::Vertex> vboData[gl::NUM_ARRAY_CLASSES];
	const std::vector<gl::Polygon> polygons = model->getPolygons(context);
	for (const gl::Polygon& polygon : polygons)
	{
		this->buildPolygon(polygon, vboData, preferences);
	}
	for (int arrayId = 0; arrayId < gl::NUM_ARRAY_CLASSES; arrayId += 1)
	{
		auto& buffer = this->glObjects[arrayId].buffer;
		auto& vector = vboData[arrayId];
		this->storedVertexCounts[arrayId] = vector.size();
		this->glObjects[arrayId].cachedData = vector; // todo: get rid of this copy
		buffer.bind();
		buffer.allocate(vector.data(), static_cast<int>(vector.size() * sizeof vector[0]));
		buffer.release();
	}
}

gl::ArrayClass classifyPolygon(const gl::Polygon& polygon)
{
	switch (polygon.type)
	{
	case gl::Polygon::EdgeLine:
		return gl::ArrayClass::Lines;
	case gl::Polygon::Triangle:
		return gl::ArrayClass::Triangles;
	case gl::Polygon::Quadrilateral:
		return gl::ArrayClass::Quads;
	case gl::Polygon::ConditionalEdge:
		return gl::ArrayClass::ConditionalLines;
	}
	return gl::ArrayClass::Lines;
}

ldraw::Id gl::Compiler::idFromColor(const std::array<GLbyte, 3>& data)
{
	return {data[0] * std::int32_t{0x10000} + data[1] * std::int32_t{0x100} + data[2]};
}

void gl::Compiler::buildPolygon(
	gl::Polygon polygon,
	std::vector<gl::Vertex>* vboData,
	const gl::RenderPreferences& preferences)
{
	const gl::ArrayClass vboClass = classifyPolygon(polygon);
	std::vector<gl::Vertex>& vertexBuffer = vboData[static_cast<int>(vboClass)];
	auto vertexRing = iter::ring(polygon.vertices, polygon.numPolygonVertices());
	reserveMore(vertexBuffer, polygon.numPolygonVertices());
	const QColor color = this->getColorForPolygon(polygon, preferences);
	for (unsigned int i = 0; i < polygon.numPolygonVertices(); i += 1)
	{
		const glm::vec3& v1 = vertexRing[i - 1];
		const glm::vec3& v2 = vertexRing[i];
		const glm::vec3& v3 = vertexRing[i + 1];
		this->boundingBox.consider(polygon.vertices[i]);
		gl::Vertex& vertex = vertexBuffer.emplace_back();
		vertex.position = polygon.vertices[i];
		vertex.normal = glm::normalize(glm::cross(v1 - v2, v3 - v2));
		vertex.color = glm::vec4{color.redF(), color.greenF(), color.blueF(), color.alphaF()};
		vertex.id = polygon.id.value;
	}
}

QColor gl::Compiler::getColorForPolygon(const gl::Polygon& polygon, const gl::RenderPreferences& preferences)
{
	QColor color;
	// For normal colors, use the polygon's color.
	if (polygon.color == ldraw::mainColor)
	{
		color = preferences.mainColor;
	}
	else if (polygon.color == ldraw::edgeColor)
	{
		// Edge color is black, unless we have a dark background, in which case lines need to be bright.
		color = luma(preferences.backgroundColor) > (40.0 / 256.0) ? Qt::black : Qt::white;
	}
	else
	{
		// Not main or edge color, use the polygon's color as is.
		color = this->colorTable[polygon.color].faceColor;
	}
	return color;
}

glm::vec3 gl::Compiler::modelCenter() const
{
	return boxCenter(this->boundingBox);
}

double gl::Compiler::modelDistance() const
{
	return static_cast<double>(longestMeasure(this->boundingBox));
}

void gl::Compiler::bindVertexArray(gl::ArrayClass arrayClass)
{
	auto& object = this->glObjects[static_cast<int>(arrayClass)];
	object.vertexArray.bind();
	object.program->bind();
}

void gl::Compiler::releaseVertexArray(gl::ArrayClass arrayClass)
{
	auto& object = this->glObjects[static_cast<int>(arrayClass)];
	object.program->release();
	object.vertexArray.release();
}

void gl::Compiler::setSelectedObjects(const QSet<ldraw::Id> ids)
{
	for (int i = 0; i < gl::NUM_ARRAY_CLASSES; i += 1)
	{
		auto& vector = this->glObjects[i].cachedData;
		for (gl::Vertex& vertex : vector)
		{
			vertex.selected = (ids.contains({vertex.id})) ? 1 : 0;
		}
		const GLsizeiptr size = static_cast<int>(vector.size() * sizeof vector[0]);
		this->glObjects[i].buffer.bind();
		glBufferSubData(GL_ARRAY_BUFFER, 0, size, vector.data());
	}
}

std::size_t gl::Compiler::vertexCount(const gl::ArrayClass arrayClass) const
{
	return this->storedVertexCounts[static_cast<int>(arrayClass)];
}

mercurial