#include "include.h"

Text * Text::instance = NULL;

Text * Text::getInstance() {
	if (Text::instance == NULL) {
		GLuint textura = loadTexture("texturas/font.png");
		Text::instance = new Text(textura);
	}
	return Text::instance;
}

Text::Text(GLuint textura) {
	this->textura = textura;
}

void Text::draw(const char * text) {
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, this->textura);
	double x, y, dx = 0.0625, dy = 0.125;
	int line = 0;
	int pos = 0;
	for (int i=0; text[i] != '\0'; i++) {
		if (text[i] == '\n') {
			line++;
			pos = 0;
		} else {
			x = (text[i] & 0xF) / 16.0;
			y = 1 - (text[i] >> 4) / 8.0;
			glBegin(GL_POLYGON); {
				glTexCoord2f(x, y);
				glVertex3f(pos * 0.5, line, 0);
				glTexCoord2f(x + dx, y);
				glVertex3f((pos + 1)*0.5, line, 0);
				glTexCoord2f(x + dx, y - dy);
				glVertex3f((pos + 1)*0.5, line + 1, 0);
				glTexCoord2f(x, y - dy);
				glVertex3f(pos * 0.5, line + 1, 0);
			}; glEnd();
			pos++;
		}
	}
	glDisable(GL_TEXTURE_2D);
}

void Text::drawRight(const char * text) {
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, this->textura);
	double x, y, dx = 0.0625, dy = 0.125;
	int line = 0;
	int pos = 0;
	int i = 0, j = 0, k;
	while (text[i] != '\0') {
		if (text[i] == '\n') {
			line++;
			pos = 0;
			i++;
		}
		int j=i;
		while (text[j] != '\n' && text[j] != '\0') j++;
		k = j - 1;
		while (k >= i) {
			x = (text[k] & 0xF) / 16.0;
			y = 1 - (text[k] >> 4) / 8.0;
			glBegin(GL_POLYGON); {
				glTexCoord2f(x, y);
				glVertex3f((-pos - 1)*0.5, line, 0);
				glTexCoord2f(x + dx, y);
				glVertex3f((-pos)*0.5, line, 0);
				glTexCoord2f(x + dx, y - dy);
				glVertex3f((-pos)*0.5, line + 1, 0);
				glTexCoord2f(x, y - dy);
				glVertex3f((-pos - 1)*0.5, line + 1, 0);
			}; glEnd();
			pos++;
			k--;
		}
		i = j;
	}
	glDisable(GL_TEXTURE_2D);
}
