#include "ofCvColorImage.h"

//-------------------------------------------------------------------------------------
ofCvColorImage::ofCvColorImage(){
	width = height = 0;;
}

//-------------------------------------------------------------------------------------
void ofCvColorImage::allocate(int _w, int _h){
	cvImage 			= cvCreateImage(cvSize(_w,_h), IPL_DEPTH_8U,3);
	cvImageTemp			= cvCreateImage(cvSize(_w,_h), IPL_DEPTH_8U,3);
	pixels 				= new unsigned char[_w*_h * 3];
	width 				= _w;
	height 				= _h;
	tex.allocate(width, height, GL_RGB);
}

//-------------------------------------------------------------------------------------
void ofCvColorImage::clear(){
	cvReleaseImage(&cvImage);
	cvReleaseImage(&cvImageTemp);
	width = height = 0;;
}

//-------------------------------------------------------------------------------------
void ofCvColorImage::setFromPixels(unsigned char * _pixels, int w, int h){
	cvSetImageData(cvImage,  _pixels, w*3);
	for (int i = 0; i < h; i++){
		memcpy(pixels + (i * w * 3), cvImage->imageData + (i * cvImage->widthStep), w*3);
	}
}

//-------------------------------------------------------------------------------------
unsigned char * ofCvColorImage::getPixels(){
	// copy each line of pixels:
	for (int i = 0; i < height; i++){
		memcpy(pixels + (i * width * 3), cvImage->imageData + (i * cvImage->widthStep), width*3);
	}
	return pixels;
}

//-------------------------------------------------------------------------------------
void ofCvColorImage::draw(float x, float y){

	// note, this is a bit ineficient, as we have to
	// copy the data out of the cvImage into the pixel array
	// and then upload to texture.  We should add
	// to the texture class an override for pixelstorei
	// that allows stepped-width image upload:

	tex.loadData(getPixels(), width, height, GL_RGB);
	tex.draw(x,y,width, height);
}
