/*  
    Crystal Shooter, a first person shooter game engine.
    Homepage: http://members.xoom.com/thieber/cs

    Copyright (C) 1999 Thomas Hieber (thieber@gmx.net)
 
    This program is free software; you can redistribute it and/or modify 
    it under the terms of the GNU General Public License as published by 
    the Free Software Foundation; either version 2 of the License, or 
    (at your option) any later version. 
 
    This program is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    GNU General Public License for more details. 
 
    You should have received a copy of the GNU General Public License 
    along with this program; if not, write to the Free Software 
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
*/

#include "sysdef.h"
#include "csgame/gstd.h"
#include "csgame/gworld.h"

geWorld::geWorld(csWorld* pCsWorld)
  : inherited(NULL)
{
  m_pWorld   = this;
  m_pCsWorld = pCsWorld;
  m_pView    = NULL;
  m_pPlayer  = new gePlayer(this);
}

geWorld::~geWorld()
{
  delete m_pPlayer;
}

void geWorld::SetView(csView* pView)
{
  ASSERT(pView);
  m_pView = pView;
}
 
void geWorld::SetCamera(gePosition Pos, float Rotation, float Pitch)
{
  ASSERT(m_pView);

  csCamera* pCamera = m_pView->GetCamera();
  ASSERT(pCamera);

  //first set the position of the camera
  m_pView->SetSector(Pos.GetSector());
  pCamera->SetSector  (Pos.GetSector());
  pCamera->SetPosition(Pos.GetPosition());

  //then init the camera with a standard view Matrix
  csMatrix3 m(1,0,0, 0,1,0, 0,0,1);
  pCamera->SetW2C(m);

  //Now rotate the camera according to the calculated angles.
  pCamera->RotateWorld (VEC_ROT_RIGHT, Rotation);
  pCamera->Rotate      (VEC_RIGHT,     Pitch);
}

void geWorld::InitCollisionDetection()
{
  int sn = m_pCsWorld->sectors.Length ();
  while (sn > 0)
  {
    sn--;
    csSector* sp = (csSector*)m_pCsWorld->sectors[sn];
    // Initialize the sector itself.
    CHK(csCollider* pCollider = new csCollider(sp));
    csColliderPointerObject::SetCollider(*sp, pCollider, true);
    // Initialize the things in this sector.
    csThing* tp = sp->GetFirstThing();
    while (tp)
    {
      CHK(csCollider* pCollider = new csCollider(tp));
      csColliderPointerObject::SetCollider(*tp, pCollider, true);
      tp = (csThing*)(tp->GetNext ());
    }
  }

  // Initialize all multisector objects that support
  // collision detection.
  // Check collision of with the sprites in this sector.
  csSprite3D* sp3d = 0;
  //csTransform cds;
  int i;
  for (i = 0 ; i < m_pWorld->GetCsWorld()->sprites.Length () ; i++)
  {
    sp3d = (csSprite3D*)m_pWorld->GetCsWorld()->sprites[i];

    CHK(csCollider* pCollider = new csCollider(sp3d));
    csColliderPointerObject::SetCollider(*sp3d, pCollider, true);
  }
}
