
#include "stdafx.h"
#include "Radiant.h"
#include "XYWnd.h"
#include "qe3.h"
#include "3DFXCamWnd.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


typedef HGLRC (WINAPI *___wglCreateContext)(HDC); ___wglCreateContext __wglCreateContext;
typedef BOOL (WINAPI *___wglMakeCurrent)(HDC, HGLRC); ___wglMakeCurrent __wglMakeCurrent;
typedef void (WINAPI *___glGetFloatv)(GLenum pname, GLfloat *params); ___glGetFloatv __glGetFloatv;
typedef void (WINAPI *___glViewport)(GLint x, GLint y, GLsizei width, GLsizei height); ___glViewport __glViewport;
typedef void (WINAPI *___glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); ___glScissor __glScissor;
typedef void (WINAPI *___glClearColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); ___glClearColor __glClearColor;
typedef void (WINAPI *___glClear)(GLbitfield mask); ___glClear __glClear;
typedef void (WINAPI *___glMatrixMode)(GLenum mode); ___glMatrixMode __glMatrixMode;
typedef void (WINAPI *___glLoadIdentity)(void); ___glLoadIdentity __glLoadIdentity;
typedef void (WINAPI *___glRotatef)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); ___glRotatef __glRotatef;
typedef void (WINAPI *___glTranslatef)(GLfloat x, GLfloat y, GLfloat z); ___glTranslatef __glTranslatef;
typedef void (WINAPI *___glCullFace)(GLenum mode); ___glCullFace __glCullFace;
typedef void (WINAPI *___glEnable)(GLenum cap); ___glEnable __glEnable;
typedef void (WINAPI *___glDisable)(GLenum cap); ___glDisable __glDisable;
typedef void (WINAPI *___glShadeModel)(GLenum mode); ___glShadeModel __glShadeModel;
typedef void (WINAPI *___glPolygonMode)(GLenum face, GLenum mode); ___glPolygonMode __glPolygonMode;
typedef void (WINAPI *___glTexEnvf)(GLenum target, GLenum pname, GLfloat param); ___glTexEnvf __glTexEnvf;
typedef void (WINAPI *___glTexParameterf)(GLenum target, GLenum pname, GLfloat param); ___glTexParameterf __glTexParameterf;
typedef void (WINAPI *___glDepthFunc)(GLenum func); ___glDepthFunc __glDepthFunc;
typedef void (WINAPI *___glDepthMask)(GLboolean flag); ___glDepthMask __glDepthMask;
typedef void (WINAPI *___glBlendFunc)(GLenum sfactor, GLenum dfactor); ___glBlendFunc __glBlendFunc;
typedef void (WINAPI *___glColor3f)(GLfloat red, GLfloat green, GLfloat blue); ___glColor3f __glColor3f;
typedef void (WINAPI *___glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); ___glColor4f __glColor4f;
typedef void (WINAPI *___glBegin)(GLenum mode); ___glBegin __glBegin;
typedef void (WINAPI *___glTexCoord2fv)(const GLfloat *v); ___glTexCoord2fv __glTexCoord2fv;
typedef void (WINAPI *___glEnd)(void); ___glEnd __glEnd;
typedef void (WINAPI *___glBindTexture)(GLenum target, GLuint texture); ___glBindTexture __glBindTexture;
typedef void (WINAPI *___glColor3fv)(const GLfloat *v); ___glColor3fv __glColor3fv;
typedef void (WINAPI *___glVertex3fv)(const GLfloat *v); ___glVertex3fv __glVertex3fv;
typedef void (WINAPI *___glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); ___glTexImage2D __glTexImage2D;

HMODULE g_h3Dfx = NULL;
bool g_b3Dfx = false;

