#include "cpu.h"
#include<QVector>
#include <QRgb>

CPU::CPU(){
}


CPU::CPU(textureWidget* p){ this->texturewidget = p;}


bool CPU::intersecta(Raig *raig, Capsa3D cub, float t0, float t1){
    float tmin, tmax, tymin, tymax, tzmin, tzmax;
    if (raig->v.x >= 0) {
        tmin = (cub.pmin.x - raig->p.x) / raig->v.x;
        tmax = (cub.a - raig->p.x) / raig->v.x;
    }
    else {
        tmin = (cub.a - raig->p.x) / raig->v.x;
        tmax = (cub.pmin.x - raig->p.x) / raig->v.x;
    }
    if (raig->v.y >= 0) {
        tymin = (cub.pmin.y - raig->p.y) / raig->v.y;
        tymax = (cub.h - raig->p.y) / raig->v.y;
    }
    else {
        tymin = (cub.h - raig->p.y) / raig->v.y;
        tymax = (cub.pmin.y - raig->p.y) / raig->v.y;
    }
    if ( (tmin > tymax) || (tymin > tmax) )
        return false;
    if (tymin > tmin)
        tmin = tymin;
    if (tymax < tmax)
        tmax = tymax;
    if (raig->v.z >= 0) {
        tzmin = (cub.pmin.z - raig->p.z) / raig->v.z;
        tzmax = (cub.p - raig->p.z) / raig->v.z;
    }
    else {
        tzmin = (cub.p - raig->p.z) / raig->v.z;
        tzmax = (cub.pmin.z - raig->p.z) / raig->v.z;
    }
    if ( (tmin > tzmax) || (tzmin > tmax) )
        return false;
    if (tzmin > tmin)
        tmin = tzmin;
    if (tzmax < tmax)
        tmax = tzmax;

    if ((tmin < t1) && (tmax > t0)){
        tnear = tmin;
        tfar = tmax;
        return ( true );
    }

    return false;

}


float CPU::getVoxel(int i, int j, int k)
{
    return voxels[i+j*anchura+k*anchura*altura];
}

float CPU::getVoxelMask(int i, int j, int k)
{
    return mask[i+j*anchura+k*anchura*altura];
}

void CPU::ShowRCCPUResults(GLubyte *ptTex,int wi,int he){
    texturewidget->showRaycastingCPUResult(ptTex);
    texturewidget->updateGL();
}

textureWidget* CPU::getTextureWidget(){
    return texturewidget;
}

void CPU::CarregaParametres(Parametres *p){

    this->voxels = p->voxels;
    this->mask = p->mask;

   this->colores = p->colores;
   this->materialPrimari=p->primari;

   this->UMBRAL_OPACITAT = p->opacitat;
   this->UMBRAL_SATURACIO = p->saturacio;
   raig->incrementMostreig = p->sampling;
   lista = p->lista;
   uns = p->uns;
   f1 = p->f1;
   imagen = p->imagen;
   nombreFichero = p->nombreFichero;
   unsCS = p->unsCS;
   capas = p->capas;
   points = p->points;
   normals = p->normals;
   colors = p->colors;
   this->altura = p->altura;
   this->anchura = p->anchura;
   this->profundidad = p->profundidad;
   this->NumVoxelsMon = p->NumVoxelsMon;
   this->colormascara = p->ColorMascara;

}
