
#include "Image.h"
#include "stb_image.h"
#include "glm/ext.hpp"
#include "Common.h"
#include "ResourceManager.h"

///////////////////////////////////////////////////////////////
//画像
///////////////////////////////////////////////////////////////

Image::Image() {
	TexID = 0;
}
Image::Image(const std::string &filename) {
	LoadFromFile(filename);
}
Image::~Image() { }

void Image::LoadFromFile(const std::string &filename) {
	const auto &tex = pResMngr->GetTexture(filename);
	TexID = tex.ID;
	Width = tex.Width;
	Height = tex.Height;
}

void Image::Draw(
	const glm::vec2 &pos,
	const glm::vec2 &size,
	bool flipY,
	const glm::vec2 &texStart,
	const glm::vec2 &texSize)
{
	
	//矩形の頂点位置
	glm::vec2 vtxPos[4];
	vtxPos[0] = glm::vec2(0.0f, 1.0f);
	vtxPos[1] = glm::vec2(1.0f, 1.0f);
	vtxPos[2] = glm::vec2(0.0f, 0.0f);
	vtxPos[3] = glm::vec2(1.0f, 0.0f);
	
	//矩形のテクスチャ座標
	glm::vec2 vtxTex[4];
	if( flipY ) {
		//Y軸反転
		vtxTex[0] = glm::vec2(texStart.x,             texStart.y + texSize.y);
		vtxTex[1] = glm::vec2(texStart.x + texSize.x, texStart.y + texSize.y);
		vtxTex[2] = glm::vec2(texStart.x,             texStart.y);
		vtxTex[3] = glm::vec2(texStart.x + texSize.x, texStart.y);
	} else {
		vtxTex[0] = glm::vec2(texStart.x,             texStart.y);
		vtxTex[1] = glm::vec2(texStart.x + texSize.x, texStart.y);
		vtxTex[2] = glm::vec2(texStart.x,             texStart.y + texSize.y);
		vtxTex[3] = glm::vec2(texStart.x + texSize.x, texStart.y + texSize.y);
	}
	
	//大きさをsize，位置をposに変換するような行列を生成
	glm::mat4 mat;
	mat = glm::translate(mat, glm::vec3(pos, 0.0f));
	mat = glm::scale(mat, glm::vec3(size, 1.0f));
	
	//生成した行列を登録
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glLoadMatrixf(&mat[0][0]);
	
	//頂点位置とテクスチャ座標の配列を有効にする
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	
	//矩形の頂点位置とテクスチャ座標配列の登録
	glVertexPointer(2, GL_FLOAT, 0, vtxPos);
	glTexCoordPointer(2, GL_FLOAT, 0, vtxTex);
	
	//テクスチャ登録
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, TexID);
	
	//描画！
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	
	//テクスチャ登録解除
	glBindTexture(GL_TEXTURE_2D, 0);
	glDisable(GL_TEXTURE_2D);
	
	//頂点位置とテクスチャ座標の配列を無効にする
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	
}



///////////////////////////////////////////////////////////////
//分割画像
//1枚のテクスチャ内に複数の画像が入っているようなテクスチャを扱う
///////////////////////////////////////////////////////////////

ImageSplitted::ImageSplitted() {
	SplitX = 0;
	SplitX = 0;
}

ImageSplitted::ImageSplitted(
	const std::string &filename,
	int splitX, int splitY) : Image(filename)
{
	this->SplitX = splitX;
	this->SplitY = splitY;
}

ImageSplitted::~ImageSplitted() { }

void ImageSplitted::DrawSplitted(
	const glm::vec2 &pos,
	const glm::vec2 &size,
	int index,
	bool flipY)
{
	
	float indexX = (float)(index % SplitX);
	float indexY = (float)(index / SplitX);
	
	Draw(
		pos, size, flipY,
		glm::vec2(indexX / SplitX, indexY / SplitY),
		glm::vec2(1.0f / SplitX, 1.0f / SplitY)
	);
	
}