BOOL Init3Dfx()
{
  if (g_h3Dfx == NULL)
  {
    g_h3Dfx = LoadLibrary("3dfxgl.dll");
    if (g_h3Dfx)
    {
      g_b3Dfx = true;
      __wglCreateContext = (___wglCreateContext)GetProcAddress(g_h3Dfx, "wglCreateContext");
      __wglMakeCurrent = (___wglMakeCurrent)GetProcAddress(g_h3Dfx, "wglMakeCurrent");
      __glGetFloatv = (___glGetFloatv)GetProcAddress(g_h3Dfx, "glGetFloatv");
      __glViewport = (___glViewport)GetProcAddress(g_h3Dfx, "glViewport");
      __glScissor = (___glScissor)GetProcAddress(g_h3Dfx, "glScissor");
      __glClearColor = (___glClearColor)GetProcAddress(g_h3Dfx, "glClearColor");
      __glClear = (___glClear)GetProcAddress(g_h3Dfx, "glClear");
      __glMatrixMode = (___glMatrixMode)GetProcAddress(g_h3Dfx, "glMatrixMode");
      __glLoadIdentity = (___glLoadIdentity)GetProcAddress(g_h3Dfx, "glLoadIdentity");
      __glRotatef = (___glRotatef)GetProcAddress(g_h3Dfx, "glRotatef");
      __glTranslatef = (___glTranslatef)GetProcAddress(g_h3Dfx, "glTranslatef");
      __glCullFace = (___glCullFace)GetProcAddress(g_h3Dfx, "glCullFace");
      __glEnable = (___glEnable)GetProcAddress(g_h3Dfx, "glEnable");
      __glDisable = (___glDisable)GetProcAddress(g_h3Dfx, "glDisable");
      __glShadeModel = (___glShadeModel)GetProcAddress(g_h3Dfx, "glShadeModel");
      __glPolygonMode = (___glPolygonMode)GetProcAddress(g_h3Dfx, "glPolygonMode");
      __glTexEnvf = (___glTexEnvf)GetProcAddress(g_h3Dfx, "glTexEnvf");
      __glTexParameterf = (___glTexParameterf)GetProcAddress(g_h3Dfx, "glTexParameterf");
      __glDepthFunc = (___glDepthFunc)GetProcAddress(g_h3Dfx, "glDepthFunc");
      __glDepthMask = (___glDepthMask)GetProcAddress(g_h3Dfx, "glDepthMask");
      __glBlendFunc = (___glBlendFunc)GetProcAddress(g_h3Dfx, "glBlendFunc");
      __glColor3f = (___glColor3f)GetProcAddress(g_h3Dfx, "glColor3f");
      __glColor4f = (___glColor4f)GetProcAddress(g_h3Dfx, "glColor4f");
      __glBegin = (___glBegin)GetProcAddress(g_h3Dfx, "glBegin");
      __glTexCoord2fv = (___glTexCoord2fv)GetProcAddress(g_h3Dfx, "glTexCoord2fv");
      __glEnd = (___glEnd)GetProcAddress(g_h3Dfx, "glEnd");
      __glBindTexture = (___glBindTexture)GetProcAddress(g_h3Dfx, "glBindTexture");
      __glColor3fv = (___glColor3fv)GetProcAddress(g_h3Dfx, "glColor3fv");
      __glVertex3fv = (___glVertex3fv)GetProcAddress(g_h3Dfx, "glVertex3fv");
      __glTexImage2D = (___glTexImage2D)GetProcAddress(g_h3Dfx, "glTexImage2D");
    }
  }
  return TRUE;
}

void Handle3DfxTexturing(qtexture_t* q, int nWidth, int nHeight, unsigned* pDest)
{
  if (g_b3Dfx)
  {
	  __glEnable(GL_TEXTURE_2D);
	  __glBindTexture( GL_TEXTURE_2D, q->texture_number );
	  __glTexImage2D(GL_TEXTURE_2D, 0, 3, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pDest);
	  __glBindTexture( GL_TEXTURE_2D, 0 );
	  __glDisable(GL_TEXTURE_2D);
  }
}


extern void DrawPathLines();
/////////////////////////////////////////////////////////////////////////////
// C3DFXCamWnd
IMPLEMENT_DYNCREATE(C3DFXCamWnd, CWnd);

C3DFXCamWnd::C3DFXCamWnd()
{
  m_pXYFriend = NULL;
  m_nNumTransBrushes = 0;
  memset(&m_Camera, 0, sizeof(camera_t));
  m_pSide_select = NULL;
  Cam_Init();
}

C3DFXCamWnd::~C3DFXCamWnd()
{
}


