]> de.git.xonotic.org Git - xonotic/netradiant.git/blobdiff - radiant/pmesh.cpp
apply patch from Martin Gerhardy - more quake2 related modules compiled and misc...
[xonotic/netradiant.git] / radiant / pmesh.cpp
index 1cf2067b834dd171cb8a37f77bea5892c2cf0996..ca8b5297ec89d1154257e4e428ee4748011e7f34 100644 (file)
-/*\r
-Copyright (C) 1999-2007 id Software, Inc. and contributors.\r
-For a list of contributors, see the accompanying CONTRIBUTORS file.\r
-\r
-This file is part of GtkRadiant.\r
-\r
-GtkRadiant is free software; you can redistribute it and/or modify\r
-it under the terms of the GNU General Public License as published by\r
-the Free Software Foundation; either version 2 of the License, or\r
-(at your option) any later version.\r
-\r
-GtkRadiant is distributed in the hope that it will be useful,\r
-but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
-GNU General Public License for more details.\r
-\r
-You should have received a copy of the GNU General Public License\r
-along with GtkRadiant; if not, write to the Free Software\r
-Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\r
-*/\r
-\r
-// \r
-// Preliminary patch stuff\r
-//\r
-// \r
-\r
-#include "stdafx.h"\r
-#include "gtkmisc.h"\r
-\r
-#include "gtkr_list.h"\r
-\r
-// externs\r
-extern void MemFile_fprintf(MemStream* pMemFile, const char* pText, ...);\r
-extern face_t *Face_Alloc( void );\r
-extern void DrawAlternatePoint(vec3_t v, float scale);\r
-\r
-void _Write3DMatrix (FILE *f, int y, int x, int z, float *m);\r
-void _Write3DMatrix (MemStream *f, int y, int x, int z, float *m);\r
-\r
-void Patch_InitialiseLODPointers(patchMesh_t *p)\r
-{\r
-       int i;\r
-       int rowcount = ((MAX_PATCH_WIDTH-1)/2) * MAX_PATCH_HEIGHT;\r
-       for (i=0; i<rowcount; i++)\r
-               p->rowLOD[i] = NULL;\r
-       int colcount = ((MAX_PATCH_HEIGHT-1)/2) * MAX_PATCH_WIDTH;\r
-       for (i=0; i<colcount; i++)\r
-               p->colLOD[i] = NULL;\r
-}\r
-\r
-patchMesh_t* Patch_Alloc()\r
-{\r
-  patchMesh_t *pPatch = (patchMesh_t *)malloc(sizeof(patchMesh_t));\r
-  pPatch->pShader = NULL;\r
-  pPatch->pSymbiot = NULL; // Hydra: added missing initialiser.\r
-       // spog - initialise patch LOD pointers\r
-  Patch_InitialiseLODPointers(pPatch);\r
-  pPatch->drawLists = NULL;\r
-  pPatch->bDirty = true;\r
-  pPatch->nListID = -1;\r
-  pPatch->bSelected = false;\r
-  pPatch->bOverlay = false;\r
-  pPatch->bDirty = true;\r
-  pPatch->LODUpdated = false;\r
-\r
-  int i;\r
-  for (i=0; i<(((MAX_PATCH_WIDTH-1)-1)/2); i++)\r
-    pPatch->rowDirty[i] = false;\r
-  for (i=0; i<(((MAX_PATCH_HEIGHT-1)-1)/2); i++)\r
-    pPatch->colDirty[i] = false;\r
-\r
-  return pPatch;\r
-}\r
-\r
-patchMesh_t* MakeNewPatch()\r
-{\r
-  patchMesh_t *pm = reinterpret_cast<patchMesh_t*>(qmalloc(sizeof(patchMesh_t)));\r
-\r
-  // spog - initialise patch LOD pointers\r
-  Patch_InitialiseLODPointers(pm);\r
-  pm->drawLists = NULL;\r
-  pm->bDirty = true;\r
-\r
-  return pm;\r
-}\r
-\r
-// FIXME: this needs to be dynamic\r
-//#define      MAX_PATCH_MESHES        4096\r
-//patchMesh_t          patchMeshes[MAX_PATCH_MESHES];\r
-//int numPatchMeshes = 0;\r
-\r
-// used for a save spot\r
-patchMesh_t patchSave;\r
-\r
-// Tracks the selected patch for point manipulation/update. FIXME: Need to revert back to a generalized \r
-// brush approach\r
-//--int  g_nSelectedPatch = -1;  \r
-\r
-// HACK: for tracking which view generated the click\r
-// as we dont want to deselect a point on a same point\r
-// click if it is from a different view\r
-int  g_nPatchClickedView = -1;\r
-bool g_bSameView = false;\r
-\r
-//typedef enum XFormType { TRANSLATE, SCALE, ROTATE };\r
-\r
-\r
-// globals\r
-bool g_bPatchShowBounds = true;\r
-bool g_bPatchWireFrame = false;\r
-bool g_bPatchWeld = true;\r
-bool g_bPatchDrillDown = true;\r
-//bool g_bPatchInsertMode = false;\r
-bool g_bPatchBendMode = false;\r
-int  g_nPatchBendState = -1;\r
-int  g_nPatchInsertState = -1;\r
-int  g_nBendOriginIndex = 0;\r
-vec3_t g_vBendOrigin;\r
-\r
-bool g_bPatchAxisOnRow = true;\r
-int  g_nPatchAxisIndex = 0;\r
-bool g_bPatchLowerEdge = true;\r
-\r
-vec3_t g_vCycleCapNormal;\r
-// cycles when we use Patch_CycleCapSelected\r
-VIEWTYPE g_nCycleCapIndex = XY;\r
-\r
-// BEND states\r
-enum\r
-{\r
-  BEND_SELECT_ROTATION = 0,\r
-  BEND_SELECT_ORIGIN,\r
-  BEND_SELECT_EDGE,\r
-  BEND_BENDIT,\r
-  BEND_STATE_COUNT\r
-};\r
-\r
-const char *g_pBendStateMsg[] =\r
-{\r
-  "Use TAB to cycle through available bend axis. Press ENTER when the desired one is highlighted.",\r
-  "Use TAB to cycle through available rotation axis. This will LOCK around that point. You may also use Shift + Middle Click to select an arbitrary point. Press ENTER when the desired one is highlighted",\r
-  "Use TAB to choose which side to bend. Press ENTER when the desired one is highlighted.",\r
-  "Use the MOUSE to bend the patch. It uses the same ui rules as Free Rotation. Press ENTER to accept the bend, press ESC to abandon it and exit Bend mode",\r
-  ""\r
-};\r
-\r
-// INSERT states\r
-enum\r
-{\r
-  INSERT_SELECT_EDGE = 0,\r
-  INSERT_STATE_COUNT\r
-};\r
-\r
-const char* g_pInsertStateMsg[] =\r
-{\r
-  "Use TAB to cycle through available rows/columns for insertion/deletion. Press INS to insert at the highlight, DEL to remove the pair"\r
-};\r
-\r
-\r
-float *g_InversePoints[1024];\r
-\r
-const float fFullBright = 1.0;\r
-const float fLowerLimit = .50;\r
-const float fDec = .05f;\r
-void _SetColor(face_t* f, float fColor[3])\r
-{\r
-  return;\r
-  fColor[0] = f->d_color[0];\r
-  fColor[1] = f->d_color[1];\r
-  fColor[2] = f->d_color[2];\r
-  qglColor3fv(fColor);\r
-}\r
-\r
-\r
-void _DecColor(float fColor[3])\r
-{\r
-  return;\r
-  fColor[0] -= fDec;\r
-  fColor[1] -= fDec ;\r
-  fColor[2] -= fDec;\r
-  for (int i = 0; i < 3; i++)\r
-  {\r
-    if (fColor[i] <= fLowerLimit)\r
-    {\r
-      fColor[0] = fFullBright;\r
-      fColor[1] = fFullBright;\r
-      fColor[2] = fFullBright;\r
-      break;\r
-    }\r
-  }\r
-       qglColor3fv(fColor);\r
-}\r
-\r
-vec_t __VectorNormalize (vec3_t in, vec3_t out)\r
-{\r
-       vec_t   length, ilength;\r
-\r
-       length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);\r
-       if (length == 0)\r
-       {\r
-               VectorClear (out);\r
-               return 0;\r
-       }\r
-\r
-       ilength = 1.0/length;\r
-       out[0] = in[0]*ilength;\r
-       out[1] = in[1]*ilength;\r
-       out[2] = in[2]*ilength;\r
-\r
-       return length;\r
-}\r
-\r
-\r
-void Patch_SetType(patchMesh_t *p, int nType)\r
-{\r
-  p->type = (p->type & PATCH_STYLEMASK) | nType;\r
-}\r
-\r
-void Patch_SetStyle(patchMesh_t *p, int nStyle)\r
-{\r
-  p->type = (p->type & PATCH_TYPEMASK) | nStyle;\r
-}\r
-\r
-/*\r
-==================\r
-Patch_MemorySize\r
-==================\r
-*/\r
-int Patch_MemorySize(patchMesh_t *p)\r
-{\r
-  //   return _msize(p);\r
-  return 0;\r
-}\r
-\r
-\r
-/*\r
-===============\r
-InterpolateInteriorPoints\r
-===============\r
-*/\r
-void InterpolateInteriorPoints( patchMesh_t *p ) \r
-{\r
-       int             i, j, k;\r
-       int             next, prev;\r
-\r
-       for ( i = 0 ; i < p->width ; i += 2 ) \r
-  {\r
-\r
-    next = ( i == p->width - 1 ) ? 1 : ( i + 1 ) % p->width;\r
-    prev = ( i == 0 ) ? p->width - 2 : i - 1;\r
-\r
-#if 0\r
-               if ( i == 0 ) \r
-    {\r
-                       next = ( i + 1 ) % p->width;\r
-                       prev = p->width - 2;                  // joined wrap case\r
-               } \r
-    else if ( i == p->width - 1 ) \r
-    {\r
-                       next = 1;\r
-                       prev = i - 1;\r
-               } \r
-    else \r
-    {\r
-                       next = ( i + 1 ) % p->width;\r
-                       prev = i - 1;\r
-               }\r
-#endif\r
-\r
-               for ( j = 0 ; j < p->height ; j++ ) \r
-    {\r
-                       for ( k = 0 ; k < 3 ; k++ ) \r
-      {\r
-                               p->ctrl[i][j].xyz[k] = ( p->ctrl[next][j].xyz[k] + p->ctrl[prev][j].xyz[k] ) * 0.5;\r
-                       }\r
-               }\r
-       }\r
-}\r
-\r
-/*\r
-=================\r
-MakeMeshNormals\r
-\r
-=================\r
-*/\r
-int    neighbors[8][2] = {\r
-       {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1}\r
-};\r
-\r
-void Patch_MeshNormals(patchMesh_t *in ) \r
-{\r
-       int             i, j, k, dist;\r
-       vec3_t  normal;\r
-       vec3_t  sum;\r
-       int             count;\r
-       vec3_t  base;\r
-       vec3_t  delta;\r
-       int             x, y;\r
-       drawVert_t      *dv;\r
-       vec3_t          around[8], temp;\r
-       qboolean        good[8];\r
-       qboolean        wrapWidth, wrapHeight;\r
-       float           len;\r
-\r
-       wrapWidth = false;\r
-       for ( i = 0 ; i < in->height ; i++ ) \r
-       {\r
-\r
-               VectorSubtract( in->ctrl[0][i].xyz, \r
-                                     in->ctrl[in->width-1][i].xyz, delta );\r
-               len = VectorLength( delta );\r
-               if ( len > 1.0 ) \r
-               {\r
-                       break;\r
-               }\r
-       }\r
-       if ( i == in->height ) \r
-       {\r
-               wrapWidth = true;\r
-       }\r
-\r
-       wrapHeight = false;\r
-       for ( i = 0 ; i < in->width ; i++ ) \r
-       {\r
-               VectorSubtract( in->ctrl[i][0].xyz, \r
-                                     in->ctrl[i][in->height-1].xyz, delta );\r
-               len = VectorLength( delta );\r
-               if ( len > 1.0 ) \r
-               {\r
-                       break;\r
-               }\r
-       }\r
-       if ( i == in->width) \r
-       {\r
-               wrapHeight = true;\r
-       }\r
-\r
-\r
-       for ( i = 0 ; i < in->width ; i++ ) \r
-       {\r
-               for ( j = 0 ; j < in->height ; j++ ) \r
-               {\r
-                       count = 0;\r
-                       //--dv = reinterpret_cast<drawVert_t*>(in.ctrl[j*in.width+i]);\r
-                       dv = &in->ctrl[i][j];\r
-                       VectorCopy( dv->xyz, base );\r
-                       for ( k = 0 ; k < 8 ; k++ ) \r
-                       {\r
-                               VectorClear( around[k] );\r
-                               good[k] = false;\r
-\r
-                               for ( dist = 1 ; dist <= 3 ; dist++ ) \r
-                               {\r
-                                       x = i + neighbors[k][0] * dist;\r
-                                       y = j + neighbors[k][1] * dist;\r
-                                       if ( wrapWidth ) \r
-                                       {\r
-                                               if ( x < 0 ) \r
-                                               {\r
-                                                       x = in->width - 1 + x;\r
-                                               } \r
-                                               else if ( x >= in->width ) \r
-                                               {\r
-                                                       x = 1 + x - in->width;\r
-                                               }\r
-                                       }\r
-                                       if ( wrapHeight ) \r
-                                       {\r
-                                               if ( y < 0 ) \r
-                                               {\r
-                                                       y = in->height - 1 + y;\r
-                                               } \r
-                                               else if ( y >= in->height ) \r
-                                               {\r
-                                                       y = 1 + y - in->height;\r
-                                               }\r
-                                       }\r
-\r
-                                       if ( x < 0 || x >= in->width || y < 0 || y >= in->height ) \r
-                                       {\r
-                                               break;                                  // edge of patch\r
-                                       }\r
-                                       //--VectorSubtract( in.ctrl[y*in.width+x]->xyz, base, temp );\r
-                                       VectorSubtract( in->ctrl[x][y].xyz, base, temp );\r
-                                       if ( __VectorNormalize( temp, temp ) == 0 ) \r
-                                       {\r
-                                               continue;                               // degenerate edge, get more dist\r
-                                       } \r
-                                       else                 \r
-                                       {\r
-                                               good[k] = true;\r
-                                               VectorCopy( temp, around[k] );\r
-                                               break;                                  // good edge\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       VectorClear( sum );\r
-                       for ( k = 0 ; k < 8 ; k++ ) \r
-                       {\r
-                               if ( !good[k] || !good[(k+1)&7] ) \r
-                               {\r
-                                       continue;       // didn't get two points\r
-                               }\r
-                               CrossProduct( around[(k+1)&7], around[k], normal );\r
-                               if ( __VectorNormalize( normal, normal ) == 0 ) \r
-                               {\r
-                                       continue;\r
-                               }\r
-                               VectorAdd( normal, sum, sum );\r
-                               count++;\r
-                       }\r
-                       if ( count == 0 ) \r
-                       {\r
-        //printf("bad normal\n");\r
-                               count = 1;\r
-        //continue;\r
-                       }\r
-                       __VectorNormalize( sum, dv->normal );\r
-               }\r
-       }\r
-}\r
-\r
-\r
-\r
-\r
-/*\r
-==================\r
-Patch_CalcBounds\r
-==================\r
-*/\r
-void Patch_CalcBounds(patchMesh_t *p, vec3_t& vMin, vec3_t& vMax)\r
-{\r
-  vMin[0] = vMin[1] = vMin[2] = 99999;\r
-  vMax[0] = vMax[1] = vMax[2] = -99999;\r
-\r
-  p->bDirty = true;\r
-  for (int w = 0; w < p->width; w++)\r
-  {\r
-    for (int h = 0; h < p->height; h++)\r
-    {\r
-      for (int j = 0; j < 3; j++)\r
-      {\r
-        float f = p->ctrl[w][h].xyz[j];\r
-        if (f < vMin[j])\r
-          vMin[j] = f;\r
-        if (f > vMax[j])\r
-          vMax[j] = f;\r
-      }\r
-    }\r
-  }\r
-}\r
-\r
-/*\r
-==================\r
-Brush_RebuildBrush\r
-==================\r
-*/\r
-void Brush_RebuildBrush(brush_t *b, vec3_t vMins, vec3_t vMaxs)\r
-{\r
-  //\r
-  // Total hack job \r
-  // Rebuilds a brush\r
-       int             i, j;\r
-       face_t  *f, *next;\r
-       vec3_t  pts[4][2];\r
-  texdef_t     texdef;\r
-       // free faces\r
-\r
-  for (j = 0; j < 3; j++)\r
-  {\r
-    if ((int)vMins[j] == (int)vMaxs[j])\r
-    {\r
-      vMins[j] -= 4;\r
-      vMaxs[j] += 4;\r
-    }\r
-  }\r
-\r
-  \r
-  for (f=b->brush_faces ; f ; f=next)\r
-       {\r
-               next = f->next;\r
-    if (f)\r
-      texdef = f->texdef;\r
-    Face_Free( f );\r
-       }\r
-\r
-  b->brush_faces = NULL;\r
-\r
-  // left the last face so we can use its texdef\r
-\r
-       for (i=0 ; i<3 ; i++)\r
-               if (vMaxs[i] < vMins[i])\r
-                       Error ("Brush_RebuildBrush: backwards");\r
-\r
-       pts[0][0][0] = vMins[0];\r
-       pts[0][0][1] = vMins[1];\r
-       \r
-       pts[1][0][0] = vMins[0];\r
-       pts[1][0][1] = vMaxs[1];\r
-       \r
-       pts[2][0][0] = vMaxs[0];\r
-       pts[2][0][1] = vMaxs[1];\r
-       \r
-       pts[3][0][0] = vMaxs[0];\r
-       pts[3][0][1] = vMins[1];\r
-       \r
-       for (i=0 ; i<4 ; i++)\r
-       {\r
-               pts[i][0][2] = vMins[2];\r
-               pts[i][1][0] = pts[i][0][0];\r
-               pts[i][1][1] = pts[i][0][1];\r
-               pts[i][1][2] = vMaxs[2];\r
-       }\r
-\r
-       for (i=0 ; i<4 ; i++)\r
-       {\r
-               f = Face_Alloc();\r
-               f->texdef = texdef;\r
-               f->texdef.flags &= ~SURF_KEEP;\r
-               f->texdef.contents &= ~CONTENTS_KEEP;\r
-//             f->texdef.flags |= SURF_PATCH; \r
-               f->next = b->brush_faces;\r
-               b->brush_faces = f;\r
-               j = (i+1)%4;\r
-\r
-               VectorCopy (pts[j][1], f->planepts[0]);\r
-               VectorCopy (pts[i][1], f->planepts[1]);\r
-               VectorCopy (pts[i][0], f->planepts[2]);\r
-       }\r
-       \r
-       f = Face_Alloc();\r
-       f->texdef = texdef;\r
-  f->texdef.flags &= ~SURF_KEEP;\r
-       f->texdef.contents &= ~CONTENTS_KEEP;\r
-//  f->texdef.flags |= SURF_PATCH; \r
-       f->next = b->brush_faces;\r
-       b->brush_faces = f;\r
-\r
-       VectorCopy (pts[0][1], f->planepts[0]);\r
-       VectorCopy (pts[1][1], f->planepts[1]);\r
-       VectorCopy (pts[2][1], f->planepts[2]);\r
-\r
-       f = Face_Alloc();\r
-       f->texdef = texdef;\r
-  f->texdef.flags &= ~SURF_KEEP;\r
-       f->texdef.contents &= ~CONTENTS_KEEP;\r
-//  f->texdef.flags |= SURF_PATCH; \r
-       f->next = b->brush_faces;\r
-       b->brush_faces = f;\r
-\r
-       VectorCopy (pts[2][0], f->planepts[0]);\r
-       VectorCopy (pts[1][0], f->planepts[1]);\r
-       VectorCopy (pts[0][0], f->planepts[2]);\r
-\r
-  Brush_Build(b);\r
-}\r
-\r
-void WINAPI Patch_Rebuild(patchMesh_t *p)\r
-{\r
-  vec3_t vMin, vMax;\r
-  Patch_CalcBounds(p, vMin, vMax);\r
-  Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-  p->bDirty = true;\r
-}\r
-\r
-/*\r
-==================\r
-AddBrushForPatch\r
-==================\r
- adds a patch brush and ties it to this patch id\r
-*/\r
-brush_t* AddBrushForPatch(patchMesh_t *pm, bool bLinkToWorld )\r
-{\r
-  // find the farthest points in x,y,z\r
-  vec3_t vMin, vMax;\r
-  Patch_CalcBounds(pm, vMin, vMax);\r
-\r
-  for (int j = 0; j < 3; j++)\r
-  {\r
-    if (vMin[j] == vMax[j])\r
-    {\r
-      vMin[j] -= 4;\r
-      vMax[j] += 4;\r
-    }\r
-  }\r
-\r
-  brush_t *b = Brush_Create(vMin, vMax, &g_qeglobals.d_texturewin.texdef);\r
-\r
-  // FIXME: this entire type of linkage needs to be fixed\r
-  b->patchBrush = true;\r
-  b->pPatch = pm;\r
-  pm->pSymbiot = b;\r
-  pm->bSelected = false;\r
-  pm->bOverlay = false;\r
-  pm->bDirty = true;\r
-  pm->nListID = -1;\r
-\r
-  if (bLinkToWorld)\r
-  {\r
-    Brush_AddToList (b, &active_brushes);\r
-         Entity_LinkBrush (world_entity, b);\r
-    Brush_Build(b);\r
-  }\r
-\r
-  return b;\r
-}\r
-\r
-void Patch_SetPointIntensities(int n)\r
-{\r
-#if 0\r
-       patchMesh_t     *p = patchMeshes[n];\r
-  for (int i = 0; i < p->width; i++)\r
-  {\r
-    for (int j = 0; j < p->height; j++)\r
-    {\r
-\r
-    }\r
-  }\r
-#endif\r
-}\r
-\r
-// very approximate widths and heights\r
-\r
-/*\r
-==================\r
-Patch_Width\r
-==================\r
-*/\r
-float Patch_Width(patchMesh_t *p)\r
-{\r
-  float f = 0;\r
-  for (int i = 0; i < p->width-1; i++)\r
-  {\r
-    vec3_t vTemp;\r
-    VectorSubtract(p->ctrl[i][0].xyz, p->ctrl[i+1][0].xyz, vTemp);\r
-    f += VectorLength(vTemp);\r
-  }\r
-  return f;\r
-}\r
-\r
-float Patch_WidthDistanceTo(patchMesh_t *p, int j)\r
-{\r
-  float f = 0;\r
-  for (int i = 0; i < j; i++)\r
-  {\r
-    vec3_t vTemp;\r
-    VectorSubtract(p->ctrl[i][0].xyz, p->ctrl[i+1][0].xyz, vTemp);\r
-    f += VectorLength(vTemp);\r
-  }\r
-  return f;\r
-}\r
-\r
-\r
-\r
-/*\r
-==================\r
-Patch_Height\r
-==================\r
-*/\r
-float Patch_Height(patchMesh_t *p)\r
-{\r
-  float f = 0;\r
-  for (int i = 0; i < p->height-1; i++)\r
-  {\r
-    vec3_t vTemp;\r
-    VectorSubtract(p->ctrl[0][i].xyz, p->ctrl[0][i+1].xyz, vTemp);\r
-    f += VectorLength(vTemp);\r
-  }\r
-  return f;\r
-}\r
-\r
-float Patch_HeightDistanceTo(patchMesh_t *p, int j)\r
-{\r
-  float f = 0;\r
-  for (int i = p->height-1; i > j; i--)\r
-  {\r
-    vec3_t vTemp;\r
-    VectorSubtract(p->ctrl[0][i].xyz, p->ctrl[0][i-1].xyz, vTemp); // reverse order for T coords\r
-    f += VectorLength(vTemp);\r
-  }\r
-  return f;\r
-}\r
-\r
-\r
-\r
-/*\r
-==================\r
-Patch_Naturalize\r
-==================\r
-texture = TotalTexture * LengthToThisControlPoint / TotalControlPointLength\r
-\r
-dist( this control point to first control point ) / dist ( last control pt to first)\r
-*/\r
-void WINAPI Patch_Naturalize(patchMesh_t *p)\r
-{\r
-  int nWidth = (int)(p->d_texture->width * g_pGameDescription->mTextureDefaultScale);\r
-  int nHeight = (int)(p->d_texture->height * g_pGameDescription->mTextureDefaultScale);\r
-  float fPWidth = Patch_Width(p);\r
-  float fPHeight = Patch_Height(p);\r
-  float xAccum = 0.0f;\r
-\r
-  for ( int i = 0; i < p->width ; i++ ) \r
-  {\r
-       float yAccum = 0.0f;\r
-       for ( int j = p->height-1; j >= 0 ; j-- ) \r
-       {\r
-         p->ctrl[i][j].st[0] = (fPWidth / nWidth) * xAccum / fPWidth;\r
-         p->ctrl[i][j].st[1] = (fPHeight / nHeight) * yAccum / fPHeight;\r
-          yAccum = Patch_HeightDistanceTo(p,j-1);\r
-         //p->ctrl[i][j][3] = (fPWidth / nWidth) * (float)i / (p->width - 1);\r
-         //p->ctrl[i][j][4] = (fPHeight/ nHeight) * (float)j / (p->height - 1);\r
-       }\r
-       xAccum = Patch_WidthDistanceTo(p,i+1);\r
-  }\r
-  p->bDirty = true;\r
-}\r
-\r
-/*\r
-  if (bIBevel)\r
-  {\r
-    VectorCopy(p->ctrl[1][0], p->ctrl[1][1]);\r
-  }\r
-\r
-  if (bIEndcap)\r
-  {\r
-    VectorCopy(p->ctrl[3][0], p->ctrl[4][1]);\r
-    VectorCopy(p->ctrl[2][0], p->ctrl[3][1]);\r
-    VectorCopy(p->ctrl[2][0], p->ctrl[2][1]);\r
-    VectorCopy(p->ctrl[2][0], p->ctrl[1][1]);\r
-    VectorCopy(p->ctrl[1][0], p->ctrl[0][1]);\r
-    VectorCopy(p->ctrl[1][0], p->ctrl[0][2]);\r
-    VectorCopy(p->ctrl[1][0], p->ctrl[1][2]);\r
-    VectorCopy(p->ctrl[2][0], p->ctrl[2][2]);\r
-    VectorCopy(p->ctrl[3][0], p->ctrl[3][2]);\r
-    VectorCopy(p->ctrl[3][0], p->ctrl[4][2]);\r
-  }\r
-*/\r
-\r
-int Index3By[][2] =\r
-{\r
-  {0,0},\r
-  {1,0},\r
-  {2,0},\r
-  {2,1},\r
-  {2,2},\r
-  {1,2},\r
-  {0,2},\r
-  {0,1},\r
-  {0,0},\r
-  {0,0},\r
-  {0,0},\r
-  {0,0},\r
-  {0,0},\r
-  {0,0},\r
-  {0,0}\r
-};\r
-\r
-int Index5By[][2] =\r
-{\r
-  {0,0},\r
-  {1,0},\r
-  {2,0},\r
-  {3,0},\r
-  {4,0},\r
-  {4,1},\r
-  {4,2},\r
-  {4,3},\r
-  {4,4},\r
-  {3,4},\r
-  {2,4},\r
-  {1,4},\r
-  {0,4},\r
-  {0,3},\r
-  {0,2},\r
-  {0,1}\r
-};\r
-\r
-\r
-\r
-int Interior3By[][2] =\r
-{\r
-  {1,1}\r
-};\r
-\r
-int Interior5By[][2] =\r
-{\r
-  {1,1},\r
-  {2,1},\r
-  {3,1},\r
-  {1,2},\r
-  {2,2},\r
-  {3,2},\r
-  {1,3},\r
-  {2,3},\r
-  {3,3}\r
-};\r
-\r
-int Interior3ByCount = sizeof(Interior3By) / sizeof(int[2]);\r
-int Interior5ByCount = sizeof(Interior5By) / sizeof(int[2]);\r
-\r
-extern int Plane_FromPoints(vec3_t p1, vec3_t p2, vec3_t p3, plane_t *plane);\r
-// the bFaceCycle only means we are going through a patch cycling loop\r
-// then we rely on g_vCycleCapNormal to compute the cap\r
-\r
-void Patch_CapTexture(patchMesh_t *p, bool bFaceCycle = false)\r
-{\r
-       vec3_t vProjection, vX, vY;\r
-       qtexture_t *texture = p->pShader->getTexture();\r
-       plane_t Plane1, Plane2, Plane3;\r
-       bool bThing=true;\r
-\r
-       if (bFaceCycle)\r
-               VectorCopy (g_vCycleCapNormal, vProjection);\r
-\r
-       else\r
-       {\r
-               VectorClear ( vProjection );\r
-\r
-               // find normal for plane from first 3 corner points\r
-               if (!Plane_FromPoints(p->ctrl[0][0].xyz,p->ctrl[0][p->height-1].xyz,p->ctrl[p->width-1][p->height-1].xyz,&Plane1))\r
-               {\r
-                       VectorClear ( Plane3.normal );\r
-                       bThing = false;\r
-               }\r
-               \r
-               // find normal for plane from next 3 corner points\r
-               if (!Plane_FromPoints(p->ctrl[p->width-1][p->height-1].xyz,p->ctrl[p->width-1][0].xyz,p->ctrl[0][0].xyz,&Plane2))\r
-               {\r
-                       if (bThing)\r
-                       {       \r
-                               VectorCopy ( Plane1.normal, Plane3.normal );\r
-                               Plane3.dist = Plane1.dist;\r
-                       }\r
-               }\r
-\r
-               else\r
-               {\r
-                       if (bThing)\r
-                               // find average plane for all 4 corner points\r
-                       {\r
-                               for (int n = 0; n <= 2; n++)\r
-                               {\r
-                                       Plane3.normal[n] = (Plane1.normal[n] + Plane2.normal[n]) / 2;\r
-                               }\r
-                               Plane3.dist = (Plane1.dist + Plane2.dist) / 2;\r
-                       }\r
-                       else\r
-                       {\r
-                               VectorCopy ( Plane2.normal, Plane3.normal );\r
-                               Plane3.dist = Plane2.dist;\r
-                       }\r
-               }\r
-\r
-               // get best axis for projection from average plane\r
-               //Sys_Printf("surface normal1: (%f,%f,%f)\n",Plane1.normal[0],Plane1.normal[1],Plane1.normal[0]);\r
-               //Sys_Printf("surface normal2: (%f,%f,%f)\n",Plane2.normal[0],Plane2.normal[1],Plane2.normal[0]);\r
-               //Sys_Printf("surface normal3: (%f,%f,%f)\n",Plane3.normal[0],Plane3.normal[1],Plane3.normal[0]);\r
-               TextureAxisFromPlane(&Plane3, vX, vY);\r
-       }\r
-\r
-       for (int w = 0; w < p->width; w++)\r
-       {\r
-               for (int h = 0; h < p->height; h++)\r
-               {\r
-                       if (vProjection[2] == 1.0f || (vX[0] == 1.0f && vY[1] == -1.0f))\r
-                       {\r
-                               p->ctrl[w][h].st[0] = p->ctrl[w][h].xyz[0] / (texture->width * g_pGameDescription->mTextureDefaultScale);\r
-                               p->ctrl[w][h].st[1] = p->ctrl[w][h].xyz[1] / (texture->height * g_pGameDescription->mTextureDefaultScale) * -1;\r
-                       }\r
-                       else if (vProjection[0] == 1.0f || (vX[1] == 1.0f && vY[2] == -1.0f))\r
-                       {\r
-                               p->ctrl[w][h].st[0] = p->ctrl[w][h].xyz[1] / (texture->width * g_pGameDescription->mTextureDefaultScale);\r
-                               p->ctrl[w][h].st[1] = p->ctrl[w][h].xyz[2] / (texture->height * g_pGameDescription->mTextureDefaultScale) * -1;\r
-                       }\r
-                       else if (vProjection[1] == 1.0f || (vX[0] == 1.0f && vY[2] == -1.0f))\r
-                       {\r
-                               p->ctrl[w][h].st[0] = p->ctrl[w][h].xyz[0] / (texture->width * g_pGameDescription->mTextureDefaultScale);\r
-                               p->ctrl[w][h].st[1] = p->ctrl[w][h].xyz[2] / (texture->height * g_pGameDescription->mTextureDefaultScale) * -1;\r
-                       }\r
-                       //Sys_Printf("(%i,%i) (%f,%f,%f) (%f,%f) %f\n",w,h,\r
-                       //      p->ctrl[w][h].xyz[0],p->ctrl[w][h].xyz[1],p->ctrl[w][h].xyz[2],\r
-                       //      p->ctrl[w][h].st[0],p->ctrl[w][h].st[1],p->ctrl[w][h].normal);\r
-               }\r
-       }\r
-       // make sure it will rebuild\r
-       p->bDirty = true;\r
-}\r
-\r
-void FillPatch(patchMesh_t *p, vec3_t v)\r
-{\r
-  for (int i = 0; i < p->width; i++)\r
-  {\r
-    for (int j = 0; j < p->height; j++)\r
-    {\r
-      VectorCopy(v, p->ctrl[i][j].xyz);\r
-    }\r
-  }\r
-}\r
-\r
-// temporarily moved function to allow use in Cap() and CapSpecial()\r
-void patchInvert(patchMesh_t *p)\r
-{\r
-  drawVert_t vertTemp;\r
-  p->bDirty = true;\r
-       for ( int i = 0 ; i < p->width ; i++ ) \r
-  {\r
-    for (int j = 0; j < p->height / 2; j++)\r
-    {\r
-      memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));\r
-      memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));\r
-      memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));\r
-               }\r
-       }\r
-}\r
-\r
-brush_t* Cap(patchMesh_t *pParent, bool bByColumn, bool bFirst)\r
-{\r
-  brush_t *b;\r
-  patchMesh_t *p;\r
-  vec3_t vMin, vMax;\r
-  int i, j;\r
-\r
-  bool bSmall = true;\r
-  // make a generic patch\r
-  if (pParent->width <= 9)\r
-  {\r
-    b = Patch_GenericMesh(3, 3, 2, false);\r
-  }\r
-  else\r
-  {\r
-    b = Patch_GenericMesh(5, 5, 2, false);\r
-    bSmall = false;\r
-  }\r
-\r
-  if (!b)\r
-  {\r
-    Sys_Printf("Unable to cap. You may need to ungroup the patch.\n");\r
-    return NULL;\r
-  }\r
-\r
-  p = b->pPatch;\r
-  p->type |= PATCH_CAP;\r
-\r
-  vMin[0] = vMin[1] = vMin[2] = 9999;\r
-  vMax[0] = vMax[1] = vMax[2] = -9999;\r
-\r
-  // we seam the column edge, FIXME: this might need to be able to seem either edge\r
-  // \r
-  int nSize = (bByColumn) ? pParent->width : pParent->height;\r
-  int nIndex = (bFirst) ? 0 : (bByColumn) ? pParent->height-1 : pParent->width-1;\r
-\r
-  FillPatch(p, pParent->ctrl[0][nIndex].xyz);\r
-\r
-  for (i = 0; i < nSize; i++)\r
-  {\r
-    if (bByColumn)\r
-    {\r
-      if (bSmall)\r
-      {\r
-        VectorCopy(pParent->ctrl[i][nIndex].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);\r
-      }\r
-      else\r
-      {\r
-        VectorCopy(pParent->ctrl[i][nIndex].xyz, p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz);\r
-      }\r
-    }\r
-    else\r
-    {\r
-      if (bSmall)\r
-      {\r
-        VectorCopy(pParent->ctrl[nIndex][i].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);\r
-      }\r
-      else\r
-      {\r
-        VectorCopy(pParent->ctrl[nIndex][i].xyz, p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz);\r
-      }\r
-    }\r
-  \r
-    for (j = 0; j < 3; j++)\r
-    {\r
-      float f = (bSmall) ? p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz[j] : p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz[j];\r
-      if (f < vMin[j])\r
-        vMin[j] = f;\r
-      if (f > vMax[j])\r
-        vMax[j] = f;\r
-    }\r
-  }\r
-\r
-  vec3_t vTemp;\r
-  for (j = 0; j < 3; j++)\r
-  {\r
-    vTemp[j] = vMin[j] + fabs((vMax[j] - vMin[j]) * 0.5);\r
-  }\r
-  int nCount = (bSmall) ? Interior3ByCount : Interior5ByCount;\r
-  for (j = 0; j < nCount; j++)\r
-  {\r
-    if (bSmall)\r
-    {\r
-      VectorCopy(vTemp, p->ctrl[Interior3By[j][0]][Interior3By[j][1]].xyz);\r
-    }\r
-    else\r
-    {\r
-      VectorCopy(vTemp, p->ctrl[Interior5By[j][0]][Interior5By[j][1]].xyz);\r
-    }\r
-  }\r
-\r
-  if (bFirst)\r
-         patchInvert(p);\r
-  /*\r
-  {\r
-    drawVert_t vertTemp;\r
-    for (i = 0; i < p->width; i++)\r
-    {\r
-      for (j = 0; j < p->height / 2; j++)\r
-      {\r
-        memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));\r
-        memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));\r
-        memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));\r
-      }\r
-    }\r
-  }\r
-  */\r
-\r
-  Patch_Rebuild(p);\r
-  Patch_CapTexture(p);\r
-  return p->pSymbiot;\r
-}\r
-\r
-brush_t* CapSpecial(patchMesh_t *pParent, int nType, bool bFirst)\r
-{\r
-\r
-  brush_t *b;\r
-  patchMesh_t *p;\r
-  vec3_t vMin, vMax, vTemp;\r
-  int i, j;\r
-\r
-  if (nType == IENDCAP)\r
-    b = Patch_GenericMesh(5, 3, 2, false);\r
-  else\r
-    b = Patch_GenericMesh(3, 3, 2, false);\r
-\r
-  if (!b)\r
-  {\r
-    Sys_Printf("Unable to cap. Make sure you ungroup before re-capping.");\r
-    return NULL;\r
-  }\r
-\r
-  p = b->pPatch;\r
-  p->type |= PATCH_CAP;\r
-\r
-  vMin[0] = vMin[1] = vMin[2] = 9999;\r
-  vMax[0] = vMax[1] = vMax[2] = -9999;\r
-\r
-  //  int nSize = pParent->width;\r
-  int nIndex = (bFirst) ? 0 : pParent->height-1;\r
-\r
-  // parent bounds are used for some things\r
-  Patch_CalcBounds(pParent, vMin, vMax);\r
-\r
-  for (j = 0; j < 3; j++)\r
-  {\r
-    vTemp[j] = vMin[j] + fabs((vMax[j] - vMin[j]) * 0.5);\r
-  }\r
-  \r
-  if (nType == IBEVEL)\r
-  {\r
-    VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[0][2].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][2].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][0].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][1].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][2].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][0].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][1].xyz);\r
-  }\r
-  else if (nType == BEVEL)\r
-  {\r
-    vec3_t p1, p2, p3, p4; //, temp, dir;\r
-\r
-    VectorCopy(pParent->ctrl[0][nIndex].xyz, p3);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p1);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p2);\r
-       \r
-       //Sys_Printf("CapSpecial() p1: %f %f %f\n",p1[0],p1[1],p1[2]);\r
-       //Sys_Printf("CapSpecial() p2: %f %f %f\n",p2[0],p2[1],p2[2]);\r
-       //Sys_Printf("CapSpecial() p3: %f %f %f\n",p3[0],p3[1],p3[2]);\r
-       \r
-       VectorSubtract(p2, p1, p4);\r
-       VectorAdd(p3, p4, p4);\r
-       // spog - use opposite-point-on-parallelogram to find p4\r
-       /*\r
-    VectorSubtract(p3, p2, dir);\r
-    VectorNormalize(dir);\r
-    VectorSubtract(p1, p2, temp);\r
-    vec_t dist = _DotProduct(temp, dir);\r
-    VectorScale(dir, dist, temp);\r
-    VectorAdd(p2, temp, temp);\r
-    VectorSubtract(temp, p1, temp);\r
-    VectorScale(temp, 2, temp);\r
-    VectorAdd(p1, temp, p4);\r
-       */\r
-\r
-       //Sys_Printf("CapSpecial() p1: %f %f %f\n",p1[0],p1[1],p1[2]);\r
-       //Sys_Printf("CapSpecial() p2: %f %f %f\n",p2[0],p2[1],p2[2]);\r
-       //Sys_Printf("CapSpecial() p3: %f %f %f\n",p3[0],p3[1],p3[2]);\r
-       //Sys_Printf("CapSpecial() p4: %f %f %f\n",p4[0],p4[1],p4[2]);\r
-\r
-    VectorCopy(p4, p->ctrl[0][0].xyz);\r
-    VectorCopy(p4, p->ctrl[1][0].xyz);\r
-    VectorCopy(p4, p->ctrl[0][1].xyz);\r
-    VectorCopy(p4, p->ctrl[1][1].xyz);\r
-    VectorCopy(p4, p->ctrl[0][2].xyz);\r
-    VectorCopy(p4, p->ctrl[1][2].xyz);\r
-    VectorCopy(p2, p->ctrl[2][0].xyz);\r
-    VectorCopy(p1, p->ctrl[2][1].xyz);\r
-    VectorCopy(p3, p->ctrl[2][2].xyz);\r
-\r
-  }\r
-  else if (nType == ENDCAP)\r
-  {\r
-    VectorAdd(pParent->ctrl[4][nIndex].xyz, pParent->ctrl[0][nIndex].xyz, vTemp);\r
-    VectorScale(vTemp, 0.5, vTemp);\r
-    VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);\r
-                                                  VectorCopy(vTemp, p->ctrl[1][0].xyz);\r
-    VectorCopy(pParent->ctrl[4][nIndex].xyz, p->ctrl[2][0].xyz);\r
-\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[0][2].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[1][2].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][2].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[1][1].xyz);\r
-    \r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);\r
-    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[2][1].xyz);\r
-  }\r
-  else\r
-  {\r
-    VectorCopy(pParent->ctrl[4][nIndex].xyz, p->ctrl[0][0].xyz);\r
-    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[1][0].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][0].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[3][0].xyz);\r
-    VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[4][0].xyz);\r
-    \r
-    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[0][1].xyz);\r
-    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[1][1].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][1].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[3][1].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[4][1].xyz);\r
-\r
-    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[0][2].xyz);\r
-    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[1][2].xyz);\r
-    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][2].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[3][2].xyz);\r
-    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[4][2].xyz);\r
-  }\r
-\r
-\r
-  if (!bFirst)\r
-  {\r
-    drawVert_t vertTemp;\r
-    for (i = 0; i < p->width; i++)\r
-    {\r
-      for (j = 0; j < p->height / 2; j++)\r
-      {\r
-        memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));\r
-        memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));\r
-        memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));\r
-      }\r
-    }\r
-  }\r
-\r
-  //--Patch_CalcBounds(p, vMin, vMax);\r
-  //--Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-  Patch_Rebuild(p);\r
-  Patch_CapTexture(p);\r
-  return p->pSymbiot;\r
-}\r
-\r
-void Patch_CapCurrent()\r
-{\r
-  patchMesh_t *pParent = NULL;\r
-  brush_t *b[4];\r
-  brush_t *pCap = NULL;\r
-  b[0] = b[1] = b[2] = b[3] = NULL;\r
-  int nIndex = 0;\r
-  bool b_GroupResult = TRUE;\r
-  \r
-  if (!QE_SingleBrush(true))\r
-  {\r
-    Sys_Printf("Patch_CapCurrent: you must have a single patch selected\n");\r
-    return;\r
-  }\r
-  \r
-  \r
-  for (brush_t *pb = selected_brushes.next ; pb != NULL && pb != &selected_brushes ; pb = pb->next)\r
-  {\r
-    if (pb->patchBrush)\r
-    {\r
-      pParent = pb->pPatch;\r
-      // decide which if any ends we are going to cap\r
-      // if any of these compares hit, it is a closed patch and as such\r
-      // the generic capping will work.. if we do not find a closed edge \r
-      // then we need to ask which kind of cap to add\r
-      if (VectorCompare(pParent->ctrl[0][0].xyz, pParent->ctrl[pParent->width-1][0].xyz))\r
-      {\r
-        pCap = Cap(pParent, true, false);\r
-        if (pCap != NULL)\r
-        {\r
-          b[nIndex++] = pCap;\r
-        }\r
-      }\r
-      if (VectorCompare(pParent->ctrl[0][pParent->height-1].xyz, pParent->ctrl[pParent->width-1][pParent->height-1].xyz))\r
-      {\r
-        pCap = Cap(pParent, true, true);\r
-        if (pCap != NULL)\r
-        {\r
-          b[nIndex++] = pCap;\r
-        }\r
-      }\r
-      if (VectorCompare(pParent->ctrl[0][0].xyz, pParent->ctrl[0][pParent->height-1].xyz))\r
-      {\r
-        pCap = Cap(pParent, false, false);\r
-        if (pCap != NULL)\r
-        {\r
-          b[nIndex++] = pCap;\r
-        }\r
-      }\r
-      if (VectorCompare(pParent->ctrl[pParent->width-1][0].xyz, pParent->ctrl[pParent->width-1][pParent->height-1].xyz))\r
-      {\r
-        pCap = Cap(pParent, false, true);\r
-        if (pCap != NULL)\r
-        {\r
-          b[nIndex++] = pCap;\r
-        }\r
-      }\r
-    }\r
-  }\r
-  \r
-  if (pParent)\r
-  {\r
-    // if we did not cap anything with the above tests\r
-    if (nIndex == 0)\r
-    {\r
-      int type;\r
-      \r
-      if (DoCapDlg (&type, &b_GroupResult) == IDOK)\r
-      {\r
-        b[nIndex++] = CapSpecial(pParent, type, false);\r
-        b[nIndex++] = CapSpecial(pParent, type, true);\r
-      }\r
-    }\r
-    \r
-    if (nIndex > 0)\r
-    {\r
-      while (nIndex > 0)\r
-      {\r
-        nIndex--;\r
-        if (b[nIndex])\r
-        {\r
-          Select_Brush(b[nIndex]);\r
-        }\r
-      }\r
-      // Gef: Added toggle for capped patch func_group\r
-      if(b_GroupResult) {\r
-        entity_t *e = Entity_Alloc();\r
-        SetKeyValue(e, "classname", "func_group");\r
-        SetKeyValue(e, "type", "patchCapped");\r
-        Select_GroupEntity(e);\r
-        Entity_AddToList(e, &entities);\r
-      }\r
-    }\r
-  }\r
-}\r
-\r
-/*\r
-===============\r
-BrushToPatchMesh\r
-===============\r
-*/\r
-void Patch_BrushToMesh(bool bCone, bool bBevel, bool bEndcap, bool bSquare, int nHeight)\r
-{\r
-       brush_t         *b;\r
-       patchMesh_t     *p;\r
-       int                     i,j;\r
-\r
-       if (!QE_SingleBrush())\r
-               return;\r
-\r
-       b = selected_brushes.next;\r
-\r
-       p = MakeNewPatch();\r
-\r
-       p->d_texture = b->brush_faces->d_texture;\r
-       p->pShader = b->brush_faces->pShader;\r
-\r
-  p->height = nHeight;\r
-\r
-  p->type = PATCH_CYLINDER;\r
-  if (bBevel & !bSquare)\r
-  {\r
-    p->type = PATCH_BEVEL;\r
-    p->width = 3;\r
-    int nStep = (int)((b->maxs[2] - b->mins[2]) / (p->height-1));\r
-    int nStart = (int)(b->mins[2]);\r
-    for (i = 0; i < p->height; i++)\r
-    {\r
-           p->ctrl[0][i].xyz[0] =  b->mins[0];\r
-           p->ctrl[0][i].xyz[1] =  b->mins[1];\r
-      p->ctrl[0][i].xyz[2] = nStart;\r
-\r
-           p->ctrl[1][i].xyz[0] =  b->maxs[0];\r
-           p->ctrl[1][i].xyz[1] =  b->mins[1];\r
-      p->ctrl[1][i].xyz[2] = nStart;\r
-\r
-           p->ctrl[2][i].xyz[0] =  b->maxs[0];\r
-           p->ctrl[2][i].xyz[1] =  b->maxs[1];\r
-      p->ctrl[2][i].xyz[2] = nStart;\r
-      nStart += nStep;\r
-    }\r
-  }\r
-  else if (bEndcap & !bSquare)\r
-  {\r
-    p->type = PATCH_ENDCAP;\r
-    p->width = 5;\r
-    int nStep = (int)((b->maxs[2] - b->mins[2]) / (p->height-1));\r
-    int nStart = (int)(b->mins[2]);\r
-    for (i = 0; i < p->height; i++)\r
-    {\r
-      p->ctrl[0][i].xyz[0] =  b->mins[0];\r
-      p->ctrl[0][i].xyz[1] =  b->mins[1];\r
-      p->ctrl[0][i].xyz[2] = nStart;\r
-\r
-      p->ctrl[1][i].xyz[0] =  b->mins[0];\r
-      p->ctrl[1][i].xyz[1] =  b->maxs[1];\r
-      p->ctrl[1][i].xyz[2] = nStart;\r
-\r
-      p->ctrl[2][i].xyz[0] =  b->mins[0] + ((b->maxs[0] - b->mins[0]) * 0.5);\r
-      p->ctrl[2][i].xyz[1] =  b->maxs[1];\r
-      p->ctrl[2][i].xyz[2] = nStart;\r
-          \r
-      p->ctrl[3][i].xyz[0] =  b->maxs[0];\r
-      p->ctrl[3][i].xyz[1] =  b->maxs[1];\r
-      p->ctrl[3][i].xyz[2] = nStart;\r
-\r
-      p->ctrl[4][i].xyz[0] =  b->maxs[0];\r
-      p->ctrl[4][i].xyz[1] =  b->mins[1];\r
-      p->ctrl[4][i].xyz[2] = nStart;\r
-      nStart += nStep;\r
-    }\r
-  }\r
-  else\r
-  {\r
-    p->width = 9;\r
-    p->ctrl[1][0].xyz[0] =  b->mins[0];\r
-    p->ctrl[1][0].xyz[1] =  b->mins[1];\r
-\r
-    p->ctrl[3][0].xyz[0] =  b->maxs[0];\r
-    p->ctrl[3][0].xyz[1] =  b->mins[1];\r
-\r
-    p->ctrl[5][0].xyz[0] =  b->maxs[0];\r
-    p->ctrl[5][0].xyz[1] =  b->maxs[1];\r
-\r
-    p->ctrl[7][0].xyz[0] =  b->mins[0];\r
-    p->ctrl[7][0].xyz[1] =  b->maxs[1];\r
-\r
-    for ( i = 1 ; i < p->width - 1 ; i += 2 ) \r
-    {\r
-\r
-      p->ctrl[i][0].xyz[2] =  b->mins[2];\r
-\r
-                 VectorCopy( p->ctrl[i][0].xyz, p->ctrl[i][2].xyz );\r
-\r
-                 p->ctrl[i][2].xyz[2] =  b->maxs[2];\r
-\r
-                 p->ctrl[i][1].xyz[0] = ( p->ctrl[i][0].xyz[0] + p->ctrl[i][2].xyz[0] ) * 0.5;\r
-                 p->ctrl[i][1].xyz[1] = ( p->ctrl[i][0].xyz[1] + p->ctrl[i][2].xyz[1] ) * 0.5;\r
-                 p->ctrl[i][1].xyz[2] = ( p->ctrl[i][0].xyz[2] + p->ctrl[i][2].xyz[2] ) * 0.5;\r
-         }\r
-         InterpolateInteriorPoints( p );\r
-\r
-    if (bSquare)\r
-    {\r
-      if (bBevel || bEndcap)\r
-      {\r
-        if (bBevel)\r
-        {\r
-          for (i = 0; i < p->height; i++)\r
-          {\r
-            VectorCopy(p->ctrl[1][i].xyz, p->ctrl[2][i].xyz);\r
-            VectorCopy(p->ctrl[7][i].xyz, p->ctrl[6][i].xyz);\r
-          }\r
-        }\r
-        else\r
-        {\r
-          for (i = 0; i < p->height; i++)\r
-          {\r
-            VectorCopy(p->ctrl[5][i].xyz, p->ctrl[4][i].xyz);\r
-            VectorCopy(p->ctrl[1][i].xyz, p->ctrl[2][i].xyz);\r
-            VectorCopy(p->ctrl[7][i].xyz, p->ctrl[6][i].xyz);\r
-            VectorCopy(p->ctrl[8][i].xyz, p->ctrl[7][i].xyz);\r
-          }\r
-        }\r
-      }\r
-      else\r
-      {\r
-        for (i = 0; i < p->width-1; i ++)\r
-        {\r
-          for (j = 0; j < p->height; j++)\r
-          {\r
-            VectorCopy(p->ctrl[i+1][j].xyz, p->ctrl[i][j].xyz);\r
-          }\r
-        }\r
-        for (j = 0; j < p->height; j++)\r
-        {\r
-          VectorCopy(p->ctrl[0][j].xyz, p->ctrl[8][j].xyz);\r
-        }\r
-      }\r
-    }\r
-  }\r
-\r
-\r
-  Patch_Naturalize(p);\r
-\r
-  if (bCone)\r
-  {\r
-    p->type = PATCH_CONE;\r
-    float xc = (b->maxs[0] + b->mins[0]) * 0.5; \r
-    float yc = (b->maxs[1] + b->mins[1]) * 0.5; \r
-\r
-    for ( i = 0 ; i < p->width ; i ++)\r
-    {\r
-      p->ctrl[i][2].xyz[0] = xc;\r
-      p->ctrl[i][2].xyz[1] = yc;\r
-    }\r
-  }\r
-  \r
-  b = AddBrushForPatch(p);\r
-\r
-  Select_Delete();\r
-  Select_Brush(b);\r
-\r
-}\r
-\r
-/*\r
-==================\r
-Patch_GenericMesh\r
-==================\r
-*/\r
-brush_t* Patch_GenericMesh(int nWidth, int nHeight, int nOrientation, bool bDeleteSource, bool bOverride)\r
-{\r
-  int i,j;\r
-\r
-  if (nHeight < 3 || nHeight > 15 || nWidth < 3 || nWidth > 15)\r
-  {\r
-    Sys_Printf("Invalid patch width or height.\n");\r
-    return NULL;\r
-  }\r
-\r
-       if (! bOverride && !QE_SingleBrush())\r
-  {\r
-    Sys_Printf("Error: you must have a single brush selected\n");\r
-               return NULL;\r
-  }\r
-\r
-  patchMesh_t* p = MakeNewPatch();\r
-  p->pShader = g_qeglobals.d_texturewin.pShader;\r
-  p->d_texture = g_qeglobals.d_texturewin.pShader->getTexture();\r
-\r
-       p->width = nWidth;\r
-       p->height = nHeight;\r
-  p->type = PATCH_GENERIC;\r
-\r
-  int nFirst = 0;\r
-  int nSecond = 1;\r
-  if (nOrientation == 0)\r
-  {\r
-    nFirst = 1;\r
-    nSecond = 2;\r
-  }\r
-  else if (nOrientation == 1)\r
-  {\r
-    nSecond = 2;\r
-  }\r
-\r
-       brush_t *b = selected_brushes.next;\r
-       // set the workzone to this brush, use it later to create the patch points\r
-       UpdateWorkzone_ForBrush( b );\r
-\r
-  int xStep = (int)(b->mins[nFirst]);\r
-  float xAdj = fabs((b->maxs[nFirst] - b->mins[nFirst]) / (nWidth - 1));\r
-  float yAdj = fabs((b->maxs[nSecond] - b->mins[nSecond]) / (nHeight - 1));\r
-\r
-  for (i = 0; i < nWidth; i++)\r
-  {\r
-    int yStep = (int)(b->mins[nSecond]);\r
-    for (j = 0; j < nHeight; j++)\r
-    {\r
-      p->ctrl[i][j].xyz[nFirst] = xStep;\r
-      p->ctrl[i][j].xyz[nSecond] = yStep;\r
-      // create patch based on workzone\r
-      p->ctrl[i][j].xyz[nOrientation] = g_qeglobals.d_work_max[nOrientation];\r
-      yStep += (int)yAdj;\r
-    }\r
-    xStep += (int)xAdj;\r
-  }\r
-\r
-  Patch_Naturalize(p);\r
-\r
-  b = AddBrushForPatch(p);\r
-  if (bDeleteSource)\r
-  {\r
-    Select_Delete();\r
-    Select_Brush(b);\r
-  }\r
-\r
-  return b;\r
-  //g_qeglobals.d_select_mode = sel_curvepoint;\r
-}\r
-\r
-/*\r
-==================\r
-PointInMoveList\r
-==================\r
-*/\r
-int PointInMoveList(float *pf)\r
-{\r
-  for (int i = 0; i < g_qeglobals.d_num_move_points; i++)\r
-  {\r
-    if (pf == &g_qeglobals.d_move_points[i][0])\r
-      return i;\r
-  }\r
-  return -1;\r
-}\r
-\r
-/*\r
-==================\r
-PointValueInMoveList\r
-==================\r
-*/\r
-int PointValueInMoveList(vec3_t v)\r
-{\r
-  for (int i = 0; i < g_qeglobals.d_num_move_points; i++)\r
-  {\r
-    if (VectorCompare(v, g_qeglobals.d_move_points[i]))\r
-      return i;\r
-  }\r
-  return -1;\r
-}\r
-\r
-\r
-/*\r
-==================\r
-RemovePointFromMoveList\r
-==================\r
-*/\r
-void RemovePointFromMoveList(vec3_t v)\r
-{\r
-  int n;\r
-  while ( (n = PointValueInMoveList(v)) >= 0)\r
-  {\r
-    for (int i = n; i < g_qeglobals.d_num_move_points-1; i++)\r
-    {\r
-      g_qeglobals.d_move_points[i] = g_qeglobals.d_move_points[i+1];\r
-    }\r
-    g_qeglobals.d_num_move_points--;\r
-  }\r
-}\r
-\r
-/*\r
-==================\r
-ColumnSelected\r
-==================\r
-*/\r
-bool ColumnSelected(patchMesh_t* p, int nCol)\r
-{\r
-  for (int i = 0; i < p->height; i++)\r
-  {\r
-    if (PointInMoveList(p->ctrl[nCol][i].xyz) == -1)\r
-      return false;\r
-  }\r
-  return true;\r
-}\r
-\r
-/*\r
-==================\r
-AddPoint\r
-==================\r
-*/\r
-void AddPoint(patchMesh_t* p, vec3_t v, bool bWeldOrDrill = true)\r
-{\r
-  int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;\r
-  int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;\r
-  g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = v;\r
-  if ((g_bPatchWeld || g_bPatchDrillDown) && bWeldOrDrill)\r
-  {\r
-         for ( int i = 0 ; i < p->width ; i++ ) \r
-    {\r
-                 for ( int j = 0 ; j < p->height ; j++ ) \r
-      {\r
-        if (g_bPatchWeld)\r
-        {\r
-          if ( VectorCompare(v, p->ctrl[i][j].xyz)\r
-            && PointInMoveList(p->ctrl[i][j].xyz) == -1)\r
-          {\r
-            g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;\r
-            continue;\r
-          }\r
-        }\r
-        if (g_bPatchDrillDown && g_nPatchClickedView != W_CAMERA)\r
-        {\r
-          if ( (fabs(v[nDim1] - p->ctrl[i][j].xyz[nDim1]) <= EQUAL_EPSILON) \r
-             &&(fabs(v[nDim2] - p->ctrl[i][j].xyz[nDim2]) <= EQUAL_EPSILON)) \r
-          {\r
-            if (PointInMoveList(p->ctrl[i][j].xyz) == -1)\r
-            {\r
-              g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;\r
-              continue;\r
-            }\r
-          }\r
-        }\r
-      }\r
-    }\r
-  }\r
-}\r
-\r
-/*\r
-==================\r
-SelectRow\r
-==================\r
-*/\r
-void SelectRow(patchMesh_t* p, int nRow, bool bMulti)\r
-{\r
-  if (!bMulti)\r
-    g_qeglobals.d_num_move_points = 0;\r
-  for (int i = 0; i < p->width; i++)\r
-  {\r
-    AddPoint(p, p->ctrl[i][nRow].xyz, false);\r
-  }\r
-  //Sys_Printf("Selected Row %d\n", nRow);\r
-}\r
-\r
-/*\r
-==================\r
-SelectColumn\r
-==================\r
-*/\r
-void SelectColumn(patchMesh_t* p, int nCol, bool bMulti)\r
-{\r
-  if (!bMulti)\r
-    g_qeglobals.d_num_move_points = 0;\r
-  for (int i = 0; i < p->height; i++)\r
-  {\r
-    AddPoint(p, p->ctrl[nCol][i].xyz, false);\r
-  }\r
-  //Sys_Printf("Selected Col %d\n", nCol);\r
-}\r
-\r
-\r
-/*\r
-==================\r
-AddPatchMovePoint\r
-==================\r
-*/\r
-void AddPatchMovePoint(vec3_t v, bool bMulti, bool bFull)\r
-{\r
-  if (!g_bSameView && !bMulti && !bFull)\r
-  {\r
-    g_bSameView = true;\r
-    //return; // was causing odd behaviour on patch vertex selection\r
-  }\r
-\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-           patchMesh_t* p = pb->pPatch;\r
-           for ( int i = 0 ; i < p->width ; i++ ) \r
-      {\r
-                   for ( int j = 0 ; j < p->height ; j++ ) \r
-        {\r
-          if (VectorCompare(v, p->ctrl[i][j].xyz))\r
-          {\r
-            if (PointInMoveList(p->ctrl[i][j].xyz) == -1)\r
-            {\r
-              if (bFull)        // if we want the full row/col this is on\r
-              {\r
-                SelectColumn(p, i, bMulti);\r
-              }\r
-              else\r
-              {\r
-                if (!bMulti)\r
-                  g_qeglobals.d_num_move_points = 0;\r
-                AddPoint(p, p->ctrl[i][j].xyz);\r
-                //Sys_Printf("Selected col:row %d:%d\n", i, j);\r
-              }\r
-              //--if (!bMulti)\r
-              return;\r
-            }\r
-            else\r
-            {\r
-              if (bFull)\r
-              {\r
-                if (ColumnSelected(p, i))\r
-                {\r
-                  SelectRow(p, j, bMulti);\r
-                }\r
-                else\r
-                {\r
-                  SelectColumn(p, i, bMulti);\r
-                }\r
-                return;\r
-              }\r
-                         //if (!bMulti)\r
-                         //{\r
-              //    g_qeglobals.d_num_move_points = 0;\r
-              //    AddPoint(p, p->ctrl[i][j].xyz);\r
-                         //}\r
-              if (bMulti)// if (g_bSameView) // this is not having desired effect\r
-              {\r
-                RemovePointFromMoveList(v);\r
-                return;\r
-              }\r
-            }\r
-          }\r
-                   }\r
-           }\r
-    }\r
-  }\r
-}\r
-\r
-/*\r
-==================\r
-Patch_UpdateSelected\r
-==================\r
-*/\r
-void Patch_UpdateSelected(vec3_t vMove)\r
-{\r
-       int i;//, j;\r
-       for (i=0 ; i < g_qeglobals.d_num_move_points ; i++)\r
-       {\r
-               VectorAdd (g_qeglobals.d_move_points[i], vMove, g_qeglobals.d_move_points[i]);\r
-               if (g_qeglobals.d_num_move_points == 1)\r
-               {\r
-               }\r
-       }\r
-       \r
-       //--patchMesh_t* p = &patchMeshes[g_nSelectedPatch];\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-               if (pb->patchBrush)\r
-               {\r
-                       patchMesh_t* p = pb->pPatch;\r
-                       \r
-#if 0 //moving to SelectCurvePointByRay\r
-                       g_qeglobals.d_numpoints = 0;\r
-                       for (i = 0 ; i < p->width ; i++ ) \r
-                       {\r
-                               for ( j = 0 ; j < p->height ; j++ ) \r
-                               {\r
-                                       VectorCopy (p->ctrl[i][j].xyz, g_qeglobals.d_points[g_qeglobals.d_numpoints]);\r
-                                       if (g_qeglobals.d_numpoints < MAX_POINTS-1)\r
-                                       {\r
-                                               g_qeglobals.d_numpoints++;\r
-                                       }\r
-                               }\r
-                       }\r
-#endif                 \r
-                       vec3_t vMin, vMax;\r
-                       Patch_CalcBounds(p, vMin, vMax);\r
-                       Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-               }\r
-       }\r
-  //Brush_Free(p->pSymbiot);\r
-  //Select_Brush(AddBrushForPatch(g_nSelectedPatch));\r
-}\r
-\r
-\r
-\r
-/*\r
-===============\r
-SampleSinglePatch\r
-===============\r
-*/\r
-void SampleSinglePatch (float ctrl[3][3][5], float u, float v, float out[5]) {\r
-       float   vCtrl[3][5];\r
-       int             vPoint;\r
-       int             axis;\r
-\r
-       // find the control points for the v coordinate\r
-       for (vPoint = 0 ; vPoint < 3 ; vPoint++) \r
-       {\r
-               for (axis = 0 ; axis < 5 ; axis++) \r
-               {\r
-                       float   a, b, c;\r
-                       float   qA, qB, qC;\r
-\r
-                       a = ctrl[0][vPoint][axis];\r
-                       b = ctrl[1][vPoint][axis];\r
-                       c = ctrl[2][vPoint][axis];\r
-                       qA = a - 2 * b + c;\r
-                       qB = 2 * b - 2 * a;\r
-                       qC = a;\r
-\r
-                       vCtrl[vPoint][axis] = qA * u * u + qB * u + qC;\r
-               }\r
-       }\r
-\r
-       // interpolate the v value\r
-       for (axis = 0 ; axis < 5 ; axis++) \r
-       {\r
-               float   a, b, c;\r
-               float   qA, qB, qC;\r
-\r
-               a = vCtrl[0][axis];\r
-               b = vCtrl[1][axis];\r
-               c = vCtrl[2][axis];\r
-               qA = a - 2 * b + c;\r
-               qB = 2 * b - 2 * a;\r
-               qC = a;\r
-\r
-               out[axis] = qA * v * v + qB * v + qC;\r
-       }\r
-}\r
-\r
-//spog - Curve LOD stuff starts\r
-\r
-float ShadeForNormal(vec3_t normal)\r
-{\r
-  float f;\r
-\r
-       vec3_t L;\r
-       L[0] = 1.0f;\r
-       L[1] = 1.0f;\r
-       L[2] = 1.0f;\r
-\r
-  \r
-       // quick diffuse shading\r
-  f = DotProduct(L, normal);\r
-\r
-  // range 0.5 to 1.0\r
-       f = (f+1)/4.0f;\r
-  //if (f < 0.0f) f = 0.0f;\r
-\r
-       f += 0.5f;\r
-       \r
-  return f;\r
-}\r
-\r
-void ShadeVertex (drawVert_t &p)\r
-{\r
-       p.lightmap[0] = ShadeForNormal(p.normal);\r
-}\r
-\r
-\r
-void Patch_DrawNormals(patchMesh_t *patch)\r
-{\r
-       int row, col;\r
-       vec3_t vNormal;\r
-\r
-       qglBegin (GL_LINES);\r
-       for (col=0; col<patch->width; col++)\r
-       {\r
-               for (row=0; row<patch->height; row++)\r
-               {\r
-                       VectorAdd(patch->ctrl[col][row].xyz, patch->ctrl[col][row].normal, vNormal);\r
-                       qglVertex3fv (patch->ctrl[col][row].xyz);\r
-                       qglVertex3fv (vNormal);\r
-               }\r
-       }\r
-       qglEnd ();\r
-}\r
-\r
-\r
-// take an array of three drawVerts, and the addresses of three more drawVerts\r
-// interpolate new XYZST values from the three drawVerts, these are:\r
-// the left sub-control-point, the right sub-control-point and the midpoint of the curve respectively\r
-// store these values in the drawVerts passed to the function\r
-void Patch_CurveSplit(drawVert_t *vCurve[3], drawVert_t &pLeft, drawVert_t &pRight, drawVert_t &pMid, float u)\r
-{\r
-       int i;\r
-       //float u = 0.5f;\r
-//     float a, b;\r
-       drawVert_t v1, v2, v3;\r
-//     vec3_t v4;\r
-       \r
-       for (i=0; i<3; i++)\r
-       {\r
-                // xyz\r
-               v1.xyz[i] = vCurve[1]->xyz[i] - vCurve[0]->xyz[i];\r
-               v2.xyz[i] = vCurve[2]->xyz[i] - vCurve[1]->xyz[i];\r
-               v1.xyz[i] *= u;\r
-               v2.xyz[i] *= u;\r
-               pLeft.xyz[i] = vCurve[0]->xyz[i] + v1.xyz[i];\r
-               pRight.xyz[i] = vCurve[1]->xyz[i] + v2.xyz[i];\r
-\r
-               v3.xyz[i] = pRight.xyz[i] - pLeft.xyz[i];\r
-               v3.xyz[i] *= u;\r
-               pMid.xyz[i] = pLeft.xyz[i] + v3.xyz[i];\r
-\r
-               // normal (weighted average) // no, that's b0rked\r
-               //a = 1 / u; // total\r
-               //b = u * a; // component 2\r
-               //a = u - b; // component 1\r
-               //pMid.normal[i] = u * ((vCurve[0]->normal[i] * b) + (vCurve[2]->normal[i] * a));\r
-\r
-               if (i==2) continue;\r
-\r
-               // st\r
-               v1.st[i] = vCurve[1]->st[i] - vCurve[0]->st[i];\r
-               v2.st[i] = vCurve[2]->st[i] - vCurve[1]->st[i];\r
-               v1.st[i] *= u;\r
-               v2.st[i] *= u;\r
-               pLeft.st[i] = vCurve[0]->st[i] + v1.st[i];\r
-               pRight.st[i] = vCurve[1]->st[i] + v2.st[i];\r
-\r
-               v3.st[i] = pRight.st[i] - pLeft.st[i];\r
-               v3.st[i] *= u;\r
-               pMid.st[i] = pLeft.st[i] + v3.st[i];\r
-       }\r
-}\r
-\r
-// take an array of three points, return an index representing the curvature of those three points\r
-// return zero if the curve is a straight line, unless the midpoint is not between the endpoints\r
-float Patch_CurveIndex(vec3_t vCurve[])\r
-{\r
-       vec3_t vTemp, v1, v2, v3, vClear;\r
-//     int i;\r
-       float width, angle;\r
-       float index, dot;\r
-\r
-       VectorClear(vClear);\r
-               \r
-       VectorSubtract(vCurve[2], vCurve[0], vTemp);\r
-       VectorSubtract(vCurve[1], vCurve[0], v1);\r
-       VectorSubtract(vCurve[2], vCurve[1], v2);\r
-\r
-       if (VectorCompare(v1, vClear) || VectorCompare(vTemp, v1)) // return 0 if 1->2 == 0 or 1->2 == 1->3\r
-               return 0.0f;\r
-\r
-       VectorNormalize(v1, v1);\r
-       VectorNormalize(v2, v2);\r
-       if (VectorCompare(v1, v2))\r
-               return 0.0f;\r
-       \r
-       VectorCopy(vTemp, v3);\r
-       width = VectorNormalize(v3, v3);\r
-\r
-       if (VectorCompare(v1, v3) && VectorCompare(v2, v3))\r
-               return 0.0f;\r
-       \r
-       dot = DotProduct(v1, v2);\r
-\r
-       angle = acos(dot) / Q_PI;\r
-\r
-       index = width * angle;\r
-\r
-       return index;\r
-}\r
-\r
-\r
-// create a new tree root, give it the coordinate values of the drawVert\r
-// return a pointer to the new tree root\r
-BTNode_t *BTree_Create(drawVert_t info)\r
-{\r
-       BTNode_t *BTree = new BTNode_t;\r
-       BTree->left = BTree->right = NULL;\r
-       VectorCopy(info.xyz, BTree->info.xyz);\r
-       VectorCopy(info.xyz, BTree->vMid.xyz);\r
-       for (int i=0; i<2; i++)\r
-       {\r
-               BTree->info.st[i] = info.st[i];\r
-               BTree->vMid.st[i] = info.st[i];\r
-       }\r
-       return BTree;\r
-}\r
-\r
-// take ownership of the subtree\r
-// delete the entire subtree\r
-// return a NULL pointer\r
-BTNode_t *BTree_Delete(BTNode_t *pBT)\r
-{\r
-       if (pBT != NULL)\r
-       {\r
-               BTree_Delete(pBT->left);\r
-               BTree_Delete(pBT->right);\r
-               delete pBT;\r
-       }\r
-       return NULL;\r
-}\r
-\r
-// NOT currently used\r
-BTNode_t *BTree_Clear(BTNode_t *pBT, bool bFirst = true)\r
-{\r
-       if (pBT != NULL)\r
-       {\r
-               BTree_Clear(pBT->left, false);\r
-               BTree_Clear(pBT->right, false);\r
-               if (!bFirst) delete pBT;\r
-       }\r
-       return pBT;\r
-}\r
-\r
-// take a pointer to the last item added to the list (this can also be a NULL pointer)\r
-// take a pointer to the root of a subtree, and the patch points to the left and right of it\r
-// add a new item to the subtree list, and add the subtree and its adjacent points to the new item\r
-// return a pointer to the last item added to the subtree list\r
-BTreeList_t *BTree_AddToList(BTreeList_t *pBTList, BTNode_t *pBT, drawVert_t &pLeft, drawVert_t &pRight)\r
-{\r
-       BTreeList_t *newBTList = new BTreeList_t;\r
-       newBTList->next = pBTList;\r
-       newBTList->pBT = pBT;\r
-       VectorCopy(pLeft.xyz, newBTList->vLeft.xyz);\r
-       VectorCopy(pRight.xyz, newBTList->vRight.xyz);\r
-       VectorCopy(pLeft.normal, newBTList->vLeft.normal);\r
-       VectorCopy(pRight.normal, newBTList->vRight.normal);\r
-       for (int i=0; i<2; i++)\r
-       {\r
-               newBTList->vLeft.st[i] = pLeft.st[i];\r
-               newBTList->vRight.st[i] = pRight.st[i];\r
-       }\r
-       return newBTList;\r
-}\r
-\r
-// NOT currently used, subtrees are now stored on the patch\r
-// take ownership of the subtree list\r
-// delete the entire list and the subtrees it points to\r
-// return a NULL pointer\r
-BTreeList_t *BTree_DeleteList(BTreeList_t *pBTList)\r
-{\r
-       if (pBTList != NULL)\r
-       {\r
-               BTree_DeleteList(pBTList->next);\r
-               pBTList->pBT = BTree_Delete(pBTList->pBT);\r
-               delete pBTList;\r
-       }\r
-       return NULL;\r
-}\r
-\r
-// take ownership of the subtree list\r
-// delete the entire subtree list, but not the subtrees themselves\r
-// return a NULL pointer\r
-BTreeList_t *BTree_DeletePointerList(BTreeList_t *pBTList)\r
-{\r
-       if (pBTList != NULL)\r
-       {\r
-               BTree_DeletePointerList(pBTList->next);\r
-               delete pBTList;\r
-       }\r
-       return NULL;\r
-}\r
-\r
-// take a pointer to the last item added to the list of subtree lists\r
-// add a subtree list to the list\r
-// return a pointer to the last item added\r
-BTListList_t *BTree_AddListToList(BTListList_t *pBTListList, BTreeList_t *pBTList)\r
-{\r
-       BTListList_t *newBTListList = new BTListList_t;\r
-       newBTListList->next = pBTListList;\r
-       newBTListList->list = pBTList;\r
-       return newBTListList;\r
-}\r
-\r
-\r
-// take ownership of the list of subtree lists\r
-// delete the entire list of lists, but not the subtrees themselves\r
-// return a NULL pointer\r
-BTListList_t *BTree_DeleteListFromList(BTListList_t *pBTListList)\r
-{\r
-       if (pBTListList != NULL)\r
-       {\r
-               BTree_DeleteListFromList(pBTListList->next);\r
-               pBTListList->list = BTree_DeletePointerList(pBTListList->list);\r
-               delete pBTListList;\r
-       }\r
-       return NULL;\r
-}\r
-\r
-// take a pointer to the last item in the list\r
-// add a NULL linker subtree to the list, setting the "flipped" flag using the left curvepoint normal .. er.. hacky?\r
-BTreeList_t *BTree_AddLinkToList(BTreeList_t *pBTList, bool bFlipped = false)\r
-{\r
-       BTreeList_t *linkBTList = new BTreeList_t;\r
-       linkBTList->pBT = NULL;\r
-       linkBTList->next = pBTList;\r
-       linkBTList->vLeft.normal[0] = (bFlipped) ? 1.0f : 0.0f;\r
-       return linkBTList;\r
-}\r
-\r
-\r
-// take an array of three points and the address of a vector\r
-// store midpoint of the bezier curve formed by the three points, in the vector\r
-void Patch_BezierInterpolate(vec3_t vCurve[], vec3_t &pMid)\r
-{\r
-       vec3_t vTemp;\r
-       int i;\r
-       VectorSubtract(vCurve[2], vCurve[0], vTemp); // Start->End\r
-       for (i=0; i<3; i++)\r
-               vTemp[i] /= 2;\r
-       VectorAdd(vCurve[0], vTemp, vTemp); // midpoint of Start->End\r
-\r
-       VectorSubtract(vTemp, vCurve[1], vTemp); // Mid->(midpoint of Start->End)\r
-       for (i=0; i<3; i++)\r
-               vTemp[i] /= 2;\r
-       VectorAdd(vCurve[1], vTemp, pMid); // midpoint of Mid->(midpoint of Start->End)\r
-}\r
-\r
-\r
-// take a pointer to the list of subtrees, and a threshold value\r
-// generate REAL surface curvature for the subtree curves, using bezier interpolation\r
-// if any of the real curves has an index greater than the threshold, return true \r
-bool Patch_MostCurvedRow(BTreeList_t *pBTList, int threshold)\r
-{\r
-       BTreeList_t *p;\r
-       float index;//, bestindex = 0;\r
-       vec3_t vCurve[3];\r
-       vec3_t vRow[3];\r
-//     int i;\r
-\r
-       for (p = pBTList; p != NULL; p = p->next->next)\r
-       {\r
-               // this row\r
-               VectorCopy(p->vLeft.xyz, vCurve[0]);\r
-               VectorCopy(p->pBT->info.xyz, vCurve[1]);\r
-               VectorCopy(p->vRight.xyz, vCurve[2]);\r
-               \r
-               index = Patch_CurveIndex(vCurve);\r
-               if (index > threshold)\r
-                       return true;\r
-\r
-               if (p->next == NULL)\r
-                       break;\r
-\r
-               if (p->next->pBT == NULL) continue;\r
-\r
-               VectorCopy(p->vLeft.xyz, vCurve[0]);\r
-               VectorCopy(p->next->vLeft.xyz, vCurve[1]);\r
-               VectorCopy(p->next->next->vLeft.xyz, vCurve[2]);\r
-               Patch_BezierInterpolate(vCurve, vRow[0]);\r
-\r
-               VectorCopy(p->pBT->info.xyz, vCurve[0]);\r
-               VectorCopy(p->next->pBT->info.xyz, vCurve[1]);\r
-               VectorCopy(p->next->next->pBT->info.xyz, vCurve[2]);\r
-               Patch_BezierInterpolate(vCurve, vRow[1]);\r
-\r
-               VectorCopy(p->vRight.xyz, vCurve[0]);\r
-               VectorCopy(p->next->vRight.xyz, vCurve[1]);\r
-               VectorCopy(p->next->next->vRight.xyz, vCurve[2]);\r
-               Patch_BezierInterpolate(vCurve, vRow[2]);\r
-\r
-               index = Patch_CurveIndex(vRow);\r
-               if (index > threshold)\r
-                       return true;\r
-       }\r
-       return false;\r
-}\r
-\r
-\r
-// take a pointer to a list of subtrees.. each subtree in the list is a 3-point bezier curve formed by two endpoints owned by the list, and a midpoint subtree node owned by a patch.\r
-// if any of the subtrees are curved above a threshold, create a left and right subsubtree for each subtree in the list.\r
-// if a NULL linker subtree is found, check for an orientation flip - ie. an inverted LOD-match - and create a NULL subsubtree with the same orientation flip\r
-// this effectively generates trees for multiple patches at the same time.. the subtrees are always owned by their respective patches though\r
-void BTree_ListCurveRecurse(BTreeList_t *pBTList)\r
-{\r
-       BTreeList_t *p;\r
-       BTreeList_t *leftBTList, *rightBTList;\r
-       //drawVert_t pLeft, pRight, pMid;\r
-       drawVert_t *vCurve[3];\r
-       int threshold;\r
-       //int i;\r
-       bool bFlipped = false;\r
-\r
-  if (g_PrefsDlg.m_nSubdivisions >= 1)\r
-    threshold = g_PrefsDlg.m_nSubdivisions;\r
-       \r
-       leftBTList = rightBTList = NULL;\r
-       \r
-       if (Patch_MostCurvedRow(pBTList, threshold)) // split all subtrees in list if any subtree is above threshold\r
-       {\r
-               //Sys_Printf("| ");\r
-               // traverse nodes in list\r
-               for (p = pBTList; p != NULL; p=p->next)\r
-               {\r
-                       if (p->pBT == NULL) \r
-                       {\r
-                               leftBTList = BTree_AddLinkToList(leftBTList, (p->vLeft.normal[0] == 1.0f));\r
-                               rightBTList = BTree_AddLinkToList(rightBTList, (p->vLeft.normal[0] == 1.0f));\r
-                               if (p->vLeft.normal[0] == 1.0f) bFlipped = (!bFlipped) ? true : false; // switch bFlipped if true\r
-                               continue;\r
-                       }\r
-\r
-                       // create left node for this subtree\r
-                       BTNode_t *newLeft = new BTNode_t;\r
-                       p->pBT->left = newLeft;\r
-                       newLeft->left = newLeft->right = NULL;\r
-                       \r
-                       // create right node for this subtree\r
-                       BTNode_t *newRight = new BTNode_t;\r
-                       p->pBT->right = newRight;\r
-                       newRight->left = newRight->right = NULL;\r
-\r
-                       // split this node\r
-                       vCurve[0] = &p->vLeft;\r
-                       vCurve[1] = &p->pBT->info;\r
-                       vCurve[2] = &p->vRight;\r
-                       Patch_CurveSplit(vCurve, newLeft->info, newRight->info, p->pBT->vMid, 0.5);\r
-\r
-                       memcpy(&newLeft->vMid, &newLeft->info, sizeof(drawVert_t));\r
-                       memcpy(&newRight->vMid, &newRight->info, sizeof(drawVert_t));\r
-                       \r
-                       \r
-                       if (!bFlipped)\r
-                       {\r
-                               // add new left subtree to left subtree list\r
-                               leftBTList = BTree_AddToList(leftBTList, newLeft, p->vLeft, p->pBT->vMid);\r
-                               \r
-                               // add new right subtree to right subtree list\r
-                               rightBTList = BTree_AddToList(rightBTList, newRight, p->pBT->vMid, p->vRight);\r
-                       }\r
-                       else\r
-                       {\r
-                               // add new left subtree to right subtree list\r
-                               rightBTList = BTree_AddToList(rightBTList, newLeft, p->vLeft, p->pBT->vMid);\r
-                               \r
-                               // add new right subtree to left subtree list\r
-                               leftBTList = BTree_AddToList(leftBTList, newRight, p->pBT->vMid, p->vRight);\r
-                       }\r
-               }\r
-\r
-               // continue tree left\r
-               BTree_ListCurveRecurse(leftBTList);\r
-               leftBTList = BTree_DeletePointerList(leftBTList);\r
-\r
-               // continue tree right\r
-               BTree_ListCurveRecurse(rightBTList);\r
-               rightBTList = BTree_DeletePointerList(rightBTList);\r
-       }\r
-}\r
-\r
-// take mins and maxs values from two brushes\r
-// return true if they intersect on every axis\r
-bool TouchingAABBs(vec3_t mins1, vec3_t maxs1, vec3_t mins2, vec3_t maxs2)\r
-{\r
-       //bool xyz[3];\r
-       vec3_t v1, v2, p1, p2, T;\r
-       for (int i=0; i<3; i++)\r
-       {\r
-               v1[i] = maxs1[i] - mins1[i];\r
-               v2[i] = maxs2[i] - mins2[i];\r
-               v1[i] /=2;\r
-               v2[i] /=2;\r
-               p1[i] = mins1[i] + v1[i];\r
-               p2[i] = mins2[i] + v2[i];\r
-               // p1 == origin of aabb1\r
-               // p2 == origin of aabb1\r
-               // v1 == displacement of aabb1\r
-               // v1 == displacement of aabb2\r
-               T[i] = p2[i] - p1[i]; // T == vector from aabb1 to aabb2\r
-               if ( fabs(T[i]) > (fabs(v1[i]) + fabs(v2[i])) )\r
-                       return false;\r
-       }\r
-       return true;\r
-}\r
-\r
-// take a pointer to the last item added to pBTList, a pointer to the patch, a row index (start) and a column index\r
-// generate a row of row-curve tree roots, owned by the patch and add the entire column of row-curves to the list, using the row index to decide the order to add\r
-// return a pointer to the last item added to the list\r
-BTreeList_t *Patch_CreateBTListForRows(BTreeList_t *pBTList, patchMesh_t *patch, int start, int col)\r
-{\r
-       int row, pos;\r
-       patch->colDirty[(col-1)/2] = true;\r
-                                               \r
-       if (start == 0)\r
-       {\r
-               for (row=0; row<patch->height; row++)\r
-               {\r
-                       pos = (((col-1)/2)*patch->height)+row;\r
-                       patch->rowLOD[pos] = BTree_Delete(patch->rowLOD[pos]);\r
-                       patch->rowLOD[pos] = BTree_Create(patch->ctrl[col][row]);\r
-                       pBTList = BTree_AddToList(pBTList, patch->rowLOD[pos], patch->ctrl[col-1][row], patch->ctrl[col+1][row]);\r
-               }\r
-       }\r
-       else\r
-       {\r
-               for (row=patch->height-1; row>=0; row--)\r
-               {\r
-                       pos = (((col-1)/2)*patch->height)+row;\r
-                       patch->rowLOD[pos] = BTree_Delete(patch->rowLOD[pos]);\r
-                       patch->rowLOD[pos] = BTree_Create(patch->ctrl[col][row]);\r
-                       pBTList = BTree_AddToList(pBTList, patch->rowLOD[pos], patch->ctrl[col-1][row], patch->ctrl[col+1][row]);\r
-               }\r
-       }\r
-       return pBTList;\r
-}\r
-\r
-// take a pointer to the last item added to pBTList, a pointer to the patch, a row index and a column index (start)\r
-// generate a row of column-curve tree roots, owned by the patch and add the entire row of column-curves to the list, using the column index to decide the order to add\r
-// return a pointer to the last item added to the list\r
-BTreeList_t *Patch_CreateBTListForCols(BTreeList_t *pBTList, patchMesh_t *patch, int row, int start)\r
-{\r
-       int col, pos;\r
-       patch->rowDirty[(row-1)/2] = true;\r
-\r
-       if (start == 0)\r
-       {\r
-               for (col=0; col<patch->width; col++)\r
-               {\r
-                       pos = (((row-1)/2)*patch->width)+col;\r
-                       patch->colLOD[pos] = BTree_Delete(patch->colLOD[pos]);\r
-                       patch->colLOD[pos] = BTree_Create(patch->ctrl[col][row]);\r
-                       pBTList = BTree_AddToList(pBTList, patch->colLOD[pos], patch->ctrl[col][row-1], patch->ctrl[col][row+1]);\r
-               }\r
-       }\r
-       else\r
-       {\r
-               for (col=patch->width-1; col>=0; col--)\r
-               {\r
-                       pos = (((row-1)/2)*patch->width)+col;\r
-                       patch->colLOD[pos] = BTree_Delete(patch->colLOD[pos]);\r
-                       patch->colLOD[pos] = BTree_Create(patch->ctrl[col][row]);\r
-                       pBTList = BTree_AddToList(pBTList, patch->colLOD[pos], patch->ctrl[col][row-1], patch->ctrl[col][row+1]);\r
-               }\r
-\r
-       }\r
-       return pBTList;\r
-}\r
-\r
-bool BTree_IsInList(BTreeList_t *pBTList, BTNode_t *pBT)\r
-{\r
-       BTreeList_t *p;\r
-       if (pBTList == NULL) return false;\r
-\r
-       for (p=pBTList; p != NULL; p=p->next)\r
-       {\r
-               if (p->pBT != NULL)\r
-               {\r
-                       if (p->pBT == pBT)\r
-        return true;\r
-               }\r
-       }\r
-       return false;\r
-}\r
-\r
-int Patch_DegenCurve(vec3_t &start, vec3_t &mid, vec3_t &end)\r
-{\r
-  if (VectorCompare(start, mid) || VectorCompare(end, mid))\r
-  {\r
-    if (VectorCompare(start, end)) return 2;\r
-    else return 1;\r
-  }\r
-  else return 0;\r
-}\r
-\r
-// take a pointer to the last item added to the list, and a pointer to a patch (this patch is the owner of the three drawverts)\r
-// take the addresses of three drawVerts, and compare them with the edges of all patches that touch the patch\r
-// if they match an edge, add the tree roots for that section of the matched patch to the list, and recurse for the opposite edge of that patch section. Also, set the matched patch Dirty, so that its drawlists will be rebuilt\r
-// return a pointer to the last item added\r
-BTreeList_t *Patch_FindLODMatches(patchMesh_t *patch, BTreeList_t *pBTList, drawVert_t &pMid, drawVert_t &pLeft, drawVert_t &pRight)\r
-{\r
-       brush_t *pb, *brushlist;\r
-       int row, col, i;//, pos;\r
-       vec3_t vTemp, v1, v2;//, vClear;\r
-  bool bAlreadyAdded;\r
-\r
-       //Sys_Printf("Patch_FindLODMatches: called\n");\r
-\r
-       if (VectorCompare(pMid.xyz, pLeft.xyz) && VectorCompare(pMid.xyz, pRight.xyz))\r
-               return pBTList;\r
-\r
-       //VectorClear(vClear);\r
-       VectorSubtract(pRight.xyz, pLeft.xyz, vTemp);\r
-       VectorSubtract(pMid.xyz, pLeft.xyz, v1);\r
-       VectorSubtract(pRight.xyz, pMid.xyz, v2);\r
-\r
-       //if (VectorCompare(v1, vClear) || VectorCompare(vTemp, v1)) // return null if 1->2 == 0 or 1->2 == 1->3\r
-       //      return pBTList;\r
-\r
-       VectorNormalize(v1, v1);\r
-       VectorNormalize(v2, v2);\r
-       if (VectorCompare(v1, v2))\r
-               return pBTList;\r
-\r
-       VectorNormalize(vTemp, vTemp);\r
-       if (VectorCompare(v1, vTemp) && VectorCompare(v2, vTemp))\r
-               return pBTList;\r
-\r
-       brushlist = &active_brushes;\r
-       for (i=0; i<2; i++)\r
-       {\r
-               for (pb = brushlist->next; pb != brushlist; pb=pb->next)\r
-               {\r
-                       if (!pb->patchBrush || pb->pPatch == patch)\r
-                               continue;\r
-\r
-                       // ignore this patch if its AABB does not touch the subject patch\r
-                       if (!TouchingAABBs(patch->pSymbiot->maxs, patch->pSymbiot->mins, pb->maxs, pb->mins))\r
-                               continue;\r
-\r
-      // all columns of curves\r
-                       for (col=1; col<pb->pPatch->width; col+=2)\r
-                       {\r
-                               if (pb->pPatch->colDirty[(col-1)/2]) continue;\r
-\r
-                               bAlreadyAdded = false;\r
-\r
-                         // top and bottom curves of this column\r
-                               for (row=0; row<pb->pPatch->height; row+=pb->pPatch->height-1)\r
-                               {\r
-          if (bAlreadyAdded)\r
-            continue;\r
-          //if (!BTree_IsInList(pBTList, pb->pPatch->rowLOD[(((col-1)/2)*patch->height)+row]))\r
-          //  continue;\r
-                                       // ignore this curve if it shares no mid ctrl point with the test curve\r
-                                       if (!VectorCompare (pb->pPatch->ctrl[col][row].xyz, pMid.xyz))\r
-                                               continue;\r
-                                       // ignore this curve if it is degenerate\r
-                                       if (VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col-1][row].xyz) || VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col+1][row].xyz))\r
-                                               continue;\r
-                                       // if curve matches the test curve directly\r
-                                       if (VectorCompare (pb->pPatch->ctrl[col-1][row].xyz, pLeft.xyz) && VectorCompare (pb->pPatch->ctrl[col+1][row].xyz, pRight.xyz))\r
-                                       {\r
-                                               // add a blank link as separator\r
-                                               pBTList = BTree_AddLinkToList(pBTList);\r
-                                               // add this entire column, if top, top-to-bottom, else bottom to top\r
-                                               pBTList = Patch_CreateBTListForRows(pBTList, pb->pPatch, row, col);\r
-                                               // continue checking from last curve added to list\r
-                                         pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);\r
-                                               // set flag\r
-                                               pb->pPatch->LODUpdated = true;\r
-            bAlreadyAdded = true;\r
-                                       }\r
-                                       // if curve matches test curve but flipped\r
-                                       else if (VectorCompare (pb->pPatch->ctrl[col-1][row].xyz, pRight.xyz) && VectorCompare (pb->pPatch->ctrl[col+1][row].xyz, pLeft.xyz))\r
-                                       {\r
-                                               pBTList = BTree_AddLinkToList(pBTList, true); // flip\r
-                                               pBTList = Patch_CreateBTListForRows(pBTList, pb->pPatch, row, col);\r
-                                               pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);                               \r
-                                               pb->pPatch->LODUpdated = true;\r
-            bAlreadyAdded = true;\r
-                                       }\r
-                               }\r
-                       }\r
-\r
-                       // all rows of curves\r
-                       for (row=1; row<pb->pPatch->height; row+=2)\r
-                       {\r
-                               if (pb->pPatch->rowDirty[(row-1)/2]) continue;\r
-\r
-                               bAlreadyAdded = false;\r
-\r
-                         for (col=0; col<pb->pPatch->width; col+=pb->pPatch->width-1)\r
-                               {\r
-          if (bAlreadyAdded)\r
-            continue;\r
-          //if (BTree_IsInList(pBTList, pb->pPatch->colLOD[(((row-1)/2)*patch->width)+col]))\r
-          //  continue;\r
-                                       if (!VectorCompare (pb->pPatch->ctrl[col][row].xyz, pMid.xyz))\r
-                                               continue;\r
-                                       if (VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col][row-1].xyz) || VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col][row+1].xyz))\r
-                                               continue;\r
-                                       if (VectorCompare (pb->pPatch->ctrl[col][row-1].xyz, pLeft.xyz) && VectorCompare (pb->pPatch->ctrl[col][row+1].xyz, pRight.xyz))\r
-                                       {\r
-                                               pBTList = BTree_AddLinkToList(pBTList);\r
-                                               pBTList = Patch_CreateBTListForCols(pBTList, pb->pPatch, row, col);\r
-                                               pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);\r
-                                               pb->pPatch->LODUpdated = true;\r
-            bAlreadyAdded = true;\r
-                                       }\r
-                                       else if (VectorCompare (pb->pPatch->ctrl[col][row-1].xyz, pRight.xyz) && VectorCompare (pb->pPatch->ctrl[col][row+1].xyz, pLeft.xyz))\r
-                                       {\r
-                                               pBTList = BTree_AddLinkToList(pBTList, true); // flip\r
-                                               pBTList = Patch_CreateBTListForCols(pBTList, pb->pPatch, row, col);\r
-                                               pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);\r
-            pb->pPatch->LODUpdated = true;\r
-            bAlreadyAdded = true;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               brushlist = &selected_brushes;\r
-       }\r
-       return pBTList;\r
-}\r
-\r
-// take a pointer to a patch\r
-// create tree roots for all the rows and columns of curves in the patch, the patch takes ownership of these new tree roots\r
-// generate lists of pointers to all the trees in all the patches in the map which need to match the LOD of trees owned by this patch\r
-// store all the lists in a list of lists\r
-// recursively generate the rest of every tree in each list in the list\r
-void Patch_CreateLODTrees(patchMesh_t *patch)\r
-{\r
-       BTreeList_t *pBTList;\r
-       int col, row, pos;//, rowcount, colcount;\r
-       BTListList_t *pLists;\r
-\r
-       //Sys_Printf("Patch_CreateMatchedLODTrees: called\n");\r
-\r
-       BTListList_t *LODLists;\r
-       LODLists = NULL;\r
-       \r
-       pBTList = NULL;\r
-\r
-       patch->bDirty = false;\r
-       patch->LODUpdated = true;\r
-       \r
-       for(col=1; col<patch->width; col+=2)\r
-       {\r
-               if (patch->colDirty[(col-1)/2]) continue;\r
-               else patch->colDirty[(col-1)/2] = true;\r
-\r
-               // create list for rows of current patch\r
-               for(row=0; row<patch->height; row++)\r
-               {\r
-                       pos = (((col-1)/2)*patch->height)+row;\r
-                       patch->rowLOD[pos] = BTree_Delete(patch->rowLOD[pos]);\r
-                       patch->rowLOD[pos] = BTree_Create(patch->ctrl[col][row]);\r
-                       pBTList = BTree_AddToList(pBTList, patch->rowLOD[pos], patch->ctrl[col-1][row], patch->ctrl[col+1][row]);\r
-               }\r
-       \r
-               //create connection list for first row\r
-               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[col][0], patch->ctrl[col-1][0], patch->ctrl[col+1][0]);\r
-               //create connection list for last row\r
-               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[col][row-1], patch->ctrl[col-1][row-1], patch->ctrl[col+1][row-1]);\r
-\r
-               LODLists = BTree_AddListToList(LODLists, pBTList);\r
-               pBTList = NULL;\r
-       }\r
-\r
-       pBTList = NULL;\r
-       for(row=1; row<patch->height; row+=2)\r
-       {\r
-               if (patch->rowDirty[(row-1)/2]) continue;\r
-               else patch->rowDirty[(row-1)/2] = true;\r
-\r
-               // create list for cols of current patch\r
-               for(col=0; col<patch->width; col++)\r
-               {\r
-                       pos = (((row-1)/2)*patch->width)+col;\r
-                       patch->colLOD[pos] = BTree_Delete(patch->colLOD[pos]);\r
-                       patch->colLOD[pos] = BTree_Create(patch->ctrl[col][row]);\r
-                       pBTList = BTree_AddToList(pBTList, patch->colLOD[pos], patch->ctrl[col][row-1], patch->ctrl[col][row+1]);\r
-               }\r
-\r
-               //create connection list for first col\r
-               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[0][row], patch->ctrl[0][row-1], patch->ctrl[0][row+1]);\r
-               //create connection list for last col\r
-               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[col-1][row], patch->ctrl[col-1][row-1], patch->ctrl[col-1][row+1]);\r
-\r
-               LODLists = BTree_AddListToList(LODLists, pBTList);\r
-               pBTList = NULL;\r
-       }\r
-\r
-       for (pLists = LODLists; pLists != NULL; pLists=pLists->next)\r
-               BTree_ListCurveRecurse(pLists->list);\r
-       LODLists = BTree_DeleteListFromList(LODLists);\r
-}\r
-\r
-int Patch_GetCVTangent(vec3_t &v1, vec3_t &p1, vec3_t &p2, vec3_t &p3)\r
-{\r
-       if (VectorCompare(p1, p2))\r
-       {\r
-               if (VectorCompare(p1, p3))\r
-               {\r
-                       return 2;\r
-               }\r
-               else VectorSubtract(p3, p1, v1);\r
-    return 1;\r
-       }\r
-       else VectorSubtract(p2, p1, v1);\r
-  return 0;\r
-}\r
-\r
-void Patch_CVNormal(vec3_t ctrl[3][3], vec3_t &normal)\r
-{\r
-       vec3_t v1, v2, vTemp1, vTemp2;\r
-  int a, b;\r
-       \r
-  a = Patch_GetCVTangent(v1, ctrl[0][0], ctrl[1][0], ctrl[2][0]);\r
-       b = Patch_GetCVTangent(v2, ctrl[0][0], ctrl[0][1], ctrl[0][2]);\r
-\r
-       //Sys_Printf("p1: (%1.1f %1.1f %1.1f) p2: (%1.1f %1.1f %1.1f) p2: (%1.1f %1.1f %1.1f)\n",\r
-       //      ctrl[0][0][0], ctrl[0][0][1], ctrl[0][0][2], ctrl[0][2][0], ctrl[0][2][1], ctrl[0][2][2], ctrl[2][0][0], ctrl[2][0][1], ctrl[2][0][2]);\r
-       \r
-  if (a == 2)\r
-  {\r
-    a = Patch_GetCVTangent(v1, ctrl[0][0], ctrl[1][1], ctrl[1][2]);\r
-  }\r
-  if (b == 2)\r
-  {\r
-    b = Patch_GetCVTangent(v2, ctrl[0][0], ctrl[1][1], ctrl[2][1]);\r
-  }\r
\r
-  if (a == 2)\r
-  {\r
-    a = Patch_GetCVTangent(v1, ctrl[0][0], ctrl[2][1], ctrl[2][2]);\r
-  }\r
-  if (b == 2)\r
-  {\r
-    b = Patch_GetCVTangent(v2, ctrl[0][0], ctrl[1][2], ctrl[2][2]);\r
-  }  \r
-\r
-       CrossProduct(v1, v2, normal);\r
-\r
-  \r
-  if (normal[0] == 0.0f && normal[1] == 0.0f && normal[2] == 0.0f)\r
-  {\r
-    // more degenerate cases\r
-    vec3_t pMid;\r
-    vec3_t vCurve[3];\r
-    /*\r
-    if (VectorCompare(ctrl[0][0], ctrl[2][0])) // endcap left\r
-    {\r
-      if (VectorCompare(ctrl[0][2], ctrl[1][2]))\r
-      {\r
-        VectorSubtract(ctrl[2][2], ctrl[0][0], v2);\r
-      }\r
-      else if (VectorCompare(ctrl[1][2], ctrl[2][2]))\r
-      {\r
-        VectorSubtract(ctrl[0][2], ctrl[0][0], v2);\r
-      }\r
-      else\r
-      a = Patch_DegenCurve(ctrl[0][2], ctrl[1][2], ctrl[2][2]);\r
-      if (a == 0)\r
-      {\r
-        VectorCopy(ctrl[0][2], vCurve[0]);\r
-        VectorCopy(ctrl[1][2], vCurve[1]);\r
-        VectorCopy(ctrl[2][2], vCurve[2]);\r
-        Patch_BezierInterpolate(vCurve, pMid);\r
-                         VectorSubtract(pMid, ctrl[0][0], v1);\r
-      }\r
-      \r
-      \r
-               }\r
-         else if (VectorCompare(ctrl[0][0], ctrl[0][2])) // endcap right\r
-               {\r
-      \r
-      if (VectorCompare(ctrl[2][0], ctrl[2][1]))\r
-      {\r
-        VectorSubtract(ctrl[2][2], ctrl[0][0], v2);\r
-      }\r
-      else if (VectorCompare(ctrl[2][1], ctrl[2][2]))\r
-      {\r
-        VectorSubtract(ctrl[2][0], ctrl[0][0], v2);\r
-      }\r
-      else\r
-      \r
-      b = Patch_DegenCurve(ctrl[2][0], ctrl[2][1], ctrl[2][2]);\r
-      if (b == 0)\r
-      {\r
-                   VectorCopy(ctrl[2][0], vCurve[0]);\r
-        VectorCopy(ctrl[2][1], vCurve[1]);\r
-        VectorCopy(ctrl[2][2], vCurve[2]);\r
-        Patch_BezierInterpolate(vCurve, pMid);\r
-                         VectorSubtract(pMid, ctrl[0][0], v2);\r
-      }\r
-      \r
-               }\r
-    */\r
-    if (VectorCompare(ctrl[0][0], ctrl[2][0])) // bottom degen\r
-    {\r
-      Patch_GetCVTangent(v1, ctrl[0][0], ctrl[2][1], ctrl[2][2]);\r
-    }\r
-    else if (VectorCompare(ctrl[0][0], ctrl[0][2])) // left degen\r
-    {\r
-      Patch_GetCVTangent(v2, ctrl[0][0], ctrl[1][2], ctrl[2][2]);\r
-    }\r
-    else if (VectorCompare(ctrl[0][2], ctrl[2][2])) // top degen\r
-    {\r
-      VectorSubtract(ctrl[2][0], ctrl[0][0], v1);\r
-    }\r
-    else if (VectorCompare(ctrl[2][0], ctrl[2][2])) // right degen\r
-    {\r
-      VectorSubtract(ctrl[0][2], ctrl[0][0], v2);\r
-    }\r
-    else // tangents parallel\r
-    {\r
-      VectorCopy(v1, vTemp1);\r
-      VectorCopy(v2, vTemp2);\r
-      VectorNormalize(vTemp1, vTemp1);\r
-      VectorNormalize(vTemp2, vTemp2);\r
-      if (VectorCompare(vTemp1, vTemp2)) // parallel same way\r
-      {\r
-        VectorSubtract(ctrl[2][0], ctrl[0][0], vTemp1);\r
-        VectorNormalize(vTemp1, vTemp1);\r
-        if (VectorCompare(vTemp1, vTemp2))\r
-        {\r
-          VectorSubtract(ctrl[0][2], ctrl[0][0], v2);\r
-        }\r
-        else\r
-        {\r
-          VectorCopy(vTemp1, v1);\r
-        }\r
-      }\r
-      else // parallel opposite way\r
-      {\r
-                   VectorCopy(ctrl[2][0], vCurve[0]);\r
-        VectorCopy(ctrl[1][1], vCurve[1]);\r
-        VectorCopy(ctrl[0][2], vCurve[2]);\r
-        Patch_BezierInterpolate(vCurve, pMid);\r
-                         VectorSubtract(pMid, ctrl[0][0], v2);\r
-                 }\r
-    }\r
-\r
-    CrossProduct(v1, v2, normal);\r
-  }\r
-}\r
-\r
-void Patch_CalcCVNormals(patchMesh_t *patch)\r
-{\r
-       int row, col, i, j, n;\r
-       vec3_t ctrl[3][3];\r
-       vec3_t normals[4];\r
-\r
-       for (col=0; col<patch->width; col+=2)\r
-       {\r
-               for (row=0; row<patch->height; row+=2)\r
-               {\r
-                       n=0;\r
-                       if (col+1 != patch->width && row+1 != patch->height)\r
-                       {\r
-                               for (i=0; i<3; i++)\r
-                                       for (j=0; j<3; j++)\r
-                                               VectorCopy (patch->ctrl[col+i][row+j].xyz, ctrl[i][j]);\r
-\r
-                               Patch_CVNormal(ctrl, normals[n]);\r
-        VectorNormalize(normals[n], normals[n]);\r
-                               n++;\r
-                       }\r
-\r
-                       if (col-1 >= 0 && row-1 >= 0)\r
-                       {\r
-                               for (i=0; i<3; i++)\r
-                                       for (j=0; j<3; j++)\r
-                                               VectorCopy (patch->ctrl[col-i][row-j].xyz, ctrl[i][j]);\r
-\r
-                               Patch_CVNormal(ctrl, normals[n]);\r
-        VectorNormalize(normals[n], normals[n]);\r
-                               n++;\r
-                       }\r
-                       if (col-1 >= 0 && row+1 != patch->height)\r
-                       {\r
-                               for (i=0; i<3; i++)\r
-                                       for (j=0; j<3; j++)\r
-                                               VectorCopy (patch->ctrl[col-i][row+j].xyz, ctrl[j][i]);\r
-\r
-                               Patch_CVNormal(ctrl, normals[n]);\r
-        VectorNormalize(normals[n], normals[n]);\r
-                               n++;\r
-                       }\r
-                       if (col+1 != patch->width && row-1 >= 0)\r
-                       {\r
-                               for (i=0; i<3; i++)\r
-                                       for (j=0; j<3; j++)\r
-                                               VectorCopy (patch->ctrl[col+i][row-j].xyz, ctrl[j][i]);\r
-\r
-                               Patch_CVNormal(ctrl, normals[n]);\r
-        VectorNormalize(normals[n], normals[n]);\r
-                               n++;\r
-                       }\r
-\r
-                       for (i=0; i<3; i++)\r
-                       {\r
-                               if (n == 1) patch->ctrl[col][row].normal[i] = normals[0][i];\r
-                               if (n == 2) patch->ctrl[col][row].normal[i] = (normals[0][i] + normals[1][i]) / n;\r
-                               //if (n == 3) patch->ctrl[col][row].normal[i] = (normals[0][i] + normals[1][i] + normals[2][i]) / n;\r
-                               if (n == 4) patch->ctrl[col][row].normal[i] = (normals[0][i] + normals[1][i] + normals[2][i] + normals[3][i]) / n;\r
-                       }\r
-                       VectorNormalize(patch->ctrl[col][row].normal, patch->ctrl[col][row].normal);\r
-                       //if (!g_PrefsDlg.m_bGLLighting)\r
-                       //      ShadeVertex(patch->ctrl[col][row]);\r
-               }\r
-       }\r
-}\r
-\r
-\r
-void BTree_SetNormals(BTNode_t *pBT, vec3_t &normal)\r
-{\r
-       if (pBT != NULL)\r
-       {\r
-               if (pBT->left != NULL && pBT->right != NULL)\r
-               {\r
-                       VectorCopy(normal, pBT->vMid.normal);\r
-                       //if (!g_PrefsDlg.m_bGLLighting)\r
-                       //      ShadeVertex(pBT->vMid);\r
-               }\r
-               BTree_SetNormals(pBT->left, normal);\r
-               BTree_SetNormals(pBT->right, normal);\r
-       }\r
-}\r
-\r
-\r
-void NormalFromPoints(vec3_t p1, vec3_t p2, vec3_t p3, vec3_t &normal, bool flip = false)\r
-{\r
-  vec3_t v1, v2;\r
-\r
-  if (flip)\r
-  {\r
-    VectorSubtract(p2, p3, v1); //p3->p2\r
-         VectorSubtract(p1, p2, v2); //p2->p1\r
-  }\r
-  else\r
-  {\r
-    VectorSubtract(p2, p1, v1); //p1->p2\r
-         VectorSubtract(p3, p2, v2); //p2->p3\r
-  }\r
-       CrossProduct(v1, v2, normal);\r
-}\r
-\r
-\r
-void BTree_GenerateNormals(BTNode_t *pBTMid, BTNode_t *pBTLeft, BTNode_t *pBTRight, bool avg, bool flat, bool nomid, bool noleft, bool noright, /*bool endcap, vec3_t &n1, vec3_t &n2,*/ bool flip)\r
-{\r
-       if (pBTMid != NULL)\r
-       {\r
-               if (pBTMid->left != NULL && pBTMid->right != NULL)\r
-               {\r
-                       vec3_t normal;\r
-     \r
-      if (noleft) // left curve is degenerate\r
-      {\r
-        if (nomid) // mid curve is degenerate\r
-        {\r
-          NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, normal, flip);\r
-               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        }\r
-        //else if (endcap)\r
-        //{\r
-        //  VectorCopy(n1, normal);\r
-        //  NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        //}\r
-        else\r
-        {\r
-          NormalFromPoints(pBTMid->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);\r
-               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        }\r
-      }\r
-      else if (noright) // right curve is degenerate\r
-      {\r
-        if (nomid) // mid curve is degenerate\r
-        {\r
-          NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);\r
-               NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        }\r
-        //else if (endcap)\r
-        //{\r
-        //  NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);\r
-        //  VectorCopy(n2, pBTRight->vMid.normal);\r
-        //}\r
-        else\r
-        {\r
-          NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);\r
-               NormalFromPoints(pBTMid->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        }\r
-      }\r
-      else\r
-      {\r
-        if (flat) // all curves are semi-degenerate (flat) or degenerate\r
-        {\r
-          NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTRight->vMid.xyz, normal, flip);\r
-               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTLeft->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        }\r
-        else\r
-        {\r
-                     NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);\r
-               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);\r
-        }\r
-      }\r
-\r
-      VectorNormalize(normal, normal);\r
-                       if (avg)\r
-                               for (int i=0; i<3; i++)\r
-                                       pBTLeft->vMid.normal[i] = (normal[i] + pBTLeft->vMid.normal[i]) / 2.0f;\r
-                       else VectorCopy(normal, pBTLeft->vMid.normal);\r
-     \r
-                       VectorNormalize(pBTLeft->vMid.normal, pBTLeft->vMid.normal);\r
-      VectorNormalize(pBTRight->vMid.normal, pBTRight->vMid.normal);\r
-\r
-               }\r
-               BTree_GenerateNormals(pBTMid->left, pBTLeft->left, pBTRight->left, avg, flat, nomid, noleft, noright, /*endcap, n1, n2,*/ flip);\r
-               BTree_GenerateNormals(pBTMid->right, pBTLeft->right, pBTRight->right, avg, flat, nomid, noleft, noright, /*endcap, n1, n2,*/ flip);\r
-       }\r
-}\r
-\r
-\r
-\r
-void Patch_GenerateLODNormals(patchMesh_t *patch)\r
-{\r
-  int col, row, rowpos, colpos, i;\r
-  BTNode_t *tree[2][3];\r
-  int degen[2][3];\r
-  bool rowAvg, colAvg;\r
-\r
-  for(col=0; col+2<patch->width; col+=2)\r
-       {\r
-               for(row=0; row+2<patch->height; row+=2)\r
-               {\r
-      if (!patch->colDirty[col/2] && !patch->rowDirty[row/2]) continue;  \r
\r
-               rowpos = ((col/2)*patch->height)+row;\r
-      colpos = ((row/2)*patch->width)+col;\r
-      \r
-      if (row==0) rowAvg = false;\r
-      else rowAvg = true;\r
-      if (col==0) colAvg = false;\r
-      else colAvg = true;\r
-\r
-      for (i=0; i<3; i++)\r
-      {\r
-        tree[0][i] = patch->rowLOD[rowpos+i];\r
-        tree[1][i] = patch->colLOD[colpos+i];\r
-        \r
-        degen[0][i] = Patch_DegenCurve(patch->ctrl[col][row+i].xyz, patch->ctrl[col+1][row+i].xyz, patch->ctrl[col+2][row+i].xyz);\r
-        degen[1][i] = Patch_DegenCurve(patch->ctrl[col+i][row].xyz, patch->ctrl[col+i][row+1].xyz, patch->ctrl[col+i][row+2].xyz);\r
-      }\r
-\r
-      BTree_GenerateNormals(tree[0][1], tree[0][0], tree[0][2], rowAvg, (degen[1][0] && degen[1][1] && degen[1][2]), degen[0][1] == 2, degen[0][0] == 2, degen[0][2] == 2, /*degen[1][1], patch->ctrl[col][row].normal, patch->ctrl[col][row+2].normal,*/ false);\r
-      BTree_GenerateNormals(tree[1][1], tree[1][0], tree[1][2], colAvg, (degen[0][0] && degen[0][1] && degen[0][2]), degen[1][1] == 2, degen[1][0] == 2, degen[1][2] == 2, /*degen[0][1], patch->ctrl[col][row].normal, patch->ctrl[col+2][row].normal,*/ true);\r
-    }\r
-  }\r
-}\r
-\r
-\r
-void Patch_ClearLODFlags(patchMesh_t *p)\r
-{\r
-       int i;\r
-\r
-       for (i=0;i<(p->width-1)/2; i++)\r
-               p->colDirty[i] = false;\r
-\r
-       for (i=0;i<(p->height-1)/2; i++)\r
-               p->rowDirty[i] = false;\r
-}\r
-\r
-// reset the lodDirty flags owned by all patches in the map\r
-// create new LOD trees for all dirty patches, matched with all other patches in the map\r
-void Patch_LODMatchAll()\r
-{\r
-       brush_t *pb, *brushlist;\r
-       int i;\r
-\r
-       // create LOD tree roots and LOD tree lists for all patches that are dirty\r
-\r
-       brushlist = &active_brushes;\r
-       for (i=0; i<2; i++)\r
-       {\r
-               for (pb = brushlist->next; pb && (pb != brushlist); pb=pb->next)\r
-               {\r
-      // create lod for selected patches when patches are filtered\r
-                       if (pb->bFiltered && (pb->patchBrush && !pb->pPatch->bSelected))\r
-                               continue;\r
-                       if (!pb->patchBrush)\r
-                               continue;\r
-                       if (!pb->pPatch->bDirty)\r
-                               continue;\r
-\r
-      Patch_CalcCVNormals(pb->pPatch);\r
-                       Patch_CreateLODTrees(pb->pPatch);\r
-               }\r
-               brushlist = &selected_brushes;\r
-       }\r
-\r
-       brushlist = &active_brushes;\r
-       for (i=0; i<2; i++)\r
-       {\r
-               for (pb = brushlist->next; pb && (pb != brushlist); pb=pb->next)\r
-               {\r
-                       if (!pb->patchBrush)\r
-                               continue;\r
-\r
-      if (pb->pPatch->LODUpdated)\r
-                         Patch_GenerateLODNormals(pb->pPatch);\r
-\r
-      Patch_ClearLODFlags(pb->pPatch);\r
-    }\r
-               brushlist = &selected_brushes;\r
-       }\r
-\r
-}\r
-\r
-void Vertex_TransformTexture(drawVert_t *pVert, float fx, float fy, transformtype xform)\r
-{\r
-  switch(xform)\r
-  {\r
-  case TRANSLATE:\r
-    pVert->st[0] += fx;\r
-    pVert->st[1] += fy;\r
-    break;\r
-  case SCALE:\r
-    pVert->st[0] *= fx;\r
-    pVert->st[1] *= fy;\r
-    break;\r
-  case ROTATE:\r
-    float x = pVert->st[0];\r
-    float y = pVert->st[1];\r
-    pVert->st[0] = x * fx - y * fy;\r
-    pVert->st[1] = y * fx + x * fy;\r
-  }\r
-}\r
-\r
-void BTree_TransformTexture(BTNode_t *pBT, float fx, float fy, transformtype xform)\r
-{\r
-       if (pBT != NULL)\r
-       {       // PreOrder traversal\r
-               Vertex_TransformTexture(&pBT->info, fx, fy, xform);\r
-    Vertex_TransformTexture(&pBT->vMid, fx, fy, xform);\r
-               BTree_TransformTexture(pBT->left, fx, fy, xform);\r
-               BTree_TransformTexture(pBT->right, fx, fy, xform);\r
-       }\r
-}\r
-\r
-void Patch_TransformLODTexture(patchMesh_t *p, float fx, float fy, transformtype xform)\r
-{\r
-       int col, row;\r
-\r
-       for(col=1; col<p->width; col+=2)\r
-               for(row=0; row<p->height; row++)\r
-                       BTree_TransformTexture(p->rowLOD[(((col-1)/2)*p->height)+row], fx, fy, xform);\r
-\r
-       for(row=1; row<p->height; row+=2)\r
-               for(col=0; col<p->width; col++)\r
-                       BTree_TransformTexture(p->colLOD[(((row-1)/2)*p->width)+col], fx, fy, xform);\r
-}\r
-\r
-void Patch_AddBTreeToDrawListInOrder(list<drawVert_t> *drawList, BTNode_t *pBT)\r
-{\r
-       if (pBT != NULL) //traverse InOrder\r
-       {\r
-               Patch_AddBTreeToDrawListInOrder(drawList, pBT->left);\r
-               if (pBT->left != NULL && pBT->right != NULL)\r
-                       drawList->push_back(pBT->vMid);\r
-               Patch_AddBTreeToDrawListInOrder(drawList, pBT->right);\r
-       }\r
-}\r
-\r
-void Patch_InterpolateListFromRowBT(list<drawVert_t> *drawList, BTNode_t *rowBT, BTNode_t *rowBTLeft, drawVert_t *vCurve[], float u, float n, float v)\r
-{\r
-       if (rowBT != NULL)\r
-       {\r
-               Patch_InterpolateListFromRowBT(drawList, rowBT->left, rowBTLeft->left, vCurve, u-n, n*0.5f, v);\r
-               if (rowBT->left != NULL && rowBT->right != NULL)\r
-               {\r
-                       vec3_t v1, v2;\r
-                       drawVert_t newVert, vTemp1, vTemp2;\r
-                       Patch_CurveSplit(vCurve, vTemp1, vTemp2, newVert, u);\r
-                       for (int i=0; i<3; i++)\r
-                       {\r
-                               v1[i] = rowBT->vMid.xyz[i] - rowBTLeft->vMid.xyz[i]; // left -> mid\r
-                               v1[i] = rowBTLeft->vMid.xyz[i] + (v1[i] * v);\r
-                               v1[i] = newVert.xyz[i] - v1[i];\r
-                       }\r
-                       VectorSubtract(vTemp1.xyz, newVert.xyz, v2);\r
-                       CrossProduct(v1, v2, newVert.normal);\r
-                       VectorNormalize(newVert.normal, newVert.normal);\r
-                       //if (!g_PrefsDlg.m_bGLLighting)\r
-                       //      ShadeVertex(newVert);\r
-                       drawList->push_back(newVert);\r
-               }\r
-               Patch_InterpolateListFromRowBT(drawList, rowBT->right, rowBTLeft->right, vCurve, u+n, n*0.5f, v);\r
-       }\r
-}\r
-\r
-void Patch_TraverseColBTInOrder(list<list<drawVert_t>*>::iterator& iter, BTNode_t *colBTLeft, BTNode_t *colBT, BTNode_t *colBTRight, BTNode_t *rowBT, BTNode_t *rowBTLeft, float v, float n)\r
-{\r
-       if (colBT != NULL)\r
-       {\r
-                //traverse subtree In Order\r
-               Patch_TraverseColBTInOrder(iter, colBTLeft->left, colBT->left, colBTRight->left, rowBT, rowBTLeft, v-n, n*0.5f);\r
-               if (colBT->left != NULL && colBT->right != NULL)\r
-               {\r
-                       drawVert_t *vCurve[3];\r
-                       vCurve[0] = &colBTLeft->vMid;\r
-                       vCurve[1] = &colBT->vMid;\r
-                       vCurve[2] = &colBTRight->vMid;\r
-                       Patch_InterpolateListFromRowBT((*iter), rowBT, rowBTLeft, vCurve, 0.5f, 0.25f, v);\r
-\r
-                       (*iter)->push_back(colBTRight->vMid);\r
-                       iter++;\r
-               }\r
-               Patch_TraverseColBTInOrder(iter, colBTLeft->right, colBT->right, colBTRight->right, rowBT, rowBTLeft, v+n, n*0.5f);\r
-       }\r
-}\r
-\r
-\r
-void Patch_StartDrawLists(list<list<drawVert_t>*> *drawLists, BTNode_t *colBT)\r
-{\r
-       if (colBT != NULL)\r
-       {\r
-                //traverse subtree In Order\r
-               Patch_StartDrawLists(drawLists, colBT->left);\r
-               if (colBT->left != NULL && colBT->right != NULL)\r
-               {\r
-                       list<drawVert_t> *newList = new list<drawVert_t>;\r
-                       drawLists->push_back(newList); // add empty list to back\r
-                       drawLists->back()->push_back(colBT->vMid);\r
-               }\r
-               Patch_StartDrawLists(drawLists, colBT->right);\r
-       }\r
-}\r
-\r
-typedef list<drawVert_t> drawList_t;\r
-typedef list<list<drawVert_t>*> drawLists_t;\r
-\r
-void Patch_CreateDrawLists(patchMesh_t *patch)\r
-{\r
-  int col, row, colpos, rowpos;\r
-\r
-       drawLists_t *drawLists = new drawLists_t;\r
-\r
-       drawLists_t::iterator iter1, iter2;\r
-\r
-       for (row=0; row<patch->height; row+=2)\r
-       {\r
-               colpos = (row/2)*patch->width;\r
-               drawList_t *newList = new drawList_t;\r
-               drawLists->push_back(newList); // add a new empty list to back\r
-               drawLists->back()->push_back(patch->ctrl[0][row]); // fill list at back\r
-\r
-               if (row+1 == patch->height)\r
-                       continue;\r
-               Patch_StartDrawLists(drawLists, patch->colLOD[colpos]);\r
-       }\r
-\r
-       iter1 = drawLists->begin();\r
-       for (row=0; row<patch->height; row+=2)\r
-       {\r
-               iter2 = iter1;\r
-               for (col=0; col+1<patch->width; col+=2)\r
-               {\r
-                       iter1 = iter2;\r
-                       colpos = ((row/2)*patch->width)+col;\r
-                       rowpos = ((col/2)*patch->height)+row;\r
-\r
-      Patch_AddBTreeToDrawListInOrder((*iter1), patch->rowLOD[rowpos]);\r
-                       (*iter1)->push_back(patch->ctrl[col+2][row]);\r
-                       \r
-                       if (row+1 == patch->height)\r
-                               continue;\r
-               \r
-                       iter1++;        \r
-\r
-      Patch_TraverseColBTInOrder(iter1, patch->colLOD[colpos], patch->colLOD[colpos+1], patch->colLOD[colpos+2], patch->rowLOD[rowpos+1], patch->rowLOD[rowpos], 0.5, 0.25);\r
-               }\r
-       }\r
-\r
-  patch->drawLists = drawLists;\r
-}\r
-\r
-\r
-void Patch_DeleteDrawLists(patchMesh_t *patch)\r
-{\r
-  drawLists_t *drawLists;\r
-  drawLists_t::iterator iter;\r
-\r
-  if (patch->drawLists == NULL)\r
-    return;\r
-\r
-  drawLists = (drawLists_t *)patch->drawLists;\r
-\r
-       for (iter=drawLists->begin(); iter != drawLists->end(); iter++)\r
-       {\r
-               delete (*iter);\r
-       }\r
-\r
-  delete drawLists;\r
-  patch->drawLists = NULL;\r
-}\r
-\r
-\r
-void Patch_DrawLODPatchMesh(patchMesh_t *patch)\r
-{\r
-       drawLists_t *drawLists;\r
-\r
-       drawLists_t::iterator iterLists, iterListsNext;\r
-       drawList_t::iterator iterList, iterListNext;\r
-\r
-  //int nGLState = g_pParentWnd->GetCamera()->Camera()->draw_glstate;\r
-\r
-  if (patch->drawLists == NULL)\r
-    return;\r
-\r
-  drawLists = (drawLists_t *)patch->drawLists;\r
-\r
-       iterListsNext=drawLists->begin();\r
-       iterListsNext++;\r
-       for (iterLists=drawLists->begin(); iterLists != drawLists->end() && iterListsNext != drawLists->end(); iterLists++, iterListsNext++)\r
-  {\r
-               // traverse two drawlists at once to draw a strip\r
-    //if (nGLState & DRAW_GL_LINE)\r
-                 qglBegin(GL_QUAD_STRIP);\r
-    //else\r
-    //  qglBegin(GL_TRIANGLE_STRIP);\r
-               for (iterList=(*iterLists)->begin(), iterListNext=(*iterListsNext)->begin(); iterList != (*iterLists)->end() && iterListNext != (*iterListsNext)->end(); iterList++, iterListNext++)\r
-               {\r
-                       //if (g_PrefsDlg.m_bGLLighting)\r
-                               qglNormal3fv((*iterList).normal);\r
-                       //else if (bShade && !g_PrefsDlg.m_bDisplayLists)\r
-                       //      qglColor3f((*iterList).lightmap[0], (*iterList).lightmap[0], (*iterList).lightmap[0]);\r
-\r
-                       qglTexCoord2fv((*iterList).st);\r
-                       qglVertex3fv((*iterList).xyz);\r
-\r
-                 //if (g_PrefsDlg.m_bGLLighting)\r
-                               qglNormal3fv((*iterListNext).normal);\r
-                       //else if (bShade && !g_PrefsDlg.m_bDisplayLists)\r
-                       //      qglColor3f((*iterListNext).lightmap[0], (*iterListNext).lightmap[0], (*iterListNext).lightmap[0]);\r
-\r
-                       qglTexCoord2fv((*iterListNext).st);\r
-                       qglVertex3fv((*iterListNext).xyz);\r
-    }\r
-               qglEnd();\r
-  }\r
-/*\r
-#ifdef _DEBUG\r
-  vec3_t vNormal;\r
-  for (iterLists=drawLists->begin(); iterLists != drawLists->end(); iterLists++)\r
-  {\r
-               qglBegin (GL_LINES); // draw normals\r
-               //qglColor3f(1,1,1);\r
-               for (iterList=(*iterLists)->begin(); iterList != (*iterLists)->end(); iterList++)\r
-               {\r
-                       VectorAdd((*iterList).xyz, (*iterList).normal, vNormal);\r
-                       qglVertex3fv ((*iterList).xyz);\r
-                       qglVertex3fv (vNormal);\r
-               }\r
-               qglEnd ();\r
-  }\r
-\r
-       Patch_DrawNormals(patch);\r
-\r
-#endif\r
-  */\r
-}\r
-\r
-/*\r
-// fast memory-efficient ray-triangle intersection - MollerTrumbore97 \r
-\r
-#define EPSILON 0.000001\r
-#define CROSS(dest,v1,v2) {dest[0]=v1[1]*v2[2]-v1[2]*v2[1];dest[1]=v1[2]*v2[0]-v1[0]*v2[2];dest[2]=v1[0]*v2[1]-v1[1]*v2[0];}\r
-#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])\r
-#define SUB(dest,v1,v2) {dest[0]=v1[0]-v2[0];dest[1]=v1[1]-v2[1];dest[2]=v1[2]-v2[2];}\r
-\r
-int intersect_triangle(float orig[3], float dir[3],\r
-                   float vert0[3], float vert1[3], float vert2[3],\r
-                   double *t, double *u, double *v)\r
-{\r
-   double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];\r
-   double det,inv_det;\r
-\r
-   // find vectors for two edges sharing vert0\r
-   SUB(edge1, vert1, vert0);\r
-   SUB(edge2, vert2, vert0);\r
-\r
-   // begin calculating determinant - also used to calculate U parameter \r
-   CROSS(pvec, dir, edge2);\r
-\r
-   // if determinant is near zero, ray lies in plane of triangle\r
-   det = DOT(edge1, pvec);\r
-\r
-#ifdef TEST_CULL           // define TEST_CULL if culling is desired\r
-   if (det < EPSILON)\r
-      return 0;\r
-\r
-   // calculate distance from vert0 to ray origin\r
-   SUB(tvec, orig, vert0);\r
-\r
-   // calculate U parameter and test bounds\r
-   *u = DOT(tvec, pvec);\r
-   if (*u < 0.0 || *u > det)\r
-      return 0;\r
-\r
-   // prepare to test V parameter\r
-   CROSS(qvec, tvec, edge1);\r
-\r
-    // calculate V parameter and test bounds\r
-   *v = DOT(dir, qvec);\r
-   if (*v < 0.0 || *u + *v > det)\r
-      return 0;\r
-\r
-   // calculate t, scale parameters, ray intersects triangle\r
-   *t = DOT(edge2, qvec);\r
-   inv_det = 1.0 / det;\r
-   *t *= inv_det;\r
-   *u *= inv_det;\r
-   *v *= inv_det;\r
-#else                    // the non-culling branch\r
-   if (det > -EPSILON && det < EPSILON)\r
-     return 0;\r
-   inv_det = 1.0 / det;\r
-\r
-   // calculate distance from vert0 to ray origin\r
-   SUB(tvec, orig, vert0);\r
-\r
-   // calculate U parameter and test bounds\r
-   *u = DOT(tvec, pvec) * inv_det;\r
-   if (*u < 0.0 || *u > 1.0)\r
-     return 0;\r
-\r
-   // prepare to test V parameter\r
-   CROSS(qvec, tvec, edge1);\r
-\r
-   // calculate V parameter and test bounds\r
-   *v = DOT(dir, qvec) * inv_det;\r
-   if (*v < 0.0 || *u + *v > 1.0)\r
-     return 0;\r
-\r
-   // calculate t, ray intersects triangle\r
-   *t = DOT(edge2, qvec) * inv_det;\r
-#endif\r
-   return 1;\r
-}\r
-*/\r
-\r
-int Triangle_Ray(float orig[3], float dir[3], bool bCullBack,\r
-                 float vert0[3], float vert1[3], float vert2[3],\r
-                 double *t, double *u, double *v)\r
-{\r
-  float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];\r
-  double det,inv_det;\r
-  \r
-  /* find vectors for two edges sharing vert0 */\r
-  VectorSubtract(vert1, vert0, edge1);\r
-  VectorSubtract(vert2, vert0, edge2);\r
-  \r
-  /* begin calculating determinant - also used to calculate U parameter */\r
-  CrossProduct(dir, edge2, pvec);\r
-  \r
-  /* if determinant is near zero, ray lies in plane of triangle */\r
-  det = DotProduct(edge1, pvec);\r
-  \r
-  if (bCullBack)\r
-  {\r
-    if (det < 0.000001)\r
-      return 0;\r
-    \r
-    // calculate distance from vert0 to ray origin\r
-    VectorSubtract(orig, vert0, tvec);\r
-    \r
-    // calculate U parameter and test bounds\r
-    *u = DotProduct(tvec, pvec);\r
-    if (*u < 0.0 || *u > det)\r
-      return 0;\r
-    \r
-    // prepare to test V parameter\r
-    CrossProduct(tvec, edge1, qvec);\r
-    \r
-    // calculate V parameter and test bounds\r
-    *v = DotProduct(dir, qvec);\r
-    if (*v < 0.0 || *u + *v > det)\r
-      return 0;\r
-    \r
-    // calculate t, scale parameters, ray intersects triangle\r
-    *t = DotProduct(edge2, qvec);\r
-    inv_det = 1.0 / det;\r
-    *t *= inv_det;\r
-    *u *= inv_det;\r
-    *v *= inv_det;\r
-  }\r
-  else\r
-  {\r
-    /* the non-culling branch */\r
-    if (det > -0.000001 && det < 0.000001)\r
-      return 0;\r
-    inv_det = 1.0 / det;\r
-    \r
-    /* calculate distance from vert0 to ray origin */\r
-    VectorSubtract(orig, vert0, tvec);\r
-    \r
-    /* calculate U parameter and test bounds */\r
-    *u = DotProduct(tvec, pvec) * inv_det;\r
-    if (*u < 0.0 || *u > 1.0)\r
-      return 0;\r
-    \r
-    /* prepare to test V parameter */\r
-    CrossProduct(tvec, edge1, qvec);\r
-    \r
-    /* calculate V parameter and test bounds */\r
-    *v = DotProduct(dir, qvec) * inv_det;\r
-    if (*v < 0.0 || *u + *v > 1.0)\r
-      return 0;\r
-    \r
-    /* calculate t, ray intersects triangle */\r
-    *t = DotProduct(edge2, qvec) * inv_det;\r
-  }\r
-  return 1;\r
-}\r
-\r
-bool Patch_Ray(patchMesh_t *patch, vec3_t origin, vec3_t dir, double *t, double *u, double *v)\r
-{\r
-       drawLists_t *drawLists;\r
-\r
-       drawLists_t::iterator iterLists, iterListsNext;\r
-       drawList_t::iterator i1, i2, i3, i4;\r
-\r
-//  vec3_t tris[2][3];\r
-  bool bIntersect = false;\r
-  float tBest = FLT_MAX;\r
-\r
-  if (patch->drawLists == NULL)\r
-    return false;\r
-\r
-  drawLists = (drawLists_t *)patch->drawLists;\r
-\r
-       iterListsNext=drawLists->begin();\r
-       iterListsNext++;\r
-       for (iterLists=drawLists->begin(); iterLists != drawLists->end() && iterListsNext != drawLists->end(); iterLists++, iterListsNext++)\r
-  {\r
-               // traverse two drawlists at once with two iterators each to triangulate\r
-    i1 = i3 = (*iterLists)->begin();\r
-    i2 = i4 = (*iterListsNext)->begin();\r
-    i3++;\r
-    i4++;\r
-               while (i3 != (*iterLists)->end() && i4 != (*iterListsNext)->end())\r
-               {\r
-      if (Triangle_Ray(origin, dir, false, (*i1).xyz, (*i2).xyz, (*i3).xyz, t, u, v))\r
-      {\r
-        bIntersect = true;\r
-        if (*t < tBest)\r
-          tBest = *t;\r
-      }      \r
-      if (Triangle_Ray(origin, dir, false, (*i3).xyz, (*i4).xyz, (*i2).xyz, t, u, v))\r
-      {\r
-        bIntersect = true;\r
-        if (*t < tBest)\r
-          tBest = *t;\r
-      }\r
-      i1++;\r
-      i2++;\r
-      i3++;\r
-      i4++;\r
-               }\r
-  }\r
-  if (bIntersect)\r
-  {\r
-    *t = tBest;\r
-    return true;\r
-  }\r
-  else\r
-  {\r
-    *t = 0;\r
-    return false;\r
-  }\r
-}\r
-\r
-// spog - curve LOD stuff ends\r
-\r
-/*\r
-=================\r
-DrawPatchMesh\r
-=================\r
-*/\r
-void DrawPatchMesh(patchMesh_t *pm)\r
-{\r
-  if (g_PrefsDlg.m_bDisplayLists)\r
-  {\r
-    if (pm->bDirty || pm->nListID <= 0 || pm->LODUpdated)\r
-    {\r
-      if (pm->nListID <= 0)\r
-        pm->nListID = qglGenLists(1);\r
-      if (pm->nListID > 0)\r
-      {\r
-        qglNewList(pm->nListID, GL_COMPILE_AND_EXECUTE);\r
-      }\r
-\r
-      Patch_DeleteDrawLists(pm);\r
-      Patch_CreateDrawLists(pm);\r
-       \r
-                 Patch_DrawLODPatchMesh(pm);\r
-\r
-      if (pm->nListID > 0)\r
-      {\r
-        qglEndList();\r
-           }\r
-\r
-           pm->bDirty = false;\r
-           pm->LODUpdated = false;\r
-    }\r
-    else\r
-    {\r
-      qglCallList(pm->nListID);\r
-    }\r
-  }\r
-  else\r
-  {\r
-    if (pm->bDirty || pm->LODUpdated)\r
-    {\r
-      Patch_DeleteDrawLists(pm);\r
-      Patch_CreateDrawLists(pm);\r
-      pm->bDirty = false;\r
-      pm->LODUpdated = false;\r
-    }\r
-         Patch_DrawLODPatchMesh(pm);\r
-  }\r
-}\r
-\r
-/*\r
-=================\r
-DrawPatchControls\r
-=================\r
-*/\r
-void DrawPatchControls(patchMesh_t *pm)\r
-{\r
-  int i, j;\r
-  bool bSelectedPoints[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; \r
\r
-  bool bOverlay = pm->bOverlay;\r
-\r
-  // bending\r
-  if (g_bPatchBendMode)\r
-  {\r
-    qglPointSize(6);\r
-    if (g_bPatchAxisOnRow)\r
-    {\r
-      qglColor3f(1, 0, 1);\r
-      if(!g_PrefsDlg.m_bGlPtWorkaround)\r
-      {\r
-        qglBegin(GL_POINTS);\r
-        for (i = 0; i < pm->width; i++)\r
-        {\r
-          qglVertex3fv(pm->ctrl[i][g_nPatchAxisIndex].xyz);\r
-        }\r
-        qglEnd();\r
-      }\r
-      else\r
-      {\r
-        qglLineWidth(2.0);\r
-        qglBegin(GL_LINES);\r
-        for(i = 0; i < pm->width; i++)\r
-        {\r
-          DrawAlternatePoint(pm->ctrl[i][g_nPatchAxisIndex].xyz, 0);\r
-        }\r
-        qglEnd();\r
-        qglLineWidth(1.0);\r
-      }                                \r
-      \r
-      if (g_nPatchBendState == BEND_SELECT_EDGE || g_nPatchBendState == BEND_BENDIT || g_nPatchBendState == BEND_SELECT_ORIGIN)\r
-      {\r
-        if(!g_PrefsDlg.m_bGlPtWorkaround)\r
-        {\r
-          qglColor3f(0, 0, 1);\r
-          qglBegin(GL_POINTS);\r
-          if (g_nPatchBendState == BEND_SELECT_ORIGIN)         \r
-          {\r
-            qglVertex3fv(g_vBendOrigin);\r
-          }\r
-          else         \r
-          {\r
-            for (i = 0; i < pm->width; i++)            \r
-            {\r
-              if (g_bPatchLowerEdge)                   \r
-              {\r
-                for (j = 0; j < g_nPatchAxisIndex; j++)\r
-                  qglVertex3fv(pm->ctrl[i][j].xyz);\r
-              }\r
-              else             \r
-              {\r
-                for (j = pm->height-1; j > g_nPatchAxisIndex; j--)\r
-                  qglVertex3fv(pm->ctrl[i][j].xyz);\r
-              }\r
-            }          \r
-          }\r
-          qglEnd();\r
-        }\r
-        else {\r
-          qglColor3f(0, 0, 1);\r
-          qglLineWidth(2.0);\r
-          qglBegin(GL_LINES);\r
-          if(g_nPatchBendState == BEND_SELECT_ORIGIN)                                  \r
-          {\r
-            DrawAlternatePoint(g_vBendOrigin, 0);\r
-          }\r
-          else                                 \r
-          {\r
-            for(i = 0; i < pm->width; i++)                                             \r
-            {\r
-              if(g_bPatchLowerEdge)                                                    \r
-              {\r
-                for(j = 0; j < g_nPatchAxisIndex; j++)\r
-                {\r
-                  DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);\r
-                }                                                      \r
-              }\r
-              else             \r
-              {\r
-                for (j = pm->height-1; j > g_nPatchAxisIndex; j--)                     \r
-                {\r
-                  DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);\r
-                }              \r
-              }                                                \r
-            }          \r
-          }\r
-          qglEnd();\r
-          qglLineWidth(1.0);\r
-        }\r
-      }\r
-    }\r
-    else\r
-    {\r
-      if(!g_PrefsDlg.m_bGlPtWorkaround)\r
-      {\r
-        qglColor3f(1, 0, 1);\r
-        qglBegin(GL_POINTS);\r
-        for (i = 0; i < pm->height; i++)\r
-        {\r
-          qglVertex3fv(pm->ctrl[g_nPatchAxisIndex][i].xyz);\r
-        }\r
-        qglEnd();\r
-      }\r
-      else {\r
-        qglColor3f(1, 0, 1);\r
-        qglLineWidth(2.0);\r
-        qglBegin(GL_LINES);\r
-        for(i = 0; i < pm->height; i++)\r
-        {\r
-          DrawAlternatePoint(pm->ctrl[g_nPatchAxisIndex][i].xyz, 0);\r
-        }\r
-        qglEnd();\r
-        qglLineWidth(1.0);\r
-      }\r
-      \r
-      if (g_nPatchBendState == BEND_SELECT_EDGE || g_nPatchBendState == BEND_BENDIT || g_nPatchBendState == BEND_SELECT_ORIGIN)\r
-      {\r
-        if(!g_PrefsDlg.m_bGlPtWorkaround)\r
-        {\r
-          qglColor3f(0, 0, 1);\r
-          qglBegin(GL_POINTS);\r
-          for (i = 0; i < pm->height; i++)\r
-          {\r
-            if (g_nPatchBendState == BEND_SELECT_ORIGIN)\r
-            {\r
-              qglVertex3fv(pm->ctrl[g_nBendOriginIndex][i].xyz);\r
-            }\r
-            else\r
-            {\r
-              if (g_bPatchLowerEdge)\r
-              {\r
-                for (j = 0; j < g_nPatchAxisIndex; j++)\r
-                  qglVertex3fv(pm->ctrl[j][i].xyz);\r
-              }\r
-              else\r
-              {\r
-                for (j = pm->width-1; j > g_nPatchAxisIndex; j--)\r
-                  qglVertex3fv(pm->ctrl[j][i].xyz);\r
-              }\r
-            }\r
-          }\r
-          qglEnd();\r
-        }\r
-        else {\r
-          qglColor3f(0, 0, 1);\r
-          qglLineWidth(2.0);\r
-          qglBegin(GL_LINES);\r
-          for(i = 0; i < pm->height; i++)\r
-          {\r
-            if(g_nPatchBendState == BEND_SELECT_ORIGIN)\r
-            {\r
-              DrawAlternatePoint(pm->ctrl[g_nBendOriginIndex][i].xyz, 0);\r
-            }\r
-            else\r
-            {\r
-              if(g_bPatchLowerEdge)\r
-              {\r
-                for(j = 0; j < g_nPatchAxisIndex; j++)\r
-                {\r
-                  DrawAlternatePoint(pm->ctrl[j][i].xyz, 0);\r
-                }\r
-              }\r
-              else\r
-              {\r
-                for(j = pm->width-1; j > g_nPatchAxisIndex; j--)\r
-                {\r
-                  DrawAlternatePoint(pm->ctrl[j][i].xyz, 0);\r
-                }\r
-              }\r
-            }\r
-          }\r
-          qglEnd();\r
-          qglLineWidth(1.0);\r
-        }\r
-      }\r
-    }\r
-  }\r
-  else \r
-  {\r
-    //qglDisable(GL_TEXTURE_2D); // stops point colours being multiplied by texture colour..\r
-    //draw CV lattice - could be made optional\r
-    //qglDisable( GL_CULL_FACE );\r
-    //    qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);\r
-    qglEnable (GL_POLYGON_OFFSET_LINE);\r
-    if (g_PrefsDlg.m_bNoStipple == FALSE)\r
-      qglDisable (GL_LINE_STIPPLE);\r
-    qglLineWidth (1);\r
-    qglColor3f(1.0f, 0.75f, 0.0f);\r
-    for ( i = 0 ; i+1 < pm->width ; i++ )\r
-    {\r
-      qglBegin(GL_QUAD_STRIP);\r
-      for ( j = 0 ; j < pm->height ; j++ ) \r
-      {\r
-        qglVertex3fv(pm->ctrl[i][j].xyz);\r
-        qglVertex3fv(pm->ctrl[i+1][j].xyz);\r
-      }\r
-      qglEnd();\r
-    }\r
-    qglDisable (GL_POLYGON_OFFSET_LINE);\r
-    //if (g_PrefsDlg.m_bNoStipple == FALSE)\r
-    //  qglEnable (GL_LINE_STIPPLE);\r
-    \r
-    // draw selection handles\r
-    if(!g_PrefsDlg.m_bGlPtWorkaround)\r
-    {\r
-      qglPointSize(6);\r
-      qglBegin(GL_POINTS);\r
-      for ( i = 0 ; i < pm->width ; i++ )\r
-      {\r
-        for ( j = 0 ; j < pm->height ; j++ ) \r
-        {\r
-          if (PointInMoveList(pm->ctrl[i][j].xyz) != -1)\r
-          {\r
-            bSelectedPoints[i][j] = true;\r
-          }\r
-          else\r
-          {    \r
-            bSelectedPoints[i][j] = false;\r
-            if (i & 0x01 || j & 0x01)\r
-              qglColor3f(1, 0, 1);\r
-            else\r
-              qglColor3f(0, 1, 0);\r
-            \r
-            qglVertex3fv(pm->ctrl[i][j].xyz);\r
-          }\r
-        }\r
-      }\r
-      qglColor3f(0, 0, 1);\r
-      for ( i = 0 ; i < pm->width ; i++ )\r
-      {\r
-        for ( j = 0 ; j < pm->height ; j++ ) \r
-        {\r
-          if (bSelectedPoints[i][j])\r
-            qglVertex3fv(pm->ctrl[i][j].xyz);\r
-        }\r
-      }\r
-      qglEnd();\r
-    }\r
-    else\r
-    {\r
-      qglLineWidth(2.0);\r
-      qglBegin(GL_LINES);\r
-      for(i = 0; i < pm->width; i++)\r
-      {\r
-        for(j = 0; j < pm->height; j++)\r
-        {\r
-          if(PointInMoveList(pm->ctrl[i][j].xyz) != -1)\r
-          {\r
-            bSelectedPoints[i][j] = true;\r
-          }\r
-          else\r
-          {\r
-            bSelectedPoints[i][j] = false;\r
-            if(i & 0x01 || j & 0x01)\r
-              qglColor3f(1, 0, 1);\r
-            else\r
-              qglColor3f(0, 1, 0);\r
-            \r
-            // draw verts\r
-            DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);\r
-          }\r
-        }\r
-      }\r
-      qglColor3f(0, 0, 1);\r
-      for(i = 0; i < pm->width; i++)\r
-      {\r
-        for(j = 0; j < pm->height; j++)\r
-        {\r
-          if(bSelectedPoints[i][j])\r
-          {\r
-            // draw verts\r
-            DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);\r
-          }\r
-        }\r
-      }\r
-      qglEnd();        \r
-      qglLineWidth(1.0);\r
-    }\r
-  }\r
-  if (bOverlay)\r
-  {\r
-    if(!g_PrefsDlg.m_bGlPtWorkaround)\r
-    {\r
-      qglPointSize(6);\r
-      qglBegin(GL_POINTS);\r
-      for ( i = 0 ; i < pm->width ; i++ )\r
-      {\r
-        for ( j = 0 ; j < pm->height ; j++ ) \r
-        {\r
-          if (i & 0x01 || j & 0x01)\r
-            qglColor3f(1, 0, 1);\r
-          else\r
-            qglColor3f(0, 1, 0);\r
-          qglVertex3fv(pm->ctrl[i][j].xyz);\r
-        }\r
-      }\r
-      qglEnd();\r
-    }\r
-    else\r
-    {\r
-      qglLineWidth(2.0);\r
-      qglBegin(GL_LINES);\r
-      for ( i = 0 ; i < pm->width ; i++ )\r
-      {\r
-        for ( j = 0 ; j < pm->height ; j++ ) \r
-        {\r
-          if (i & 0x01 || j & 0x01)\r
-            qglColor3f(1, 0, 1);\r
-          else\r
-            qglColor3f(0, 1, 0);\r
-          // draw verts\r
-          DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);\r
-        }\r
-      }\r
-      qglEnd();\r
-      qglLineWidth(1.0);\r
-    }\r
-  }\r
-  //qglPopAttrib();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_DrawXY\r
-==================\r
-*/\r
-void Patch_DrawXY(patchMesh_t *pm)\r
-{\r
-  qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);\r
-\r
-  if (pm->bSelected)\r
-  {\r
-    qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES]);\r
-    if (g_PrefsDlg.m_bNoStipple == FALSE)\r
-      qglEnable (GL_LINE_STIPPLE);\r
-    qglLineWidth (2);\r
-  }\r
-\r
-  DrawPatchMesh(pm);\r
-\r
-  if ( (pm->bSelected && (g_qeglobals.d_select_mode == sel_curvepoint\r
-    || g_qeglobals.d_select_mode == sel_area\r
-    || g_bPatchBendMode))\r
-    || pm->bOverlay )\r
-    DrawPatchControls(pm);\r
-}\r
-\r
-/*\r
-==================\r
-Patch_DrawCam\r
-==================\r
-*/\r
-void Patch_DrawCam(patchMesh_t *pm)\r
-{\r
-       qglPushAttrib(GL_ALL_ATTRIB_BITS); // save the current state\r
-\r
-  if (g_bPatchWireFrame)\r
-  {\r
-    qglDisable( GL_CULL_FACE );\r
-    qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);\r
-    qglDisable(GL_TEXTURE_2D);\r
-    if (g_PrefsDlg.m_bGLLighting)\r
-      qglDisable(GL_LIGHTING);\r
-\r
-    DrawPatchMesh(pm);\r
-\r
-    //if (g_PrefsDlg.m_bGLLighting)\r
-    //  qglEnable(GL_LIGHTING);\r
-    //qglEnable( GL_CULL_FACE );\r
-  }\r
-  else\r
-  {\r
-    qglDisable(GL_CULL_FACE);\r
-    qglBindTexture (GL_TEXTURE_2D, pm->d_texture->texture_number);\r
-    qglPolygonMode (GL_FRONT, GL_FILL);\r
-    qglPolygonMode (GL_BACK, GL_LINE);\r
-\r
-    if (pm->pShader->getTrans() < 1.0f)\r
-    {\r
-      qglEnable(GL_BLEND);\r
-      qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\r
-      qglColor4f(pm->d_texture->color[0], pm->d_texture->color[1], pm->d_texture->color[2], pm->pShader->getTrans());\r
-    }\r
-    \r
-    DrawPatchMesh(pm); // both sides\r
-  }\r
-\r
-  qglPopAttrib(); // restore saved state\r
-}\r
-\r
-void ConvexHullForSection( float section[2][4][7] ) {\r
-}\r
-\r
-void BrushesForSection( float section[2][4][7] ) {\r
-}\r
-\r
-/*\r
-================\r
-Patch_BuildPoints\r
-================\r
-*/\r
-void Patch_BuildPoints (brush_t *b) \r
-{\r
-       face_t          *f;\r
-       b->patchBrush = false;\r
-       for (f=b->brush_faces ; f ; f=f->next) \r
-  {\r
-               if (f->texdef.flags & SURF_PATCH) \r
-    {\r
-                       b->patchBrush = true;\r
-      //vec3_t vMin, vMax;\r
-      //Patch_CalcBounds(&patchMeshes[b->nPatchID], vMin, vMax);\r
-      //VectorCopy(vMin, b->mins);\r
-      //VectorCopy(vMax, b->maxs);\r
-                       break;\r
-               }\r
-       }\r
-}\r
-\r
-/*\r
-==================\r
-Patch_Move\r
-==================\r
-*/\r
-void Patch_Move(patchMesh_t *pm, const vec3_t vMove, bool bRebuild)\r
-{\r
-  pm->bDirty = true;\r
-  for (int w = 0; w < pm->width; w++)\r
-  {\r
-    for (int h = 0; h < pm->height; h++)\r
-    {\r
-      VectorAdd(pm->ctrl[w][h].xyz, vMove, pm->ctrl[w][h].xyz);\r
-    }\r
-  }\r
-  // bRebuild is never true\r
-  if (bRebuild)\r
-  {\r
-    vec3_t vMin, vMax;\r
-    Patch_CalcBounds(pm, vMin, vMax);\r
-    //Brush_RebuildBrush(patchMeshes[n].pSymbiot, vMin, vMax);\r
-  }\r
-  UpdatePatchInspector();\r
-\r
-}\r
-\r
-/*\r
-==================\r
-Patch_ApplyMatrix\r
-==================\r
-*/\r
-void Patch_ApplyMatrix(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vMatrix[3], bool bSnap)\r
-{\r
-       vec3_t vTemp;\r
-       \r
-       for (int w = 0; w < p->width; w++)\r
-       {\r
-               for (int h = 0; h < p->height; h++)\r
-               {\r
-                       if (((g_qeglobals.d_select_mode == sel_curvepoint && g_qeglobals.d_num_move_points != 0) || g_bPatchBendMode)\r
-                               && PointInMoveList(p->ctrl[w][h].xyz) == -1) // snap selected points only, if selected\r
-                               continue;\r
-                       VectorSubtract (p->ctrl[w][h].xyz, vOrigin, vTemp);\r
-                       for (int j = 0; j < 3; j++)\r
-                       {\r
-                               p->ctrl[w][h].xyz[j] = DotProduct(vTemp, vMatrix[j]) + vOrigin[j];\r
-                               if (bSnap)\r
-                               {\r
-                                       p->ctrl[w][h].xyz[j] = floor(p->ctrl[w][h].xyz[j] + 0.5);\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-       vec3_t vMin, vMax;\r
-       Patch_CalcBounds(p, vMin, vMax);\r
-       Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-}\r
-\r
-/*\r
-==================\r
-Patch_EditPatch\r
-==================\r
-*/\r
-void Patch_EditPatch()\r
-{\r
-  //--patchMesh_t* p = &patchMeshes[n];\r
-  g_qeglobals.d_numpoints = 0;\r
-  g_qeglobals.d_num_move_points = 0;\r
-       \r
-  for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-           patchMesh_t* p = pb->pPatch;\r
-           for ( int i = 0 ; i < p->width ; i++ ) \r
-      {\r
-                   for ( int j = 0 ; j < p->height ; j++ ) \r
-        {\r
-               VectorCopy (p->ctrl[i][j].xyz, g_qeglobals.d_points[g_qeglobals.d_numpoints]);\r
-          if (g_qeglobals.d_numpoints < MAX_POINTS-1)\r
-          {\r
-                 g_qeglobals.d_numpoints++;\r
-          }\r
-                   }\r
-      }\r
-    }\r
-  }\r
-  g_qeglobals.d_select_mode = sel_curvepoint;\r
-  //--g_nSelectedPatch = n;\r
-}\r
-\r
-\r
-\r
-/*\r
-==================\r
-Patch_Deselect\r
-==================\r
-*/\r
-//FIXME: need all sorts of asserts throughout a lot of this crap\r
-void Patch_Deselect()\r
-{\r
-  //--g_nSelectedPatch = -1;\r
-  g_qeglobals.d_select_mode = sel_brush;\r
-\r
-       for (brush_t *b = selected_brushes.next ; b != &selected_brushes ; b=b->next)\r
-  {\r
-    if (b->patchBrush)\r
-    {\r
-      b->pPatch->bSelected = false;\r
-    }\r
-  }\r
-\r
-  //for (int i = 0; i < numPatchMeshes; i++)\r
-  //  patchMeshes[i].bSelected = false;\r
-\r
-  if (g_bPatchBendMode)\r
-    Patch_BendToggle();\r
-//  if (g_bPatchInsertMode)\r
-//    Patch_InsDelToggle();\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_Select\r
-==================\r
-*/\r
-void Patch_Select(patchMesh_t *p)\r
-{\r
-  // maintained for point manip.. which i need to fix as this \r
-  // is pf error prone\r
-  //--g_nSelectedPatch = n;\r
-  p->bSelected = true;\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_Deselect\r
-==================\r
-*/\r
-void Patch_Deselect(patchMesh_t *p)\r
-{\r
-  p->bSelected = false;\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_Delete\r
-==================\r
-*/\r
-extern BTNode_t *BTree_Delete(BTNode_t *pBT);\r
-extern BTListList_t *BTree_DeleteListFromList(BTListList_t *pBTListList);\r
-\r
-void Patch_Delete(patchMesh_t *p)\r
-{\r
-  if (p->pSymbiot) // Hydra - added a check to prevent access violations.\r
-  {\r
-  p->pSymbiot->pPatch = NULL;\r
-  p->pSymbiot->patchBrush = false;\r
-  }\r
-\r
-  // spog - free dynamically allocated memory used by LODs\r
-  int rowcount = ((MAX_PATCH_WIDTH-1)/2) * MAX_PATCH_HEIGHT;\r
-       int colcount = ((MAX_PATCH_HEIGHT-1)/2) * MAX_PATCH_WIDTH;\r
-       int i;\r
-       for (i=0; i<rowcount; i++)\r
-               p->rowLOD[i] = BTree_Delete(p->rowLOD[i]);\r
-       for (i=0; i<colcount; i++)\r
-               p->colLOD[i] = BTree_Delete(p->colLOD[i]);\r
-\r
-  // delete display list associated with patch\r
-  if (p->nListID != -1)\r
-    qglDeleteLists (p->nListID, 1); // list#, number of lists\r
-  \r
-  // delete LOD drawLists\r
-  Patch_DeleteDrawLists(p);\r
-\r
-\r
-  free(p);\r
-  p = NULL;\r
-\r
-  \r
-  UpdatePatchInspector();\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_Scale\r
-==================\r
-*/\r
-void Patch_Scale(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vAmt, bool bRebuild)\r
-{\r
-\r
-  for (int w = 0; w < p->width; w++)\r
-  {\r
-    for (int h = 0; h < p->height; h++)\r
-    {\r
-      if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)\r
-        continue;\r
-                       for (int i=0 ; i<3 ; i++)\r
-                       {\r
-        p->ctrl[w][h].xyz[i] -= vOrigin[i];\r
-        p->ctrl[w][h].xyz[i] *= vAmt[i];\r
-        p->ctrl[w][h].xyz[i] += vOrigin[i];\r
-      }\r
-    }\r
-  }\r
-  if (bRebuild)\r
-  {\r
-    vec3_t vMin, vMax;\r
-    Patch_CalcBounds(p, vMin, vMax);\r
-    Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-  }\r
-  UpdatePatchInspector();\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_SetView\r
-==================\r
-*/\r
-void Patch_SetView(int n)\r
-{\r
-  g_bSameView = (n == g_nPatchClickedView);\r
-  g_nPatchClickedView = n;\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_SetTexture\r
-==================\r
-*/\r
-// FIXME: need array validation throughout\r
-void Patch_SetTexture(patchMesh_t *p, texdef_t *tex_def, IPluginTexdef* pPlugTexdef)\r
-{\r
-  // NOTE: I don't know for sure if this happens\r
-  if (p->pShader)\r
-    p->pShader->DecRef();\r
-  p->pShader = QERApp_Shader_ForName(tex_def->GetName());\r
-  p->pShader->IncRef();\r
-  p->d_texture = p->pShader->getTexture();\r
-\r
-  UpdatePatchInspector();\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_DragScale\r
-==================\r
-*/\r
-bool Patch_DragScale(patchMesh_t *p, vec3_t vAmt, vec3_t vMove)\r
-{\r
-  vec3_t vMin, vMax, vScale, vTemp, vMid;\r
-  int i;\r
-\r
-  Patch_CalcBounds(p, vMin, vMax);\r
-\r
-  VectorSubtract(vMax, vMin, vTemp);\r
-\r
-  // if we are scaling in the same dimension the patch has no depth\r
-  for (i = 0; i < 3; i ++)\r
-  {\r
-    if (vTemp[i] == 0 && vMove[i] != 0)\r
-    {\r
-      //Patch_Move(n, vMove, true);\r
-      return false;\r
-    }\r
-  }\r
-  \r
-  for (i=0 ; i<3 ; i++)\r
-    vMid[i] = (vMin[i] + ((vMax[i] - vMin[i]) / 2));\r
-\r
-  for (i = 0; i < 3; i++)\r
-  {\r
-    if (vAmt[i] != 0)\r
-    {\r
-      vScale[i] = 1.0 + vAmt[i] / vTemp[i];\r
-    }\r
-    else\r
-    {\r
-      vScale[i] = 1.0;\r
-    }\r
-  }\r
-\r
-  Patch_Scale(p, vMid, vScale, false);\r
-\r
-  VectorSubtract(vMax, vMin, vTemp);\r
-\r
-  Patch_CalcBounds(p, vMin, vMax);\r
-  \r
-  VectorSubtract(vMax, vMin, vMid);\r
-\r
-  VectorSubtract(vMid, vTemp, vTemp);\r
-\r
-  VectorScale(vTemp, 0.5, vTemp);\r
-\r
-  // abs of both should always be equal\r
-  if (!VectorCompare(vMove, vAmt))\r
-  {\r
-    for (i = 0; i < 3; i++)\r
-    {\r
-      if (vMove[i] != vAmt[i])\r
-        vTemp[i] = -(vTemp[i]);\r
-    }\r
-  }\r
-\r
-  Patch_Move(p, vTemp);\r
-  return true;\r
-}\r
-\r
-/*\r
-==================\r
-Patch_InsertColumn\r
-==================\r
-*/\r
-void Patch_InsertColumn(patchMesh_t *p, bool bAdd)\r
-{\r
-       int w, h, i, width;\r
-       vec3_t vTemp;\r
-       float stTemp[2];\r
-  \r
-       if (p->width + 2 >= MAX_PATCH_WIDTH)\r
-               return;\r
-\r
-       // check for selected column points\r
-       for (h = 0; h < p->height; h++)\r
-       {\r
-               for (w = 1; w < p->width; w+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (w < p->width)\r
-                       break;\r
-               for (w = 0; w < p->width; w+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (w < p->width)\r
-                       break;\r
-       }\r
-\r
-       if (w >= p->width)\r
-       {\r
-               if (bAdd) w=p->width-1;\r
-               else w=2;\r
-       }\r
-       else if (w==0) w=2;\r
-       else if (w%2) w++;\r
-\r
-       // add columns at w\r
-       for (h = 0; h < p->height; h++)\r
-       {\r
-               for (width = p->width-1; width > w; width--)\r
-                       memcpy(&p->ctrl[width+2][h],&p->ctrl[width][h], sizeof(drawVert_t));\r
-               \r
-               // set two new column points\r
-               memcpy(&p->ctrl[w+2][h],&p->ctrl[w][h], sizeof(drawVert_t));\r
-               memcpy(&p->ctrl[w+1][h],&p->ctrl[w-1][h], sizeof(drawVert_t));\r
-               \r
-               for (i=0; i<3; i++) // xyz\r
-               {\r
-                       vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w-1][h].xyz[i];\r
-                       p->ctrl[w+1][h].xyz[i] = p->ctrl[w+1][h].xyz[i] + (vTemp[i] / 2);\r
-                       \r
-                       vTemp[i] = p->ctrl[w-2][h].xyz[i] - p->ctrl[w-1][h].xyz[i];\r
-                       p->ctrl[w-1][h].xyz[i] = p->ctrl[w-1][h].xyz[i] + (vTemp[i] / 2);\r
-                       \r
-                       vTemp[i] = p->ctrl[w+1][h].xyz[i] - p->ctrl[w-1][h].xyz[i];\r
-                       p->ctrl[w][h].xyz[i] = p->ctrl[w-1][h].xyz[i] + (vTemp[i] / 2);\r
-               }\r
-               for (i=0; i<2; i++) // st\r
-               {\r
-                       stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w-1][h].st[i];\r
-                       p->ctrl[w+1][h].st[i] = p->ctrl[w+1][h].st[i] + (stTemp[i] / 2);\r
-                       \r
-                       stTemp[i] = p->ctrl[w-2][h].st[i] - p->ctrl[w-1][h].st[i];\r
-                       p->ctrl[w-1][h].st[i] = p->ctrl[w-1][h].st[i] + (stTemp[i] / 2);\r
-                       \r
-                       stTemp[i] = p->ctrl[w+1][h].st[i] - p->ctrl[w-1][h].st[i];\r
-                       p->ctrl[w][h].st[i] = p->ctrl[w-1][h].st[i] + (stTemp[i] / 2);\r
-               }\r
-       }\r
-\r
-       p->width += 2;\r
-       // deselect all points to keep things neat\r
-       if (g_qeglobals.d_select_mode == sel_curvepoint)\r
-               Patch_EditPatch();\r
-\r
-       UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_InsertRow\r
-==================\r
-*/\r
-\r
-void Patch_InsertRow(patchMesh_t *p, bool bAdd)\r
-{\r
-       int h, w, i, height;\r
-       vec3_t vTemp;\r
-       float stTemp[2];\r
-  \r
-       if (p->height + 2 >= MAX_PATCH_HEIGHT)\r
-               return;\r
-\r
-       // check for selected row points\r
-       for (w = 0; w < p->width; w++)\r
-       {\r
-               for (h = 1; h < p->height; h+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (h < p->height)\r
-                       break;\r
-               for (h = 0; h < p->height; h+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (h < p->height)\r
-                       break;\r
-       }\r
-       if (h >= p->height)\r
-       {\r
-               if (bAdd) h=p->height-1;\r
-               else h=2;\r
-       }\r
-       else if (h==0) h=2;\r
-       else if (h%2) h++;\r
-\r
-       // add rows at h\r
-       for (w = 0; w < p->width; w++)\r
-       {\r
-               for (height = p->height-1; height > h; height--)\r
-                       memcpy(&p->ctrl[w][height+2],&p->ctrl[w][height], sizeof(drawVert_t));\r
-               \r
-               // set two new row points\r
-               memcpy(&p->ctrl[w][h+2],&p->ctrl[w][h], sizeof(drawVert_t));\r
-               memcpy(&p->ctrl[w][h+1],&p->ctrl[w][h-1], sizeof(drawVert_t));\r
-               \r
-               for (i=0; i<3; i++) // xyz\r
-               {\r
-                       vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w][h-1].xyz[i];\r
-                       p->ctrl[w][h+1].xyz[i] = p->ctrl[w][h+1].xyz[i] + (vTemp[i] / 2);\r
-                       \r
-                       vTemp[i] = p->ctrl[w][h-2].xyz[i] - p->ctrl[w][h-1].xyz[i];\r
-                       p->ctrl[w][h-1].xyz[i] = p->ctrl[w][h-1].xyz[i] + (vTemp[i] / 2);\r
-                       \r
-                       vTemp[i] = p->ctrl[w][h+1].xyz[i] - p->ctrl[w][h-1].xyz[i];\r
-                       p->ctrl[w][h].xyz[i] = p->ctrl[w][h-1].xyz[i] + (vTemp[i] / 2);\r
-               }\r
-               for (i=0; i<2; i++) // st\r
-               {\r
-                       stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w][h-1].st[i];\r
-                       p->ctrl[w][h+1].st[i] = p->ctrl[w][h+1].st[i] + (stTemp[i] / 2);\r
-                       \r
-                       stTemp[i] = p->ctrl[w][h-2].st[i] - p->ctrl[w][h-1].st[i];\r
-                       p->ctrl[w][h-1].st[i] = p->ctrl[w][h-1].st[i] + (stTemp[i] / 2);\r
-                       \r
-                       stTemp[i] = p->ctrl[w][h+1].st[i] - p->ctrl[w][h-1].st[i];\r
-                       p->ctrl[w][h].st[i] = p->ctrl[w][h-1].st[i] + (stTemp[i] / 2);\r
-               }\r
-       }\r
-\r
-       p->height += 2;\r
-       // deselect all points to keep things neat\r
-       if (g_qeglobals.d_select_mode == sel_curvepoint)\r
-               Patch_EditPatch();\r
-\r
-       UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_RemoveRow\r
-==================\r
-*/\r
-void Patch_RemoveRow(patchMesh_t *p, bool bFirst)\r
-{\r
-       int w, h, i, height;\r
-       vec3_t vTemp;\r
-       float stTemp[2];\r
-       bool bExtrapolate = true;\r
-  \r
-       if (p->height <= MIN_PATCH_HEIGHT)\r
-               return;\r
-\r
-       for (w = 0; w < p->width; w++)\r
-       {\r
-               for (h = 0; h < p->height; h+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (h < p->height)\r
-                       break;\r
-               for (h = 1; h < p->height; h+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (h < p->height)\r
-                       break;\r
-       }\r
-\r
-       if (h >= p->height)\r
-       {\r
-               bExtrapolate = false;\r
-               if (bFirst) h=p->height-3;\r
-               else h=2;\r
-       }\r
-       else if (h <= 0) h=2;\r
-       else if (h > p->height-3) h = p->height-3;\r
-       else if (h%2) h++;\r
-       \r
-       p->height -= 2;\r
-\r
-       for (w = 0; w < p->width; w++)\r
-       {\r
-               if (bExtrapolate)\r
-               {\r
-                       for (i = 0; i < 3; i++) // xyz\r
-                       {\r
-                               vTemp[i] = p->ctrl[w][h+2].xyz[i] - p->ctrl[w][h-2].xyz[i];\r
-                               p->ctrl[w][h-1].xyz[i] = p->ctrl[w][h-2].xyz[i] + (vTemp[i] / 2);\r
-\r
-                               vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w][h-1].xyz[i];\r
-                               p->ctrl[w][h-1].xyz[i] = p->ctrl[w][h-1].xyz[i] + (vTemp[i] * 2);\r
-                       }\r
-\r
-                       for (i = 0; i < 2; i++) // st\r
-                       {\r
-                               stTemp[i] = p->ctrl[w][h+2].st[i] - p->ctrl[w][h-2].st[i];\r
-                               p->ctrl[w][h-1].st[i] = p->ctrl[w][h-2].st[i] + (stTemp[i] / 2);\r
-\r
-                               stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w][h-1].st[i];\r
-                               p->ctrl[w][h-1].st[i] = p->ctrl[w][h-1].st[i] + (stTemp[i] * 2);\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       if (!bFirst)\r
-                       continue;\r
-                       else h=0;\r
-               }\r
-               for (height = h; height < p->height; height++)\r
-                       memcpy(&p->ctrl[w][height], &p->ctrl[w][height+2], sizeof(drawVert_t));                 \r
-       }\r
-       // deselect all points to keep things neat\r
-       if (g_qeglobals.d_select_mode == sel_curvepoint)\r
-               Patch_EditPatch();\r
-       \r
-       UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_RemoveColumn\r
-==================\r
-*/\r
-void Patch_RemoveColumn(patchMesh_t *p, bool bFirst)\r
-{\r
-       int w, h, i, width;\r
-       vec3_t vTemp;\r
-       float stTemp[2];\r
-       bool bExtrapolate = true;\r
-  \r
-       if (p->width <= MIN_PATCH_WIDTH)\r
-               return;\r
-\r
-       for (h = 0; h < p->height; h++)\r
-       {\r
-               for (w = 0; w < p->width; w+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (w < p->width)\r
-                       break;\r
-               for (w = 1; w < p->width; w+=2)\r
-                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)\r
-                               break;\r
-               if (w < p->width)\r
-                       break;\r
-       }\r
-\r
-       if (w >= p->width)\r
-       {\r
-               bExtrapolate = false;\r
-               if (bFirst) w=p->width-3;\r
-               else w=2;\r
-       }\r
-       else if (w<=0) w=2;\r
-       else if (w > p->width-3) w = p->width-3;\r
-       else if (w%2) w++;\r
-       \r
-       p->width -= 2;\r
-\r
-       for (h = 0; h < p->height; h++)\r
-       {\r
-               if (bExtrapolate)\r
-               {\r
-                       for (i = 0; i < 3; i++) // xyz\r
-                       {\r
-                               vTemp[i] = p->ctrl[w+2][h].xyz[i] - p->ctrl[w-2][h].xyz[i];\r
-                               p->ctrl[w-1][h].xyz[i] = p->ctrl[w-2][h].xyz[i] + (vTemp[i] / 2);\r
-\r
-                               vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w-1][h].xyz[i];\r
-                               p->ctrl[w-1][h].xyz[i] = p->ctrl[w-1][h].xyz[i] + (vTemp[i] * 2);\r
-                       }\r
-\r
-                       for (i = 0; i < 2; i++) // st\r
-                       {\r
-                               stTemp[i] = p->ctrl[w+2][h].st[i] - p->ctrl[w-2][h].st[i];\r
-                               p->ctrl[w-1][h].st[i] = p->ctrl[w-2][h].st[i] + (stTemp[i] / 2);\r
-\r
-                               stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w-1][h].st[i];\r
-                               p->ctrl[w-1][h].st[i] = p->ctrl[w-1][h].st[i] + (stTemp[i] * 2);\r
-                       }\r
-               }\r
-               else\r
-               {\r
-                       if (!bFirst)\r
-                       continue;\r
-                       else w=0;\r
-               }\r
-               \r
-               for (width = w; width < p->width; width++)\r
-                       memcpy(&p->ctrl[width][h], &p->ctrl[width+2][h], sizeof(drawVert_t));                   \r
-       }\r
-       // deselect all points to keep things neat\r
-       if (g_qeglobals.d_select_mode == sel_curvepoint)\r
-               Patch_EditPatch();\r
-\r
-       UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_AdjustColumns\r
-==================\r
-*/\r
-/*\r
-void Patch_AdjustColumns(patchMesh_t *p, int nCols)\r
-{\r
-  vec3_t vTemp, vTemp2;\r
-  int i, w, h;\r
-\r
-  if (nCols & 0x01 || p->width + nCols < 3 || p->width + nCols > MAX_PATCH_WIDTH)\r
-    return;\r
-\r
-  // add in column adjustment\r
-  p->width += nCols;\r
-\r
-  for (h = 0; h < p->height; h++)\r
-  {\r
-    // for each column, we need to evenly disperse p->width number \r
-    // of points across the old bounds\r
-    \r
-    // calc total distance to interpolate \r
-    VectorSubtract(p->ctrl[p->width - 1 - nCols][h].xyz, p->ctrl[0][h].xyz, vTemp);\r
-\r
-    // amount per cycle\r
-    for (i = 0; i < 3; i ++)\r
-    {\r
-      vTemp2[i] = vTemp[i] / (p->width - 1);\r
-    }\r
-\r
-    // move along\r
-    for (w = 0; w < p->width-1; w++)\r
-    {\r
-      VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w+1][h].xyz);\r
-    }\r
-\r
-  }\r
-       for ( w = 0 ; w < p->width ; w++ ) \r
-  {\r
-               for ( h = 0 ; h < p->height ; h++ ) \r
-    {\r
-                       p->ctrl[w][h].st[0] = 4 * (float)w / (p->width - 1);\r
-                       p->ctrl[w][h].st[1] = 4 * (float)h / (p->height - 1);\r
-               }\r
-       }\r
-  UpdatePatchInspector();\r
-}\r
-*/\r
-\r
-/*\r
-==================\r
-Patch_AdjustRows\r
-==================\r
-*/\r
-/*\r
-void Patch_AdjustRows(patchMesh_t *p, int nRows)\r
-{\r
-  vec3_t vTemp, vTemp2;\r
-  int i, w, h;\r
-\r
-  if (nRows & 0x01 || p->height + nRows < 3 || p->height + nRows > MAX_PATCH_HEIGHT)\r
-    return;\r
-\r
-  // add in column adjustment\r
-  p->height += nRows;\r
-\r
-  for (w = 0; w < p->width; w++)\r
-  {\r
-    // for each row, we need to evenly disperse p->height number \r
-    // of points across the old bounds\r
-\r
-    // calc total distance to interpolate \r
-    VectorSubtract(p->ctrl[w][p->height - 1 - nRows].xyz, p->ctrl[w][0].xyz, vTemp);\r
-    \r
-    //vTemp[0] = vTemp[1] = vTemp[2] = 0;\r
-    //for (h = 0; h < p->height - nRows; h ++)\r
-    //{\r
-    //  VectorAdd(vTemp, p->ctrl[w][h], vTemp);\r
-    //}\r
-\r
-    // amount per cycle\r
-    for (i = 0; i < 3; i ++)\r
-    {\r
-      vTemp2[i] = vTemp[i] / (p->height - 1);\r
-    }\r
-\r
-    // move along\r
-    for (h = 0; h < p->height-1; h++)\r
-    {\r
-      VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);\r
-    }\r
-\r
-  }\r
-       for ( w = 0 ; w < p->width ; w++ ) \r
-  {\r
-               for ( h = 0 ; h < p->height ; h++ ) \r
-    {\r
-                       p->ctrl[w][h].st[0] = 4 * (float)w / (p->width - 1);\r
-                       p->ctrl[w][h].st[1] = 4 * (float)h / (p->height - 1);\r
-               }\r
-       }\r
-  UpdatePatchInspector();\r
-}\r
-*/\r
-\r
-/*\r
-==================\r
-Patch_DisperseRows\r
-==================\r
-*/\r
-\r
-void Patch_DisperseRows()\r
-{\r
-       vec3_t vTemp, vTemp2;\r
-       int i, w, h;\r
-       \r
-       \r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-     if (pb->patchBrush)\r
-     {\r
-       patchMesh_t *p = pb->pPatch;\r
-       Patch_Rebuild(p);\r
-       for (w = 0; w < p->width; w++)\r
-       {\r
-         // for each row, we need to evenly disperse p->height number \r
-         // of points across the old bounds\r
\r
-         // calc total distance to interpolate \r
-         VectorSubtract(p->ctrl[w][p->height - 1].xyz, p->ctrl[w][0].xyz, vTemp);\r
-     \r
-         //vTemp[0] = vTemp[1] = vTemp[2] = 0;\r
-         //for (h = 0; h < p->height - nRows; h ++)\r
-         //{\r
-         //  VectorAdd(vTemp, p->ctrl[w][h], vTemp);\r
-         //}\r
\r
-         // amount per cycle\r
-         for (i = 0; i < 3; i ++)\r
-         {\r
-           vTemp2[i] = vTemp[i] / (p->height - 1);\r
-         }\r
\r
-         // move along\r
-         for (h = 0; h < p->height-1; h++)\r
-         {\r
-           VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);\r
-         }\r
-         Patch_Naturalize(p);\r
\r
-       }\r
-     }\r
-   }\r
-               UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_DisperseIntermediateRows\r
-==================\r
-*/\r
-\r
-void Patch_DisperseIntermediateRows()\r
-{\r
-       vec3_t vTemp, vTemp2;\r
-       int i, w, h;\r
-       \r
-       \r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-               if (pb->patchBrush)\r
-               {\r
-                       patchMesh_t *p = pb->pPatch;\r
-                       Patch_Rebuild(p);\r
-                       for (w = 0; w < p->width; w++)\r
-                       {\r
-                               // move along\r
-                               for (h = 0; h < p->height; h+=2)\r
-                               {\r
-                                       // calc distance to interpolate \r
-                                       VectorSubtract(p->ctrl[w][h+2].xyz, p->ctrl[w][h].xyz, vTemp);\r
-                                       \r
-                                       // halve distance\r
-                                       for (i = 0; i < 3; i ++)\r
-                                       {\r
-                                               vTemp2[i] = vTemp[i] / 2;\r
-                                       }\r
-                                       \r
-                                       // move control points\r
-                                       VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-       UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_DisperseIntermediateColumns\r
-==================\r
-*/\r
-void Patch_DisperseIntermediateColumns()\r
-{\r
-       vec3_t vTemp, vTemp2;\r
-       int i, w, h;\r
-       \r
-       \r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-               if (pb->patchBrush)\r
-               {\r
-                       patchMesh_t *p = pb->pPatch;\r
-                       Patch_Rebuild(p);\r
-                       for (h = 0; h < p->height; h++)\r
-                       {\r
-                                       // move along\r
-                               for (w = 0; w < p->width; w+=2)\r
-                               {\r
-                                       // calc distance to interpolate \r
-                                       VectorSubtract(p->ctrl[w+2][h].xyz, p->ctrl[w][h].xyz, vTemp);\r
-                                       \r
-                                       // halve distance\r
-                                       for (i = 0; i < 3; i ++)\r
-                                       {\r
-                                               vTemp2[i] = vTemp[i] / 2;\r
-                                       }\r
-                                       \r
-                                       // move control points\r
-                                       VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w+1][h].xyz);\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-       UpdatePatchInspector();\r
-}\r
-\r
-\r
-\r
-/*\r
-==================\r
-Patch_AdjustSelected\r
-==================\r
-*/\r
-void Patch_AdjustSelected(bool bInsert, bool bColumn, bool bFlag)\r
-{\r
-  bool bUpdate = false;\r
-       for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      if (bInsert)\r
-      {\r
-        if (bColumn)\r
-        {\r
-          Patch_InsertColumn(pb->pPatch, bFlag);\r
-        }\r
-        else\r
-        {\r
-          Patch_InsertRow(pb->pPatch, bFlag);\r
-        }\r
-      }\r
-      else\r
-      {\r
-        if (bColumn)\r
-        {\r
-          Patch_RemoveColumn(pb->pPatch, bFlag);\r
-        }\r
-        else\r
-        {\r
-          Patch_RemoveRow(pb->pPatch, bFlag);\r
-        }\r
-      }\r
-      bUpdate = true;\r
-      vec3_t vMin, vMax;\r
-      patchMesh_t *p = pb->pPatch;\r
-      Patch_CalcBounds(p, vMin, vMax);\r
-      Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-      pb->pPatch->bDirty = true; // rebuild LOD trees and their normals\r
-    }\r
-  }\r
-  if (bUpdate)\r
-  {\r
-    Sys_UpdateWindows(W_ALL);\r
-  }\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_AdjustSelectedRowCols\r
-==================\r
-*/\r
-/*\r
-void Patch_AdjustSelectedRowCols(int nRows, int nCols)\r
-{\r
-       for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      Patch_InsertColumn(pb->pPatch, false);\r
-      if (nRows != 0)\r
-      {\r
-        Patch_AdjustRows(pb->pPatch, nRows);\r
-      }\r
-      \r
-      if (nCols != 0)\r
-      {\r
-        Patch_AdjustColumns(pb->pPatch, nCols);\r
-      }\r
-               }\r
-  }\r
-  UpdatePatchInspector();\r
-}\r
-*/\r
-\r
-/*\r
-=================\r
-CheckName\r
-temporary stuff, detect potential problems when saving the texture name\r
-will correct the patch on the fly if problem detected\r
-=================\r
-*/\r
-/*!\r
-\todo performance issue with CheckName calls\r
-don't call this too much, only when absolutely necessary\r
-strategies that call here too much are known to be slow\r
-patch 84 to bug 253 adds an additionnal check for textures/\r
-*/\r
-void CheckName( patchMesh_t *p, char *pname )\r
-{\r
-  if(strncmp(p->pShader->getName(), "textures/", 9) != 0)\r
-    p->pShader = QERApp_Shader_ForName(SHADER_NOT_FOUND);\r
-\r
-       // some manage to get long filename textures (with spaces) in their maps\r
-       if (strchr( p->pShader->getName(), ' ' ))\r
-       {\r
-               char Msg1[1024];\r
-               sprintf( Msg1, "Can't save texture with spaces in name. Rename %s\nNOTE: This message may popup several times .. once for each buggy face detected.", p->pShader->getName() );\r
-               Sys_Printf("%s\n", Msg1 );\r
-               gtk_MessageBox(g_pParentWnd->m_pWidget, Msg1, "Error saving map", MB_OK );\r
-               strcpy( pname, SHADER_NOT_FOUND );\r
-               p->pShader = QERApp_Shader_ForName(SHADER_NOT_FOUND);\r
-    p->d_texture = p->pShader->getTexture();\r
-               return;\r
-       }\r
-       strcpy( pname, p->pShader->getName()+9 ); // remove "textures/"\r
-}\r
-\r
-/*\r
-==================\r
-Patch_Write \r
-==================\r
-*/\r
-void Patch_Write (patchMesh_t *p, MemStream *file)\r
-{\r
-  char pname[1024];\r
-\r
-  MemFile_fprintf(file, " {\n  patchDef2\n  {\n");\r
-\r
-  CheckName( p, pname );\r
-  MemFile_fprintf(file, "   %s\n", pname );\r
-  MemFile_fprintf(file, "   ( %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value);\r
-\r
-\r
-       float           ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];\r
-\r
-  int w, h;\r
-  for (w = 0; w < p->width; w++)\r
-  {\r
-    for (h = 0; h < p->height; h++)\r
-    {\r
-      ctrl[w][h][0] = p->ctrl[w][h].xyz[0];\r
-      ctrl[w][h][1] = p->ctrl[w][h].xyz[1];\r
-      ctrl[w][h][2] = p->ctrl[w][h].xyz[2];\r
-      ctrl[w][h][3] = p->ctrl[w][h].st[0];\r
-      ctrl[w][h][4] = p->ctrl[w][h].st[1];\r
-    }\r
-  }\r
-\r
-  _Write3DMatrix(file, p->width, p->height, 5, reinterpret_cast<float*>(&ctrl));\r
-\r
-       if (g_qeglobals.m_bBrushPrimitMode)\r
-  {\r
-         if (p->epairs)\r
-    {\r
-                       for (epair_t *ep = p->epairs ; ep ; ep=ep->next)\r
-      {\r
-                               MemFile_fprintf (file, "\"%s\" \"%s\"\n", ep->key, ep->value);\r
-      }\r
-    }\r
-  }\r
-\r
-  MemFile_fprintf(file, "  }\n }\n");\r
-}\r
-\r
-void Patch_Write (patchMesh_t *p, FILE *file)\r
-{\r
-  char pname[1024];\r
-\r
-       fprintf(file, " {\n  patchDef2\n  {\n");\r
-  {\r
-         CheckName( p, pname );\r
-         fprintf(file, "   %s\n", pname );\r
-         fprintf(file, "   ( %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value);\r
-       }\r
-\r
-       float           ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];\r
-\r
-  int w, h;\r
-  for (w = 0; w < p->width; w++)\r
-  {\r
-    for (h = 0; h < p->height; h++)\r
-    {\r
-      ctrl[w][h][0] = p->ctrl[w][h].xyz[0];\r
-      ctrl[w][h][1] = p->ctrl[w][h].xyz[1];\r
-      ctrl[w][h][2] = p->ctrl[w][h].xyz[2];\r
-      ctrl[w][h][3] = p->ctrl[w][h].st[0];\r
-      ctrl[w][h][4] = p->ctrl[w][h].st[1];\r
-    }\r
-  }\r
-\r
-  _Write3DMatrix(file, p->width, p->height, 5, reinterpret_cast<float*>(&ctrl));\r
-\r
-       if (g_qeglobals.m_bBrushPrimitMode)\r
-  {\r
-         if (p->epairs)\r
-    {\r
-                       for (epair_t *ep = p->epairs ; ep ; ep=ep->next)\r
-      {\r
-                               fprintf (file, "\"%s\" \"%s\"\n", ep->key, ep->value);\r
-      }\r
-    }\r
-  }\r
-\r
-  fprintf(file, "  }\n }\n");\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_RotateTexture\r
-==================\r
-*/\r
-void Patch_RotateTexture(patchMesh_t *p, float fAngle)\r
-{\r
-  p->bDirty = true;\r
-  float c = cos(fAngle * Q_PI / 180);\r
-  float s = sin(fAngle * Q_PI / 180);\r
-\r
-  Patch_TransformLODTexture(p, c, s, ROTATE);\r
-\r
-  for (int w = 0; w < p->width; w++)\r
-  {\r
-    for (int h = 0; h < p->height; h++)\r
-    {\r
-      //if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)\r
-      //  continue;\r
-\r
-      float x = p->ctrl[w][h].st[0];\r
-      float y = p->ctrl[w][h].st[1];\r
-      p->ctrl[w][h].st[0] = x * c - y * s;\r
-      p->ctrl[w][h].st[1] = y * c + x * s;\r
-    }\r
-  }\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_ScaleTexture\r
-==================\r
-*/\r
-void Patch_ScaleTexture(patchMesh_t *p, float fx, float fy, bool bFixup)\r
-{\r
-  // FIXME:\r
-  // this hack turns scales into 1.1 or 0.9\r
-  if (bFixup)\r
-  {\r
-    fx = (fx == 0) ? 1.0 : (fx > 0) ? 0.9 : 1.10;\r
-    fy = (fy == 0) ? 1.0 : (fy > 0) ? 0.9 : 1.10;\r
-  }\r
-  else\r
-  {\r
-    if (fx == 0)\r
-      fx = 1.0;\r
-    if (fy == 0)\r
-      fy = 1.0;\r
-  }\r
-  \r
-  for (int w = 0; w < p->width; w++)\r
-  {\r
-    for (int h = 0; h < p->height; h++)\r
-    {\r
-      if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)\r
-        continue;\r
-\r
-      p->ctrl[w][h].st[0] *= fx;\r
-      p->ctrl[w][h].st[1] *= fy;\r
-    }\r
-  }\r
-  if (g_qeglobals.d_select_mode == sel_curvepoint)\r
-  {\r
-         p->bDirty = true;\r
-         Patch_LODMatchAll();\r
-  }\r
-  else\r
-  {\r
-    Patch_TransformLODTexture(p, fx, fy, SCALE);\r
-         p->LODUpdated = true;\r
-  }\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_ShiftTexture\r
-shift a texture given a pixel count\r
-==================\r
-*/\r
-void Patch_ShiftTexture(patchMesh_t *p, float fx, float fy)\r
-{\r
-       qtexture_t *pTex;\r
-       pTex = p->pShader->getTexture();\r
-       fx = -1 * fx / pTex->width;\r
-       fy = fy / pTex->height;\r
-       Patch_ShiftTextureST(p, fx, fy);\r
-}\r
-\r
-/*\r
-====================\r
-Patch_ShiftTextureST\r
-shift a patch texture given an ST increment\r
-====================\r
-*/\r
-void Patch_ShiftTextureST(patchMesh_t *p, float fx, float fy)\r
-{\r
-#ifdef _DEBUG\r
-       // NOTE: when called by Patch_ShiftTexture this warning may be bogus\r
-       if ((ABS(fx) >= 1) || (ABS(fy) >= 1))\r
-               Sys_Printf("WARNING: increments exceed 1 in Patch_ShiftTextureST\n");\r
-#endif\r
-  for (int w = 0; w < p->width; w++)\r
-  {\r
-    for (int h = 0; h < p->height; h++)\r
-    {\r
-      if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)\r
-        continue;\r
-\r
-      p->ctrl[w][h].st[0] += fx;\r
-      p->ctrl[w][h].st[1] += fy;\r
-    }\r
-  }\r
-  if (g_qeglobals.d_select_mode == sel_curvepoint)\r
-  {\r
-         p->bDirty = true;\r
-         Patch_LODMatchAll();\r
-  }\r
-  else\r
-  {\r
-         Patch_TransformLODTexture(p, fx, fy, TRANSLATE);\r
-         p->LODUpdated = true;\r
-  }\r
-}\r
-\r
-/*\r
-==================\r
-Patch_ToggleInverted\r
-==================\r
-*/\r
-void Patch_ToggleInverted()\r
-{\r
-  bool bUpdate = false;\r
-\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      bUpdate = true;\r
-      patchInvert(pb->pPatch);\r
-    }\r
-  }\r
-\r
-  if (bUpdate)\r
-  {\r
-    Sys_UpdateWindows(W_ALL);\r
-  }\r
-  UpdatePatchInspector();\r
-}\r
-\r
-/*\r
-==================\r
-Patch_ToggleInverted\r
-==================\r
-*/\r
-void Patch_InvertTexture(bool bY)\r
-{\r
-  bool bUpdate = false;\r
-\r
-  float fTemp[2];\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      bUpdate = true;\r
-      patchMesh_t *p = pb->pPatch;\r
-      p->bDirty = true;\r
-      if (bY)\r
-      {\r
-             for ( int i = 0 ; i < p->height ; i++ ) \r
-        {\r
-          for (int j = 0; j < p->width / 2; j++)\r
-          {\r
-            memcpy(fTemp, &p->ctrl[p->width - 1- j][i].st[0], sizeof (float[2]));\r
-            memcpy(&p->ctrl[p->width - 1- j][i].st[0], &p->ctrl[j][i].st[0], sizeof(float[2]));\r
-            memcpy(&p->ctrl[j][i].st[0], fTemp, sizeof(float[2]));\r
-                     }\r
-             }\r
-      }\r
-      else\r
-      {\r
-             for ( int i = 0 ; i < p->width ; i++ ) \r
-        {\r
-          for (int j = 0; j < p->height / 2; j++)\r
-          {\r
-            memcpy(fTemp, &p->ctrl[i][p->height - 1- j].st[0], sizeof (float[2]));\r
-            memcpy(&p->ctrl[i][p->height - 1 - j].st[0], &p->ctrl[i][j].st[0], sizeof(float[2]));\r
-            memcpy(&p->ctrl[i][j].st[0], fTemp, sizeof(float[2]));\r
-                     }\r
-             }\r
-      }\r
-    }\r
-  }\r
-\r
-  if (bUpdate)\r
-  {\r
-    Sys_UpdateWindows(W_ALL);\r
-  }\r
-  UpdatePatchInspector();\r
-}\r
-\r
-\r
-\r
-\r
-/*\r
-==================\r
-Patch_Save\r
-==================\r
- Saves patch ctrl info (originally to deal with a \r
- cancel in the surface dialog\r
-*/\r
-void Patch_Save(patchMesh_t *p)\r
-{\r
-  patchSave.width = p->width;\r
-  patchSave.height = p->height;\r
-  memcpy(patchSave.ctrl, p->ctrl, sizeof(p->ctrl));\r
-}\r
-\r
-\r
-/*\r
-==================\r
-Patch_Restore\r
-==================\r
-*/\r
-void Patch_Restore(patchMesh_t *p)\r
-{\r
-  p->width = patchSave.width;\r
-  p->height = patchSave.height;\r
-  memcpy(p->ctrl, patchSave.ctrl, sizeof(p->ctrl));\r
-}\r
-\r
-void Patch_ResetTexturing(float fx, float fy)\r
-{\r
-       for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      patchMesh_t *p = pb->pPatch;\r
-      p->bDirty = true;\r
-           for ( int i = 0 ; i < p->width ; i++ ) \r
-      {\r
-                   for ( int j = 0 ; j < p->height ; j++ ) \r
-        {\r
-                           p->ctrl[i][j].st[0] = fx * (float)i / (p->width - 1);\r
-                           p->ctrl[i][j].st[1] = 1 - fy * (float)j / (p->height - 1);\r
-                   }\r
-           }\r
-    }\r
-  }\r
-}\r
-\r
-// NOTE TTimo stub!\r
-void Patch_FitTexturing()\r
-{\r
-  Patch_ResetTexturing(1.0f, 1.0f);\r
-}\r
-\r
-void Patch_SetTextureInfo(texdef_t *pt)\r
-{\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      if (pt->rotate)\r
-        Patch_RotateTexture(pb->pPatch, pt->rotate);\r
-\r
-      if (pt->shift[0] || pt->shift[1])\r
-        Patch_ShiftTexture(pb->pPatch, pt->shift[0], pt->shift[1]);\r
-\r
-      if (pt->scale[0] || pt->scale[1])\r
-        Patch_ScaleTexture(pb->pPatch, pt->scale[0], pt->scale[1], false);\r
-\r
-      patchMesh_t *p = pb->pPatch;\r
-      p->contents = pt->contents;\r
-      p->flags = pt->flags;\r
-      p->value = pt->value;\r
-    }\r
-  }\r
-}\r
-\r
-bool OnlyPatchesSelected()\r
-{\r
-  if (g_ptrSelectedFaces.GetSize() > 0 || selected_brushes.next == &selected_brushes)\r
-    return false;\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (!pb->patchBrush)\r
-    {\r
-      return false;\r
-    }\r
-  }\r
-  return true;\r
-}\r
-\r
-bool AnyPatchesSelected()\r
-{\r
-  if (g_ptrSelectedFaces.GetSize() > 0  || selected_brushes.next == &selected_brushes)\r
-    return false;\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      return true;\r
-    }\r
-  }\r
-  return false;\r
-}\r
-\r
-patchMesh_t* SinglePatchSelected()\r
-{\r
-  if (selected_brushes.next->patchBrush)\r
-  {\r
-    return selected_brushes.next->pPatch;\r
-  }\r
-  return NULL;\r
-}\r
-\r
-void Patch_BendToggle()\r
-{\r
-  if (g_bPatchBendMode)\r
-  {\r
-    g_bPatchBendMode = false;\r
-    HideInfoDialog();\r
-    g_pParentWnd->UpdatePatchToolbarButtons() ;\r
-    return;\r
-  }\r
-\r
-       brush_t* b = selected_brushes.next;\r
-\r
-  if (!QE_SingleBrush(true) || !b->patchBrush)\r
-  {\r
-    Sys_Printf("Patch_BendToggle: you must have a single patch selected\n");\r
-               return;\r
-  }\r
-\r
-  Patch_Save(b->pPatch);\r
-       g_bPatchBendMode = true;\r
-  g_nPatchBendState = BEND_SELECT_ROTATION;\r
-  g_bPatchAxisOnRow = true;\r
-  g_nPatchAxisIndex = 1;\r
-  ShowInfoDialog(g_pBendStateMsg[BEND_SELECT_ROTATION]);\r
-}\r
-\r
-void Patch_BendHandleTAB()\r
-{\r
-  if (!g_bPatchBendMode)\r
-  {\r
-    return;\r
-  }\r
-\r
-       brush_t* b = selected_brushes.next;\r
-  if (!QE_SingleBrush() || !b->patchBrush)\r
-  {\r
-    Patch_BendToggle();\r
-    Sys_Printf("No patch to bend!");\r
-               return;\r
-  }\r
-\r
-  patchMesh_t *p = b->pPatch;\r
-\r
-  bool bShift = Sys_ShiftDown ();\r
-\r
-  if (g_nPatchBendState == BEND_SELECT_ROTATION)\r
-  {\r
-    // only able to deal with odd numbered rows/cols\r
-    g_nPatchAxisIndex += (bShift) ? -2 : 2;\r
-    if (g_bPatchAxisOnRow)\r
-    {\r
-      if ((bShift) ? g_nPatchAxisIndex <= 0 : g_nPatchAxisIndex >= p->height)\r
-      {\r
-        g_bPatchAxisOnRow = false;\r
-        g_nPatchAxisIndex = (bShift) ? p->width-1 : 1;\r
-      }\r
-    }\r
-    else\r
-    {\r
-      if ((bShift) ? g_nPatchAxisIndex <= 0 : g_nPatchAxisIndex >= p->width)\r
-      {\r
-        g_bPatchAxisOnRow = true;\r
-        g_nPatchAxisIndex = (bShift) ? p->height-1 : 1;\r
-      }\r
-    }\r
-  }\r
-  else\r
-  if (g_nPatchBendState == BEND_SELECT_ORIGIN)\r
-  {\r
-    g_nBendOriginIndex += (bShift) ? -1 : 1;\r
-    if (g_bPatchAxisOnRow)\r
-    {\r
-      if (bShift)\r
-      {\r
-        if (g_nBendOriginIndex < 0)\r
-          g_nBendOriginIndex = p->width-1;\r
-      }\r
-      else\r
-      {\r
-        if (g_nBendOriginIndex > p->width-1)\r
-          g_nBendOriginIndex = 0;\r
-      }\r
-      VectorCopy(p->ctrl[g_nBendOriginIndex][g_nPatchAxisIndex].xyz, g_vBendOrigin);\r
-    }\r
-    else\r
-    {\r
-      if (bShift)\r
-      {\r
-        if (g_nBendOriginIndex < 0)\r
-          g_nBendOriginIndex = p->height-1;\r
-      }\r
-      else\r
-      {\r
-        if (g_nBendOriginIndex > p->height-1)\r
-          g_nBendOriginIndex = 0;\r
-      }\r
-      VectorCopy(p->ctrl[g_nPatchAxisIndex][g_nBendOriginIndex].xyz, g_vBendOrigin);\r
-    }\r
-  }\r
-  else\r
-  if (g_nPatchBendState == BEND_SELECT_EDGE)\r
-  {\r
-    g_bPatchLowerEdge ^= 1;\r
-  }\r
-  Sys_UpdateWindows(W_ALL);\r
-}\r
-\r
-void Patch_BendHandleENTER()\r
-{\r
-  if (!g_bPatchBendMode)\r
-  {\r
-    return;\r
-  }\r
-\r
-  if (g_nPatchBendState  < BEND_BENDIT)\r
-  {\r
-    g_nPatchBendState++;\r
-    ShowInfoDialog(g_pBendStateMsg[g_nPatchBendState]);\r
-    if (g_nPatchBendState == BEND_SELECT_ORIGIN)\r
-    {\r
-      g_vBendOrigin[0] = g_vBendOrigin[1] = g_vBendOrigin[2] = 0;\r
-      g_nBendOriginIndex = 0;\r
-      Patch_BendHandleTAB();\r
-    }\r
-    else\r
-    if (g_nPatchBendState == BEND_SELECT_EDGE)\r
-    {\r
-      g_bPatchLowerEdge = true;\r
-    }\r
-    else\r
-    if (g_nPatchBendState == BEND_BENDIT)\r
-    {\r
-      // basically we go into rotation mode, set the axis to the center of the \r
-    }\r
-  }\r
-  else\r
-  {\r
-    // done\r
-    Patch_BendToggle();\r
-  }\r
-  Sys_UpdateWindows(W_ALL);\r
-\r
-}\r
-\r
-\r
-void Patch_BendHandleESC()\r
-{\r
-  if (!g_bPatchBendMode)\r
-  {\r
-    return;\r
-  }\r
-  Patch_BendToggle();\r
-       brush_t* b = selected_brushes.next;\r
-  if (QE_SingleBrush() && b->patchBrush)\r
-  {\r
-    Patch_Restore(b->pPatch);\r
-  }\r
-  Sys_UpdateWindows(W_ALL);\r
-}\r
-\r
-void Patch_SetBendRotateOrigin(patchMesh_t *p)\r
-{\r
-#if 1\r
-  int nType = g_pParentWnd->ActiveXY()->GetViewType();\r
-  int nDim3 = (nType == XY) ? 2 : (nType == YZ) ? 0 : 1;\r
-\r
-  g_vBendOrigin[nDim3] = 0;\r
-  VectorCopy(g_vBendOrigin, g_pParentWnd->ActiveXY()->RotateOrigin());\r
-  return;\r
-#else\r
-  int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;\r
-  int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;\r
-\r
-  float fxLo, fyLo, fxHi, fyHi;\r
-  fxLo = fyLo = 9999;\r
-  fxHi = fyHi = -9999;\r
-\r
-  if (g_bPatchAxisOnRow)\r
-  {\r
-    for (int i = 0; i < p->width; i++)\r
-    {\r
-      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1] < fxLo)\r
-        fxLo = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1];\r
-\r
-      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1] > fxHi)\r
-        fxHi = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1];\r
-\r
-      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2] < fyLo)\r
-        fyLo = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2];\r
-\r
-      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2] > fyHi)\r
-        fyHi = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2];\r
-    }\r
-  }\r
-  else\r
-  {\r
-    for (int i = 0; i < p->height; i++)\r
-    {\r
-      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1] < fxLo)\r
-        fxLo = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1];\r
-\r
-      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1] > fxHi)\r
-        fxHi = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1];\r
-\r
-      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2] < fyLo)\r
-        fyLo = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2];\r
-\r
-      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2] > fyHi)\r
-        fyHi = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2];\r
-    }\r
-  }\r
-\r
-  g_pParentWnd->ActiveXY()->RotateOrigin()[0] = g_pParentWnd->ActiveXY()->RotateOrigin()[1] = g_pParentWnd->ActiveXY()->RotateOrigin()[2] = 0.0;\r
-  g_pParentWnd->ActiveXY()->RotateOrigin()[nDim1] = (fxLo + fxHi) * 0.5;\r
-  g_pParentWnd->ActiveXY()->RotateOrigin()[nDim2] = (fyLo + fyHi) * 0.5;\r
-#endif\r
-}\r
-\r
-// also sets the rotational origin\r
-void Patch_SelectBendAxis()\r
-{\r
-       brush_t* b = selected_brushes.next;\r
-  if (!QE_SingleBrush() || !b->patchBrush)\r
-  {\r
-    // should not ever happen\r
-    Patch_BendToggle();\r
-               return;\r
-  }\r
-\r
-  patchMesh_t *p = b->pPatch;\r
-  if (g_bPatchAxisOnRow)\r
-  {\r
-    SelectRow(p, g_nPatchAxisIndex, false);\r
-  }\r
-  else\r
-  {\r
-    SelectColumn(p, g_nPatchAxisIndex, false);\r
-  }\r
-\r
-  //FIXME: this only needs to be set once... \r
-  Patch_SetBendRotateOrigin(p);\r
-\r
-}\r
-\r
-void Patch_SelectBendNormal()\r
-{\r
-       brush_t* b = selected_brushes.next;\r
-  if (!QE_SingleBrush() || !b->patchBrush)\r
-  {\r
-    // should not ever happen\r
-    Patch_BendToggle();\r
-               return;\r
-  }\r
-\r
-  patchMesh_t *p = b->pPatch;\r
-\r
-  g_qeglobals.d_num_move_points = 0;\r
-  if (g_bPatchAxisOnRow)\r
-  {\r
-    if (g_bPatchLowerEdge)\r
-    {\r
-      for (int j = 0; j < g_nPatchAxisIndex; j++)\r
-        SelectRow(p, j, true);\r
-    }\r
-    else\r
-    {\r
-      for (int j = p->height-1; j > g_nPatchAxisIndex; j--)\r
-        SelectRow(p, j, true);\r
-    }\r
-  }\r
-  else\r
-  {\r
-    if (g_bPatchLowerEdge)\r
-    {\r
-      for (int j = 0; j < g_nPatchAxisIndex; j++)\r
-        SelectColumn(p, j, true);\r
-    }\r
-    else\r
-    {\r
-      for (int j = p->width-1; j > g_nPatchAxisIndex; j--)\r
-        SelectColumn(p, j, true);\r
-    }\r
-  }\r
-  Patch_SetBendRotateOrigin(p);\r
-}\r
-\r
-\r
-\r
-/*\r
-void Patch_InsDelToggle()\r
-{\r
-  if (g_bPatchInsertMode)\r
-  {\r
-    g_bPatchInsertMode = false;\r
-    HideInfoDialog();\r
-    g_pParentWnd->UpdatePatchToolbarButtons() ;\r
-    return;\r
-  }\r
-\r
-       brush_t* b = selected_brushes.next;\r
-\r
-  if (!QE_SingleBrush(true) || !b->patchBrush)\r
-  {\r
-    Sys_Printf("Patch_InsDelToggle: you must have a single patch selected\n");\r
-               return;\r
-  }\r
-\r
-  Patch_Save(b->pPatch);\r
-       g_bPatchInsertMode = true;\r
-  g_nPatchInsertState = INSERT_SELECT_EDGE;\r
-  g_bPatchAxisOnRow = true;\r
-  g_nPatchAxisIndex = 0;\r
-  ShowInfoDialog(g_pInsertStateMsg[INSERT_SELECT_EDGE]);\r
-\r
-}\r
-\r
-void Patch_InsDelESC()\r
-{\r
-  if (!g_bPatchInsertMode)\r
-  {\r
-    return;\r
-  }\r
-  Patch_InsDelToggle();\r
-  Sys_UpdateWindows(W_ALL);\r
-}\r
-\r
-\r
-void Patch_InsDelHandleENTER()\r
-{\r
-}\r
-\r
-void Patch_InsDelHandleTAB()\r
-{\r
-  if (!g_bPatchInsertMode)\r
-  {\r
-    Patch_InsDelToggle();\r
-    return;\r
-  }\r
-\r
-       brush_t* b = selected_brushes.next;\r
-  if (!QE_SingleBrush() || !b->patchBrush)\r
-  {\r
-    Patch_BendToggle();\r
-    Sys_Printf("No patch to bend!");\r
-               return;\r
-  }\r
-\r
-  patchMesh_t *p = b->pPatch;\r
-\r
-  // only able to deal with odd numbered rows/cols\r
-  g_nPatchAxisIndex += 2;\r
-  if (g_bPatchAxisOnRow)\r
-  {\r
-    if (g_nPatchAxisIndex >= p->height-1)\r
-    {\r
-      g_bPatchAxisOnRow = false;\r
-      g_nPatchAxisIndex = 0;\r
-    }\r
-  }\r
-  else\r
-  {\r
-    if (g_nPatchAxisIndex >= p->width-1)\r
-    {\r
-      g_bPatchAxisOnRow = true;\r
-      g_nPatchAxisIndex = 0;\r
-    }\r
-  }\r
-  Sys_UpdateWindows(W_ALL);\r
-}\r
-*/\r
-\r
-\r
-void _Write1DMatrix (FILE *f, int x, float *m) {\r
-       int             i;\r
-\r
-       fprintf (f, "( ");\r
-       for (i = 0 ; i < x ; i++) {\r
-               if (m[i] == (int)m[i] ) {\r
-                       fprintf (f, "%i ", (int)m[i]);\r
-               } else {\r
-                       fprintf (f, "%f ", m[i]);\r
-               }\r
-       }\r
-       fprintf (f, ")");\r
-}\r
-\r
-void _Write2DMatrix (FILE *f, int y, int x, float *m) {\r
-       int             i;\r
-\r
-       fprintf (f, "( ");\r
-       for (i = 0 ; i < y ; i++) {\r
-               _Write1DMatrix (f, x, m + i*x);\r
-               fprintf (f, " ");\r
-       }\r
-       fprintf (f, ")\n");\r
-}\r
-\r
-\r
-void _Write3DMatrix (FILE *f, int z, int y, int x, float *m) {\r
-       int             i;\r
-\r
-       fprintf (f, "(\n");\r
-       for (i = 0 ; i < z ; i++) {\r
-               _Write2DMatrix (f, y, x, m + i*(x*MAX_PATCH_HEIGHT) );\r
-       }\r
-       fprintf (f, ")\n");\r
-}\r
-\r
-void _Write1DMatrix (MemStream *f, int x, float *m) {\r
-       int             i;\r
-\r
-       MemFile_fprintf (f, "( ");\r
-       for (i = 0 ; i < x ; i++) {\r
-               if (m[i] == (int)m[i] ) {\r
-                       MemFile_fprintf (f, "%i ", (int)m[i]);\r
-               } else {\r
-                       MemFile_fprintf (f, "%f ", m[i]);\r
-               }\r
-       }\r
-       MemFile_fprintf (f, ")");\r
-}\r
-\r
-void _Write2DMatrix (MemStream *f, int y, int x, float *m) {\r
-       int             i;\r
-\r
-       MemFile_fprintf (f, "( ");\r
-       for (i = 0 ; i < y ; i++) {\r
-               _Write1DMatrix (f, x, m + i*x);\r
-               MemFile_fprintf (f, " ");\r
-       }\r
-       MemFile_fprintf (f, ")\n");\r
-}\r
-\r
-\r
-void _Write3DMatrix (MemStream *f, int z, int y, int x, float *m) {\r
-       int             i;\r
-\r
-       MemFile_fprintf (f, "(\n");\r
-       for (i = 0 ; i < z ; i++) {\r
-               _Write2DMatrix (f, y, x, m + i*(x*MAX_PATCH_HEIGHT) );\r
-       }\r
-       MemFile_fprintf (f, ")\n");\r
-}\r
-\r
-// NOTE: why the hell is this called Naturalize?\r
-// we dispatch either to Patch+Naturalize or Patch_CapTexture..\r
-void Patch_NaturalizeSelected(bool bCap)\r
-{\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      if (bCap)\r
-        Patch_CapTexture(pb->pPatch);//, bCycleCap);\r
-      else\r
-        Patch_Naturalize(pb->pPatch);\r
-    }\r
-  }\r
-}\r
-\r
-// go through the selected patches and call Patch_CapTexture\r
-// deal with cycling\r
-void Patch_CycleCapSelected()\r
-{\r
-  // compute the g_vCycleCapNormal according to g_nCycleCapIndex\r
-  VectorClear (g_vCycleCapNormal);\r
-  g_vCycleCapNormal[g_nCycleCapIndex] = 1.0f; // cf VIEWTYPE defintion: enum VIEWTYPE {YZ, XZ, XY};\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      Patch_CapTexture(pb->pPatch, true);\r
-    }\r
-  }\r
-  switch (g_nCycleCapIndex)\r
-  {\r
-  case YZ:\r
-    g_nCycleCapIndex = XZ;\r
-    break;\r
-  case XZ:\r
-    g_nCycleCapIndex = XY;\r
-    break;\r
-  case XY:\r
-    g_nCycleCapIndex = YZ;\r
-    break;\r
-  }\r
-}\r
-\r
-bool within(vec3_t vTest, vec3_t vTL, vec3_t vBR)\r
-{\r
-  int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;\r
-  int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;\r
-  if ((vTest[nDim1] > vTL[nDim1] && vTest[nDim1] < vBR[nDim1]) ||\r
-      (vTest[nDim1] < vTL[nDim1] && vTest[nDim1] > vBR[nDim1]))\r
-  {\r
-    if ((vTest[nDim2] > vTL[nDim2] && vTest[nDim2] < vBR[nDim2]) ||\r
-        (vTest[nDim2] < vTL[nDim2] && vTest[nDim2] > vBR[nDim2]))\r
-      return true;\r
-  }\r
-  return false;\r
-}\r
-\r
-\r
-void Patch_SelectAreaPoints(bool bMulti)\r
-{\r
-  if (!bMulti)\r
-    g_qeglobals.d_num_move_points = 0;\r
-\r
-  if( g_nPatchClickedView == W_CAMERA ) {\r
-    // Clip against a pyramid\r
-    // Create our 5 normals (that are pointing to the inside)\r
-    camera_t *m_pCamera = g_pParentWnd->GetCamWnd()->Camera();\r
-    vec3_t     norm[5];\r
-    float              r[2], u[2], hh, hw;\r
-    int                        idx;\r
-    vec_t              corners[2][2];\r
-    vec3_t     ray[4];\r
-    vec3_t  check;\r
-\r
-    VectorCopy( m_pCamera->vpn, norm[0] ); // only points in front of the camera\r
-\r
-    // get our rectangle\r
-    corners[0][0] = MIN( g_qeglobals.d_vAreaTL[0], g_qeglobals.d_vAreaBR[0] );\r
-    corners[0][1] = MAX( g_qeglobals.d_vAreaTL[1], g_qeglobals.d_vAreaBR[1] );\r
-    corners[1][0] = MAX( g_qeglobals.d_vAreaTL[0], g_qeglobals.d_vAreaBR[0] );\r
-    corners[1][1] = MIN( g_qeglobals.d_vAreaTL[1], g_qeglobals.d_vAreaBR[1] );\r
-\r
-    // calculate our four ray vectors\r
-    hh = m_pCamera->height/2;\r
-    hw = m_pCamera->width/2;\r
-    u[0] = (float)(corners[0][1] - hh) / (hw);\r
-    r[0] = (float)(corners[0][0] - hw) / (hw);\r
-    u[1] = (float)(corners[1][1] - hh) / (hw);\r
-    r[1] = (float)(corners[1][0] - hw) / (hw);\r
-\r
-    for (idx=0 ; idx<3; idx++)\r
-           ray[0][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[0] + m_pCamera->vup[idx] * u[0];\r
-    for (idx=0 ; idx<3; idx++)\r
-           ray[1][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[1] + m_pCamera->vup[idx] * u[0];\r
-    for (idx=0 ; idx<3; idx++)\r
-           ray[2][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[1] + m_pCamera->vup[idx] * u[1];\r
-    for (idx=0 ; idx<3; idx++)\r
-           ray[3][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[0] + m_pCamera->vup[idx] * u[1];\r
-\r
-    // Create our four other directions from these\r
-    CrossProduct( ray[0], ray[1], norm[1] ); VectorNormalize( norm[1], norm[1] );\r
-    CrossProduct( ray[1], ray[2], norm[2] ); VectorNormalize( norm[2], norm[2] );\r
-    CrossProduct( ray[2], ray[3], norm[3] ); VectorNormalize( norm[3], norm[3] );\r
-    CrossProduct( ray[3], ray[0], norm[4] ); VectorNormalize( norm[4], norm[4] );\r
-               \r
-               // 3D clipping\r
-               for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-               {\r
-                       if (pb->patchBrush)\r
-                       {\r
-                               patchMesh_t *p = pb->pPatch;\r
-                               for (int i = 0; i < p->width; i++)\r
-                               {\r
-                                       for (int j = 0; j < p->height; j++)\r
-                                       {\r
-                                               VectorSubtract( m_pCamera->origin, p->ctrl[i][j].xyz, check );\r
-                                               VectorNormalize( check, check );\r
-                                               for (idx=0 ; idx<5; idx++)\r
-                                               {\r
-                                                       if (DotProduct(check, norm[idx])>=0)\r
-                                                               break;\r
-                                               }\r
-                                               if (idx == 5) // all test were good\r
-            {\r
-                                                       if (bMulti && PointInMoveList(p->ctrl[i][j].xyz) != -1)\r
-                                                               RemovePointFromMoveList(p->ctrl[i][j].xyz);\r
-              else\r
-                                                         g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;\r
-            }\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-       } else\r
-       {\r
-               // Simple 2D clipping\r
-               for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-               {\r
-                       if (pb->patchBrush)\r
-                       {\r
-                               patchMesh_t *p = pb->pPatch;\r
-                               for (int i = 0; i < p->width; i++)\r
-                               {\r
-                                       for (int j = 0; j < p->height; j++)\r
-                                       {\r
-                                               if (within(p->ctrl[i][j].xyz, g_qeglobals.d_vAreaTL, g_qeglobals.d_vAreaBR))\r
-                                               {\r
-                                                       if (bMulti && PointInMoveList(p->ctrl[i][j].xyz) != -1)\r
-                                                               RemovePointFromMoveList(p->ctrl[i][j].xyz);\r
-                                                       else\r
-                                                               g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       g_nPatchClickedView = -1;\r
-}\r
-\r
-// TTimo: return the shader name for a patch\r
-const char* Patch_GetTextureName()\r
-{\r
-       brush_t* b = selected_brushes.next;\r
-  if (b->patchBrush)\r
-  {\r
-    patchMesh_t *p = b->pPatch;\r
-    return p->pShader->getName();\r
-  }\r
-  return "";\r
-}\r
-\r
-patchMesh_t* Patch_Duplicate(patchMesh_t *pFrom)\r
-{\r
-  patchMesh_t* p = MakeNewPatch();\r
-  memcpy(p, pFrom , sizeof(patchMesh_t));\r
-  \r
-       // spog - initialise patch LOD pointers (again)\r
-  Patch_InitialiseLODPointers(p);\r
-  p->drawLists = NULL;\r
-\r
-  p->bSelected = false;\r
-  p->bDirty = true;\r
-  p->bOverlay = false;\r
-  p->nListID = -1;\r
-  AddBrushForPatch(p);\r
\r
-  return p;\r
-}\r
-\r
-\r
-void Patch_Thicken(int nAmount, bool bSeam, qboolean bGroupResult)\r
-{\r
-  int i, j, h, w;\r
-  brush_t *b;\r
-  patchMesh_t *pSeam;\r
-  vec3_t vMin, vMax;\r
-  CPtrArray brushes;\r
-\r
-  nAmount = -nAmount;\r
-\r
-\r
-       if (!QE_SingleBrush())\r
-  {\r
-    Sys_Printf("Cannot thicken multiple patches. Please select a single patch.\n");\r
-               return;\r
-  }\r
-\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      patchMesh_t *p = pb->pPatch;\r
-      Patch_MeshNormals(p);\r
-      patchMesh_t *pNew = Patch_Duplicate(p);\r
-      for (i = 0; i < p->width; i++)\r
-      {\r
-        for (j = 0; j < p->height; j++)\r
-        {\r
-                     VectorMA (p->ctrl[i][j].xyz, nAmount, p->ctrl[i][j].normal, pNew->ctrl[i][j].xyz);\r
-        }\r
-      }\r
-\r
-      Patch_Rebuild(pNew);\r
-      pNew->type |= PATCH_THICK;\r
-      brushes.Add(pNew->pSymbiot);\r
-\r
-      if (bSeam)\r
-      {\r
-\r
-        // FIXME: this should detect if any edges of the patch are closed and act appropriately\r
-        // \r
-        if (!(p->type & PATCH_CYLINDER))\r
-        {\r
-          b = Patch_GenericMesh(3, p->height, 2, false, true);\r
-          pSeam = b->pPatch;\r
-          pSeam->type |= PATCH_SEAM;\r
-          for (i = 0; i < p->height; i++)\r
-          {\r
-            VectorCopy(p->ctrl[0][i].xyz, pSeam->ctrl[0][i].xyz);\r
-            VectorCopy(pNew->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz);\r
-            VectorAdd(pSeam->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz, pSeam->ctrl[1][i].xyz);\r
-            VectorScale(pSeam->ctrl[1][i].xyz, 0.5, pSeam->ctrl[1][i].xyz);\r
-          }\r
-\r
-\r
-          Patch_CalcBounds(pSeam, vMin, vMax);\r
-          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);\r
-          //--Patch_CapTexture(pSeam);\r
-          Patch_Naturalize(pSeam);\r
-          patchInvert(pSeam);\r
-          brushes.Add(b);\r
-\r
-          w = p->width - 1;\r
-          b = Patch_GenericMesh(3, p->height, 2, false, true);\r
-          pSeam = b->pPatch;\r
-          pSeam->type |= PATCH_SEAM;\r
-          for (i = 0; i < p->height; i++)\r
-          {\r
-            VectorCopy(p->ctrl[w][i].xyz, pSeam->ctrl[0][i].xyz);\r
-            VectorCopy(pNew->ctrl[w][i].xyz, pSeam->ctrl[2][i].xyz);\r
-            VectorAdd(pSeam->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz, pSeam->ctrl[1][i].xyz);\r
-            VectorScale(pSeam->ctrl[1][i].xyz, 0.5, pSeam->ctrl[1][i].xyz);\r
-          }\r
-          Patch_CalcBounds(pSeam, vMin, vMax);\r
-          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);\r
-          //--Patch_CapTexture(pSeam);\r
-          Patch_Naturalize(pSeam);\r
-          brushes.Add(b);\r
-        }\r
-    \r
-        //--{\r
-          // otherwise we will add one per end\r
-          b = Patch_GenericMesh(p->width, 3, 2, false, true);\r
-          pSeam = b->pPatch;\r
-          pSeam->type |= PATCH_SEAM;\r
-          for (i = 0; i < p->width; i++)\r
-          {\r
-            VectorCopy(p->ctrl[i][0].xyz, pSeam->ctrl[i][0].xyz);\r
-            VectorCopy(pNew->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz);\r
-            VectorAdd(pSeam->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz, pSeam->ctrl[i][1].xyz);\r
-            VectorScale(pSeam->ctrl[i][1].xyz, 0.5, pSeam->ctrl[i][1].xyz);\r
-          }\r
-\r
-\r
-          Patch_CalcBounds(pSeam, vMin, vMax);\r
-          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);\r
-          //--Patch_CapTexture(pSeam);\r
-          Patch_Naturalize(pSeam);\r
-          patchInvert(pSeam);\r
-          brushes.Add(b);\r
-\r
-          h = p->height - 1;\r
-          b = Patch_GenericMesh(p->width, 3, 2, false, true);\r
-          pSeam = b->pPatch;\r
-          pSeam->type |= PATCH_SEAM;\r
-          for (i = 0; i < p->width; i++)\r
-          {\r
-            VectorCopy(p->ctrl[i][h].xyz, pSeam->ctrl[i][0].xyz);\r
-            VectorCopy(pNew->ctrl[i][h].xyz, pSeam->ctrl[i][2].xyz);\r
-            VectorAdd(pSeam->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz, pSeam->ctrl[i][1].xyz);\r
-            VectorScale(pSeam->ctrl[i][1].xyz, 0.5, pSeam->ctrl[i][1].xyz);\r
-          }\r
-          Patch_CalcBounds(pSeam, vMin, vMax);\r
-          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);\r
-          //--Patch_CapTexture(pSeam);\r
-          Patch_Naturalize(pSeam);\r
-          brushes.Add(b);\r
-\r
-      }\r
-      patchInvert(pNew);\r
-    }\r
-  }\r
-\r
-  for (i = 0; i < brushes.GetSize(); i++)\r
-  {\r
-    Select_Brush(reinterpret_cast<brush_t*>(brushes.GetAt(i)));\r
-  }\r
-\r
-  if(bGroupResult) \r
-  {\r
-    entity_t *e = Entity_Alloc();\r
-    SetKeyValue(e, "classname", "func_group");\r
-    SetKeyValue(e, "type", "patchThick");\r
-    Select_GroupEntity(e);\r
-    Entity_AddToList(e, &entities);\r
-  }\r
-  \r
-  UpdatePatchInspector();\r
-}\r
-\r
-\r
-/*\r
-lets get another list together as far as necessities..\r
-\r
-*snapping stuff to the grid (i will only snap movements by the mouse to the grid.. snapping the rotational bend stuff will fubar everything)\r
-\r
-capping bevels/endcaps\r
-\r
-hot keys\r
-\r
-texture fix for caps\r
-\r
-clear clipboard\r
-\r
-*region fix\r
-\r
-*surface dialog\r
-\r
-*/\r
-\r
-void Patch_SetOverlays()\r
-{\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      pb->pPatch->bOverlay = true;\r
-    }\r
-  }\r
-}\r
-\r
-\r
-\r
-void Patch_ClearOverlays()\r
-{\r
-  brush_t *pb;\r
-       for (pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      pb->pPatch->bOverlay = false;\r
-    }\r
-  }\r
-\r
-       for (pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      pb->pPatch->bOverlay = false;\r
-    }\r
-  }\r
-\r
-}\r
-\r
-// FIXME: spog - er, someone forgot to finish their patch point freezing feature?\r
-// freezes selected vertices\r
-void Patch_Freeze()\r
-{\r
-  brush_t *pb;\r
-       for (pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      pb->pPatch->bOverlay = false;\r
-    }\r
-  }\r
-\r
-       for (pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      pb->pPatch->bOverlay = false;\r
-    }\r
-  }\r
-\r
-}\r
-\r
-void Patch_UnFreeze(bool bAll)\r
-{\r
-}\r
-\r
-void Patch_Transpose()\r
-{\r
-       int             i, j, w;\r
-  drawVert_t dv;\r
-       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)\r
-       {\r
-    if (pb->patchBrush)\r
-    {\r
-      patchMesh_t *p = pb->pPatch;\r
-\r
-      if ( p->width > p->height ) \r
-      {\r
-       for ( i = 0 ; i < p->height ; i++ ) \r
-        {\r
-         for ( j = i + 1 ; j < p->width ; j++ ) \r
-          {\r
-           if ( j < p->height ) \r
-            {\r
-             // swap the value\r
-             memcpy(&dv,&p->ctrl[j][i],sizeof(drawVert_t));\r
-             memcpy(&p->ctrl[j][i],&p->ctrl[i][j], sizeof(drawVert_t));\r
-             memcpy(&p->ctrl[i][j],&dv, sizeof(drawVert_t));\r
-           } \r
-            else \r
-            {\r
-                                       // just copy\r
-                                       memcpy(&p->ctrl[i][j],&p->ctrl[j][i], sizeof(drawVert_t));\r
-                               }\r
-                       }\r
-                 }\r
-           } \r
-      else \r
-      {\r
-               for ( i = 0 ; i < p->width ; i++ ) \r
-        {\r
-                         for ( j = i + 1 ; j < p->height ; j++ ) \r
-          {\r
-                               if ( j < p->width ) \r
-            {\r
-                                           // swap the value\r
-                                           memcpy(&dv,&p->ctrl[i][j], sizeof(drawVert_t));\r
-              memcpy(&p->ctrl[i][j],&p->ctrl[j][i], sizeof(drawVert_t));\r
-                                       memcpy(&p->ctrl[j][i],&dv, sizeof(drawVert_t));\r
-                               } \r
-            else \r
-            {\r
-                                       // just copy\r
-                                       memcpy(&p->ctrl[j][i],&p->ctrl[i][j], sizeof(drawVert_t));\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-      w = p->width;\r
-      p->width = p->height;\r
-      p->height = w;\r
-      patchInvert(p);\r
-      Patch_Rebuild(p);\r
-               }\r
-       }\r
-}\r
-\r
-\r
-\r
-void Patch_SnapToGrid(patchMesh_t *p)\r
-{\r
-       int i,j,k;\r
-       \r
-       // if patch points selected, snap only selected points\r
-       if (g_qeglobals.d_select_mode == sel_curvepoint && g_qeglobals.d_num_move_points != 0)\r
-               for (i=0; i<g_qeglobals.d_num_move_points; i++)\r
-                       for (j = 0; j < 3; j++)\r
-                               g_qeglobals.d_move_points[i][j] = floor(g_qeglobals.d_move_points[i][j] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;\r
-                       \r
-       // else snap all patch points\r
-       else\r
-               for (i = 0; i < p->width; i++)\r
-                       for (j = 0; j < p->height; j++)\r
-                               for (k = 0; k < 3; k++)\r
-                                       p->ctrl[i][j].xyz[k] = floor(p->ctrl[i][j].xyz[k] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;\r
-                               \r
-       vec3_t vMin, vMax;\r
-       Patch_CalcBounds(p, vMin, vMax);\r
-       Brush_RebuildBrush(p->pSymbiot, vMin, vMax);\r
-}\r
-\r
-\r
-void Patch_FindReplaceTexture(brush_t *pb, const char *pFind, const char *pReplace, bool bForce)\r
-{\r
-  if (pb->patchBrush)\r
-  {\r
-    patchMesh_t *p = pb->pPatch;\r
-    if (bForce || strcmpi(p->pShader->getName(), pFind) == 0)\r
-    {\r
-      p->pShader->DecRef();\r
-      p->pShader = QERApp_Shader_ForName(pReplace);\r
-      p->d_texture = p->pShader->getTexture();\r
-    }\r
-  }\r
-}\r
-\r
-/* uncomment if necessary, currently not used\r
-void Patch_FromTriangle(vec5_t vx, vec5_t vy, vec5_t vz)\r
-{\r
-  patchMesh_t* p = MakeNewPatch();\r
-  p->pShader = g_qeglobals.d_texturewin.pShader;\r
-  p->d_texture = g_qeglobals.d_texturewin.pShader->getTexture();\r
-  p->width = 3;\r
-  p->height = 3;\r
-  p->type = PATCH_TRIANGLE;\r
-\r
-  // 0 0 goes to x\r
-  // 0 1 goes to x\r
-  // 0 2 goes to x\r
-\r
-  // 1 0 goes to mid of x and z\r
-  // 1 1 goes to mid of x y and z\r
-  // 1 2 goes to mid of x and y\r
-\r
-  // 2 0 goes to z\r
-  // 2 1 goes to mid of y and z\r
-  // 2 2 goes to y\r
-\r
-  vec5_t vMidXZ;\r
-  vec5_t vMidXY;\r
-  vec5_t vMidYZ;\r
-  int j;\r
-\r
-  for (j = 0; j < 3; j++)\r
-  {\r
-    _Vector5Add(vx, vz, vMidXZ);\r
-    _Vector5Scale(vMidXZ, 0.5, vMidXZ);\r
-    //vMidXZ[j] = vx[j] + abs((vx[j] - vz[j]) * 0.5);\r
-  }\r
-\r
-  for (j = 0; j < 3; j++)\r
-  {\r
-    _Vector5Add(vx, vy, vMidXY);\r
-    _Vector5Scale(vMidXY, 0.5, vMidXY);\r
-    //vMidXY[j] = vx[j] + abs((vx[j] - vy[j]) * 0.5);\r
-  }\r
-\r
-  for (j = 0; j < 3; j++)\r
-  {\r
-    _Vector5Add(vy, vz, vMidYZ);\r
-    _Vector5Scale(vMidYZ, 0.5, vMidYZ);\r
-    //vMidYZ[j] = vy[j] + abs((vy[j] - vz[j]) * 0.5);\r
-  }\r
-\r
-  _Vector53Copy(vx, p->ctrl[0][0].xyz);\r
-  _Vector53Copy(vx, p->ctrl[0][1].xyz);\r
-  _Vector53Copy(vx, p->ctrl[0][2].xyz);\r
-  p->ctrl[0][0].st[0] = vx[3];\r
-  p->ctrl[0][0].st[1] = vx[4];\r
-  p->ctrl[0][1].st[0] = vx[3];\r
-  p->ctrl[0][1].st[1] = vx[4];\r
-  p->ctrl[0][2].st[0] = vx[3];\r
-  p->ctrl[0][2].st[1] = vx[4];\r
-\r
-  _Vector53Copy(vMidXY, p->ctrl[1][0].xyz);\r
-  _Vector53Copy(vx, p->ctrl[1][1].xyz);\r
-  _Vector53Copy(vMidXZ, p->ctrl[1][2].xyz);\r
-  p->ctrl[1][0].st[0] = vMidXY[3];\r
-  p->ctrl[1][0].st[1] = vMidXY[4];\r
-  p->ctrl[1][1].st[0] = vx[3];\r
-  p->ctrl[1][1].st[1] = vx[4];\r
-  p->ctrl[1][2].st[0] = vMidXZ[3];\r
-  p->ctrl[1][2].st[1] = vMidXZ[4];\r
-\r
-  _Vector53Copy(vy, p->ctrl[2][0].xyz);\r
-  _Vector53Copy(vMidYZ, p->ctrl[2][1].xyz);\r
-  _Vector53Copy(vz, p->ctrl[2][2].xyz);\r
-  p->ctrl[2][0].st[0] = vy[3];\r
-  p->ctrl[2][0].st[1] = vy[4];\r
-  p->ctrl[2][1].st[0] = vMidYZ[3];\r
-  p->ctrl[2][1].st[1] = vMidYZ[4];\r
-  p->ctrl[2][2].st[0] = vz[3];\r
-  p->ctrl[2][2].st[1] = vz[4];\r
-\r
-\r
-  //Patch_Naturalize(p);\r
-\r
-  //  brush_t *b = \r
-  AddBrushForPatch(p);\r
-\r
-}\r
-*/\r
-\r
-#ifdef ENABLE_GROUPS\r
-/*\r
-==============\r
-Patch_SetEpair\r
-sets an epair for the given patch\r
-==============\r
-*/\r
-void Patch_SetEpair(patchMesh_t *p, const char *pKey, const char *pValue)\r
-{\r
-       if (g_qeglobals.m_bBrushPrimitMode)\r
-       {\r
-               SetKeyValue(p->epairs, pKey, pValue);\r
-       }\r
-}\r
-\r
-/* \r
-=================\r
-Patch_GetKeyValue\r
-=================\r
-*/\r
-const char* Patch_GetKeyValue(patchMesh_t *p, const char *pKey)\r
-{\r
-       if (g_qeglobals.m_bBrushPrimitMode)\r
-       {\r
-    return ValueForKey(p->epairs, pKey);\r
-       }\r
-  return "";\r
-}\r
-#endif\r
-\r
-\r
-//Real nitpicky, but could you make CTRL-S save the current map with the current name? (ie: File/Save)\r
-/*\r
-Feature addition.\r
-When reading in textures, please check for the presence of a file called "textures.link" or something, which contains one line such as;\r
-\r
-g:\quake3\baseq3\textures\common\r
-\r
- So that, when I'm reading in, lets say, my \eerie directory, it goes through and adds my textures to the palette, along with everything in common.\r
-\r
-  Don't forget to add "Finer texture alignment" to the list. I'd like to be able to move in 0.1 increments using the Shift-Arrow Keys.\r
-\r
-  No. Sometimes textures are drawn the wrong way on patches. We'd like the ability to flip a texture. Like the way X/Y scale -1 used to worked.\r
-\r
-  1) Easier way of deleting rows, columns\r
-2) Fine tuning of textures on patches (X/Y shifts other than with the surface dialog)\r
-2) Patch matrix transposition\r
-\r
-  1) Actually, bump texture flipping on patches to the top of the list of things to do.\r
-2) When you select a patch, and hit S, it should read in the selected patch texture. Should not work if you multiselect patches and hit S\r
-3) Brandon has a wierd anomoly. He fine-tunes a patch with caps. It looks fine when the patch is selected, but as soon as he escapes out, it reverts to it's pre-tuned state. When he selects the patch again, it looks tuned\r
-\r
-\r
-*1) Flipping textures on patches\r
-*2) When you select a patch, and hit S, it should read in the selected patch texture. Should not work if you multiselect patches and hit S\r
-3) Easier way of deleting rows columns\r
-*4) Thick Curves\r
-5) Patch matrix transposition\r
-6) Inverted cylinder capping\r
-*7) bugs\r
-*8) curve speed\r
-\r
-  Have a new feature request. "Compute Bounding Box" for mapobjects (md3 files). This would be used for misc_mapobject (essentially, drop in 3DS Max models into our maps)\r
-\r
-  Ok, Feature Request. Load and draw MD3's in the Camera view with proper bounding boxes. This should be off misc_model\r
-\r
-  Feature Addition: View/Hide Hint Brushes -- This should be a specific case.\r
-*/\r
+/*
+Copyright (C) 1999-2007 id Software, Inc. and contributors.
+For a list of contributors, see the accompanying CONTRIBUTORS file.
+
+This file is part of GtkRadiant.
+
+GtkRadiant 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.
+
+GtkRadiant 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 GtkRadiant; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+
+// 
+// Preliminary patch stuff
+//
+// 
+
+#include "stdafx.h"
+#include "gtkmisc.h"
+
+#include "gtkr_list.h"
+
+// externs
+extern void MemFile_fprintf(MemStream* pMemFile, const char* pText, ...);
+extern face_t *Face_Alloc( void );
+extern void DrawAlternatePoint(vec3_t v, float scale);
+
+void _Write3DMatrix (FILE *f, int y, int x, int z, float *m);
+void _Write3DMatrix (MemStream *f, int y, int x, int z, float *m);
+
+void Patch_InitialiseLODPointers(patchMesh_t *p)
+{
+       int i;
+       int rowcount = ((MAX_PATCH_WIDTH-1)/2) * MAX_PATCH_HEIGHT;
+       for (i=0; i<rowcount; i++)
+               p->rowLOD[i] = NULL;
+       int colcount = ((MAX_PATCH_HEIGHT-1)/2) * MAX_PATCH_WIDTH;
+       for (i=0; i<colcount; i++)
+               p->colLOD[i] = NULL;
+}
+
+patchMesh_t* Patch_Alloc()
+{
+  patchMesh_t *pPatch = (patchMesh_t *)malloc(sizeof(patchMesh_t));
+  pPatch->pShader = NULL;
+  pPatch->pSymbiot = NULL; // Hydra: added missing initialiser.
+       // spog - initialise patch LOD pointers
+  Patch_InitialiseLODPointers(pPatch);
+  pPatch->drawLists = NULL;
+  pPatch->bDirty = true;
+  pPatch->nListID = -1;
+  pPatch->bSelected = false;
+  pPatch->bOverlay = false;
+  pPatch->bDirty = true;
+  pPatch->LODUpdated = false;
+
+  int i;
+  for (i=0; i<(((MAX_PATCH_WIDTH-1)-1)/2); i++)
+    pPatch->rowDirty[i] = false;
+  for (i=0; i<(((MAX_PATCH_HEIGHT-1)-1)/2); i++)
+    pPatch->colDirty[i] = false;
+
+  return pPatch;
+}
+
+patchMesh_t* MakeNewPatch()
+{
+  patchMesh_t *pm = reinterpret_cast<patchMesh_t*>(qmalloc(sizeof(patchMesh_t)));
+
+  // spog - initialise patch LOD pointers
+  Patch_InitialiseLODPointers(pm);
+  pm->drawLists = NULL;
+  pm->bDirty = true;
+
+  return pm;
+}
+
+// FIXME: this needs to be dynamic
+//#define      MAX_PATCH_MESHES        4096
+//patchMesh_t          patchMeshes[MAX_PATCH_MESHES];
+//int numPatchMeshes = 0;
+
+// used for a save spot
+patchMesh_t patchSave;
+
+// Tracks the selected patch for point manipulation/update. FIXME: Need to revert back to a generalized 
+// brush approach
+//--int  g_nSelectedPatch = -1;  
+
+// HACK: for tracking which view generated the click
+// as we dont want to deselect a point on a same point
+// click if it is from a different view
+int  g_nPatchClickedView = -1;
+bool g_bSameView = false;
+
+//typedef enum XFormType { TRANSLATE, SCALE, ROTATE };
+
+
+// globals
+bool g_bPatchShowBounds = true;
+bool g_bPatchWireFrame = false;
+bool g_bPatchWeld = true;
+bool g_bPatchDrillDown = true;
+//bool g_bPatchInsertMode = false;
+bool g_bPatchBendMode = false;
+int  g_nPatchBendState = -1;
+int  g_nPatchInsertState = -1;
+int  g_nBendOriginIndex = 0;
+vec3_t g_vBendOrigin;
+
+bool g_bPatchAxisOnRow = true;
+int  g_nPatchAxisIndex = 0;
+bool g_bPatchLowerEdge = true;
+
+vec3_t g_vCycleCapNormal;
+// cycles when we use Patch_CycleCapSelected
+VIEWTYPE g_nCycleCapIndex = XY;
+
+// BEND states
+enum
+{
+  BEND_SELECT_ROTATION = 0,
+  BEND_SELECT_ORIGIN,
+  BEND_SELECT_EDGE,
+  BEND_BENDIT,
+  BEND_STATE_COUNT
+};
+
+const char *g_pBendStateMsg[] =
+{
+  "Use TAB to cycle through available bend axis. Press ENTER when the desired one is highlighted.",
+  "Use TAB to cycle through available rotation axis. This will LOCK around that point. You may also use Shift + Middle Click to select an arbitrary point. Press ENTER when the desired one is highlighted",
+  "Use TAB to choose which side to bend. Press ENTER when the desired one is highlighted.",
+  "Use the MOUSE to bend the patch. It uses the same ui rules as Free Rotation. Press ENTER to accept the bend, press ESC to abandon it and exit Bend mode",
+  ""
+};
+
+// INSERT states
+enum
+{
+  INSERT_SELECT_EDGE = 0,
+  INSERT_STATE_COUNT
+};
+
+const char* g_pInsertStateMsg[] =
+{
+  "Use TAB to cycle through available rows/columns for insertion/deletion. Press INS to insert at the highlight, DEL to remove the pair"
+};
+
+
+float *g_InversePoints[1024];
+
+const float fFullBright = 1.0;
+const float fLowerLimit = .50;
+const float fDec = .05f;
+void _SetColor(face_t* f, float fColor[3])
+{
+  return;
+  fColor[0] = f->d_color[0];
+  fColor[1] = f->d_color[1];
+  fColor[2] = f->d_color[2];
+  qglColor3fv(fColor);
+}
+
+
+void _DecColor(float fColor[3])
+{
+  return;
+  fColor[0] -= fDec;
+  fColor[1] -= fDec ;
+  fColor[2] -= fDec;
+  for (int i = 0; i < 3; i++)
+  {
+    if (fColor[i] <= fLowerLimit)
+    {
+      fColor[0] = fFullBright;
+      fColor[1] = fFullBright;
+      fColor[2] = fFullBright;
+      break;
+    }
+  }
+       qglColor3fv(fColor);
+}
+
+vec_t __VectorNormalize (vec3_t in, vec3_t out)
+{
+       vec_t   length, ilength;
+
+       length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);
+       if (length == 0)
+       {
+               VectorClear (out);
+               return 0;
+       }
+
+       ilength = 1.0/length;
+       out[0] = in[0]*ilength;
+       out[1] = in[1]*ilength;
+       out[2] = in[2]*ilength;
+
+       return length;
+}
+
+
+void Patch_SetType(patchMesh_t *p, int nType)
+{
+  p->type = (p->type & PATCH_STYLEMASK) | nType;
+}
+
+void Patch_SetStyle(patchMesh_t *p, int nStyle)
+{
+  p->type = (p->type & PATCH_TYPEMASK) | nStyle;
+}
+
+/*
+==================
+Patch_MemorySize
+==================
+*/
+int Patch_MemorySize(patchMesh_t *p)
+{
+  //   return _msize(p);
+  return 0;
+}
+
+
+/*
+===============
+InterpolateInteriorPoints
+===============
+*/
+void InterpolateInteriorPoints( patchMesh_t *p ) 
+{
+       int             i, j, k;
+       int             next, prev;
+
+       for ( i = 0 ; i < p->width ; i += 2 ) 
+  {
+
+    next = ( i == p->width - 1 ) ? 1 : ( i + 1 ) % p->width;
+    prev = ( i == 0 ) ? p->width - 2 : i - 1;
+
+#if 0
+               if ( i == 0 ) 
+    {
+                       next = ( i + 1 ) % p->width;
+                       prev = p->width - 2;                  // joined wrap case
+               } 
+    else if ( i == p->width - 1 ) 
+    {
+                       next = 1;
+                       prev = i - 1;
+               } 
+    else 
+    {
+                       next = ( i + 1 ) % p->width;
+                       prev = i - 1;
+               }
+#endif
+
+               for ( j = 0 ; j < p->height ; j++ ) 
+    {
+                       for ( k = 0 ; k < 3 ; k++ ) 
+      {
+                               p->ctrl[i][j].xyz[k] = ( p->ctrl[next][j].xyz[k] + p->ctrl[prev][j].xyz[k] ) * 0.5;
+                       }
+               }
+       }
+}
+
+/*
+=================
+MakeMeshNormals
+
+=================
+*/
+int    neighbors[8][2] = {
+       {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1}
+};
+
+void Patch_MeshNormals(patchMesh_t *in ) 
+{
+       int             i, j, k, dist;
+       vec3_t  normal;
+       vec3_t  sum;
+       int             count;
+       vec3_t  base;
+       vec3_t  delta;
+       int             x, y;
+       drawVert_t      *dv;
+       vec3_t          around[8], temp;
+       qboolean        good[8];
+       qboolean        wrapWidth, wrapHeight;
+       float           len;
+
+       wrapWidth = false;
+       for ( i = 0 ; i < in->height ; i++ ) 
+       {
+
+               VectorSubtract( in->ctrl[0][i].xyz, 
+                                     in->ctrl[in->width-1][i].xyz, delta );
+               len = VectorLength( delta );
+               if ( len > 1.0 ) 
+               {
+                       break;
+               }
+       }
+       if ( i == in->height ) 
+       {
+               wrapWidth = true;
+       }
+
+       wrapHeight = false;
+       for ( i = 0 ; i < in->width ; i++ ) 
+       {
+               VectorSubtract( in->ctrl[i][0].xyz, 
+                                     in->ctrl[i][in->height-1].xyz, delta );
+               len = VectorLength( delta );
+               if ( len > 1.0 ) 
+               {
+                       break;
+               }
+       }
+       if ( i == in->width) 
+       {
+               wrapHeight = true;
+       }
+
+
+       for ( i = 0 ; i < in->width ; i++ ) 
+       {
+               for ( j = 0 ; j < in->height ; j++ ) 
+               {
+                       count = 0;
+                       //--dv = reinterpret_cast<drawVert_t*>(in.ctrl[j*in.width+i]);
+                       dv = &in->ctrl[i][j];
+                       VectorCopy( dv->xyz, base );
+                       for ( k = 0 ; k < 8 ; k++ ) 
+                       {
+                               VectorClear( around[k] );
+                               good[k] = false;
+
+                               for ( dist = 1 ; dist <= 3 ; dist++ ) 
+                               {
+                                       x = i + neighbors[k][0] * dist;
+                                       y = j + neighbors[k][1] * dist;
+                                       if ( wrapWidth ) 
+                                       {
+                                               if ( x < 0 ) 
+                                               {
+                                                       x = in->width - 1 + x;
+                                               } 
+                                               else if ( x >= in->width ) 
+                                               {
+                                                       x = 1 + x - in->width;
+                                               }
+                                       }
+                                       if ( wrapHeight ) 
+                                       {
+                                               if ( y < 0 ) 
+                                               {
+                                                       y = in->height - 1 + y;
+                                               } 
+                                               else if ( y >= in->height ) 
+                                               {
+                                                       y = 1 + y - in->height;
+                                               }
+                                       }
+
+                                       if ( x < 0 || x >= in->width || y < 0 || y >= in->height ) 
+                                       {
+                                               break;                                  // edge of patch
+                                       }
+                                       //--VectorSubtract( in.ctrl[y*in.width+x]->xyz, base, temp );
+                                       VectorSubtract( in->ctrl[x][y].xyz, base, temp );
+                                       if ( __VectorNormalize( temp, temp ) == 0 ) 
+                                       {
+                                               continue;                               // degenerate edge, get more dist
+                                       } 
+                                       else                 
+                                       {
+                                               good[k] = true;
+                                               VectorCopy( temp, around[k] );
+                                               break;                                  // good edge
+                                       }
+                               }
+                       }
+
+                       VectorClear( sum );
+                       for ( k = 0 ; k < 8 ; k++ ) 
+                       {
+                               if ( !good[k] || !good[(k+1)&7] ) 
+                               {
+                                       continue;       // didn't get two points
+                               }
+                               CrossProduct( around[(k+1)&7], around[k], normal );
+                               if ( __VectorNormalize( normal, normal ) == 0 ) 
+                               {
+                                       continue;
+                               }
+                               VectorAdd( normal, sum, sum );
+                               count++;
+                       }
+                       if ( count == 0 ) 
+                       {
+        //printf("bad normal\n");
+                               count = 1;
+        //continue;
+                       }
+                       __VectorNormalize( sum, dv->normal );
+               }
+       }
+}
+
+
+
+
+/*
+==================
+Patch_CalcBounds
+==================
+*/
+void Patch_CalcBounds(patchMesh_t *p, vec3_t& vMin, vec3_t& vMax)
+{
+  vMin[0] = vMin[1] = vMin[2] = 99999;
+  vMax[0] = vMax[1] = vMax[2] = -99999;
+
+  p->bDirty = true;
+  for (int w = 0; w < p->width; w++)
+  {
+    for (int h = 0; h < p->height; h++)
+    {
+      for (int j = 0; j < 3; j++)
+      {
+        float f = p->ctrl[w][h].xyz[j];
+        if (f < vMin[j])
+          vMin[j] = f;
+        if (f > vMax[j])
+          vMax[j] = f;
+      }
+    }
+  }
+}
+
+/*
+==================
+Brush_RebuildBrush
+==================
+*/
+void Brush_RebuildBrush(brush_t *b, vec3_t vMins, vec3_t vMaxs)
+{
+  //
+  // Total hack job 
+  // Rebuilds a brush
+       int             i, j;
+       face_t  *f, *next;
+       vec3_t  pts[4][2];
+  texdef_t     texdef;
+       // free faces
+
+  for (j = 0; j < 3; j++)
+  {
+    if ((int)vMins[j] == (int)vMaxs[j])
+    {
+      vMins[j] -= 4;
+      vMaxs[j] += 4;
+    }
+  }
+
+  
+  for (f=b->brush_faces ; f ; f=next)
+       {
+               next = f->next;
+    if (f)
+      texdef = f->texdef;
+    Face_Free( f );
+       }
+
+  b->brush_faces = NULL;
+
+  // left the last face so we can use its texdef
+
+       for (i=0 ; i<3 ; i++)
+               if (vMaxs[i] < vMins[i])
+                       Error ("Brush_RebuildBrush: backwards");
+
+       pts[0][0][0] = vMins[0];
+       pts[0][0][1] = vMins[1];
+       
+       pts[1][0][0] = vMins[0];
+       pts[1][0][1] = vMaxs[1];
+       
+       pts[2][0][0] = vMaxs[0];
+       pts[2][0][1] = vMaxs[1];
+       
+       pts[3][0][0] = vMaxs[0];
+       pts[3][0][1] = vMins[1];
+       
+       for (i=0 ; i<4 ; i++)
+       {
+               pts[i][0][2] = vMins[2];
+               pts[i][1][0] = pts[i][0][0];
+               pts[i][1][1] = pts[i][0][1];
+               pts[i][1][2] = vMaxs[2];
+       }
+
+       for (i=0 ; i<4 ; i++)
+       {
+               f = Face_Alloc();
+               f->texdef = texdef;
+               f->texdef.flags &= ~SURF_KEEP;
+               f->texdef.contents &= ~CONTENTS_KEEP;
+//             f->texdef.flags |= SURF_PATCH; 
+               f->next = b->brush_faces;
+               b->brush_faces = f;
+               j = (i+1)%4;
+
+               VectorCopy (pts[j][1], f->planepts[0]);
+               VectorCopy (pts[i][1], f->planepts[1]);
+               VectorCopy (pts[i][0], f->planepts[2]);
+       }
+       
+       f = Face_Alloc();
+       f->texdef = texdef;
+  f->texdef.flags &= ~SURF_KEEP;
+       f->texdef.contents &= ~CONTENTS_KEEP;
+//  f->texdef.flags |= SURF_PATCH; 
+       f->next = b->brush_faces;
+       b->brush_faces = f;
+
+       VectorCopy (pts[0][1], f->planepts[0]);
+       VectorCopy (pts[1][1], f->planepts[1]);
+       VectorCopy (pts[2][1], f->planepts[2]);
+
+       f = Face_Alloc();
+       f->texdef = texdef;
+  f->texdef.flags &= ~SURF_KEEP;
+       f->texdef.contents &= ~CONTENTS_KEEP;
+//  f->texdef.flags |= SURF_PATCH; 
+       f->next = b->brush_faces;
+       b->brush_faces = f;
+
+       VectorCopy (pts[2][0], f->planepts[0]);
+       VectorCopy (pts[1][0], f->planepts[1]);
+       VectorCopy (pts[0][0], f->planepts[2]);
+
+  Brush_Build(b);
+}
+
+void WINAPI Patch_Rebuild(patchMesh_t *p)
+{
+  vec3_t vMin, vMax;
+  Patch_CalcBounds(p, vMin, vMax);
+  Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+  p->bDirty = true;
+}
+
+/*
+==================
+AddBrushForPatch
+==================
+ adds a patch brush and ties it to this patch id
+*/
+brush_t* AddBrushForPatch(patchMesh_t *pm, bool bLinkToWorld )
+{
+  // find the farthest points in x,y,z
+  vec3_t vMin, vMax;
+  Patch_CalcBounds(pm, vMin, vMax);
+
+  for (int j = 0; j < 3; j++)
+  {
+    if (vMin[j] == vMax[j])
+    {
+      vMin[j] -= 4;
+      vMax[j] += 4;
+    }
+  }
+
+  brush_t *b = Brush_Create(vMin, vMax, &g_qeglobals.d_texturewin.texdef);
+
+  // FIXME: this entire type of linkage needs to be fixed
+  b->patchBrush = true;
+  b->pPatch = pm;
+  pm->pSymbiot = b;
+  pm->bSelected = false;
+  pm->bOverlay = false;
+  pm->bDirty = true;
+  pm->nListID = -1;
+
+  if (bLinkToWorld)
+  {
+    Brush_AddToList (b, &active_brushes);
+         Entity_LinkBrush (world_entity, b);
+    Brush_Build(b);
+  }
+
+  return b;
+}
+
+void Patch_SetPointIntensities(int n)
+{
+#if 0
+       patchMesh_t     *p = patchMeshes[n];
+  for (int i = 0; i < p->width; i++)
+  {
+    for (int j = 0; j < p->height; j++)
+    {
+
+    }
+  }
+#endif
+}
+
+// very approximate widths and heights
+
+/*
+==================
+Patch_Width
+==================
+*/
+float Patch_Width(patchMesh_t *p)
+{
+  float f = 0;
+  for (int i = 0; i < p->width-1; i++)
+  {
+    vec3_t vTemp;
+    VectorSubtract(p->ctrl[i][0].xyz, p->ctrl[i+1][0].xyz, vTemp);
+    f += VectorLength(vTemp);
+  }
+  return f;
+}
+
+float Patch_WidthDistanceTo(patchMesh_t *p, int j)
+{
+  float f = 0;
+  for (int i = 0; i < j; i++)
+  {
+    vec3_t vTemp;
+    VectorSubtract(p->ctrl[i][0].xyz, p->ctrl[i+1][0].xyz, vTemp);
+    f += VectorLength(vTemp);
+  }
+  return f;
+}
+
+
+
+/*
+==================
+Patch_Height
+==================
+*/
+float Patch_Height(patchMesh_t *p)
+{
+  float f = 0;
+  for (int i = 0; i < p->height-1; i++)
+  {
+    vec3_t vTemp;
+    VectorSubtract(p->ctrl[0][i].xyz, p->ctrl[0][i+1].xyz, vTemp);
+    f += VectorLength(vTemp);
+  }
+  return f;
+}
+
+float Patch_HeightDistanceTo(patchMesh_t *p, int j)
+{
+  float f = 0;
+  for (int i = p->height-1; i > j; i--)
+  {
+    vec3_t vTemp;
+    VectorSubtract(p->ctrl[0][i].xyz, p->ctrl[0][i-1].xyz, vTemp); // reverse order for T coords
+    f += VectorLength(vTemp);
+  }
+  return f;
+}
+
+
+
+/*
+==================
+Patch_Naturalize
+==================
+texture = TotalTexture * LengthToThisControlPoint / TotalControlPointLength
+
+dist( this control point to first control point ) / dist ( last control pt to first)
+*/
+void WINAPI Patch_Naturalize(patchMesh_t *p)
+{
+  int nWidth = (int)(p->d_texture->width * g_pGameDescription->mTextureDefaultScale);
+  int nHeight = (int)(p->d_texture->height * g_pGameDescription->mTextureDefaultScale);
+  float fPWidth = Patch_Width(p);
+  float fPHeight = Patch_Height(p);
+  float xAccum = 0.0f;
+
+  for ( int i = 0; i < p->width ; i++ ) 
+  {
+       float yAccum = 0.0f;
+       for ( int j = p->height-1; j >= 0 ; j-- ) 
+       {
+         p->ctrl[i][j].st[0] = (fPWidth / nWidth) * xAccum / fPWidth;
+         p->ctrl[i][j].st[1] = (fPHeight / nHeight) * yAccum / fPHeight;
+          yAccum = Patch_HeightDistanceTo(p,j-1);
+         //p->ctrl[i][j][3] = (fPWidth / nWidth) * (float)i / (p->width - 1);
+         //p->ctrl[i][j][4] = (fPHeight/ nHeight) * (float)j / (p->height - 1);
+       }
+       xAccum = Patch_WidthDistanceTo(p,i+1);
+  }
+  p->bDirty = true;
+}
+
+/*
+  if (bIBevel)
+  {
+    VectorCopy(p->ctrl[1][0], p->ctrl[1][1]);
+  }
+
+  if (bIEndcap)
+  {
+    VectorCopy(p->ctrl[3][0], p->ctrl[4][1]);
+    VectorCopy(p->ctrl[2][0], p->ctrl[3][1]);
+    VectorCopy(p->ctrl[2][0], p->ctrl[2][1]);
+    VectorCopy(p->ctrl[2][0], p->ctrl[1][1]);
+    VectorCopy(p->ctrl[1][0], p->ctrl[0][1]);
+    VectorCopy(p->ctrl[1][0], p->ctrl[0][2]);
+    VectorCopy(p->ctrl[1][0], p->ctrl[1][2]);
+    VectorCopy(p->ctrl[2][0], p->ctrl[2][2]);
+    VectorCopy(p->ctrl[3][0], p->ctrl[3][2]);
+    VectorCopy(p->ctrl[3][0], p->ctrl[4][2]);
+  }
+*/
+
+int Index3By[][2] =
+{
+  {0,0},
+  {1,0},
+  {2,0},
+  {2,1},
+  {2,2},
+  {1,2},
+  {0,2},
+  {0,1},
+  {0,0},
+  {0,0},
+  {0,0},
+  {0,0},
+  {0,0},
+  {0,0},
+  {0,0}
+};
+
+int Index5By[][2] =
+{
+  {0,0},
+  {1,0},
+  {2,0},
+  {3,0},
+  {4,0},
+  {4,1},
+  {4,2},
+  {4,3},
+  {4,4},
+  {3,4},
+  {2,4},
+  {1,4},
+  {0,4},
+  {0,3},
+  {0,2},
+  {0,1}
+};
+
+
+
+int Interior3By[][2] =
+{
+  {1,1}
+};
+
+int Interior5By[][2] =
+{
+  {1,1},
+  {2,1},
+  {3,1},
+  {1,2},
+  {2,2},
+  {3,2},
+  {1,3},
+  {2,3},
+  {3,3}
+};
+
+int Interior3ByCount = sizeof(Interior3By) / sizeof(int[2]);
+int Interior5ByCount = sizeof(Interior5By) / sizeof(int[2]);
+
+extern int Plane_FromPoints(vec3_t p1, vec3_t p2, vec3_t p3, plane_t *plane);
+// the bFaceCycle only means we are going through a patch cycling loop
+// then we rely on g_vCycleCapNormal to compute the cap
+
+void Patch_CapTexture(patchMesh_t *p, bool bFaceCycle = false)
+{
+       vec3_t vProjection, vX, vY;
+       qtexture_t *texture = p->pShader->getTexture();
+       plane_t Plane1, Plane2, Plane3;
+       bool bThing=true;
+
+       if (bFaceCycle)
+               VectorCopy (g_vCycleCapNormal, vProjection);
+
+       else
+       {
+               VectorClear ( vProjection );
+
+               // find normal for plane from first 3 corner points
+               if (!Plane_FromPoints(p->ctrl[0][0].xyz,p->ctrl[0][p->height-1].xyz,p->ctrl[p->width-1][p->height-1].xyz,&Plane1))
+               {
+                       VectorClear ( Plane3.normal );
+                       bThing = false;
+               }
+               
+               // find normal for plane from next 3 corner points
+               if (!Plane_FromPoints(p->ctrl[p->width-1][p->height-1].xyz,p->ctrl[p->width-1][0].xyz,p->ctrl[0][0].xyz,&Plane2))
+               {
+                       if (bThing)
+                       {       
+                               VectorCopy ( Plane1.normal, Plane3.normal );
+                               Plane3.dist = Plane1.dist;
+                       }
+               }
+
+               else
+               {
+                       if (bThing)
+                               // find average plane for all 4 corner points
+                       {
+                               for (int n = 0; n <= 2; n++)
+                               {
+                                       Plane3.normal[n] = (Plane1.normal[n] + Plane2.normal[n]) / 2;
+                               }
+                               Plane3.dist = (Plane1.dist + Plane2.dist) / 2;
+                       }
+                       else
+                       {
+                               VectorCopy ( Plane2.normal, Plane3.normal );
+                               Plane3.dist = Plane2.dist;
+                       }
+               }
+
+               // get best axis for projection from average plane
+               //Sys_Printf("surface normal1: (%f,%f,%f)\n",Plane1.normal[0],Plane1.normal[1],Plane1.normal[0]);
+               //Sys_Printf("surface normal2: (%f,%f,%f)\n",Plane2.normal[0],Plane2.normal[1],Plane2.normal[0]);
+               //Sys_Printf("surface normal3: (%f,%f,%f)\n",Plane3.normal[0],Plane3.normal[1],Plane3.normal[0]);
+               TextureAxisFromPlane(&Plane3, vX, vY);
+       }
+
+       for (int w = 0; w < p->width; w++)
+       {
+               for (int h = 0; h < p->height; h++)
+               {
+                       if (vProjection[2] == 1.0f || (vX[0] == 1.0f && vY[1] == -1.0f))
+                       {
+                               p->ctrl[w][h].st[0] = p->ctrl[w][h].xyz[0] / (texture->width * g_pGameDescription->mTextureDefaultScale);
+                               p->ctrl[w][h].st[1] = p->ctrl[w][h].xyz[1] / (texture->height * g_pGameDescription->mTextureDefaultScale) * -1;
+                       }
+                       else if (vProjection[0] == 1.0f || (vX[1] == 1.0f && vY[2] == -1.0f))
+                       {
+                               p->ctrl[w][h].st[0] = p->ctrl[w][h].xyz[1] / (texture->width * g_pGameDescription->mTextureDefaultScale);
+                               p->ctrl[w][h].st[1] = p->ctrl[w][h].xyz[2] / (texture->height * g_pGameDescription->mTextureDefaultScale) * -1;
+                       }
+                       else if (vProjection[1] == 1.0f || (vX[0] == 1.0f && vY[2] == -1.0f))
+                       {
+                               p->ctrl[w][h].st[0] = p->ctrl[w][h].xyz[0] / (texture->width * g_pGameDescription->mTextureDefaultScale);
+                               p->ctrl[w][h].st[1] = p->ctrl[w][h].xyz[2] / (texture->height * g_pGameDescription->mTextureDefaultScale) * -1;
+                       }
+                       //Sys_Printf("(%i,%i) (%f,%f,%f) (%f,%f) %f\n",w,h,
+                       //      p->ctrl[w][h].xyz[0],p->ctrl[w][h].xyz[1],p->ctrl[w][h].xyz[2],
+                       //      p->ctrl[w][h].st[0],p->ctrl[w][h].st[1],p->ctrl[w][h].normal);
+               }
+       }
+       // make sure it will rebuild
+       p->bDirty = true;
+}
+
+void FillPatch(patchMesh_t *p, vec3_t v)
+{
+  for (int i = 0; i < p->width; i++)
+  {
+    for (int j = 0; j < p->height; j++)
+    {
+      VectorCopy(v, p->ctrl[i][j].xyz);
+    }
+  }
+}
+
+// temporarily moved function to allow use in Cap() and CapSpecial()
+void patchInvert(patchMesh_t *p)
+{
+  drawVert_t vertTemp;
+  p->bDirty = true;
+       for ( int i = 0 ; i < p->width ; i++ ) 
+  {
+    for (int j = 0; j < p->height / 2; j++)
+    {
+      memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+      memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+      memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+               }
+       }
+}
+
+brush_t* Cap(patchMesh_t *pParent, bool bByColumn, bool bFirst)
+{
+  brush_t *b;
+  patchMesh_t *p;
+  vec3_t vMin, vMax;
+  int i, j;
+
+  bool bSmall = true;
+  // make a generic patch
+  if (pParent->width <= 9)
+  {
+    b = Patch_GenericMesh(3, 3, 2, false);
+  }
+  else
+  {
+    b = Patch_GenericMesh(5, 5, 2, false);
+    bSmall = false;
+  }
+
+  if (!b)
+  {
+    Sys_Printf("Unable to cap. You may need to ungroup the patch.\n");
+    return NULL;
+  }
+
+  p = b->pPatch;
+  p->type |= PATCH_CAP;
+
+  vMin[0] = vMin[1] = vMin[2] = 9999;
+  vMax[0] = vMax[1] = vMax[2] = -9999;
+
+  // we seam the column edge, FIXME: this might need to be able to seem either edge
+  // 
+  int nSize = (bByColumn) ? pParent->width : pParent->height;
+  int nIndex = (bFirst) ? 0 : (bByColumn) ? pParent->height-1 : pParent->width-1;
+
+  FillPatch(p, pParent->ctrl[0][nIndex].xyz);
+
+  for (i = 0; i < nSize; i++)
+  {
+    if (bByColumn)
+    {
+      if (bSmall)
+      {
+        VectorCopy(pParent->ctrl[i][nIndex].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);
+      }
+      else
+      {
+        VectorCopy(pParent->ctrl[i][nIndex].xyz, p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz);
+      }
+    }
+    else
+    {
+      if (bSmall)
+      {
+        VectorCopy(pParent->ctrl[nIndex][i].xyz, p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz);
+      }
+      else
+      {
+        VectorCopy(pParent->ctrl[nIndex][i].xyz, p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz);
+      }
+    }
+  
+    for (j = 0; j < 3; j++)
+    {
+      float f = (bSmall) ? p->ctrl[Index3By[i][0]][Index3By[i][1]].xyz[j] : p->ctrl[Index5By[i][0]][Index5By[i][1]].xyz[j];
+      if (f < vMin[j])
+        vMin[j] = f;
+      if (f > vMax[j])
+        vMax[j] = f;
+    }
+  }
+
+  vec3_t vTemp;
+  for (j = 0; j < 3; j++)
+  {
+    vTemp[j] = vMin[j] + fabs((vMax[j] - vMin[j]) * 0.5);
+  }
+  int nCount = (bSmall) ? Interior3ByCount : Interior5ByCount;
+  for (j = 0; j < nCount; j++)
+  {
+    if (bSmall)
+    {
+      VectorCopy(vTemp, p->ctrl[Interior3By[j][0]][Interior3By[j][1]].xyz);
+    }
+    else
+    {
+      VectorCopy(vTemp, p->ctrl[Interior5By[j][0]][Interior5By[j][1]].xyz);
+    }
+  }
+
+  if (bFirst)
+         patchInvert(p);
+  /*
+  {
+    drawVert_t vertTemp;
+    for (i = 0; i < p->width; i++)
+    {
+      for (j = 0; j < p->height / 2; j++)
+      {
+        memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+        memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+        memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+      }
+    }
+  }
+  */
+
+  Patch_Rebuild(p);
+  Patch_CapTexture(p);
+  return p->pSymbiot;
+}
+
+brush_t* CapSpecial(patchMesh_t *pParent, int nType, bool bFirst)
+{
+
+  brush_t *b;
+  patchMesh_t *p;
+  vec3_t vMin, vMax, vTemp;
+  int i, j;
+
+  if (nType == IENDCAP)
+    b = Patch_GenericMesh(5, 3, 2, false);
+  else
+    b = Patch_GenericMesh(3, 3, 2, false);
+
+  if (!b)
+  {
+    Sys_Printf("Unable to cap. Make sure you ungroup before re-capping.");
+    return NULL;
+  }
+
+  p = b->pPatch;
+  p->type |= PATCH_CAP;
+
+  vMin[0] = vMin[1] = vMin[2] = 9999;
+  vMax[0] = vMax[1] = vMax[2] = -9999;
+
+  //  int nSize = pParent->width;
+  int nIndex = (bFirst) ? 0 : pParent->height-1;
+
+  // parent bounds are used for some things
+  Patch_CalcBounds(pParent, vMin, vMax);
+
+  for (j = 0; j < 3; j++)
+  {
+    vTemp[j] = vMin[j] + fabs((vMax[j] - vMin[j]) * 0.5);
+  }
+  
+  if (nType == IBEVEL)
+  {
+    VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[0][2].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][2].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][0].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][1].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[1][2].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][0].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[2][1].xyz);
+  }
+  else if (nType == BEVEL)
+  {
+    vec3_t p1, p2, p3, p4; //, temp, dir;
+
+    VectorCopy(pParent->ctrl[0][nIndex].xyz, p3);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p1);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p2);
+       
+       //Sys_Printf("CapSpecial() p1: %f %f %f\n",p1[0],p1[1],p1[2]);
+       //Sys_Printf("CapSpecial() p2: %f %f %f\n",p2[0],p2[1],p2[2]);
+       //Sys_Printf("CapSpecial() p3: %f %f %f\n",p3[0],p3[1],p3[2]);
+       
+       VectorSubtract(p2, p1, p4);
+       VectorAdd(p3, p4, p4);
+       // spog - use opposite-point-on-parallelogram to find p4
+       /*
+    VectorSubtract(p3, p2, dir);
+    VectorNormalize(dir);
+    VectorSubtract(p1, p2, temp);
+    vec_t dist = _DotProduct(temp, dir);
+    VectorScale(dir, dist, temp);
+    VectorAdd(p2, temp, temp);
+    VectorSubtract(temp, p1, temp);
+    VectorScale(temp, 2, temp);
+    VectorAdd(p1, temp, p4);
+       */
+
+       //Sys_Printf("CapSpecial() p1: %f %f %f\n",p1[0],p1[1],p1[2]);
+       //Sys_Printf("CapSpecial() p2: %f %f %f\n",p2[0],p2[1],p2[2]);
+       //Sys_Printf("CapSpecial() p3: %f %f %f\n",p3[0],p3[1],p3[2]);
+       //Sys_Printf("CapSpecial() p4: %f %f %f\n",p4[0],p4[1],p4[2]);
+
+    VectorCopy(p4, p->ctrl[0][0].xyz);
+    VectorCopy(p4, p->ctrl[1][0].xyz);
+    VectorCopy(p4, p->ctrl[0][1].xyz);
+    VectorCopy(p4, p->ctrl[1][1].xyz);
+    VectorCopy(p4, p->ctrl[0][2].xyz);
+    VectorCopy(p4, p->ctrl[1][2].xyz);
+    VectorCopy(p2, p->ctrl[2][0].xyz);
+    VectorCopy(p1, p->ctrl[2][1].xyz);
+    VectorCopy(p3, p->ctrl[2][2].xyz);
+
+  }
+  else if (nType == ENDCAP)
+  {
+    VectorAdd(pParent->ctrl[4][nIndex].xyz, pParent->ctrl[0][nIndex].xyz, vTemp);
+    VectorScale(vTemp, 0.5, vTemp);
+    VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[0][0].xyz);
+                                                  VectorCopy(vTemp, p->ctrl[1][0].xyz);
+    VectorCopy(pParent->ctrl[4][nIndex].xyz, p->ctrl[2][0].xyz);
+
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[0][2].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[1][2].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][2].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[1][1].xyz);
+    
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[0][1].xyz);
+    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[2][1].xyz);
+  }
+  else
+  {
+    VectorCopy(pParent->ctrl[4][nIndex].xyz, p->ctrl[0][0].xyz);
+    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[1][0].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][0].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[3][0].xyz);
+    VectorCopy(pParent->ctrl[0][nIndex].xyz, p->ctrl[4][0].xyz);
+    
+    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[0][1].xyz);
+    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[1][1].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][1].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[3][1].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[4][1].xyz);
+
+    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[0][2].xyz);
+    VectorCopy(pParent->ctrl[3][nIndex].xyz, p->ctrl[1][2].xyz);
+    VectorCopy(pParent->ctrl[2][nIndex].xyz, p->ctrl[2][2].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[3][2].xyz);
+    VectorCopy(pParent->ctrl[1][nIndex].xyz, p->ctrl[4][2].xyz);
+  }
+
+
+  if (!bFirst)
+  {
+    drawVert_t vertTemp;
+    for (i = 0; i < p->width; i++)
+    {
+      for (j = 0; j < p->height / 2; j++)
+      {
+        memcpy(&vertTemp, &p->ctrl[i][p->height - 1- j], sizeof (drawVert_t));
+        memcpy(&p->ctrl[i][p->height - 1 - j], &p->ctrl[i][j], sizeof(drawVert_t));
+        memcpy(&p->ctrl[i][j], &vertTemp, sizeof(drawVert_t));
+      }
+    }
+  }
+
+  //--Patch_CalcBounds(p, vMin, vMax);
+  //--Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+  Patch_Rebuild(p);
+  Patch_CapTexture(p);
+  return p->pSymbiot;
+}
+
+void Patch_CapCurrent()
+{
+  patchMesh_t *pParent = NULL;
+  brush_t *b[4];
+  brush_t *pCap = NULL;
+  b[0] = b[1] = b[2] = b[3] = NULL;
+  int nIndex = 0;
+  bool b_GroupResult = TRUE;
+  
+  if (!QE_SingleBrush(true))
+  {
+    Sys_Printf("Patch_CapCurrent: you must have a single patch selected\n");
+    return;
+  }
+  
+  
+  for (brush_t *pb = selected_brushes.next ; pb != NULL && pb != &selected_brushes ; pb = pb->next)
+  {
+    if (pb->patchBrush)
+    {
+      pParent = pb->pPatch;
+      // decide which if any ends we are going to cap
+      // if any of these compares hit, it is a closed patch and as such
+      // the generic capping will work.. if we do not find a closed edge 
+      // then we need to ask which kind of cap to add
+      if (VectorCompare(pParent->ctrl[0][0].xyz, pParent->ctrl[pParent->width-1][0].xyz))
+      {
+        pCap = Cap(pParent, true, false);
+        if (pCap != NULL)
+        {
+          b[nIndex++] = pCap;
+        }
+      }
+      if (VectorCompare(pParent->ctrl[0][pParent->height-1].xyz, pParent->ctrl[pParent->width-1][pParent->height-1].xyz))
+      {
+        pCap = Cap(pParent, true, true);
+        if (pCap != NULL)
+        {
+          b[nIndex++] = pCap;
+        }
+      }
+      if (VectorCompare(pParent->ctrl[0][0].xyz, pParent->ctrl[0][pParent->height-1].xyz))
+      {
+        pCap = Cap(pParent, false, false);
+        if (pCap != NULL)
+        {
+          b[nIndex++] = pCap;
+        }
+      }
+      if (VectorCompare(pParent->ctrl[pParent->width-1][0].xyz, pParent->ctrl[pParent->width-1][pParent->height-1].xyz))
+      {
+        pCap = Cap(pParent, false, true);
+        if (pCap != NULL)
+        {
+          b[nIndex++] = pCap;
+        }
+      }
+    }
+  }
+  
+  if (pParent)
+  {
+    // if we did not cap anything with the above tests
+    if (nIndex == 0)
+    {
+      int type;
+      
+      if (DoCapDlg (&type, &b_GroupResult) == IDOK)
+      {
+        b[nIndex++] = CapSpecial(pParent, type, false);
+        b[nIndex++] = CapSpecial(pParent, type, true);
+      }
+    }
+    
+    if (nIndex > 0)
+    {
+      while (nIndex > 0)
+      {
+        nIndex--;
+        if (b[nIndex])
+        {
+          Select_Brush(b[nIndex]);
+        }
+      }
+      // Gef: Added toggle for capped patch func_group
+      if(b_GroupResult) {
+        entity_t *e = Entity_Alloc();
+        SetKeyValue(e, "classname", "func_group");
+        SetKeyValue(e, "type", "patchCapped");
+        Select_GroupEntity(e);
+        Entity_AddToList(e, &entities);
+      }
+    }
+  }
+}
+
+/*
+===============
+BrushToPatchMesh
+===============
+*/
+void Patch_BrushToMesh(bool bCone, bool bBevel, bool bEndcap, bool bSquare, int nHeight)
+{
+       brush_t         *b;
+       patchMesh_t     *p;
+       int                     i,j;
+
+       if (!QE_SingleBrush())
+               return;
+
+       b = selected_brushes.next;
+
+       p = MakeNewPatch();
+
+       p->d_texture = b->brush_faces->d_texture;
+       p->pShader = b->brush_faces->pShader;
+
+  p->height = nHeight;
+
+  p->type = PATCH_CYLINDER;
+  if (bBevel & !bSquare)
+  {
+    p->type = PATCH_BEVEL;
+    p->width = 3;
+    int nStep = (int)((b->maxs[2] - b->mins[2]) / (p->height-1));
+    int nStart = (int)(b->mins[2]);
+    for (i = 0; i < p->height; i++)
+    {
+           p->ctrl[0][i].xyz[0] =  b->mins[0];
+           p->ctrl[0][i].xyz[1] =  b->mins[1];
+      p->ctrl[0][i].xyz[2] = nStart;
+
+           p->ctrl[1][i].xyz[0] =  b->maxs[0];
+           p->ctrl[1][i].xyz[1] =  b->mins[1];
+      p->ctrl[1][i].xyz[2] = nStart;
+
+           p->ctrl[2][i].xyz[0] =  b->maxs[0];
+           p->ctrl[2][i].xyz[1] =  b->maxs[1];
+      p->ctrl[2][i].xyz[2] = nStart;
+      nStart += nStep;
+    }
+  }
+  else if (bEndcap & !bSquare)
+  {
+    p->type = PATCH_ENDCAP;
+    p->width = 5;
+    int nStep = (int)((b->maxs[2] - b->mins[2]) / (p->height-1));
+    int nStart = (int)(b->mins[2]);
+    for (i = 0; i < p->height; i++)
+    {
+      p->ctrl[0][i].xyz[0] =  b->mins[0];
+      p->ctrl[0][i].xyz[1] =  b->mins[1];
+      p->ctrl[0][i].xyz[2] = nStart;
+
+      p->ctrl[1][i].xyz[0] =  b->mins[0];
+      p->ctrl[1][i].xyz[1] =  b->maxs[1];
+      p->ctrl[1][i].xyz[2] = nStart;
+
+      p->ctrl[2][i].xyz[0] =  b->mins[0] + ((b->maxs[0] - b->mins[0]) * 0.5);
+      p->ctrl[2][i].xyz[1] =  b->maxs[1];
+      p->ctrl[2][i].xyz[2] = nStart;
+          
+      p->ctrl[3][i].xyz[0] =  b->maxs[0];
+      p->ctrl[3][i].xyz[1] =  b->maxs[1];
+      p->ctrl[3][i].xyz[2] = nStart;
+
+      p->ctrl[4][i].xyz[0] =  b->maxs[0];
+      p->ctrl[4][i].xyz[1] =  b->mins[1];
+      p->ctrl[4][i].xyz[2] = nStart;
+      nStart += nStep;
+    }
+  }
+  else
+  {
+    p->width = 9;
+    p->ctrl[1][0].xyz[0] =  b->mins[0];
+    p->ctrl[1][0].xyz[1] =  b->mins[1];
+
+    p->ctrl[3][0].xyz[0] =  b->maxs[0];
+    p->ctrl[3][0].xyz[1] =  b->mins[1];
+
+    p->ctrl[5][0].xyz[0] =  b->maxs[0];
+    p->ctrl[5][0].xyz[1] =  b->maxs[1];
+
+    p->ctrl[7][0].xyz[0] =  b->mins[0];
+    p->ctrl[7][0].xyz[1] =  b->maxs[1];
+
+    for ( i = 1 ; i < p->width - 1 ; i += 2 ) 
+    {
+
+      p->ctrl[i][0].xyz[2] =  b->mins[2];
+
+                 VectorCopy( p->ctrl[i][0].xyz, p->ctrl[i][2].xyz );
+
+                 p->ctrl[i][2].xyz[2] =  b->maxs[2];
+
+                 p->ctrl[i][1].xyz[0] = ( p->ctrl[i][0].xyz[0] + p->ctrl[i][2].xyz[0] ) * 0.5;
+                 p->ctrl[i][1].xyz[1] = ( p->ctrl[i][0].xyz[1] + p->ctrl[i][2].xyz[1] ) * 0.5;
+                 p->ctrl[i][1].xyz[2] = ( p->ctrl[i][0].xyz[2] + p->ctrl[i][2].xyz[2] ) * 0.5;
+         }
+         InterpolateInteriorPoints( p );
+
+    if (bSquare)
+    {
+      if (bBevel || bEndcap)
+      {
+        if (bBevel)
+        {
+          for (i = 0; i < p->height; i++)
+          {
+            VectorCopy(p->ctrl[1][i].xyz, p->ctrl[2][i].xyz);
+            VectorCopy(p->ctrl[7][i].xyz, p->ctrl[6][i].xyz);
+          }
+        }
+        else
+        {
+          for (i = 0; i < p->height; i++)
+          {
+            VectorCopy(p->ctrl[5][i].xyz, p->ctrl[4][i].xyz);
+            VectorCopy(p->ctrl[1][i].xyz, p->ctrl[2][i].xyz);
+            VectorCopy(p->ctrl[7][i].xyz, p->ctrl[6][i].xyz);
+            VectorCopy(p->ctrl[8][i].xyz, p->ctrl[7][i].xyz);
+          }
+        }
+      }
+      else
+      {
+        for (i = 0; i < p->width-1; i ++)
+        {
+          for (j = 0; j < p->height; j++)
+          {
+            VectorCopy(p->ctrl[i+1][j].xyz, p->ctrl[i][j].xyz);
+          }
+        }
+        for (j = 0; j < p->height; j++)
+        {
+          VectorCopy(p->ctrl[0][j].xyz, p->ctrl[8][j].xyz);
+        }
+      }
+    }
+  }
+
+
+  Patch_Naturalize(p);
+
+  if (bCone)
+  {
+    p->type = PATCH_CONE;
+    float xc = (b->maxs[0] + b->mins[0]) * 0.5; 
+    float yc = (b->maxs[1] + b->mins[1]) * 0.5; 
+
+    for ( i = 0 ; i < p->width ; i ++)
+    {
+      p->ctrl[i][2].xyz[0] = xc;
+      p->ctrl[i][2].xyz[1] = yc;
+    }
+  }
+  
+  b = AddBrushForPatch(p);
+
+  Select_Delete();
+  Select_Brush(b);
+
+}
+
+/*
+==================
+Patch_GenericMesh
+==================
+*/
+brush_t* Patch_GenericMesh(int nWidth, int nHeight, int nOrientation, bool bDeleteSource, bool bOverride)
+{
+  int i,j;
+
+  if (nHeight < 3 || nHeight > 15 || nWidth < 3 || nWidth > 15)
+  {
+    Sys_Printf("Invalid patch width or height.\n");
+    return NULL;
+  }
+
+       if (! bOverride && !QE_SingleBrush())
+  {
+    Sys_Printf("Error: you must have a single brush selected\n");
+               return NULL;
+  }
+
+  patchMesh_t* p = MakeNewPatch();
+  p->pShader = g_qeglobals.d_texturewin.pShader;
+  p->d_texture = g_qeglobals.d_texturewin.pShader->getTexture();
+
+       p->width = nWidth;
+       p->height = nHeight;
+  p->type = PATCH_GENERIC;
+
+  int nFirst = 0;
+  int nSecond = 1;
+  if (nOrientation == 0)
+  {
+    nFirst = 1;
+    nSecond = 2;
+  }
+  else if (nOrientation == 1)
+  {
+    nSecond = 2;
+  }
+
+       brush_t *b = selected_brushes.next;
+       // set the workzone to this brush, use it later to create the patch points
+       UpdateWorkzone_ForBrush( b );
+
+  int xStep = (int)(b->mins[nFirst]);
+  float xAdj = fabs((b->maxs[nFirst] - b->mins[nFirst]) / (nWidth - 1));
+  float yAdj = fabs((b->maxs[nSecond] - b->mins[nSecond]) / (nHeight - 1));
+
+  for (i = 0; i < nWidth; i++)
+  {
+    int yStep = (int)(b->mins[nSecond]);
+    for (j = 0; j < nHeight; j++)
+    {
+      p->ctrl[i][j].xyz[nFirst] = xStep;
+      p->ctrl[i][j].xyz[nSecond] = yStep;
+      // create patch based on workzone
+      p->ctrl[i][j].xyz[nOrientation] = g_qeglobals.d_work_max[nOrientation];
+      yStep += (int)yAdj;
+    }
+    xStep += (int)xAdj;
+  }
+
+  Patch_Naturalize(p);
+
+  b = AddBrushForPatch(p);
+  if (bDeleteSource)
+  {
+    Select_Delete();
+    Select_Brush(b);
+  }
+
+  return b;
+  //g_qeglobals.d_select_mode = sel_curvepoint;
+}
+
+/*
+==================
+PointInMoveList
+==================
+*/
+int PointInMoveList(float *pf)
+{
+  for (int i = 0; i < g_qeglobals.d_num_move_points; i++)
+  {
+    if (pf == &g_qeglobals.d_move_points[i][0])
+      return i;
+  }
+  return -1;
+}
+
+/*
+==================
+PointValueInMoveList
+==================
+*/
+int PointValueInMoveList(vec3_t v)
+{
+  for (int i = 0; i < g_qeglobals.d_num_move_points; i++)
+  {
+    if (VectorCompare(v, g_qeglobals.d_move_points[i]))
+      return i;
+  }
+  return -1;
+}
+
+
+/*
+==================
+RemovePointFromMoveList
+==================
+*/
+void RemovePointFromMoveList(vec3_t v)
+{
+  int n;
+  while ( (n = PointValueInMoveList(v)) >= 0)
+  {
+    for (int i = n; i < g_qeglobals.d_num_move_points-1; i++)
+    {
+      g_qeglobals.d_move_points[i] = g_qeglobals.d_move_points[i+1];
+    }
+    g_qeglobals.d_num_move_points--;
+  }
+}
+
+/*
+==================
+ColumnSelected
+==================
+*/
+bool ColumnSelected(patchMesh_t* p, int nCol)
+{
+  for (int i = 0; i < p->height; i++)
+  {
+    if (PointInMoveList(p->ctrl[nCol][i].xyz) == -1)
+      return false;
+  }
+  return true;
+}
+
+/*
+==================
+AddPoint
+==================
+*/
+void AddPoint(patchMesh_t* p, vec3_t v, bool bWeldOrDrill = true)
+{
+  int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+  int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+  g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = v;
+  if ((g_bPatchWeld || g_bPatchDrillDown) && bWeldOrDrill)
+  {
+         for ( int i = 0 ; i < p->width ; i++ ) 
+    {
+                 for ( int j = 0 ; j < p->height ; j++ ) 
+      {
+        if (g_bPatchWeld)
+        {
+          if ( VectorCompare(v, p->ctrl[i][j].xyz)
+            && PointInMoveList(p->ctrl[i][j].xyz) == -1)
+          {
+            g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+            continue;
+          }
+        }
+        if (g_bPatchDrillDown && g_nPatchClickedView != W_CAMERA)
+        {
+          if ( (fabs(v[nDim1] - p->ctrl[i][j].xyz[nDim1]) <= EQUAL_EPSILON) 
+             &&(fabs(v[nDim2] - p->ctrl[i][j].xyz[nDim2]) <= EQUAL_EPSILON)) 
+          {
+            if (PointInMoveList(p->ctrl[i][j].xyz) == -1)
+            {
+              g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+              continue;
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+/*
+==================
+SelectRow
+==================
+*/
+void SelectRow(patchMesh_t* p, int nRow, bool bMulti)
+{
+  if (!bMulti)
+    g_qeglobals.d_num_move_points = 0;
+  for (int i = 0; i < p->width; i++)
+  {
+    AddPoint(p, p->ctrl[i][nRow].xyz, false);
+  }
+  //Sys_Printf("Selected Row %d\n", nRow);
+}
+
+/*
+==================
+SelectColumn
+==================
+*/
+void SelectColumn(patchMesh_t* p, int nCol, bool bMulti)
+{
+  if (!bMulti)
+    g_qeglobals.d_num_move_points = 0;
+  for (int i = 0; i < p->height; i++)
+  {
+    AddPoint(p, p->ctrl[nCol][i].xyz, false);
+  }
+  //Sys_Printf("Selected Col %d\n", nCol);
+}
+
+
+/*
+==================
+AddPatchMovePoint
+==================
+*/
+void AddPatchMovePoint(vec3_t v, bool bMulti, bool bFull)
+{
+  if (!g_bSameView && !bMulti && !bFull)
+  {
+    g_bSameView = true;
+    //return; // was causing odd behaviour on patch vertex selection
+  }
+
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+           patchMesh_t* p = pb->pPatch;
+           for ( int i = 0 ; i < p->width ; i++ ) 
+      {
+                   for ( int j = 0 ; j < p->height ; j++ ) 
+        {
+          if (VectorCompare(v, p->ctrl[i][j].xyz))
+          {
+            if (PointInMoveList(p->ctrl[i][j].xyz) == -1)
+            {
+              if (bFull)        // if we want the full row/col this is on
+              {
+                SelectColumn(p, i, bMulti);
+              }
+              else
+              {
+                if (!bMulti)
+                  g_qeglobals.d_num_move_points = 0;
+                AddPoint(p, p->ctrl[i][j].xyz);
+                //Sys_Printf("Selected col:row %d:%d\n", i, j);
+              }
+              //--if (!bMulti)
+              return;
+            }
+            else
+            {
+              if (bFull)
+              {
+                if (ColumnSelected(p, i))
+                {
+                  SelectRow(p, j, bMulti);
+                }
+                else
+                {
+                  SelectColumn(p, i, bMulti);
+                }
+                return;
+              }
+                         //if (!bMulti)
+                         //{
+              //    g_qeglobals.d_num_move_points = 0;
+              //    AddPoint(p, p->ctrl[i][j].xyz);
+                         //}
+              if (bMulti)// if (g_bSameView) // this is not having desired effect
+              {
+                RemovePointFromMoveList(v);
+                return;
+              }
+            }
+          }
+                   }
+           }
+    }
+  }
+}
+
+/*
+==================
+Patch_UpdateSelected
+==================
+*/
+void Patch_UpdateSelected(vec3_t vMove)
+{
+       int i;//, j;
+       for (i=0 ; i < g_qeglobals.d_num_move_points ; i++)
+       {
+               VectorAdd (g_qeglobals.d_move_points[i], vMove, g_qeglobals.d_move_points[i]);
+               if (g_qeglobals.d_num_move_points == 1)
+               {
+               }
+       }
+       
+       //--patchMesh_t* p = &patchMeshes[g_nSelectedPatch];
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+               if (pb->patchBrush)
+               {
+                       patchMesh_t* p = pb->pPatch;
+                       
+#if 0 //moving to SelectCurvePointByRay
+                       g_qeglobals.d_numpoints = 0;
+                       for (i = 0 ; i < p->width ; i++ ) 
+                       {
+                               for ( j = 0 ; j < p->height ; j++ ) 
+                               {
+                                       VectorCopy (p->ctrl[i][j].xyz, g_qeglobals.d_points[g_qeglobals.d_numpoints]);
+                                       if (g_qeglobals.d_numpoints < MAX_POINTS-1)
+                                       {
+                                               g_qeglobals.d_numpoints++;
+                                       }
+                               }
+                       }
+#endif                 
+                       vec3_t vMin, vMax;
+                       Patch_CalcBounds(p, vMin, vMax);
+                       Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+               }
+       }
+  //Brush_Free(p->pSymbiot);
+  //Select_Brush(AddBrushForPatch(g_nSelectedPatch));
+}
+
+
+
+/*
+===============
+SampleSinglePatch
+===============
+*/
+void SampleSinglePatch (float ctrl[3][3][5], float u, float v, float out[5]) {
+       float   vCtrl[3][5];
+       int             vPoint;
+       int             axis;
+
+       // find the control points for the v coordinate
+       for (vPoint = 0 ; vPoint < 3 ; vPoint++) 
+       {
+               for (axis = 0 ; axis < 5 ; axis++) 
+               {
+                       float   a, b, c;
+                       float   qA, qB, qC;
+
+                       a = ctrl[0][vPoint][axis];
+                       b = ctrl[1][vPoint][axis];
+                       c = ctrl[2][vPoint][axis];
+                       qA = a - 2 * b + c;
+                       qB = 2 * b - 2 * a;
+                       qC = a;
+
+                       vCtrl[vPoint][axis] = qA * u * u + qB * u + qC;
+               }
+       }
+
+       // interpolate the v value
+       for (axis = 0 ; axis < 5 ; axis++) 
+       {
+               float   a, b, c;
+               float   qA, qB, qC;
+
+               a = vCtrl[0][axis];
+               b = vCtrl[1][axis];
+               c = vCtrl[2][axis];
+               qA = a - 2 * b + c;
+               qB = 2 * b - 2 * a;
+               qC = a;
+
+               out[axis] = qA * v * v + qB * v + qC;
+       }
+}
+
+//spog - Curve LOD stuff starts
+
+float ShadeForNormal(vec3_t normal)
+{
+  float f;
+
+       vec3_t L;
+       L[0] = 1.0f;
+       L[1] = 1.0f;
+       L[2] = 1.0f;
+
+  
+       // quick diffuse shading
+  f = DotProduct(L, normal);
+
+  // range 0.5 to 1.0
+       f = (f+1)/4.0f;
+  //if (f < 0.0f) f = 0.0f;
+
+       f += 0.5f;
+       
+  return f;
+}
+
+void ShadeVertex (drawVert_t &p)
+{
+       p.lightmap[0] = ShadeForNormal(p.normal);
+}
+
+
+void Patch_DrawNormals(patchMesh_t *patch)
+{
+       int row, col;
+       vec3_t vNormal;
+
+       qglBegin (GL_LINES);
+       for (col=0; col<patch->width; col++)
+       {
+               for (row=0; row<patch->height; row++)
+               {
+                       VectorAdd(patch->ctrl[col][row].xyz, patch->ctrl[col][row].normal, vNormal);
+                       qglVertex3fv (patch->ctrl[col][row].xyz);
+                       qglVertex3fv (vNormal);
+               }
+       }
+       qglEnd ();
+}
+
+
+// take an array of three drawVerts, and the addresses of three more drawVerts
+// interpolate new XYZST values from the three drawVerts, these are:
+// the left sub-control-point, the right sub-control-point and the midpoint of the curve respectively
+// store these values in the drawVerts passed to the function
+void Patch_CurveSplit(drawVert_t *vCurve[3], drawVert_t &pLeft, drawVert_t &pRight, drawVert_t &pMid, float u)
+{
+       int i;
+       //float u = 0.5f;
+//     float a, b;
+       drawVert_t v1, v2, v3;
+//     vec3_t v4;
+       
+       for (i=0; i<3; i++)
+       {
+                // xyz
+               v1.xyz[i] = vCurve[1]->xyz[i] - vCurve[0]->xyz[i];
+               v2.xyz[i] = vCurve[2]->xyz[i] - vCurve[1]->xyz[i];
+               v1.xyz[i] *= u;
+               v2.xyz[i] *= u;
+               pLeft.xyz[i] = vCurve[0]->xyz[i] + v1.xyz[i];
+               pRight.xyz[i] = vCurve[1]->xyz[i] + v2.xyz[i];
+
+               v3.xyz[i] = pRight.xyz[i] - pLeft.xyz[i];
+               v3.xyz[i] *= u;
+               pMid.xyz[i] = pLeft.xyz[i] + v3.xyz[i];
+
+               // normal (weighted average) // no, that's b0rked
+               //a = 1 / u; // total
+               //b = u * a; // component 2
+               //a = u - b; // component 1
+               //pMid.normal[i] = u * ((vCurve[0]->normal[i] * b) + (vCurve[2]->normal[i] * a));
+
+               if (i==2) continue;
+
+               // st
+               v1.st[i] = vCurve[1]->st[i] - vCurve[0]->st[i];
+               v2.st[i] = vCurve[2]->st[i] - vCurve[1]->st[i];
+               v1.st[i] *= u;
+               v2.st[i] *= u;
+               pLeft.st[i] = vCurve[0]->st[i] + v1.st[i];
+               pRight.st[i] = vCurve[1]->st[i] + v2.st[i];
+
+               v3.st[i] = pRight.st[i] - pLeft.st[i];
+               v3.st[i] *= u;
+               pMid.st[i] = pLeft.st[i] + v3.st[i];
+       }
+}
+
+// take an array of three points, return an index representing the curvature of those three points
+// return zero if the curve is a straight line, unless the midpoint is not between the endpoints
+float Patch_CurveIndex(vec3_t vCurve[])
+{
+       vec3_t vTemp, v1, v2, v3, vClear;
+//     int i;
+       float width, angle;
+       float index, dot;
+
+       VectorClear(vClear);
+               
+       VectorSubtract(vCurve[2], vCurve[0], vTemp);
+       VectorSubtract(vCurve[1], vCurve[0], v1);
+       VectorSubtract(vCurve[2], vCurve[1], v2);
+
+       if (VectorCompare(v1, vClear) || VectorCompare(vTemp, v1)) // return 0 if 1->2 == 0 or 1->2 == 1->3
+               return 0.0f;
+
+       VectorNormalize(v1, v1);
+       VectorNormalize(v2, v2);
+       if (VectorCompare(v1, v2))
+               return 0.0f;
+       
+       VectorCopy(vTemp, v3);
+       width = VectorNormalize(v3, v3);
+
+       if (VectorCompare(v1, v3) && VectorCompare(v2, v3))
+               return 0.0f;
+       
+       dot = DotProduct(v1, v2);
+
+       angle = acos(dot) / Q_PI;
+
+       index = width * angle;
+
+       return index;
+}
+
+
+// create a new tree root, give it the coordinate values of the drawVert
+// return a pointer to the new tree root
+BTNode_t *BTree_Create(drawVert_t info)
+{
+       BTNode_t *BTree = new BTNode_t;
+       BTree->left = BTree->right = NULL;
+       VectorCopy(info.xyz, BTree->info.xyz);
+       VectorCopy(info.xyz, BTree->vMid.xyz);
+       for (int i=0; i<2; i++)
+       {
+               BTree->info.st[i] = info.st[i];
+               BTree->vMid.st[i] = info.st[i];
+       }
+       return BTree;
+}
+
+// take ownership of the subtree
+// delete the entire subtree
+// return a NULL pointer
+BTNode_t *BTree_Delete(BTNode_t *pBT)
+{
+       if (pBT != NULL)
+       {
+               BTree_Delete(pBT->left);
+               BTree_Delete(pBT->right);
+               delete pBT;
+       }
+       return NULL;
+}
+
+// NOT currently used
+BTNode_t *BTree_Clear(BTNode_t *pBT, bool bFirst = true)
+{
+       if (pBT != NULL)
+       {
+               BTree_Clear(pBT->left, false);
+               BTree_Clear(pBT->right, false);
+               if (!bFirst) delete pBT;
+       }
+       return pBT;
+}
+
+// take a pointer to the last item added to the list (this can also be a NULL pointer)
+// take a pointer to the root of a subtree, and the patch points to the left and right of it
+// add a new item to the subtree list, and add the subtree and its adjacent points to the new item
+// return a pointer to the last item added to the subtree list
+BTreeList_t *BTree_AddToList(BTreeList_t *pBTList, BTNode_t *pBT, drawVert_t &pLeft, drawVert_t &pRight)
+{
+       BTreeList_t *newBTList = new BTreeList_t;
+       newBTList->next = pBTList;
+       newBTList->pBT = pBT;
+       VectorCopy(pLeft.xyz, newBTList->vLeft.xyz);
+       VectorCopy(pRight.xyz, newBTList->vRight.xyz);
+       VectorCopy(pLeft.normal, newBTList->vLeft.normal);
+       VectorCopy(pRight.normal, newBTList->vRight.normal);
+       for (int i=0; i<2; i++)
+       {
+               newBTList->vLeft.st[i] = pLeft.st[i];
+               newBTList->vRight.st[i] = pRight.st[i];
+       }
+       return newBTList;
+}
+
+// NOT currently used, subtrees are now stored on the patch
+// take ownership of the subtree list
+// delete the entire list and the subtrees it points to
+// return a NULL pointer
+BTreeList_t *BTree_DeleteList(BTreeList_t *pBTList)
+{
+       if (pBTList != NULL)
+       {
+               BTree_DeleteList(pBTList->next);
+               pBTList->pBT = BTree_Delete(pBTList->pBT);
+               delete pBTList;
+       }
+       return NULL;
+}
+
+// take ownership of the subtree list
+// delete the entire subtree list, but not the subtrees themselves
+// return a NULL pointer
+BTreeList_t *BTree_DeletePointerList(BTreeList_t *pBTList)
+{
+       if (pBTList != NULL)
+       {
+               BTree_DeletePointerList(pBTList->next);
+               delete pBTList;
+       }
+       return NULL;
+}
+
+// take a pointer to the last item added to the list of subtree lists
+// add a subtree list to the list
+// return a pointer to the last item added
+BTListList_t *BTree_AddListToList(BTListList_t *pBTListList, BTreeList_t *pBTList)
+{
+       BTListList_t *newBTListList = new BTListList_t;
+       newBTListList->next = pBTListList;
+       newBTListList->list = pBTList;
+       return newBTListList;
+}
+
+
+// take ownership of the list of subtree lists
+// delete the entire list of lists, but not the subtrees themselves
+// return a NULL pointer
+BTListList_t *BTree_DeleteListFromList(BTListList_t *pBTListList)
+{
+       if (pBTListList != NULL)
+       {
+               BTree_DeleteListFromList(pBTListList->next);
+               pBTListList->list = BTree_DeletePointerList(pBTListList->list);
+               delete pBTListList;
+       }
+       return NULL;
+}
+
+// take a pointer to the last item in the list
+// add a NULL linker subtree to the list, setting the "flipped" flag using the left curvepoint normal .. er.. hacky?
+BTreeList_t *BTree_AddLinkToList(BTreeList_t *pBTList, bool bFlipped = false)
+{
+       BTreeList_t *linkBTList = new BTreeList_t;
+       linkBTList->pBT = NULL;
+       linkBTList->next = pBTList;
+       linkBTList->vLeft.normal[0] = (bFlipped) ? 1.0f : 0.0f;
+       return linkBTList;
+}
+
+
+// take an array of three points and the address of a vector
+// store midpoint of the bezier curve formed by the three points, in the vector
+void Patch_BezierInterpolate(vec3_t vCurve[], vec3_t &pMid)
+{
+       vec3_t vTemp;
+       int i;
+       VectorSubtract(vCurve[2], vCurve[0], vTemp); // Start->End
+       for (i=0; i<3; i++)
+               vTemp[i] /= 2;
+       VectorAdd(vCurve[0], vTemp, vTemp); // midpoint of Start->End
+
+       VectorSubtract(vTemp, vCurve[1], vTemp); // Mid->(midpoint of Start->End)
+       for (i=0; i<3; i++)
+               vTemp[i] /= 2;
+       VectorAdd(vCurve[1], vTemp, pMid); // midpoint of Mid->(midpoint of Start->End)
+}
+
+
+// take a pointer to the list of subtrees, and a threshold value
+// generate REAL surface curvature for the subtree curves, using bezier interpolation
+// if any of the real curves has an index greater than the threshold, return true 
+bool Patch_MostCurvedRow(BTreeList_t *pBTList, int threshold)
+{
+       BTreeList_t *p;
+       float index;//, bestindex = 0;
+       vec3_t vCurve[3];
+       vec3_t vRow[3];
+//     int i;
+
+       for (p = pBTList; p != NULL; p = p->next->next)
+       {
+               // this row
+               VectorCopy(p->vLeft.xyz, vCurve[0]);
+               VectorCopy(p->pBT->info.xyz, vCurve[1]);
+               VectorCopy(p->vRight.xyz, vCurve[2]);
+               
+               index = Patch_CurveIndex(vCurve);
+               if (index > threshold)
+                       return true;
+
+               if (p->next == NULL)
+                       break;
+
+               if (p->next->pBT == NULL) continue;
+
+               VectorCopy(p->vLeft.xyz, vCurve[0]);
+               VectorCopy(p->next->vLeft.xyz, vCurve[1]);
+               VectorCopy(p->next->next->vLeft.xyz, vCurve[2]);
+               Patch_BezierInterpolate(vCurve, vRow[0]);
+
+               VectorCopy(p->pBT->info.xyz, vCurve[0]);
+               VectorCopy(p->next->pBT->info.xyz, vCurve[1]);
+               VectorCopy(p->next->next->pBT->info.xyz, vCurve[2]);
+               Patch_BezierInterpolate(vCurve, vRow[1]);
+
+               VectorCopy(p->vRight.xyz, vCurve[0]);
+               VectorCopy(p->next->vRight.xyz, vCurve[1]);
+               VectorCopy(p->next->next->vRight.xyz, vCurve[2]);
+               Patch_BezierInterpolate(vCurve, vRow[2]);
+
+               index = Patch_CurveIndex(vRow);
+               if (index > threshold)
+                       return true;
+       }
+       return false;
+}
+
+
+// take a pointer to a list of subtrees.. each subtree in the list is a 3-point bezier curve formed by two endpoints owned by the list, and a midpoint subtree node owned by a patch.
+// if any of the subtrees are curved above a threshold, create a left and right subsubtree for each subtree in the list.
+// if a NULL linker subtree is found, check for an orientation flip - ie. an inverted LOD-match - and create a NULL subsubtree with the same orientation flip
+// this effectively generates trees for multiple patches at the same time.. the subtrees are always owned by their respective patches though
+void BTree_ListCurveRecurse(BTreeList_t *pBTList)
+{
+       BTreeList_t *p;
+       BTreeList_t *leftBTList, *rightBTList;
+       //drawVert_t pLeft, pRight, pMid;
+       drawVert_t *vCurve[3];
+       int threshold;
+       //int i;
+       bool bFlipped = false;
+
+  if (g_PrefsDlg.m_nSubdivisions >= 1)
+    threshold = g_PrefsDlg.m_nSubdivisions;
+       
+       leftBTList = rightBTList = NULL;
+       
+       if (Patch_MostCurvedRow(pBTList, threshold)) // split all subtrees in list if any subtree is above threshold
+       {
+               //Sys_Printf("| ");
+               // traverse nodes in list
+               for (p = pBTList; p != NULL; p=p->next)
+               {
+                       if (p->pBT == NULL) 
+                       {
+                               leftBTList = BTree_AddLinkToList(leftBTList, (p->vLeft.normal[0] == 1.0f));
+                               rightBTList = BTree_AddLinkToList(rightBTList, (p->vLeft.normal[0] == 1.0f));
+                               if (p->vLeft.normal[0] == 1.0f) bFlipped = (!bFlipped) ? true : false; // switch bFlipped if true
+                               continue;
+                       }
+
+                       // create left node for this subtree
+                       BTNode_t *newLeft = new BTNode_t;
+                       p->pBT->left = newLeft;
+                       newLeft->left = newLeft->right = NULL;
+                       
+                       // create right node for this subtree
+                       BTNode_t *newRight = new BTNode_t;
+                       p->pBT->right = newRight;
+                       newRight->left = newRight->right = NULL;
+
+                       // split this node
+                       vCurve[0] = &p->vLeft;
+                       vCurve[1] = &p->pBT->info;
+                       vCurve[2] = &p->vRight;
+                       Patch_CurveSplit(vCurve, newLeft->info, newRight->info, p->pBT->vMid, 0.5);
+
+                       memcpy(&newLeft->vMid, &newLeft->info, sizeof(drawVert_t));
+                       memcpy(&newRight->vMid, &newRight->info, sizeof(drawVert_t));
+                       
+                       
+                       if (!bFlipped)
+                       {
+                               // add new left subtree to left subtree list
+                               leftBTList = BTree_AddToList(leftBTList, newLeft, p->vLeft, p->pBT->vMid);
+                               
+                               // add new right subtree to right subtree list
+                               rightBTList = BTree_AddToList(rightBTList, newRight, p->pBT->vMid, p->vRight);
+                       }
+                       else
+                       {
+                               // add new left subtree to right subtree list
+                               rightBTList = BTree_AddToList(rightBTList, newLeft, p->vLeft, p->pBT->vMid);
+                               
+                               // add new right subtree to left subtree list
+                               leftBTList = BTree_AddToList(leftBTList, newRight, p->pBT->vMid, p->vRight);
+                       }
+               }
+
+               // continue tree left
+               BTree_ListCurveRecurse(leftBTList);
+               leftBTList = BTree_DeletePointerList(leftBTList);
+
+               // continue tree right
+               BTree_ListCurveRecurse(rightBTList);
+               rightBTList = BTree_DeletePointerList(rightBTList);
+       }
+}
+
+// take mins and maxs values from two brushes
+// return true if they intersect on every axis
+bool TouchingAABBs(vec3_t mins1, vec3_t maxs1, vec3_t mins2, vec3_t maxs2)
+{
+       //bool xyz[3];
+       vec3_t v1, v2, p1, p2, T;
+       for (int i=0; i<3; i++)
+       {
+               v1[i] = maxs1[i] - mins1[i];
+               v2[i] = maxs2[i] - mins2[i];
+               v1[i] /=2;
+               v2[i] /=2;
+               p1[i] = mins1[i] + v1[i];
+               p2[i] = mins2[i] + v2[i];
+               // p1 == origin of aabb1
+               // p2 == origin of aabb1
+               // v1 == displacement of aabb1
+               // v1 == displacement of aabb2
+               T[i] = p2[i] - p1[i]; // T == vector from aabb1 to aabb2
+               if ( fabs(T[i]) > (fabs(v1[i]) + fabs(v2[i])) )
+                       return false;
+       }
+       return true;
+}
+
+// take a pointer to the last item added to pBTList, a pointer to the patch, a row index (start) and a column index
+// generate a row of row-curve tree roots, owned by the patch and add the entire column of row-curves to the list, using the row index to decide the order to add
+// return a pointer to the last item added to the list
+BTreeList_t *Patch_CreateBTListForRows(BTreeList_t *pBTList, patchMesh_t *patch, int start, int col)
+{
+       int row, pos;
+       patch->colDirty[(col-1)/2] = true;
+                                               
+       if (start == 0)
+       {
+               for (row=0; row<patch->height; row++)
+               {
+                       pos = (((col-1)/2)*patch->height)+row;
+                       patch->rowLOD[pos] = BTree_Delete(patch->rowLOD[pos]);
+                       patch->rowLOD[pos] = BTree_Create(patch->ctrl[col][row]);
+                       pBTList = BTree_AddToList(pBTList, patch->rowLOD[pos], patch->ctrl[col-1][row], patch->ctrl[col+1][row]);
+               }
+       }
+       else
+       {
+               for (row=patch->height-1; row>=0; row--)
+               {
+                       pos = (((col-1)/2)*patch->height)+row;
+                       patch->rowLOD[pos] = BTree_Delete(patch->rowLOD[pos]);
+                       patch->rowLOD[pos] = BTree_Create(patch->ctrl[col][row]);
+                       pBTList = BTree_AddToList(pBTList, patch->rowLOD[pos], patch->ctrl[col-1][row], patch->ctrl[col+1][row]);
+               }
+       }
+       return pBTList;
+}
+
+// take a pointer to the last item added to pBTList, a pointer to the patch, a row index and a column index (start)
+// generate a row of column-curve tree roots, owned by the patch and add the entire row of column-curves to the list, using the column index to decide the order to add
+// return a pointer to the last item added to the list
+BTreeList_t *Patch_CreateBTListForCols(BTreeList_t *pBTList, patchMesh_t *patch, int row, int start)
+{
+       int col, pos;
+       patch->rowDirty[(row-1)/2] = true;
+
+       if (start == 0)
+       {
+               for (col=0; col<patch->width; col++)
+               {
+                       pos = (((row-1)/2)*patch->width)+col;
+                       patch->colLOD[pos] = BTree_Delete(patch->colLOD[pos]);
+                       patch->colLOD[pos] = BTree_Create(patch->ctrl[col][row]);
+                       pBTList = BTree_AddToList(pBTList, patch->colLOD[pos], patch->ctrl[col][row-1], patch->ctrl[col][row+1]);
+               }
+       }
+       else
+       {
+               for (col=patch->width-1; col>=0; col--)
+               {
+                       pos = (((row-1)/2)*patch->width)+col;
+                       patch->colLOD[pos] = BTree_Delete(patch->colLOD[pos]);
+                       patch->colLOD[pos] = BTree_Create(patch->ctrl[col][row]);
+                       pBTList = BTree_AddToList(pBTList, patch->colLOD[pos], patch->ctrl[col][row-1], patch->ctrl[col][row+1]);
+               }
+
+       }
+       return pBTList;
+}
+
+bool BTree_IsInList(BTreeList_t *pBTList, BTNode_t *pBT)
+{
+       BTreeList_t *p;
+       if (pBTList == NULL) return false;
+
+       for (p=pBTList; p != NULL; p=p->next)
+       {
+               if (p->pBT != NULL)
+               {
+                       if (p->pBT == pBT)
+        return true;
+               }
+       }
+       return false;
+}
+
+int Patch_DegenCurve(vec3_t &start, vec3_t &mid, vec3_t &end)
+{
+  if (VectorCompare(start, mid) || VectorCompare(end, mid))
+  {
+    if (VectorCompare(start, end)) return 2;
+    else return 1;
+  }
+  else return 0;
+}
+
+// take a pointer to the last item added to the list, and a pointer to a patch (this patch is the owner of the three drawverts)
+// take the addresses of three drawVerts, and compare them with the edges of all patches that touch the patch
+// if they match an edge, add the tree roots for that section of the matched patch to the list, and recurse for the opposite edge of that patch section. Also, set the matched patch Dirty, so that its drawlists will be rebuilt
+// return a pointer to the last item added
+BTreeList_t *Patch_FindLODMatches(patchMesh_t *patch, BTreeList_t *pBTList, drawVert_t &pMid, drawVert_t &pLeft, drawVert_t &pRight)
+{
+       brush_t *pb, *brushlist;
+       int row, col, i;//, pos;
+       vec3_t vTemp, v1, v2;//, vClear;
+  bool bAlreadyAdded;
+
+       //Sys_Printf("Patch_FindLODMatches: called\n");
+
+       if (VectorCompare(pMid.xyz, pLeft.xyz) && VectorCompare(pMid.xyz, pRight.xyz))
+               return pBTList;
+
+       //VectorClear(vClear);
+       VectorSubtract(pRight.xyz, pLeft.xyz, vTemp);
+       VectorSubtract(pMid.xyz, pLeft.xyz, v1);
+       VectorSubtract(pRight.xyz, pMid.xyz, v2);
+
+       //if (VectorCompare(v1, vClear) || VectorCompare(vTemp, v1)) // return null if 1->2 == 0 or 1->2 == 1->3
+       //      return pBTList;
+
+       VectorNormalize(v1, v1);
+       VectorNormalize(v2, v2);
+       if (VectorCompare(v1, v2))
+               return pBTList;
+
+       VectorNormalize(vTemp, vTemp);
+       if (VectorCompare(v1, vTemp) && VectorCompare(v2, vTemp))
+               return pBTList;
+
+       brushlist = &active_brushes;
+       for (i=0; i<2; i++)
+       {
+               for (pb = brushlist->next; pb != brushlist; pb=pb->next)
+               {
+                       if (!pb->patchBrush || pb->pPatch == patch)
+                               continue;
+
+                       // ignore this patch if its AABB does not touch the subject patch
+                       if (!TouchingAABBs(patch->pSymbiot->maxs, patch->pSymbiot->mins, pb->maxs, pb->mins))
+                               continue;
+
+      // all columns of curves
+                       for (col=1; col<pb->pPatch->width; col+=2)
+                       {
+                               if (pb->pPatch->colDirty[(col-1)/2]) continue;
+
+                               bAlreadyAdded = false;
+
+                         // top and bottom curves of this column
+                               for (row=0; row<pb->pPatch->height; row+=pb->pPatch->height-1)
+                               {
+          if (bAlreadyAdded)
+            continue;
+          //if (!BTree_IsInList(pBTList, pb->pPatch->rowLOD[(((col-1)/2)*patch->height)+row]))
+          //  continue;
+                                       // ignore this curve if it shares no mid ctrl point with the test curve
+                                       if (!VectorCompare (pb->pPatch->ctrl[col][row].xyz, pMid.xyz))
+                                               continue;
+                                       // ignore this curve if it is degenerate
+                                       if (VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col-1][row].xyz) || VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col+1][row].xyz))
+                                               continue;
+                                       // if curve matches the test curve directly
+                                       if (VectorCompare (pb->pPatch->ctrl[col-1][row].xyz, pLeft.xyz) && VectorCompare (pb->pPatch->ctrl[col+1][row].xyz, pRight.xyz))
+                                       {
+                                               // add a blank link as separator
+                                               pBTList = BTree_AddLinkToList(pBTList);
+                                               // add this entire column, if top, top-to-bottom, else bottom to top
+                                               pBTList = Patch_CreateBTListForRows(pBTList, pb->pPatch, row, col);
+                                               // continue checking from last curve added to list
+                                         pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);
+                                               // set flag
+                                               pb->pPatch->LODUpdated = true;
+            bAlreadyAdded = true;
+                                       }
+                                       // if curve matches test curve but flipped
+                                       else if (VectorCompare (pb->pPatch->ctrl[col-1][row].xyz, pRight.xyz) && VectorCompare (pb->pPatch->ctrl[col+1][row].xyz, pLeft.xyz))
+                                       {
+                                               pBTList = BTree_AddLinkToList(pBTList, true); // flip
+                                               pBTList = Patch_CreateBTListForRows(pBTList, pb->pPatch, row, col);
+                                               pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);                               
+                                               pb->pPatch->LODUpdated = true;
+            bAlreadyAdded = true;
+                                       }
+                               }
+                       }
+
+                       // all rows of curves
+                       for (row=1; row<pb->pPatch->height; row+=2)
+                       {
+                               if (pb->pPatch->rowDirty[(row-1)/2]) continue;
+
+                               bAlreadyAdded = false;
+
+                         for (col=0; col<pb->pPatch->width; col+=pb->pPatch->width-1)
+                               {
+          if (bAlreadyAdded)
+            continue;
+          //if (BTree_IsInList(pBTList, pb->pPatch->colLOD[(((row-1)/2)*patch->width)+col]))
+          //  continue;
+                                       if (!VectorCompare (pb->pPatch->ctrl[col][row].xyz, pMid.xyz))
+                                               continue;
+                                       if (VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col][row-1].xyz) || VectorCompare (pb->pPatch->ctrl[col][row].xyz, pb->pPatch->ctrl[col][row+1].xyz))
+                                               continue;
+                                       if (VectorCompare (pb->pPatch->ctrl[col][row-1].xyz, pLeft.xyz) && VectorCompare (pb->pPatch->ctrl[col][row+1].xyz, pRight.xyz))
+                                       {
+                                               pBTList = BTree_AddLinkToList(pBTList);
+                                               pBTList = Patch_CreateBTListForCols(pBTList, pb->pPatch, row, col);
+                                               pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);
+                                               pb->pPatch->LODUpdated = true;
+            bAlreadyAdded = true;
+                                       }
+                                       else if (VectorCompare (pb->pPatch->ctrl[col][row-1].xyz, pRight.xyz) && VectorCompare (pb->pPatch->ctrl[col][row+1].xyz, pLeft.xyz))
+                                       {
+                                               pBTList = BTree_AddLinkToList(pBTList, true); // flip
+                                               pBTList = Patch_CreateBTListForCols(pBTList, pb->pPatch, row, col);
+                                               pBTList = Patch_FindLODMatches(pb->pPatch, pBTList, pBTList->pBT->info, pBTList->vLeft, pBTList->vRight);
+            pb->pPatch->LODUpdated = true;
+            bAlreadyAdded = true;
+                                       }
+                               }
+                       }
+               }
+               brushlist = &selected_brushes;
+       }
+       return pBTList;
+}
+
+// take a pointer to a patch
+// create tree roots for all the rows and columns of curves in the patch, the patch takes ownership of these new tree roots
+// generate lists of pointers to all the trees in all the patches in the map which need to match the LOD of trees owned by this patch
+// store all the lists in a list of lists
+// recursively generate the rest of every tree in each list in the list
+void Patch_CreateLODTrees(patchMesh_t *patch)
+{
+       BTreeList_t *pBTList;
+       int col, row, pos;//, rowcount, colcount;
+       BTListList_t *pLists;
+
+       //Sys_Printf("Patch_CreateMatchedLODTrees: called\n");
+
+       BTListList_t *LODLists;
+       LODLists = NULL;
+       
+       pBTList = NULL;
+
+       patch->bDirty = false;
+       patch->LODUpdated = true;
+       
+       for(col=1; col<patch->width; col+=2)
+       {
+               if (patch->colDirty[(col-1)/2]) continue;
+               else patch->colDirty[(col-1)/2] = true;
+
+               // create list for rows of current patch
+               for(row=0; row<patch->height; row++)
+               {
+                       pos = (((col-1)/2)*patch->height)+row;
+                       patch->rowLOD[pos] = BTree_Delete(patch->rowLOD[pos]);
+                       patch->rowLOD[pos] = BTree_Create(patch->ctrl[col][row]);
+                       pBTList = BTree_AddToList(pBTList, patch->rowLOD[pos], patch->ctrl[col-1][row], patch->ctrl[col+1][row]);
+               }
+       
+               //create connection list for first row
+               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[col][0], patch->ctrl[col-1][0], patch->ctrl[col+1][0]);
+               //create connection list for last row
+               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[col][row-1], patch->ctrl[col-1][row-1], patch->ctrl[col+1][row-1]);
+
+               LODLists = BTree_AddListToList(LODLists, pBTList);
+               pBTList = NULL;
+       }
+
+       pBTList = NULL;
+       for(row=1; row<patch->height; row+=2)
+       {
+               if (patch->rowDirty[(row-1)/2]) continue;
+               else patch->rowDirty[(row-1)/2] = true;
+
+               // create list for cols of current patch
+               for(col=0; col<patch->width; col++)
+               {
+                       pos = (((row-1)/2)*patch->width)+col;
+                       patch->colLOD[pos] = BTree_Delete(patch->colLOD[pos]);
+                       patch->colLOD[pos] = BTree_Create(patch->ctrl[col][row]);
+                       pBTList = BTree_AddToList(pBTList, patch->colLOD[pos], patch->ctrl[col][row-1], patch->ctrl[col][row+1]);
+               }
+
+               //create connection list for first col
+               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[0][row], patch->ctrl[0][row-1], patch->ctrl[0][row+1]);
+               //create connection list for last col
+               pBTList = Patch_FindLODMatches(patch, pBTList, patch->ctrl[col-1][row], patch->ctrl[col-1][row-1], patch->ctrl[col-1][row+1]);
+
+               LODLists = BTree_AddListToList(LODLists, pBTList);
+               pBTList = NULL;
+       }
+
+       for (pLists = LODLists; pLists != NULL; pLists=pLists->next)
+               BTree_ListCurveRecurse(pLists->list);
+       LODLists = BTree_DeleteListFromList(LODLists);
+}
+
+int Patch_GetCVTangent(vec3_t &v1, vec3_t &p1, vec3_t &p2, vec3_t &p3)
+{
+       if (VectorCompare(p1, p2))
+       {
+               if (VectorCompare(p1, p3))
+               {
+                       return 2;
+               }
+               else VectorSubtract(p3, p1, v1);
+    return 1;
+       }
+       else VectorSubtract(p2, p1, v1);
+  return 0;
+}
+
+void Patch_CVNormal(vec3_t ctrl[3][3], vec3_t &normal)
+{
+       vec3_t v1, v2, vTemp1, vTemp2;
+  int a, b;
+       
+  a = Patch_GetCVTangent(v1, ctrl[0][0], ctrl[1][0], ctrl[2][0]);
+       b = Patch_GetCVTangent(v2, ctrl[0][0], ctrl[0][1], ctrl[0][2]);
+
+       //Sys_Printf("p1: (%1.1f %1.1f %1.1f) p2: (%1.1f %1.1f %1.1f) p2: (%1.1f %1.1f %1.1f)\n",
+       //      ctrl[0][0][0], ctrl[0][0][1], ctrl[0][0][2], ctrl[0][2][0], ctrl[0][2][1], ctrl[0][2][2], ctrl[2][0][0], ctrl[2][0][1], ctrl[2][0][2]);
+       
+  if (a == 2)
+  {
+    a = Patch_GetCVTangent(v1, ctrl[0][0], ctrl[1][1], ctrl[1][2]);
+  }
+  if (b == 2)
+  {
+    b = Patch_GetCVTangent(v2, ctrl[0][0], ctrl[1][1], ctrl[2][1]);
+  }
+  if (a == 2)
+  {
+    a = Patch_GetCVTangent(v1, ctrl[0][0], ctrl[2][1], ctrl[2][2]);
+  }
+  if (b == 2)
+  {
+    b = Patch_GetCVTangent(v2, ctrl[0][0], ctrl[1][2], ctrl[2][2]);
+  }  
+
+       CrossProduct(v1, v2, normal);
+
+  
+  if (normal[0] == 0.0f && normal[1] == 0.0f && normal[2] == 0.0f)
+  {
+    // more degenerate cases
+    vec3_t pMid;
+    vec3_t vCurve[3];
+    /*
+    if (VectorCompare(ctrl[0][0], ctrl[2][0])) // endcap left
+    {
+      if (VectorCompare(ctrl[0][2], ctrl[1][2]))
+      {
+        VectorSubtract(ctrl[2][2], ctrl[0][0], v2);
+      }
+      else if (VectorCompare(ctrl[1][2], ctrl[2][2]))
+      {
+        VectorSubtract(ctrl[0][2], ctrl[0][0], v2);
+      }
+      else
+      a = Patch_DegenCurve(ctrl[0][2], ctrl[1][2], ctrl[2][2]);
+      if (a == 0)
+      {
+        VectorCopy(ctrl[0][2], vCurve[0]);
+        VectorCopy(ctrl[1][2], vCurve[1]);
+        VectorCopy(ctrl[2][2], vCurve[2]);
+        Patch_BezierInterpolate(vCurve, pMid);
+                         VectorSubtract(pMid, ctrl[0][0], v1);
+      }
+      
+      
+               }
+         else if (VectorCompare(ctrl[0][0], ctrl[0][2])) // endcap right
+               {
+      
+      if (VectorCompare(ctrl[2][0], ctrl[2][1]))
+      {
+        VectorSubtract(ctrl[2][2], ctrl[0][0], v2);
+      }
+      else if (VectorCompare(ctrl[2][1], ctrl[2][2]))
+      {
+        VectorSubtract(ctrl[2][0], ctrl[0][0], v2);
+      }
+      else
+      
+      b = Patch_DegenCurve(ctrl[2][0], ctrl[2][1], ctrl[2][2]);
+      if (b == 0)
+      {
+                   VectorCopy(ctrl[2][0], vCurve[0]);
+        VectorCopy(ctrl[2][1], vCurve[1]);
+        VectorCopy(ctrl[2][2], vCurve[2]);
+        Patch_BezierInterpolate(vCurve, pMid);
+                         VectorSubtract(pMid, ctrl[0][0], v2);
+      }
+      
+               }
+    */
+    if (VectorCompare(ctrl[0][0], ctrl[2][0])) // bottom degen
+    {
+      Patch_GetCVTangent(v1, ctrl[0][0], ctrl[2][1], ctrl[2][2]);
+    }
+    else if (VectorCompare(ctrl[0][0], ctrl[0][2])) // left degen
+    {
+      Patch_GetCVTangent(v2, ctrl[0][0], ctrl[1][2], ctrl[2][2]);
+    }
+    else if (VectorCompare(ctrl[0][2], ctrl[2][2])) // top degen
+    {
+      VectorSubtract(ctrl[2][0], ctrl[0][0], v1);
+    }
+    else if (VectorCompare(ctrl[2][0], ctrl[2][2])) // right degen
+    {
+      VectorSubtract(ctrl[0][2], ctrl[0][0], v2);
+    }
+    else // tangents parallel
+    {
+      VectorCopy(v1, vTemp1);
+      VectorCopy(v2, vTemp2);
+      VectorNormalize(vTemp1, vTemp1);
+      VectorNormalize(vTemp2, vTemp2);
+      if (VectorCompare(vTemp1, vTemp2)) // parallel same way
+      {
+        VectorSubtract(ctrl[2][0], ctrl[0][0], vTemp1);
+        VectorNormalize(vTemp1, vTemp1);
+        if (VectorCompare(vTemp1, vTemp2))
+        {
+          VectorSubtract(ctrl[0][2], ctrl[0][0], v2);
+        }
+        else
+        {
+          VectorCopy(vTemp1, v1);
+        }
+      }
+      else // parallel opposite way
+      {
+                   VectorCopy(ctrl[2][0], vCurve[0]);
+        VectorCopy(ctrl[1][1], vCurve[1]);
+        VectorCopy(ctrl[0][2], vCurve[2]);
+        Patch_BezierInterpolate(vCurve, pMid);
+                         VectorSubtract(pMid, ctrl[0][0], v2);
+                 }
+    }
+
+    CrossProduct(v1, v2, normal);
+  }
+}
+
+void Patch_CalcCVNormals(patchMesh_t *patch)
+{
+       int row, col, i, j, n;
+       vec3_t ctrl[3][3];
+       vec3_t normals[4];
+
+       for (col=0; col<patch->width; col+=2)
+       {
+               for (row=0; row<patch->height; row+=2)
+               {
+                       n=0;
+                       if (col+1 != patch->width && row+1 != patch->height)
+                       {
+                               for (i=0; i<3; i++)
+                                       for (j=0; j<3; j++)
+                                               VectorCopy (patch->ctrl[col+i][row+j].xyz, ctrl[i][j]);
+
+                               Patch_CVNormal(ctrl, normals[n]);
+        VectorNormalize(normals[n], normals[n]);
+                               n++;
+                       }
+
+                       if (col-1 >= 0 && row-1 >= 0)
+                       {
+                               for (i=0; i<3; i++)
+                                       for (j=0; j<3; j++)
+                                               VectorCopy (patch->ctrl[col-i][row-j].xyz, ctrl[i][j]);
+
+                               Patch_CVNormal(ctrl, normals[n]);
+        VectorNormalize(normals[n], normals[n]);
+                               n++;
+                       }
+                       if (col-1 >= 0 && row+1 != patch->height)
+                       {
+                               for (i=0; i<3; i++)
+                                       for (j=0; j<3; j++)
+                                               VectorCopy (patch->ctrl[col-i][row+j].xyz, ctrl[j][i]);
+
+                               Patch_CVNormal(ctrl, normals[n]);
+        VectorNormalize(normals[n], normals[n]);
+                               n++;
+                       }
+                       if (col+1 != patch->width && row-1 >= 0)
+                       {
+                               for (i=0; i<3; i++)
+                                       for (j=0; j<3; j++)
+                                               VectorCopy (patch->ctrl[col+i][row-j].xyz, ctrl[j][i]);
+
+                               Patch_CVNormal(ctrl, normals[n]);
+        VectorNormalize(normals[n], normals[n]);
+                               n++;
+                       }
+
+                       for (i=0; i<3; i++)
+                       {
+                               if (n == 1) patch->ctrl[col][row].normal[i] = normals[0][i];
+                               if (n == 2) patch->ctrl[col][row].normal[i] = (normals[0][i] + normals[1][i]) / n;
+                               //if (n == 3) patch->ctrl[col][row].normal[i] = (normals[0][i] + normals[1][i] + normals[2][i]) / n;
+                               if (n == 4) patch->ctrl[col][row].normal[i] = (normals[0][i] + normals[1][i] + normals[2][i] + normals[3][i]) / n;
+                       }
+                       VectorNormalize(patch->ctrl[col][row].normal, patch->ctrl[col][row].normal);
+                       //if (!g_PrefsDlg.m_bGLLighting)
+                       //      ShadeVertex(patch->ctrl[col][row]);
+               }
+       }
+}
+
+
+void BTree_SetNormals(BTNode_t *pBT, vec3_t &normal)
+{
+       if (pBT != NULL)
+       {
+               if (pBT->left != NULL && pBT->right != NULL)
+               {
+                       VectorCopy(normal, pBT->vMid.normal);
+                       //if (!g_PrefsDlg.m_bGLLighting)
+                       //      ShadeVertex(pBT->vMid);
+               }
+               BTree_SetNormals(pBT->left, normal);
+               BTree_SetNormals(pBT->right, normal);
+       }
+}
+
+
+void NormalFromPoints(vec3_t p1, vec3_t p2, vec3_t p3, vec3_t &normal, bool flip = false)
+{
+  vec3_t v1, v2;
+
+  if (flip)
+  {
+    VectorSubtract(p2, p3, v1); //p3->p2
+         VectorSubtract(p1, p2, v2); //p2->p1
+  }
+  else
+  {
+    VectorSubtract(p2, p1, v1); //p1->p2
+         VectorSubtract(p3, p2, v2); //p2->p3
+  }
+       CrossProduct(v1, v2, normal);
+}
+
+
+void BTree_GenerateNormals(BTNode_t *pBTMid, BTNode_t *pBTLeft, BTNode_t *pBTRight, bool avg, bool flat, bool nomid, bool noleft, bool noright, /*bool endcap, vec3_t &n1, vec3_t &n2,*/ bool flip)
+{
+       if (pBTMid != NULL)
+       {
+               if (pBTMid->left != NULL && pBTMid->right != NULL)
+               {
+                       vec3_t normal;
+     
+      if (noleft) // left curve is degenerate
+      {
+        if (nomid) // mid curve is degenerate
+        {
+          NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, normal, flip);
+               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);
+        }
+        //else if (endcap)
+        //{
+        //  VectorCopy(n1, normal);
+        //  NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);
+        //}
+        else
+        {
+          NormalFromPoints(pBTMid->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);
+               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);
+        }
+      }
+      else if (noright) // right curve is degenerate
+      {
+        if (nomid) // mid curve is degenerate
+        {
+          NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);
+               NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);
+        }
+        //else if (endcap)
+        //{
+        //  NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);
+        //  VectorCopy(n2, pBTRight->vMid.normal);
+        //}
+        else
+        {
+          NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);
+               NormalFromPoints(pBTMid->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);
+        }
+      }
+      else
+      {
+        if (flat) // all curves are semi-degenerate (flat) or degenerate
+        {
+          NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTRight->vMid.xyz, normal, flip);
+               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTLeft->vMid.xyz, pBTRight->vMid.normal, flip);
+        }
+        else
+        {
+                     NormalFromPoints(pBTLeft->left->info.xyz, pBTLeft->vMid.xyz, pBTMid->vMid.xyz, normal, flip);
+               NormalFromPoints(pBTRight->right->info.xyz, pBTRight->vMid.xyz, pBTMid->vMid.xyz, pBTRight->vMid.normal, flip);
+        }
+      }
+
+      VectorNormalize(normal, normal);
+                       if (avg)
+                               for (int i=0; i<3; i++)
+                                       pBTLeft->vMid.normal[i] = (normal[i] + pBTLeft->vMid.normal[i]) / 2.0f;
+                       else VectorCopy(normal, pBTLeft->vMid.normal);
+     
+                       VectorNormalize(pBTLeft->vMid.normal, pBTLeft->vMid.normal);
+      VectorNormalize(pBTRight->vMid.normal, pBTRight->vMid.normal);
+
+               }
+               BTree_GenerateNormals(pBTMid->left, pBTLeft->left, pBTRight->left, avg, flat, nomid, noleft, noright, /*endcap, n1, n2,*/ flip);
+               BTree_GenerateNormals(pBTMid->right, pBTLeft->right, pBTRight->right, avg, flat, nomid, noleft, noright, /*endcap, n1, n2,*/ flip);
+       }
+}
+
+
+
+void Patch_GenerateLODNormals(patchMesh_t *patch)
+{
+  int col, row, rowpos, colpos, i;
+  BTNode_t *tree[2][3];
+  int degen[2][3];
+  bool rowAvg, colAvg;
+
+  for(col=0; col+2<patch->width; col+=2)
+       {
+               for(row=0; row+2<patch->height; row+=2)
+               {
+      if (!patch->colDirty[col/2] && !patch->rowDirty[row/2]) continue;  
+               rowpos = ((col/2)*patch->height)+row;
+      colpos = ((row/2)*patch->width)+col;
+      
+      if (row==0) rowAvg = false;
+      else rowAvg = true;
+      if (col==0) colAvg = false;
+      else colAvg = true;
+
+      for (i=0; i<3; i++)
+      {
+        tree[0][i] = patch->rowLOD[rowpos+i];
+        tree[1][i] = patch->colLOD[colpos+i];
+        
+        degen[0][i] = Patch_DegenCurve(patch->ctrl[col][row+i].xyz, patch->ctrl[col+1][row+i].xyz, patch->ctrl[col+2][row+i].xyz);
+        degen[1][i] = Patch_DegenCurve(patch->ctrl[col+i][row].xyz, patch->ctrl[col+i][row+1].xyz, patch->ctrl[col+i][row+2].xyz);
+      }
+
+      BTree_GenerateNormals(tree[0][1], tree[0][0], tree[0][2], rowAvg, (degen[1][0] && degen[1][1] && degen[1][2]), degen[0][1] == 2, degen[0][0] == 2, degen[0][2] == 2, /*degen[1][1], patch->ctrl[col][row].normal, patch->ctrl[col][row+2].normal,*/ false);
+      BTree_GenerateNormals(tree[1][1], tree[1][0], tree[1][2], colAvg, (degen[0][0] && degen[0][1] && degen[0][2]), degen[1][1] == 2, degen[1][0] == 2, degen[1][2] == 2, /*degen[0][1], patch->ctrl[col][row].normal, patch->ctrl[col+2][row].normal,*/ true);
+    }
+  }
+}
+
+
+void Patch_ClearLODFlags(patchMesh_t *p)
+{
+       int i;
+
+       for (i=0;i<(p->width-1)/2; i++)
+               p->colDirty[i] = false;
+
+       for (i=0;i<(p->height-1)/2; i++)
+               p->rowDirty[i] = false;
+}
+
+// reset the lodDirty flags owned by all patches in the map
+// create new LOD trees for all dirty patches, matched with all other patches in the map
+void Patch_LODMatchAll()
+{
+       brush_t *pb, *brushlist;
+       int i;
+
+       // create LOD tree roots and LOD tree lists for all patches that are dirty
+
+       brushlist = &active_brushes;
+       for (i=0; i<2; i++)
+       {
+               for (pb = brushlist->next; pb && (pb != brushlist); pb=pb->next)
+               {
+      // create lod for selected patches when patches are filtered
+                       if (pb->bFiltered && (pb->patchBrush && !pb->pPatch->bSelected))
+                               continue;
+                       if (!pb->patchBrush)
+                               continue;
+                       if (!pb->pPatch->bDirty)
+                               continue;
+
+      Patch_CalcCVNormals(pb->pPatch);
+                       Patch_CreateLODTrees(pb->pPatch);
+               }
+               brushlist = &selected_brushes;
+       }
+
+       brushlist = &active_brushes;
+       for (i=0; i<2; i++)
+       {
+               for (pb = brushlist->next; pb && (pb != brushlist); pb=pb->next)
+               {
+                       if (!pb->patchBrush)
+                               continue;
+
+      if (pb->pPatch->LODUpdated)
+                         Patch_GenerateLODNormals(pb->pPatch);
+
+      Patch_ClearLODFlags(pb->pPatch);
+    }
+               brushlist = &selected_brushes;
+       }
+
+}
+
+void Vertex_TransformTexture(drawVert_t *pVert, float fx, float fy, transformtype xform)
+{
+  switch(xform)
+  {
+  case TRANSLATE:
+    pVert->st[0] += fx;
+    pVert->st[1] += fy;
+    break;
+  case SCALE:
+    pVert->st[0] *= fx;
+    pVert->st[1] *= fy;
+    break;
+  case ROTATE:
+    float x = pVert->st[0];
+    float y = pVert->st[1];
+    pVert->st[0] = x * fx - y * fy;
+    pVert->st[1] = y * fx + x * fy;
+  }
+}
+
+void BTree_TransformTexture(BTNode_t *pBT, float fx, float fy, transformtype xform)
+{
+       if (pBT != NULL)
+       {       // PreOrder traversal
+               Vertex_TransformTexture(&pBT->info, fx, fy, xform);
+    Vertex_TransformTexture(&pBT->vMid, fx, fy, xform);
+               BTree_TransformTexture(pBT->left, fx, fy, xform);
+               BTree_TransformTexture(pBT->right, fx, fy, xform);
+       }
+}
+
+void Patch_TransformLODTexture(patchMesh_t *p, float fx, float fy, transformtype xform)
+{
+       int col, row;
+
+       for(col=1; col<p->width; col+=2)
+               for(row=0; row<p->height; row++)
+                       BTree_TransformTexture(p->rowLOD[(((col-1)/2)*p->height)+row], fx, fy, xform);
+
+       for(row=1; row<p->height; row+=2)
+               for(col=0; col<p->width; col++)
+                       BTree_TransformTexture(p->colLOD[(((row-1)/2)*p->width)+col], fx, fy, xform);
+}
+
+void Patch_AddBTreeToDrawListInOrder(list<drawVert_t> *drawList, BTNode_t *pBT)
+{
+       if (pBT != NULL) //traverse InOrder
+       {
+               Patch_AddBTreeToDrawListInOrder(drawList, pBT->left);
+               if (pBT->left != NULL && pBT->right != NULL)
+                       drawList->push_back(pBT->vMid);
+               Patch_AddBTreeToDrawListInOrder(drawList, pBT->right);
+       }
+}
+
+void Patch_InterpolateListFromRowBT(list<drawVert_t> *drawList, BTNode_t *rowBT, BTNode_t *rowBTLeft, drawVert_t *vCurve[], float u, float n, float v)
+{
+       if (rowBT != NULL)
+       {
+               Patch_InterpolateListFromRowBT(drawList, rowBT->left, rowBTLeft->left, vCurve, u-n, n*0.5f, v);
+               if (rowBT->left != NULL && rowBT->right != NULL)
+               {
+                       vec3_t v1, v2;
+                       drawVert_t newVert, vTemp1, vTemp2;
+                       Patch_CurveSplit(vCurve, vTemp1, vTemp2, newVert, u);
+                       for (int i=0; i<3; i++)
+                       {
+                               v1[i] = rowBT->vMid.xyz[i] - rowBTLeft->vMid.xyz[i]; // left -> mid
+                               v1[i] = rowBTLeft->vMid.xyz[i] + (v1[i] * v);
+                               v1[i] = newVert.xyz[i] - v1[i];
+                       }
+                       VectorSubtract(vTemp1.xyz, newVert.xyz, v2);
+                       CrossProduct(v1, v2, newVert.normal);
+                       VectorNormalize(newVert.normal, newVert.normal);
+                       //if (!g_PrefsDlg.m_bGLLighting)
+                       //      ShadeVertex(newVert);
+                       drawList->push_back(newVert);
+               }
+               Patch_InterpolateListFromRowBT(drawList, rowBT->right, rowBTLeft->right, vCurve, u+n, n*0.5f, v);
+       }
+}
+
+void Patch_TraverseColBTInOrder(list<list<drawVert_t>*>::iterator& iter, BTNode_t *colBTLeft, BTNode_t *colBT, BTNode_t *colBTRight, BTNode_t *rowBT, BTNode_t *rowBTLeft, float v, float n)
+{
+       if (colBT != NULL)
+       {
+                //traverse subtree In Order
+               Patch_TraverseColBTInOrder(iter, colBTLeft->left, colBT->left, colBTRight->left, rowBT, rowBTLeft, v-n, n*0.5f);
+               if (colBT->left != NULL && colBT->right != NULL)
+               {
+                       drawVert_t *vCurve[3];
+                       vCurve[0] = &colBTLeft->vMid;
+                       vCurve[1] = &colBT->vMid;
+                       vCurve[2] = &colBTRight->vMid;
+                       Patch_InterpolateListFromRowBT((*iter), rowBT, rowBTLeft, vCurve, 0.5f, 0.25f, v);
+
+                       (*iter)->push_back(colBTRight->vMid);
+                       iter++;
+               }
+               Patch_TraverseColBTInOrder(iter, colBTLeft->right, colBT->right, colBTRight->right, rowBT, rowBTLeft, v+n, n*0.5f);
+       }
+}
+
+
+void Patch_StartDrawLists(list<list<drawVert_t>*> *drawLists, BTNode_t *colBT)
+{
+       if (colBT != NULL)
+       {
+                //traverse subtree In Order
+               Patch_StartDrawLists(drawLists, colBT->left);
+               if (colBT->left != NULL && colBT->right != NULL)
+               {
+                       list<drawVert_t> *newList = new list<drawVert_t>;
+                       drawLists->push_back(newList); // add empty list to back
+                       drawLists->back()->push_back(colBT->vMid);
+               }
+               Patch_StartDrawLists(drawLists, colBT->right);
+       }
+}
+
+typedef list<drawVert_t> drawList_t;
+typedef list<list<drawVert_t>*> drawLists_t;
+
+void Patch_CreateDrawLists(patchMesh_t *patch)
+{
+  int col, row, colpos, rowpos;
+
+       drawLists_t *drawLists = new drawLists_t;
+
+       drawLists_t::iterator iter1, iter2;
+
+       for (row=0; row<patch->height; row+=2)
+       {
+               colpos = (row/2)*patch->width;
+               drawList_t *newList = new drawList_t;
+               drawLists->push_back(newList); // add a new empty list to back
+               drawLists->back()->push_back(patch->ctrl[0][row]); // fill list at back
+
+               if (row+1 == patch->height)
+                       continue;
+               Patch_StartDrawLists(drawLists, patch->colLOD[colpos]);
+       }
+
+       iter1 = drawLists->begin();
+       for (row=0; row<patch->height; row+=2)
+       {
+               iter2 = iter1;
+               for (col=0; col+1<patch->width; col+=2)
+               {
+                       iter1 = iter2;
+                       colpos = ((row/2)*patch->width)+col;
+                       rowpos = ((col/2)*patch->height)+row;
+
+      Patch_AddBTreeToDrawListInOrder((*iter1), patch->rowLOD[rowpos]);
+                       (*iter1)->push_back(patch->ctrl[col+2][row]);
+                       
+                       if (row+1 == patch->height)
+                               continue;
+               
+                       iter1++;        
+
+      Patch_TraverseColBTInOrder(iter1, patch->colLOD[colpos], patch->colLOD[colpos+1], patch->colLOD[colpos+2], patch->rowLOD[rowpos+1], patch->rowLOD[rowpos], 0.5, 0.25);
+               }
+       }
+
+  patch->drawLists = drawLists;
+}
+
+
+void Patch_DeleteDrawLists(patchMesh_t *patch)
+{
+  drawLists_t *drawLists;
+  drawLists_t::iterator iter;
+
+  if (patch->drawLists == NULL)
+    return;
+
+  drawLists = (drawLists_t *)patch->drawLists;
+
+       for (iter=drawLists->begin(); iter != drawLists->end(); iter++)
+       {
+               delete (*iter);
+       }
+
+  delete drawLists;
+  patch->drawLists = NULL;
+}
+
+
+void Patch_DrawLODPatchMesh(patchMesh_t *patch)
+{
+       drawLists_t *drawLists;
+
+       drawLists_t::iterator iterLists, iterListsNext;
+       drawList_t::iterator iterList, iterListNext;
+
+  //int nGLState = g_pParentWnd->GetCamera()->Camera()->draw_glstate;
+
+  if (patch->drawLists == NULL)
+    return;
+
+  drawLists = (drawLists_t *)patch->drawLists;
+
+       iterListsNext=drawLists->begin();
+       iterListsNext++;
+       for (iterLists=drawLists->begin(); iterLists != drawLists->end() && iterListsNext != drawLists->end(); iterLists++, iterListsNext++)
+  {
+               // traverse two drawlists at once to draw a strip
+    //if (nGLState & DRAW_GL_LINE)
+                 qglBegin(GL_QUAD_STRIP);
+    //else
+    //  qglBegin(GL_TRIANGLE_STRIP);
+               for (iterList=(*iterLists)->begin(), iterListNext=(*iterListsNext)->begin(); iterList != (*iterLists)->end() && iterListNext != (*iterListsNext)->end(); iterList++, iterListNext++)
+               {
+                       //if (g_PrefsDlg.m_bGLLighting)
+                               qglNormal3fv((*iterList).normal);
+                       //else if (bShade && !g_PrefsDlg.m_bDisplayLists)
+                       //      qglColor3f((*iterList).lightmap[0], (*iterList).lightmap[0], (*iterList).lightmap[0]);
+
+                       qglTexCoord2fv((*iterList).st);
+                       qglVertex3fv((*iterList).xyz);
+
+                 //if (g_PrefsDlg.m_bGLLighting)
+                               qglNormal3fv((*iterListNext).normal);
+                       //else if (bShade && !g_PrefsDlg.m_bDisplayLists)
+                       //      qglColor3f((*iterListNext).lightmap[0], (*iterListNext).lightmap[0], (*iterListNext).lightmap[0]);
+
+                       qglTexCoord2fv((*iterListNext).st);
+                       qglVertex3fv((*iterListNext).xyz);
+    }
+               qglEnd();
+  }
+/*
+#ifdef _DEBUG
+  vec3_t vNormal;
+  for (iterLists=drawLists->begin(); iterLists != drawLists->end(); iterLists++)
+  {
+               qglBegin (GL_LINES); // draw normals
+               //qglColor3f(1,1,1);
+               for (iterList=(*iterLists)->begin(); iterList != (*iterLists)->end(); iterList++)
+               {
+                       VectorAdd((*iterList).xyz, (*iterList).normal, vNormal);
+                       qglVertex3fv ((*iterList).xyz);
+                       qglVertex3fv (vNormal);
+               }
+               qglEnd ();
+  }
+
+       Patch_DrawNormals(patch);
+
+#endif
+  */
+}
+
+/*
+// fast memory-efficient ray-triangle intersection - MollerTrumbore97 
+
+#define EPSILON 0.000001
+#define CROSS(dest,v1,v2) {dest[0]=v1[1]*v2[2]-v1[2]*v2[1];dest[1]=v1[2]*v2[0]-v1[0]*v2[2];dest[2]=v1[0]*v2[1]-v1[1]*v2[0];}
+#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2])
+#define SUB(dest,v1,v2) {dest[0]=v1[0]-v2[0];dest[1]=v1[1]-v2[1];dest[2]=v1[2]-v2[2];}
+
+int intersect_triangle(float orig[3], float dir[3],
+                   float vert0[3], float vert1[3], float vert2[3],
+                   double *t, double *u, double *v)
+{
+   double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
+   double det,inv_det;
+
+   // find vectors for two edges sharing vert0
+   SUB(edge1, vert1, vert0);
+   SUB(edge2, vert2, vert0);
+
+   // begin calculating determinant - also used to calculate U parameter 
+   CROSS(pvec, dir, edge2);
+
+   // if determinant is near zero, ray lies in plane of triangle
+   det = DOT(edge1, pvec);
+
+#ifdef TEST_CULL           // define TEST_CULL if culling is desired
+   if (det < EPSILON)
+      return 0;
+
+   // calculate distance from vert0 to ray origin
+   SUB(tvec, orig, vert0);
+
+   // calculate U parameter and test bounds
+   *u = DOT(tvec, pvec);
+   if (*u < 0.0 || *u > det)
+      return 0;
+
+   // prepare to test V parameter
+   CROSS(qvec, tvec, edge1);
+
+    // calculate V parameter and test bounds
+   *v = DOT(dir, qvec);
+   if (*v < 0.0 || *u + *v > det)
+      return 0;
+
+   // calculate t, scale parameters, ray intersects triangle
+   *t = DOT(edge2, qvec);
+   inv_det = 1.0 / det;
+   *t *= inv_det;
+   *u *= inv_det;
+   *v *= inv_det;
+#else                    // the non-culling branch
+   if (det > -EPSILON && det < EPSILON)
+     return 0;
+   inv_det = 1.0 / det;
+
+   // calculate distance from vert0 to ray origin
+   SUB(tvec, orig, vert0);
+
+   // calculate U parameter and test bounds
+   *u = DOT(tvec, pvec) * inv_det;
+   if (*u < 0.0 || *u > 1.0)
+     return 0;
+
+   // prepare to test V parameter
+   CROSS(qvec, tvec, edge1);
+
+   // calculate V parameter and test bounds
+   *v = DOT(dir, qvec) * inv_det;
+   if (*v < 0.0 || *u + *v > 1.0)
+     return 0;
+
+   // calculate t, ray intersects triangle
+   *t = DOT(edge2, qvec) * inv_det;
+#endif
+   return 1;
+}
+*/
+
+int Triangle_Ray(float orig[3], float dir[3], bool bCullBack,
+                 float vert0[3], float vert1[3], float vert2[3],
+                 double *t, double *u, double *v)
+{
+  float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
+  double det,inv_det;
+  
+  /* find vectors for two edges sharing vert0 */
+  VectorSubtract(vert1, vert0, edge1);
+  VectorSubtract(vert2, vert0, edge2);
+  
+  /* begin calculating determinant - also used to calculate U parameter */
+  CrossProduct(dir, edge2, pvec);
+  
+  /* if determinant is near zero, ray lies in plane of triangle */
+  det = DotProduct(edge1, pvec);
+  
+  if (bCullBack)
+  {
+    if (det < 0.000001)
+      return 0;
+    
+    // calculate distance from vert0 to ray origin
+    VectorSubtract(orig, vert0, tvec);
+    
+    // calculate U parameter and test bounds
+    *u = DotProduct(tvec, pvec);
+    if (*u < 0.0 || *u > det)
+      return 0;
+    
+    // prepare to test V parameter
+    CrossProduct(tvec, edge1, qvec);
+    
+    // calculate V parameter and test bounds
+    *v = DotProduct(dir, qvec);
+    if (*v < 0.0 || *u + *v > det)
+      return 0;
+    
+    // calculate t, scale parameters, ray intersects triangle
+    *t = DotProduct(edge2, qvec);
+    inv_det = 1.0 / det;
+    *t *= inv_det;
+    *u *= inv_det;
+    *v *= inv_det;
+  }
+  else
+  {
+    /* the non-culling branch */
+    if (det > -0.000001 && det < 0.000001)
+      return 0;
+    inv_det = 1.0 / det;
+    
+    /* calculate distance from vert0 to ray origin */
+    VectorSubtract(orig, vert0, tvec);
+    
+    /* calculate U parameter and test bounds */
+    *u = DotProduct(tvec, pvec) * inv_det;
+    if (*u < 0.0 || *u > 1.0)
+      return 0;
+    
+    /* prepare to test V parameter */
+    CrossProduct(tvec, edge1, qvec);
+    
+    /* calculate V parameter and test bounds */
+    *v = DotProduct(dir, qvec) * inv_det;
+    if (*v < 0.0 || *u + *v > 1.0)
+      return 0;
+    
+    /* calculate t, ray intersects triangle */
+    *t = DotProduct(edge2, qvec) * inv_det;
+  }
+  return 1;
+}
+
+bool Patch_Ray(patchMesh_t *patch, vec3_t origin, vec3_t dir, double *t, double *u, double *v)
+{
+       drawLists_t *drawLists;
+
+       drawLists_t::iterator iterLists, iterListsNext;
+       drawList_t::iterator i1, i2, i3, i4;
+
+//  vec3_t tris[2][3];
+  bool bIntersect = false;
+  float tBest = FLT_MAX;
+
+  if (patch->drawLists == NULL)
+    return false;
+
+  drawLists = (drawLists_t *)patch->drawLists;
+
+       iterListsNext=drawLists->begin();
+       iterListsNext++;
+       for (iterLists=drawLists->begin(); iterLists != drawLists->end() && iterListsNext != drawLists->end(); iterLists++, iterListsNext++)
+  {
+               // traverse two drawlists at once with two iterators each to triangulate
+    i1 = i3 = (*iterLists)->begin();
+    i2 = i4 = (*iterListsNext)->begin();
+    i3++;
+    i4++;
+               while (i3 != (*iterLists)->end() && i4 != (*iterListsNext)->end())
+               {
+      if (Triangle_Ray(origin, dir, false, (*i1).xyz, (*i2).xyz, (*i3).xyz, t, u, v))
+      {
+        bIntersect = true;
+        if (*t < tBest)
+          tBest = *t;
+      }      
+      if (Triangle_Ray(origin, dir, false, (*i3).xyz, (*i4).xyz, (*i2).xyz, t, u, v))
+      {
+        bIntersect = true;
+        if (*t < tBest)
+          tBest = *t;
+      }
+      i1++;
+      i2++;
+      i3++;
+      i4++;
+               }
+  }
+  if (bIntersect)
+  {
+    *t = tBest;
+    return true;
+  }
+  else
+  {
+    *t = 0;
+    return false;
+  }
+}
+
+// spog - curve LOD stuff ends
+
+/*
+=================
+DrawPatchMesh
+=================
+*/
+void DrawPatchMesh(patchMesh_t *pm)
+{
+  if (g_PrefsDlg.m_bDisplayLists)
+  {
+    if (pm->bDirty || pm->nListID <= 0 || pm->LODUpdated)
+    {
+      if (pm->nListID <= 0)
+        pm->nListID = qglGenLists(1);
+      if (pm->nListID > 0)
+      {
+        qglNewList(pm->nListID, GL_COMPILE_AND_EXECUTE);
+      }
+
+      Patch_DeleteDrawLists(pm);
+      Patch_CreateDrawLists(pm);
+       
+                 Patch_DrawLODPatchMesh(pm);
+
+      if (pm->nListID > 0)
+      {
+        qglEndList();
+           }
+
+           pm->bDirty = false;
+           pm->LODUpdated = false;
+    }
+    else
+    {
+      qglCallList(pm->nListID);
+    }
+  }
+  else
+  {
+    if (pm->bDirty || pm->LODUpdated)
+    {
+      Patch_DeleteDrawLists(pm);
+      Patch_CreateDrawLists(pm);
+      pm->bDirty = false;
+      pm->LODUpdated = false;
+    }
+         Patch_DrawLODPatchMesh(pm);
+  }
+}
+
+/*
+=================
+DrawPatchControls
+=================
+*/
+void DrawPatchControls(patchMesh_t *pm)
+{
+  int i, j;
+  bool bSelectedPoints[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; 
+  bool bOverlay = pm->bOverlay;
+
+  // bending
+  if (g_bPatchBendMode)
+  {
+    qglPointSize(6);
+    if (g_bPatchAxisOnRow)
+    {
+      qglColor3f(1, 0, 1);
+      if(!g_PrefsDlg.m_bGlPtWorkaround)
+      {
+        qglBegin(GL_POINTS);
+        for (i = 0; i < pm->width; i++)
+        {
+          qglVertex3fv(pm->ctrl[i][g_nPatchAxisIndex].xyz);
+        }
+        qglEnd();
+      }
+      else
+      {
+        qglLineWidth(2.0);
+        qglBegin(GL_LINES);
+        for(i = 0; i < pm->width; i++)
+        {
+          DrawAlternatePoint(pm->ctrl[i][g_nPatchAxisIndex].xyz, 0);
+        }
+        qglEnd();
+        qglLineWidth(1.0);
+      }                                
+      
+      if (g_nPatchBendState == BEND_SELECT_EDGE || g_nPatchBendState == BEND_BENDIT || g_nPatchBendState == BEND_SELECT_ORIGIN)
+      {
+        if(!g_PrefsDlg.m_bGlPtWorkaround)
+        {
+          qglColor3f(0, 0, 1);
+          qglBegin(GL_POINTS);
+          if (g_nPatchBendState == BEND_SELECT_ORIGIN)         
+          {
+            qglVertex3fv(g_vBendOrigin);
+          }
+          else         
+          {
+            for (i = 0; i < pm->width; i++)            
+            {
+              if (g_bPatchLowerEdge)                   
+              {
+                for (j = 0; j < g_nPatchAxisIndex; j++)
+                  qglVertex3fv(pm->ctrl[i][j].xyz);
+              }
+              else             
+              {
+                for (j = pm->height-1; j > g_nPatchAxisIndex; j--)
+                  qglVertex3fv(pm->ctrl[i][j].xyz);
+              }
+            }          
+          }
+          qglEnd();
+        }
+        else {
+          qglColor3f(0, 0, 1);
+          qglLineWidth(2.0);
+          qglBegin(GL_LINES);
+          if(g_nPatchBendState == BEND_SELECT_ORIGIN)                                  
+          {
+            DrawAlternatePoint(g_vBendOrigin, 0);
+          }
+          else                                 
+          {
+            for(i = 0; i < pm->width; i++)                                             
+            {
+              if(g_bPatchLowerEdge)                                                    
+              {
+                for(j = 0; j < g_nPatchAxisIndex; j++)
+                {
+                  DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);
+                }                                                      
+              }
+              else             
+              {
+                for (j = pm->height-1; j > g_nPatchAxisIndex; j--)                     
+                {
+                  DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);
+                }              
+              }                                                
+            }          
+          }
+          qglEnd();
+          qglLineWidth(1.0);
+        }
+      }
+    }
+    else
+    {
+      if(!g_PrefsDlg.m_bGlPtWorkaround)
+      {
+        qglColor3f(1, 0, 1);
+        qglBegin(GL_POINTS);
+        for (i = 0; i < pm->height; i++)
+        {
+          qglVertex3fv(pm->ctrl[g_nPatchAxisIndex][i].xyz);
+        }
+        qglEnd();
+      }
+      else {
+        qglColor3f(1, 0, 1);
+        qglLineWidth(2.0);
+        qglBegin(GL_LINES);
+        for(i = 0; i < pm->height; i++)
+        {
+          DrawAlternatePoint(pm->ctrl[g_nPatchAxisIndex][i].xyz, 0);
+        }
+        qglEnd();
+        qglLineWidth(1.0);
+      }
+      
+      if (g_nPatchBendState == BEND_SELECT_EDGE || g_nPatchBendState == BEND_BENDIT || g_nPatchBendState == BEND_SELECT_ORIGIN)
+      {
+        if(!g_PrefsDlg.m_bGlPtWorkaround)
+        {
+          qglColor3f(0, 0, 1);
+          qglBegin(GL_POINTS);
+          for (i = 0; i < pm->height; i++)
+          {
+            if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+            {
+              qglVertex3fv(pm->ctrl[g_nBendOriginIndex][i].xyz);
+            }
+            else
+            {
+              if (g_bPatchLowerEdge)
+              {
+                for (j = 0; j < g_nPatchAxisIndex; j++)
+                  qglVertex3fv(pm->ctrl[j][i].xyz);
+              }
+              else
+              {
+                for (j = pm->width-1; j > g_nPatchAxisIndex; j--)
+                  qglVertex3fv(pm->ctrl[j][i].xyz);
+              }
+            }
+          }
+          qglEnd();
+        }
+        else {
+          qglColor3f(0, 0, 1);
+          qglLineWidth(2.0);
+          qglBegin(GL_LINES);
+          for(i = 0; i < pm->height; i++)
+          {
+            if(g_nPatchBendState == BEND_SELECT_ORIGIN)
+            {
+              DrawAlternatePoint(pm->ctrl[g_nBendOriginIndex][i].xyz, 0);
+            }
+            else
+            {
+              if(g_bPatchLowerEdge)
+              {
+                for(j = 0; j < g_nPatchAxisIndex; j++)
+                {
+                  DrawAlternatePoint(pm->ctrl[j][i].xyz, 0);
+                }
+              }
+              else
+              {
+                for(j = pm->width-1; j > g_nPatchAxisIndex; j--)
+                {
+                  DrawAlternatePoint(pm->ctrl[j][i].xyz, 0);
+                }
+              }
+            }
+          }
+          qglEnd();
+          qglLineWidth(1.0);
+        }
+      }
+    }
+  }
+  else 
+  {
+    //qglDisable(GL_TEXTURE_2D); // stops point colours being multiplied by texture colour..
+    //draw CV lattice - could be made optional
+    //qglDisable( GL_CULL_FACE );
+    //    qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+    qglEnable (GL_POLYGON_OFFSET_LINE);
+    if (g_PrefsDlg.m_bNoStipple == FALSE)
+      qglDisable (GL_LINE_STIPPLE);
+    qglLineWidth (1);
+    qglColor3f(1.0f, 0.75f, 0.0f);
+    for ( i = 0 ; i+1 < pm->width ; i++ )
+    {
+      qglBegin(GL_QUAD_STRIP);
+      for ( j = 0 ; j < pm->height ; j++ ) 
+      {
+        qglVertex3fv(pm->ctrl[i][j].xyz);
+        qglVertex3fv(pm->ctrl[i+1][j].xyz);
+      }
+      qglEnd();
+    }
+    qglDisable (GL_POLYGON_OFFSET_LINE);
+    //if (g_PrefsDlg.m_bNoStipple == FALSE)
+    //  qglEnable (GL_LINE_STIPPLE);
+    
+    // draw selection handles
+    if(!g_PrefsDlg.m_bGlPtWorkaround)
+    {
+      qglPointSize(6);
+      qglBegin(GL_POINTS);
+      for ( i = 0 ; i < pm->width ; i++ )
+      {
+        for ( j = 0 ; j < pm->height ; j++ ) 
+        {
+          if (PointInMoveList(pm->ctrl[i][j].xyz) != -1)
+          {
+            bSelectedPoints[i][j] = true;
+          }
+          else
+          {    
+            bSelectedPoints[i][j] = false;
+            if (i & 0x01 || j & 0x01)
+              qglColor3f(1, 0, 1);
+            else
+              qglColor3f(0, 1, 0);
+            
+            qglVertex3fv(pm->ctrl[i][j].xyz);
+          }
+        }
+      }
+      qglColor3f(0, 0, 1);
+      for ( i = 0 ; i < pm->width ; i++ )
+      {
+        for ( j = 0 ; j < pm->height ; j++ ) 
+        {
+          if (bSelectedPoints[i][j])
+            qglVertex3fv(pm->ctrl[i][j].xyz);
+        }
+      }
+      qglEnd();
+    }
+    else
+    {
+      qglLineWidth(2.0);
+      qglBegin(GL_LINES);
+      for(i = 0; i < pm->width; i++)
+      {
+        for(j = 0; j < pm->height; j++)
+        {
+          if(PointInMoveList(pm->ctrl[i][j].xyz) != -1)
+          {
+            bSelectedPoints[i][j] = true;
+          }
+          else
+          {
+            bSelectedPoints[i][j] = false;
+            if(i & 0x01 || j & 0x01)
+              qglColor3f(1, 0, 1);
+            else
+              qglColor3f(0, 1, 0);
+            
+            // draw verts
+            DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);
+          }
+        }
+      }
+      qglColor3f(0, 0, 1);
+      for(i = 0; i < pm->width; i++)
+      {
+        for(j = 0; j < pm->height; j++)
+        {
+          if(bSelectedPoints[i][j])
+          {
+            // draw verts
+            DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);
+          }
+        }
+      }
+      qglEnd();        
+      qglLineWidth(1.0);
+    }
+  }
+  if (bOverlay)
+  {
+    if(!g_PrefsDlg.m_bGlPtWorkaround)
+    {
+      qglPointSize(6);
+      qglBegin(GL_POINTS);
+      for ( i = 0 ; i < pm->width ; i++ )
+      {
+        for ( j = 0 ; j < pm->height ; j++ ) 
+        {
+          if (i & 0x01 || j & 0x01)
+            qglColor3f(1, 0, 1);
+          else
+            qglColor3f(0, 1, 0);
+          qglVertex3fv(pm->ctrl[i][j].xyz);
+        }
+      }
+      qglEnd();
+    }
+    else
+    {
+      qglLineWidth(2.0);
+      qglBegin(GL_LINES);
+      for ( i = 0 ; i < pm->width ; i++ )
+      {
+        for ( j = 0 ; j < pm->height ; j++ ) 
+        {
+          if (i & 0x01 || j & 0x01)
+            qglColor3f(1, 0, 1);
+          else
+            qglColor3f(0, 1, 0);
+          // draw verts
+          DrawAlternatePoint(pm->ctrl[i][j].xyz, 0);
+        }
+      }
+      qglEnd();
+      qglLineWidth(1.0);
+    }
+  }
+  //qglPopAttrib();
+}
+
+/*
+==================
+Patch_DrawXY
+==================
+*/
+void Patch_DrawXY(patchMesh_t *pm)
+{
+  qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+
+  if (pm->bSelected)
+  {
+    qglColor3fv(g_qeglobals.d_savedinfo.colors[COLOR_SELBRUSHES]);
+    if (g_PrefsDlg.m_bNoStipple == FALSE)
+      qglEnable (GL_LINE_STIPPLE);
+    qglLineWidth (2);
+  }
+
+  DrawPatchMesh(pm);
+
+  if ( (pm->bSelected && (g_qeglobals.d_select_mode == sel_curvepoint
+    || g_qeglobals.d_select_mode == sel_area
+    || g_bPatchBendMode))
+    || pm->bOverlay )
+    DrawPatchControls(pm);
+}
+
+/*
+==================
+Patch_DrawCam
+==================
+*/
+void Patch_DrawCam(patchMesh_t *pm)
+{
+       qglPushAttrib(GL_ALL_ATTRIB_BITS); // save the current state
+
+  if (g_bPatchWireFrame)
+  {
+    qglDisable( GL_CULL_FACE );
+    qglPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+    qglDisable(GL_TEXTURE_2D);
+    if (g_PrefsDlg.m_bGLLighting)
+      qglDisable(GL_LIGHTING);
+
+    DrawPatchMesh(pm);
+
+    //if (g_PrefsDlg.m_bGLLighting)
+    //  qglEnable(GL_LIGHTING);
+    //qglEnable( GL_CULL_FACE );
+  }
+  else
+  {
+    qglDisable(GL_CULL_FACE);
+    qglBindTexture (GL_TEXTURE_2D, pm->d_texture->texture_number);
+    qglPolygonMode (GL_FRONT, GL_FILL);
+    qglPolygonMode (GL_BACK, GL_LINE);
+
+    if (pm->pShader->getTrans() < 1.0f)
+    {
+      qglEnable(GL_BLEND);
+      qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+      qglColor4f(pm->d_texture->color[0], pm->d_texture->color[1], pm->d_texture->color[2], pm->pShader->getTrans());
+    }
+    
+    DrawPatchMesh(pm); // both sides
+  }
+
+  qglPopAttrib(); // restore saved state
+}
+
+void ConvexHullForSection( float section[2][4][7] ) {
+}
+
+void BrushesForSection( float section[2][4][7] ) {
+}
+
+/*
+================
+Patch_BuildPoints
+================
+*/
+void Patch_BuildPoints (brush_t *b) 
+{
+       face_t          *f;
+       b->patchBrush = false;
+       for (f=b->brush_faces ; f ; f=f->next) 
+  {
+               if (f->texdef.flags & SURF_PATCH) 
+    {
+                       b->patchBrush = true;
+      //vec3_t vMin, vMax;
+      //Patch_CalcBounds(&patchMeshes[b->nPatchID], vMin, vMax);
+      //VectorCopy(vMin, b->mins);
+      //VectorCopy(vMax, b->maxs);
+                       break;
+               }
+       }
+}
+
+/*
+==================
+Patch_Move
+==================
+*/
+void Patch_Move(patchMesh_t *pm, const vec3_t vMove, bool bRebuild)
+{
+  pm->bDirty = true;
+  for (int w = 0; w < pm->width; w++)
+  {
+    for (int h = 0; h < pm->height; h++)
+    {
+      VectorAdd(pm->ctrl[w][h].xyz, vMove, pm->ctrl[w][h].xyz);
+    }
+  }
+  // bRebuild is never true
+  if (bRebuild)
+  {
+    vec3_t vMin, vMax;
+    Patch_CalcBounds(pm, vMin, vMax);
+    //Brush_RebuildBrush(patchMeshes[n].pSymbiot, vMin, vMax);
+  }
+  UpdatePatchInspector();
+
+}
+
+/*
+==================
+Patch_ApplyMatrix
+==================
+*/
+void Patch_ApplyMatrix(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vMatrix[3], bool bSnap)
+{
+       vec3_t vTemp;
+       
+       for (int w = 0; w < p->width; w++)
+       {
+               for (int h = 0; h < p->height; h++)
+               {
+                       if (((g_qeglobals.d_select_mode == sel_curvepoint && g_qeglobals.d_num_move_points != 0) || g_bPatchBendMode)
+                               && PointInMoveList(p->ctrl[w][h].xyz) == -1) // snap selected points only, if selected
+                               continue;
+                       VectorSubtract (p->ctrl[w][h].xyz, vOrigin, vTemp);
+                       for (int j = 0; j < 3; j++)
+                       {
+                               p->ctrl[w][h].xyz[j] = DotProduct(vTemp, vMatrix[j]) + vOrigin[j];
+                               if (bSnap)
+                               {
+                                       p->ctrl[w][h].xyz[j] = floor(p->ctrl[w][h].xyz[j] + 0.5);
+                               }
+                       }
+               }
+       }
+       vec3_t vMin, vMax;
+       Patch_CalcBounds(p, vMin, vMax);
+       Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+}
+
+/*
+==================
+Patch_EditPatch
+==================
+*/
+void Patch_EditPatch()
+{
+  //--patchMesh_t* p = &patchMeshes[n];
+  g_qeglobals.d_numpoints = 0;
+  g_qeglobals.d_num_move_points = 0;
+       
+  for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+           patchMesh_t* p = pb->pPatch;
+           for ( int i = 0 ; i < p->width ; i++ ) 
+      {
+                   for ( int j = 0 ; j < p->height ; j++ ) 
+        {
+               VectorCopy (p->ctrl[i][j].xyz, g_qeglobals.d_points[g_qeglobals.d_numpoints]);
+          if (g_qeglobals.d_numpoints < MAX_POINTS-1)
+          {
+                 g_qeglobals.d_numpoints++;
+          }
+                   }
+      }
+    }
+  }
+  g_qeglobals.d_select_mode = sel_curvepoint;
+  //--g_nSelectedPatch = n;
+}
+
+
+
+/*
+==================
+Patch_Deselect
+==================
+*/
+//FIXME: need all sorts of asserts throughout a lot of this crap
+void Patch_Deselect()
+{
+  //--g_nSelectedPatch = -1;
+  g_qeglobals.d_select_mode = sel_brush;
+
+       for (brush_t *b = selected_brushes.next ; b != &selected_brushes ; b=b->next)
+  {
+    if (b->patchBrush)
+    {
+      b->pPatch->bSelected = false;
+    }
+  }
+
+  //for (int i = 0; i < numPatchMeshes; i++)
+  //  patchMeshes[i].bSelected = false;
+
+  if (g_bPatchBendMode)
+    Patch_BendToggle();
+//  if (g_bPatchInsertMode)
+//    Patch_InsDelToggle();
+}
+
+
+/*
+==================
+Patch_Select
+==================
+*/
+void Patch_Select(patchMesh_t *p)
+{
+  // maintained for point manip.. which i need to fix as this 
+  // is pf error prone
+  //--g_nSelectedPatch = n;
+  p->bSelected = true;
+}
+
+
+/*
+==================
+Patch_Deselect
+==================
+*/
+void Patch_Deselect(patchMesh_t *p)
+{
+  p->bSelected = false;
+}
+
+
+/*
+==================
+Patch_Delete
+==================
+*/
+extern BTNode_t *BTree_Delete(BTNode_t *pBT);
+extern BTListList_t *BTree_DeleteListFromList(BTListList_t *pBTListList);
+
+void Patch_Delete(patchMesh_t *p)
+{
+  if (p->pSymbiot) // Hydra - added a check to prevent access violations.
+  {
+  p->pSymbiot->pPatch = NULL;
+  p->pSymbiot->patchBrush = false;
+  }
+
+  // spog - free dynamically allocated memory used by LODs
+  int rowcount = ((MAX_PATCH_WIDTH-1)/2) * MAX_PATCH_HEIGHT;
+       int colcount = ((MAX_PATCH_HEIGHT-1)/2) * MAX_PATCH_WIDTH;
+       int i;
+       for (i=0; i<rowcount; i++)
+               p->rowLOD[i] = BTree_Delete(p->rowLOD[i]);
+       for (i=0; i<colcount; i++)
+               p->colLOD[i] = BTree_Delete(p->colLOD[i]);
+
+  // delete display list associated with patch
+  if (p->nListID != -1)
+    qglDeleteLists (p->nListID, 1); // list#, number of lists
+  
+  // delete LOD drawLists
+  Patch_DeleteDrawLists(p);
+
+
+  free(p);
+  p = NULL;
+
+  
+  UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_Scale
+==================
+*/
+void Patch_Scale(patchMesh_t *p, const vec3_t vOrigin, const vec3_t vAmt, bool bRebuild)
+{
+
+  for (int w = 0; w < p->width; w++)
+  {
+    for (int h = 0; h < p->height; h++)
+    {
+      if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+        continue;
+                       for (int i=0 ; i<3 ; i++)
+                       {
+        p->ctrl[w][h].xyz[i] -= vOrigin[i];
+        p->ctrl[w][h].xyz[i] *= vAmt[i];
+        p->ctrl[w][h].xyz[i] += vOrigin[i];
+      }
+    }
+  }
+  if (bRebuild)
+  {
+    vec3_t vMin, vMax;
+    Patch_CalcBounds(p, vMin, vMax);
+    Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+  }
+  UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_SetView
+==================
+*/
+void Patch_SetView(int n)
+{
+  g_bSameView = (n == g_nPatchClickedView);
+  g_nPatchClickedView = n;
+}
+
+
+/*
+==================
+Patch_SetTexture
+==================
+*/
+// FIXME: need array validation throughout
+void Patch_SetTexture(patchMesh_t *p, texdef_t *tex_def, IPluginTexdef* pPlugTexdef)
+{
+  // NOTE: I don't know for sure if this happens
+  if (p->pShader)
+    p->pShader->DecRef();
+  p->pShader = QERApp_Shader_ForName(tex_def->GetName());
+  p->pShader->IncRef();
+  p->d_texture = p->pShader->getTexture();
+
+  UpdatePatchInspector();
+}
+
+
+/*
+==================
+Patch_DragScale
+==================
+*/
+bool Patch_DragScale(patchMesh_t *p, vec3_t vAmt, vec3_t vMove)
+{
+  vec3_t vMin, vMax, vScale, vTemp, vMid;
+  int i;
+
+  Patch_CalcBounds(p, vMin, vMax);
+
+  VectorSubtract(vMax, vMin, vTemp);
+
+  // if we are scaling in the same dimension the patch has no depth
+  for (i = 0; i < 3; i ++)
+  {
+    if (vTemp[i] == 0 && vMove[i] != 0)
+    {
+      //Patch_Move(n, vMove, true);
+      return false;
+    }
+  }
+  
+  for (i=0 ; i<3 ; i++)
+    vMid[i] = (vMin[i] + ((vMax[i] - vMin[i]) / 2));
+
+  for (i = 0; i < 3; i++)
+  {
+    if (vAmt[i] != 0)
+    {
+      vScale[i] = 1.0 + vAmt[i] / vTemp[i];
+    }
+    else
+    {
+      vScale[i] = 1.0;
+    }
+  }
+
+  Patch_Scale(p, vMid, vScale, false);
+
+  VectorSubtract(vMax, vMin, vTemp);
+
+  Patch_CalcBounds(p, vMin, vMax);
+  
+  VectorSubtract(vMax, vMin, vMid);
+
+  VectorSubtract(vMid, vTemp, vTemp);
+
+  VectorScale(vTemp, 0.5, vTemp);
+
+  // abs of both should always be equal
+  if (!VectorCompare(vMove, vAmt))
+  {
+    for (i = 0; i < 3; i++)
+    {
+      if (vMove[i] != vAmt[i])
+        vTemp[i] = -(vTemp[i]);
+    }
+  }
+
+  Patch_Move(p, vTemp);
+  return true;
+}
+
+/*
+==================
+Patch_InsertColumn
+==================
+*/
+void Patch_InsertColumn(patchMesh_t *p, bool bAdd)
+{
+       int w, h, i, width;
+       vec3_t vTemp;
+       float stTemp[2];
+  
+       if (p->width + 2 >= MAX_PATCH_WIDTH)
+               return;
+
+       // check for selected column points
+       for (h = 0; h < p->height; h++)
+       {
+               for (w = 1; w < p->width; w+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (w < p->width)
+                       break;
+               for (w = 0; w < p->width; w+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (w < p->width)
+                       break;
+       }
+
+       if (w >= p->width)
+       {
+               if (bAdd) w=p->width-1;
+               else w=2;
+       }
+       else if (w==0) w=2;
+       else if (w%2) w++;
+
+       // add columns at w
+       for (h = 0; h < p->height; h++)
+       {
+               for (width = p->width-1; width > w; width--)
+                       memcpy(&p->ctrl[width+2][h],&p->ctrl[width][h], sizeof(drawVert_t));
+               
+               // set two new column points
+               memcpy(&p->ctrl[w+2][h],&p->ctrl[w][h], sizeof(drawVert_t));
+               memcpy(&p->ctrl[w+1][h],&p->ctrl[w-1][h], sizeof(drawVert_t));
+               
+               for (i=0; i<3; i++) // xyz
+               {
+                       vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w-1][h].xyz[i];
+                       p->ctrl[w+1][h].xyz[i] = p->ctrl[w+1][h].xyz[i] + (vTemp[i] / 2);
+                       
+                       vTemp[i] = p->ctrl[w-2][h].xyz[i] - p->ctrl[w-1][h].xyz[i];
+                       p->ctrl[w-1][h].xyz[i] = p->ctrl[w-1][h].xyz[i] + (vTemp[i] / 2);
+                       
+                       vTemp[i] = p->ctrl[w+1][h].xyz[i] - p->ctrl[w-1][h].xyz[i];
+                       p->ctrl[w][h].xyz[i] = p->ctrl[w-1][h].xyz[i] + (vTemp[i] / 2);
+               }
+               for (i=0; i<2; i++) // st
+               {
+                       stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w-1][h].st[i];
+                       p->ctrl[w+1][h].st[i] = p->ctrl[w+1][h].st[i] + (stTemp[i] / 2);
+                       
+                       stTemp[i] = p->ctrl[w-2][h].st[i] - p->ctrl[w-1][h].st[i];
+                       p->ctrl[w-1][h].st[i] = p->ctrl[w-1][h].st[i] + (stTemp[i] / 2);
+                       
+                       stTemp[i] = p->ctrl[w+1][h].st[i] - p->ctrl[w-1][h].st[i];
+                       p->ctrl[w][h].st[i] = p->ctrl[w-1][h].st[i] + (stTemp[i] / 2);
+               }
+       }
+
+       p->width += 2;
+       // deselect all points to keep things neat
+       if (g_qeglobals.d_select_mode == sel_curvepoint)
+               Patch_EditPatch();
+
+       UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_InsertRow
+==================
+*/
+
+void Patch_InsertRow(patchMesh_t *p, bool bAdd)
+{
+       int h, w, i, height;
+       vec3_t vTemp;
+       float stTemp[2];
+  
+       if (p->height + 2 >= MAX_PATCH_HEIGHT)
+               return;
+
+       // check for selected row points
+       for (w = 0; w < p->width; w++)
+       {
+               for (h = 1; h < p->height; h+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (h < p->height)
+                       break;
+               for (h = 0; h < p->height; h+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (h < p->height)
+                       break;
+       }
+       if (h >= p->height)
+       {
+               if (bAdd) h=p->height-1;
+               else h=2;
+       }
+       else if (h==0) h=2;
+       else if (h%2) h++;
+
+       // add rows at h
+       for (w = 0; w < p->width; w++)
+       {
+               for (height = p->height-1; height > h; height--)
+                       memcpy(&p->ctrl[w][height+2],&p->ctrl[w][height], sizeof(drawVert_t));
+               
+               // set two new row points
+               memcpy(&p->ctrl[w][h+2],&p->ctrl[w][h], sizeof(drawVert_t));
+               memcpy(&p->ctrl[w][h+1],&p->ctrl[w][h-1], sizeof(drawVert_t));
+               
+               for (i=0; i<3; i++) // xyz
+               {
+                       vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w][h-1].xyz[i];
+                       p->ctrl[w][h+1].xyz[i] = p->ctrl[w][h+1].xyz[i] + (vTemp[i] / 2);
+                       
+                       vTemp[i] = p->ctrl[w][h-2].xyz[i] - p->ctrl[w][h-1].xyz[i];
+                       p->ctrl[w][h-1].xyz[i] = p->ctrl[w][h-1].xyz[i] + (vTemp[i] / 2);
+                       
+                       vTemp[i] = p->ctrl[w][h+1].xyz[i] - p->ctrl[w][h-1].xyz[i];
+                       p->ctrl[w][h].xyz[i] = p->ctrl[w][h-1].xyz[i] + (vTemp[i] / 2);
+               }
+               for (i=0; i<2; i++) // st
+               {
+                       stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w][h-1].st[i];
+                       p->ctrl[w][h+1].st[i] = p->ctrl[w][h+1].st[i] + (stTemp[i] / 2);
+                       
+                       stTemp[i] = p->ctrl[w][h-2].st[i] - p->ctrl[w][h-1].st[i];
+                       p->ctrl[w][h-1].st[i] = p->ctrl[w][h-1].st[i] + (stTemp[i] / 2);
+                       
+                       stTemp[i] = p->ctrl[w][h+1].st[i] - p->ctrl[w][h-1].st[i];
+                       p->ctrl[w][h].st[i] = p->ctrl[w][h-1].st[i] + (stTemp[i] / 2);
+               }
+       }
+
+       p->height += 2;
+       // deselect all points to keep things neat
+       if (g_qeglobals.d_select_mode == sel_curvepoint)
+               Patch_EditPatch();
+
+       UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_RemoveRow
+==================
+*/
+void Patch_RemoveRow(patchMesh_t *p, bool bFirst)
+{
+       int w, h, i, height;
+       vec3_t vTemp;
+       float stTemp[2];
+       bool bExtrapolate = true;
+  
+       if (p->height <= MIN_PATCH_HEIGHT)
+               return;
+
+       for (w = 0; w < p->width; w++)
+       {
+               for (h = 0; h < p->height; h+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (h < p->height)
+                       break;
+               for (h = 1; h < p->height; h+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (h < p->height)
+                       break;
+       }
+
+       if (h >= p->height)
+       {
+               bExtrapolate = false;
+               if (bFirst) h=p->height-3;
+               else h=2;
+       }
+       else if (h <= 0) h=2;
+       else if (h > p->height-3) h = p->height-3;
+       else if (h%2) h++;
+       
+       p->height -= 2;
+
+       for (w = 0; w < p->width; w++)
+       {
+               if (bExtrapolate)
+               {
+                       for (i = 0; i < 3; i++) // xyz
+                       {
+                               vTemp[i] = p->ctrl[w][h+2].xyz[i] - p->ctrl[w][h-2].xyz[i];
+                               p->ctrl[w][h-1].xyz[i] = p->ctrl[w][h-2].xyz[i] + (vTemp[i] / 2);
+
+                               vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w][h-1].xyz[i];
+                               p->ctrl[w][h-1].xyz[i] = p->ctrl[w][h-1].xyz[i] + (vTemp[i] * 2);
+                       }
+
+                       for (i = 0; i < 2; i++) // st
+                       {
+                               stTemp[i] = p->ctrl[w][h+2].st[i] - p->ctrl[w][h-2].st[i];
+                               p->ctrl[w][h-1].st[i] = p->ctrl[w][h-2].st[i] + (stTemp[i] / 2);
+
+                               stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w][h-1].st[i];
+                               p->ctrl[w][h-1].st[i] = p->ctrl[w][h-1].st[i] + (stTemp[i] * 2);
+                       }
+               }
+               else
+               {
+                       if (!bFirst)
+                       continue;
+                       else h=0;
+               }
+               for (height = h; height < p->height; height++)
+                       memcpy(&p->ctrl[w][height], &p->ctrl[w][height+2], sizeof(drawVert_t));                 
+       }
+       // deselect all points to keep things neat
+       if (g_qeglobals.d_select_mode == sel_curvepoint)
+               Patch_EditPatch();
+       
+       UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_RemoveColumn
+==================
+*/
+void Patch_RemoveColumn(patchMesh_t *p, bool bFirst)
+{
+       int w, h, i, width;
+       vec3_t vTemp;
+       float stTemp[2];
+       bool bExtrapolate = true;
+  
+       if (p->width <= MIN_PATCH_WIDTH)
+               return;
+
+       for (h = 0; h < p->height; h++)
+       {
+               for (w = 0; w < p->width; w+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (w < p->width)
+                       break;
+               for (w = 1; w < p->width; w+=2)
+                       if (PointInMoveList(p->ctrl[w][h].xyz) != -1)
+                               break;
+               if (w < p->width)
+                       break;
+       }
+
+       if (w >= p->width)
+       {
+               bExtrapolate = false;
+               if (bFirst) w=p->width-3;
+               else w=2;
+       }
+       else if (w<=0) w=2;
+       else if (w > p->width-3) w = p->width-3;
+       else if (w%2) w++;
+       
+       p->width -= 2;
+
+       for (h = 0; h < p->height; h++)
+       {
+               if (bExtrapolate)
+               {
+                       for (i = 0; i < 3; i++) // xyz
+                       {
+                               vTemp[i] = p->ctrl[w+2][h].xyz[i] - p->ctrl[w-2][h].xyz[i];
+                               p->ctrl[w-1][h].xyz[i] = p->ctrl[w-2][h].xyz[i] + (vTemp[i] / 2);
+
+                               vTemp[i] = p->ctrl[w][h].xyz[i] - p->ctrl[w-1][h].xyz[i];
+                               p->ctrl[w-1][h].xyz[i] = p->ctrl[w-1][h].xyz[i] + (vTemp[i] * 2);
+                       }
+
+                       for (i = 0; i < 2; i++) // st
+                       {
+                               stTemp[i] = p->ctrl[w+2][h].st[i] - p->ctrl[w-2][h].st[i];
+                               p->ctrl[w-1][h].st[i] = p->ctrl[w-2][h].st[i] + (stTemp[i] / 2);
+
+                               stTemp[i] = p->ctrl[w][h].st[i] - p->ctrl[w-1][h].st[i];
+                               p->ctrl[w-1][h].st[i] = p->ctrl[w-1][h].st[i] + (stTemp[i] * 2);
+                       }
+               }
+               else
+               {
+                       if (!bFirst)
+                       continue;
+                       else w=0;
+               }
+               
+               for (width = w; width < p->width; width++)
+                       memcpy(&p->ctrl[width][h], &p->ctrl[width+2][h], sizeof(drawVert_t));                   
+       }
+       // deselect all points to keep things neat
+       if (g_qeglobals.d_select_mode == sel_curvepoint)
+               Patch_EditPatch();
+
+       UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_AdjustColumns
+==================
+*/
+/*
+void Patch_AdjustColumns(patchMesh_t *p, int nCols)
+{
+  vec3_t vTemp, vTemp2;
+  int i, w, h;
+
+  if (nCols & 0x01 || p->width + nCols < 3 || p->width + nCols > MAX_PATCH_WIDTH)
+    return;
+
+  // add in column adjustment
+  p->width += nCols;
+
+  for (h = 0; h < p->height; h++)
+  {
+    // for each column, we need to evenly disperse p->width number 
+    // of points across the old bounds
+    
+    // calc total distance to interpolate 
+    VectorSubtract(p->ctrl[p->width - 1 - nCols][h].xyz, p->ctrl[0][h].xyz, vTemp);
+
+    // amount per cycle
+    for (i = 0; i < 3; i ++)
+    {
+      vTemp2[i] = vTemp[i] / (p->width - 1);
+    }
+
+    // move along
+    for (w = 0; w < p->width-1; w++)
+    {
+      VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w+1][h].xyz);
+    }
+
+  }
+       for ( w = 0 ; w < p->width ; w++ ) 
+  {
+               for ( h = 0 ; h < p->height ; h++ ) 
+    {
+                       p->ctrl[w][h].st[0] = 4 * (float)w / (p->width - 1);
+                       p->ctrl[w][h].st[1] = 4 * (float)h / (p->height - 1);
+               }
+       }
+  UpdatePatchInspector();
+}
+*/
+
+/*
+==================
+Patch_AdjustRows
+==================
+*/
+/*
+void Patch_AdjustRows(patchMesh_t *p, int nRows)
+{
+  vec3_t vTemp, vTemp2;
+  int i, w, h;
+
+  if (nRows & 0x01 || p->height + nRows < 3 || p->height + nRows > MAX_PATCH_HEIGHT)
+    return;
+
+  // add in column adjustment
+  p->height += nRows;
+
+  for (w = 0; w < p->width; w++)
+  {
+    // for each row, we need to evenly disperse p->height number 
+    // of points across the old bounds
+
+    // calc total distance to interpolate 
+    VectorSubtract(p->ctrl[w][p->height - 1 - nRows].xyz, p->ctrl[w][0].xyz, vTemp);
+    
+    //vTemp[0] = vTemp[1] = vTemp[2] = 0;
+    //for (h = 0; h < p->height - nRows; h ++)
+    //{
+    //  VectorAdd(vTemp, p->ctrl[w][h], vTemp);
+    //}
+
+    // amount per cycle
+    for (i = 0; i < 3; i ++)
+    {
+      vTemp2[i] = vTemp[i] / (p->height - 1);
+    }
+
+    // move along
+    for (h = 0; h < p->height-1; h++)
+    {
+      VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);
+    }
+
+  }
+       for ( w = 0 ; w < p->width ; w++ ) 
+  {
+               for ( h = 0 ; h < p->height ; h++ ) 
+    {
+                       p->ctrl[w][h].st[0] = 4 * (float)w / (p->width - 1);
+                       p->ctrl[w][h].st[1] = 4 * (float)h / (p->height - 1);
+               }
+       }
+  UpdatePatchInspector();
+}
+*/
+
+/*
+==================
+Patch_DisperseRows
+==================
+*/
+
+void Patch_DisperseRows()
+{
+       vec3_t vTemp, vTemp2;
+       int i, w, h;
+       
+       
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+     if (pb->patchBrush)
+     {
+       patchMesh_t *p = pb->pPatch;
+       Patch_Rebuild(p);
+       for (w = 0; w < p->width; w++)
+       {
+         // for each row, we need to evenly disperse p->height number 
+         // of points across the old bounds
+         // calc total distance to interpolate 
+         VectorSubtract(p->ctrl[w][p->height - 1].xyz, p->ctrl[w][0].xyz, vTemp);
+     
+         //vTemp[0] = vTemp[1] = vTemp[2] = 0;
+         //for (h = 0; h < p->height - nRows; h ++)
+         //{
+         //  VectorAdd(vTemp, p->ctrl[w][h], vTemp);
+         //}
+         // amount per cycle
+         for (i = 0; i < 3; i ++)
+         {
+           vTemp2[i] = vTemp[i] / (p->height - 1);
+         }
+         // move along
+         for (h = 0; h < p->height-1; h++)
+         {
+           VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);
+         }
+         Patch_Naturalize(p);
+       }
+     }
+   }
+               UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_DisperseIntermediateRows
+==================
+*/
+
+void Patch_DisperseIntermediateRows()
+{
+       vec3_t vTemp, vTemp2;
+       int i, w, h;
+       
+       
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+               if (pb->patchBrush)
+               {
+                       patchMesh_t *p = pb->pPatch;
+                       Patch_Rebuild(p);
+                       for (w = 0; w < p->width; w++)
+                       {
+                               // move along
+                               for (h = 0; h < p->height; h+=2)
+                               {
+                                       // calc distance to interpolate 
+                                       VectorSubtract(p->ctrl[w][h+2].xyz, p->ctrl[w][h].xyz, vTemp);
+                                       
+                                       // halve distance
+                                       for (i = 0; i < 3; i ++)
+                                       {
+                                               vTemp2[i] = vTemp[i] / 2;
+                                       }
+                                       
+                                       // move control points
+                                       VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w][h+1].xyz);
+                               }
+                       }
+               }
+       }
+       UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_DisperseIntermediateColumns
+==================
+*/
+void Patch_DisperseIntermediateColumns()
+{
+       vec3_t vTemp, vTemp2;
+       int i, w, h;
+       
+       
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+               if (pb->patchBrush)
+               {
+                       patchMesh_t *p = pb->pPatch;
+                       Patch_Rebuild(p);
+                       for (h = 0; h < p->height; h++)
+                       {
+                                       // move along
+                               for (w = 0; w < p->width; w+=2)
+                               {
+                                       // calc distance to interpolate 
+                                       VectorSubtract(p->ctrl[w+2][h].xyz, p->ctrl[w][h].xyz, vTemp);
+                                       
+                                       // halve distance
+                                       for (i = 0; i < 3; i ++)
+                                       {
+                                               vTemp2[i] = vTemp[i] / 2;
+                                       }
+                                       
+                                       // move control points
+                                       VectorAdd(p->ctrl[w][h].xyz, vTemp2, p->ctrl[w+1][h].xyz);
+                               }
+                       }
+               }
+       }
+       UpdatePatchInspector();
+}
+
+
+
+/*
+==================
+Patch_AdjustSelected
+==================
+*/
+void Patch_AdjustSelected(bool bInsert, bool bColumn, bool bFlag)
+{
+  bool bUpdate = false;
+       for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      if (bInsert)
+      {
+        if (bColumn)
+        {
+          Patch_InsertColumn(pb->pPatch, bFlag);
+        }
+        else
+        {
+          Patch_InsertRow(pb->pPatch, bFlag);
+        }
+      }
+      else
+      {
+        if (bColumn)
+        {
+          Patch_RemoveColumn(pb->pPatch, bFlag);
+        }
+        else
+        {
+          Patch_RemoveRow(pb->pPatch, bFlag);
+        }
+      }
+      bUpdate = true;
+      vec3_t vMin, vMax;
+      patchMesh_t *p = pb->pPatch;
+      Patch_CalcBounds(p, vMin, vMax);
+      Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+      pb->pPatch->bDirty = true; // rebuild LOD trees and their normals
+    }
+  }
+  if (bUpdate)
+  {
+    Sys_UpdateWindows(W_ALL);
+  }
+}
+
+
+/*
+==================
+Patch_AdjustSelectedRowCols
+==================
+*/
+/*
+void Patch_AdjustSelectedRowCols(int nRows, int nCols)
+{
+       for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      Patch_InsertColumn(pb->pPatch, false);
+      if (nRows != 0)
+      {
+        Patch_AdjustRows(pb->pPatch, nRows);
+      }
+      
+      if (nCols != 0)
+      {
+        Patch_AdjustColumns(pb->pPatch, nCols);
+      }
+               }
+  }
+  UpdatePatchInspector();
+}
+*/
+
+/*
+=================
+CheckName
+temporary stuff, detect potential problems when saving the texture name
+will correct the patch on the fly if problem detected
+=================
+*/
+/*!
+\todo performance issue with CheckName calls
+don't call this too much, only when absolutely necessary
+strategies that call here too much are known to be slow
+patch 84 to bug 253 adds an additionnal check for textures/
+*/
+void CheckName( patchMesh_t *p, char *pname )
+{
+  if(strncmp(p->pShader->getName(), "textures/", 9) != 0)
+    p->pShader = QERApp_Shader_ForName(SHADER_NOT_FOUND);
+
+       // some manage to get long filename textures (with spaces) in their maps
+       if (strchr( p->pShader->getName(), ' ' ))
+       {
+               char Msg1[1024];
+               sprintf( Msg1, "Can't save texture with spaces in name. Rename %s\nNOTE: This message may popup several times .. once for each buggy face detected.", p->pShader->getName() );
+               Sys_Printf("%s\n", Msg1 );
+               gtk_MessageBox(g_pParentWnd->m_pWidget, Msg1, "Error saving map", MB_OK );
+               strcpy( pname, SHADER_NOT_FOUND );
+               p->pShader = QERApp_Shader_ForName(SHADER_NOT_FOUND);
+    p->d_texture = p->pShader->getTexture();
+               return;
+       }
+       strcpy( pname, p->pShader->getName()+9 ); // remove "textures/"
+}
+
+/*
+==================
+Patch_Write 
+==================
+*/
+void Patch_Write (patchMesh_t *p, MemStream *file)
+{
+  char pname[1024];
+
+  MemFile_fprintf(file, " {\n  patchDef2\n  {\n");
+
+  CheckName( p, pname );
+  MemFile_fprintf(file, "   %s\n", pname );
+  MemFile_fprintf(file, "   ( %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value);
+
+
+       float           ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];
+
+  int w, h;
+  for (w = 0; w < p->width; w++)
+  {
+    for (h = 0; h < p->height; h++)
+    {
+      ctrl[w][h][0] = p->ctrl[w][h].xyz[0];
+      ctrl[w][h][1] = p->ctrl[w][h].xyz[1];
+      ctrl[w][h][2] = p->ctrl[w][h].xyz[2];
+      ctrl[w][h][3] = p->ctrl[w][h].st[0];
+      ctrl[w][h][4] = p->ctrl[w][h].st[1];
+    }
+  }
+
+  _Write3DMatrix(file, p->width, p->height, 5, reinterpret_cast<float*>(&ctrl));
+
+       if (g_qeglobals.m_bBrushPrimitMode)
+  {
+         if (p->epairs)
+    {
+                       for (epair_t *ep = p->epairs ; ep ; ep=ep->next)
+      {
+                               MemFile_fprintf (file, "\"%s\" \"%s\"\n", ep->key, ep->value);
+      }
+    }
+  }
+
+  MemFile_fprintf(file, "  }\n }\n");
+}
+
+void Patch_Write (patchMesh_t *p, FILE *file)
+{
+  char pname[1024];
+
+       fprintf(file, " {\n  patchDef2\n  {\n");
+  {
+         CheckName( p, pname );
+         fprintf(file, "   %s\n", pname );
+         fprintf(file, "   ( %i %i %i %i %i ) \n", p->width, p->height, p->contents, p->flags, p->value);
+       }
+
+       float           ctrl[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT][5];
+
+  int w, h;
+  for (w = 0; w < p->width; w++)
+  {
+    for (h = 0; h < p->height; h++)
+    {
+      ctrl[w][h][0] = p->ctrl[w][h].xyz[0];
+      ctrl[w][h][1] = p->ctrl[w][h].xyz[1];
+      ctrl[w][h][2] = p->ctrl[w][h].xyz[2];
+      ctrl[w][h][3] = p->ctrl[w][h].st[0];
+      ctrl[w][h][4] = p->ctrl[w][h].st[1];
+    }
+  }
+
+  _Write3DMatrix(file, p->width, p->height, 5, reinterpret_cast<float*>(&ctrl));
+
+       if (g_qeglobals.m_bBrushPrimitMode)
+  {
+         if (p->epairs)
+    {
+                       for (epair_t *ep = p->epairs ; ep ; ep=ep->next)
+      {
+                               fprintf (file, "\"%s\" \"%s\"\n", ep->key, ep->value);
+      }
+    }
+  }
+
+  fprintf(file, "  }\n }\n");
+}
+
+
+/*
+==================
+Patch_RotateTexture
+==================
+*/
+void Patch_RotateTexture(patchMesh_t *p, float fAngle)
+{
+  p->bDirty = true;
+  float c = cos(fAngle * Q_PI / 180);
+  float s = sin(fAngle * Q_PI / 180);
+
+  Patch_TransformLODTexture(p, c, s, ROTATE);
+
+  for (int w = 0; w < p->width; w++)
+  {
+    for (int h = 0; h < p->height; h++)
+    {
+      //if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+      //  continue;
+
+      float x = p->ctrl[w][h].st[0];
+      float y = p->ctrl[w][h].st[1];
+      p->ctrl[w][h].st[0] = x * c - y * s;
+      p->ctrl[w][h].st[1] = y * c + x * s;
+    }
+  }
+}
+
+
+/*
+==================
+Patch_ScaleTexture
+==================
+*/
+void Patch_ScaleTexture(patchMesh_t *p, float fx, float fy, bool bFixup)
+{
+  // FIXME:
+  // this hack turns scales into 1.1 or 0.9
+  if (bFixup)
+  {
+    fx = (fx == 0) ? 1.0 : (fx > 0) ? 0.9 : 1.10;
+    fy = (fy == 0) ? 1.0 : (fy > 0) ? 0.9 : 1.10;
+  }
+  else
+  {
+    if (fx == 0)
+      fx = 1.0;
+    if (fy == 0)
+      fy = 1.0;
+  }
+  
+  for (int w = 0; w < p->width; w++)
+  {
+    for (int h = 0; h < p->height; h++)
+    {
+      if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+        continue;
+
+      p->ctrl[w][h].st[0] *= fx;
+      p->ctrl[w][h].st[1] *= fy;
+    }
+  }
+  if (g_qeglobals.d_select_mode == sel_curvepoint)
+  {
+         p->bDirty = true;
+         Patch_LODMatchAll();
+  }
+  else
+  {
+    Patch_TransformLODTexture(p, fx, fy, SCALE);
+         p->LODUpdated = true;
+  }
+}
+
+
+/*
+==================
+Patch_ShiftTexture
+shift a texture given a pixel count
+==================
+*/
+void Patch_ShiftTexture(patchMesh_t *p, float fx, float fy)
+{
+       qtexture_t *pTex;
+       pTex = p->pShader->getTexture();
+       fx = -1 * fx / pTex->width;
+       fy = fy / pTex->height;
+       Patch_ShiftTextureST(p, fx, fy);
+}
+
+/*
+====================
+Patch_ShiftTextureST
+shift a patch texture given an ST increment
+====================
+*/
+void Patch_ShiftTextureST(patchMesh_t *p, float fx, float fy)
+{
+#ifdef _DEBUG
+       // NOTE: when called by Patch_ShiftTexture this warning may be bogus
+       if ((ABS(fx) >= 1) || (ABS(fy) >= 1))
+               Sys_Printf("WARNING: increments exceed 1 in Patch_ShiftTextureST\n");
+#endif
+  for (int w = 0; w < p->width; w++)
+  {
+    for (int h = 0; h < p->height; h++)
+    {
+      if (g_qeglobals.d_select_mode == sel_curvepoint && PointInMoveList(p->ctrl[w][h].xyz) == -1)
+        continue;
+
+      p->ctrl[w][h].st[0] += fx;
+      p->ctrl[w][h].st[1] += fy;
+    }
+  }
+  if (g_qeglobals.d_select_mode == sel_curvepoint)
+  {
+         p->bDirty = true;
+         Patch_LODMatchAll();
+  }
+  else
+  {
+         Patch_TransformLODTexture(p, fx, fy, TRANSLATE);
+         p->LODUpdated = true;
+  }
+}
+
+/*
+==================
+Patch_ToggleInverted
+==================
+*/
+void Patch_ToggleInverted()
+{
+  bool bUpdate = false;
+
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      bUpdate = true;
+      patchInvert(pb->pPatch);
+    }
+  }
+
+  if (bUpdate)
+  {
+    Sys_UpdateWindows(W_ALL);
+  }
+  UpdatePatchInspector();
+}
+
+/*
+==================
+Patch_ToggleInverted
+==================
+*/
+void Patch_InvertTexture(bool bY)
+{
+  bool bUpdate = false;
+
+  float fTemp[2];
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      bUpdate = true;
+      patchMesh_t *p = pb->pPatch;
+      p->bDirty = true;
+      if (bY)
+      {
+             for ( int i = 0 ; i < p->height ; i++ ) 
+        {
+          for (int j = 0; j < p->width / 2; j++)
+          {
+            memcpy(fTemp, &p->ctrl[p->width - 1- j][i].st[0], sizeof (float[2]));
+            memcpy(&p->ctrl[p->width - 1- j][i].st[0], &p->ctrl[j][i].st[0], sizeof(float[2]));
+            memcpy(&p->ctrl[j][i].st[0], fTemp, sizeof(float[2]));
+                     }
+             }
+      }
+      else
+      {
+             for ( int i = 0 ; i < p->width ; i++ ) 
+        {
+          for (int j = 0; j < p->height / 2; j++)
+          {
+            memcpy(fTemp, &p->ctrl[i][p->height - 1- j].st[0], sizeof (float[2]));
+            memcpy(&p->ctrl[i][p->height - 1 - j].st[0], &p->ctrl[i][j].st[0], sizeof(float[2]));
+            memcpy(&p->ctrl[i][j].st[0], fTemp, sizeof(float[2]));
+                     }
+             }
+      }
+    }
+  }
+
+  if (bUpdate)
+  {
+    Sys_UpdateWindows(W_ALL);
+  }
+  UpdatePatchInspector();
+}
+
+
+
+
+/*
+==================
+Patch_Save
+==================
+ Saves patch ctrl info (originally to deal with a 
+ cancel in the surface dialog
+*/
+void Patch_Save(patchMesh_t *p)
+{
+  patchSave.width = p->width;
+  patchSave.height = p->height;
+  memcpy(patchSave.ctrl, p->ctrl, sizeof(p->ctrl));
+}
+
+
+/*
+==================
+Patch_Restore
+==================
+*/
+void Patch_Restore(patchMesh_t *p)
+{
+  p->width = patchSave.width;
+  p->height = patchSave.height;
+  memcpy(p->ctrl, patchSave.ctrl, sizeof(p->ctrl));
+}
+
+void Patch_ResetTexturing(float fx, float fy)
+{
+       for (brush_t* pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      patchMesh_t *p = pb->pPatch;
+      p->bDirty = true;
+           for ( int i = 0 ; i < p->width ; i++ ) 
+      {
+                   for ( int j = 0 ; j < p->height ; j++ ) 
+        {
+                           p->ctrl[i][j].st[0] = fx * (float)i / (p->width - 1);
+                           p->ctrl[i][j].st[1] = 1 - fy * (float)j / (p->height - 1);
+                   }
+           }
+    }
+  }
+}
+
+// NOTE TTimo stub!
+void Patch_FitTexturing()
+{
+  Patch_ResetTexturing(1.0f, 1.0f);
+}
+
+void Patch_SetTextureInfo(texdef_t *pt)
+{
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      if (pt->rotate)
+        Patch_RotateTexture(pb->pPatch, pt->rotate);
+
+      if (pt->shift[0] || pt->shift[1])
+        Patch_ShiftTexture(pb->pPatch, pt->shift[0], pt->shift[1]);
+
+      if (pt->scale[0] || pt->scale[1])
+        Patch_ScaleTexture(pb->pPatch, pt->scale[0], pt->scale[1], false);
+
+      patchMesh_t *p = pb->pPatch;
+      p->contents = pt->contents;
+      p->flags = pt->flags;
+      p->value = pt->value;
+    }
+  }
+}
+
+bool OnlyPatchesSelected()
+{
+  if (g_ptrSelectedFaces.GetSize() > 0 || selected_brushes.next == &selected_brushes)
+    return false;
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (!pb->patchBrush)
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+bool AnyPatchesSelected()
+{
+  if (g_ptrSelectedFaces.GetSize() > 0  || selected_brushes.next == &selected_brushes)
+    return false;
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      return true;
+    }
+  }
+  return false;
+}
+
+patchMesh_t* SinglePatchSelected()
+{
+  if (selected_brushes.next->patchBrush)
+  {
+    return selected_brushes.next->pPatch;
+  }
+  return NULL;
+}
+
+void Patch_BendToggle()
+{
+  if (g_bPatchBendMode)
+  {
+    g_bPatchBendMode = false;
+    HideInfoDialog();
+    g_pParentWnd->UpdatePatchToolbarButtons() ;
+    return;
+  }
+
+       brush_t* b = selected_brushes.next;
+
+  if (!QE_SingleBrush(true) || !b->patchBrush)
+  {
+    Sys_Printf("Patch_BendToggle: you must have a single patch selected\n");
+               return;
+  }
+
+  Patch_Save(b->pPatch);
+       g_bPatchBendMode = true;
+  g_nPatchBendState = BEND_SELECT_ROTATION;
+  g_bPatchAxisOnRow = true;
+  g_nPatchAxisIndex = 1;
+  ShowInfoDialog(g_pBendStateMsg[BEND_SELECT_ROTATION]);
+}
+
+void Patch_BendHandleTAB()
+{
+  if (!g_bPatchBendMode)
+  {
+    return;
+  }
+
+       brush_t* b = selected_brushes.next;
+  if (!QE_SingleBrush() || !b->patchBrush)
+  {
+    Patch_BendToggle();
+    Sys_Printf("No patch to bend!");
+               return;
+  }
+
+  patchMesh_t *p = b->pPatch;
+
+  bool bShift = Sys_ShiftDown ();
+
+  if (g_nPatchBendState == BEND_SELECT_ROTATION)
+  {
+    // only able to deal with odd numbered rows/cols
+    g_nPatchAxisIndex += (bShift) ? -2 : 2;
+    if (g_bPatchAxisOnRow)
+    {
+      if ((bShift) ? g_nPatchAxisIndex <= 0 : g_nPatchAxisIndex >= p->height)
+      {
+        g_bPatchAxisOnRow = false;
+        g_nPatchAxisIndex = (bShift) ? p->width-1 : 1;
+      }
+    }
+    else
+    {
+      if ((bShift) ? g_nPatchAxisIndex <= 0 : g_nPatchAxisIndex >= p->width)
+      {
+        g_bPatchAxisOnRow = true;
+        g_nPatchAxisIndex = (bShift) ? p->height-1 : 1;
+      }
+    }
+  }
+  else
+  if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+  {
+    g_nBendOriginIndex += (bShift) ? -1 : 1;
+    if (g_bPatchAxisOnRow)
+    {
+      if (bShift)
+      {
+        if (g_nBendOriginIndex < 0)
+          g_nBendOriginIndex = p->width-1;
+      }
+      else
+      {
+        if (g_nBendOriginIndex > p->width-1)
+          g_nBendOriginIndex = 0;
+      }
+      VectorCopy(p->ctrl[g_nBendOriginIndex][g_nPatchAxisIndex].xyz, g_vBendOrigin);
+    }
+    else
+    {
+      if (bShift)
+      {
+        if (g_nBendOriginIndex < 0)
+          g_nBendOriginIndex = p->height-1;
+      }
+      else
+      {
+        if (g_nBendOriginIndex > p->height-1)
+          g_nBendOriginIndex = 0;
+      }
+      VectorCopy(p->ctrl[g_nPatchAxisIndex][g_nBendOriginIndex].xyz, g_vBendOrigin);
+    }
+  }
+  else
+  if (g_nPatchBendState == BEND_SELECT_EDGE)
+  {
+    g_bPatchLowerEdge ^= 1;
+  }
+  Sys_UpdateWindows(W_ALL);
+}
+
+void Patch_BendHandleENTER()
+{
+  if (!g_bPatchBendMode)
+  {
+    return;
+  }
+
+  if (g_nPatchBendState  < BEND_BENDIT)
+  {
+    g_nPatchBendState++;
+    ShowInfoDialog(g_pBendStateMsg[g_nPatchBendState]);
+    if (g_nPatchBendState == BEND_SELECT_ORIGIN)
+    {
+      g_vBendOrigin[0] = g_vBendOrigin[1] = g_vBendOrigin[2] = 0;
+      g_nBendOriginIndex = 0;
+      Patch_BendHandleTAB();
+    }
+    else
+    if (g_nPatchBendState == BEND_SELECT_EDGE)
+    {
+      g_bPatchLowerEdge = true;
+    }
+    else
+    if (g_nPatchBendState == BEND_BENDIT)
+    {
+      // basically we go into rotation mode, set the axis to the center of the 
+    }
+  }
+  else
+  {
+    // done
+    Patch_BendToggle();
+  }
+  Sys_UpdateWindows(W_ALL);
+
+}
+
+
+void Patch_BendHandleESC()
+{
+  if (!g_bPatchBendMode)
+  {
+    return;
+  }
+  Patch_BendToggle();
+       brush_t* b = selected_brushes.next;
+  if (QE_SingleBrush() && b->patchBrush)
+  {
+    Patch_Restore(b->pPatch);
+  }
+  Sys_UpdateWindows(W_ALL);
+}
+
+void Patch_SetBendRotateOrigin(patchMesh_t *p)
+{
+#if 1
+  int nType = g_pParentWnd->ActiveXY()->GetViewType();
+  int nDim3 = (nType == XY) ? 2 : (nType == YZ) ? 0 : 1;
+
+  g_vBendOrigin[nDim3] = 0;
+  VectorCopy(g_vBendOrigin, g_pParentWnd->ActiveXY()->RotateOrigin());
+  return;
+#else
+  int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+  int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+
+  float fxLo, fyLo, fxHi, fyHi;
+  fxLo = fyLo = 9999;
+  fxHi = fyHi = -9999;
+
+  if (g_bPatchAxisOnRow)
+  {
+    for (int i = 0; i < p->width; i++)
+    {
+      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1] < fxLo)
+        fxLo = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1];
+
+      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1] > fxHi)
+        fxHi = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim1];
+
+      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2] < fyLo)
+        fyLo = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2];
+
+      if (p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2] > fyHi)
+        fyHi = p->ctrl[i][g_nPatchAxisIndex].xyz[nDim2];
+    }
+  }
+  else
+  {
+    for (int i = 0; i < p->height; i++)
+    {
+      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1] < fxLo)
+        fxLo = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1];
+
+      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1] > fxHi)
+        fxHi = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim1];
+
+      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2] < fyLo)
+        fyLo = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2];
+
+      if (p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2] > fyHi)
+        fyHi = p->ctrl[g_nPatchAxisIndex][i].xyz[nDim2];
+    }
+  }
+
+  g_pParentWnd->ActiveXY()->RotateOrigin()[0] = g_pParentWnd->ActiveXY()->RotateOrigin()[1] = g_pParentWnd->ActiveXY()->RotateOrigin()[2] = 0.0;
+  g_pParentWnd->ActiveXY()->RotateOrigin()[nDim1] = (fxLo + fxHi) * 0.5;
+  g_pParentWnd->ActiveXY()->RotateOrigin()[nDim2] = (fyLo + fyHi) * 0.5;
+#endif
+}
+
+// also sets the rotational origin
+void Patch_SelectBendAxis()
+{
+       brush_t* b = selected_brushes.next;
+  if (!QE_SingleBrush() || !b->patchBrush)
+  {
+    // should not ever happen
+    Patch_BendToggle();
+               return;
+  }
+
+  patchMesh_t *p = b->pPatch;
+  if (g_bPatchAxisOnRow)
+  {
+    SelectRow(p, g_nPatchAxisIndex, false);
+  }
+  else
+  {
+    SelectColumn(p, g_nPatchAxisIndex, false);
+  }
+
+  //FIXME: this only needs to be set once... 
+  Patch_SetBendRotateOrigin(p);
+
+}
+
+void Patch_SelectBendNormal()
+{
+       brush_t* b = selected_brushes.next;
+  if (!QE_SingleBrush() || !b->patchBrush)
+  {
+    // should not ever happen
+    Patch_BendToggle();
+               return;
+  }
+
+  patchMesh_t *p = b->pPatch;
+
+  g_qeglobals.d_num_move_points = 0;
+  if (g_bPatchAxisOnRow)
+  {
+    if (g_bPatchLowerEdge)
+    {
+      for (int j = 0; j < g_nPatchAxisIndex; j++)
+        SelectRow(p, j, true);
+    }
+    else
+    {
+      for (int j = p->height-1; j > g_nPatchAxisIndex; j--)
+        SelectRow(p, j, true);
+    }
+  }
+  else
+  {
+    if (g_bPatchLowerEdge)
+    {
+      for (int j = 0; j < g_nPatchAxisIndex; j++)
+        SelectColumn(p, j, true);
+    }
+    else
+    {
+      for (int j = p->width-1; j > g_nPatchAxisIndex; j--)
+        SelectColumn(p, j, true);
+    }
+  }
+  Patch_SetBendRotateOrigin(p);
+}
+
+
+
+/*
+void Patch_InsDelToggle()
+{
+  if (g_bPatchInsertMode)
+  {
+    g_bPatchInsertMode = false;
+    HideInfoDialog();
+    g_pParentWnd->UpdatePatchToolbarButtons() ;
+    return;
+  }
+
+       brush_t* b = selected_brushes.next;
+
+  if (!QE_SingleBrush(true) || !b->patchBrush)
+  {
+    Sys_Printf("Patch_InsDelToggle: you must have a single patch selected\n");
+               return;
+  }
+
+  Patch_Save(b->pPatch);
+       g_bPatchInsertMode = true;
+  g_nPatchInsertState = INSERT_SELECT_EDGE;
+  g_bPatchAxisOnRow = true;
+  g_nPatchAxisIndex = 0;
+  ShowInfoDialog(g_pInsertStateMsg[INSERT_SELECT_EDGE]);
+
+}
+
+void Patch_InsDelESC()
+{
+  if (!g_bPatchInsertMode)
+  {
+    return;
+  }
+  Patch_InsDelToggle();
+  Sys_UpdateWindows(W_ALL);
+}
+
+
+void Patch_InsDelHandleENTER()
+{
+}
+
+void Patch_InsDelHandleTAB()
+{
+  if (!g_bPatchInsertMode)
+  {
+    Patch_InsDelToggle();
+    return;
+  }
+
+       brush_t* b = selected_brushes.next;
+  if (!QE_SingleBrush() || !b->patchBrush)
+  {
+    Patch_BendToggle();
+    Sys_Printf("No patch to bend!");
+               return;
+  }
+
+  patchMesh_t *p = b->pPatch;
+
+  // only able to deal with odd numbered rows/cols
+  g_nPatchAxisIndex += 2;
+  if (g_bPatchAxisOnRow)
+  {
+    if (g_nPatchAxisIndex >= p->height-1)
+    {
+      g_bPatchAxisOnRow = false;
+      g_nPatchAxisIndex = 0;
+    }
+  }
+  else
+  {
+    if (g_nPatchAxisIndex >= p->width-1)
+    {
+      g_bPatchAxisOnRow = true;
+      g_nPatchAxisIndex = 0;
+    }
+  }
+  Sys_UpdateWindows(W_ALL);
+}
+*/
+
+
+void _Write1DMatrix (FILE *f, int x, float *m) {
+       int             i;
+
+       fprintf (f, "( ");
+       for (i = 0 ; i < x ; i++) {
+               if (m[i] == (int)m[i] ) {
+                       fprintf (f, "%i ", (int)m[i]);
+               } else {
+                       fprintf (f, "%f ", m[i]);
+               }
+       }
+       fprintf (f, ")");
+}
+
+void _Write2DMatrix (FILE *f, int y, int x, float *m) {
+       int             i;
+
+       fprintf (f, "( ");
+       for (i = 0 ; i < y ; i++) {
+               _Write1DMatrix (f, x, m + i*x);
+               fprintf (f, " ");
+       }
+       fprintf (f, ")\n");
+}
+
+
+void _Write3DMatrix (FILE *f, int z, int y, int x, float *m) {
+       int             i;
+
+       fprintf (f, "(\n");
+       for (i = 0 ; i < z ; i++) {
+               _Write2DMatrix (f, y, x, m + i*(x*MAX_PATCH_HEIGHT) );
+       }
+       fprintf (f, ")\n");
+}
+
+void _Write1DMatrix (MemStream *f, int x, float *m) {
+       int             i;
+
+       MemFile_fprintf (f, "( ");
+       for (i = 0 ; i < x ; i++) {
+               if (m[i] == (int)m[i] ) {
+                       MemFile_fprintf (f, "%i ", (int)m[i]);
+               } else {
+                       MemFile_fprintf (f, "%f ", m[i]);
+               }
+       }
+       MemFile_fprintf (f, ")");
+}
+
+void _Write2DMatrix (MemStream *f, int y, int x, float *m) {
+       int             i;
+
+       MemFile_fprintf (f, "( ");
+       for (i = 0 ; i < y ; i++) {
+               _Write1DMatrix (f, x, m + i*x);
+               MemFile_fprintf (f, " ");
+       }
+       MemFile_fprintf (f, ")\n");
+}
+
+
+void _Write3DMatrix (MemStream *f, int z, int y, int x, float *m) {
+       int             i;
+
+       MemFile_fprintf (f, "(\n");
+       for (i = 0 ; i < z ; i++) {
+               _Write2DMatrix (f, y, x, m + i*(x*MAX_PATCH_HEIGHT) );
+       }
+       MemFile_fprintf (f, ")\n");
+}
+
+// NOTE: why the hell is this called Naturalize?
+// we dispatch either to Patch+Naturalize or Patch_CapTexture..
+void Patch_NaturalizeSelected(bool bCap)
+{
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      if (bCap)
+        Patch_CapTexture(pb->pPatch);//, bCycleCap);
+      else
+        Patch_Naturalize(pb->pPatch);
+    }
+  }
+}
+
+// go through the selected patches and call Patch_CapTexture
+// deal with cycling
+void Patch_CycleCapSelected()
+{
+  // compute the g_vCycleCapNormal according to g_nCycleCapIndex
+  VectorClear (g_vCycleCapNormal);
+  g_vCycleCapNormal[g_nCycleCapIndex] = 1.0f; // cf VIEWTYPE defintion: enum VIEWTYPE {YZ, XZ, XY};
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      Patch_CapTexture(pb->pPatch, true);
+    }
+  }
+  switch (g_nCycleCapIndex)
+  {
+  case YZ:
+    g_nCycleCapIndex = XZ;
+    break;
+  case XZ:
+    g_nCycleCapIndex = XY;
+    break;
+  case XY:
+    g_nCycleCapIndex = YZ;
+    break;
+  }
+}
+
+bool within(vec3_t vTest, vec3_t vTL, vec3_t vBR)
+{
+  int nDim1 = (g_pParentWnd->ActiveXY()->GetViewType() == YZ) ? 1 : 0;
+  int nDim2 = (g_pParentWnd->ActiveXY()->GetViewType() == XY) ? 1 : 2;
+  if ((vTest[nDim1] > vTL[nDim1] && vTest[nDim1] < vBR[nDim1]) ||
+      (vTest[nDim1] < vTL[nDim1] && vTest[nDim1] > vBR[nDim1]))
+  {
+    if ((vTest[nDim2] > vTL[nDim2] && vTest[nDim2] < vBR[nDim2]) ||
+        (vTest[nDim2] < vTL[nDim2] && vTest[nDim2] > vBR[nDim2]))
+      return true;
+  }
+  return false;
+}
+
+
+void Patch_SelectAreaPoints(bool bMulti)
+{
+  if (!bMulti)
+    g_qeglobals.d_num_move_points = 0;
+
+  if( g_nPatchClickedView == W_CAMERA ) {
+    // Clip against a pyramid
+    // Create our 5 normals (that are pointing to the inside)
+    camera_t *m_pCamera = g_pParentWnd->GetCamWnd()->Camera();
+    vec3_t     norm[5];
+    float              r[2], u[2], hh, hw;
+    int                        idx;
+    vec_t              corners[2][2];
+    vec3_t     ray[4];
+    vec3_t  check;
+
+    VectorCopy( m_pCamera->vpn, norm[0] ); // only points in front of the camera
+
+    // get our rectangle
+    corners[0][0] = MIN( g_qeglobals.d_vAreaTL[0], g_qeglobals.d_vAreaBR[0] );
+    corners[0][1] = MAX( g_qeglobals.d_vAreaTL[1], g_qeglobals.d_vAreaBR[1] );
+    corners[1][0] = MAX( g_qeglobals.d_vAreaTL[0], g_qeglobals.d_vAreaBR[0] );
+    corners[1][1] = MIN( g_qeglobals.d_vAreaTL[1], g_qeglobals.d_vAreaBR[1] );
+
+    // calculate our four ray vectors
+    hh = m_pCamera->height/2;
+    hw = m_pCamera->width/2;
+    u[0] = (float)(corners[0][1] - hh) / (hw);
+    r[0] = (float)(corners[0][0] - hw) / (hw);
+    u[1] = (float)(corners[1][1] - hh) / (hw);
+    r[1] = (float)(corners[1][0] - hw) / (hw);
+
+    for (idx=0 ; idx<3; idx++)
+           ray[0][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[0] + m_pCamera->vup[idx] * u[0];
+    for (idx=0 ; idx<3; idx++)
+           ray[1][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[1] + m_pCamera->vup[idx] * u[0];
+    for (idx=0 ; idx<3; idx++)
+           ray[2][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[1] + m_pCamera->vup[idx] * u[1];
+    for (idx=0 ; idx<3; idx++)
+           ray[3][idx] = m_pCamera->vpn[idx] + m_pCamera->vright[idx] * r[0] + m_pCamera->vup[idx] * u[1];
+
+    // Create our four other directions from these
+    CrossProduct( ray[0], ray[1], norm[1] ); VectorNormalize( norm[1], norm[1] );
+    CrossProduct( ray[1], ray[2], norm[2] ); VectorNormalize( norm[2], norm[2] );
+    CrossProduct( ray[2], ray[3], norm[3] ); VectorNormalize( norm[3], norm[3] );
+    CrossProduct( ray[3], ray[0], norm[4] ); VectorNormalize( norm[4], norm[4] );
+               
+               // 3D clipping
+               for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+               {
+                       if (pb->patchBrush)
+                       {
+                               patchMesh_t *p = pb->pPatch;
+                               for (int i = 0; i < p->width; i++)
+                               {
+                                       for (int j = 0; j < p->height; j++)
+                                       {
+                                               VectorSubtract( m_pCamera->origin, p->ctrl[i][j].xyz, check );
+                                               VectorNormalize( check, check );
+                                               for (idx=0 ; idx<5; idx++)
+                                               {
+                                                       if (DotProduct(check, norm[idx])>=0)
+                                                               break;
+                                               }
+                                               if (idx == 5) // all test were good
+            {
+                                                       if (bMulti && PointInMoveList(p->ctrl[i][j].xyz) != -1)
+                                                               RemovePointFromMoveList(p->ctrl[i][j].xyz);
+              else
+                                                         g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+            }
+                                       }
+                               }
+                       }
+               }
+       } else
+       {
+               // Simple 2D clipping
+               for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+               {
+                       if (pb->patchBrush)
+                       {
+                               patchMesh_t *p = pb->pPatch;
+                               for (int i = 0; i < p->width; i++)
+                               {
+                                       for (int j = 0; j < p->height; j++)
+                                       {
+                                               if (within(p->ctrl[i][j].xyz, g_qeglobals.d_vAreaTL, g_qeglobals.d_vAreaBR))
+                                               {
+                                                       if (bMulti && PointInMoveList(p->ctrl[i][j].xyz) != -1)
+                                                               RemovePointFromMoveList(p->ctrl[i][j].xyz);
+                                                       else
+                                                               g_qeglobals.d_move_points[g_qeglobals.d_num_move_points++] = p->ctrl[i][j].xyz;
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+
+       g_nPatchClickedView = -1;
+}
+
+// TTimo: return the shader name for a patch
+const char* Patch_GetTextureName()
+{
+       brush_t* b = selected_brushes.next;
+  if (b->patchBrush)
+  {
+    patchMesh_t *p = b->pPatch;
+    return p->pShader->getName();
+  }
+  return "";
+}
+
+patchMesh_t* Patch_Duplicate(patchMesh_t *pFrom)
+{
+  patchMesh_t* p = MakeNewPatch();
+  memcpy(p, pFrom , sizeof(patchMesh_t));
+  
+       // spog - initialise patch LOD pointers (again)
+  Patch_InitialiseLODPointers(p);
+  p->drawLists = NULL;
+
+  p->bSelected = false;
+  p->bDirty = true;
+  p->bOverlay = false;
+  p->nListID = -1;
+  AddBrushForPatch(p);
+  return p;
+}
+
+
+void Patch_Thicken(int nAmount, bool bSeam, qboolean bGroupResult)
+{
+  int i, j, h, w;
+  brush_t *b;
+  patchMesh_t *pSeam;
+  vec3_t vMin, vMax;
+  CPtrArray brushes;
+
+  nAmount = -nAmount;
+
+
+       if (!QE_SingleBrush())
+  {
+    Sys_Printf("Cannot thicken multiple patches. Please select a single patch.\n");
+               return;
+  }
+
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      patchMesh_t *p = pb->pPatch;
+      Patch_MeshNormals(p);
+      patchMesh_t *pNew = Patch_Duplicate(p);
+      for (i = 0; i < p->width; i++)
+      {
+        for (j = 0; j < p->height; j++)
+        {
+                     VectorMA (p->ctrl[i][j].xyz, nAmount, p->ctrl[i][j].normal, pNew->ctrl[i][j].xyz);
+        }
+      }
+
+      Patch_Rebuild(pNew);
+      pNew->type |= PATCH_THICK;
+      brushes.Add(pNew->pSymbiot);
+
+      if (bSeam)
+      {
+
+        // FIXME: this should detect if any edges of the patch are closed and act appropriately
+        // 
+        if (!(p->type & PATCH_CYLINDER))
+        {
+          b = Patch_GenericMesh(3, p->height, 2, false, true);
+          pSeam = b->pPatch;
+          pSeam->type |= PATCH_SEAM;
+          for (i = 0; i < p->height; i++)
+          {
+            VectorCopy(p->ctrl[0][i].xyz, pSeam->ctrl[0][i].xyz);
+            VectorCopy(pNew->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz);
+            VectorAdd(pSeam->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz, pSeam->ctrl[1][i].xyz);
+            VectorScale(pSeam->ctrl[1][i].xyz, 0.5, pSeam->ctrl[1][i].xyz);
+          }
+
+
+          Patch_CalcBounds(pSeam, vMin, vMax);
+          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+          //--Patch_CapTexture(pSeam);
+          Patch_Naturalize(pSeam);
+          patchInvert(pSeam);
+          brushes.Add(b);
+
+          w = p->width - 1;
+          b = Patch_GenericMesh(3, p->height, 2, false, true);
+          pSeam = b->pPatch;
+          pSeam->type |= PATCH_SEAM;
+          for (i = 0; i < p->height; i++)
+          {
+            VectorCopy(p->ctrl[w][i].xyz, pSeam->ctrl[0][i].xyz);
+            VectorCopy(pNew->ctrl[w][i].xyz, pSeam->ctrl[2][i].xyz);
+            VectorAdd(pSeam->ctrl[0][i].xyz, pSeam->ctrl[2][i].xyz, pSeam->ctrl[1][i].xyz);
+            VectorScale(pSeam->ctrl[1][i].xyz, 0.5, pSeam->ctrl[1][i].xyz);
+          }
+          Patch_CalcBounds(pSeam, vMin, vMax);
+          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+          //--Patch_CapTexture(pSeam);
+          Patch_Naturalize(pSeam);
+          brushes.Add(b);
+        }
+    
+        //--{
+          // otherwise we will add one per end
+          b = Patch_GenericMesh(p->width, 3, 2, false, true);
+          pSeam = b->pPatch;
+          pSeam->type |= PATCH_SEAM;
+          for (i = 0; i < p->width; i++)
+          {
+            VectorCopy(p->ctrl[i][0].xyz, pSeam->ctrl[i][0].xyz);
+            VectorCopy(pNew->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz);
+            VectorAdd(pSeam->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz, pSeam->ctrl[i][1].xyz);
+            VectorScale(pSeam->ctrl[i][1].xyz, 0.5, pSeam->ctrl[i][1].xyz);
+          }
+
+
+          Patch_CalcBounds(pSeam, vMin, vMax);
+          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+          //--Patch_CapTexture(pSeam);
+          Patch_Naturalize(pSeam);
+          patchInvert(pSeam);
+          brushes.Add(b);
+
+          h = p->height - 1;
+          b = Patch_GenericMesh(p->width, 3, 2, false, true);
+          pSeam = b->pPatch;
+          pSeam->type |= PATCH_SEAM;
+          for (i = 0; i < p->width; i++)
+          {
+            VectorCopy(p->ctrl[i][h].xyz, pSeam->ctrl[i][0].xyz);
+            VectorCopy(pNew->ctrl[i][h].xyz, pSeam->ctrl[i][2].xyz);
+            VectorAdd(pSeam->ctrl[i][0].xyz, pSeam->ctrl[i][2].xyz, pSeam->ctrl[i][1].xyz);
+            VectorScale(pSeam->ctrl[i][1].xyz, 0.5, pSeam->ctrl[i][1].xyz);
+          }
+          Patch_CalcBounds(pSeam, vMin, vMax);
+          Brush_RebuildBrush(pSeam->pSymbiot, vMin, vMax);
+          //--Patch_CapTexture(pSeam);
+          Patch_Naturalize(pSeam);
+          brushes.Add(b);
+
+      }
+      patchInvert(pNew);
+    }
+  }
+
+  for (i = 0; i < brushes.GetSize(); i++)
+  {
+    Select_Brush(reinterpret_cast<brush_t*>(brushes.GetAt(i)));
+  }
+
+  if(bGroupResult) 
+  {
+    entity_t *e = Entity_Alloc();
+    SetKeyValue(e, "classname", "func_group");
+    SetKeyValue(e, "type", "patchThick");
+    Select_GroupEntity(e);
+    Entity_AddToList(e, &entities);
+  }
+  
+  UpdatePatchInspector();
+}
+
+
+/*
+lets get another list together as far as necessities..
+
+*snapping stuff to the grid (i will only snap movements by the mouse to the grid.. snapping the rotational bend stuff will fubar everything)
+
+capping bevels/endcaps
+
+hot keys
+
+texture fix for caps
+
+clear clipboard
+
+*region fix
+
+*surface dialog
+
+*/
+
+void Patch_SetOverlays()
+{
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      pb->pPatch->bOverlay = true;
+    }
+  }
+}
+
+
+
+void Patch_ClearOverlays()
+{
+  brush_t *pb;
+       for (pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      pb->pPatch->bOverlay = false;
+    }
+  }
+
+       for (pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      pb->pPatch->bOverlay = false;
+    }
+  }
+
+}
+
+// FIXME: spog - er, someone forgot to finish their patch point freezing feature?
+// freezes selected vertices
+void Patch_Freeze()
+{
+  brush_t *pb;
+       for (pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      pb->pPatch->bOverlay = false;
+    }
+  }
+
+       for (pb = active_brushes.next ; pb != &active_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      pb->pPatch->bOverlay = false;
+    }
+  }
+
+}
+
+void Patch_UnFreeze(bool bAll)
+{
+}
+
+void Patch_Transpose()
+{
+       int             i, j, w;
+  drawVert_t dv;
+       for (brush_t *pb = selected_brushes.next ; pb != &selected_brushes ; pb = pb->next)
+       {
+    if (pb->patchBrush)
+    {
+      patchMesh_t *p = pb->pPatch;
+
+      if ( p->width > p->height ) 
+      {
+       for ( i = 0 ; i < p->height ; i++ ) 
+        {
+         for ( j = i + 1 ; j < p->width ; j++ ) 
+          {
+           if ( j < p->height ) 
+            {
+             // swap the value
+             memcpy(&dv,&p->ctrl[j][i],sizeof(drawVert_t));
+             memcpy(&p->ctrl[j][i],&p->ctrl[i][j], sizeof(drawVert_t));
+             memcpy(&p->ctrl[i][j],&dv, sizeof(drawVert_t));
+           } 
+            else 
+            {
+                                       // just copy
+                                       memcpy(&p->ctrl[i][j],&p->ctrl[j][i], sizeof(drawVert_t));
+                               }
+                       }
+                 }
+           } 
+      else 
+      {
+               for ( i = 0 ; i < p->width ; i++ ) 
+        {
+                         for ( j = i + 1 ; j < p->height ; j++ ) 
+          {
+                               if ( j < p->width ) 
+            {
+                                           // swap the value
+                                           memcpy(&dv,&p->ctrl[i][j], sizeof(drawVert_t));
+              memcpy(&p->ctrl[i][j],&p->ctrl[j][i], sizeof(drawVert_t));
+                                       memcpy(&p->ctrl[j][i],&dv, sizeof(drawVert_t));
+                               } 
+            else 
+            {
+                                       // just copy
+                                       memcpy(&p->ctrl[j][i],&p->ctrl[i][j], sizeof(drawVert_t));
+                               }
+                       }
+               }
+       }
+
+      w = p->width;
+      p->width = p->height;
+      p->height = w;
+      patchInvert(p);
+      Patch_Rebuild(p);
+               }
+       }
+}
+
+
+
+void Patch_SnapToGrid(patchMesh_t *p)
+{
+       int i,j,k;
+       
+       // if patch points selected, snap only selected points
+       if (g_qeglobals.d_select_mode == sel_curvepoint && g_qeglobals.d_num_move_points != 0)
+               for (i=0; i<g_qeglobals.d_num_move_points; i++)
+                       for (j = 0; j < 3; j++)
+                               g_qeglobals.d_move_points[i][j] = floor(g_qeglobals.d_move_points[i][j] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+                       
+       // else snap all patch points
+       else
+               for (i = 0; i < p->width; i++)
+                       for (j = 0; j < p->height; j++)
+                               for (k = 0; k < 3; k++)
+                                       p->ctrl[i][j].xyz[k] = floor(p->ctrl[i][j].xyz[k] / g_qeglobals.d_gridsize + 0.5) * g_qeglobals.d_gridsize;
+                               
+       vec3_t vMin, vMax;
+       Patch_CalcBounds(p, vMin, vMax);
+       Brush_RebuildBrush(p->pSymbiot, vMin, vMax);
+}
+
+
+void Patch_FindReplaceTexture(brush_t *pb, const char *pFind, const char *pReplace, bool bForce)
+{
+  if (pb->patchBrush)
+  {
+    patchMesh_t *p = pb->pPatch;
+    if (bForce || strcmpi(p->pShader->getName(), pFind) == 0)
+    {
+      p->pShader->DecRef();
+      p->pShader = QERApp_Shader_ForName(pReplace);
+      p->d_texture = p->pShader->getTexture();
+    }
+  }
+}
+
+/* uncomment if necessary, currently not used
+void Patch_FromTriangle(vec5_t vx, vec5_t vy, vec5_t vz)
+{
+  patchMesh_t* p = MakeNewPatch();
+  p->pShader = g_qeglobals.d_texturewin.pShader;
+  p->d_texture = g_qeglobals.d_texturewin.pShader->getTexture();
+  p->width = 3;
+  p->height = 3;
+  p->type = PATCH_TRIANGLE;
+
+  // 0 0 goes to x
+  // 0 1 goes to x
+  // 0 2 goes to x
+
+  // 1 0 goes to mid of x and z
+  // 1 1 goes to mid of x y and z
+  // 1 2 goes to mid of x and y
+
+  // 2 0 goes to z
+  // 2 1 goes to mid of y and z
+  // 2 2 goes to y
+
+  vec5_t vMidXZ;
+  vec5_t vMidXY;
+  vec5_t vMidYZ;
+  int j;
+
+  for (j = 0; j < 3; j++)
+  {
+    _Vector5Add(vx, vz, vMidXZ);
+    _Vector5Scale(vMidXZ, 0.5, vMidXZ);
+    //vMidXZ[j] = vx[j] + abs((vx[j] - vz[j]) * 0.5);
+  }
+
+  for (j = 0; j < 3; j++)
+  {
+    _Vector5Add(vx, vy, vMidXY);
+    _Vector5Scale(vMidXY, 0.5, vMidXY);
+    //vMidXY[j] = vx[j] + abs((vx[j] - vy[j]) * 0.5);
+  }
+
+  for (j = 0; j < 3; j++)
+  {
+    _Vector5Add(vy, vz, vMidYZ);
+    _Vector5Scale(vMidYZ, 0.5, vMidYZ);
+    //vMidYZ[j] = vy[j] + abs((vy[j] - vz[j]) * 0.5);
+  }
+
+  _Vector53Copy(vx, p->ctrl[0][0].xyz);
+  _Vector53Copy(vx, p->ctrl[0][1].xyz);
+  _Vector53Copy(vx, p->ctrl[0][2].xyz);
+  p->ctrl[0][0].st[0] = vx[3];
+  p->ctrl[0][0].st[1] = vx[4];
+  p->ctrl[0][1].st[0] = vx[3];
+  p->ctrl[0][1].st[1] = vx[4];
+  p->ctrl[0][2].st[0] = vx[3];
+  p->ctrl[0][2].st[1] = vx[4];
+
+  _Vector53Copy(vMidXY, p->ctrl[1][0].xyz);
+  _Vector53Copy(vx, p->ctrl[1][1].xyz);
+  _Vector53Copy(vMidXZ, p->ctrl[1][2].xyz);
+  p->ctrl[1][0].st[0] = vMidXY[3];
+  p->ctrl[1][0].st[1] = vMidXY[4];
+  p->ctrl[1][1].st[0] = vx[3];
+  p->ctrl[1][1].st[1] = vx[4];
+  p->ctrl[1][2].st[0] = vMidXZ[3];
+  p->ctrl[1][2].st[1] = vMidXZ[4];
+
+  _Vector53Copy(vy, p->ctrl[2][0].xyz);
+  _Vector53Copy(vMidYZ, p->ctrl[2][1].xyz);
+  _Vector53Copy(vz, p->ctrl[2][2].xyz);
+  p->ctrl[2][0].st[0] = vy[3];
+  p->ctrl[2][0].st[1] = vy[4];
+  p->ctrl[2][1].st[0] = vMidYZ[3];
+  p->ctrl[2][1].st[1] = vMidYZ[4];
+  p->ctrl[2][2].st[0] = vz[3];
+  p->ctrl[2][2].st[1] = vz[4];
+
+
+  //Patch_Naturalize(p);
+
+  //  brush_t *b = 
+  AddBrushForPatch(p);
+
+}
+*/
+
+#ifdef ENABLE_GROUPS
+/*
+==============
+Patch_SetEpair
+sets an epair for the given patch
+==============
+*/
+void Patch_SetEpair(patchMesh_t *p, const char *pKey, const char *pValue)
+{
+       if (g_qeglobals.m_bBrushPrimitMode)
+       {
+               SetKeyValue(p->epairs, pKey, pValue);
+       }
+}
+
+/* 
+=================
+Patch_GetKeyValue
+=================
+*/
+const char* Patch_GetKeyValue(patchMesh_t *p, const char *pKey)
+{
+       if (g_qeglobals.m_bBrushPrimitMode)
+       {
+    return ValueForKey(p->epairs, pKey);
+       }
+  return "";
+}
+#endif
+
+
+//Real nitpicky, but could you make CTRL-S save the current map with the current name? (ie: File/Save)
+/*
+Feature addition.
+When reading in textures, please check for the presence of a file called "textures.link" or something, which contains one line such as;
+
+g:\quake3\baseq3\textures\common
+
+ So that, when I'm reading in, lets say, my \eerie directory, it goes through and adds my textures to the palette, along with everything in common.
+
+  Don't forget to add "Finer texture alignment" to the list. I'd like to be able to move in 0.1 increments using the Shift-Arrow Keys.
+
+  No. Sometimes textures are drawn the wrong way on patches. We'd like the ability to flip a texture. Like the way X/Y scale -1 used to worked.
+
+  1) Easier way of deleting rows, columns
+2) Fine tuning of textures on patches (X/Y shifts other than with the surface dialog)
+2) Patch matrix transposition
+
+  1) Actually, bump texture flipping on patches to the top of the list of things to do.
+2) When you select a patch, and hit S, it should read in the selected patch texture. Should not work if you multiselect patches and hit S
+3) Brandon has a wierd anomoly. He fine-tunes a patch with caps. It looks fine when the patch is selected, but as soon as he escapes out, it reverts to it's pre-tuned state. When he selects the patch again, it looks tuned
+
+
+*1) Flipping textures on patches
+*2) When you select a patch, and hit S, it should read in the selected patch texture. Should not work if you multiselect patches and hit S
+3) Easier way of deleting rows columns
+*4) Thick Curves
+5) Patch matrix transposition
+6) Inverted cylinder capping
+*7) bugs
+*8) curve speed
+
+  Have a new feature request. "Compute Bounding Box" for mapobjects (md3 files). This would be used for misc_mapobject (essentially, drop in 3DS Max models into our maps)
+
+  Ok, Feature Request. Load and draw MD3's in the Camera view with proper bounding boxes. This should be off misc_model
+
+  Feature Addition: View/Hide Hint Brushes -- This should be a specific case.
+*/