#include "SM_Engine3DPCH.h"


RenderContext::RenderContext()
{
  m_x=0.0f;
  m_y=0.0f;
  m_w=1.0f;
  m_h=0.75f;
}

void RenderContext::UpdateFrustum()
{
  Matrix4X4 View;
  Matrix4X4 Projection;

  m_Viewport3D.ViewMatrix(View);
  m_Viewport3D.ProjectionMatrix(Projection);

  
  GenerateFrustumPlanes(&View, &Projection, m_Planes);  
}

void RenderContext::SyncRasterizer()
{
  Matrix4X4 m;

  assert(sizeof(m)==sizeof(D3DMATRIX));

  

  m=Matrix4X4::Identity;
  SM_D3d::Device()->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&m);  

  m_Viewport3D.ViewMatrix(m);

  m_VRP.x=m.m_11;
  m_VRP.y=m.m_21;
  m_VRP.z=m.m_31;

  m_VUP.x=m.m_12;
  m_VUP.y=m.m_22;
  m_VUP.z=m.m_32;

  m_VPN.x=m.m_13;
  m_VPN.y=m.m_23;
  m_VPN.z=m.m_33;  
  
  
  SM_D3d::Device()->SetTransform(D3DTS_VIEW, (D3DMATRIX*)&m);  
  
  m_Viewport3D.ProjectionMatrix(m);
  SM_D3d::Device()->SetTransform(D3DTS_PROJECTION, (D3DMATRIX*)&m);    
   
  
  Coordinates::UpdatePhysicViewport(m_x, m_y, m_w, m_h);
}

void RenderContext::SetViewport(float x, float y, float w, float h)
{
  m_x=x;
  m_y=y;
  m_w=w;
  m_h=h;
}

void RenderContext::Set (const    Vector3D&   v3dPosition, 
            const    Quaternion& qRotation,
            float    fFOV,
            float    fAspectRatio,
            float    fZNear,
            float    fZFar)
{
  m_Viewport3D.Set(v3dPosition, 
                   qRotation,
                   fFOV,
                   fAspectRatio,
                   fZNear,
                   fZFar);
}

void RenderContext::Set (const    Vector3D&   pos, 
                       const    Vector3D&   at, 
                       const    Vector3D&   up, 
                       float    fFOV,
                       float    fAspectRatio,
                       float    fZNear,
                       float    fZFar)
{
  m_Viewport3D.Set(pos, 
                   at,
                   up,
                   fFOV,
                   fAspectRatio,
                   fZNear,
                   fZFar);
}


 

int RenderContext::OutcodeSphere(Vector3D* pVector3D, float fRadius)
{
  int i;
  int iReturn=0;

  for (i=0 ; i<6 ; i++)
  {
    float fDistance=m_Planes[i].Evaluate(pVector3D);
    if (fDistance<-fRadius)
    {
      return -1;
    }
    else if (fDistance<=fRadius)
    {
      iReturn|=1<<i;
    }
  }

  return iReturn;
}