BEGIN_MESSAGE_MAP(C3DFXCamWnd, CWnd)
	//{{AFX_MSG_MAP(C3DFXCamWnd)
	ON_WM_KEYDOWN()
	ON_WM_PAINT()
	ON_WM_ERASEBKGND()
	ON_WM_DESTROY()
	ON_WM_CLOSE()
	ON_WM_MOUSEMOVE()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MBUTTONDOWN()
	ON_WM_MBUTTONUP()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
	ON_WM_CREATE()
	ON_WM_NCCALCSIZE()
	ON_WM_KILLFOCUS()
	ON_WM_SETFOCUS()
	ON_WM_SIZE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


LONG WINAPI _3DFXCamWndProc (
    HWND    hWnd,
    UINT    uMsg,
    WPARAM  wParam,
    LPARAM  lParam)
{
    RECT	rect;

    GetClientRect(hWnd, &rect);

    switch (uMsg)
    {
	case WM_KILLFOCUS:
	case WM_SETFOCUS:
		SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
		return 0;

	case WM_NCCALCSIZE:// don't let windows copy pixels
		DefWindowProc (hWnd, uMsg, wParam, lParam);
		return WVR_REDRAW;

    }

	return DefWindowProc( hWnd, uMsg, wParam, lParam );
}


/////////////////////////////////////////////////////////////////////////////
// C3DFXCamWnd message handlers

BOOL C3DFXCamWnd::PreCreateWindow(CREATESTRUCT& cs) 
{
  WNDCLASS wc;
  HINSTANCE hInstance = AfxGetInstanceHandle();
  if (::GetClassInfo(hInstance, _3DFXCAMERA_WINDOW_CLASS, &wc) == FALSE)
  {
    // Register a new class
  	memset (&wc, 0, sizeof(wc));
    wc.style         = CS_NOCLOSE | CS_OWNDC;
    wc.lpszClassName = _3DFXCAMERA_WINDOW_CLASS;
    wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
    wc.lpfnWndProc   = _3DFXCamWndProc;
    if (AfxRegisterClass(&wc) == FALSE)
      Error ("C3DFXCamWnd RegisterClass: failed");
  }

  cs.lpszClass = _3DFXCAMERA_WINDOW_CLASS;
  cs.lpszName = "3Dfx CAM";
  if (cs.style != QE3_CHILDSTYLE)
    cs.style = QE3_SPLITTER_STYLE;

	BOOL bResult = CWnd::PreCreateWindow(cs);

  // See if the class already exists and if not then we need
  // to register our new window class.
  return bResult;
	
}


void C3DFXCamWnd::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
  g_pParentWnd->HandleKey(nChar, nRepCnt, nFlags);
}

extern bool g_bClipMode;
extern bool g_bSwitch;
extern brush_t g_brFrontSplits;
extern brush_t g_brBackSplits;
extern CClipPoint g_Clip1;
extern CClipPoint g_Clip2;
extern brush_t* g_pSplitList;

void C3DFXCamWnd::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
  bool bPaint = true;
  if (!__wglMakeCurrent(m_hDC, m_hRC))
  {
    Sys_Printf("ERROR: wglMakeCurrent failed..\n ");
    Sys_Printf("Please restart QERadiant if the camera view is not working\n");
  }
  else
  {
    //QE_CheckOpenGLForErrors();
    g_bClipMode = false;
    if (m_pXYFriend)
    {
      g_bClipMode = m_pXYFriend->ClipMode();
      if (g_bClipMode)
      {
        if (g_Clip1.Set() && g_Clip2.Set())
        {
          g_pSplitList = (g_bSwitch) ? &g_brFrontSplits : &g_brBackSplits;
        }
        else
        {
          g_bClipMode = false;
        }
      }
    }
		Cam_Draw ();
		QE_CheckOpenGLForErrors();
		qwglSwapBuffers(m_hDC);
  }
}


void C3DFXCamWnd::SetXYFriend(CXYWnd * pWnd)
{
  m_pXYFriend = pWnd;
}

BOOL C3DFXCamWnd::OnEraseBkgnd(CDC* pDC) 
{
  return CWnd::OnEraseBkgnd(pDC);
  //TRUE;
}

void C3DFXCamWnd::OnDestroy() 
{
	QEW_StopGL(GetSafeHwnd(), g_qeglobals.d_hglrcBase, g_qeglobals.d_hdcBase );
	CWnd::OnDestroy();
}

void C3DFXCamWnd::OnClose() 
{
	CWnd::OnClose();
}

void C3DFXCamWnd::OnMouseMove(UINT nFlags, CPoint point) 
{
  CRect r;
  GetClientRect(r);
	SetCapture();
	Cam_MouseMoved(point.x, r.bottom - 1 - point.y, nFlags);
}

