src/colors.cpp

Wed, 25 Mar 2020 16:07:20 +0200

author
Teemu Piippo <teemu@hecknology.net>
date
Wed, 25 Mar 2020 16:07:20 +0200
changeset 87
93ec4d630346
parent 43
08dc62e03a6d
child 94
164f53fb5921
permissions
-rw-r--r--

added PolygonObject and refactored away a lot of boilerplate

/*
 *  LDForge: LDraw parts authoring CAD
 *  Copyright (C) 2013 - 2020 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/>.
 */

#include "colors.h"

const ldraw::ColorTable::ColorDefinition ldraw::ColorTable::unknownColor{{}, {}, "Unknown"};

void ldraw::ColorTable::clear()
{
	definitions = {};
}

Result ldraw::ColorTable::load(QIODevice& device, QTextStream& errors)
{
	this->clear();
	if (device.isReadable())
	{
		QTextStream stream{&device};
		QString line;
		while (stream.readLineInto(&line))
		{
			this->loadColorFromString(line);
		}
		return Success;
	}
	else
	{
		errors << "could not read colors";
		return Failure;
	}
}

const ldraw::ColorTable::ColorDefinition& ldraw::ColorTable::operator[](Color color) const
{
	auto it = this->definitions.find(color.index);
	if (it != this->definitions.end())
	{
		return *it;
	}
	else
	{
		return unknownColor;
	}
}

void ldraw::ColorTable::loadColorFromString(const QString& string)
{
	const QRegExp pattern{
		R"(^\s*0 \!COLOUR\s+([^\s]+)\s+)"_q +
		R"(CODE\s+(\d+)\s+)"_q +
		R"(VALUE\s+(\#[0-9a-fA-F]{3,6})\s+)"_q +
		R"(EDGE\s+(\#[0-9a-fA-F]{3,6}))"_q +
		R"((?:\s+ALPHA\s+(\d+))?)"_q
	};
	if (pattern.indexIn(string) != -1)
	{
		const int code = pattern.cap(2).toInt();
		ColorDefinition& definition = definitions[code];
		definition = {}; // in case there's an existing definition
		definition.name = pattern.cap(1);
		definition.faceColor = pattern.cap(3);
		definition.edgeColor = pattern.cap(4);
		if (not pattern.cap(5).isEmpty())
		{
			const int alpha = pattern.cap(5).toInt();
			definition.faceColor.setAlpha(alpha);
		}
	}
}

/*
 * Calculates the luma-value for the given color.
 * c.f. https://en.wikipedia.org/wiki/Luma_(video)
 */
double luma(const QColor& color)
{
	return 0.2126 * color.redF() + 0.7152 * color.greenF() + 0.0722 * color.blueF();
}

mercurial