void C3DFXCamWnd::OnLButtonDown(UINT nFlags, CPoint point) 
{
  OriginalMouseDown(nFlags, point);
}

void C3DFXCamWnd::OnLButtonUp(UINT nFlags, CPoint point) 
{
  OriginalMouseUp(nFlags, point);
}

void C3DFXCamWnd::OnMButtonDown(UINT nFlags, CPoint point) 
{
  OriginalMouseDown(nFlags, point);
}

void C3DFXCamWnd::OnMButtonUp(UINT nFlags, CPoint point) 
{
  OriginalMouseUp(nFlags, point);
}

void C3DFXCamWnd::OnRButtonDown(UINT nFlags, CPoint point) 
{
  OriginalMouseDown(nFlags, point);
}

void C3DFXCamWnd::OnRButtonUp(UINT nFlags, CPoint point) 
{
  OriginalMouseUp(nFlags, point);
}

int C3DFXCamWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
  if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	//g_qeglobals.d_hdcBase = GetDC()->m_hDC;
  

  m_hDC = GetDC()->m_hDC;
	QEW_SetupPixelFormat(m_hDC, true);
  m_hRC = __wglCreateContext(m_hDC);
  __wglMakeCurrent(m_hDC, m_hRC);
  //InitFXTextures();
	return 0;
}

void C3DFXCamWnd::OriginalMouseUp(UINT nFlags, CPoint point)
{
  CRect r;
  GetClientRect(r);
  Cam_MouseUp(point.x, r.bottom - 1 - point.y, nFlags);
	if (!(nFlags & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
  	ReleaseCapture ();
}

void C3DFXCamWnd::OriginalMouseDown(UINT nFlags, CPoint point)
{
  if (GetTopWindow()->GetSafeHwnd() != GetSafeHwnd())
    BringWindowToTop();
  CRect r;
  GetClientRect(r);
  SetFocus();
	SetCapture();
	Cam_MouseDown (point.x, r.bottom - 1 - point.y, nFlags);
}

void C3DFXCamWnd::Cam_Init()
{
	//m_Camera.draw_mode = cd_texture;
	m_Camera.timing = false;
	m_Camera.origin[0] = 0;
	m_Camera.origin[1] = 20;
	m_Camera.origin[2] = 46;
	m_Camera.color[0] = 0.3;
	m_Camera.color[1] = 0.3;
	m_Camera.color[2] = 0.3;
}

void C3DFXCamWnd::Cam_BuildMatrix()
{
	float	xa, ya;
	float	matrix[4][4];
	int		i;

	xa = m_Camera.angles[0]/180*Q_PI;
	ya = m_Camera.angles[1]/180*Q_PI;

	// the movement matrix is kept 2d

  m_Camera.forward[0] = cos(ya);
  m_Camera.forward[1] = sin(ya);
  m_Camera.right[0] = m_Camera.forward[1];
  m_Camera.right[1] = -m_Camera.forward[0];

	__glGetFloatv (GL_PROJECTION_MATRIX, &matrix[0][0]);

	for (i=0 ; i<3 ; i++)
	{
		m_Camera.vright[i] = matrix[i][0];
		m_Camera.vup[i] = matrix[i][1];
		m_Camera.vpn[i] = matrix[i][2];
	}

	VectorNormalize (m_Camera.vright);
	VectorNormalize (m_Camera.vup);
	VectorNormalize (m_Camera.vpn);
}



void C3DFXCamWnd::Cam_ChangeFloor (qboolean up)
{
	brush_t	*b;
	float	d, bestd, current;
	vec3_t	start, dir;

	start[0] = m_Camera.origin[0];
	start[1] = m_Camera.origin[1];
	start[2] = 8192;
	dir[0] = dir[1] = 0;
	dir[2] = -1;

	current = 8192 - (m_Camera.origin[2] - 48);
	if (up)
		bestd = 0;
	else
		bestd = 16384;

	for (b=active_brushes.next ; b != &active_brushes ; b=b->next)
	{
		if (!Brush_Ray (start, dir, b, &d))
			continue;
		if (up && d < current && d > bestd)
			bestd = d;
		if (!up && d > current && d < bestd)
			bestd = d;
	}

	if (bestd == 0 || bestd == 16384)
		return;

	m_Camera.origin[2] += current - bestd;
	Sys_UpdateWindows (W_CAMERA|W_Z_OVERLAY);
}


void C3DFXCamWnd::Cam_PositionDrag()
{
	int	x, y;
	Sys_GetCursorPos (&x, &y);
	if (x != m_ptCursor.x || y != m_ptCursor.y)
	{
		x -= m_ptCursor.x;
		VectorMA (m_Camera.origin, x, m_Camera.vright, m_Camera.origin);
		y -= m_ptCursor.y;
		m_Camera.origin[2] -= y;
    SetCursorPos(m_ptCursor.x, m_ptCursor.y);
		Sys_UpdateWindows (W_CAMERA | W_XY_OVERLAY);
	}
}


void C3DFXCamWnd::Cam_MouseControl (float dtime)
{
	int		xl, xh;
	int		yl, yh;
	float	xf, yf;

  if (g_PrefsDlg.m_nMouseButtons == 2)
  {
    if (m_nCambuttonstate != (MK_RBUTTON | MK_SHIFT))
      return;
  }
  else
  {
	  if (m_nCambuttonstate != MK_RBUTTON)
      return;
  }

	xf = (float)(m_ptButton.x - m_Camera.width/2) / (m_Camera.width/2);
	yf = (float)(m_ptButton.y - m_Camera.height/2) / (m_Camera.height/2);


	xl = m_Camera.width/3;
	xh = xl*2;
	yl = m_Camera.height/3;
	yh = yl*2;

  //Sys_Printf("xf-%f  yf-%f  xl-%i  xh-i%  yl-i%  yh-i%\n",xf,yf,xl,xh,yl,yh);
#if 0
	// strafe
	if (buttony < yl && (buttonx < xl || buttonx > xh))
		VectorMA (camera.origin, xf*dtime*MOVE_SPEED, camera.right, camera.origin);
	else
#endif
	{
		xf *= 1.0 - fabs(yf);
		if (xf < 0)
		{
			xf += 0.1;
			if (xf > 0)
				xf = 0;
		}
		else
		{
			xf -= 0.1;
			if (xf < 0)
				xf = 0;
		}
		
		VectorMA (m_Camera.origin, yf*dtime*MOVE_SPEED, m_Camera.forward, m_Camera.origin);
		m_Camera.angles[YAW] += xf*-dtime*ANGLE_SPEED;
	}
	Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY);
  MSG msg;

  while (::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE )) 
  { 
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
}



void C3DFXCamWnd::Cam_MouseDown(int x, int y, int buttons)
{
	vec3_t		dir;
	float		f, r, u;
	int			i;

	//
	// calc ray direction
	//
	u = (float)(y - m_Camera.height/2) / (m_Camera.width/2);
	r = (float)(x - m_Camera.width/2) / (m_Camera.width/2);
	f = 1;

	for (i=0 ; i<3 ; i++)
		dir[i] = m_Camera.vpn[i] * f + m_Camera.vright[i] * r + m_Camera.vup[i] * u;
	VectorNormalize (dir);

	GetCursorPos(&m_ptCursor);

	m_nCambuttonstate = buttons;
	m_ptButton.x = x;
	m_ptButton.y = y;

	// LBUTTON = manipulate selection
	// shift-LBUTTON = select
	// middle button = grab texture
	// ctrl-middle button = set entire brush to texture
	// ctrl-shift-middle button = set single face to texture
  int nMouseButton = g_PrefsDlg.m_nMouseButtons == 2 ? MK_RBUTTON : MK_MBUTTON;
	if ((buttons == MK_LBUTTON)
		        || (buttons == (MK_LBUTTON | MK_SHIFT))
		        || (buttons == (MK_LBUTTON | MK_CONTROL))
		        || (buttons == (MK_LBUTTON | MK_CONTROL | MK_SHIFT))
		        || (buttons == nMouseButton)
		        || (buttons == (nMouseButton|MK_CONTROL))
		        || (buttons == (nMouseButton|MK_SHIFT|MK_CONTROL)))
	{

    if (g_PrefsDlg.m_nMouseButtons == 2 && (buttons == (MK_RBUTTON | MK_SHIFT)))
		  Cam_MouseControl (0.1);
    else
		  Drag_Begin (x, y, buttons, m_Camera.vright, m_Camera.vup,	m_Camera.origin, dir);
    return;
	}

	if (buttons == MK_RBUTTON)
	{
		Cam_MouseControl (0.1);
		return;
	}
}


void C3DFXCamWnd::Cam_MouseUp (int x, int y, int buttons)
{
	m_nCambuttonstate = 0;
	Drag_MouseUp ();
}


void C3DFXCamWnd::Cam_MouseMoved (int x, int y, int buttons)
{
	m_nCambuttonstate = buttons;
	if (!buttons)
		return;
	m_ptButton.x = x;
	m_ptButton.y = y;

	if (buttons == (MK_RBUTTON|MK_CONTROL) )
	{
		Cam_PositionDrag ();
		Sys_UpdateWindows (W_XY|W_CAMERA|W_Z);
		return;
	}

	GetCursorPos(&m_ptCursor);

	if (buttons & (MK_LBUTTON | MK_MBUTTON) )
	{
		Drag_MouseMoved (x, y, buttons);
		Sys_UpdateWindows (W_XY|W_CAMERA|W_Z);
	}
}


void C3DFXCamWnd::InitCull()
{
	int		i;

	VectorSubtract (m_Camera.vpn, m_Camera.vright, m_vCull1);
	VectorAdd (m_Camera.vpn, m_Camera.vright, m_vCull2);

	for (i=0 ; i<3 ; i++)
	{
		if (m_vCull1[i] > 0)
			m_nCullv1[i] = 3+i;
		else
			m_nCullv1[i] = i;
		if (m_vCull2[i] > 0)
			m_nCullv2[i] = 3+i;
		else
			m_nCullv2[i] = i;
	}
}

qboolean C3DFXCamWnd::CullBrush (brush_t *b)
{
	int		i;
	vec3_t	point;
	float	d;

	for (i=0 ; i<3 ; i++)
		point[i] = b->mins[m_nCullv1[i]] - m_Camera.origin[i];

	d = DotProduct (point, m_vCull1);
	if (d < -1)
		return true;

	for (i=0 ; i<3 ; i++)
		point[i] = b->mins[m_nCullv2[i]] - m_Camera.origin[i];

	d = DotProduct (point, m_vCull2);
	if (d < -1)
		return true;

	return false;
}



void __Brush_Draw( brush_t *b )
{
	face_t			*face;
	int				i, order;
  qtexture_t		*prev = 0;
	winding_t *w;

	__glDisable (GL_TEXTURE_2D);

	// guarantee the texture will be set first
	prev = NULL;
	for (face = b->brush_faces,order = 0 ; face ; face=face->next, order++)
	{
		w = face->face_winding;
		if (!w)
			continue;		// freed face

    if (face->d_texture != prev)
    {
	    // set the texture for this face
			prev = face->d_texture;
			__glBindTexture( GL_TEXTURE_2D, face->d_texture->texture_number );
    }

		if (face->texdef.flags & ( 1 << 4 )) 
		  __glColor4f ( face->d_color[0], face->d_color[1], face->d_color[2], 0.33 );
		else if ( face->texdef.flags & ( 1 << 5 ) ) 
			__glColor4f ( face->d_color[0], face->d_color[1], face->d_color[2], 0.66 );
		else
			__glColor3fv( face->d_color );

    // draw the polygon
		__glBegin(GL_POLYGON);
	    for (i=0 ; i<w->numpoints ; i++)
		{
			__glTexCoord2fv( &w->points[i][3] );
			__glVertex3fv(w->points[i]);
		}
		__glEnd();

	}

	__glEnable (GL_TEXTURE_2D);
	__glBindTexture(GL_TEXTURE_2D, 0);
}

void __Face_Draw( face_t *f )
{
	int i;

	if ( f->face_winding == 0 )
		return;
	__glBegin( GL_POLYGON );
	for ( i = 0 ; i < f->face_winding->numpoints; i++)
		glVertex3fv( f->face_winding->points[i] );
	__glEnd();
}


/*
==============
Cam_Draw
==============
*/
void C3DFXCamWnd::Cam_Draw()
{
  brush_t	*brush;
	face_t	*face;
	float	screenaspect;
	float	yfov;
	double	start;
	int		i;

	if (!active_brushes.next)
		return;	// not valid yet

	if (m_Camera.timing)
		start = Sys_DoubleTime ();

	//
	// clear
	//
	//QE_CheckOpenGLForErrors();

	__glViewport(0, 0, m_Camera.width, m_Camera.height);
	__glScissor(0, 0, m_Camera.width, m_Camera.height);
	__glClearColor (g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][0],
		              g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][1],
		              g_qeglobals.d_savedinfo.colors[COLOR_CAMERABACK][2],0);
  __glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//
	// set up viewpoint
	//
	__glMatrixMode(GL_PROJECTION);
  __glLoadIdentity ();

  screenaspect = (float)m_Camera.width / m_Camera.height;
	yfov = 2*atan((float)m_Camera.height / m_Camera.width)*180/Q_PI;
  gluPerspective (yfov,  screenaspect,  2,  8192);

  __glRotatef (-90,  1, 0, 0);	    // put Z going up
  __glRotatef (90,  0, 0, 1);	    // put Z going up
  __glRotatef (m_Camera.angles[0],  0, 1, 0);
  __glRotatef (-m_Camera.angles[1],  0, 0, 1);
  __glTranslatef (-m_Camera.origin[0],  -m_Camera.origin[1],  -m_Camera.origin[2]);

	Cam_BuildMatrix ();

	InitCull ();

	//
	// draw stuff
	//

  __glCullFace(GL_FRONT);
	__glEnable(GL_CULL_FACE);
	__glShadeModel (GL_FLAT);
	__glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
	__glEnable(GL_TEXTURE_2D);
	__glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	__glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	__glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	__glDisable(GL_BLEND);
	__glEnable(GL_DEPTH_TEST);
	__glDepthFunc (GL_LEQUAL);

	__glMatrixMode(GL_TEXTURE);

  m_nNumTransBrushes = 0;

	for (brush = active_brushes.next ; brush != &active_brushes ; brush=brush->next)
	{
		if (CullBrush (brush))
			continue;
		if (FilterBrush (brush))
			continue;

		if (( brush->brush_faces->texdef.flags & ( 1 << 4 ) ) ||
			  ( brush->brush_faces->texdef.flags & ( 1 << 5 ) ) ) 
    {
			// This means it's somehow transparent
			m_TransBrushes [ m_nNumTransBrushes++ ] = brush;
		} 
    else 
    {
			__Brush_Draw(brush);
		}
	}
  __glDepthMask ( 0 ); // Don't write to depth buffer
	__glEnable ( GL_BLEND );
	__glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	for ( i = 0; i < m_nNumTransBrushes; i++ ) 
		__Brush_Draw (m_TransBrushes[i]);

	__glDepthMask ( 1 ); // Ok, write now

	__glMatrixMode(GL_PROJECTION);

	//
	// now draw selected brushes
	//

	__glTranslatef (g_qeglobals.d_select_translate[0], g_qeglobals.d_select_translate[1], g_qeglobals.d_select_translate[2]);
	__glMatrixMode(GL_TEXTURE);

  brush_t* pList = (g_bClipMode && g_pSplitList) ? g_pSplitList : &selected_brushes;
	// draw normally
	for (brush = pList->next ; brush != pList ; brush=brush->next)
	{
	  __Brush_Draw(brush);
	}

	// blend on top
	__glMatrixMode(GL_PROJECTION);


	__glColor4f(1.0, 0.0, 0.0, 0.3);
	__glEnable (GL_BLEND);
	//__glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
	__glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	__glDisable (GL_TEXTURE_2D);
	for (brush = pList->next ; brush != pList ; brush=brush->next)
		for (face=brush->brush_faces ; face ; face=face->next)
			__Face_Draw( face );

  if (selected_face)
		__Face_Draw(selected_face);

	// non-zbuffered outline

	__glDisable (GL_BLEND);
	__glDisable (GL_DEPTH_TEST);
	__glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
	__glColor3f (1, 1, 1);
	for (brush = pList->next ; brush != pList ; brush=brush->next)
		for (face=brush->brush_faces ; face ; face=face->next)
			__Face_Draw( face );

  glFinish();
}


void C3DFXCamWnd::OnSize(UINT nType, int cx, int cy) 
{
	CWnd::OnSize(nType, cx, cy);
  CRect rect;
  GetClientRect(rect);
	m_Camera.width = rect.right;
	m_Camera.height = rect.bottom;
	InvalidateRect(NULL, false);
}

