]> git.rm.cloudns.org Git - xonotic/darkplaces.git/commitdiff
implemented Direct3D9 renderer (off by default), not very optimized but almost comple...
authorhavoc <havoc@d7cf8633-e32d-0410-b094-e92efae38249>
Sat, 3 Jul 2010 10:27:16 +0000 (10:27 +0000)
committerhavoc <havoc@d7cf8633-e32d-0410-b094-e92efae38249>
Sat, 3 Jul 2010 10:27:16 +0000 (10:27 +0000)
git-svn-id: svn://svn.icculus.org/twilight/trunk/darkplaces@10267 d7cf8633-e32d-0410-b094-e92efae38249

16 files changed:
builddate.c
cl_screen.c
darkplaces-wgl.vcproj
gl_backend.c
gl_backend.h
gl_draw.c
gl_rmain.c
gl_textures.c
model_shared.c
model_shared.h
r_shadow.c
r_textures.h
render.h
vid.h
vid_shared.c
vid_wgl.c

index b7b53519ae65d2eecf9a155d4b73a1415fcd6770..061173ef4ca90c0750817b27ac9a80ac72db257e 100644 (file)
@@ -1,6 +1,7 @@
 #define STRINGIFY2(arg) #arg
 #define STRINGIFY(arg) STRINGIFY2(arg)
 
+extern const char *buildstring;
 const char *buildstring = __TIME__ " " __DATE__
 #ifdef SVNREVISION
 " " STRINGIFY(SVNREVISION)
index 5945f690c1e34994024c510f51f8eaddd5e31d65..36bc038e1f594467fd5c37f62e8cab48b565595e 100644 (file)
@@ -706,7 +706,7 @@ void R_TimeReport(char *desc)
                return;
 
        CHECKGLERROR
-       if (r_speeds.integer == 2)
+       if (r_speeds.integer == 2 && qglFinish)
                qglFinish();
        CHECKGLERROR
        r_timereport_temp = r_timereport_current;
@@ -1231,7 +1231,8 @@ void SCR_CaptureVideo_VideoFrame(int newframestepframenum)
        CHECKGLERROR
        // speed is critical here, so do saving as directly as possible
 
-       qglReadPixels (x, y, vid.width, vid.height, GL_BGRA, GL_UNSIGNED_BYTE, cls.capturevideo.screenbuffer);CHECKGLERROR
+       GL_ReadPixelsBGRA(x, y, vid.width, vid.height, cls.capturevideo.screenbuffer);
+
        SCR_ScaleDownBGRA (cls.capturevideo.screenbuffer, vid.width, vid.height, cls.capturevideo.outbuffer, width, height);
 
        cls.capturevideo.videoframes(newframestepframenum - cls.capturevideo.framestepframe);
@@ -1476,8 +1477,7 @@ qboolean SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *b
        int     indices[4] = {0,1,2,3}; // BGRA
        qboolean ret;
 
-       CHECKGLERROR
-       qglReadPixels (x, y, width, height, GL_BGRA, GL_UNSIGNED_BYTE, buffer1);CHECKGLERROR
+       GL_ReadPixelsBGRA(x, y, width, height, buffer1);
 
        if(gammacorrect && (scr_screenshot_gammaboost.value != 1 || WANT_SCREENSHOT_HWGAMMA))
        {
@@ -1543,36 +1543,20 @@ qboolean SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *b
 extern void R_UpdateFogColor(void);
 void R_ClearScreen(qboolean fogcolor)
 {
+       float clearcolor[4];
        // clear to black
-       CHECKGLERROR
+       Vector4Clear(clearcolor);
        if (fogcolor)
        {
                R_UpdateFogColor();
-               qglClearColor(r_refdef.fogcolor[0],r_refdef.fogcolor[1],r_refdef.fogcolor[2],0);CHECKGLERROR
-       }
-       else
-       {
-               qglClearColor(0,0,0,0);CHECKGLERROR
-       }
-       qglClearDepth(1);CHECKGLERROR
-       if (vid.stencil)
-       {
-               // LordHavoc: we use a stencil centered around 128 instead of 0,
-               // to avoid clamping interfering with strange shadow volume
-               // drawing orders
-               qglClearStencil(128);CHECKGLERROR
+               VectorCopy(r_refdef.fogcolor, clearcolor);
        }
+       // clear depth is 1.0
+       // LordHavoc: we use a stencil centered around 128 instead of 0,
+       // to avoid clamping interfering with strange shadow volume
+       // drawing orders
        // clear the screen
-       GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (vid.stencil ? GL_STENCIL_BUFFER_BIT : 0));
-       // set dithering mode
-       if (gl_dither.integer)
-       {
-               qglEnable(GL_DITHER);CHECKGLERROR
-       }
-       else
-       {
-               qglDisable(GL_DITHER);CHECKGLERROR
-       }
+       GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (vid.stencil ? GL_STENCIL_BUFFER_BIT : 0), clearcolor, 1.0f, 128);
 }
 
 qboolean CL_VM_UpdateView (void);
@@ -1793,7 +1777,7 @@ static void SCR_SetLoadingScreenTexture(void)
                loadingscreentexture_h = vid.height / (float) h;
        }
 
-       loadingscreentexture = R_LoadTexture2D(r_main_texturepool, "loadingscreentexture", w, h, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
+       loadingscreentexture = R_LoadTexture2D(r_main_texturepool, "loadingscreentexture", w, h, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
        R_Mesh_CopyToTexture(loadingscreentexture, 0, 0, 0, 0, vid.width, vid.height);
 
        loadingscreentexture_vertex3f[2] = loadingscreentexture_vertex3f[5] = loadingscreentexture_vertex3f[8] = loadingscreentexture_vertex3f[11] = 0;
@@ -1952,16 +1936,14 @@ static void SCR_DrawLoadingScreen_SharedSetup (qboolean clear)
        // release mouse grab while loading
        if (!vid.fullscreen)
                VID_SetMouse(false, false, false);
-       CHECKGLERROR
+//     CHECKGLERROR
+       r_refdef.draw2dstage = true;
        R_Viewport_InitOrtho(&viewport, &identitymatrix, 0, 0, vid.width, vid.height, 0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100, NULL);
        R_SetViewport(&viewport);
-       //qglDisable(GL_SCISSOR_TEST);CHECKGLERROR
-       //qglDepthMask(1);CHECKGLERROR
-       qglColorMask(1,1,1,1);CHECKGLERROR
-       qglClearColor(0,0,0,0);CHECKGLERROR
+       GL_ColorMask(1,1,1,1);
        // when starting up a new video mode, make sure the screen is cleared to black
        if (clear)
-               qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
+               GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
        R_Textures_Frame();
        R_Mesh_Start();
        R_EntityMatrix(&identitymatrix);
@@ -2006,8 +1988,6 @@ static void SCR_DrawLoadingScreen_SharedFinish (qboolean clear)
        R_Mesh_Finish();
        // refresh
        VID_Finish();
-       // however this IS necessary on Windows Vista
-       qglFinish();
 }
 
 void SCR_UpdateLoadingScreen (qboolean clear)
@@ -2050,7 +2030,8 @@ void SCR_UpdateLoadingScreen (qboolean clear)
        }
        else
        {
-               qglDrawBuffer(GL_BACK);
+               if (qglDrawBuffer)
+                       qglDrawBuffer(GL_BACK);
                SCR_DrawLoadingScreen(clear);
        }
        SCR_DrawLoadingScreen_SharedFinish(clear);
@@ -2089,6 +2070,7 @@ void CL_UpdateScreen(void)
        double rendertime1;
        float conwidth, conheight;
        float f;
+       r_viewport_t viewport;
 
        Sbar_ShowFPS_Update();
 
@@ -2109,7 +2091,10 @@ void CL_UpdateScreen(void)
        }
 
        if (vid_hidden)
+       {
+               VID_Finish();
                return;
+       }
 
        rendertime1 = Sys_DoubleTime();
 
@@ -2151,13 +2136,27 @@ void CL_UpdateScreen(void)
 
        SCR_SetUpToDrawConsole();
 
-       CHECKGLERROR
-       qglDrawBuffer(GL_BACK);CHECKGLERROR
-       qglViewport(0, 0, vid.width, vid.height);CHECKGLERROR
-       qglDisable(GL_SCISSOR_TEST);CHECKGLERROR
-       qglDepthMask(1);CHECKGLERROR
-       qglColorMask(1,1,1,1);CHECKGLERROR
-       qglClearColor(0,0,0,0);CHECKGLERROR
+       if (qglDrawBuffer)
+       {
+               CHECKGLERROR
+               qglDrawBuffer(GL_BACK);CHECKGLERROR
+               // set dithering mode
+               if (gl_dither.integer)
+               {
+                       qglEnable(GL_DITHER);CHECKGLERROR
+               }
+               else
+               {
+                       qglDisable(GL_DITHER);CHECKGLERROR
+               }
+       }
+
+       R_Viewport_InitOrtho(&viewport, &identitymatrix, 0, 0, vid.width, vid.height, 0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100, NULL);
+       R_SetViewport(&viewport);
+       GL_ScissorTest(false);
+       GL_ColorMask(1,1,1,1);
+       GL_DepthMask(true);
+
        R_ClearScreen(false);
        r_refdef.view.clear = false;
        r_refdef.view.isoverlay = false;
@@ -2191,7 +2190,6 @@ void CL_UpdateScreen(void)
                }
        }
 
-       CHECKGLERROR
        if (R_Stereo_Active())
        {
                matrix4x4_t originalmatrix = r_refdef.view.matrix;
@@ -2236,13 +2234,13 @@ void CL_UpdateScreen(void)
        }
        else
                SCR_DrawScreen();
-       CHECKGLERROR
 
        SCR_CaptureVideo();
 
+       if (qglFlush)
+               qglFlush(); // FIXME: should we really be using qglFlush here?
+
        // quality adjustment according to render time
-       CHECKGLERROR
-       qglFlush(); // FIXME: should we really be using qglFlush here?
        cl_updatescreen_rendertime += ((Sys_DoubleTime() - rendertime1) - cl_updatescreen_rendertime) * bound(0, cl_minfps_fade.value, 1);
        if (cl_minfps.value > 0 && cl_updatescreen_rendertime > 0 && !cls.timedemo && (!cls.capturevideo.active || !cls.capturevideo.realtime))
                cl_updatescreen_quality = 1 / (cl_updatescreen_rendertime * cl_minfps.value);
index 3c736357aa47f526c9dc5229abe9ef1711e72ab1..a5393f9c54c681e580530b952b2572a27124e458 100644 (file)
                        <Tool\r
                                Name="VCCLCompilerTool"\r
                                Optimization="0"\r
-                               PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"\r
+                               PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;WIN32_LEAN_AND_MEAN;SUPPORTDIRECTX;SUPPORTD3D"\r
                                MinimalRebuild="true"\r
                                BasicRuntimeChecks="3"\r
                                RuntimeLibrary="3"\r
                                UsePrecompiledHeader="0"\r
                                WarningLevel="4"\r
                                DebugInformationFormat="4"\r
-                               DisableSpecificWarnings="4706;4127;4100;4055;4054;4244;4305;4702"\r
+                               DisableSpecificWarnings="4706;4127;4100;4055;4054;4244;4305;4702;4201;4611"\r
                        />\r
                        <Tool\r
                                Name="VCManagedResourceCompilerTool"\r
                                Name="VCCLCompilerTool"\r
                                Optimization="2"\r
                                EnableIntrinsicFunctions="true"\r
-                               PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"\r
+                               PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;WIN32_LEAN_AND_MEAN;SUPPORTDIRECTX;SUPPORTD3D"\r
                                RuntimeLibrary="2"\r
                                EnableFunctionLevelLinking="true"\r
                                UsePrecompiledHeader="0"\r
                                WarningLevel="3"\r
                                DebugInformationFormat="3"\r
-                               DisableSpecificWarnings="4706;4127;4100;4055;4054;4244;4305;4702"\r
+                               DisableSpecificWarnings="4706;4127;4100;4055;4054;4244;4305;4702;4201;4611"\r
                        />\r
                        <Tool\r
                                Name="VCManagedResourceCompilerTool"\r
                        <File\r
                                RelativePath=".\bih.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\builddate.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cap_avi.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cap_ogg.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cd_shared.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cd_win.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_collision.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_demo.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_dyntexture.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_gecko.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_input.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_main.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_parse.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_particles.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_screen.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cl_video.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\clvm_cmds.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cmd.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\collision.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\common.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\console.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\csprogs.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\curves.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\cvar.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\dpvsimpledecode.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\filematch.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\fractalnoise.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\fs.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\ft2.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\gl_backend.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\gl_draw.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\gl_rmain.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\gl_rsurf.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\gl_textures.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\hmac.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\host.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\host_cmd.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\image.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\image_png.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\jpeg.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\keys.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\lhnet.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\libcurl.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\mathlib.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\matrixlib.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\mdfour.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\menu.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\meshqueue.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\model_alias.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\model_brush.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\model_shared.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\model_sprite.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\mvm_cmds.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\netconn.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\palette.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\polygon.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\portals.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\protocol.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\prvm_cmds.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\prvm_edict.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\prvm_exec.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\r_explosion.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\r_lightning.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\r_modules.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\r_shadow.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\r_sky.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\r_sprites.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sbar.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_main.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_mem.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_mix.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_modplug.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_ogg.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_wav.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\snd_win.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sv_demo.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sv_main.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sv_move.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sv_phys.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sv_user.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\svbsp.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\svvm_cmds.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sys_shared.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\sys_win.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\utf8lib.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\vid_shared.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\vid_wgl.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\view.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\wad.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\world.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                        <File\r
                                RelativePath=".\zone.c"\r
                                >\r
+                               <FileConfiguration\r
+                                       Name="Debug|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
+                               <FileConfiguration\r
+                                       Name="Release|Win32"\r
+                                       >\r
+                                       <Tool\r
+                                               Name="VCCLCompilerTool"\r
+                                               CompileAs="2"\r
+                                       />\r
+                               </FileConfiguration>\r
                        </File>\r
                </Filter>\r
                <Filter\r
index d132def1ccc33b0ef08e69c950541f823c97d5f9..515085a99c93902b2c15c5687731f840152b140d 100644 (file)
@@ -1,6 +1,13 @@
 
 #include "quakedef.h"
 #include "cl_collision.h"
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+extern LPDIRECT3DDEVICE9 vid_d3d9dev;
+extern D3DCAPS9 vid_d3d9caps;
+#endif
+
+#define MAX_RENDERTARGETS 4
 
 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
 cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0", "use glBegin(GL_TRIANGLES);glTexCoord2f();glVertex3f();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
@@ -102,6 +109,7 @@ typedef struct gltextureunit_s
        const r_meshbuffer_t *pointer_texcoord_vertexbuffer;
        size_t pointer_texcoord_offset;
 
+       rtexture_t *texture;
        int t2d, t3d, tcubemap, trectangle;
        int arrayenabled;
        int rgbscale, alphascale;
@@ -119,13 +127,16 @@ typedef struct gl_state_s
        int cullfaceenable;
        int blendfunc1;
        int blendfunc2;
-       int blend;
+       qboolean blend;
        GLboolean depthmask;
        int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
        int depthtest;
+       int depthfunc;
        float depthrange[2];
        float polygonoffset[2];
        int alphatest;
+       int alphafunc;
+       float alphafuncvalue;
        int scissortest;
        unsigned int unit;
        unsigned int clientunit;
@@ -135,6 +146,7 @@ typedef struct gl_state_s
        int lockrange_count;
        int vertexbufferobject;
        int elementbufferobject;
+       int framebufferobject;
        qboolean pointer_color_enabled;
 
        int pointer_vertex_components;
@@ -169,6 +181,15 @@ typedef struct gl_state_s
        memexpandablearray_t meshbufferarray;
 
        qboolean active;
+
+#ifdef SUPPORTD3D
+       rtexture_t *d3drt_depthtexture;
+       rtexture_t *d3drt_colortextures[MAX_RENDERTARGETS];
+       IDirect3DSurface9 *d3drt_depthsurface;
+       IDirect3DSurface9 *d3drt_colorsurfaces[MAX_RENDERTARGETS];
+       IDirect3DSurface9 *d3drt_backbufferdepthsurface;
+       IDirect3DSurface9 *d3drt_backbuffercolorsurface;
+#endif
 }
 gl_state_t;
 
@@ -241,10 +262,15 @@ void GL_VBOStats_f(void)
 
 static void GL_Backend_ResetState(void);
 
+static void R_Mesh_InitVertexDeclarations(void);
+static void R_Mesh_DestroyVertexDeclarations(void);
+
 static void gl_backend_start(void)
 {
        memset(&gl_state, 0, sizeof(gl_state));
 
+       R_Mesh_InitVertexDeclarations();
+
        gl_state.usevbo_staticvertex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
        gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && (gl_vbo.integer == 1 || gl_vbo.integer == 3)) || vid.forcevbo;
        gl_state.usevbo_dynamicvertex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer) || vid.forcevbo;
@@ -256,12 +282,54 @@ static void gl_backend_start(void)
        CHECKGLERROR
 
        GL_Backend_ResetState();
+
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               IDirect3DDevice9_GetDepthStencilSurface(vid_d3d9dev, &gl_state.d3drt_backbufferdepthsurface);
+               IDirect3DDevice9_GetRenderTarget(vid_d3d9dev, 0, &gl_state.d3drt_backbuffercolorsurface);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 }
 
 static void gl_backend_shutdown(void)
 {
        Con_DPrint("OpenGL Backend shutting down\n");
 
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               IDirect3DSurface9_Release(gl_state.d3drt_backbufferdepthsurface);
+               IDirect3DSurface9_Release(gl_state.d3drt_backbuffercolorsurface);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+
        if (gl_state.preparevertices_tempdata)
                Mem_Free(gl_state.preparevertices_tempdata);
        if (gl_state.preparevertices_dynamicvertexbuffer)
@@ -269,6 +337,8 @@ static void gl_backend_shutdown(void)
 
        Mem_ExpandableArray_FreeArray(&gl_state.meshbufferarray);
 
+       R_Mesh_DestroyVertexDeclarations();
+
        memset(&gl_state, 0, sizeof(gl_state));
 }
 
@@ -276,6 +346,49 @@ static void gl_backend_newmap(void)
 {
 }
 
+static void gl_backend_devicelost(void)
+{
+       int i, endindex;
+       r_meshbuffer_t *buffer;
+       endindex = Mem_ExpandableArray_IndexRange(&gl_state.meshbufferarray);
+       for (i = 0;i < endindex;i++)
+       {
+               buffer = (r_meshbuffer_t *) Mem_ExpandableArray_RecordAtIndex(&gl_state.meshbufferarray, i);
+               if (!buffer || !buffer->isdynamic)
+                       continue;
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       if (buffer->devicebuffer)
+                       {
+                               if (buffer->isindexbuffer)
+                                       IDirect3DIndexBuffer9_Release((IDirect3DIndexBuffer9*)buffer->devicebuffer);
+                               else
+                                       IDirect3DVertexBuffer9_Release((IDirect3DVertexBuffer9*)buffer->devicebuffer);
+                               buffer->devicebuffer = NULL;
+                       }
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
+       }
+}
+
+static void gl_backend_devicerestored(void)
+{
+}
+
 void gl_backend_init(void)
 {
        int i;
@@ -321,7 +434,7 @@ void gl_backend_init(void)
 
        Cmd_AddCommand("gl_vbostats", GL_VBOStats_f, "prints a list of all buffer objects (vertex data and triangle elements) and total video memory used by them");
 
-       R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap, NULL, NULL);
+       R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap, gl_backend_devicelost, gl_backend_devicerestored);
 }
 
 void GL_SetMirrorState(qboolean state);
@@ -402,10 +515,12 @@ void R_Viewport_InitOrtho(r_viewport_t *v, const matrix4x4_t *cameramatrix, int
        memset(m, 0, sizeof(m));
        m[0]  = 2/(right - left);
        m[5]  = 2/(top - bottom);
-       m[10] = -2/(zFar - zNear);
+//     m[10] = -2/(zFar - zNear);
+       m[10] = -1/(zFar - zNear);
        m[12] = - (right + left)/(right - left);
        m[13] = - (top + bottom)/(top - bottom);
-       m[14] = - (zFar + zNear)/(zFar - zNear);
+//     m[14] = - (zFar + zNear)/(zFar - zNear);
+       m[14] = -zNear/(zFar-zNear);
        m[15] = 1;
        v->screentodepth[0] = -farclip / (farclip - nearclip);
        v->screentodepth[1] = farclip * nearclip / (farclip - nearclip);
@@ -632,6 +747,24 @@ void R_Viewport_InitRectSideView(r_viewport_t *v, const matrix4x4_t *cameramatri
        Matrix4x4_Invert_Simple(&tempmatrix, &v->cameramatrix);
        Matrix4x4_Concat(&v->viewmatrix, &basematrix, &tempmatrix);
 
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL11:
+               break;
+       case RENDERPATH_D3D9:
+               m[5] *= -1;
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+
        if (nearplane)
                R_Viewport_ApplyNearClipPlaneFloatGL(v, m, nearplane[0], nearplane[1], nearplane[2], nearplane[3]);
 
@@ -643,9 +776,6 @@ void R_SetViewport(const r_viewport_t *v)
        float m[16];
        gl_viewport = *v;
 
-       CHECKGLERROR
-       qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
-
        // FIXME: v_flipped_state is evil, this probably breaks somewhere
        GL_SetMirrorState(v_flipped.integer && (v->type == R_VIEWPORTTYPE_PERSPECTIVE || v->type == R_VIEWPORTTYPE_PERSPECTIVE_INFINITEFARCLIP));
 
@@ -657,15 +787,39 @@ void R_SetViewport(const r_viewport_t *v)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+//             CHECKGLERROR
+//             qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
 //             break;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
+               CHECKGLERROR
+               qglViewport(v->x, v->y, v->width, v->height);CHECKGLERROR
                // Load the projection matrix into OpenGL
                qglMatrixMode(GL_PROJECTION);CHECKGLERROR
                Matrix4x4_ToArrayFloatGL(&gl_projectionmatrix, m);
                qglLoadMatrixf(m);CHECKGLERROR
                qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
                break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       D3DVIEWPORT9 d3dviewport;
+                       d3dviewport.X = gl_viewport.x;
+                       d3dviewport.Y = gl_viewport.y;
+                       d3dviewport.Width = gl_viewport.width;
+                       d3dviewport.Height = gl_viewport.height;
+                       d3dviewport.MinZ = gl_state.depthrange[0];
+                       d3dviewport.MaxZ = gl_state.depthrange[1];
+                       IDirect3DDevice9_SetViewport(vid_d3d9dev, &d3dviewport);
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
 
        // force an update of the derived matrices
@@ -684,8 +838,7 @@ static void GL_BindVBO(int bufferobject)
        {
                gl_state.vertexbufferobject = bufferobject;
                CHECKGLERROR
-               qglBindBufferARB(GL_ARRAY_BUFFER_ARB, bufferobject);
-               CHECKGLERROR
+               qglBindBufferARB(GL_ARRAY_BUFFER_ARB, bufferobject);CHECKGLERROR
        }
 }
 
@@ -695,17 +848,204 @@ static void GL_BindEBO(int bufferobject)
        {
                gl_state.elementbufferobject = bufferobject;
                CHECKGLERROR
-               qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, bufferobject);
-               CHECKGLERROR
+               qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, bufferobject);CHECKGLERROR
+       }
+}
+
+int R_Mesh_CreateFramebufferObject(rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
+{
+       int temp;
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (!vid.support.ext_framebuffer_object)
+                       return 0;
+               qglGenFramebuffersEXT(1, (GLuint*)&temp);CHECKGLERROR
+               R_Mesh_SetRenderTargets(temp, NULL, NULL, NULL, NULL, NULL);
+               if (depthtexture) qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, depthtexture->gltexturetypeenum, R_GetTexture(depthtexture), 0);CHECKGLERROR
+               if (colortexture) qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, colortexture->gltexturetypeenum, R_GetTexture(colortexture), 0);CHECKGLERROR
+               if (colortexture2) qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, colortexture2->gltexturetypeenum, R_GetTexture(colortexture2), 0);CHECKGLERROR
+               if (colortexture3) qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT2_EXT, colortexture3->gltexturetypeenum, R_GetTexture(colortexture3), 0);CHECKGLERROR
+               if (colortexture4) qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT3_EXT, colortexture4->gltexturetypeenum, R_GetTexture(colortexture4), 0);CHECKGLERROR
+               return temp;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               return 1;
+       }
+       return 0;
+}
+
+void R_Mesh_DestroyFramebufferObject(int fbo)
+{
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (fbo)
+                       qglDeleteFramebuffersEXT(1, (GLuint*)&fbo);
+               break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
+       }
+}
+
+void R_Mesh_ResetRenderTargets(void)
+{
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (gl_state.framebufferobject)
+               {
+                       gl_state.framebufferobject = 0;
+                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, gl_state.framebufferobject);
+               }
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               if (gl_state.framebufferobject)
+               {
+                       unsigned int i;
+                       gl_state.framebufferobject = 0;
+                       IDirect3DDevice9_SetDepthStencilSurface(vid_d3d9dev, gl_state.d3drt_backbufferdepthsurface);
+                       IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, 0, gl_state.d3drt_backbuffercolorsurface);
+                       gl_state.d3drt_depthsurface = NULL;
+                       for (i = 1;i < vid.maxdrawbuffers;i++)
+                       {
+                               if (gl_state.d3drt_colorsurfaces[i])
+                               {
+                                       gl_state.d3drt_colorsurfaces[i] = NULL;
+                                       IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, i, NULL);
+                               }
+                       }
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+}
+
+void R_Mesh_SetRenderTargets(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4)
+{
+       unsigned int i;
+       unsigned int j;
+       rtexture_t *textures[5];
+       Vector4Set(textures, colortexture, colortexture2, colortexture3, colortexture4);
+       textures[4] = depthtexture;
+       // unbind any matching textures immediately, otherwise D3D will complain about a bound texture being used as a render target
+       for (j = 0;j < 5;j++)
+               if (textures[j])
+                       for (i = 0;i < vid.teximageunits;i++)
+                               if (gl_state.units[i].texture == textures[j])
+                                       R_Mesh_TexBind(i, NULL);
+       // set up framebuffer object or render targets for the active rendering API
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (gl_state.framebufferobject != fbo)
+               {
+                       gl_state.framebufferobject = fbo;
+                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, gl_state.framebufferobject);
+               }
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               // set up the new render targets, a NULL depthtexture intentionally binds nothing
+               // TODO: optimize: keep surface pointer around in rtexture_t until texture is freed or lost
+               if (fbo)
+               {
+                       gl_state.framebufferobject = 1;
+                       gl_state.d3drt_depthtexture = depthtexture;
+                       if (gl_state.d3drt_depthtexture)
+                       {
+                               IDirect3DTexture9_GetSurfaceLevel((IDirect3DTexture9 *)gl_state.d3drt_depthtexture->d3dtexture, 0, &gl_state.d3drt_depthsurface);
+                               IDirect3DDevice9_SetDepthStencilSurface(vid_d3d9dev, gl_state.d3drt_depthsurface);
+                               IDirect3DSurface9_Release(gl_state.d3drt_depthsurface);
+                       }
+                       else
+                               IDirect3DDevice9_SetDepthStencilSurface(vid_d3d9dev, NULL);
+                       for (i = 0;i < vid.maxdrawbuffers;i++)
+                       {
+                               gl_state.d3drt_colortextures[i] = textures[i];
+                               if (gl_state.d3drt_colortextures[i])
+                               {
+                                       IDirect3DTexture9_GetSurfaceLevel((IDirect3DTexture9 *)gl_state.d3drt_colortextures[i]->d3dtexture, 0, &gl_state.d3drt_colorsurfaces[i]);
+                                       IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, i, gl_state.d3drt_colorsurfaces[i]);
+                                       IDirect3DSurface9_Release(gl_state.d3drt_colorsurfaces[i]);
+                               }
+                               else
+                                       IDirect3DDevice9_SetRenderTarget(vid_d3d9dev, i, NULL);
+                       }
+               }
+               else
+                       R_Mesh_ResetRenderTargets();
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
 }
 
+#ifdef SUPPORTD3D
+static int d3dcmpforglfunc(int f)
+{
+       switch(f)
+       {
+       case GL_NEVER: return D3DCMP_NEVER;
+       case GL_LESS: return D3DCMP_LESS;
+       case GL_EQUAL: return D3DCMP_EQUAL;
+       case GL_LEQUAL: return D3DCMP_LESSEQUAL;
+       case GL_GREATER: return D3DCMP_GREATER;
+       case GL_NOTEQUAL: return D3DCMP_NOTEQUAL;
+       case GL_GEQUAL: return D3DCMP_GREATEREQUAL;
+       case GL_ALWAYS: return D3DCMP_ALWAYS;
+       default: Con_DPrintf("Unknown GL_DepthFunc\n");return D3DCMP_ALWAYS;
+       }
+}
+
+static int d3dstencilopforglfunc(int f)
+{
+       switch(f)
+       {
+       case GL_KEEP: return D3DSTENCILOP_KEEP;
+       case GL_INCR: return D3DSTENCILOP_INCR; // note: GL_INCR is clamped, D3DSTENCILOP_INCR wraps
+       case GL_DECR: return D3DSTENCILOP_DECR; // note: GL_DECR is clamped, D3DSTENCILOP_DECR wraps
+       default: Con_DPrintf("Unknown GL_StencilFunc\n");return D3DSTENCILOP_KEEP;
+       }
+}
+#endif
+
+
 static void GL_Backend_ResetState(void)
 {
        unsigned int i;
        gl_state.active = true;
        gl_state.depthtest = true;
        gl_state.alphatest = false;
+       gl_state.alphafunc = GL_GEQUAL;
+       gl_state.alphafuncvalue = 0.5f;
        gl_state.blendfunc1 = GL_ONE;
        gl_state.blendfunc2 = GL_ZERO;
        gl_state.blend = false;
@@ -714,52 +1054,71 @@ static void GL_Backend_ResetState(void)
        gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
        gl_state.lockrange_first = 0;
        gl_state.lockrange_count = 0;
-       gl_state.cullface = v_flipped_state ? GL_BACK : GL_FRONT; // quake is backwards, this culls back faces
-       gl_state.cullfaceenable = true;
+       gl_state.cullface = GL_NONE;
+       gl_state.cullfaceenable = false;
        gl_state.polygonoffset[0] = 0;
        gl_state.polygonoffset[1] = 0;
+       gl_state.framebufferobject = 0;
+       gl_state.depthfunc = GL_LEQUAL;
 
-       CHECKGLERROR
-
-       qglColorMask(1, 1, 1, 1);
-       qglAlphaFunc(GL_GEQUAL, 0.5);CHECKGLERROR
-       qglDisable(GL_ALPHA_TEST);CHECKGLERROR
-       qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
-       qglDisable(GL_BLEND);CHECKGLERROR
-       qglCullFace(gl_state.cullface);CHECKGLERROR
-       qglEnable(GL_CULL_FACE);CHECKGLERROR
-       qglDepthFunc(GL_LEQUAL);CHECKGLERROR
-       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
-       qglDepthMask(gl_state.depthmask);CHECKGLERROR
-       qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
-
-       if (vid.support.arb_vertex_buffer_object)
+       switch(vid.renderpath)
        {
-               qglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-               qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
-       }
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_COLORWRITEENABLE, gl_state.colormask);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHATESTENABLE, gl_state.alphatest);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHAFUNC, d3dcmpforglfunc(gl_state.alphafunc));
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHAREF, (int)bound(0, gl_state.alphafuncvalue * 256.0f, 255));
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_NONE);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZFUNC, d3dcmpforglfunc(gl_state.depthfunc));
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZENABLE, gl_state.depthtest);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZWRITEENABLE, gl_state.depthmask);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SLOPESCALEDEPTHBIAS, gl_state.polygonoffset[0]);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DEPTHBIAS, gl_state.polygonoffset[1] * (1.0f / 16777216.0f));
+               }
+#endif
+               break;
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
 
-       if (vid.support.ext_framebuffer_object)
-       {
-               qglBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
-       }
+               qglColorMask(1, 1, 1, 1);CHECKGLERROR
+               qglAlphaFunc(gl_state.alphafunc, gl_state.alphafuncvalue);CHECKGLERROR
+               qglDisable(GL_ALPHA_TEST);CHECKGLERROR
+               qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
+               qglDisable(GL_BLEND);CHECKGLERROR
+               qglCullFace(gl_state.cullface);CHECKGLERROR
+               qglDisable(GL_CULL_FACE);CHECKGLERROR
+               qglDepthFunc(GL_LEQUAL);CHECKGLERROR
+               qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+               qglDepthMask(gl_state.depthmask);CHECKGLERROR
+               qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
+
+               if (vid.support.arb_vertex_buffer_object)
+               {
+                       qglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+                       qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+               }
 
-       qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
-       qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
+               if (vid.support.ext_framebuffer_object)
+               {
+                       qglBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
+                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+               }
 
-       qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
-       qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+               qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
+               qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
 
-       GL_Color(0, 0, 0, 0);
-       GL_Color(1, 1, 1, 1);
+               qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
+               qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+               qglColor4f(1, 1, 1, 1);CHECKGLERROR
 
-       gl_state.unit = MAX_TEXTUREUNITS;
-       gl_state.clientunit = MAX_TEXTUREUNITS;
-       switch(vid.renderpath)
-       {
-       case RENDERPATH_GL20:
-       case RENDERPATH_CGGL:
+               if (vid.support.ext_framebuffer_object)
+                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, gl_state.framebufferobject);
+
+               gl_state.unit = MAX_TEXTUREUNITS;
+               gl_state.clientunit = MAX_TEXTUREUNITS;
                for (i = 0;i < vid.teximageunits;i++)
                {
                        GL_ActiveTexture(i);
@@ -789,6 +1148,44 @@ static void GL_Backend_ResetState(void)
                break;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
+               CHECKGLERROR
+
+               qglColorMask(1, 1, 1, 1);CHECKGLERROR
+               qglAlphaFunc(gl_state.alphafunc, gl_state.alphafuncvalue);CHECKGLERROR
+               qglDisable(GL_ALPHA_TEST);CHECKGLERROR
+               qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
+               qglDisable(GL_BLEND);CHECKGLERROR
+               qglCullFace(gl_state.cullface);CHECKGLERROR
+               qglDisable(GL_CULL_FACE);CHECKGLERROR
+               qglDepthFunc(GL_LEQUAL);CHECKGLERROR
+               qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+               qglDepthMask(gl_state.depthmask);CHECKGLERROR
+               qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
+
+               if (vid.support.arb_vertex_buffer_object)
+               {
+                       qglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+                       qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+               }
+
+               if (vid.support.ext_framebuffer_object)
+               {
+                       qglBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
+                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+               }
+
+               qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
+               qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
+
+               qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
+               qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+               qglColor4f(1, 1, 1, 1);CHECKGLERROR
+
+               if (vid.support.ext_framebuffer_object)
+                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, gl_state.framebufferobject);
+
+               gl_state.unit = MAX_TEXTUREUNITS;
+               gl_state.clientunit = MAX_TEXTUREUNITS;
                for (i = 0;i < vid.texunits;i++)
                {
                        GL_ActiveTexture(i);
@@ -828,11 +1225,23 @@ void GL_ActiveTexture(unsigned int num)
        if (gl_state.unit != num)
        {
                gl_state.unit = num;
-               if (qglActiveTexture)
+               switch(vid.renderpath)
                {
-                       CHECKGLERROR
-                       qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
-                       CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       if (qglActiveTexture)
+                       {
+                               CHECKGLERROR
+                               qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
+                               CHECKGLERROR
+                       }
+                       break;
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
+                       break;
                }
        }
 }
@@ -842,11 +1251,23 @@ void GL_ClientActiveTexture(unsigned int num)
        if (gl_state.clientunit != num)
        {
                gl_state.clientunit = num;
-               if (qglActiveTexture)
+               switch(vid.renderpath)
                {
-                       CHECKGLERROR
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
-                       CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       if (qglActiveTexture)
+                       {
+                               CHECKGLERROR
+                               qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
+                               CHECKGLERROR
+                       }
+                       break;
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
+                       break;
                }
        }
 }
@@ -855,35 +1276,72 @@ void GL_BlendFunc(int blendfunc1, int blendfunc2)
 {
        if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
        {
-               CHECKGLERROR
-               qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
-               if (gl_state.blendfunc2 == GL_ZERO)
+               qboolean blendenable;
+               gl_state.blendfunc1 = blendfunc1;
+               gl_state.blendfunc2 = blendfunc2;
+               blendenable = (gl_state.blendfunc1 != GL_ONE || gl_state.blendfunc2 != GL_ZERO);
+               switch(vid.renderpath)
                {
-                       if (gl_state.blendfunc1 == GL_ONE)
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
+                       if (gl_state.blend != blendenable)
                        {
-                               if (gl_state.blend)
+                               gl_state.blend = blendenable;
+                               if (!gl_state.blend)
                                {
-                                       gl_state.blend = 0;
                                        qglDisable(GL_BLEND);CHECKGLERROR
                                }
-                       }
-                       else
-                       {
-                               if (!gl_state.blend)
+                               else
                                {
-                                       gl_state.blend = 1;
                                        qglEnable(GL_BLEND);CHECKGLERROR
                                }
                        }
-               }
-               else
-               {
-                       if (!gl_state.blend)
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
                        {
-                               gl_state.blend = 1;
-                               qglEnable(GL_BLEND);CHECKGLERROR
+                               int i;
+                               int glblendfunc[2];
+                               D3DBLEND d3dblendfunc[2];
+                               glblendfunc[0] = gl_state.blendfunc1;
+                               glblendfunc[1] = gl_state.blendfunc2;
+                               for (i = 0;i < 2;i++)
+                               {
+                                       switch(glblendfunc[i])
+                                       {
+                                       case GL_ZERO: d3dblendfunc[i] = D3DBLEND_ZERO;break;
+                                       case GL_ONE: d3dblendfunc[i] = D3DBLEND_ONE;break;
+                                       case GL_SRC_COLOR: d3dblendfunc[i] = D3DBLEND_SRCCOLOR;break;
+                                       case GL_ONE_MINUS_SRC_COLOR: d3dblendfunc[i] = D3DBLEND_INVSRCCOLOR;break;
+                                       case GL_SRC_ALPHA: d3dblendfunc[i] = D3DBLEND_SRCALPHA;break;
+                                       case GL_ONE_MINUS_SRC_ALPHA: d3dblendfunc[i] = D3DBLEND_INVSRCALPHA;break;
+                                       case GL_DST_ALPHA: d3dblendfunc[i] = D3DBLEND_DESTALPHA;break;
+                                       case GL_ONE_MINUS_DST_ALPHA: d3dblendfunc[i] = D3DBLEND_INVDESTALPHA;break;
+                                       case GL_DST_COLOR: d3dblendfunc[i] = D3DBLEND_DESTCOLOR;break;
+                                       case GL_ONE_MINUS_DST_COLOR: d3dblendfunc[i] = D3DBLEND_INVDESTCOLOR;break;
+                                       }
+                               }
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SRCBLEND, d3dblendfunc[0]);
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DESTBLEND, d3dblendfunc[1]);
+                               if (gl_state.blend != blendenable)
+                               {
+                                       gl_state.blend = blendenable;
+                                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHABLENDENABLE, gl_state.blend);
+                               }
                        }
-               }
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
 }
 
@@ -891,8 +1349,28 @@ void GL_DepthMask(int state)
 {
        if (gl_state.depthmask != state)
        {
-               CHECKGLERROR
-               qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
+               gl_state.depthmask = state;
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglDepthMask(gl_state.depthmask);CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZWRITEENABLE, gl_state.depthmask);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
 }
 
@@ -901,14 +1379,62 @@ void GL_DepthTest(int state)
        if (gl_state.depthtest != state)
        {
                gl_state.depthtest = state;
-               CHECKGLERROR
-               if (gl_state.depthtest)
+               switch(vid.renderpath)
                {
-                       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       if (gl_state.depthtest)
+                       {
+                               qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+                       }
+                       else
+                       {
+                               qglDisable(GL_DEPTH_TEST);CHECKGLERROR
+                       }
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZENABLE, gl_state.depthtest);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
-               else
+       }
+}
+
+void GL_DepthFunc(int state)
+{
+       if (gl_state.depthfunc != state)
+       {
+               gl_state.depthfunc = state;
+               switch(vid.renderpath)
                {
-                       qglDisable(GL_DEPTH_TEST);CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglDepthFunc(gl_state.depthfunc);CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ZFUNC, d3dcmpforglfunc(gl_state.depthfunc));
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
        }
 }
@@ -919,7 +1445,147 @@ void GL_DepthRange(float nearfrac, float farfrac)
        {
                gl_state.depthrange[0] = nearfrac;
                gl_state.depthrange[1] = farfrac;
-               qglDepthRange(nearfrac, farfrac);
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       qglDepthRange(gl_state.depthrange[0], gl_state.depthrange[1]);
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       {
+                               D3DVIEWPORT9 d3dviewport;
+                               d3dviewport.X = gl_viewport.x;
+                               d3dviewport.Y = gl_viewport.y;
+                               d3dviewport.Width = gl_viewport.width;
+                               d3dviewport.Height = gl_viewport.height;
+                               d3dviewport.MinZ = gl_state.depthrange[0];
+                               d3dviewport.MaxZ = gl_state.depthrange[1];
+                               IDirect3DDevice9_SetViewport(vid_d3d9dev, &d3dviewport);
+                       }
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
+       }
+}
+
+void R_SetStencilSeparate(qboolean enable, int writemask, int frontfail, int frontzfail, int frontzpass, int backfail, int backzfail, int backzpass, int frontcompare, int backcompare, int comparereference, int comparemask)
+{
+       switch (vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               if (enable)
+               {
+                       qglEnable(GL_STENCIL_TEST);CHECKGLERROR
+               }
+               else
+               {
+                       qglDisable(GL_STENCIL_TEST);CHECKGLERROR
+               }
+               if (vid.support.ati_separate_stencil)
+               {
+                       qglStencilMask(writemask);CHECKGLERROR
+                       qglStencilOpSeparate(GL_FRONT, frontfail, frontzfail, frontzpass);CHECKGLERROR
+                       qglStencilOpSeparate(GL_BACK, backfail, backzfail, backzpass);CHECKGLERROR
+                       qglStencilFuncSeparate(frontcompare, backcompare, comparereference, comparereference);CHECKGLERROR
+               }
+               else if (vid.support.ext_stencil_two_side)
+               {
+                       qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
+                       qglActiveStencilFaceEXT(GL_FRONT);CHECKGLERROR
+                       qglStencilMask(writemask);CHECKGLERROR
+                       qglStencilOp(frontfail, frontzfail, frontzpass);CHECKGLERROR
+                       qglStencilFunc(frontcompare, comparereference, comparemask);CHECKGLERROR
+                       qglActiveStencilFaceEXT(GL_BACK);CHECKGLERROR
+                       qglStencilMask(writemask);CHECKGLERROR
+                       qglStencilOp(backfail, backzfail, backzpass);CHECKGLERROR
+                       qglStencilFunc(backcompare, comparereference, comparemask);CHECKGLERROR
+               }
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_TWOSIDEDSTENCILMODE, true);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILENABLE, enable);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILWRITEMASK, writemask);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFAIL, d3dstencilopforglfunc(frontfail));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILZFAIL, d3dstencilopforglfunc(frontzfail));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILPASS, d3dstencilopforglfunc(frontzpass));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFUNC, frontcompare);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILFAIL, d3dstencilopforglfunc(backfail));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILZFAIL, d3dstencilopforglfunc(backzfail));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILPASS, d3dstencilopforglfunc(backzpass));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CCW_STENCILFUNC, backcompare);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILREF, comparereference);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILMASK, comparemask);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+}
+
+void R_SetStencil(qboolean enable, int writemask, int fail, int zfail, int zpass, int compare, int comparereference, int comparemask)
+{
+       switch (vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               if (enable)
+               {
+                       qglEnable(GL_STENCIL_TEST);CHECKGLERROR
+               }
+               else
+               {
+                       qglDisable(GL_STENCIL_TEST);CHECKGLERROR
+               }
+               if (vid.support.ext_stencil_two_side)
+               {
+                       qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
+               }
+               qglStencilMask(writemask);CHECKGLERROR
+               qglStencilOp(fail, zfail, zpass);CHECKGLERROR
+               qglStencilFunc(compare, comparereference, comparemask);CHECKGLERROR
+               CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               if (vid.support.ati_separate_stencil)
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_TWOSIDEDSTENCILMODE, true);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILENABLE, enable);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILWRITEMASK, writemask);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFAIL, d3dstencilopforglfunc(fail));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILZFAIL, d3dstencilopforglfunc(zfail));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILPASS, d3dstencilopforglfunc(zpass));
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILFUNC, compare);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILREF, comparereference);
+               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_STENCILMASK, comparemask);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
 }
 
@@ -929,27 +1595,66 @@ void GL_PolygonOffset(float planeoffset, float depthoffset)
        {
                gl_state.polygonoffset[0] = planeoffset;
                gl_state.polygonoffset[1] = depthoffset;
-               qglPolygonOffset(planeoffset, depthoffset);
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SLOPESCALEDEPTHBIAS, gl_state.polygonoffset[0]);
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_DEPTHBIAS, gl_state.polygonoffset[1] * (1.0f / 16777216.0f));
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
 }
 
 void GL_SetMirrorState(qboolean state)
 {
-       if(!state != !v_flipped_state)
+       if (v_flipped_state != state)
        {
-               // change cull face mode!
-               if(gl_state.cullface == GL_BACK)
-                       qglCullFace((gl_state.cullface = GL_FRONT));
-               else if(gl_state.cullface == GL_FRONT)
-                       qglCullFace((gl_state.cullface = GL_BACK));
+               v_flipped_state = state;
+               if (gl_state.cullface == GL_BACK)
+                       gl_state.cullface = GL_FRONT;
+               else if (gl_state.cullface == GL_FRONT)
+                       gl_state.cullface = GL_BACK;
+               else
+                       return;
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       qglCullFace(gl_state.cullface);
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, gl_state.cullface == GL_FRONT ? D3DCULL_CCW : D3DCULL_CW);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
-       v_flipped_state = state;
 }
 
 void GL_CullFace(int state)
 {
-       CHECKGLERROR
-
        if(v_flipped_state)
        {
                if(state == GL_FRONT)
@@ -958,26 +1663,65 @@ void GL_CullFace(int state)
                        state = GL_FRONT;
        }
 
-       if (state != GL_NONE)
+       switch(vid.renderpath)
        {
-               if (!gl_state.cullfaceenable)
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+
+               if (state != GL_NONE)
                {
-                       gl_state.cullfaceenable = true;
-                       qglEnable(GL_CULL_FACE);CHECKGLERROR
+                       if (!gl_state.cullfaceenable)
+                       {
+                               gl_state.cullfaceenable = true;
+                               qglEnable(GL_CULL_FACE);CHECKGLERROR
+                       }
+                       if (gl_state.cullface != state)
+                       {
+                               gl_state.cullface = state;
+                               qglCullFace(gl_state.cullface);CHECKGLERROR
+                       }
                }
-               if (gl_state.cullface != state)
+               else
                {
-                       gl_state.cullface = state;
-                       qglCullFace(gl_state.cullface);CHECKGLERROR
+                       if (gl_state.cullfaceenable)
+                       {
+                               gl_state.cullfaceenable = false;
+                               qglDisable(GL_CULL_FACE);CHECKGLERROR
+                       }
                }
-       }
-       else
-       {
-               if (gl_state.cullfaceenable)
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               if (gl_state.cullface != state)
                {
-                       gl_state.cullfaceenable = false;
-                       qglDisable(GL_CULL_FACE);CHECKGLERROR
+                       gl_state.cullface = state;
+                       switch(gl_state.cullface)
+                       {
+                       case GL_NONE:
+                               gl_state.cullfaceenable = false;
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_NONE);
+                               break;
+                       case GL_FRONT:
+                               gl_state.cullfaceenable = true;
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_CCW);
+                               break;
+                       case GL_BACK:
+                               gl_state.cullfaceenable = true;
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_CULLMODE, D3DCULL_CW);
+                               break;
+                       }
                }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
 }
 
@@ -986,26 +1730,96 @@ void GL_AlphaTest(int state)
        if (gl_state.alphatest != state)
        {
                gl_state.alphatest = state;
-               CHECKGLERROR
-               if (gl_state.alphatest)
+               switch(vid.renderpath)
                {
-                       qglEnable(GL_ALPHA_TEST);CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       if (gl_state.alphatest)
+                       {
+                               qglEnable(GL_ALPHA_TEST);CHECKGLERROR
+                       }
+                       else
+                       {
+                               qglDisable(GL_ALPHA_TEST);CHECKGLERROR
+                       }
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHATESTENABLE, gl_state.alphatest);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
-               else
+       }
+}
+
+void GL_AlphaFunc(int state, float value)
+{
+       if (gl_state.alphafunc != state || gl_state.alphafuncvalue != value)
+       {
+               gl_state.alphafunc = state;
+               gl_state.alphafuncvalue = value;
+               switch(vid.renderpath)
                {
-                       qglDisable(GL_ALPHA_TEST);CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglAlphaFunc(gl_state.alphafunc, gl_state.alphafuncvalue);CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHAFUNC, d3dcmpforglfunc(gl_state.alphafunc));
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_ALPHAREF, (int)bound(0, value * 256.0f, 255));
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
        }
 }
 
 void GL_ColorMask(int r, int g, int b, int a)
 {
-       int state = r*8 + g*4 + b*2 + a*1;
+       // NOTE: this matches D3DCOLORWRITEENABLE_RED, GREEN, BLUE, ALPHA
+       int state = (r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0);
        if (gl_state.colormask != state)
        {
                gl_state.colormask = state;
-               CHECKGLERROR
-               qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_COLORWRITEENABLE, state);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
 }
 
@@ -1017,43 +1831,197 @@ void GL_Color(float cr, float cg, float cb, float ca)
                gl_state.color4f[1] = cg;
                gl_state.color4f[2] = cb;
                gl_state.color4f[3] = ca;
-               CHECKGLERROR
-               qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
-               CHECKGLERROR
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
+                       CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
+                       // no equivalent in D3D
+                       break;
+               }
        }
 }
 
 void GL_Scissor (int x, int y, int width, int height)
 {
-       CHECKGLERROR
-       qglScissor(x, y,width,height);
-       CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               qglScissor(x, y,width,height);
+               CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       RECT d3drect;
+                       d3drect.left = x;
+                       d3drect.top = y;
+                       d3drect.right = x + width;
+                       d3drect.bottom = y + height;
+                       IDirect3DDevice9_SetScissorRect(vid_d3d9dev, &d3drect);
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 }
 
 void GL_ScissorTest(int state)
 {
-       if(gl_state.scissortest == state)
-               return;
+       if (gl_state.scissortest != state)
+       {
+               gl_state.scissortest = state;
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       if(gl_state.scissortest)
+                               qglEnable(GL_SCISSOR_TEST);
+                       else
+                               qglDisable(GL_SCISSOR_TEST);
+                       CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_SCISSORTESTENABLE, gl_state.scissortest);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
+       }
+}
 
-       CHECKGLERROR
-       if((gl_state.scissortest = state))
-               qglEnable(GL_SCISSOR_TEST);
-       else
-               qglDisable(GL_SCISSOR_TEST);
-       CHECKGLERROR
+void GL_Clear(int mask, const float *colorvalue, float depthvalue, int stencilvalue)
+{
+       static const float blackcolor[4] = {0, 0, 0, 0};
+       // prevent warnings when trying to clear a buffer that does not exist
+       if (!colorvalue)
+               colorvalue = blackcolor;
+       if (!vid.stencil)
+       {
+               mask &= ~GL_STENCIL_BUFFER_BIT;
+               stencilvalue = 0;
+       }
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               if (mask & GL_COLOR_BUFFER_BIT)
+               {
+                       qglClearColor(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]);CHECKGLERROR
+               }
+               if (mask & GL_DEPTH_BUFFER_BIT)
+               {
+                       qglClearDepth(depthvalue);CHECKGLERROR
+               }
+               if (mask & GL_STENCIL_BUFFER_BIT)
+               {
+                       qglClearStencil(stencilvalue);CHECKGLERROR
+               }
+               qglClear(mask);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, ((mask & GL_COLOR_BUFFER_BIT) ? D3DCLEAR_TARGET : 0) | ((mask & GL_STENCIL_BUFFER_BIT) ? D3DCLEAR_STENCIL : 0) | ((mask & GL_DEPTH_BUFFER_BIT) ? D3DCLEAR_ZBUFFER : 0), D3DCOLOR_COLORVALUE(colorvalue[0], colorvalue[1], colorvalue[2], colorvalue[3]), depthvalue, stencilvalue);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 }
 
-void GL_Clear(int mask)
+void GL_ReadPixelsBGRA(int x, int y, int width, int height, unsigned char *outpixels)
 {
-       CHECKGLERROR
-       qglClear(mask);CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               qglReadPixels(x, y, width, height, GL_BGRA, GL_UNSIGNED_BYTE, outpixels);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       // LordHavoc: we can't directly download the backbuffer because it may be
+                       // multisampled, and it may not be lockable, so we blit it to a lockable
+                       // surface of the same dimensions (but without multisample) to resolve the
+                       // multisample buffer to a normal image, and then lock that...
+                       IDirect3DSurface9 *stretchsurface = NULL;
+                       if (!FAILED(IDirect3DDevice9_CreateRenderTarget(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, TRUE, &stretchsurface, NULL)))
+                       {
+                               D3DLOCKED_RECT lockedrect;
+                               if (!FAILED(IDirect3DDevice9_StretchRect(vid_d3d9dev, gl_state.d3drt_backbuffercolorsurface, NULL, stretchsurface, NULL, D3DTEXF_POINT)))
+                               {
+                                       if (!FAILED(IDirect3DSurface9_LockRect(stretchsurface, &lockedrect, NULL, D3DLOCK_READONLY)))
+                                       {
+                                               int line;
+                                               unsigned char *row = (unsigned char *)lockedrect.pBits + x * 4 + lockedrect.Pitch * (vid.height - 1 - y);
+                                               for (line = 0;line < height;line++, row -= lockedrect.Pitch)
+                                                       memcpy(outpixels + line * width * 4, row, width * 4);
+                                               IDirect3DSurface9_UnlockRect(stretchsurface);
+                                       }
+                               }
+                               IDirect3DSurface9_Release(stretchsurface);
+                       }
+                       // code scraps
+                       //IDirect3DSurface9 *syssurface = NULL;
+                       //if (!FAILED(IDirect3DDevice9_CreateRenderTarget(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, FALSE, &stretchsurface, NULL)))
+                       //if (!FAILED(IDirect3DDevice9_CreateOffscreenPlainSurface(vid_d3d9dev, vid.width, vid.height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &syssurface, NULL)))
+                       //IDirect3DDevice9_GetRenderTargetData(vid_d3d9dev, gl_state.d3drt_backbuffercolorsurface, syssurface);
+                       //if (!FAILED(IDirect3DDevice9_GetFrontBufferData(vid_d3d9dev, 0, syssurface)))
+                       //if (!FAILED(IDirect3DSurface9_LockRect(syssurface, &lockedrect, NULL, D3DLOCK_READONLY)))
+                       //IDirect3DSurface9_UnlockRect(syssurface);
+                       //IDirect3DSurface9_Release(syssurface);
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 }
 
 // called at beginning of frame
 void R_Mesh_Start(void)
 {
        BACKENDACTIVECHECK
-       CHECKGLERROR
        gl_state.usevbo_staticvertex = (vid.support.arb_vertex_buffer_object && gl_vbo.integer) || vid.forcevbo;
        gl_state.usevbo_staticindex = (vid.support.arb_vertex_buffer_object && (gl_vbo.integer == 1 || gl_vbo.integer == 3)) || vid.forcevbo;
        gl_state.usevbo_dynamicvertex = (vid.support.arb_vertex_buffer_object && gl_vbo_dynamicvertex.integer) || vid.forcevbo;
@@ -1176,11 +2144,6 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtri
                        Con_DPrintf("R_Mesh_Draw(%d, %d, %d, %d, %8p, %8p, %8x, %8p, %8p, %8x);\n", firstvertex, numvertices, firsttriangle, numtriangles, (void *)element3i, (void *)element3i_indexbuffer, (int)element3i_bufferoffset, (void *)element3s, (void *)element3s_indexbuffer, (int)element3s_bufferoffset);
                return;
        }
-       if (gl_state.pointer_vertex_pointer == NULL)
-       {
-               Con_DPrintf("R_Mesh_Draw with no vertex pointer!\n");
-               return;
-       }
        if (!gl_mesh_prefer_short_elements.integer)
        {
                if (element3i)
@@ -1211,7 +2174,7 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtri
                        if (gl_state.draw_dynamicindexbuffer)
                                R_Mesh_UpdateMeshBuffer(gl_state.draw_dynamicindexbuffer, (void *)element3s, numelements * sizeof(*element3s));
                        else
-                               gl_state.draw_dynamicindexbuffer = R_Mesh_CreateMeshBuffer((void *)element3s, numelements * sizeof(*element3s), "temporary", true, true);
+                               gl_state.draw_dynamicindexbuffer = R_Mesh_CreateMeshBuffer((void *)element3s, numelements * sizeof(*element3s), "temporary", true, true, true);
                        element3s_indexbuffer = gl_state.draw_dynamicindexbuffer;
                        element3s_bufferoffset = 0;
                }
@@ -1223,7 +2186,7 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtri
                        if (gl_state.draw_dynamicindexbuffer)
                                R_Mesh_UpdateMeshBuffer(gl_state.draw_dynamicindexbuffer, (void *)element3i, numelements * sizeof(*element3i));
                        else
-                               gl_state.draw_dynamicindexbuffer = R_Mesh_CreateMeshBuffer((void *)element3i, numelements * sizeof(*element3i), "temporary", true, true);
+                               gl_state.draw_dynamicindexbuffer = R_Mesh_CreateMeshBuffer((void *)element3i, numelements * sizeof(*element3i), "temporary", true, true, false);
                        element3i_indexbuffer = gl_state.draw_dynamicindexbuffer;
                        element3i_bufferoffset = 0;
                }
@@ -1232,7 +2195,6 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtri
        bufferoffset3i = element3i_bufferoffset;
        bufferobject3s = element3s_indexbuffer ? element3s_indexbuffer->bufferobject : 0;
        bufferoffset3s = element3s_bufferoffset;
-       CHECKGLERROR
        r_refdef.stats.meshes++;
        r_refdef.stats.meshes_elements += numelements;
        if (gl_paranoid.integer)
@@ -1298,195 +2260,226 @@ void R_Mesh_Draw(int firstvertex, int numvertices, int firsttriangle, int numtri
                                }
                        }
                }
-               CHECKGLERROR
        }
        if (r_render.integer || r_refdef.draw2dstage)
        {
-               CHECKGLERROR
-               if (gl_mesh_testmanualfeeding.integer)
+               switch(vid.renderpath)
                {
-                       unsigned int i, j, element;
-                       const GLfloat *p;
-                       qglBegin(GL_TRIANGLES);
-                       for (i = 0;i < (unsigned int) numtriangles * 3;i++)
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       if (gl_mesh_testmanualfeeding.integer)
                        {
-                               if (element3i)
-                                       element = element3i[i];
-                               else if (element3s)
-                                       element = element3s[i];
-                               else
-                                       element = firstvertex + i;
-                               for (j = 0;j < vid.texarrayunits;j++)
+                               unsigned int i, j, element;
+                               const GLfloat *p;
+                               qglBegin(GL_TRIANGLES);
+                               for (i = 0;i < (unsigned int) numtriangles * 3;i++)
                                {
-                                       if (gl_state.units[j].pointer_texcoord_pointer && gl_state.units[j].arrayenabled)
+                                       if (element3i)
+                                               element = element3i[i];
+                                       else if (element3s)
+                                               element = element3s[i];
+                                       else
+                                               element = firstvertex + i;
+                                       for (j = 0;j < vid.texarrayunits;j++)
                                        {
-                                               if (gl_state.units[j].pointer_texcoord_gltype == GL_FLOAT)
+                                               if (gl_state.units[j].pointer_texcoord_pointer && gl_state.units[j].arrayenabled)
                                                {
-                                                       p = (const GLfloat *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
-                                                       if (vid.texarrayunits > 1)
+                                                       if (gl_state.units[j].pointer_texcoord_gltype == GL_FLOAT)
                                                        {
-                                                               if (gl_state.units[j].pointer_texcoord_components == 4)
-                                                                       qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 3)
-                                                                       qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 2)
-                                                                       qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
+                                                               p = (const GLfloat *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
+                                                               if (vid.texarrayunits > 1)
+                                                               {
+                                                                       if (gl_state.units[j].pointer_texcoord_components == 4)
+                                                                               qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 3)
+                                                                               qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 2)
+                                                                               qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
+                                                                       else
+                                                                               qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
+                                                               }
                                                                else
-                                                                       qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
+                                                               {
+                                                                       if (gl_state.units[j].pointer_texcoord_components == 4)
+                                                                               qglTexCoord4f(p[0], p[1], p[2], p[3]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 3)
+                                                                               qglTexCoord3f(p[0], p[1], p[2]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 2)
+                                                                               qglTexCoord2f(p[0], p[1]);
+                                                                       else
+                                                                               qglTexCoord1f(p[0]);
+                                                               }
                                                        }
-                                                       else
+                                                       else if (gl_state.units[j].pointer_texcoord_gltype == GL_SHORT)
                                                        {
-                                                               if (gl_state.units[j].pointer_texcoord_components == 4)
-                                                                       qglTexCoord4f(p[0], p[1], p[2], p[3]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 3)
-                                                                       qglTexCoord3f(p[0], p[1], p[2]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 2)
-                                                                       qglTexCoord2f(p[0], p[1]);
+                                                               const GLshort *s = (const GLshort *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
+                                                               if (vid.texarrayunits > 1)
+                                                               {
+                                                                       if (gl_state.units[j].pointer_texcoord_components == 4)
+                                                                               qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, s[0], s[1], s[2], s[3]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 3)
+                                                                               qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, s[0], s[1], s[2]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 2)
+                                                                               qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, s[0], s[1]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 1)
+                                                                               qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, s[0]);
+                                                               }
                                                                else
-                                                                       qglTexCoord1f(p[0]);
-                                                       }
-                                               }
-                                               else if (gl_state.units[j].pointer_texcoord_gltype == GL_SHORT)
-                                               {
-                                                       const GLshort *s = (const GLshort *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
-                                                       if (vid.texarrayunits > 1)
-                                                       {
-                                                               if (gl_state.units[j].pointer_texcoord_components == 4)
-                                                                       qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, s[0], s[1], s[2], s[3]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 3)
-                                                                       qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, s[0], s[1], s[2]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 2)
-                                                                       qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, s[0], s[1]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 1)
-                                                                       qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, s[0]);
-                                                       }
-                                                       else
-                                                       {
-                                                               if (gl_state.units[j].pointer_texcoord_components == 4)
-                                                                       qglTexCoord4f(s[0], s[1], s[2], s[3]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 3)
-                                                                       qglTexCoord3f(s[0], s[1], s[2]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 2)
-                                                                       qglTexCoord2f(s[0], s[1]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 1)
-                                                                       qglTexCoord1f(s[0]);
-                                                       }
-                                               }
-                                               else if (gl_state.units[j].pointer_texcoord_gltype == GL_BYTE)
-                                               {
-                                                       const GLbyte *sb = (const GLbyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
-                                                       if (vid.texarrayunits > 1)
-                                                       {
-                                                               if (gl_state.units[j].pointer_texcoord_components == 4)
-                                                                       qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, sb[0], sb[1], sb[2], sb[3]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 3)
-                                                                       qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, sb[0], sb[1], sb[2]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 2)
-                                                                       qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, sb[0], sb[1]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 1)
-                                                                       qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, sb[0]);
+                                                               {
+                                                                       if (gl_state.units[j].pointer_texcoord_components == 4)
+                                                                               qglTexCoord4f(s[0], s[1], s[2], s[3]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 3)
+                                                                               qglTexCoord3f(s[0], s[1], s[2]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 2)
+                                                                               qglTexCoord2f(s[0], s[1]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 1)
+                                                                               qglTexCoord1f(s[0]);
+                                                               }
                                                        }
-                                                       else
+                                                       else if (gl_state.units[j].pointer_texcoord_gltype == GL_BYTE)
                                                        {
-                                                               if (gl_state.units[j].pointer_texcoord_components == 4)
-                                                                       qglTexCoord4f(sb[0], sb[1], sb[2], sb[3]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 3)
-                                                                       qglTexCoord3f(sb[0], sb[1], sb[2]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 2)
-                                                                       qglTexCoord2f(sb[0], sb[1]);
-                                                               else if (gl_state.units[j].pointer_texcoord_components == 1)
-                                                                       qglTexCoord1f(sb[0]);
+                                                               const GLbyte *sb = (const GLbyte *)((const unsigned char *)gl_state.units[j].pointer_texcoord_pointer + element * gl_state.units[j].pointer_texcoord_stride);
+                                                               if (vid.texarrayunits > 1)
+                                                               {
+                                                                       if (gl_state.units[j].pointer_texcoord_components == 4)
+                                                                               qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, sb[0], sb[1], sb[2], sb[3]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 3)
+                                                                               qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, sb[0], sb[1], sb[2]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 2)
+                                                                               qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, sb[0], sb[1]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 1)
+                                                                               qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, sb[0]);
+                                                               }
+                                                               else
+                                                               {
+                                                                       if (gl_state.units[j].pointer_texcoord_components == 4)
+                                                                               qglTexCoord4f(sb[0], sb[1], sb[2], sb[3]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 3)
+                                                                               qglTexCoord3f(sb[0], sb[1], sb[2]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 2)
+                                                                               qglTexCoord2f(sb[0], sb[1]);
+                                                                       else if (gl_state.units[j].pointer_texcoord_components == 1)
+                                                                               qglTexCoord1f(sb[0]);
+                                                               }
                                                        }
                                                }
                                        }
-                               }
-                               if (gl_state.pointer_color_pointer && gl_state.pointer_color_enabled && gl_state.pointer_color_components == 4)
-                               {
-                                       if (gl_state.pointer_color_gltype == GL_FLOAT)
+                                       if (gl_state.pointer_color_pointer && gl_state.pointer_color_enabled && gl_state.pointer_color_components == 4)
                                        {
-                                               p = (const GLfloat *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
-                                               qglColor4f(p[0], p[1], p[2], p[3]);
+                                               if (gl_state.pointer_color_gltype == GL_FLOAT)
+                                               {
+                                                       p = (const GLfloat *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
+                                                       qglColor4f(p[0], p[1], p[2], p[3]);
+                                               }
+                                               else if (gl_state.pointer_color_gltype == GL_UNSIGNED_BYTE)
+                                               {
+                                                       const GLubyte *ub = (const GLubyte *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
+                                                       qglColor4ub(ub[0], ub[1], ub[2], ub[3]);
+                                               }
                                        }
-                                       else if (gl_state.pointer_color_gltype == GL_UNSIGNED_BYTE)
+                                       if (gl_state.pointer_vertex_gltype == GL_FLOAT)
                                        {
-                                               const GLubyte *ub = (const GLubyte *)((const unsigned char *)gl_state.pointer_color_pointer + element * gl_state.pointer_color_stride);
-                                               qglColor4ub(ub[0], ub[1], ub[2], ub[3]);
+                                               p = (const GLfloat *)((const unsigned char *)gl_state.pointer_vertex_pointer + element * gl_state.pointer_vertex_stride);
+                                               if (gl_state.pointer_vertex_components == 4)
+                                                       qglVertex4f(p[0], p[1], p[2], p[3]);
+                                               else if (gl_state.pointer_vertex_components == 3)
+                                                       qglVertex3f(p[0], p[1], p[2]);
+                                               else
+                                                       qglVertex2f(p[0], p[1]);
                                        }
                                }
-                               if (gl_state.pointer_vertex_gltype == GL_FLOAT)
-                               {
-                                       p = (const GLfloat *)((const unsigned char *)gl_state.pointer_vertex_pointer + element * gl_state.pointer_vertex_stride);
-                                       if (gl_state.pointer_vertex_components == 4)
-                                               qglVertex4f(p[0], p[1], p[2], p[3]);
-                                       else if (gl_state.pointer_vertex_components == 3)
-                                               qglVertex3f(p[0], p[1], p[2]);
-                                       else
-                                               qglVertex2f(p[0], p[1]);
-                               }
-                       }
-                       qglEnd();
-                       CHECKGLERROR
-               }
-               else if (bufferobject3s)
-               {
-                       GL_BindEBO(bufferobject3s);
-                       if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
-                       {
-                               qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_SHORT, (void *)bufferoffset3s);
+                               qglEnd();
                                CHECKGLERROR
                        }
-                       else
+                       else if (bufferobject3s)
                        {
-                               qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, (void *)(firsttriangle * sizeof(unsigned short[3])));
-                               CHECKGLERROR
+                               GL_BindEBO(bufferobject3s);
+                               if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+                               {
+                                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_SHORT, (void *)bufferoffset3s);
+                                       CHECKGLERROR
+                               }
+                               else
+                               {
+                                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, (void *)(firsttriangle * sizeof(unsigned short[3])));
+                                       CHECKGLERROR
+                               }
                        }
-               }
-               else if (bufferobject3i)
-               {
-                       GL_BindEBO(bufferobject3i);
-                       if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+                       else if (bufferobject3i)
                        {
-                               qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_INT, (void *)bufferoffset3i);
-                               CHECKGLERROR
+                               GL_BindEBO(bufferobject3i);
+                               if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+                               {
+                                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_INT, (void *)bufferoffset3i);
+                                       CHECKGLERROR
+                               }
+                               else
+                               {
+                                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (void *)(firsttriangle * sizeof(unsigned int[3])));
+                                       CHECKGLERROR
+                               }
                        }
-                       else
+                       else if (element3s)
                        {
-                               qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, (void *)(firsttriangle * sizeof(unsigned int[3])));
-                               CHECKGLERROR
+                               GL_BindEBO(0);
+                               if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+                               {
+                                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_SHORT, element3s);
+                                       CHECKGLERROR
+                               }
+                               else
+                               {
+                                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, element3s);
+                                       CHECKGLERROR
+                               }
                        }
-               }
-               else if (element3s)
-               {
-                       GL_BindEBO(0);
-                       if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+                       else if (element3i)
                        {
-                               qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_SHORT, element3s);
-                               CHECKGLERROR
+                               GL_BindEBO(0);
+                               if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+                               {
+                                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_INT, element3i);
+                                       CHECKGLERROR
+                               }
+                               else
+                               {
+                                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, element3i);
+                                       CHECKGLERROR
+                               }
                        }
                        else
                        {
-                               qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_SHORT, element3s);
-                               CHECKGLERROR
-                       }
-               }
-               else if (element3i)
-               {
-                       GL_BindEBO(0);
-                       if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
-                       {
-                               qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices - 1, numelements, GL_UNSIGNED_INT, element3i);
+                               qglDrawArrays(GL_TRIANGLES, firstvertex, numvertices);
                                CHECKGLERROR
                        }
-                       else
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
                        {
-                               qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, element3i);
-                               CHECKGLERROR
+                               if (element3s_indexbuffer)
+                               {
+                                       IDirect3DDevice9_SetIndices(vid_d3d9dev, (IDirect3DIndexBuffer9 *)element3s_indexbuffer->devicebuffer);
+                                       IDirect3DDevice9_DrawIndexedPrimitive(vid_d3d9dev, D3DPT_TRIANGLELIST, 0, firstvertex, numvertices, element3s_bufferoffset>>1, numtriangles);
+                               }
+                               else if (element3i_indexbuffer)
+                               {
+                                       IDirect3DDevice9_SetIndices(vid_d3d9dev, (IDirect3DIndexBuffer9 *)element3i_indexbuffer->devicebuffer);
+                                       IDirect3DDevice9_DrawIndexedPrimitive(vid_d3d9dev, D3DPT_TRIANGLELIST, 0, firstvertex, numvertices, element3i_bufferoffset>>2, numtriangles);
+                               }
+                               else
+                                       IDirect3DDevice9_DrawPrimitive(vid_d3d9dev, D3DPT_TRIANGLELIST, firstvertex, numvertices);
                        }
-               }
-               else
-               {
-                       qglDrawArrays(GL_TRIANGLES, firstvertex, numvertices);
-                       CHECKGLERROR
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
        }
 }
@@ -1496,51 +2489,27 @@ void R_Mesh_Finish(void)
 {
 }
 
-r_meshbuffer_t *R_Mesh_CreateMeshBuffer(const void *data, size_t size, const char *name, qboolean isindexbuffer, qboolean isdynamic)
+r_meshbuffer_t *R_Mesh_CreateMeshBuffer(const void *data, size_t size, const char *name, qboolean isindexbuffer, qboolean isdynamic, qboolean isindex16)
 {
-       int bufferobject = 0;
-       void *devicebuffer = NULL;
        r_meshbuffer_t *buffer;
        if (!(isdynamic ? (isindexbuffer ? gl_state.usevbo_dynamicindex : gl_state.usevbo_dynamicvertex) : (isindexbuffer ? gl_state.usevbo_staticindex : gl_state.usevbo_staticvertex)))
                return NULL;
-       if (isindexbuffer)
-       {
-               r_refdef.stats.indexbufferuploadcount++;
-               r_refdef.stats.indexbufferuploadsize += size;
-       }
-       else
-       {
-               r_refdef.stats.vertexbufferuploadcount++;
-               r_refdef.stats.vertexbufferuploadsize += size;
-       }
-       switch(vid.renderpath)
-       {
-       case RENDERPATH_GL11:
-       case RENDERPATH_GL13:
-       case RENDERPATH_GL20:
-       case RENDERPATH_CGGL:
-               qglGenBuffersARB(1, (GLuint *)&bufferobject);
-               if (isindexbuffer)
-                       GL_BindEBO(bufferobject);
-               else
-                       GL_BindVBO(bufferobject);
-               qglBufferDataARB(isindexbuffer ? GL_ELEMENT_ARRAY_BUFFER_ARB : GL_ARRAY_BUFFER_ARB, size, data, isdynamic ? GL_STREAM_DRAW_ARB : GL_STATIC_DRAW_ARB);
-               break;
-       }
        buffer = (r_meshbuffer_t *)Mem_ExpandableArray_AllocRecord(&gl_state.meshbufferarray);
        memset(buffer, 0, sizeof(*buffer));
-       buffer->bufferobject = bufferobject;
-       buffer->devicebuffer = devicebuffer;
-       buffer->size = size;
+       buffer->bufferobject = 0;
+       buffer->devicebuffer = NULL;
+       buffer->size = 0;
        buffer->isindexbuffer = isindexbuffer;
        buffer->isdynamic = isdynamic;
+       buffer->isindex16 = isindex16;
        strlcpy(buffer->name, name, sizeof(buffer->name));
+       R_Mesh_UpdateMeshBuffer(buffer, data, size);
        return buffer;
 }
 
 void R_Mesh_UpdateMeshBuffer(r_meshbuffer_t *buffer, const void *data, size_t size)
 {
-       if (!buffer || (!buffer->bufferobject && !buffer->devicebuffer))
+       if (!buffer)
                return;
        if (buffer->isindexbuffer)
        {
@@ -1558,12 +2527,72 @@ void R_Mesh_UpdateMeshBuffer(r_meshbuffer_t *buffer, const void *data, size_t si
        case RENDERPATH_GL13:
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+               if (!buffer->bufferobject)
+                       qglGenBuffersARB(1, (GLuint *)&buffer->bufferobject);
                if (buffer->isindexbuffer)
                        GL_BindEBO(buffer->bufferobject);
                else
                        GL_BindVBO(buffer->bufferobject);
                qglBufferDataARB(buffer->isindexbuffer ? GL_ELEMENT_ARRAY_BUFFER_ARB : GL_ARRAY_BUFFER_ARB, size, data, buffer->isdynamic ? GL_STREAM_DRAW_ARB : GL_STATIC_DRAW_ARB);
                break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       int result;
+                       void *datapointer = NULL;
+                       if (buffer->isindexbuffer)
+                       {
+                               IDirect3DIndexBuffer9 *d3d9indexbuffer = (IDirect3DIndexBuffer9 *)buffer->devicebuffer;
+                               if (size != buffer->size || !buffer->devicebuffer)
+                               {
+                                       if (buffer->devicebuffer)
+                                               IDirect3DIndexBuffer9_Release((IDirect3DIndexBuffer9*)buffer->devicebuffer);
+                                       buffer->devicebuffer = NULL;
+                                       if (FAILED(result = IDirect3DDevice9_CreateIndexBuffer(vid_d3d9dev, size, buffer->isdynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : 0, buffer->isindex16 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, buffer->isdynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED, &d3d9indexbuffer, NULL)))
+                                               Sys_Error("IDirect3DDevice9_CreateIndexBuffer(%p, %d, %x, %x, %x, %p, NULL) returned %x\n", vid_d3d9dev, (int)size, buffer->isdynamic ? D3DUSAGE_DYNAMIC : 0, buffer->isindex16 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, buffer->isdynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED, &d3d9indexbuffer, result);
+                                       buffer->devicebuffer = (void *)d3d9indexbuffer;
+                                       buffer->size = size;
+                               }
+                               if (!FAILED(IDirect3DIndexBuffer9_Lock(d3d9indexbuffer, 0, 0, &datapointer, buffer->isdynamic ? D3DLOCK_DISCARD : 0)))
+                               {
+                                       if (data)
+                                               memcpy(datapointer, data, size);
+                                       else
+                                               memset(datapointer, 0, size);
+                                       IDirect3DIndexBuffer9_Unlock(d3d9indexbuffer);
+                               }
+                       }
+                       else
+                       {
+                               IDirect3DVertexBuffer9 *d3d9vertexbuffer = (IDirect3DVertexBuffer9 *)buffer->devicebuffer;
+                               if (size != buffer->size || !buffer->devicebuffer)
+                               {
+                                       if (buffer->devicebuffer)
+                                               IDirect3DVertexBuffer9_Release((IDirect3DVertexBuffer9*)buffer->devicebuffer);
+                                       buffer->devicebuffer = NULL;
+                                       if (FAILED(result = IDirect3DDevice9_CreateVertexBuffer(vid_d3d9dev, size, buffer->isdynamic ? D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC : 0, 0, buffer->isdynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED, &d3d9vertexbuffer, NULL)))
+                                               Sys_Error("IDirect3DDevice9_CreateVertexBuffer(%p, %d, %x, %x, %x, %p, NULL) returned %x\n", vid_d3d9dev, (int)size, buffer->isdynamic ? D3DUSAGE_DYNAMIC : 0, 0, buffer->isdynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED, &d3d9vertexbuffer, result);
+                                       buffer->devicebuffer = (void *)d3d9vertexbuffer;
+                                       buffer->size = size;
+                               }
+                               if (!FAILED(IDirect3DVertexBuffer9_Lock(d3d9vertexbuffer, 0, 0, &datapointer, buffer->isdynamic ? D3DLOCK_DISCARD : 0)))
+                               {
+                                       if (data)
+                                               memcpy(datapointer, data, size);
+                                       else
+                                               memset(datapointer, 0, size);
+                                       IDirect3DVertexBuffer9_Unlock(d3d9vertexbuffer);
+                               }
+                       }
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
 }
 
@@ -1579,6 +2608,23 @@ void R_Mesh_DestroyMeshBuffer(r_meshbuffer_t *buffer)
        case RENDERPATH_CGGL:
                qglDeleteBuffersARB(1, (GLuint *)&buffer->bufferobject);
                break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               if (buffer->devicebuffer)
+               {
+                       if (buffer->isindexbuffer)
+                               IDirect3DIndexBuffer9_Release((IDirect3DIndexBuffer9 *)buffer->devicebuffer);
+                       else
+                               IDirect3DVertexBuffer9_Release((IDirect3DVertexBuffer9 *)buffer->devicebuffer);
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
        Mem_ExpandableArray_FreeRecord(&gl_state.meshbufferarray, (void *)buffer);
 }
@@ -1722,23 +2768,76 @@ int R_Mesh_TexBound(unsigned int unitnum, int id)
 
 void R_Mesh_CopyToTexture(rtexture_t *tex, int tx, int ty, int sx, int sy, int width, int height)
 {
-       R_Mesh_TexBind(0, tex);
-       GL_ActiveTexture(0);CHECKGLERROR
-       qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, tx, ty, sx, sy, width, height);CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               R_Mesh_TexBind(0, tex);
+               GL_ActiveTexture(0);CHECKGLERROR
+               qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, tx, ty, sx, sy, width, height);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       IDirect3DSurface9 *currentsurface = NULL;
+                       IDirect3DSurface9 *texturesurface = NULL;
+                       RECT sourcerect;
+                       RECT destrect;
+                       sourcerect.left = sx;
+                       sourcerect.top = sy;
+                       sourcerect.right = sx + width;
+                       sourcerect.bottom = sy + height;
+                       destrect.left = tx;
+                       destrect.top = ty;
+                       destrect.right = tx + width;
+                       destrect.bottom = ty + height;
+                       if (!FAILED(IDirect3DTexture9_GetSurfaceLevel(((IDirect3DTexture9 *)tex->d3dtexture), 0, &texturesurface)))
+                       {
+                               if (!FAILED(IDirect3DDevice9_GetRenderTarget(vid_d3d9dev, 0, &currentsurface)))
+                               {
+                                       IDirect3DDevice9_StretchRect(vid_d3d9dev, currentsurface, &sourcerect, texturesurface, &destrect, D3DTEXF_NONE);
+                                       IDirect3DSurface9_Release(currentsurface);
+                               }
+                               IDirect3DSurface9_Release(texturesurface);
+                       }
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 }
 
+#ifdef SUPPORTD3D
+int d3drswrap[16] = {D3DRS_WRAP0, D3DRS_WRAP1, D3DRS_WRAP2, D3DRS_WRAP3, D3DRS_WRAP4, D3DRS_WRAP5, D3DRS_WRAP6, D3DRS_WRAP7, D3DRS_WRAP8, D3DRS_WRAP9, D3DRS_WRAP10, D3DRS_WRAP11, D3DRS_WRAP12, D3DRS_WRAP13, D3DRS_WRAP14, D3DRS_WRAP15};
+#endif
+
 void R_Mesh_TexBind(unsigned int unitnum, rtexture_t *tex)
 {
        gltextureunit_t *unit = gl_state.units + unitnum;
        int tex2d, tex3d, texcubemap, texnum;
        if (unitnum >= vid.teximageunits)
                return;
+//     if (unit->texture == tex)
+//             return;
        switch(vid.renderpath)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
                if (!tex)
+               {
                        tex = r_texture_white;
+                       // not initialized enough yet...
+                       if (!tex)
+                               return;
+               }
+               unit->texture = tex;
                texnum = R_GetTexture(tex);
                switch(tex->gltexturetypeenum)
                {
@@ -1750,6 +2849,7 @@ void R_Mesh_TexBind(unsigned int unitnum, rtexture_t *tex)
                break;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
+               unit->texture = tex;
                tex2d = 0;
                tex3d = 0;
                texcubemap = 0;
@@ -1833,41 +2933,91 @@ void R_Mesh_TexBind(unsigned int unitnum, rtexture_t *tex)
                        qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
                }
                break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       extern cvar_t gl_texture_anisotropy;
+                       if (!tex)
+                       {
+                               tex = r_texture_white;
+                               // not initialized enough yet...
+                               if (!tex)
+                                       return;
+                       }
+                       if (unit->texture == tex)
+                               return;
+                       unit->texture = tex;
+                       // upload texture if needed
+                       if (tex->dirty)
+                               R_RealGetTexture(tex);
+                       IDirect3DDevice9_SetTexture(vid_d3d9dev, unitnum, (IDirect3DBaseTexture9*)tex->d3dtexture);
+                       //IDirect3DDevice9_SetRenderState(vid_d3d9dev, d3drswrap[unitnum], (tex->flags & TEXF_CLAMP) ? (D3DWRAPCOORD_0 | D3DWRAPCOORD_1 | D3DWRAPCOORD_2) : 0);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_ADDRESSU, tex->d3daddressu);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_ADDRESSV, tex->d3daddressv);
+                       if (tex->d3daddressw)
+                               IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_ADDRESSW,  tex->d3daddressw);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_MAGFILTER, tex->d3dmagfilter);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_MINFILTER, tex->d3dminfilter);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_MIPFILTER, tex->d3dmipfilter);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_MIPMAPLODBIAS, tex->d3dmipmaplodbias);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_MAXMIPLEVEL, tex->d3dmaxmiplevelfilter);
+                       IDirect3DDevice9_SetSamplerState(vid_d3d9dev, unitnum, D3DSAMP_MAXANISOTROPY, gl_texture_anisotropy.integer);
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
 }
 
 void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
 {
        gltextureunit_t *unit = gl_state.units + unitnum;
-       if (matrix && matrix->m[3][3])
+       switch(vid.renderpath)
        {
-               // texmatrix specified, check if it is different
-               if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (matrix && matrix->m[3][3])
                {
-                       float glmatrix[16];
-                       unit->texmatrixenabled = true;
-                       unit->matrix = *matrix;
-                       CHECKGLERROR
-                       Matrix4x4_ToArrayFloatGL(&unit->matrix, glmatrix);
-                       GL_ActiveTexture(unitnum);
-                       qglMatrixMode(GL_TEXTURE);CHECKGLERROR
-                       qglLoadMatrixf(glmatrix);CHECKGLERROR
-                       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+                       // texmatrix specified, check if it is different
+                       if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
+                       {
+                               float glmatrix[16];
+                               unit->texmatrixenabled = true;
+                               unit->matrix = *matrix;
+                               CHECKGLERROR
+                               Matrix4x4_ToArrayFloatGL(&unit->matrix, glmatrix);
+                               GL_ActiveTexture(unitnum);
+                               qglMatrixMode(GL_TEXTURE);CHECKGLERROR
+                               qglLoadMatrixf(glmatrix);CHECKGLERROR
+                               qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+                       }
                }
-       }
-       else
-       {
-               // no texmatrix specified, revert to identity
-               if (unit->texmatrixenabled)
+               else
                {
-                       unit->texmatrixenabled = false;
-                       unit->matrix = identitymatrix;
-                       CHECKGLERROR
-                       GL_ActiveTexture(unitnum);
-                       qglMatrixMode(GL_TEXTURE);CHECKGLERROR
-                       qglLoadIdentity();CHECKGLERROR
-                       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+                       // no texmatrix specified, revert to identity
+                       if (unit->texmatrixenabled)
+                       {
+                               unit->texmatrixenabled = false;
+                               unit->matrix = identitymatrix;
+                               CHECKGLERROR
+                               GL_ActiveTexture(unitnum);
+                               qglMatrixMode(GL_TEXTURE);CHECKGLERROR
+                               qglLoadIdentity();CHECKGLERROR
+                               qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+                       }
                }
+               break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
        }
 }
 
@@ -1948,6 +3098,10 @@ void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, i
                        qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combine);CHECKGLERROR
                }
                break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
        }
 }
 
@@ -2072,11 +3226,89 @@ void R_Mesh_ResetTextureState(void)
                        }
                }
                break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
        }
 }
 
 
 
+#ifdef SUPPORTD3D
+//#define r_vertexposition_d3d9fvf (D3DFVF_XYZ)
+//#define r_vertexgeneric_d3d9fvf (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1)
+//#define r_vertexmesh_d3d9fvf (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX5 | D3DFVF_TEXCOORDSIZE1(3) | D3DFVF_TEXCOORDSIZE2(3) | D3DFVF_TEXCOORDSIZE3(3))
+
+D3DVERTEXELEMENT9 r_vertexposition_d3d9elements[] =
+{
+       {0, (int)((size_t)&((r_vertexposition_t *)0)->vertex3f), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
+       D3DDECL_END()
+};
+
+D3DVERTEXELEMENT9 r_vertexgeneric_d3d9elements[] =
+{
+       {0, (int)((size_t)&((r_vertexgeneric_t *)0)->vertex3f  ), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
+       {0, (int)((size_t)&((r_vertexgeneric_t *)0)->color4ub  ), D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0},
+       {0, (int)((size_t)&((r_vertexgeneric_t *)0)->texcoord2f), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
+       D3DDECL_END()
+};
+
+D3DVERTEXELEMENT9 r_vertexmesh_d3d9elements[] =
+{
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->vertex3f          ), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->color4ub          ), D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0},
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->texcoordtexture2f ), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->svector3f         ), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->tvector3f         ), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->normal3f          ), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
+       {0, (int)((size_t)&((r_vertexmesh_t *)0)->texcoordlightmap2f), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4},
+       D3DDECL_END()
+};
+
+IDirect3DVertexDeclaration9 *r_vertexposition_d3d9decl;
+IDirect3DVertexDeclaration9 *r_vertexgeneric_d3d9decl;
+IDirect3DVertexDeclaration9 *r_vertexmesh_d3d9decl;
+#endif
+
+static void R_Mesh_InitVertexDeclarations(void)
+{
+#ifdef SUPPORTD3D
+       r_vertexposition_d3d9decl = NULL;
+       r_vertexgeneric_d3d9decl = NULL;
+       r_vertexmesh_d3d9decl = NULL;
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_D3D9:
+               IDirect3DDevice9_CreateVertexDeclaration(vid_d3d9dev, r_vertexposition_d3d9elements, &r_vertexposition_d3d9decl);
+               IDirect3DDevice9_CreateVertexDeclaration(vid_d3d9dev, r_vertexgeneric_d3d9elements, &r_vertexgeneric_d3d9decl);
+               IDirect3DDevice9_CreateVertexDeclaration(vid_d3d9dev, r_vertexmesh_d3d9elements, &r_vertexmesh_d3d9decl);
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+#endif
+}
+
+static void R_Mesh_DestroyVertexDeclarations(void)
+{
+#ifdef SUPPORTD3D
+       if (r_vertexposition_d3d9decl)
+               IDirect3DVertexDeclaration9_Release(r_vertexposition_d3d9decl);
+       r_vertexposition_d3d9decl = NULL;
+       if (r_vertexgeneric_d3d9decl)
+               IDirect3DVertexDeclaration9_Release(r_vertexgeneric_d3d9decl);
+       r_vertexgeneric_d3d9decl = NULL;
+       if (r_vertexmesh_d3d9decl)
+               IDirect3DVertexDeclaration9_Release(r_vertexmesh_d3d9decl);
+       r_vertexmesh_d3d9decl = NULL;
+#endif
+}
+
 r_vertexposition_t *R_Mesh_PrepareVertices_Position_Lock(int numvertices)
 {
        size_t size;
@@ -2114,7 +3346,7 @@ void R_Mesh_PrepareVertices_Position_Arrays(int numvertices, const float *vertex
                R_Mesh_TexCoordPointer(2, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
                R_Mesh_TexCoordPointer(3, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
                R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
-               break;
+               return;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
                R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), vertex3f, NULL, 0);
@@ -2124,7 +3356,7 @@ void R_Mesh_PrepareVertices_Position_Arrays(int numvertices, const float *vertex
                        R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
                if (vid.texunits >= 3)
                        R_Mesh_TexCoordPointer(2, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
-               break;
+               return;
        }
 
        // no quick path for this case, convert to vertex structs
@@ -2145,7 +3377,7 @@ void R_Mesh_PrepareVertices_Position(int numvertices, const r_vertexposition_t *
                if (gl_state.preparevertices_dynamicvertexbuffer)
                        R_Mesh_UpdateMeshBuffer(gl_state.preparevertices_dynamicvertexbuffer, vertex, numvertices * sizeof(*vertex));
                else
-                       gl_state.preparevertices_dynamicvertexbuffer = R_Mesh_CreateMeshBuffer(vertex, numvertices * sizeof(*vertex), "temporary", false, true);
+                       gl_state.preparevertices_dynamicvertexbuffer = R_Mesh_CreateMeshBuffer(vertex, numvertices * sizeof(*vertex), "temporary", false, true, false);
                vertexbuffer = gl_state.preparevertices_dynamicvertexbuffer;
        }
        if (vertexbuffer)
@@ -2164,6 +3396,18 @@ void R_Mesh_PrepareVertices_Position(int numvertices, const r_vertexposition_t *
                        R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, NULL, 0);
                        R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, NULL, 0);
                        break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetVertexDeclaration(vid_d3d9dev, r_vertexposition_d3d9decl);
+                       IDirect3DDevice9_SetStreamSource(vid_d3d9dev, 0, (IDirect3DVertexBuffer9*)vertexbuffer->devicebuffer, 0, sizeof(*vertex));
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
                return;
        }
@@ -2282,7 +3526,7 @@ void R_Mesh_PrepareVertices_Generic(int numvertices, const r_vertexgeneric_t *ve
                if (gl_state.preparevertices_dynamicvertexbuffer)
                        R_Mesh_UpdateMeshBuffer(gl_state.preparevertices_dynamicvertexbuffer, vertex, numvertices * sizeof(*vertex));
                else
-                       gl_state.preparevertices_dynamicvertexbuffer = R_Mesh_CreateMeshBuffer(vertex, numvertices * sizeof(*vertex), "temporary", false, true);
+                       gl_state.preparevertices_dynamicvertexbuffer = R_Mesh_CreateMeshBuffer(vertex, numvertices * sizeof(*vertex), "temporary", false, true, false);
                vertexbuffer = gl_state.preparevertices_dynamicvertexbuffer;
        }
        if (vertexbuffer)
@@ -2301,6 +3545,18 @@ void R_Mesh_PrepareVertices_Generic(int numvertices, const r_vertexgeneric_t *ve
                        R_Mesh_ColorPointer(      4, GL_UNSIGNED_BYTE, sizeof(*vertex), vertex->color4ub          , vertexbuffer, (int)((unsigned char *)vertex->color4ub           - (unsigned char *)vertex));
                        R_Mesh_TexCoordPointer(0, 2, GL_FLOAT        , sizeof(*vertex), vertex->texcoord2f        , vertexbuffer, (int)((unsigned char *)vertex->texcoord2f         - (unsigned char *)vertex));
                        break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetVertexDeclaration(vid_d3d9dev, r_vertexgeneric_d3d9decl);
+                       IDirect3DDevice9_SetStreamSource(vid_d3d9dev, 0, (IDirect3DVertexBuffer9*)vertexbuffer->devicebuffer, 0, sizeof(*vertex));
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
                return;
        }
@@ -2430,7 +3686,7 @@ void R_Mesh_PrepareVertices_Mesh(int numvertices, const r_vertexmesh_t *vertex,
                if (gl_state.preparevertices_dynamicvertexbuffer)
                        R_Mesh_UpdateMeshBuffer(gl_state.preparevertices_dynamicvertexbuffer, vertex, numvertices * sizeof(*vertex));
                else
-                       gl_state.preparevertices_dynamicvertexbuffer = R_Mesh_CreateMeshBuffer(vertex, numvertices * sizeof(*vertex), "temporary", false, true);
+                       gl_state.preparevertices_dynamicvertexbuffer = R_Mesh_CreateMeshBuffer(vertex, numvertices * sizeof(*vertex), "temporary", false, true, false);
                vertexbuffer = gl_state.preparevertices_dynamicvertexbuffer;
        }
        if (vertexbuffer)
@@ -2454,6 +3710,18 @@ void R_Mesh_PrepareVertices_Mesh(int numvertices, const r_vertexmesh_t *vertex,
                        R_Mesh_ColorPointer(      4, GL_UNSIGNED_BYTE, sizeof(*vertex), vertex->color4ub          , vertexbuffer, (int)((unsigned char *)vertex->color4ub           - (unsigned char *)vertex));
                        R_Mesh_TexCoordPointer(0, 2, GL_FLOAT        , sizeof(*vertex), vertex->texcoordtexture2f , vertexbuffer, (int)((unsigned char *)vertex->texcoordtexture2f  - (unsigned char *)vertex));
                        break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetVertexDeclaration(vid_d3d9dev, r_vertexmesh_d3d9decl);
+                       IDirect3DDevice9_SetStreamSource(vid_d3d9dev, 0, (IDirect3DVertexBuffer9*)vertexbuffer->devicebuffer, 0, sizeof(*vertex));
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
                return;
        }
index 952cecd782c3df11f2ddc99a17ffaf73d8199aa1..aff9f4024feb8fd2796e6099f30393bd0d25a3f0 100644 (file)
@@ -31,17 +31,26 @@ void R_GetViewport(r_viewport_t *v);
 void GL_BlendFunc(int blendfunc1, int blendfunc2);
 void GL_DepthMask(int state);
 void GL_DepthTest(int state);
+void GL_DepthFunc(int state);
 void GL_DepthRange(float nearfrac, float farfrac);
+void R_SetStencilSeparate(qboolean enable, int writemask, int frontfail, int frontzfail, int frontzpass, int backfail, int backzfail, int backzpass, int frontcompare, int backcompare, int comparereference, int comparemask);
+void R_SetStencil(qboolean enable, int writemask, int fail, int zfail, int zpass, int compare, int comparereference, int comparemask);
 void GL_PolygonOffset(float planeoffset, float depthoffset);
 void GL_CullFace(int state);
 void GL_AlphaTest(int state);
+void GL_AlphaFunc(int state, float value);
 void GL_ColorMask(int r, int g, int b, int a);
 void GL_Color(float cr, float cg, float cb, float ca);
 void GL_ActiveTexture(unsigned int num);
 void GL_ClientActiveTexture(unsigned int num);
 void GL_Scissor(int x, int y, int width, int height);
 void GL_ScissorTest(int state);
-void GL_Clear(int mask);
+void GL_Clear(int mask, const float *colorvalue, float depthvalue, int stencilvalue);
+void GL_ReadPixelsBGRA(int x, int y, int width, int height, unsigned char *outpixels);
+int R_Mesh_CreateFramebufferObject(rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4);
+void R_Mesh_DestroyFramebufferObject(int fbo);
+void R_Mesh_ResetRenderTargets(void);
+void R_Mesh_SetRenderTargets(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture, rtexture_t *colortexture2, rtexture_t *colortexture3, rtexture_t *colortexture4);
 
 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int geometrystrings_count, const char **geometrystrings_list, int fragmentstrings_count, const char **fragmentstrings_list);
 void GL_Backend_FreeProgram(unsigned int prog);
@@ -61,7 +70,7 @@ void R_Mesh_Finish(void);
 
 
 // vertex buffer and index buffer creation/updating/freeing
-r_meshbuffer_t *R_Mesh_CreateMeshBuffer(const void *data, size_t size, const char *name, qboolean isindexbuffer, qboolean isdynamic);
+r_meshbuffer_t *R_Mesh_CreateMeshBuffer(const void *data, size_t size, const char *name, qboolean isindexbuffer, qboolean isdynamic, qboolean isindex16);
 void R_Mesh_UpdateMeshBuffer(r_meshbuffer_t *buffer, const void *data, size_t size);
 void R_Mesh_DestroyMeshBuffer(r_meshbuffer_t *buffer);
 void GL_Mesh_ListVBOs(qboolean printeach);
index 4fdee6f4d80f2bb58ed8c2eaf284c2177158f39e..63896464351f309bdaf617e87897d29af3d31d38 100644 (file)
--- a/gl_draw.c
+++ b/gl_draw.c
@@ -969,9 +969,9 @@ void _DrawQ_Setup(void)
        R_Viewport_InitOrtho(&viewport, &identitymatrix, r_refdef.view.x, vid.height - r_refdef.view.y - r_refdef.view.height, r_refdef.view.width, r_refdef.view.height, 0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100, NULL);
        R_SetViewport(&viewport);
        GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
-       qglDepthFunc(GL_LEQUAL);CHECKGLERROR
-       qglDisable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
-       GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
+       GL_DepthFunc(GL_LEQUAL);
+       GL_PolygonOffset(0,0);
+       GL_CullFace(GL_NONE);
        R_EntityMatrix(&identitymatrix);
 
        GL_DepthMask(true);
@@ -1839,16 +1839,33 @@ void DrawQ_LineLoop (drawqueuemesh_t *mesh, int flags)
                return;
 
        GL_Color(1,1,1,1);
-       CHECKGLERROR
-       qglBegin(GL_LINE_LOOP);
-       for (num = 0;num < mesh->num_vertices;num++)
+       switch(vid.renderpath)
        {
-               if (mesh->data_color4f)
-                       GL_Color(mesh->data_color4f[num*4+0], mesh->data_color4f[num*4+1], mesh->data_color4f[num*4+2], mesh->data_color4f[num*4+3]);
-               qglVertex2f(mesh->data_vertex3f[num*3+0], mesh->data_vertex3f[num*3+1]);
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               qglBegin(GL_LINE_LOOP);
+               for (num = 0;num < mesh->num_vertices;num++)
+               {
+                       if (mesh->data_color4f)
+                               GL_Color(mesh->data_color4f[num*4+0], mesh->data_color4f[num*4+1], mesh->data_color4f[num*4+2], mesh->data_color4f[num*4+3]);
+                       qglVertex2f(mesh->data_vertex3f[num*3+0], mesh->data_vertex3f[num*3+1]);
+               }
+               qglEnd();
+               CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+               //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
-       qglEnd();
-       CHECKGLERROR
 }
 
 //[515]: this is old, delete
@@ -1860,16 +1877,34 @@ void DrawQ_Line (float width, float x1, float y1, float x2, float y2, float r, f
 
        R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
 
-       CHECKGLERROR
-       //qglLineWidth(width);CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
 
-       GL_Color(r,g,b,alpha);
-       CHECKGLERROR
-       qglBegin(GL_LINES);
-       qglVertex2f(x1, y1);
-       qglVertex2f(x2, y2);
-       qglEnd();
-       CHECKGLERROR
+               //qglLineWidth(width);CHECKGLERROR
+
+               GL_Color(r,g,b,alpha);
+               CHECKGLERROR
+               qglBegin(GL_LINES);
+               qglVertex2f(x1, y1);
+               qglVertex2f(x2, y2);
+               qglEnd();
+               CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+               //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 }
 
 void DrawQ_SetClipArea(float x, float y, float width, float height)
@@ -1907,6 +1942,9 @@ void R_DrawGamma(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                if (vid_usinghwgamma || v_glslgamma.integer)
                        return;
                break;
index 6e3e34f18f57cb29abaaccd4ae5fabaa5d01340f..dec15bbc2b23b67a84209c97d5a8a4934c644ffe 100644 (file)
@@ -28,6 +28,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "csprogs.h"
 #include "cl_video.h"
 
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+extern LPDIRECT3DDEVICE9 vid_d3d9dev;
+#endif
+
 mempool_t *r_main_mempool;
 rtexturepool_t *r_main_texturepool;
 
@@ -253,6 +258,7 @@ static int r_qwskincache_size;
 
 /// vertex coordinates for a quad that covers the screen exactly
 extern const float r_screenvertex3f[12];
+extern const float r_d3dscreenvertex3f[12];
 const float r_screenvertex3f[12] =
 {
        0, 0, 0,
@@ -260,6 +266,13 @@ const float r_screenvertex3f[12] =
        1, 1, 0,
        0, 1, 0
 };
+const float r_d3dscreenvertex3f[12] =
+{
+       0, 1, 0,
+       1, 1, 0,
+       1, 0, 0,
+       0, 0, 0
+};
 
 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
 {
@@ -3314,6 +3327,7 @@ const char *builtincgshaderstring =
 
 char *glslshaderstring = NULL;
 char *cgshaderstring = NULL;
+char *hlslshaderstring = NULL;
 
 //=======================================================================================================================================================
 
@@ -3467,6 +3481,27 @@ shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
 };
 #endif
 
+#ifdef SUPPORTD3D
+shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
+{
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
+       {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
+};
+#endif
+
 struct r_glsl_permutation_s;
 typedef struct r_glsl_permutation_s
 {
@@ -3561,7 +3596,8 @@ typedef struct r_glsl_permutation_s
        int loc_ModelViewMatrix;
        int loc_PixelToScreenTexCoord;
        int loc_ModelToReflectCube;
-       int loc_ShadowMapMatrix;        
+       int loc_ShadowMapMatrix;
+       int loc_BloomColorSubtract;
 }
 r_glsl_permutation_t;
 
@@ -3788,7 +3824,8 @@ static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode
                p->loc_ModelViewProjectionMatrix  = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
                p->loc_PixelToScreenTexCoord      = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
                p->loc_ModelToReflectCube         = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
-               p->loc_ShadowMapMatrix            = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");            
+               p->loc_ShadowMapMatrix            = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
+               p->loc_BloomColorSubtract         = qglGetUniformLocationARB(p->program, "BloomColorSubtract");
                // initialize the samplers to refer to the texture units we use
                if (p->loc_Texture_First           >= 0) qglUniform1iARB(p->loc_Texture_First          , GL20TU_FIRST);
                if (p->loc_Texture_Second          >= 0) qglUniform1iARB(p->loc_Texture_Second         , GL20TU_SECOND);
@@ -3983,6 +4020,7 @@ typedef struct r_cg_permutation_s
        CGparameter fp_ViewToLight;
        CGparameter fp_PixelToScreenTexCoord;
        CGparameter fp_ModelToReflectCube;
+       CGparameter fp_BloomColorSubtract;
 }
 r_cg_permutation_t;
 
@@ -4282,6 +4320,7 @@ static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, un
                p->fp_ViewToLight                = cgGetNamedParameter(p->fprogram, "ViewToLight");
                p->fp_PixelToScreenTexCoord      = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
                p->fp_ModelToReflectCube         = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
+               p->fp_BloomColorSubtract         = cgGetNamedParameter(p->fprogram, "BloomColorSubtract");
                CHECKCGERROR
        }
 
@@ -4380,6 +4419,429 @@ void CG_BindTexture(CGparameter param, rtexture_t *tex)
 }
 #endif
 
+#ifdef SUPPORTD3D
+
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+extern LPDIRECT3DDEVICE9 vid_d3d9dev;
+extern D3DCAPS9 vid_d3d9caps;
+#endif
+
+struct r_hlsl_permutation_s;
+typedef struct r_hlsl_permutation_s
+{
+       /// hash lookup data
+       struct r_hlsl_permutation_s *hashnext;
+       unsigned int mode;
+       unsigned int permutation;
+
+       /// indicates if we have tried compiling this permutation already
+       qboolean compiled;
+       /// NULL if compilation failed
+       IDirect3DVertexShader9 *vertexshader;
+       IDirect3DPixelShader9 *pixelshader;
+}
+r_hlsl_permutation_t;
+
+typedef enum D3DVSREGISTER_e
+{
+       D3DVSREGISTER_TexMatrix = 0, // float4x4
+       D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
+       D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
+       D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
+       D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
+       D3DVSREGISTER_ModelToLight = 20, // float4x4
+       D3DVSREGISTER_EyePosition = 24,
+       D3DVSREGISTER_FogPlane = 25,
+       D3DVSREGISTER_LightDir = 26,
+       D3DVSREGISTER_LightPosition = 27,
+}
+D3DVSREGISTER_t;
+
+typedef enum D3DPSREGISTER_e
+{
+       D3DPSREGISTER_Alpha = 0,
+       D3DPSREGISTER_BloomBlur_Parameters = 1,
+       D3DPSREGISTER_ClientTime = 2,
+       D3DPSREGISTER_Color_Ambient = 3,
+       D3DPSREGISTER_Color_Diffuse = 4,
+       D3DPSREGISTER_Color_Specular = 5,
+       D3DPSREGISTER_Color_Glow = 6,
+       D3DPSREGISTER_Color_Pants = 7,
+       D3DPSREGISTER_Color_Shirt = 8,
+       D3DPSREGISTER_DeferredColor_Ambient = 9,
+       D3DPSREGISTER_DeferredColor_Diffuse = 10,
+       D3DPSREGISTER_DeferredColor_Specular = 11,
+       D3DPSREGISTER_DeferredMod_Diffuse = 12,
+       D3DPSREGISTER_DeferredMod_Specular = 13,
+       D3DPSREGISTER_DistortScaleRefractReflect = 14,
+       D3DPSREGISTER_EyePosition = 15, // unused
+       D3DPSREGISTER_FogColor = 16,
+       D3DPSREGISTER_FogHeightFade = 17,
+       D3DPSREGISTER_FogPlane = 18,
+       D3DPSREGISTER_FogPlaneViewDist = 19,
+       D3DPSREGISTER_FogRangeRecip = 20,
+       D3DPSREGISTER_LightColor = 21,
+       D3DPSREGISTER_LightDir = 22, // unused
+       D3DPSREGISTER_LightPosition = 23,
+       D3DPSREGISTER_OffsetMapping_Scale = 24,
+       D3DPSREGISTER_PixelSize = 25,
+       D3DPSREGISTER_ReflectColor = 26,
+       D3DPSREGISTER_ReflectFactor = 27,
+       D3DPSREGISTER_ReflectOffset = 28,
+       D3DPSREGISTER_RefractColor = 29,
+       D3DPSREGISTER_Saturation = 30,
+       D3DPSREGISTER_ScreenCenterRefractReflect = 31,
+       D3DPSREGISTER_ScreenScaleRefractReflect = 32,
+       D3DPSREGISTER_ScreenToDepth = 33,
+       D3DPSREGISTER_ShadowMap_Parameters = 34,
+       D3DPSREGISTER_ShadowMap_TextureScale = 35,
+       D3DPSREGISTER_SpecularPower = 36,
+       D3DPSREGISTER_UserVec1 = 37,
+       D3DPSREGISTER_UserVec2 = 38,
+       D3DPSREGISTER_UserVec3 = 39,
+       D3DPSREGISTER_UserVec4 = 40,
+       D3DPSREGISTER_ViewTintColor = 41,
+       D3DPSREGISTER_PixelToScreenTexCoord = 42,
+       D3DPSREGISTER_BloomColorSubtract = 43,
+       D3DPSREGISTER_ViewToLight = 44, // float4x4
+       D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
+       // next at 52
+}
+D3DPSREGISTER_t;
+
+/// information about each possible shader permutation
+r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
+/// currently selected permutation
+r_hlsl_permutation_t *r_hlsl_permutation;
+/// storage for permutations linked in the hash table
+memexpandablearray_t r_hlsl_permutationarray;
+
+static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
+{
+       //unsigned int hashdepth = 0;
+       unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
+       r_hlsl_permutation_t *p;
+       for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
+       {
+               if (p->mode == mode && p->permutation == permutation)
+               {
+                       //if (hashdepth > 10)
+                       //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
+                       return p;
+               }
+               //hashdepth++;
+       }
+       p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
+       p->mode = mode;
+       p->permutation = permutation;
+       p->hashnext = r_hlsl_permutationhash[mode][hashindex];
+       r_hlsl_permutationhash[mode][hashindex] = p;
+       //if (hashdepth > 10)
+       //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
+       return p;
+}
+
+static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
+{
+       char *shaderstring;
+       if (!filename || !filename[0])
+               return NULL;
+       if (!strcmp(filename, "hlsl/default.hlsl"))
+       {
+               if (!hlslshaderstring)
+               {
+                       hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
+                       if (hlslshaderstring)
+                               Con_DPrintf("Loading shaders from file %s...\n", filename);
+                       else
+                               hlslshaderstring = (char *)builtincgshaderstring;
+               }
+               shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
+               memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
+               return shaderstring;
+       }
+       shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
+       if (shaderstring)
+       {
+               if (printfromdisknotice)
+                       Con_DPrintf("from disk %s... ", filename);
+               return shaderstring;
+       }
+       return shaderstring;
+}
+
+#include <d3dx9.h>
+#include <d3dx9mesh.h>
+#pragma comment(lib, "d3dx9.lib")
+
+static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
+{
+       DWORD *vsbin = NULL;
+       DWORD *psbin = NULL;
+       fs_offset_t vsbinsize;
+       fs_offset_t psbinsize;
+//     IDirect3DVertexShader9 *vs = NULL;
+//     IDirect3DPixelShader9 *ps = NULL;
+       ID3DXBuffer *vslog = NULL;
+       ID3DXBuffer *vsbuffer = NULL;
+       ID3DXConstantTable *vsconstanttable = NULL;
+       ID3DXBuffer *pslog = NULL;
+       ID3DXBuffer *psbuffer = NULL;
+       ID3DXConstantTable *psconstanttable = NULL;
+       int vsresult = 0;
+       int psresult = 0;
+       char temp[MAX_INPUTLINE];
+       const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
+       if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
+       if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
+       vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
+       psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
+       if ((!vsbin && vertstring) || (!psbin && fragstring))
+       {
+               vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
+               psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
+               if (vertstring && vertstring[0])
+               {
+                       vsresult = D3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, 0, &vsbuffer, &vslog, &vsconstanttable);
+                       if (vsbuffer)
+                       {
+                               vsbinsize = vsbuffer->GetBufferSize();
+                               vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
+                               memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
+                               vsbuffer->Release();
+                       }
+                       if (vslog)
+                       {
+                               strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
+                               Con_Printf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
+                               vslog->Release();
+                       }
+               }
+               if (fragstring && fragstring[0])
+               {
+                       psresult = D3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, 0, &psbuffer, &pslog, &psconstanttable);
+                       if (psbuffer)
+                       {
+                               psbinsize = psbuffer->GetBufferSize();
+                               psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
+                               memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
+                               psbuffer->Release();
+                       }
+                       if (pslog)
+                       {
+                               strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
+                               Con_Printf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
+                               pslog->Release();
+                       }
+               }
+       }
+       if (vsbin)
+       {
+               vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
+               if (FAILED(vsresult))
+                       Con_Printf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
+       }
+       if (psbin)
+       {
+               psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
+               if (FAILED(psresult))
+                       Con_Printf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
+       }
+       // free the shader data
+       vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
+       psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
+}
+
+static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
+{
+       int i;
+       shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
+       int vertstrings_count = 0, vertstring_length = 0;
+       int geomstrings_count = 0, geomstring_length = 0;
+       int fragstrings_count = 0, fragstring_length = 0;
+       char *t;
+       char *vertexstring, *geometrystring, *fragmentstring;
+       char *vertstring, *geomstring, *fragstring;
+       const char *vertstrings_list[32+3];
+       const char *geomstrings_list[32+3];
+       const char *fragstrings_list[32+3];
+       char permutationname[256];
+       char cachename[256];
+
+       if (p->compiled)
+               return;
+       p->compiled = true;
+       p->vertexshader = NULL;
+       p->pixelshader = NULL;
+
+       permutationname[0] = 0;
+       cachename[0] = 0;
+       vertexstring   = R_HLSL_GetText(modeinfo->vertexfilename, true);
+       geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
+       fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
+
+       strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
+       strlcat(cachename, "hlsl/", sizeof(cachename));
+
+       // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
+       vertstrings_list[vertstrings_count++] = "#define HLSL\n";
+       geomstrings_list[geomstrings_count++] = "#define HLSL\n";
+       fragstrings_list[fragstrings_count++] = "#define HLSL\n";
+
+       // the first pretext is which type of shader to compile as
+       // (later these will all be bound together as a program object)
+       vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
+       geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
+       fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
+
+       // the second pretext is the mode (for example a light source)
+       vertstrings_list[vertstrings_count++] = modeinfo->pretext;
+       geomstrings_list[geomstrings_count++] = modeinfo->pretext;
+       fragstrings_list[fragstrings_count++] = modeinfo->pretext;
+       strlcat(permutationname, modeinfo->name, sizeof(permutationname));
+       strlcat(cachename, modeinfo->name, sizeof(cachename));
+
+       // now add all the permutation pretexts
+       for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
+       {
+               if (permutation & (1<<i))
+               {
+                       vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
+                       geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
+                       fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
+                       strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
+                       strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
+               }
+               else
+               {
+                       // keep line numbers correct
+                       vertstrings_list[vertstrings_count++] = "\n";
+                       geomstrings_list[geomstrings_count++] = "\n";
+                       fragstrings_list[fragstrings_count++] = "\n";
+               }
+       }
+
+       // replace spaces in the cachename with _ characters
+       for (i = 0;cachename[i];i++)
+               if (cachename[i] == ' ')
+                       cachename[i] = '_';
+
+       // now append the shader text itself
+       vertstrings_list[vertstrings_count++] = vertexstring;
+       geomstrings_list[geomstrings_count++] = geometrystring;
+       fragstrings_list[fragstrings_count++] = fragmentstring;
+
+       // if any sources were NULL, clear the respective list
+       if (!vertexstring)
+               vertstrings_count = 0;
+       if (!geometrystring)
+               geomstrings_count = 0;
+       if (!fragmentstring)
+               fragstrings_count = 0;
+
+       vertstring_length = 0;
+       for (i = 0;i < vertstrings_count;i++)
+               vertstring_length += strlen(vertstrings_list[i]);
+       vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
+       for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
+               memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
+
+       geomstring_length = 0;
+       for (i = 0;i < geomstrings_count;i++)
+               geomstring_length += strlen(geomstrings_list[i]);
+       geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
+       for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
+               memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
+
+       fragstring_length = 0;
+       for (i = 0;i < fragstrings_count;i++)
+               fragstring_length += strlen(fragstrings_list[i]);
+       fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
+       for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
+               memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
+
+       // try to load the cached shader, or generate one
+       R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
+
+       if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
+               Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
+       else
+               Con_Printf("^1HLSL shader %s failed!  some features may not work properly.\n", permutationname);
+
+       // free the strings
+       if (vertstring)
+               Mem_Free(vertstring);
+       if (geomstring)
+               Mem_Free(geomstring);
+       if (fragstring)
+               Mem_Free(fragstring);
+       if (vertexstring)
+               Mem_Free(vertexstring);
+       if (geometrystring)
+               Mem_Free(geometrystring);
+       if (fragmentstring)
+               Mem_Free(fragmentstring);
+}
+
+static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
+static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
+static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
+static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
+static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
+static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
+
+static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
+static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
+static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
+static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
+static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
+static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
+
+void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
+{
+       r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
+       if (r_hlsl_permutation != perm)
+       {
+               r_hlsl_permutation = perm;
+               if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
+               {
+                       if (!r_hlsl_permutation->compiled)
+                               R_HLSL_CompilePermutation(perm, mode, permutation);
+                       if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
+                       {
+                               // remove features until we find a valid permutation
+                               int i;
+                               for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
+                               {
+                                       // reduce i more quickly whenever it would not remove any bits
+                                       int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
+                                       if (!(permutation & j))
+                                               continue;
+                                       permutation -= j;
+                                       r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
+                                       if (!r_hlsl_permutation->compiled)
+                                               R_HLSL_CompilePermutation(perm, mode, permutation);
+                                       if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
+                                               break;
+                               }
+                               if (i >= SHADERPERMUTATION_COUNT)
+                               {
+                                       //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
+                                       r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
+                                       return; // no bit left to clear, entire mode is broken
+                               }
+                       }
+               }
+               IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
+               IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
+       }
+       hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
+       hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
+       hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
+}
+#endif
+
 void R_GLSL_Restart_f(void)
 {
        unsigned int i, limit;
@@ -4389,8 +4851,42 @@ void R_GLSL_Restart_f(void)
        if (cgshaderstring && cgshaderstring != builtincgshaderstring)
                Mem_Free(cgshaderstring);
        cgshaderstring = NULL;
+       if (hlslshaderstring && hlslshaderstring != builtincgshaderstring)
+               Mem_Free(hlslshaderstring);
+       hlslshaderstring = NULL;
        switch(vid.renderpath)
        {
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       r_hlsl_permutation_t *p;
+                       r_hlsl_permutation = NULL;
+//                     cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
+//                     cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
+//                     cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
+//                     cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
+                       limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
+                       for (i = 0;i < limit;i++)
+                       {
+                               if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
+                               {
+                                       if (p->vertexshader)
+                                               IDirect3DVertexShader9_Release(p->vertexshader);
+                                       if (p->pixelshader)
+                                               IDirect3DPixelShader9_Release(p->pixelshader);
+                                       Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
+                               }
+                       }
+                       memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        case RENDERPATH_GL20:
                {
                        r_glsl_permutation_t *p;
@@ -4478,6 +4974,25 @@ void R_GLSL_DumpShader_f(void)
        else
                Con_Printf("failed to write to cg/default.cg\n");
 #endif
+
+#ifdef SUPPORTD3D
+       file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
+       if (file)
+       {
+               FS_Print(file, "/* The engine may define the following macros:\n");
+               FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
+               for (i = 0;i < SHADERMODE_COUNT;i++)
+                       FS_Print(file, hlslshadermodeinfo[i].pretext);
+               for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
+                       FS_Print(file, shaderpermutationinfo[i].pretext);
+               FS_Print(file, "*/\n");
+               FS_Print(file, builtincgshaderstring);
+               FS_Close(file);
+               Con_Printf("hlsl/default.hlsl written\n");
+       }
+       else
+               Con_Printf("failed to write to hlsl/default.hlsl\n");
+#endif
 }
 
 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
@@ -4486,10 +5001,23 @@ void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemod
                texturemode = GL_MODULATE;
        switch (vid.renderpath)
        {
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
+               R_Mesh_TexBind(GL20TU_FIRST , first );
+               R_Mesh_TexBind(GL20TU_SECOND, second);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        case RENDERPATH_GL20:
                R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
-               if (r_glsl_permutation->loc_Texture_First ) R_Mesh_TexBind(GL20TU_FIRST , first );
-               if (r_glsl_permutation->loc_Texture_Second) R_Mesh_TexBind(GL20TU_SECOND, second);
+               R_Mesh_TexBind(GL20TU_FIRST , first );
+               R_Mesh_TexBind(GL20TU_SECOND, second);
                break;
        case RENDERPATH_CGGL:
 #ifdef SUPPORTCG
@@ -4516,6 +5044,17 @@ void R_SetupShader_DepthOrShadow(void)
 {
        switch (vid.renderpath)
        {
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        case RENDERPATH_GL20:
                R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
                break;
@@ -4538,6 +5077,17 @@ void R_SetupShader_ShowDepth(void)
 {
        switch (vid.renderpath)
        {
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTHLSL
+               R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, 0);
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        case RENDERPATH_GL20:
                R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
                break;
@@ -4570,6 +5120,7 @@ extern int r_shadow_shadowmappcf;
 extern rtexture_t *r_shadow_shadowmaprectangletexture;
 extern rtexture_t *r_shadow_shadowmap2dtexture;
 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
+extern rtexture_t *r_shadow_shadowmap2dcolortexture;
 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
 extern matrix4x4_t r_shadow_shadowmapmatrix;
 extern int r_shadow_shadowmaplod; // changes for each light based on distance
@@ -4580,7 +5131,7 @@ extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
 extern cvar_t gl_mesh_separatearrays;
-void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist)
+void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane)
 {
        // select a permutation of the lighting shader appropriate to this
        // combination of texture, entity, light source, and fogging, only use the
@@ -4589,6 +5140,7 @@ void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting,
        unsigned int permutation = 0;
        unsigned int mode = 0;
        float m16f[16];
+       r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
        if (rsurfacepass == RSURFPASS_BACKGROUND)
        {
                // distorted background
@@ -4928,6 +5480,149 @@ void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting,
        }
        switch(vid.renderpath)
        {
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
+               R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
+               R_SetupShader_SetPermutationHLSL(mode, permutation);
+               Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
+               if (mode == SHADERMODE_LIGHTSOURCE)
+               {
+                       Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
+                       hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
+               }
+               else
+               {
+                       if (mode == SHADERMODE_LIGHTDIRECTION)                                   
+                       {
+                               hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
+                       }
+               }
+               Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
+               Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
+               Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
+               hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
+               hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
+
+               if (mode == SHADERMODE_LIGHTSOURCE)
+               {
+                       hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
+                       hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
+
+                       // additive passes are only darkened by fog, not tinted
+                       hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
+                       hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
+               }
+               else
+               {
+                       if (mode == SHADERMODE_FLATCOLOR)
+                       {
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
+                       }
+                       else if (mode == SHADERMODE_LIGHTDIRECTION)
+                       {
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
+                               hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);
+                               hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
+                               hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
+                               hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
+                       }
+                       else
+                       {
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
+                               hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
+                               hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
+                               hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
+                       }
+                       // additive passes are only darkened by fog, not tinted
+                       if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
+                               hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
+                       else
+                               hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
+                       hlslPSSetParameter4f(D3DPSREGISTER_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
+                       hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
+                       hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
+                       hlslPSSetParameter4fv(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f);
+                       hlslPSSetParameter4fv(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f);
+                       hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
+                       hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
+                       hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
+               }
+               hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
+               hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
+               hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
+               hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3]);
+               hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
+               if (rsurface.texture->pantstexture)
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
+               else
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
+               if (rsurface.texture->shirttexture)
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
+               else
+                       hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
+               hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
+               hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
+               hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
+               hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
+               hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
+               hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
+               hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
+
+               R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
+               R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
+               R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
+               R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
+               if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
+               if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
+               if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
+               if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
+               if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
+               if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
+               if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
+               if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
+               if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
+               if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
+               R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
+               R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
+               if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
+               if (rsurfacepass == RSURFPASS_BACKGROUND)
+               {
+                       R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
+                       R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
+                       R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
+               }
+               else
+               {
+                       if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
+               }
+//             if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
+//             if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
+               if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
+               if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
+               if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
+               {
+                       R_Mesh_TexBind((permutation & SHADERPERMUTATION_SHADOWMAPORTHO) ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, (permutation & SHADERPERMUTATION_SHADOWSAMPLER) ? r_shadow_shadowmap2dtexture : r_shadow_shadowmap2dcolortexture);
+                       if (rsurface.rtlight)
+                       {
+                               if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
+                               if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
+                       }
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        case RENDERPATH_GL20:
                if (gl_mesh_separatearrays.integer)
                {
@@ -5050,13 +5745,21 @@ void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting,
                if (r_glsl_permutation->loc_Texture_ReflectCube     >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
                if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
                if (r_glsl_permutation->loc_Texture_FogMask         >= 0) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
-               if (r_glsl_permutation->loc_Texture_Lightmap        >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP          , r_texture_white                                     );
-               if (r_glsl_permutation->loc_Texture_Deluxemap       >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP         , r_texture_blanknormalmap                            );
+               if (r_glsl_permutation->loc_Texture_Lightmap        >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
+               if (r_glsl_permutation->loc_Texture_Deluxemap       >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
                if (r_glsl_permutation->loc_Texture_Attenuation     >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
-               if (r_glsl_permutation->loc_Texture_Refraction      >= 0) R_Mesh_TexBind(GL20TU_REFRACTION        , r_texture_white                                     );
-               if (r_glsl_permutation->loc_Texture_Reflection      >= 0) R_Mesh_TexBind(GL20TU_REFLECTION        , r_texture_white                                     );
-               if (r_glsl_permutation->loc_Texture_ScreenDepth     >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
-               if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
+               if (rsurfacepass == RSURFPASS_BACKGROUND)
+               {
+                       R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
+                       R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
+                       R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
+               }
+               else
+               {
+                       if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
+               }
+//             if (r_glsl_permutation->loc_Texture_ScreenDepth     >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
+//             if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
                if (r_glsl_permutation->loc_Texture_ScreenDiffuse   >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
                if (r_glsl_permutation->loc_Texture_ScreenSpecular  >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
                if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
@@ -5212,11 +5915,19 @@ void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting,
                if (r_cg_permutation->fp_Texture_ReflectCube    ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectCube    , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);CHECKCGERROR
                if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture                         );CHECKCGERROR
                if (r_cg_permutation->fp_Texture_FogMask        ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask        , r_texture_fogattenuation                            );CHECKCGERROR
-               if (r_cg_permutation->fp_Texture_Lightmap       ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap       , r_texture_white                                     );CHECKCGERROR
-               if (r_cg_permutation->fp_Texture_Deluxemap      ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap      , r_texture_blanknormalmap                            );CHECKCGERROR
+               if (r_cg_permutation->fp_Texture_Lightmap       ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap       , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);CHECKCGERROR
+               if (r_cg_permutation->fp_Texture_Deluxemap      ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap      , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);CHECKCGERROR
                if (r_cg_permutation->fp_Texture_Attenuation    ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation    , r_shadow_attenuationgradienttexture                 );CHECKCGERROR
-               if (r_cg_permutation->fp_Texture_Refraction     ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction     , r_texture_white                                     );CHECKCGERROR
-               if (r_cg_permutation->fp_Texture_Reflection     ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection     , r_texture_white                                     );CHECKCGERROR
+               if (rsurfacepass == RSURFPASS_BACKGROUND)
+               {
+                       if (r_cg_permutation->fp_Texture_Refraction     ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction     , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);CHECKCGERROR
+                       if (r_cg_permutation->fp_Texture_Reflection     ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection     , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
+                       if (r_cg_permutation->fp_Texture_First          ) CG_BindTexture(r_cg_permutation->fp_Texture_First          , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);CHECKCGERROR
+               }
+               else
+               {
+                       if (r_cg_permutation->fp_Texture_Reflection     ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection     , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
+               }
                if (r_cg_permutation->fp_Texture_ScreenDepth    ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth    , r_shadow_prepassgeometrydepthtexture                );CHECKCGERROR
                if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture            );CHECKCGERROR
                if (r_cg_permutation->fp_Texture_ScreenDiffuse  ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse  , r_shadow_prepasslightingdiffusetexture              );CHECKCGERROR
@@ -5298,6 +6009,37 @@ void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
        Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
        switch(vid.renderpath)
        {
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               R_SetupShader_SetPermutationHLSL(mode, permutation);
+               hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
+               hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
+               hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
+               hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
+               hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
+               hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
+               hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
+               hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
+               hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
+               hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
+
+               R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
+               R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthtexture                );
+               R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
+               R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
+               R_Mesh_TexBind(GL20TU_SHADOWMAPRECT      , r_shadow_shadowmaprectangletexture                  );
+               if (r_shadow_usingshadowmapcube)
+                       R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE      , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
+               R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dtexture                         );
+               R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        case RENDERPATH_GL20:
                R_SetupShader_SetPermutationGLSL(mode, permutation);
                if (r_glsl_permutation->loc_LightPosition             >= 0) qglUniform3fARB(       r_glsl_permutation->loc_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
@@ -6189,6 +6931,9 @@ void gl_main_start(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                Cvar_SetValueQuick(&r_textureunits, vid.texunits);
                Cvar_SetValueQuick(&gl_combine, 1);
                Cvar_SetValueQuick(&r_glsl, 1);
@@ -6252,6 +6997,12 @@ void gl_main_start(void)
        memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
        Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
        cgshaderstring = NULL;
+#endif
+#ifdef SUPPORTD3D
+       r_hlsl_permutation = NULL;
+       memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
+       Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
+       hlslshaderstring = NULL;
 #endif
        memset(&r_svbsp, 0, sizeof (r_svbsp));
 
@@ -6265,8 +7016,25 @@ void gl_main_shutdown(void)
 
        R_Main_FreeViewCache();
 
-       if (r_maxqueries)
-               qglDeleteQueriesARB(r_maxqueries, r_queries);
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (r_maxqueries)
+                       qglDeleteQueriesARB(r_maxqueries, r_queries);
+               break;
+       case RENDERPATH_D3D9:
+               //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 
        r_numqueries = 0;
        r_maxqueries = 0;
@@ -6297,14 +7065,6 @@ void gl_main_shutdown(void)
        //r_texture_fogintensity = NULL;
        memset(&r_bloomstate, 0, sizeof(r_bloomstate));
        memset(&r_waterstate, 0, sizeof(r_waterstate));
-       r_glsl_permutation = NULL;
-       memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
-       glslshaderstring = NULL;
-#ifdef SUPPORTCG
-       r_cg_permutation = NULL;
-       memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
-       cgshaderstring = NULL;
-#endif
        R_GLSL_Restart_f();
 }
 
@@ -6529,9 +7289,7 @@ void GL_Init (void)
        Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
 
        // clear to black (loading plaque will be seen over this)
-       CHECKGLERROR
-       qglClearColor(0,0,0,1);CHECKGLERROR
-       qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
+       GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
 }
 
 int R_CullBox(const vec3_t mins, const vec3_t maxs)
@@ -6825,6 +7583,9 @@ void R_AnimCache_CacheVisibleEntities(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                break;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
@@ -7321,6 +8082,18 @@ void R_EntityMatrix(const matrix4x4_t *matrix)
                CHECKGLERROR
                switch(vid.renderpath)
                {
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
+                       hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
+                       break;
                case RENDERPATH_GL20:
                        if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
                        if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
@@ -7359,16 +8132,25 @@ void R_ResetViewRendering2D(void)
        GL_DepthMask(false);
        GL_DepthRange(0, 1);
        GL_DepthTest(false);
+       GL_DepthFunc(GL_LEQUAL);
        R_EntityMatrix(&identitymatrix);
        R_Mesh_ResetTextureState();
        GL_PolygonOffset(0, 0);
-       qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
-       qglDepthFunc(GL_LEQUAL);CHECKGLERROR
-       qglDisable(GL_STENCIL_TEST);CHECKGLERROR
-       qglStencilMask(255);CHECKGLERROR
-       qglStencilFunc(GL_ALWAYS, 128, 255);CHECKGLERROR
-       qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
-       GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
+       R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
+       }
+       GL_CullFace(GL_NONE);
 }
 
 void R_ResetViewRendering3D(void)
@@ -7385,15 +8167,24 @@ void R_ResetViewRendering3D(void)
        GL_DepthMask(true);
        GL_DepthRange(0, 1);
        GL_DepthTest(true);
+       GL_DepthFunc(GL_LEQUAL);
        R_EntityMatrix(&identitymatrix);
        R_Mesh_ResetTextureState();
        GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
-       qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
-       qglDepthFunc(GL_LEQUAL);CHECKGLERROR
-       qglDisable(GL_STENCIL_TEST);CHECKGLERROR
-       qglStencilMask(255);CHECKGLERROR
-       qglStencilFunc(GL_ALWAYS, 128, 255);CHECKGLERROR
-       qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
+       R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
+       }
        GL_CullFace(r_refdef.view.cullface_back);
 }
 
@@ -7429,6 +8220,9 @@ static void R_Water_StartFrame(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                break;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
@@ -7593,14 +8387,14 @@ static void R_Water_ProcessPlanes(void)
                if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
                {
                        if (!p->texture_refraction)
-                               p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
+                               p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
                        if (!p->texture_refraction)
                                goto error;
                }
                else if (p->materialflags & MATERIALFLAG_CAMERA)
                {
                        if (!p->texture_camera)
-                               p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR, -1, NULL);
+                               p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
                        if (!p->texture_camera)
                                goto error;
                }
@@ -7608,7 +8402,7 @@ static void R_Water_ProcessPlanes(void)
                if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
                {
                        if (!p->texture_reflection)
-                               p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
+                               p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
                        if (!p->texture_reflection)
                                goto error;
                }
@@ -7747,6 +8541,9 @@ void R_Bloom_StartFrame(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                break;
        case RENDERPATH_GL13:
        case RENDERPATH_GL11:
@@ -7799,7 +8596,7 @@ void R_Bloom_StartFrame(void)
                r_bloomstate.screentexturewidth = screentexturewidth;
                r_bloomstate.screentextureheight = screentextureheight;
                if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
-                       r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
+                       r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
        }
        if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
        {
@@ -7809,7 +8606,7 @@ void R_Bloom_StartFrame(void)
                r_bloomstate.bloomtexturewidth = bloomtexturewidth;
                r_bloomstate.bloomtextureheight = bloomtextureheight;
                if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
-                       r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
+                       r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
        }
 
        // when doing a reduced render (HDR) we want to use a smaller area
@@ -7841,6 +8638,24 @@ void R_Bloom_StartFrame(void)
        r_bloomstate.bloomtexcoord2f[6] = 0;
        r_bloomstate.bloomtexcoord2f[7] = 0;
 
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               {
+                       int i;
+                       for (i = 0;i < 4;i++)
+                       {
+                               r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
+                               r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
+                               r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
+                               r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
+                       }
+               }
+               break;
+       }
+
        if (r_hdr.integer || r_bloom.integer)
        {
                r_bloomstate.enabled = true;
@@ -7859,7 +8674,21 @@ void R_Bloom_CopyBloomTexture(float colorscale)
        R_SetViewport(&r_bloomstate.viewport);
        GL_BlendFunc(GL_ONE, GL_ZERO);
        GL_Color(colorscale, colorscale, colorscale, 1);
-       R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
+       // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
+               break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
+               break;
+       }
        // TODO: do boxfilter scale-down in shader?
        R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
        R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
@@ -7955,31 +8784,6 @@ void R_Bloom_MakeTexture(void)
                R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
                r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
        }
-
-       // apply subtract last
-       // (just like it would be in a GLSL shader)
-       if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
-       {
-               GL_BlendFunc(GL_ONE, GL_ZERO);
-               GL_Color(1,1,1,1);
-               R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
-               R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
-               R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
-               r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
-
-               GL_BlendFunc(GL_ONE, GL_ONE);
-               qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
-               R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
-               GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
-               R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
-               R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
-               r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
-               qglBlendEquationEXT(GL_FUNC_ADD_EXT);
-
-               // copy the darkened bloom view to a texture
-               R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
-               r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
-       }
 }
 
 void R_HDR_RenderBloomTexture(void)
@@ -8045,6 +8849,9 @@ static void R_BlendView(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                permutation =
                          (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
                        | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
@@ -8092,7 +8899,20 @@ static void R_BlendView(void)
                                {
                                        GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
                                        GL_Color(1, 1, 1, cl.motionbluralpha);
-                                       R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
+                                       switch(vid.renderpath)
+                                       {
+                                       case RENDERPATH_GL11:
+                                       case RENDERPATH_GL13:
+                                       case RENDERPATH_GL20:
+                                       case RENDERPATH_CGGL:
+                                               R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
+                                               break;
+                                       case RENDERPATH_D3D9:
+                                       case RENDERPATH_D3D10:
+                                       case RENDERPATH_D3D11:
+                                               R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
+                                               break;
+                                       }
                                        R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
                                        R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
                                        r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
@@ -8139,12 +8959,12 @@ static void R_BlendView(void)
 
                R_ResetViewRendering2D();
                GL_Color(1, 1, 1, 1);
-               R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
                GL_BlendFunc(GL_ONE, GL_ZERO);
 
                switch(vid.renderpath)
                {
                case RENDERPATH_GL20:
+                       R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
                        R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
                        if (r_glsl_permutation->loc_Texture_First      >= 0) R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
                        if (r_glsl_permutation->loc_Texture_Second     >= 0) R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
@@ -8157,9 +8977,11 @@ static void R_BlendView(void)
                        if (r_glsl_permutation->loc_UserVec4           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
                        if (r_glsl_permutation->loc_Saturation         >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation        , r_glsl_saturation.value);
                        if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
+                       if (r_glsl_permutation->loc_BloomColorSubtract    >= 0) qglUniform4fARB(r_glsl_permutation->loc_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
                        break;
                case RENDERPATH_CGGL:
 #ifdef SUPPORTCG
+                       R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
                        R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
                        if (r_cg_permutation->fp_Texture_First     ) CG_BindTexture(r_cg_permutation->fp_Texture_First     , r_bloomstate.texture_screen);CHECKCGERROR
                        if (r_cg_permutation->fp_Texture_Second    ) CG_BindTexture(r_cg_permutation->fp_Texture_Second    , r_bloomstate.texture_bloom );CHECKCGERROR
@@ -8172,8 +8994,34 @@ static void R_BlendView(void)
                        if (r_cg_permutation->fp_UserVec4          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);CHECKCGERROR
                        if (r_cg_permutation->fp_Saturation        ) cgGLSetParameter1f(     r_cg_permutation->fp_Saturation        , r_glsl_saturation.value);CHECKCGERROR
                        if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
+                       if (r_cg_permutation->fp_BloomColorSubtract   ) cgGLSetParameter4f(r_cg_permutation->fp_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
 #endif
                        break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
+                       R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
+                       R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
+                       R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
+                       R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
+                       R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
+                       hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor        , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
+                       hlslPSSetParameter2f(D3DPSREGISTER_PixelSize            , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
+                       hlslPSSetParameter4f(D3DPSREGISTER_UserVec1             , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
+                       hlslPSSetParameter4f(D3DPSREGISTER_UserVec2             , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
+                       hlslPSSetParameter4f(D3DPSREGISTER_UserVec3             , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
+                       hlslPSSetParameter4f(D3DPSREGISTER_UserVec4             , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
+                       hlslPSSetParameter1f(D3DPSREGISTER_Saturation           , r_glsl_saturation.value);
+                       hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
+                       hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                default:
                        break;
                }
@@ -8320,6 +9168,9 @@ void R_UpdateVariables(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                if(v_glslgamma.integer && !vid_gammatables_trivial)
                {
                        if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
@@ -8414,7 +9265,7 @@ void R_RenderView(void)
        if (r_refdef.view.isoverlay)
        {
                // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
-               GL_Clear( GL_DEPTH_BUFFER_BIT );
+               GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
                R_TimeReport("depthclear");
 
                r_refdef.view.showdebug = false;
@@ -10925,27 +11776,6 @@ void RSurf_DrawBatch(void)
        R_Mesh_Draw(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchfirsttriangle, rsurface.batchnumtriangles, rsurface.batchelement3i, rsurface.batchelement3i_indexbuffer, rsurface.batchelement3i_bufferoffset, rsurface.batchelement3s, rsurface.batchelement3s_indexbuffer, rsurface.batchelement3s_bufferoffset);
 }
 
-static void RSurf_BindLightmapForBatch(void)
-{
-       switch(vid.renderpath)
-       {
-       case RENDERPATH_CGGL:
-#ifdef SUPPORTCG
-               if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture );CHECKCGERROR
-               if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, rsurface.deluxemaptexture);CHECKCGERROR
-#endif
-               break;
-       case RENDERPATH_GL20:
-               if (r_glsl_permutation->loc_Texture_Lightmap  >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture );
-               if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, rsurface.deluxemaptexture);
-               break;
-       case RENDERPATH_GL13:
-       case RENDERPATH_GL11:
-               R_Mesh_TexBind(0, rsurface.lightmaptexture);
-               break;
-       }
-}
-
 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
 {
        // pick the closest matching water plane
@@ -10975,30 +11805,6 @@ static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
        return bestplaneindex;
 }
 
-static void RSurf_BindReflectionForBatch(int planeindex)
-{
-       // pick the closest matching water plane and bind textures
-       r_waterstate_waterplane_t *bestp = planeindex >= 0 ? r_waterstate.waterplanes + planeindex : NULL;
-       switch(vid.renderpath)
-       {
-       case RENDERPATH_CGGL:
-#ifdef SUPPORTCG
-               if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
-               else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
-               if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
-#endif
-               break;
-       case RENDERPATH_GL20:
-               if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
-               else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
-               if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
-               break;
-       case RENDERPATH_GL13:
-       case RENDERPATH_GL11:
-               break;
-       }
-}
-
 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
 {
        int i;
@@ -11114,7 +11920,7 @@ static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qb
        if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
        R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
        GL_Color(r, g, b, a);
-       RSurf_BindLightmapForBatch();
+       R_Mesh_TexBind(0, rsurface.lightmaptexture);
        RSurf_DrawBatch();
 }
 
@@ -11307,7 +12113,7 @@ static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface
        {
                // render screenspace normalmap to texture
                GL_DepthMask(true);
-               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist);
+               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL);
                RSurf_DrawBatch();
                return;
        }
@@ -11328,24 +12134,18 @@ static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface
                        {
                                // render water or distortion background
                                GL_DepthMask(true);
-                               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start);
-                               RSurf_BindReflectionForBatch(startplaneindex);
-                               if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
-                                       RSurf_BindLightmapForBatch();
+                               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
                                RSurf_DrawBatch();
                                // blend surface on top
                                GL_DepthMask(false);
-                               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
+                               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL);
                                RSurf_DrawBatch();
                        }
                        else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
                        {
                                // render surface with reflection texture as input
                                GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
-                               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
-                               RSurf_BindReflectionForBatch(startplaneindex);
-                               if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
-                                       RSurf_BindLightmapForBatch();
+                               R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
                                RSurf_DrawBatch();
                        }
                }
@@ -11354,9 +12154,7 @@ static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface
 
        // render surface batch normally
        GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
-       R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist);
-       if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
-               RSurf_BindLightmapForBatch();
+       R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL);
        RSurf_DrawBatch();
 }
 
@@ -11381,7 +12179,7 @@ static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface
                        else
                        {
                                GL_AlphaTest(false);
-                               qglDepthFunc(GL_EQUAL);CHECKGLERROR
+                               GL_DepthFunc(GL_EQUAL);
                        }
                }
                GL_DepthMask(layer->depthmask && writedepth);
@@ -11459,10 +12257,9 @@ static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface
                        Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
                }
        }
-       CHECKGLERROR
        if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
        {
-               qglDepthFunc(GL_LEQUAL);CHECKGLERROR
+               GL_DepthFunc(GL_LEQUAL);
                GL_AlphaTest(false);
        }
 }
@@ -11485,7 +12282,7 @@ static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface
                        else
                        {
                                GL_AlphaTest(false);
-                               qglDepthFunc(GL_EQUAL);CHECKGLERROR
+                               GL_DepthFunc(GL_EQUAL);
                        }
                }
                GL_DepthMask(layer->depthmask && writedepth);
@@ -11561,10 +12358,9 @@ static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface
                        Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
                }
        }
-       CHECKGLERROR
        if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
        {
-               qglDepthFunc(GL_LEQUAL);CHECKGLERROR
+               GL_DepthFunc(GL_LEQUAL);
                GL_AlphaTest(false);
        }
 }
@@ -11761,6 +12557,9 @@ static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
                break;
        case RENDERPATH_GL13:
@@ -11786,6 +12585,9 @@ static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
                break;
        case RENDERPATH_GL13:
@@ -11820,6 +12622,9 @@ static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const
                {
                case RENDERPATH_GL20:
                case RENDERPATH_CGGL:
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
                        RSurf_ActiveModelEntity(ent, true, true, false);
                        break;
                case RENDERPATH_GL13:
@@ -12788,6 +13593,24 @@ void R_DrawDebugModel(void)
        dp_model_t *model = ent->model;
        vec3_t v;
 
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               break;
+       case RENDERPATH_D3D9:
+               //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               return;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               return;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               return;
+       }
+
        flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
 
        R_Mesh_ResetTextureState();
@@ -13073,6 +13896,9 @@ void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean wr
                {
                case RENDERPATH_GL20:
                case RENDERPATH_CGGL:
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
                        RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
                        break;
                case RENDERPATH_GL13:
@@ -13087,6 +13913,9 @@ void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean wr
                {
                case RENDERPATH_GL20:
                case RENDERPATH_CGGL:
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
                        RSurf_ActiveModelEntity(ent, true, true, false);
                        break;
                case RENDERPATH_GL13:
index 47981b431f38f2214b6a262895c47ad38b518e9d..bf504d96f68f4f5ae6e54de29276c1c3bc56e774 100644 (file)
@@ -1,5 +1,9 @@
 
 #include "quakedef.h"
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+extern LPDIRECT3DDEVICE9 vid_d3d9dev;
+#endif
 #include "image.h"
 #include "jpeg.h"
 #include "image_png.h"
@@ -32,6 +36,16 @@ qboolean     gl_filter_force = false;
 int            gl_filter_min = GL_LINEAR_MIPMAP_LINEAR;
 int            gl_filter_mag = GL_LINEAR;
 
+#ifdef SUPPORTD3D
+int d3d_filter_flatmin = D3DTEXF_LINEAR;
+int d3d_filter_flatmag = D3DTEXF_LINEAR;
+int d3d_filter_flatmix = D3DTEXF_POINT;
+int d3d_filter_mipmin = D3DTEXF_LINEAR;
+int d3d_filter_mipmag = D3DTEXF_LINEAR;
+int d3d_filter_mipmix = D3DTEXF_LINEAR;
+int d3d_filter_nomip = false;
+#endif
+
 
 static mempool_t *texturemempool;
 static memexpandablearray_t texturearray;
@@ -104,6 +118,22 @@ typedef struct gltexture_s
        int texnum; // GL texture slot number
        qboolean dirty; // indicates that R_RealGetTexture should be called
        int gltexturetypeenum; // used by R_Mesh_TexBind
+       // d3d stuff the backend needs
+       void *d3dtexture;
+#ifdef SUPPORTD3D
+       int d3dformat;
+       int d3dusage;
+       int d3dpool;
+       int d3daddressu;
+       int d3daddressv;
+       int d3daddressw;
+       int d3dmagfilter;
+       int d3dminfilter;
+       int d3dmipfilter;
+       int d3dmaxmiplevelfilter;
+       int d3dmipmaplodbias;
+       int d3dmaxmiplevel;
+#endif
 
        // dynamic texture stuff [11/22/2007 Black]
        updatecallback_t updatecallback;
@@ -143,6 +173,8 @@ typedef struct gltexture_s
        int tilewidth, tileheight, tiledepth;
        // 1 or 6 depending on texturetype
        int sides;
+       // how many mipmap levels in this texture
+       int miplevels;
        // bytes per pixel
        int bytesperpixel;
        // GL_RGB or GL_RGBA or GL_DEPTH_COMPONENT
@@ -323,6 +355,25 @@ static glmode_t modes[6] =
        {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}
 };
 
+#ifdef SUPPORTD3D
+typedef struct d3dmode_s
+{
+       char *name;
+       int m1, m2;
+}
+d3dmode_t;
+
+static d3dmode_t d3dmodes[6] =
+{
+       {"GL_NEAREST", D3DTEXF_POINT, D3DTEXF_POINT},
+       {"GL_LINEAR", D3DTEXF_LINEAR, D3DTEXF_POINT},
+       {"GL_NEAREST_MIPMAP_NEAREST", D3DTEXF_POINT, D3DTEXF_POINT},
+       {"GL_LINEAR_MIPMAP_NEAREST", D3DTEXF_LINEAR, D3DTEXF_POINT},
+       {"GL_NEAREST_MIPMAP_LINEAR", D3DTEXF_POINT, D3DTEXF_LINEAR},
+       {"GL_LINEAR_MIPMAP_LINEAR", D3DTEXF_LINEAR, D3DTEXF_LINEAR}
+};
+#endif
+
 static void GL_TextureMode_f (void)
 {
        int i;
@@ -358,37 +409,82 @@ static void GL_TextureMode_f (void)
        gl_filter_mag = modes[i].magnification;
        gl_filter_force = ((Cmd_Argc() > 2) && !strcasecmp(Cmd_Argv(2), "force"));
 
-       // change all the existing mipmap texture objects
-       // FIXME: force renderer(/client/something?) restart instead?
-       CHECKGLERROR
-       GL_ActiveTexture(0);
-       for (pool = gltexturepoolchain;pool;pool = pool->next)
+       switch(vid.renderpath)
        {
-               for (glt = pool->gltchain;glt;glt = glt->chain)
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               // change all the existing mipmap texture objects
+               // FIXME: force renderer(/client/something?) restart instead?
+               CHECKGLERROR
+               GL_ActiveTexture(0);
+               for (pool = gltexturepoolchain;pool;pool = pool->next)
                {
-                       // only update already uploaded images
-                       if (glt->texnum && (gl_filter_force || !(glt->flags & (TEXF_FORCENEAREST | TEXF_FORCELINEAR))))
+                       for (glt = pool->gltchain;glt;glt = glt->chain)
                        {
-                               oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
-                               qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
-                               if (glt->flags & TEXF_MIPMAP)
+                               // only update already uploaded images
+                               if (glt->texnum && (gl_filter_force || !(glt->flags & (TEXF_FORCENEAREST | TEXF_FORCELINEAR))))
                                {
-                                       qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_min);CHECKGLERROR
+                                       oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
+                                       qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
+                                       if (glt->flags & TEXF_MIPMAP)
+                                       {
+                                               qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_min);CHECKGLERROR
+                                       }
+                                       else
+                                       {
+                                               qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_mag);CHECKGLERROR
+                                       }
+                                       qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAG_FILTER, gl_filter_mag);CHECKGLERROR
+                                       qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
                                }
-                               else
+                       }
+               }
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               d3d_filter_flatmin = d3dmodes[i].m1;
+               d3d_filter_flatmag = d3dmodes[i].m1;
+               d3d_filter_flatmix = D3DTEXF_POINT;
+               d3d_filter_mipmin = d3dmodes[i].m1;
+               d3d_filter_mipmag = d3dmodes[i].m1;
+               d3d_filter_mipmix = d3dmodes[i].m2;
+               d3d_filter_nomip = i < 2;
+               if (gl_texture_anisotropy.integer > 1 && i == 5)
+                       d3d_filter_mipmin = d3d_filter_mipmag = D3DTEXF_ANISOTROPIC;
+               for (pool = gltexturepoolchain;pool;pool = pool->next)
+               {
+                       for (glt = pool->gltchain;glt;glt = glt->chain)
+                       {
+                               // only update already uploaded images
+                               if (glt->d3dtexture && (gl_filter_force || !(glt->flags & (TEXF_FORCENEAREST | TEXF_FORCELINEAR))))
                                {
-                                       qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MIN_FILTER, gl_filter_mag);CHECKGLERROR
+                                       if (glt->flags & TEXF_MIPMAP)
+                                       {
+                                               glt->d3dminfilter = d3d_filter_mipmin;
+                                               glt->d3dmagfilter = d3d_filter_mipmag;
+                                               glt->d3dmipfilter = d3d_filter_mipmix;
+                                               glt->d3dmaxmiplevelfilter = 0;
+                                       }
+                                       else
+                                       {
+                                               glt->d3dminfilter = d3d_filter_flatmin;
+                                               glt->d3dmagfilter = d3d_filter_flatmag;
+                                               glt->d3dmipfilter = d3d_filter_flatmix;
+                                               glt->d3dmaxmiplevelfilter = 0;
+                                       }
                                }
-                               qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAG_FILTER, gl_filter_mag);CHECKGLERROR
-                               qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
                        }
                }
+#endif
+               break;
        }
 }
 
-static void GL_Texture_CalcImageSize(int texturetype, int flags, int miplevel, int inwidth, int inheight, int indepth, int *outwidth, int *outheight, int *outdepth)
+static void GL_Texture_CalcImageSize(int texturetype, int flags, int miplevel, int inwidth, int inheight, int indepth, int *outwidth, int *outheight, int *outdepth, int *outmiplevels)
 {
-       int picmip = 0, maxsize = 0, width2 = 1, height2 = 1, depth2 = 1;
+       int picmip = 0, maxsize = 0, width2 = 1, height2 = 1, depth2 = 1, miplevels = 1;
 
        switch (texturetype)
        {
@@ -442,6 +538,16 @@ static void GL_Texture_CalcImageSize(int texturetype, int flags, int miplevel, i
                }
                *outdepth = max(1, depth2);
        }
+
+       miplevels = 1;
+       if (flags & TEXF_MIPMAP)
+       {
+               int extent = max(width2, max(height2, depth2));
+               while(extent >>= 1)
+                       miplevels++;
+       }
+       if (outmiplevels)
+               *outmiplevels = miplevels;
 }
 
 
@@ -449,7 +555,7 @@ static int R_CalcTexelDataSize (gltexture_t *glt)
 {
        int width2, height2, depth2, size;
 
-       GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->miplevel, glt->inputwidth, glt->inputheight, glt->inputdepth, &width2, &height2, &depth2);
+       GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->miplevel, glt->inputwidth, glt->inputheight, glt->inputdepth, &width2, &height2, &depth2, NULL);
 
        size = width2 * height2 * depth2;
 
@@ -524,10 +630,26 @@ static void R_TextureStats_f(void)
 
 static void r_textures_start(void)
 {
-       // LordHavoc: allow any alignment
-       CHECKGLERROR
-       qglPixelStorei(GL_UNPACK_ALIGNMENT, 1);CHECKGLERROR
-       qglPixelStorei(GL_PACK_ALIGNMENT, 1);CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               // LordHavoc: allow any alignment
+               CHECKGLERROR
+               qglPixelStorei(GL_UNPACK_ALIGNMENT, 1);CHECKGLERROR
+               qglPixelStorei(GL_PACK_ALIGNMENT, 1);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
 
        texturemempool = Mem_AllocPool("texture management", 0, NULL);
        Mem_ExpandableArray_NewArray(&texturearray, texturemempool, sizeof(gltexture_t), 512);
@@ -563,6 +685,94 @@ static void r_textures_newmap(void)
 {
 }
 
+static void r_textures_devicelost(void)
+{
+       int i, endindex;
+       gltexture_t *glt;
+       endindex = Mem_ExpandableArray_IndexRange(&texturearray);
+       for (i = 0;i < endindex;i++)
+       {
+               glt = (gltexture_t *) Mem_ExpandableArray_RecordAtIndex(&texturearray, i);
+               if (!glt || !(glt->flags & TEXF_RENDERTARGET))
+                       continue;
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       if (glt->tiledepth > 1)
+                               IDirect3DVolumeTexture9_Release((IDirect3DVolumeTexture9 *)glt->d3dtexture);
+                       else if (glt->sides == 6)
+                               IDirect3DCubeTexture9_Release((IDirect3DCubeTexture9 *)glt->d3dtexture);
+                       else
+                               IDirect3DTexture9_Release((IDirect3DTexture9 *)glt->d3dtexture);
+                       glt->d3dtexture = NULL;
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
+       }
+}
+
+static void r_textures_devicerestored(void)
+{
+       int i, endindex;
+       gltexture_t *glt;
+       endindex = Mem_ExpandableArray_IndexRange(&texturearray);
+       for (i = 0;i < endindex;i++)
+       {
+               glt = (gltexture_t *) Mem_ExpandableArray_RecordAtIndex(&texturearray, i);
+               if (!glt || !(glt->flags & TEXF_RENDERTARGET))
+                       continue;
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       {
+                               HRESULT d3dresult;
+                               if (glt->tiledepth > 1)
+                               {
+                                       if (FAILED(d3dresult = IDirect3DDevice9_CreateVolumeTexture(vid_d3d9dev, glt->tilewidth, glt->tileheight, glt->tiledepth, glt->miplevels, glt->d3dusage, (D3DFORMAT)glt->d3dformat, (D3DPOOL)glt->d3dpool, (IDirect3DVolumeTexture9 **)&glt->d3dtexture, NULL)))
+                                               Sys_Error("IDirect3DDevice9_CreateVolumeTexture failed!");
+                               }
+                               else if (glt->sides == 6)
+                               {
+                                       if (FAILED(d3dresult = IDirect3DDevice9_CreateCubeTexture(vid_d3d9dev, glt->tilewidth, glt->miplevels, glt->d3dusage, (D3DFORMAT)glt->d3dformat, (D3DPOOL)glt->d3dpool, (IDirect3DCubeTexture9 **)&glt->d3dtexture, NULL)))
+                                               Sys_Error("IDirect3DDevice9_CreateCubeTexture failed!");
+                               }
+                               else
+                               {
+                                       if (FAILED(d3dresult = IDirect3DDevice9_CreateTexture(vid_d3d9dev, glt->tilewidth, glt->tileheight, glt->miplevels, glt->d3dusage, (D3DFORMAT)glt->d3dformat, (D3DPOOL)glt->d3dpool, (IDirect3DTexture9 **)&glt->d3dtexture, NULL)))
+                                               Sys_Error("IDirect3DDevice9_CreateTexture failed!");
+                               }
+                       }
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
+       }
+}
+
+
 void R_Textures_Init (void)
 {
        Cmd_AddCommand("gl_texturemode", &GL_TextureMode_f, "set texture filtering mode (GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, etc); an additional argument 'force' forces the texture mode even in cases where it may not be appropriate");
@@ -590,7 +800,7 @@ void R_Textures_Init (void)
        Cvar_RegisterVariable (&gl_texturecompression_reflectmask);
        Cvar_RegisterVariable (&gl_nopartialtextureupdates);
 
-       R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap, NULL, NULL);
+       R_RegisterModule("R_Textures", r_textures_start, r_textures_shutdown, r_textures_newmap, r_textures_devicelost, r_textures_devicerestored);
 }
 
 void R_Textures_Frame (void)
@@ -623,23 +833,35 @@ void R_Textures_Frame (void)
 
                Cvar_SetValueQuick(&gl_texture_anisotropy, old_aniso);
 
-               CHECKGLERROR
-               GL_ActiveTexture(0);
-               for (pool = gltexturepoolchain;pool;pool = pool->next)
+               switch(vid.renderpath)
                {
-                       for (glt = pool->gltchain;glt;glt = glt->chain)
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       GL_ActiveTexture(0);
+                       for (pool = gltexturepoolchain;pool;pool = pool->next)
                        {
-                               // only update already uploaded images
-                               if (glt->texnum && (glt->flags & TEXF_MIPMAP) == TEXF_MIPMAP)
+                               for (glt = pool->gltchain;glt;glt = glt->chain)
                                {
-                                       oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
+                                       // only update already uploaded images
+                                       if (glt->texnum && (glt->flags & TEXF_MIPMAP) == TEXF_MIPMAP)
+                                       {
+                                               oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
 
-                                       qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
-                                       qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAX_ANISOTROPY_EXT, old_aniso);CHECKGLERROR
+                                               qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
+                                               qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAX_ANISOTROPY_EXT, old_aniso);CHECKGLERROR
 
-                                       qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
+                                               qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
+                                       }
                                }
                        }
+                       break;
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
+                       break;
                }
        }
 }
@@ -753,12 +975,24 @@ static void R_Upload(gltexture_t *glt, const unsigned char *data, int fragx, int
        const unsigned char *prevbuffer;
        prevbuffer = data;
 
-       CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
 
-       // we need to restore the texture binding after finishing the upload
-       GL_ActiveTexture(0);
-       oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
-       qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
+               // we need to restore the texture binding after finishing the upload
+               GL_ActiveTexture(0);
+               oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
+               qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               break;
+       }
 
        // these are rounded up versions of the size to do better resampling
        if (vid.support.arb_texture_non_power_of_two || glt->texturetype == GLTEXTURETYPE_RECTANGLE)
@@ -794,16 +1028,42 @@ static void R_Upload(gltexture_t *glt, const unsigned char *data, int fragx, int
        if ((glt->flags & (TEXF_MIPMAP | TEXF_PICMIP)) == 0 && glt->inputwidth == glt->tilewidth && glt->inputheight == glt->tileheight && glt->inputdepth == glt->tiledepth && (fragx != 0 || fragy != 0 || fragwidth != glt->tilewidth || fragheight != glt->tileheight))
        {
                // update a portion of the image
-               switch(glt->texturetype)
+               if (glt->texturetype != GLTEXTURETYPE_2D)
+                       Sys_Error("R_Upload: partial update of type other than 2D");
+               switch(vid.renderpath)
                {
-               case GLTEXTURETYPE_2D:
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
                        qglTexSubImage2D(GL_TEXTURE_2D, 0, fragx, fragy, fragwidth, fragheight, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                       qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
                        break;
-               case GLTEXTURETYPE_3D:
-                       qglTexSubImage3D(GL_TEXTURE_3D, 0, fragx, fragy, fragz, fragwidth, fragheight, fragdepth, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       {
+                               RECT d3drect;
+                               D3DLOCKED_RECT d3dlockedrect;
+                               int y;
+                               memset(&d3drect, 0, sizeof(d3drect));
+                               d3drect.left = fragx;
+                               d3drect.top = fragy;
+                               d3drect.right = fragx+fragwidth;
+                               d3drect.bottom = fragy+fragheight;
+                               if (IDirect3DTexture9_LockRect((IDirect3DTexture9*)glt->d3dtexture, 0, &d3dlockedrect, &d3drect, 0) == D3D_OK && d3dlockedrect.pBits)
+                               {
+                                       for (y = 0;y < fragheight;y++)
+                                               memcpy((unsigned char *)d3dlockedrect.pBits + d3dlockedrect.Pitch * y, (unsigned char *)prevbuffer + fragwidth*glt->bytesperpixel * y, fragwidth*glt->bytesperpixel);
+                                       IDirect3DTexture9_UnlockRect((IDirect3DTexture9*)glt->d3dtexture, 0);
+                               }
+                       }
+#endif
                        break;
-               default:
-                       Host_Error("R_Upload: partial update of type other than 2D");
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
                        break;
                }
        }
@@ -828,79 +1088,241 @@ static void R_Upload(gltexture_t *glt, const unsigned char *data, int fragx, int
                        }
                }
                mip = 0;
-               if (qglGetCompressedTexImageARB)
+               switch(vid.renderpath)
                {
-                       if (gl_texturecompression.integer >= 2)
-                               qglHint(GL_TEXTURE_COMPRESSION_HINT_ARB, GL_NICEST);
-                       else
-                               qglHint(GL_TEXTURE_COMPRESSION_HINT_ARB, GL_FASTEST);
-                       CHECKGLERROR
-               }
-               switch(glt->texturetype)
-               {
-               case GLTEXTURETYPE_2D:
-                       qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
-                       if (glt->flags & TEXF_MIPMAP)
-                       {
-                               while (width > 1 || height > 1 || depth > 1)
-                               {
-                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
-                                       prevbuffer = resizebuffer;
-                                       qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
-                               }
-                       }
-                       break;
-               case GLTEXTURETYPE_3D:
-                       qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
-                       if (glt->flags & TEXF_MIPMAP)
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       if (qglGetCompressedTexImageARB)
                        {
-                               while (width > 1 || height > 1 || depth > 1)
-                               {
-                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
-                                       prevbuffer = resizebuffer;
-                                       qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
-                               }
+                               if (gl_texturecompression.integer >= 2)
+                                       qglHint(GL_TEXTURE_COMPRESSION_HINT_ARB, GL_NICEST);
+                               else
+                                       qglHint(GL_TEXTURE_COMPRESSION_HINT_ARB, GL_FASTEST);
+                               CHECKGLERROR
                        }
-                       break;
-               case GLTEXTURETYPE_CUBEMAP:
-                       // convert and upload each side in turn,
-                       // from a continuous block of input texels
-                       texturebuffer = (unsigned char *)prevbuffer;
-                       for (i = 0;i < 6;i++)
+                       switch(glt->texturetype)
                        {
-                               prevbuffer = texturebuffer;
-                               texturebuffer += glt->inputwidth * glt->inputheight * glt->inputdepth * glt->textype->inputbytesperpixel;
-                               if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
-                               {
-                                       Image_Resample32(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, r_lerpimages.integer);
-                                       prevbuffer = resizebuffer;
-                               }
-                               // picmip/max_size
-                               while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
+                       case GLTEXTURETYPE_2D:
+                               qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                               if (glt->flags & TEXF_MIPMAP)
                                {
-                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth);
-                                       prevbuffer = resizebuffer;
+                                       while (width > 1 || height > 1 || depth > 1)
+                                       {
+                                               Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
+                                               prevbuffer = resizebuffer;
+                                               qglTexImage2D(GL_TEXTURE_2D, mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                                       }
                                }
-                               mip = 0;
-                               qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                               break;
+                       case GLTEXTURETYPE_3D:
+                               qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
                                if (glt->flags & TEXF_MIPMAP)
                                {
                                        while (width > 1 || height > 1 || depth > 1)
                                        {
                                                Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
                                                prevbuffer = resizebuffer;
-                                               qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                                               qglTexImage3D(GL_TEXTURE_3D, mip++, glt->glinternalformat, width, height, depth, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
                                        }
                                }
+                               break;
+                       case GLTEXTURETYPE_CUBEMAP:
+                               // convert and upload each side in turn,
+                               // from a continuous block of input texels
+                               texturebuffer = (unsigned char *)prevbuffer;
+                               for (i = 0;i < 6;i++)
+                               {
+                                       prevbuffer = texturebuffer;
+                                       texturebuffer += glt->inputwidth * glt->inputheight * glt->inputdepth * glt->textype->inputbytesperpixel;
+                                       if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
+                                       {
+                                               Image_Resample32(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, r_lerpimages.integer);
+                                               prevbuffer = resizebuffer;
+                                       }
+                                       // picmip/max_size
+                                       while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
+                                       {
+                                               Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth);
+                                               prevbuffer = resizebuffer;
+                                       }
+                                       mip = 0;
+                                       qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                                       if (glt->flags & TEXF_MIPMAP)
+                                       {
+                                               while (width > 1 || height > 1 || depth > 1)
+                                               {
+                                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
+                                                       prevbuffer = resizebuffer;
+                                                       qglTexImage2D(cubemapside[i], mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, prevbuffer);CHECKGLERROR
+                                               }
+                                       }
+                               }
+                               break;
+                       case GLTEXTURETYPE_RECTANGLE:
+                               qglTexImage2D(GL_TEXTURE_RECTANGLE_ARB, mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, NULL);CHECKGLERROR
+                               break;
                        }
+                       GL_SetupTextureParameters(glt->flags, glt->textype->textype, glt->texturetype);
+                       qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
                        break;
-               case GLTEXTURETYPE_RECTANGLE:
-                       qglTexImage2D(GL_TEXTURE_RECTANGLE_ARB, mip++, glt->glinternalformat, width, height, 0, glt->glformat, glt->gltype, NULL);CHECKGLERROR
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       if (!(glt->flags & TEXF_RENDERTARGET))
+                       {
+                               D3DLOCKED_RECT d3dlockedrect;
+                               D3DLOCKED_BOX d3dlockedbox;
+                               switch(glt->texturetype)
+                               {
+                               case GLTEXTURETYPE_2D:
+                                       if (IDirect3DTexture9_LockRect((IDirect3DTexture9*)glt->d3dtexture, mip, &d3dlockedrect, NULL, 0) == D3D_OK && d3dlockedrect.pBits)
+                                       {
+                                               if (prevbuffer)
+                                                       memcpy(d3dlockedrect.pBits, prevbuffer, width*height*glt->bytesperpixel);
+                                               else
+                                                       memset(d3dlockedrect.pBits, 255, width*height*glt->bytesperpixel);
+                                               IDirect3DTexture9_UnlockRect((IDirect3DTexture9*)glt->d3dtexture, mip);
+                                       }
+                                       mip++;
+                                       if ((glt->flags & TEXF_MIPMAP) && prevbuffer)
+                                       {
+                                               while (width > 1 || height > 1 || depth > 1)
+                                               {
+                                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
+                                                       prevbuffer = resizebuffer;
+                                                       if (IDirect3DTexture9_LockRect((IDirect3DTexture9*)glt->d3dtexture, mip, &d3dlockedrect, NULL, 0) == D3D_OK && d3dlockedrect.pBits)
+                                                       {
+                                                               memcpy(d3dlockedrect.pBits, prevbuffer, width*height*glt->bytesperpixel);
+                                                               IDirect3DTexture9_UnlockRect((IDirect3DTexture9*)glt->d3dtexture, mip);
+                                                       }
+                                                       mip++;
+                                               }
+                                       }
+                                       break;
+                               case GLTEXTURETYPE_3D:
+                                       if (IDirect3DVolumeTexture9_LockBox((IDirect3DVolumeTexture9*)glt->d3dtexture, mip, &d3dlockedbox, NULL, 0) == D3D_OK && d3dlockedbox.pBits)
+                                       {
+                                               // we are not honoring the RowPitch or SlicePitch, hopefully this works with all sizes
+                                               memcpy(d3dlockedbox.pBits, prevbuffer, width*height*depth*glt->bytesperpixel);
+                                               IDirect3DVolumeTexture9_UnlockBox((IDirect3DVolumeTexture9*)glt->d3dtexture, mip);
+                                       }
+                                       mip++;
+                                       if (glt->flags & TEXF_MIPMAP)
+                                       {
+                                               while (width > 1 || height > 1 || depth > 1)
+                                               {
+                                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
+                                                       prevbuffer = resizebuffer;
+                                                       if (IDirect3DVolumeTexture9_LockBox((IDirect3DVolumeTexture9*)glt->d3dtexture, mip, &d3dlockedbox, NULL, 0) == D3D_OK && d3dlockedbox.pBits)
+                                                       {
+                                                               // we are not honoring the RowPitch or SlicePitch, hopefully this works with all sizes
+                                                               memcpy(d3dlockedbox.pBits, prevbuffer, width*height*depth*glt->bytesperpixel);
+                                                               IDirect3DVolumeTexture9_UnlockBox((IDirect3DVolumeTexture9*)glt->d3dtexture, mip);
+                                                       }
+                                                       mip++;
+                                               }
+                                       }
+                                       break;
+                               case GLTEXTURETYPE_CUBEMAP:
+                                       // convert and upload each side in turn,
+                                       // from a continuous block of input texels
+                                       texturebuffer = (unsigned char *)prevbuffer;
+                                       for (i = 0;i < 6;i++)
+                                       {
+                                               prevbuffer = texturebuffer;
+                                               texturebuffer += glt->inputwidth * glt->inputheight * glt->inputdepth * glt->textype->inputbytesperpixel;
+                                               if (glt->inputwidth != width || glt->inputheight != height || glt->inputdepth != depth)
+                                               {
+                                                       Image_Resample32(prevbuffer, glt->inputwidth, glt->inputheight, glt->inputdepth, resizebuffer, width, height, depth, r_lerpimages.integer);
+                                                       prevbuffer = resizebuffer;
+                                               }
+                                               // picmip/max_size
+                                               while (width > glt->tilewidth || height > glt->tileheight || depth > glt->tiledepth)
+                                               {
+                                                       Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, glt->tilewidth, glt->tileheight, glt->tiledepth);
+                                                       prevbuffer = resizebuffer;
+                                               }
+                                               mip = 0;
+                                               if (IDirect3DCubeTexture9_LockRect((IDirect3DCubeTexture9*)glt->d3dtexture, (D3DCUBEMAP_FACES)i, mip, &d3dlockedrect, NULL, 0) == D3D_OK && d3dlockedrect.pBits)
+                                               {
+                                                       memcpy(d3dlockedrect.pBits, prevbuffer, width*height*glt->bytesperpixel);
+                                                       IDirect3DCubeTexture9_UnlockRect((IDirect3DCubeTexture9*)glt->d3dtexture, (D3DCUBEMAP_FACES)i, mip);
+                                               }
+                                               mip++;
+                                               if (glt->flags & TEXF_MIPMAP)
+                                               {
+                                                       while (width > 1 || height > 1 || depth > 1)
+                                                       {
+                                                               Image_MipReduce32(prevbuffer, resizebuffer, &width, &height, &depth, 1, 1, 1);
+                                                               prevbuffer = resizebuffer;
+                                                               if (IDirect3DCubeTexture9_LockRect((IDirect3DCubeTexture9*)glt->d3dtexture, (D3DCUBEMAP_FACES)i, mip, &d3dlockedrect, NULL, 0) == D3D_OK && d3dlockedrect.pBits)
+                                                               {
+                                                                       memcpy(d3dlockedrect.pBits, prevbuffer, width*height*glt->bytesperpixel);
+                                                                       IDirect3DCubeTexture9_UnlockRect((IDirect3DCubeTexture9*)glt->d3dtexture, (D3DCUBEMAP_FACES)i, mip);
+                                                               }
+                                                               mip++;
+                                                       }
+                                               }
+                                       }
+                                       break;
+                               case GLTEXTURETYPE_RECTANGLE:
+                                       Sys_Error("Direct3D does not have RECTANGLE textures\n");
+                                       break;
+                               }
+                       }
+                       glt->d3daddressw = 0;
+                       if (glt->flags & TEXF_CLAMP)
+                       {
+                               glt->d3daddressu = D3DTADDRESS_CLAMP;
+                               glt->d3daddressv = D3DTADDRESS_CLAMP;
+                               if (glt->tiledepth > 1)
+                                       glt->d3daddressw = D3DTADDRESS_CLAMP;
+                       }
+                       else
+                       {
+                               glt->d3daddressu = D3DTADDRESS_WRAP;
+                               glt->d3daddressv = D3DTADDRESS_WRAP;
+                               if (glt->tiledepth > 1)
+                                       glt->d3daddressw = D3DTADDRESS_WRAP;
+                       }
+                       glt->d3dmipmaplodbias = 0;
+                       glt->d3dmaxmiplevel = 0;
+                       glt->d3dmaxmiplevelfilter = d3d_filter_nomip ? 0 : glt->d3dmaxmiplevel;
+                       if (glt->flags & TEXF_FORCELINEAR)
+                       {
+                               glt->d3dminfilter = D3DTEXF_LINEAR;
+                               glt->d3dmagfilter = D3DTEXF_LINEAR;
+                               glt->d3dmipfilter = D3DTEXF_POINT;
+                       }
+                       else if (glt->flags & TEXF_FORCENEAREST)
+                       {
+                               glt->d3dminfilter = D3DTEXF_POINT;
+                               glt->d3dmagfilter = D3DTEXF_POINT;
+                               glt->d3dmipfilter = D3DTEXF_POINT;
+                       }
+                       else if (glt->flags & TEXF_MIPMAP)
+                       {
+                               glt->d3dminfilter = d3d_filter_mipmin;
+                               glt->d3dmagfilter = d3d_filter_mipmag;
+                               glt->d3dmipfilter = d3d_filter_mipmix;
+                       }
+                       else
+                       {
+                               glt->d3dminfilter = d3d_filter_flatmin;
+                               glt->d3dmagfilter = d3d_filter_flatmag;
+                               glt->d3dmipfilter = d3d_filter_flatmix;
+                       }
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
                        break;
                }
-               GL_SetupTextureParameters(glt->flags, glt->textype->textype, glt->texturetype);
        }
-       qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
 }
 
 static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *identifier, int width, int height, int depth, int sides, int flags, int miplevel, textype_t textype, int texturetype, const unsigned char *data, const unsigned int *palette)
@@ -909,6 +1331,7 @@ static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *iden
        gltexture_t *glt;
        gltexturepool_t *pool = (gltexturepool_t *)rtexturepool;
        textypeinfo_t *texinfo, *texinfo2;
+       unsigned char *temppixels = NULL;
 
        if (cls.state == ca_dedicated)
                return NULL;
@@ -937,6 +1360,17 @@ static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *iden
                return NULL;
        }
 
+       if (textype == TEXTYPE_RGBA)
+       {
+               // swap bytes
+               static int rgbaswapindices[4] = {2, 1, 0, 3};
+               textype = TEXTYPE_BGRA;
+               texinfo = R_GetTexTypeInfo(textype, flags);
+               temppixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * depth * sides * 4);
+               Image_CopyMux(temppixels, data, width, height*depth*sides, false, false, false, 4, 4, rgbaswapindices);
+               data = temppixels;
+       }
+
        // clear the alpha flag if the texture has no transparent pixels
        switch(textype)
        {
@@ -991,7 +1425,7 @@ static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *iden
                flags |= TEXF_ALPHA;
                break;
        default:
-               Host_Error("R_LoadTexture: unknown texture type");
+               Sys_Error("R_LoadTexture: unknown texture type");
        }
 
        texinfo2 = R_GetTexTypeInfo(textype, flags);
@@ -1027,18 +1461,83 @@ static rtexture_t *R_SetupTexture(rtexturepool_t *rtexturepool, const char *iden
        glt->updatecallback = NULL;
        glt->updatacallback_data = NULL;
 
-       GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->miplevel, glt->inputwidth, glt->inputheight, glt->inputdepth, &glt->tilewidth, &glt->tileheight, &glt->tiledepth);
+       GL_Texture_CalcImageSize(glt->texturetype, glt->flags, glt->miplevel, glt->inputwidth, glt->inputheight, glt->inputdepth, &glt->tilewidth, &glt->tileheight, &glt->tiledepth, &glt->miplevels);
 
        // upload the texture
        // data may be NULL (blank texture for dynamic rendering)
-       CHECKGLERROR
-       qglGenTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               qglGenTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       D3DFORMAT d3dformat;
+                       D3DPOOL d3dpool;
+                       DWORD d3dusage;
+                       HRESULT d3dresult;
+                       d3dusage = 0;
+                       d3dpool = D3DPOOL_MANAGED;
+                       if (flags & TEXF_RENDERTARGET)
+                       {
+                               d3dusage |= D3DUSAGE_RENDERTARGET;
+                               d3dpool = D3DPOOL_DEFAULT;
+                       }
+                       switch(textype)
+                       {
+                       case TEXTYPE_PALETTE: d3dformat = (flags & TEXF_ALPHA) ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8;break;
+                       case TEXTYPE_RGBA: d3dformat = (flags & TEXF_ALPHA) ? D3DFMT_A8B8G8R8 : D3DFMT_X8B8G8R8;break;
+                       case TEXTYPE_BGRA: d3dformat = (flags & TEXF_ALPHA) ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8;break;
+                       case TEXTYPE_COLORBUFFER: d3dformat = (flags & TEXF_ALPHA) ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8;break;
+                       case TEXTYPE_SHADOWMAP: d3dformat = D3DFMT_D16;d3dusage = D3DUSAGE_DEPTHSTENCIL;break; // note: can not use D3DUSAGE_RENDERTARGET here
+                       case TEXTYPE_ALPHA: d3dformat = D3DFMT_A8;break;
+                       default: d3dformat = D3DFMT_A8R8G8B8;Sys_Error("R_LoadTexture: unsupported texture type %i when picking D3DFMT", (int)textype);break;
+                       }
+                       glt->d3dformat = d3dformat;
+                       glt->d3dusage = d3dusage;
+                       glt->d3dpool = d3dpool;
+                       if (glt->tiledepth > 1)
+                       {
+                               if (FAILED(d3dresult = IDirect3DDevice9_CreateVolumeTexture(vid_d3d9dev, glt->tilewidth, glt->tileheight, glt->tiledepth, glt->miplevels, glt->d3dusage, (D3DFORMAT)glt->d3dformat, (D3DPOOL)glt->d3dpool, (IDirect3DVolumeTexture9 **)&glt->d3dtexture, NULL)))
+                                       Sys_Error("IDirect3DDevice9_CreateVolumeTexture failed!");
+                       }
+                       else if (glt->sides == 6)
+                       {
+                               if (FAILED(d3dresult = IDirect3DDevice9_CreateCubeTexture(vid_d3d9dev, glt->tilewidth, glt->miplevels, glt->d3dusage, (D3DFORMAT)glt->d3dformat, (D3DPOOL)glt->d3dpool, (IDirect3DCubeTexture9 **)&glt->d3dtexture, NULL)))
+                                       Sys_Error("IDirect3DDevice9_CreateCubeTexture failed!");
+                       }
+                       else
+                       {
+                               if (FAILED(d3dresult = IDirect3DDevice9_CreateTexture(vid_d3d9dev, glt->tilewidth, glt->tileheight, glt->miplevels, glt->d3dusage, (D3DFORMAT)glt->d3dformat, (D3DPOOL)glt->d3dpool, (IDirect3DTexture9 **)&glt->d3dtexture, NULL)))
+                                       Sys_Error("IDirect3DDevice9_CreateTexture failed!");
+                       }
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+
        R_Upload(glt, data, 0, 0, 0, glt->inputwidth, glt->inputheight, glt->inputdepth);
        if ((glt->flags & TEXF_ALLOWUPDATES) && gl_nopartialtextureupdates.integer)
                glt->bufferpixels = (unsigned char *)Mem_Alloc(texturemempool, glt->tilewidth*glt->tileheight*glt->tiledepth*glt->sides*glt->bytesperpixel);
 
+       // free any temporary processing buffer we allocated...
+       if (temppixels)
+               Mem_Free(temppixels);
+
        // texture converting and uploading can take a while, so make sure we're sending keepalives
-       CL_KeepaliveMessage(false);
+       // FIXME: this causes rendering during R_Shadow_DrawLights
+//     CL_KeepaliveMessage(false);
 
        return (rtexture_t *)glt;
 }
@@ -1065,7 +1564,7 @@ rtexture_t *R_LoadTextureRectangle(rtexturepool_t *rtexturepool, const char *ide
 
 static int R_ShadowMapTextureFlags(int precision, qboolean filter)
 {
-       int flags = TEXF_CLAMP;
+       int flags = TEXF_RENDERTARGET | TEXF_CLAMP;
        if (filter)
                flags |= TEXF_FORCELINEAR | TEXF_COMPARE;
        else
@@ -1425,17 +1924,54 @@ rtexture_t *R_LoadTextureDDSFile(rtexturepool_t *rtexturepool, const char *filen
        glt->tilewidth = mipwidth;
        glt->tileheight = mipheight;
        glt->tiledepth = 1;
+       glt->miplevels = dds_miplevels;
 
        // texture uploading can take a while, so make sure we're sending keepalives
        CL_KeepaliveMessage(false);
 
+       // create the texture object
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               CHECKGLERROR
+               GL_ActiveTexture(0);
+               oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
+               qglGenTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
+               qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               {
+                       D3DFORMAT d3dformat;
+                       D3DPOOL d3dpool;
+                       DWORD d3dusage;
+                       switch(textype)
+                       {
+                       case TEXTYPE_BGRA: d3dformat = (flags & TEXF_ALPHA) ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8;break;
+                       case TEXTYPE_DXT1: case TEXTYPE_DXT1A: d3dformat = D3DFMT_DXT1;break;
+                       case TEXTYPE_DXT3: d3dformat = D3DFMT_DXT3;break;
+                       case TEXTYPE_DXT5: d3dformat = D3DFMT_DXT5;break;
+                       default: d3dformat = D3DFMT_A8R8G8B8;Host_Error("R_LoadTextureDDSFile: unsupported texture type %i when picking D3DFMT", (int)textype);break;
+                       }
+                       d3dusage = 0;
+                       d3dpool = D3DPOOL_MANAGED;
+                       IDirect3DDevice9_CreateTexture(vid_d3d9dev, glt->tilewidth, glt->tileheight, glt->miplevels, d3dusage, d3dformat, d3dpool, (IDirect3DTexture9 **)&glt->d3dtexture, NULL);
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       }
+
        // upload the texture
        // we need to restore the texture binding after finishing the upload
-       CHECKGLERROR
-       GL_ActiveTexture(0);
-       oldbindtexnum = R_Mesh_TexBound(0, gltexturetypeenums[glt->texturetype]);
-       qglGenTextures(1, (GLuint *)&glt->texnum);CHECKGLERROR
-       qglBindTexture(gltexturetypeenums[glt->texturetype], glt->texnum);CHECKGLERROR
        mipcomplete = false;
 
        for (mip = 0;mip <= dds_miplevels;mip++) // <= to include the not-counted "largest" miplevel
@@ -1443,13 +1979,40 @@ rtexture_t *R_LoadTextureDDSFile(rtexturepool_t *rtexturepool, const char *filen
                mipsize = bytesperblock ? ((mipwidth+3)/4)*((mipheight+3)/4)*bytesperblock : mipwidth*mipheight*bytesperpixel;
                if (mippixels + mipsize > dds + ddssize)
                        break;
-               if (bytesperblock)
-               {
-                       qglCompressedTexImage2DARB(GL_TEXTURE_2D, mip, glt->glinternalformat, mipwidth, mipheight, 0, mipsize, mippixels);CHECKGLERROR
-               }
-               else
+               switch(vid.renderpath)
                {
-                       qglTexImage2D(GL_TEXTURE_2D, mip, glt->glinternalformat, mipwidth, mipheight, 0, glt->glformat, glt->gltype, mippixels);CHECKGLERROR
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       if (bytesperblock)
+                       {
+                               qglCompressedTexImage2DARB(GL_TEXTURE_2D, mip, glt->glinternalformat, mipwidth, mipheight, 0, mipsize, mippixels);CHECKGLERROR
+                       }
+                       else
+                       {
+                               qglTexImage2D(GL_TEXTURE_2D, mip, glt->glinternalformat, mipwidth, mipheight, 0, glt->glformat, glt->gltype, mippixels);CHECKGLERROR
+                       }
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       {
+                               D3DLOCKED_RECT d3dlockedrect;
+                               if (IDirect3DTexture9_LockRect((IDirect3DTexture9*)glt->d3dtexture, mip, &d3dlockedrect, NULL, 0) == D3D_OK && d3dlockedrect.pBits)
+                               {
+                                       memcpy(d3dlockedrect.pBits, mippixels, mipsize);
+                                       IDirect3DTexture9_UnlockRect((IDirect3DTexture9*)glt->d3dtexture, mip);
+                               }
+                               break;
+                       }
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
                }
                mippixels += mipsize;
                if (mipwidth <= 1 && mipheight <= 1)
@@ -1462,13 +2025,63 @@ rtexture_t *R_LoadTextureDDSFile(rtexturepool_t *rtexturepool, const char *filen
                if (mipheight > 1)
                        mipheight >>= 1;
        }
-       if (dds_miplevels >= 1 && !mipcomplete)
+
+       // after upload we have to set some parameters...
+       switch(vid.renderpath)
        {
-               // need to set GL_TEXTURE_MAX_LEVEL
-               qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAX_LEVEL, dds_miplevels - 1);CHECKGLERROR
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               if (dds_miplevels >= 1 && !mipcomplete)
+               {
+                       // need to set GL_TEXTURE_MAX_LEVEL
+                       qglTexParameteri(gltexturetypeenums[glt->texturetype], GL_TEXTURE_MAX_LEVEL, dds_miplevels - 1);CHECKGLERROR
+               }
+               GL_SetupTextureParameters(glt->flags, glt->textype->textype, glt->texturetype);
+               qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
+               break;
+       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+               glt->d3daddressw = 0;
+               if (glt->flags & TEXF_CLAMP)
+               {
+                       glt->d3daddressu = D3DTADDRESS_CLAMP;
+                       glt->d3daddressv = D3DTADDRESS_CLAMP;
+                       if (glt->tiledepth > 1)
+                               glt->d3daddressw = D3DTADDRESS_CLAMP;
+               }
+               else
+               {
+                       glt->d3daddressu = D3DTADDRESS_WRAP;
+                       glt->d3daddressv = D3DTADDRESS_WRAP;
+                       if (glt->tiledepth > 1)
+                               glt->d3daddressw = D3DTADDRESS_WRAP;
+               }
+               glt->d3dmipmaplodbias = 0;
+               glt->d3dmaxmiplevel = 0;
+               glt->d3dmaxmiplevelfilter = 0;
+               if (glt->flags & TEXF_MIPMAP)
+               {
+                       glt->d3dminfilter = d3d_filter_mipmin;
+                       glt->d3dmagfilter = d3d_filter_mipmag;
+                       glt->d3dmipfilter = d3d_filter_mipmix;
+               }
+               else
+               {
+                       glt->d3dminfilter = d3d_filter_flatmin;
+                       glt->d3dmagfilter = d3d_filter_flatmag;
+                       glt->d3dmipfilter = d3d_filter_flatmix;
+               }
+#endif
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
-       GL_SetupTextureParameters(glt->flags, glt->textype->textype, glt->texturetype);
-       qglBindTexture(gltexturetypeenums[glt->texturetype], oldbindtexnum);CHECKGLERROR
 
        Mem_Free(dds);
        return (rtexture_t *)glt;
@@ -1491,8 +2104,11 @@ void R_UpdateTexture(rtexture_t *rt, const unsigned char *data, int x, int y, in
                Host_Error("R_UpdateTexture: no data supplied");
        if (glt == NULL)
                Host_Error("R_UpdateTexture: no texture supplied");
-       if (!glt->texnum)
-               Host_Error("R_UpdateTexture: texture has not been uploaded yet");
+       if (!glt->texnum && !glt->d3dtexture)
+       {
+               Con_Printf("R_UpdateTexture: texture %p \"%s\" in pool %p has not been uploaded yet", glt, glt->identifier, glt->pool);
+               return;
+       }
        // update part of the texture
        if (glt->bufferpixels)
        {
index 0309c7f6b0cb1652419117736f8b6a0a7202a30f..5599b0204d512a16ed75241b5a309269cfb53744 100644 (file)
@@ -1221,19 +1221,19 @@ static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
 
        // upload r_vertexmesh_t array as a buffer
        if (mesh->vertexmesh && !mesh->vertexmeshbuffer)
-               mesh->vertexmeshbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexmesh, mesh->numverts * sizeof(*mesh->vertexmesh), loadmodel->name, false, false);
+               mesh->vertexmeshbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexmesh, mesh->numverts * sizeof(*mesh->vertexmesh), loadmodel->name, false, false, false);
 
        // upload r_vertexposition_t array as a buffer
        if (mesh->vertexposition && !mesh->vertexpositionbuffer)
-               mesh->vertexpositionbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexposition, mesh->numverts * sizeof(*mesh->vertexposition), loadmodel->name, false, false);
+               mesh->vertexpositionbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexposition, mesh->numverts * sizeof(*mesh->vertexposition), loadmodel->name, false, false, false);
 
        // upload short indices as a buffer
        if (mesh->element3s && !mesh->element3s_indexbuffer)
-               mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), loadmodel->name, true, false);
+               mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), loadmodel->name, true, false, true);
 
        // upload int indices as a buffer
        if (mesh->element3i && !mesh->element3i_indexbuffer && !mesh->element3s)
-               mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), loadmodel->name, true, false);
+               mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), loadmodel->name, true, false, false);
 
        // vertex buffer is several arrays and we put them in the same buffer
        //
@@ -1256,7 +1256,7 @@ static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
                if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
                if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
                if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
-               mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, "shadowmesh", false, false);
+               mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, "shadowmesh", false, false, false);
                Mem_Free(mem);
        }
 }
@@ -2782,19 +2782,19 @@ void Mod_BuildVBOs(void)
 
        // upload r_vertexmesh_t array as a buffer
        if (loadmodel->surfmesh.vertexmesh && !loadmodel->surfmesh.vertexmeshbuffer)
-               loadmodel->surfmesh.vertexmeshbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexmesh, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexmesh), loadmodel->name, false, false);
+               loadmodel->surfmesh.vertexmeshbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexmesh, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexmesh), loadmodel->name, false, false, false);
 
        // upload r_vertexposition_t array as a buffer
        if (loadmodel->surfmesh.vertexposition && !loadmodel->surfmesh.vertexpositionbuffer)
-               loadmodel->surfmesh.vertexpositionbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexposition, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexposition), loadmodel->name, false, false);
+               loadmodel->surfmesh.vertexpositionbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexposition, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexposition), loadmodel->name, false, false, false);
 
        // upload short indices as a buffer
        if (loadmodel->surfmesh.data_element3s && !loadmodel->surfmesh.data_element3s_indexbuffer)
-               loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false);
+               loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false, true);
 
        // upload int indices as a buffer
        if (loadmodel->surfmesh.data_element3i && !loadmodel->surfmesh.data_element3i_indexbuffer && !loadmodel->surfmesh.data_element3s)
-               loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false);
+               loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false, false);
 
        // only build a vbo if one has not already been created (this is important for brush models which load specially)
        // vertex buffer is several arrays and we put them in the same buffer
@@ -2822,7 +2822,7 @@ void Mod_BuildVBOs(void)
                if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
                if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
                if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
-               loadmodel->surfmesh.vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false);
+               loadmodel->surfmesh.vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false, false);
                Mem_Free(mem);
        }
 }
index 8b15a6ef46cc1978d3ff54161dfd733f6442eb4b..144cdc6662117d85d25de9866c4be9198b9783ef 100644 (file)
@@ -137,6 +137,7 @@ typedef struct r_meshbuffer_s
        size_t size;
        qboolean isindexbuffer;
        qboolean isdynamic;
+       qboolean isindex16;
        char name[MAX_QPATH];
 }
 r_meshbuffer_t;
index 2155596ba31e414ed496cccf13a0fd6ef20c18f4..ec0b84ef60103c9d449dec940822abc8316bc325 100644 (file)
@@ -140,6 +140,11 @@ demonstrated by the game Doom3.
 #include "portals.h"
 #include "image.h"
 
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+extern LPDIRECT3DDEVICE9 vid_d3d9dev;
+#endif
+
 extern void R_Shadow_EditLights_Init(void);
 
 typedef enum r_shadow_rendermode_e
@@ -250,6 +255,7 @@ skinframe_t *r_shadow_lightcorona;
 rtexture_t *r_shadow_shadowmaprectangletexture;
 rtexture_t *r_shadow_shadowmap2dtexture;
 rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
+rtexture_t *r_shadow_shadowmap2dcolortexture;
 rtexture_t *r_shadow_shadowmapvsdcttexture;
 int r_shadow_shadowmapsize; // changes for each light based on distance
 int r_shadow_shadowmaplod; // changes for each light based on distance
@@ -384,12 +390,11 @@ void R_Shadow_SetShadowMode(void)
        r_shadow_shadowmapsampler = false;
        r_shadow_shadowmappcf = 0;
        r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL;
-       switch(vid.renderpath)
+       if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
        {
-       case RENDERPATH_GL20:
-       case RENDERPATH_CGGL:
-               if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object)
+               switch(vid.renderpath)
                {
+               case RENDERPATH_GL20:
                        if(r_shadow_shadowmapfilterquality < 0)
                        {
                                if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather)
@@ -449,12 +454,20 @@ void R_Shadow_SetShadowMode(void)
                                r_shadow_shadowmapsampler = false;
                                r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
                        }
+                       break;
+               case RENDERPATH_CGGL:
+               case RENDERPATH_D3D9:
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
+                       r_shadow_shadowmapsampler = false;
+                       r_shadow_shadowmappcf = 1;
+                       r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D;
+                       break;
+               case RENDERPATH_GL13:
+                       break;
+               case RENDERPATH_GL11:
+                       break;
                }
-               break;
-       case RENDERPATH_GL13:
-               break;
-       case RENDERPATH_GL11:
-               break;
        }
 }
 
@@ -477,21 +490,14 @@ void R_Shadow_FreeShadowMaps(void)
 
        R_Shadow_SetShadowMode();
 
-       if (!vid.support.ext_framebuffer_object || !vid.support.arb_fragment_shader)
-               return;
+       R_Mesh_DestroyFramebufferObject(r_shadow_fborectangle);
 
-       CHECKGLERROR
+       R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d);
+       for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
+               R_Mesh_DestroyFramebufferObject(r_shadow_fbocubeside[i]);
 
-       if (r_shadow_fborectangle)
-               qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR
        r_shadow_fborectangle = 0;
-
-       if (r_shadow_fbo2d)
-               qglDeleteFramebuffersEXT(1, &r_shadow_fbo2d);CHECKGLERROR
        r_shadow_fbo2d = 0;
-       for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++)
-               if (r_shadow_fbocubeside[i])
-                       qglDeleteFramebuffersEXT(1, &r_shadow_fbocubeside[i]);CHECKGLERROR
        memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside));
 
        if (r_shadow_shadowmaprectangletexture)
@@ -507,11 +513,13 @@ void R_Shadow_FreeShadowMaps(void)
                        R_FreeTexture(r_shadow_shadowmapcubetexture[i]);
        memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
 
+       if (r_shadow_shadowmap2dcolortexture)
+               R_FreeTexture(r_shadow_shadowmap2dcolortexture);
+       r_shadow_shadowmap2dcolortexture = NULL;
+
        if (r_shadow_shadowmapvsdcttexture)
                R_FreeTexture(r_shadow_shadowmapvsdcttexture);
        r_shadow_shadowmapvsdcttexture = NULL;
-
-       CHECKGLERROR
 }
 
 void r_shadow_start(void)
@@ -524,6 +532,7 @@ void r_shadow_start(void)
        r_shadow_shadowmaprectangletexture = NULL;
        r_shadow_shadowmap2dtexture = NULL;
        memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture));
+       r_shadow_shadowmap2dcolortexture = NULL;
        r_shadow_shadowmapvsdcttexture = NULL;
        r_shadow_shadowmapmaxsize = 0;
        r_shadow_shadowmapsize = 0;
@@ -1338,30 +1347,28 @@ void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f,
                        tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris);
                r_refdef.stats.lights_dynamicshadowtriangles += tris;
                r_refdef.stats.lights_shadowtriangles += tris;
-               CHECKGLERROR
                if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL)
                {
                        // increment stencil if frontface is infront of depthbuffer
                        GL_CullFace(r_refdef.view.cullface_front);
-                       qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+                       R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
                        R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
                        // decrement stencil if backface is infront of depthbuffer
                        GL_CullFace(r_refdef.view.cullface_back);
-                       qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
+                       R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
                }
                else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
                {
                        // decrement stencil if backface is behind depthbuffer
                        GL_CullFace(r_refdef.view.cullface_front);
-                       qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
+                       R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
                        R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
                        // increment stencil if frontface is behind depthbuffer
                        GL_CullFace(r_refdef.view.cullface_back);
-                       qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
+                       R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
                }
                R_Mesh_PrepareVertices_Position_Arrays(outverts, shadowvertex3f);
                R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0);
-               CHECKGLERROR
        }
 }
 
@@ -1896,7 +1903,7 @@ void R_Shadow_ValidateCvars(void)
                Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0);
 }
 
-static const r_vertexposition_t resetvertexposition[3] = {{0, 0, 0}};
+//static const r_vertexposition_t resetvertexposition[3] = {{0, 0, 0}};
 
 void R_Shadow_RenderMode_Begin(void)
 {
@@ -1914,7 +1921,7 @@ void R_Shadow_RenderMode_Begin(void)
 
        CHECKGLERROR
        R_Mesh_ResetTextureState();
-       R_Mesh_PrepareVertices_Position(0, resetvertexposition, NULL);
+//     R_Mesh_PrepareVertices_Position(0, resetvertexposition, NULL);
        GL_BlendFunc(GL_ONE, GL_ZERO);
        GL_DepthRange(0, 1);
        GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
@@ -1945,6 +1952,9 @@ void R_Shadow_RenderMode_Begin(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL;
                break;
        case RENDERPATH_GL13:
@@ -1978,32 +1988,16 @@ void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight)
 
 void R_Shadow_RenderMode_Reset(void)
 {
-       CHECKGLERROR
-       if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE)
-       {
-               qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
-       }
-       if (vid.support.ext_framebuffer_object)
-       {
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
-       }
-#if 0
-       qglDrawBuffer(r_shadow_drawbuffer);CHECKGLERROR
-       qglReadBuffer(r_shadow_readbuffer);CHECKGLERROR
-#endif
+       R_Mesh_ResetRenderTargets();
        R_SetViewport(&r_refdef.view.viewport);
        GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]);
        R_Mesh_ResetTextureState();
-       R_Mesh_PrepareVertices_Position(0, resetvertexposition, NULL);
+//     R_Mesh_PrepareVertices_Position(0, resetvertexposition, NULL);
        GL_DepthRange(0, 1);
        GL_DepthTest(true);
        GL_DepthMask(false);
-       qglDepthFunc(GL_LEQUAL);CHECKGLERROR
+       GL_DepthFunc(GL_LEQUAL);
        GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
-       qglDisable(GL_STENCIL_TEST);CHECKGLERROR
-       qglStencilMask(255);CHECKGLERROR
-       qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
-       qglStencilFunc(GL_ALWAYS, 128, 255);CHECKGLERROR
        r_refdef.view.cullface_front = r_shadow_cullface_front;
        r_refdef.view.cullface_back = r_shadow_cullface_back;
        GL_CullFace(r_refdef.view.cullface_back);
@@ -2015,13 +2009,12 @@ void R_Shadow_RenderMode_Reset(void)
        r_shadow_usingshadowmapcube = false;
        r_shadow_usingshadowmap2d = false;
        r_shadow_usingshadowmaportho = false;
-       CHECKGLERROR
+       R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
 }
 
 void R_Shadow_ClearStencil(void)
 {
-       CHECKGLERROR
-       GL_Clear(GL_STENCIL_BUFFER_BIT);
+       GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128);
        r_refdef.stats.lights_clears++;
 }
 
@@ -2030,47 +2023,24 @@ void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass)
        r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail;
        if (r_shadow_rendermode == mode)
                return;
-       CHECKGLERROR
        R_Shadow_RenderMode_Reset();
+       GL_DepthFunc(GL_LESS);
        GL_ColorMask(0, 0, 0, 0);
        GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR
+       GL_CullFace(GL_NONE);
        R_SetupShader_DepthOrShadow();
-       qglDepthFunc(GL_LESS);CHECKGLERROR
-       qglEnable(GL_STENCIL_TEST);CHECKGLERROR
        r_shadow_rendermode = mode;
        switch(mode)
        {
        default:
                break;
-       case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
-               GL_CullFace(GL_NONE);
-               qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
-               qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
-               break;
-       case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
-               GL_CullFace(GL_NONE);
-               qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
-               qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
-               break;
        case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE:
-               GL_CullFace(GL_NONE);
-               qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
-               qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
-               qglStencilMask(255);CHECKGLERROR
-               qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
-               qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
-               qglStencilMask(255);CHECKGLERROR
-               qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+       case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL:
+               R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255);
                break;
        case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE:
-               GL_CullFace(GL_NONE);
-               qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR
-               qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR
-               qglStencilMask(255);CHECKGLERROR
-               qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
-               qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR
-               qglStencilMask(255);CHECKGLERROR
-               qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
+       case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL:
+               R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255);
                break;
        }
 }
@@ -2097,52 +2067,67 @@ static void R_Shadow_MakeVSDCT(void)
 
 static void R_Shadow_MakeShadowMap(int side, int size)
 {
-       int status;
        switch (r_shadow_shadowmode)
        {
        case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
                if (r_shadow_shadowmap2dtexture) return;
                r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler);
-               qglGenFramebuffersEXT(1, &r_shadow_fbo2d);CHECKGLERROR
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR
-               qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_shadowmap2dtexture), 0);CHECKGLERROR
+               r_shadow_shadowmap2dcolortexture = NULL;
+               switch(vid.renderpath)
+               {
+#ifdef SUPPORTD3D
+               case RENDERPATH_D3D9:
+                       r_shadow_shadowmap2dcolortexture = R_LoadTexture2D(r_shadow_texturepool, "shadowmaprendertarget", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), NULL, TEXTYPE_BGRA, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL);
+                       r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
+                       break;
+#endif
+               default:
+                       r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2dtexture, NULL, NULL, NULL, NULL);
+                       break;
+               }
                break;
        case R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE:
                if (r_shadow_shadowmaprectangletexture) return;
                r_shadow_shadowmaprectangletexture = R_LoadTextureShadowMapRectangle(r_shadow_texturepool, "shadowmap", size*2, size*3, r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler);
-               qglGenFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR
-               qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_RECTANGLE_ARB, R_GetTexture(r_shadow_shadowmaprectangletexture), 0);CHECKGLERROR
+               r_shadow_fborectangle = R_Mesh_CreateFramebufferObject(r_shadow_shadowmaprectangletexture, NULL, NULL, NULL, NULL);
                break;
        case R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE:
                if (r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]) return;
                r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod] = R_LoadTextureShadowMapCube(r_shadow_texturepool, "shadowmapcube", size, r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler);
-               qglGenFramebuffersEXT(1, &r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR
-               qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + side, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR
+               // special trick to get an empty fbo we configure ourselves...
+               r_shadow_fbocubeside[r_shadow_shadowmaplod] = R_Mesh_CreateFramebufferObject(NULL, NULL, NULL, NULL, NULL);
+               R_Mesh_SetRenderTargets(r_shadow_fbocubeside[r_shadow_shadowmaplod], NULL, NULL, NULL, NULL, NULL);
+               if (qglFramebufferTexture2DEXT)
+                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + side, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR
                break;
        default:
                return;
        }
+
        // render depth into the fbo, do not render color at all
-       qglDrawBuffer(GL_NONE);CHECKGLERROR
-       qglReadBuffer(GL_NONE);CHECKGLERROR
-       status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
-       if (status != GL_FRAMEBUFFER_COMPLETE_EXT && (r_shadow_shadowmapping.integer || r_shadow_deferred.integer))
-       {
-               Con_Printf("R_Shadow_MakeShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
-               Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
-               Cvar_SetValueQuick(&r_shadow_deferred, 0);
+       // validate the fbo now
+       if (qglDrawBuffer)
+       {
+               int status;
+               qglDrawBuffer(GL_NONE);CHECKGLERROR
+               qglReadBuffer(GL_NONE);CHECKGLERROR
+               status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
+               if (status != GL_FRAMEBUFFER_COMPLETE_EXT && (r_shadow_shadowmapping.integer || r_shadow_deferred.integer))
+               {
+                       Con_Printf("R_Shadow_MakeShadowMap: glCheckFramebufferStatusEXT returned %i\n", status);
+                       Cvar_SetValueQuick(&r_shadow_shadowmapping, 0);
+                       Cvar_SetValueQuick(&r_shadow_deferred, 0);
+               }
        }
 }
 
+static float testcolor[4] = {0,1,0,1};
 void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
 {
        float nearclip, farclip, bias;
        r_viewport_t viewport;
        int flipped;
        GLuint fbo = 0;
-       CHECKGLERROR
        nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius;
        farclip = 1.0f;
        bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius;
@@ -2163,7 +2148,6 @@ void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
                        R_Shadow_MakeVSDCT();
                if (!r_shadow_shadowmap2dtexture)
                        R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
-               CHECKGLERROR
                if (r_shadow_shadowmap2dtexture) fbo = r_shadow_fbo2d;
                r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture);
                r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture);
@@ -2180,7 +2164,6 @@ void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
                        R_Shadow_MakeVSDCT();
                if (!r_shadow_shadowmaprectangletexture)
                        R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize);
-               CHECKGLERROR
                if(r_shadow_shadowmaprectangletexture) fbo = r_shadow_fborectangle;
                r_shadow_shadowmap_texturescale[0] = 1.0f;
                r_shadow_shadowmap_texturescale[1] = 1.0f;
@@ -2195,7 +2178,6 @@ void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
                // simple cube approach
                if (!r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])
                        R_Shadow_MakeShadowMap(side, size);
-               CHECKGLERROR
                if (r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]) fbo = r_shadow_fbocubeside[r_shadow_shadowmaplod];
                r_shadow_shadowmap_texturescale[0] = 0.0f;
                r_shadow_shadowmap_texturescale[1] = 0.0f;
@@ -2208,20 +2190,14 @@ void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size)
        R_Shadow_RenderMode_Reset();
        if (fbo)
        {
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);CHECKGLERROR
+               R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, r_shadow_shadowmap2dcolortexture, NULL, NULL, NULL);
                R_SetupShader_DepthOrShadow();
        }
        else
-       {
                R_SetupShader_ShowDepth();
-               qglClearColor(1,1,1,1);CHECKGLERROR
-       }
-       CHECKGLERROR
        GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
        GL_DepthMask(true);
        GL_DepthTest(true);
-       qglClearDepth(1);
-       CHECKGLERROR
 
 init_done:
        R_SetViewport(&viewport);
@@ -2232,29 +2208,68 @@ init_done:
                flipped = (side & 1) ^ (side >> 2);
                r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front;
                r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back;
-               GL_CullFace(r_refdef.view.cullface_back);
-               if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
+               switch(vid.renderpath)
                {
-                       // get tightest scissor rectangle that encloses all viewports in the clear mask
-                       int x1 = clear & 0x15 ? 0 : size;
-                       int x2 = clear & 0x2A ? 2 * size : size;
-                       int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
-                       int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
-                       GL_Scissor(x1, y1, x2 - x1, y2 - y1);
-                       GL_Clear(GL_DEPTH_BUFFER_BIT);
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       GL_CullFace(r_refdef.view.cullface_back);
+                       // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once
+                       if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask
+                       {
+                               // get tightest scissor rectangle that encloses all viewports in the clear mask
+                               int x1 = clear & 0x15 ? 0 : size;
+                               int x2 = clear & 0x2A ? 2 * size : size;
+                               int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size);
+                               int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size);
+                               GL_Scissor(x1, y1, x2 - x1, y2 - y1);
+                               GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
+                       }
+                       GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
+                       break;
+               case RENDERPATH_D3D9:
+                       // completely different meaning than in OpenGL path
+                       r_shadow_shadowmap_parameters[1] = 0;
+                       r_shadow_shadowmap_parameters[3] = -bias;
+                       // we invert the cull mode because we flip the projection matrix
+                       // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided...
+                       GL_CullFace(r_refdef.view.cullface_front);
+                       // D3D considers it an error to use a scissor larger than the viewport...  clear just this view
+                       GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
+                       if (r_shadow_shadowmapsampler)
+                       {
+                               GL_ColorMask(0,0,0,0);
+                               if (clear)
+                                       GL_Clear(GL_DEPTH_BUFFER_BIT, testcolor, 1.0f, 0);
+                       }
+                       else
+                       {
+                               GL_ColorMask(1,1,1,1);
+                               if (clear)
+                                       GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, testcolor, 1.0f, 0);
+                       }
+                       break;
+               case RENDERPATH_D3D10:
+               case RENDERPATH_D3D11:
+                       // D3D considers it an error to use a scissor larger than the viewport...  clear just this view
+                       GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
+                       GL_ColorMask(0,0,0,0);
+                       if (clear)
+                               GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
+                       break;
                }
-               GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
                break;
        case R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE:
-               qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + side, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR
+               if (qglFramebufferTexture2DEXT)
+                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + side, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR
                GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
                if (clear)
-                       GL_Clear(GL_DEPTH_BUFFER_BIT);
+                       GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
                break;
        default:
                break;
        }
-       CHECKGLERROR
 }
 
 void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping)
@@ -2266,27 +2281,13 @@ void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qb
                r_shadow_lightscissor[2] = r_refdef.view.viewport.width;
                r_shadow_lightscissor[3] = r_refdef.view.viewport.height;
        }
-       CHECKGLERROR
        R_Shadow_RenderMode_Reset();
        GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
        if (!transparent)
-       {
-               qglDepthFunc(GL_EQUAL);CHECKGLERROR
-       }
-       if (stenciltest)
-       {
-               qglEnable(GL_STENCIL_TEST);CHECKGLERROR
-               // only draw light where this geometry was already rendered AND the
-               // stencil is 128 (values other than this mean shadow)
-               qglStencilFunc(GL_EQUAL, 128, 255);CHECKGLERROR
-       }
-       r_shadow_rendermode = r_shadow_lightingrendermode;
+               GL_DepthFunc(GL_EQUAL);
        // do global setup needed for the chosen lighting mode
        if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL)
-       {
                GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0);
-               CHECKGLERROR
-       }
        if (shadowmapping)
        {
                switch (r_shadow_shadowmode)
@@ -2304,8 +2305,13 @@ void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qb
                        break;
                }
        }
-       //R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
-       CHECKGLERROR
+       r_shadow_rendermode = r_shadow_lightingrendermode;
+       // only draw light where this geometry was already rendered AND the
+       // stencil is 128 (values other than this mean shadow)
+       if (stenciltest)
+               R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
+       else
+               R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
 }
 
 static const unsigned short bboxelements[36] =
@@ -2335,59 +2341,51 @@ void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadow
        int i;
        float vertex3f[8*3];
        const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld;
-       CHECKGLERROR
+// do global setup needed for the chosen lighting mode
        R_Shadow_RenderMode_Reset();
        r_shadow_rendermode = r_shadow_lightingrendermode;
-       // do global setup needed for the chosen lighting mode
+       R_EntityMatrix(&identitymatrix);
+       GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
+       // only draw light where this geometry was already rendered AND the
+       // stencil is 128 (values other than this mean shadow)
+       R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
+       R_Mesh_SetRenderTargets(r_shadow_prepasslightingfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
+
+       if (shadowmapping)
        {
-               R_EntityMatrix(&identitymatrix);
-               GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
-               if (stenciltest)
-               {
-                       qglEnable(GL_STENCIL_TEST);CHECKGLERROR
-                       // only draw light where this geometry was already rendered AND the
-                       // stencil is 128 (values other than this mean shadow)
-                       qglStencilFunc(GL_EQUAL, 128, 255);CHECKGLERROR
-               }
-               qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_prepasslightingfbo);CHECKGLERROR
-               if (shadowmapping)
+               switch (r_shadow_shadowmode)
                {
-                       switch (r_shadow_shadowmode)
-                       {
-                       case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
-                               r_shadow_usingshadowmap2d = true;
-                               break;
-                       case R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE:
-                               r_shadow_usingshadowmaprect = true;
-                               break;
-                       case R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE:
-                               r_shadow_usingshadowmapcube = true;
-                               break;
-                       default:
-                               break;
-                       }
+               case R_SHADOW_SHADOWMODE_SHADOWMAP2D:
+                       r_shadow_usingshadowmap2d = true;
+                       break;
+               case R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE:
+                       r_shadow_usingshadowmaprect = true;
+                       break;
+               case R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE:
+                       r_shadow_usingshadowmapcube = true;
+                       break;
+               default:
+                       break;
                }
-
-               // render the lighting
-               R_SetupShader_DeferredLight(rsurface.rtlight);
-               for (i = 0;i < 8;i++)
-                       Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
-               CHECKGLERROR
-               GL_ColorMask(1,1,1,1);
-               GL_DepthMask(false);
-               GL_DepthRange(0, 1);
-               GL_PolygonOffset(0, 0);
-               GL_DepthTest(true);
-               qglDepthFunc(GL_GREATER);CHECKGLERROR
-               GL_CullFace(r_refdef.view.cullface_back);
-               R_Mesh_PrepareVertices_Position_Arrays(8, vertex3f);
-               R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
        }
+
+       // render the lighting
+       R_SetupShader_DeferredLight(rsurface.rtlight);
+       for (i = 0;i < 8;i++)
+               Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3);
+       GL_ColorMask(1,1,1,1);
+       GL_DepthMask(false);
+       GL_DepthRange(0, 1);
+       GL_PolygonOffset(0, 0);
+       GL_DepthTest(true);
+       GL_DepthFunc(GL_GREATER);
+       GL_CullFace(r_refdef.view.cullface_back);
+       R_Mesh_PrepareVertices_Position_Arrays(8, vertex3f);
+       R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
 }
 
 void R_Shadow_RenderMode_VisibleShadowVolumes(void)
 {
-       CHECKGLERROR
        R_Shadow_RenderMode_Reset();
        GL_BlendFunc(GL_ONE, GL_ONE);
        GL_DepthRange(0, 1);
@@ -2400,27 +2398,19 @@ void R_Shadow_RenderMode_VisibleShadowVolumes(void)
 
 void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent)
 {
-       CHECKGLERROR
        R_Shadow_RenderMode_Reset();
        GL_BlendFunc(GL_ONE, GL_ONE);
        GL_DepthRange(0, 1);
        GL_DepthTest(r_showlighting.integer < 2);
        GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1);
        if (!transparent)
-       {
-               qglDepthFunc(GL_EQUAL);CHECKGLERROR
-       }
-       if (stenciltest)
-       {
-               qglEnable(GL_STENCIL_TEST);CHECKGLERROR
-               qglStencilFunc(GL_EQUAL, 128, 255);CHECKGLERROR
-       }
+               GL_DepthFunc(GL_EQUAL);
+       R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255);
        r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING;
 }
 
 void R_Shadow_RenderMode_End(void)
 {
-       CHECKGLERROR
        R_Shadow_RenderMode_Reset();
        R_Shadow_RenderMode_ActiveLight(NULL);
        GL_DepthMask(true);
@@ -2558,6 +2548,16 @@ qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs)
        r_shadow_lightscissor[2] = ix2 - ix1;
        r_shadow_lightscissor[3] = iy2 - iy1;
 
+       // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
+       switch(vid.renderpath)
+       {
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
+               r_shadow_lightscissor[1] = vid.height - r_shadow_lightscissor[1] - r_shadow_lightscissor[3];
+               break;
+       }
+
        r_refdef.stats.lights_scissored++;
        return false;
 }
@@ -2743,16 +2743,12 @@ static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, cons
 static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale)
 {
        // ARB2 GLSL shader path (GFFX5200, Radeon 9500)
-       R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist);
+       R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL);
        if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
-       {
-               qglDepthFunc(GL_EQUAL);CHECKGLERROR
-       }
+               GL_DepthFunc(GL_EQUAL);
        RSurf_DrawBatch();
        if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
-       {
-               qglDepthFunc(GL_LEQUAL);CHECKGLERROR
-       }
+               GL_DepthFunc(GL_LEQUAL);
 }
 
 static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2)
@@ -2934,7 +2930,26 @@ void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **textures
        if(negated)
        {
                VectorNegate(lightcolor, lightcolor);
-               qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
        RSurf_SetupDepthAndCulling();
        switch (r_shadow_rendermode)
@@ -2957,7 +2972,28 @@ void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **textures
                break;
        }
        if(negated)
-               qglBlendEquationEXT(GL_FUNC_ADD_EXT);
+       {
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL11:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL20:
+               case RENDERPATH_CGGL:
+                       qglBlendEquationEXT(GL_FUNC_ADD_EXT);
+                       break;
+               case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                       IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
+#endif
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
+       }
 }
 
 void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, int shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
@@ -3372,21 +3408,21 @@ void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, co
                        {
                                // increment stencil if frontface is infront of depthbuffer
                                GL_CullFace(r_refdef.view.cullface_back);
-                               qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR
+                               R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255);
                                R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
                                // decrement stencil if backface is infront of depthbuffer
                                GL_CullFace(r_refdef.view.cullface_front);
-                               qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR
+                               R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255);
                        }
                        else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL)
                        {
                                // decrement stencil if backface is behind depthbuffer
                                GL_CullFace(r_refdef.view.cullface_front);
-                               qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR
+                               R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255);
                                R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
                                // increment stencil if frontface is behind depthbuffer
                                GL_CullFace(r_refdef.view.cullface_back);
-                               qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR
+                               R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255);
                        }
                        R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset);
                }
@@ -3962,12 +3998,10 @@ void R_Shadow_DrawLight(rtlight_t *rtlight)
 
 static void R_Shadow_FreeDeferred(void)
 {
-       if (r_shadow_prepassgeometryfbo)
-               qglDeleteFramebuffersEXT(1, &r_shadow_prepassgeometryfbo);CHECKGLERROR
+       R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo);
        r_shadow_prepassgeometryfbo = 0;
 
-       if (r_shadow_prepasslightingfbo)
-               qglDeleteFramebuffersEXT(1, &r_shadow_prepasslightingfbo);CHECKGLERROR
+       R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingfbo);
        r_shadow_prepasslightingfbo = 0;
 
        if (r_shadow_prepassgeometrydepthtexture)
@@ -3996,6 +4030,7 @@ void R_Shadow_DrawPrepass(void)
        dlight_t *light;
        size_t range;
        entity_render_t *ent;
+       float clearcolor[4];
 
        GL_AlphaTest(false);
        R_Mesh_ResetTextureState();
@@ -4004,9 +4039,11 @@ void R_Shadow_DrawPrepass(void)
        GL_BlendFunc(GL_ONE, GL_ZERO);
        GL_Color(1,1,1,1);
        GL_DepthTest(true);
-       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_prepassgeometryfbo);CHECKGLERROR
-       qglClearColor(0.5f,0.5f,0.5f,1.0f);CHECKGLERROR
-       GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);CHECKGLERROR
+       R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
+       Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f);
+       GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, clearcolor, 1.0f, 0);
+       if (r_timereport_active)
+               R_TimeReport("prepasscleargeom");
 
        if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass)
                r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity);
@@ -4029,11 +4066,11 @@ void R_Shadow_DrawPrepass(void)
        GL_ColorMask(1,1,1,1);
        GL_Color(1,1,1,1);
        GL_DepthTest(true);
-       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_prepasslightingfbo);CHECKGLERROR
-       qglClearColor(0.0f,0.0f,0.0f,0.0f);CHECKGLERROR
-       GL_Clear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
-       if (r_refdef.fogenabled)
-               qglClearColor(r_refdef.fogcolor[0],r_refdef.fogcolor[1],r_refdef.fogcolor[2],0);CHECKGLERROR
+       R_Mesh_SetRenderTargets(r_shadow_prepasslightingfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
+       Vector4Set(clearcolor, 0, 0, 0, 0);
+       GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0);
+       if (r_timereport_active)
+               R_TimeReport("prepassclearlit");
 
        R_Shadow_RenderMode_Begin();
 
@@ -4059,9 +4096,7 @@ void R_Shadow_DrawPrepass(void)
                for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++)
                        R_Shadow_DrawLight(r_refdef.scene.lights[lnum]);
 
-       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
-       if (r_refdef.fogenabled)
-               qglClearColor(r_refdef.fogcolor[0],r_refdef.fogcolor[1],r_refdef.fogcolor[2],0);CHECKGLERROR
+       R_Mesh_ResetRenderTargets();
 
        R_Shadow_RenderMode_End();
 
@@ -4095,6 +4130,9 @@ void R_Shadow_PrepareLights(void)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2)
                {
                        r_shadow_usingdeferredprepass = false;
@@ -4112,35 +4150,30 @@ void R_Shadow_PrepareLights(void)
                        r_shadow_prepass_width = vid.width;
                        r_shadow_prepass_height = vid.height;
                        r_shadow_prepassgeometrydepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "prepassgeometrydepthmap", vid.width, vid.height, 24, false);
-                       r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
-                       r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
-                       r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
+                       r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
+                       r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
+                       r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL);
 
                        // set up the geometry pass fbo (depth + normalmap)
-                       qglGenFramebuffersEXT(1, &r_shadow_prepassgeometryfbo);CHECKGLERROR
-                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_prepassgeometryfbo);CHECKGLERROR
-                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_prepassgeometrydepthtexture), 0);CHECKGLERROR
-                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_prepassgeometrynormalmaptexture), 0);CHECKGLERROR
+                       r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
+                       R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL);
                        // render depth into one texture and normalmap into the other
                        if (qglDrawBuffersARB)
                        {
                                qglDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);CHECKGLERROR
                                qglReadBuffer(GL_NONE);CHECKGLERROR
-                       }
-                       status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
-                       if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
-                       {
-                               Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
-                               Cvar_SetValueQuick(&r_shadow_deferred, 0);
-                               r_shadow_usingdeferredprepass = false;
+                               status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
+                               if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
+                               {
+                                       Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
+                                       Cvar_SetValueQuick(&r_shadow_deferred, 0);
+                                       r_shadow_usingdeferredprepass = false;
+                               }
                        }
 
                        // set up the lighting pass fbo (diffuse + specular)
-                       qglGenFramebuffersEXT(1, &r_shadow_prepasslightingfbo);CHECKGLERROR
-                       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_prepasslightingfbo);CHECKGLERROR
-                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_prepassgeometrydepthtexture), 0);CHECKGLERROR
-                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_prepasslightingdiffusetexture), 0);CHECKGLERROR
-                       qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_prepasslightingspeculartexture), 0);CHECKGLERROR
+                       r_shadow_prepasslightingfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
+                       R_Mesh_SetRenderTargets(r_shadow_prepasslightingfbo, r_shadow_prepassgeometrydepthtexture, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL);
                        // render diffuse into one texture and specular into another,
                        // with depth and normalmap bound as textures,
                        // with depth bound as attachment as well
@@ -4148,13 +4181,13 @@ void R_Shadow_PrepareLights(void)
                        {
                                qglDrawBuffersARB(2, r_shadow_prepasslightingdrawbuffers);CHECKGLERROR
                                qglReadBuffer(GL_NONE);CHECKGLERROR
-                       }
-                       status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
-                       if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
-                       {
-                               Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
-                               Cvar_SetValueQuick(&r_shadow_deferred, 0);
-                               r_shadow_usingdeferredprepass = false;
+                               status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR
+                               if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
+                               {
+                                       Con_Printf("R_PrepareRTLights: glCheckFramebufferStatusEXT returned %i\n", status);
+                                       Cvar_SetValueQuick(&r_shadow_deferred, 0);
+                                       r_shadow_usingdeferredprepass = false;
+                               }
                        }
                }
                break;
@@ -4334,6 +4367,7 @@ void R_DrawModelShadowMaps(void)
        matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix;
        r_viewport_t viewport;
        GLuint fbo = 0;
+       float clearcolor[4];
 
        if (!r_refdef.scene.numentities)
                return;
@@ -4347,7 +4381,6 @@ void R_DrawModelShadowMaps(void)
                return;
        }
 
-       CHECKGLERROR
        R_ResetViewRendering3D();
        R_Shadow_RenderMode_Begin();
        R_Shadow_RenderMode_ActiveLight(NULL);
@@ -4416,27 +4449,24 @@ void R_DrawModelShadowMaps(void)
        VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin);
  
 #if 0
-       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR
+       R_Mesh_ResetRenderTargets();
        R_SetupShader_ShowDepth();
 #else
-       qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);CHECKGLERROR
+       R_Mesh_SetRenderTargets(fbo, r_shadow_shadowmap2dtexture, NULL, NULL, NULL, NULL);
        R_SetupShader_DepthOrShadow();
 #endif
-       CHECKGLERROR
        GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value);
        GL_DepthMask(true);
        GL_DepthTest(true);
        R_SetViewport(&viewport);
        GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder);
-       qglClearDepth(1);
+       Vector4Set(clearcolor, 1,1,1,1);
 #if 0
-       qglClearColor(1,1,1,1);
-       GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+       GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
 #else
-       GL_Clear(GL_DEPTH_BUFFER_BIT);
+       GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0);
 #endif
        GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder);
-       CHECKGLERROR
 
        for (i = 0;i < r_refdef.scene.numentities;i++)
        {
@@ -4498,7 +4528,6 @@ void R_DrawModelShadows(void)
        if (!r_refdef.scene.numentities || !vid.stencil || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1))
                return;
 
-       CHECKGLERROR
        R_ResetViewRendering3D();
        //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
        //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
@@ -4594,11 +4623,8 @@ void R_DrawModelShadows(void)
        //GL_PolygonOffset(0, 0);CHECKGLERROR
        GL_Color(0, 0, 0, r_shadows_darken.value);
        //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
-       //qglDepthFunc(GL_ALWAYS);CHECKGLERROR
-       qglEnable(GL_STENCIL_TEST);CHECKGLERROR
-       qglStencilMask(255);CHECKGLERROR
-       qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
-       qglStencilFunc(GL_NOTEQUAL, 128, 255);CHECKGLERROR
+       //GL_DepthFunc(GL_ALWAYS);
+       R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255);
 
        // apply the blend to the shadowed areas
        R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
@@ -4630,21 +4656,38 @@ void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery)
                // we count potential samples in the middle of the screen, we count actual samples at the light location, this allows counting potential samples of off-screen lights
                VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin);
 
-               CHECKGLERROR
-               // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use qglDepthFunc instead
-               qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
-               qglDepthFunc(GL_ALWAYS);
-               R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
-               R_Mesh_PrepareVertices_Position_Arrays(4, vertex3f);
-               R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
-               qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
-               qglDepthFunc(GL_LEQUAL);
-               qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
-               R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
-               R_Mesh_PrepareVertices_Position_Arrays(4, vertex3f);
-               R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
-               qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
-               CHECKGLERROR
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL20:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL11:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead
+                       qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels);
+                       GL_DepthFunc(GL_ALWAYS);
+                       R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
+                       R_Mesh_PrepareVertices_Position_Arrays(4, vertex3f);
+                       R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
+                       qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
+                       GL_DepthFunc(GL_LEQUAL);
+                       qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels);
+                       R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
+                       R_Mesh_PrepareVertices_Position_Arrays(4, vertex3f);
+                       R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
+                       qglEndQueryARB(GL_SAMPLES_PASSED_ARB);
+                       CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+                       Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
        }
        rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1);
 }
@@ -4658,10 +4701,27 @@ void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
        // now we have to check the query result
        if (rtlight->corona_queryindex_visiblepixels)
        {
-               CHECKGLERROR
-               qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
-               qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
-               CHECKGLERROR
+               switch(vid.renderpath)
+               {
+               case RENDERPATH_GL20:
+               case RENDERPATH_GL13:
+               case RENDERPATH_GL11:
+               case RENDERPATH_CGGL:
+                       CHECKGLERROR
+                       qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels);
+                       qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels);
+                       CHECKGLERROR
+                       break;
+               case RENDERPATH_D3D9:
+                       Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D10:
+                       Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               case RENDERPATH_D3D11:
+                       Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                       break;
+               }
                //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels);
                if (visiblepixels < 1 || allpixels < 1)
                        return;
@@ -4682,20 +4742,60 @@ void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale)
                if(negated)
                {
                        VectorNegate(color, color);
-                       qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
+                       switch(vid.renderpath)
+                       {
+                       case RENDERPATH_GL11:
+                       case RENDERPATH_GL13:
+                       case RENDERPATH_GL20:
+                       case RENDERPATH_CGGL:
+                               qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
+                               break;
+                       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_SUBTRACT);
+#endif
+                               break;
+                       case RENDERPATH_D3D10:
+                               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                               break;
+                       case RENDERPATH_D3D11:
+                               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                               break;
+                       }
                }
                R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale);
                RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, RENDER_NODEPTHTEST, 0, color[0], color[1], color[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false);
                R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false);
                if(negated)
-                       qglBlendEquationEXT(GL_FUNC_ADD_EXT);
+               {
+                       switch(vid.renderpath)
+                       {
+                       case RENDERPATH_GL11:
+                       case RENDERPATH_GL13:
+                       case RENDERPATH_GL20:
+                       case RENDERPATH_CGGL:
+                               qglBlendEquationEXT(GL_FUNC_ADD_EXT);
+                               break;
+                       case RENDERPATH_D3D9:
+#ifdef SUPPORTD3D
+                               IDirect3DDevice9_SetRenderState(vid_d3d9dev, D3DRS_BLENDOP, D3DBLENDOP_ADD);
+#endif
+                               break;
+                       case RENDERPATH_D3D10:
+                               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                               break;
+                       case RENDERPATH_D3D11:
+                               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+                               break;
+                       }
+               }
        }
 }
 
 void R_Shadow_DrawCoronas(void)
 {
        int i, flag;
-       qboolean usequery;
+       qboolean usequery = false;
        size_t lightindex;
        dlight_t *light;
        rtlight_t *rtlight;
@@ -4713,29 +4813,47 @@ void R_Shadow_DrawCoronas(void)
        // use GL_ARB_occlusion_query if available
        // otherwise use raytraces
        r_numqueries = 0;
-       usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
-       if (usequery)
+       switch (vid.renderpath)
        {
-               GL_ColorMask(0,0,0,0);
-               if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
-               if (r_maxqueries < MAX_OCCLUSION_QUERIES)
+       case RENDERPATH_GL11:
+       case RENDERPATH_GL13:
+       case RENDERPATH_GL20:
+       case RENDERPATH_CGGL:
+               usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer;
+               if (usequery)
                {
-                       i = r_maxqueries;
-                       r_maxqueries = (range + r_refdef.scene.numlights) * 4;
-                       r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
-                       CHECKGLERROR
-                       qglGenQueriesARB(r_maxqueries - i, r_queries + i);
-                       CHECKGLERROR
+                       GL_ColorMask(0,0,0,0);
+                       if (r_maxqueries < (range + r_refdef.scene.numlights) * 2)
+                       if (r_maxqueries < MAX_OCCLUSION_QUERIES)
+                       {
+                               i = r_maxqueries;
+                               r_maxqueries = (range + r_refdef.scene.numlights) * 4;
+                               r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES);
+                               CHECKGLERROR
+                               qglGenQueriesARB(r_maxqueries - i, r_queries + i);
+                               CHECKGLERROR
+                       }
+                       RSurf_ActiveWorldEntity();
+                       GL_BlendFunc(GL_ONE, GL_ZERO);
+                       GL_CullFace(GL_NONE);
+                       GL_DepthMask(false);
+                       GL_DepthRange(0, 1);
+                       GL_PolygonOffset(0, 0);
+                       GL_DepthTest(true);
+                       R_Mesh_ResetTextureState();
+                       R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
                }
-               RSurf_ActiveWorldEntity();
-               GL_BlendFunc(GL_ONE, GL_ZERO);
-               GL_CullFace(GL_NONE);
-               GL_DepthMask(false);
-               GL_DepthRange(0, 1);
-               GL_PolygonOffset(0, 0);
-               GL_DepthTest(true);
-               R_Mesh_ResetTextureState();
-               R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
+               break;
+       case RENDERPATH_D3D9:
+               usequery = false;
+               //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D10:
+               Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
+       case RENDERPATH_D3D11:
+               Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
+               break;
        }
        for (lightindex = 0;lightindex < range;lightindex++)
        {
index 76ad5fe2627837ecd4b0fca58f0f689ce43f7d47..0d7ca0479a2e43fc6a90f052b6540c8ec49a4d91 100644 (file)
 #define TEXF_ISWORLD 0x00004000
 // indicates texture should be affected by gl_picmip_sprites and r_picmipsprites (maybe others in the future) instead of gl_picmip_other
 #define TEXF_ISSPRITE 0x00008000
+// indicates the texture will be used as a render target (D3D hint)
+#define TEXF_RENDERTARGET 0x0010000
 // used for checking if textures mismatch
-#define TEXF_IMPORTANTBITS (TEXF_ALPHA | TEXF_MIPMAP | TEXF_CLAMP | TEXF_FORCENEAREST | TEXF_FORCELINEAR | TEXF_PICMIP | TEXF_COMPRESS | TEXF_COMPARE | TEXF_LOWPRECISION)
+#define TEXF_IMPORTANTBITS (TEXF_ALPHA | TEXF_MIPMAP | TEXF_CLAMP | TEXF_FORCENEAREST | TEXF_FORCELINEAR | TEXF_PICMIP | TEXF_COMPRESS | TEXF_COMPARE | TEXF_LOWPRECISION | TEXF_RENDERTARGET)
 
 typedef enum textype_e
 {
@@ -56,6 +58,16 @@ typedef enum textype_e
 }
 textype_t;
 
+/*
+#ifdef WIN32
+#define SUPPORTD3D
+#define SUPPORTDIRECTX
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+#endif
+#endif
+*/
+
 // contents of this structure are mostly private to gl_textures.c
 typedef struct rtexture_s
 {
@@ -63,6 +75,22 @@ typedef struct rtexture_s
        int texnum;
        qboolean dirty;
        int gltexturetypeenum; // exposed for use in R_Mesh_TexBind
+       // d3d stuff the backend needs
+       void *d3dtexture;
+#ifdef SUPPORTD3D
+       int d3dformat;
+       int d3dusage;
+       int d3dpool;
+       int d3daddressu;
+       int d3daddressv;
+       int d3daddressw;
+       int d3dmagfilter;
+       int d3dminfilter;
+       int d3dmipfilter;
+       int d3dmaxmiplevelfilter;
+       int d3dmipmaplodbias;
+       int d3dmaxmiplevel;
+#endif
 }
 rtexture_t;
 
index d81cc5656b55ed56716f7d8106a8b975728b00dc..7f85446b448c885f9dc57cf52b92daf8be1c3dec 100644 (file)
--- a/render.h
+++ b/render.h
@@ -523,7 +523,7 @@ gl20_texunit;
 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale);
 void R_SetupShader_DepthOrShadow(void);
 void R_SetupShader_ShowDepth(void);
-void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist);
+void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *waterplane);
 void R_SetupShader_DeferredLight(const rtlight_t *rtlight);
 
 typedef struct r_waterstate_waterplane_s
diff --git a/vid.h b/vid.h
index 540a0c429286cc1923ac1610937b8ed3822b3c0d..900628071844dd7e757952dc50028d6bef40d3e5 100644 (file)
--- a/vid.h
+++ b/vid.h
@@ -34,6 +34,9 @@ typedef enum renderpath_e
        RENDERPATH_GL13,
        RENDERPATH_GL20,
        RENDERPATH_CGGL,
+       RENDERPATH_D3D9,
+       RENDERPATH_D3D10,
+       RENDERPATH_D3D11,
 }
 renderpath_t;
 
@@ -188,6 +191,7 @@ void VID_Shared_Init(void);
 
 void GL_Init (void);
 
+void VID_ClearExtensions(void);
 void VID_CheckExtensions(void);
 
 void VID_Init (void);
index 20f2b3e1dd3dd8f74e0b5d2226c8924b1cc98bc5..fccb1e4ab61a46b73cec3c676de238181bfcaf63 100644 (file)
@@ -790,13 +790,37 @@ static dllfunction_t drawbuffersfuncs[] =
        {NULL, NULL}
 };
 
-void VID_CheckExtensions(void)
+void VID_ClearExtensions(void)
 {
+       // VorteX: reset extensions info cvar, it got filled by GL_CheckExtension
+       Cvar_SetQuick(&gl_info_extensions, "");
+
        // clear the extension flags
        memset(&vid.support, 0, sizeof(vid.support));
+       vid.renderpath = RENDERPATH_GL11;
+       vid.forcevbo = false;
+       vid.maxtexturesize_2d = 0;
+       vid.maxtexturesize_3d = 0;
+       vid.maxtexturesize_cubemap = 0;
+       vid.texunits = 1;
+       vid.teximageunits = 1;
+       vid.texarrayunits = 1;
+       vid.max_anisotropy = 1;
+       vid.maxdrawbuffers = 1;
 
-       // VorteX: reset extensions info cvar, it got filled by GL_CheckExtension
-       Cvar_SetQuick(&gl_info_extensions, "");
+       // this is a complete list of all functions that are directly checked in the renderer
+       qglDrawRangeElements = NULL;
+       qglDrawBuffer = NULL;
+       qglPolygonStipple = NULL;
+       qglFlush = NULL;
+       qglActiveTexture = NULL;
+       qglGetCompressedTexImageARB = NULL;
+       qglFramebufferTexture2DEXT = NULL;
+       qglDrawBuffersARB = NULL;
+}
+
+void VID_CheckExtensions(void)
+{
        if (!GL_CheckExtension("1.1", opengl110funcs, NULL, false))
                Sys_Error("OpenGL 1.1.0 functions not found");
 
@@ -804,7 +828,6 @@ void VID_CheckExtensions(void)
 
        Con_DPrint("Checking OpenGL extensions...\n");
 
-       vid.forcevbo = false;
        vid.support.amd_texture_texture4 = GL_CheckExtension("GL_AMD_texture_texture4", NULL, "-notexture4", false);
        vid.support.arb_depth_texture = GL_CheckExtension("GL_ARB_depth_texture", NULL, "-nodepthtexture", false);
        vid.support.arb_draw_buffers = GL_CheckExtension("GL_ARB_draw_buffers", drawbuffersfuncs, "-nodrawbuffers", false);
@@ -860,15 +883,6 @@ void VID_CheckExtensions(void)
 // COMMANDLINEOPTION: GL: -novbo disables GL_ARB_vertex_buffer_object (which accelerates rendering)
 // COMMANDLINEOPTION: GL: -novertexshader disables GL_ARB_vertex_shader (allows vertex shader effects)
 
-       vid.maxtexturesize_2d = 0;
-       vid.maxtexturesize_3d = 0;
-       vid.maxtexturesize_cubemap = 0;
-       vid.texunits = 1;
-       vid.teximageunits = 1;
-       vid.texarrayunits = 1;
-       vid.max_anisotropy = 1;
-       vid.maxdrawbuffers = 1;
-
        if (vid.support.arb_draw_buffers)
                qglGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, (GLint*)&vid.maxdrawbuffers);
 
@@ -1036,6 +1050,9 @@ void VID_UpdateGamma(qboolean force, int rampsize)
        {
        case RENDERPATH_GL20:
        case RENDERPATH_CGGL:
+       case RENDERPATH_D3D9:
+       case RENDERPATH_D3D10:
+       case RENDERPATH_D3D11:
                if (v_glslgamma.integer)
                        wantgamma = 0;
                break;
@@ -1236,6 +1253,7 @@ int VID_Mode(int fullscreen, int width, int height, int bpp, float refreshrate,
        mode.stereobuffer = stereobuffer != 0;
        mode.samples = samples;
        cl_ignoremousemoves = 2;
+       VID_ClearExtensions();
        if (VID_InitMode(&mode))
        {
                // accept the (possibly modified) mode
index 1b9e758d3dcb524d09833a1bd044b4bdbd8e7c23..8ea9f586cea0f46cbc53c2a69635c4d3564ae1d8 100644 (file)
--- a/vid_wgl.c
+++ b/vid_wgl.c
@@ -42,8 +42,30 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include <dinput.h>
 #endif
 
+#ifdef SUPPORTD3D
+#include <d3d9.h>
+#pragma comment(lib, "d3d9.lib")
+
+cvar_t vid_dx9 = {CVAR_SAVE, "vid_dx9", "0", "use Microsoft Direct3D9(r) for rendering"};
+cvar_t vid_dx9_hal = {CVAR_SAVE, "vid_dx9_hal", "1", "enables hardware rendering (1), otherwise software reference rasterizer (0 - very slow), note that 0 is necessary when using NVPerfHUD (which renders in hardware but requires this option to enable it)"};
+cvar_t vid_dx9_softvertex = {CVAR_SAVE, "vid_dx9_softvertex", "0", "enables software vertex processing (for compatibility testing?  or if you have a very fast CPU), usually you want this off"};
+cvar_t vid_dx9_triplebuffer = {CVAR_SAVE, "vid_dx9_triplebuffer", "0", "enables triple buffering when using vid_vsync in fullscreen, this options adds some latency and only helps when framerate is below 60 so you usually don't want it"};
+//cvar_t vid_dx10 = {CVAR_SAVE, "vid_dx10", "1", "use Microsoft Direct3D10(r) for rendering"};
+//cvar_t vid_dx11 = {CVAR_SAVE, "vid_dx11", "1", "use Microsoft Direct3D11(r) for rendering"};
+
+D3DPRESENT_PARAMETERS vid_d3dpresentparameters;
+#endif
+
 extern HINSTANCE global_hInstance;
 
+static HINSTANCE gldll;
+
+#ifdef SUPPORTD3D
+LPDIRECT3D9 vid_d3d9;
+LPDIRECT3DDEVICE9 vid_d3d9dev;
+D3DCAPS9 vid_d3d9caps;
+qboolean vid_d3ddevicelost;
+#endif
 
 #ifndef WM_MOUSEWHEEL
 #define WM_MOUSEWHEEL                   0x020A
@@ -250,8 +272,54 @@ static void IN_StartupMouse (void);
 
 //====================================
 
+qboolean vid_reallyhidden = true;
+#ifdef SUPPORTD3D
+qboolean vid_begunscene = false;
+#endif
 void VID_Finish (void)
 {
+#ifdef SUPPORTD3D
+       if (vid_d3d9dev)
+       {
+               DWORD d;
+               if (vid_begunscene)
+               {
+                       IDirect3DDevice9_EndScene(vid_d3d9dev);
+                       vid_begunscene = false;
+               }
+               if (vid_reallyhidden)
+                       return;
+               d = IDirect3DDevice9_TestCooperativeLevel(vid_d3d9dev);
+               switch(d)
+               {
+               case D3DERR_DEVICELOST:
+                       vid_d3ddevicelost = true;
+                       vid_hidden = true;
+                       Sleep(100);
+                       break;
+               case D3DERR_DEVICENOTRESET:
+                       vid_d3ddevicelost = false;
+                       vid_hidden = vid_reallyhidden;
+                       R_Modules_DeviceLost();
+                       IDirect3DDevice9_Reset(vid_d3d9dev, &vid_d3dpresentparameters);
+                       R_Modules_DeviceRestored();
+                       break;
+               case D3D_OK:
+                       vid_hidden = vid_reallyhidden;
+                       IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
+                       break;
+               }
+               if (!vid_begunscene && !vid_hidden)
+               {
+                       IDirect3DDevice9_BeginScene(vid_d3d9dev);
+                       vid_begunscene = true;
+               }
+               return;
+       }
+#endif
+
+       vid_hidden = vid_reallyhidden;
+
        vid_usevsync = vid_vsync.integer && !cls.timedemo && qwglSwapIntervalEXT;
        if (vid_usingvsync != vid_usevsync)
        {
@@ -398,10 +466,10 @@ void AppActivate(BOOL fActive, BOOL minimize)
        static qboolean sound_active = false;  // initially blocked by Sys_InitConsole()
 
        vid_activewindow = fActive != FALSE;
-       vid_hidden = minimize != FALSE;
+       vid_reallyhidden = minimize != FALSE;
 
        // enable/disable sound on focus gain/loss
-       if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
+       if ((!vid_reallyhidden && vid_activewindow) || !snd_mutewhenidle.integer)
        {
                if (!sound_active)
                {
@@ -425,12 +493,16 @@ void AppActivate(BOOL fActive, BOOL minimize)
                        if (vid_wassuspended)
                        {
                                vid_wassuspended = false;
-                               ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
-                               ShowWindow(mainwindow, SW_SHOWNORMAL);
+                               if (gldll)
+                               {
+                                       ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN);
+                                       ShowWindow(mainwindow, SW_SHOWNORMAL);
+                               }
                        }
 
                        // LordHavoc: from dabb, fix for alt-tab bug in NVidia drivers
-                       MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
+                       if (gldll)
+                               MoveWindow(mainwindow,0,0,gdevmode.dmPelsWidth,gdevmode.dmPelsHeight,false);
                }
        }
 
@@ -439,7 +511,8 @@ void AppActivate(BOOL fActive, BOOL minimize)
                VID_SetMouse(false, false, false);
                if (vid_isfullscreen)
                {
-                       ChangeDisplaySettings (NULL, 0);
+                       if (gldll)
+                               ChangeDisplaySettings (NULL, 0);
                        vid_wassuspended = true;
                }
                VID_RestoreSystemGamma();
@@ -652,31 +725,42 @@ LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM  wParam, LPARAM lParam)
 
 int VID_SetGamma(unsigned short *ramps, int rampsize)
 {
-       HDC hdc = GetDC (NULL);
-       int i = SetDeviceGammaRamp(hdc, ramps);
-       ReleaseDC (NULL, hdc);
-       return i; // return success or failure
+       if (qwglMakeCurrent)
+       {
+               HDC hdc = GetDC (NULL);
+               int i = SetDeviceGammaRamp(hdc, ramps);
+               ReleaseDC (NULL, hdc);
+               return i; // return success or failure
+       }
+       else
+               return 0;
 }
 
 int VID_GetGamma(unsigned short *ramps, int rampsize)
 {
-       HDC hdc = GetDC (NULL);
-       int i = GetDeviceGammaRamp(hdc, ramps);
-       ReleaseDC (NULL, hdc);
-       return i; // return success or failure
+       if (qwglMakeCurrent)
+       {
+               HDC hdc = GetDC (NULL);
+               int i = GetDeviceGammaRamp(hdc, ramps);
+               ReleaseDC (NULL, hdc);
+               return i; // return success or failure
+       }
+       else
+               return 0;
 }
 
-static HINSTANCE gldll;
-
 static void GL_CloseLibrary(void)
 {
-       FreeLibrary(gldll);
-       gldll = 0;
-       gl_driver[0] = 0;
-       qwglGetProcAddress = NULL;
-       gl_extensions = "";
-       gl_platform = "";
-       gl_platformextensions = "";
+       if (gldll)
+       {
+               FreeLibrary(gldll);
+               gldll = 0;
+               gl_driver[0] = 0;
+               qwglGetProcAddress = NULL;
+               gl_extensions = "";
+               gl_platform = "";
+               gl_platformextensions = "";
+       }
 }
 
 static int GL_OpenLibrary(const char *name)
@@ -694,12 +778,17 @@ static int GL_OpenLibrary(const char *name)
 
 void *GL_GetProcAddress(const char *name)
 {
-       void *p = NULL;
-       if (qwglGetProcAddress != NULL)
-               p = (void *) qwglGetProcAddress(name);
-       if (p == NULL)
-               p = (void *) GetProcAddress(gldll, name);
-       return p;
+       if (gldll)
+       {
+               void *p = NULL;
+               if (qwglGetProcAddress != NULL)
+                       p = (void *) qwglGetProcAddress(name);
+               if (p == NULL)
+                       p = (void *) GetProcAddress(gldll, name);
+               return p;
+       }
+       else
+               return NULL;
 }
 
 #ifndef WGL_ARB_pixel_format
@@ -765,6 +854,15 @@ void VID_Init(void)
 {
        WNDCLASS wc;
 
+#ifdef SUPPORTD3D
+       Cvar_RegisterVariable(&vid_dx9);
+       Cvar_RegisterVariable(&vid_dx9_hal);
+       Cvar_RegisterVariable(&vid_dx9_softvertex);
+       Cvar_RegisterVariable(&vid_dx9_triplebuffer);
+//     Cvar_RegisterVariable(&vid_dx10);
+//     Cvar_RegisterVariable(&vid_dx11);
+#endif
+
        InitCommonControls();
        hIcon = LoadIcon (global_hInstance, MAKEINTRESOURCE (IDI_ICON1));
 
@@ -789,7 +887,7 @@ void VID_Init(void)
        IN_Init();
 }
 
-qboolean VID_InitMode(viddef_mode_t *mode)
+qboolean VID_InitModeGL(viddef_mode_t *mode)
 {
        int i;
        HDC hdc;
@@ -1234,7 +1332,7 @@ qboolean VID_InitMode(viddef_mode_t *mode)
        vid_usingmouse = false;
        vid_usinghidecursor = false;
        vid_usingvsync = false;
-       vid_hidden = false;
+       vid_reallyhidden = vid_hidden = false;
        vid_initialized = true;
 
        IN_StartupMouse ();
@@ -1250,9 +1348,261 @@ qboolean VID_InitMode(viddef_mode_t *mode)
        return true;
 }
 
+#ifdef SUPPORTD3D
+static D3DADAPTER_IDENTIFIER9 d3d9adapteridentifier;
+
+extern cvar_t gl_info_extensions;
+extern cvar_t gl_info_vendor;
+extern cvar_t gl_info_renderer;
+extern cvar_t gl_info_version;
+extern cvar_t gl_info_platform;
+extern cvar_t gl_info_driver;
+qboolean VID_InitModeDX(viddef_mode_t *mode, int version)
+{
+       int deviceindex;
+       RECT rect;
+       MSG msg;
+       int pixelformat, newpixelformat;
+       DWORD WindowStyle, ExWindowStyle;
+       int CenterX, CenterY;
+       int bpp = mode->bitsperpixel;
+       int width = mode->width;
+       int height = mode->height;
+       int refreshrate = (int)floor(mode->refreshrate+0.5);
+//     int stereobuffer = mode->stereobuffer;
+       int samples = mode->samples;
+       int fullscreen = mode->fullscreen;
+       int numdevices;
+
+       if (vid_initialized)
+               Sys_Error("VID_InitMode called when video is already initialised");
+
+       vid_isfullscreen = fullscreen != 0;
+       if (fullscreen)
+       {
+               WindowStyle = WS_POPUP;
+               ExWindowStyle = WS_EX_TOPMOST;
+       }
+       else
+       {
+               WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
+               ExWindowStyle = 0;
+       }
+
+       rect.top = 0;
+       rect.left = 0;
+       rect.right = width;
+       rect.bottom = height;
+       AdjustWindowRectEx(&rect, WindowStyle, false, 0);
+
+       if (fullscreen)
+       {
+               CenterX = 0;
+               CenterY = 0;
+       }
+       else
+       {
+               CenterX = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
+               CenterY = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
+       }
+       CenterX = max(0, CenterX);
+       CenterY = max(0, CenterY);
+
+       // x and y may be changed by WM_MOVE messages
+       window_x = CenterX;
+       window_y = CenterY;
+       rect.left += CenterX;
+       rect.right += CenterX;
+       rect.top += CenterY;
+       rect.bottom += CenterY;
+
+       pixelformat = 0;
+       newpixelformat = 0;
+       gl_extensions = "";
+       gl_platformextensions = "";
+
+       mainwindow = CreateWindowEx (ExWindowStyle, "DarkPlacesWindowClass", gamename, WindowStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, global_hInstance, NULL);
+       if (!mainwindow)
+       {
+               Con_Printf("CreateWindowEx(%d, %s, %s, %d, %d, %d, %d, %d, %p, %p, %p, %p) failed\n", (int)ExWindowStyle, "DarkPlacesWindowClass", gamename, (int)WindowStyle, (int)(rect.left), (int)(rect.top), (int)(rect.right - rect.left), (int)(rect.bottom - rect.top), NULL, NULL, global_hInstance, NULL);
+               VID_Shutdown();
+               return false;
+       }
+
+       baseDC = GetDC(mainwindow);
+
+       vid_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
+       if (!vid_d3d9)
+               Sys_Error("VID_InitMode: Direct3DCreate9 failed");
+
+       numdevices = IDirect3D9_GetAdapterCount(vid_d3d9);
+       vid_d3d9dev = NULL;
+       memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
+       for (deviceindex = 0;deviceindex < numdevices && !vid_d3d9dev;deviceindex++)
+       {
+               memset(&vid_d3dpresentparameters, 0, sizeof(vid_d3dpresentparameters));
+               vid_d3dpresentparameters.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
+               vid_d3dpresentparameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
+               vid_d3dpresentparameters.hDeviceWindow = mainwindow;
+               vid_d3dpresentparameters.BackBufferWidth = width;
+               vid_d3dpresentparameters.BackBufferHeight = height;
+               vid_d3dpresentparameters.MultiSampleType = samples > 1 ? (D3DMULTISAMPLE_TYPE)samples : D3DMULTISAMPLE_NONE;
+               vid_d3dpresentparameters.BackBufferCount = fullscreen ? (vid_dx9_triplebuffer.integer ? 3 : 2) : 1;
+               vid_d3dpresentparameters.FullScreen_RefreshRateInHz = fullscreen ? refreshrate : 0;
+               vid_d3dpresentparameters.Windowed = !fullscreen;
+               vid_d3dpresentparameters.EnableAutoDepthStencil = true;
+               vid_d3dpresentparameters.AutoDepthStencilFormat = bpp > 16 ? D3DFMT_D24S8 : D3DFMT_D16;
+               vid_d3dpresentparameters.BackBufferFormat = fullscreen?D3DFMT_X8R8G8B8:D3DFMT_UNKNOWN;
+               vid_d3dpresentparameters.PresentationInterval = vid_vsync.integer ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
+
+               memset(&d3d9adapteridentifier, 0, sizeof(d3d9adapteridentifier));
+               IDirect3D9_GetAdapterIdentifier(vid_d3d9, deviceindex, 0, &d3d9adapteridentifier);
+
+               IDirect3D9_CreateDevice(vid_d3d9, deviceindex, vid_dx9_hal.integer ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF, mainwindow, vid_dx9_softvertex.integer ? D3DCREATE_SOFTWARE_VERTEXPROCESSING : D3DCREATE_HARDWARE_VERTEXPROCESSING, &vid_d3dpresentparameters, &vid_d3d9dev);
+       }
+
+       if (!vid_d3d9dev)
+       {
+               VID_Shutdown();
+               return false;
+       }
+
+       IDirect3DDevice9_GetDeviceCaps(vid_d3d9dev, &vid_d3d9caps);
+
+       Con_Printf("Using D3D9 device: %s\n", d3d9adapteridentifier.Description);
+       gl_extensions = "";
+       gl_platform = "D3D9";
+       gl_platformextensions = "";
+
+       ShowWindow (mainwindow, SW_SHOWDEFAULT);
+       UpdateWindow (mainwindow);
+
+       // now we try to make sure we get the focus on the mode switch, because
+       // sometimes in some systems we don't.  We grab the foreground, then
+       // finish setting up, pump all our messages, and sleep for a little while
+       // to let messages finish bouncing around the system, then we put
+       // ourselves at the top of the z order, then grab the foreground again,
+       // Who knows if it helps, but it probably doesn't hurt
+       SetForegroundWindow (mainwindow);
+
+       while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+       {
+               TranslateMessage (&msg);
+               DispatchMessage (&msg);
+       }
+
+       Sleep (100);
+
+       SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOCOPYBITS);
+
+       SetForegroundWindow (mainwindow);
+
+       // fix the leftover Alt from any Alt-Tab or the like that switched us away
+       ClearAllStates ();
+
+       gl_renderer = d3d9adapteridentifier.Description;
+       gl_vendor = d3d9adapteridentifier.Driver;
+       gl_version = "";
+       gl_extensions = "";
+
+       Con_Printf("D3D9 adapter info:\n");
+       Con_Printf("Description: %s\n", d3d9adapteridentifier.Description);
+       Con_Printf("DeviceId: %x\n", d3d9adapteridentifier.DeviceId);
+       Con_Printf("DeviceName: %x\n", d3d9adapteridentifier.DeviceName);
+       Con_Printf("Driver: %s\n", d3d9adapteridentifier.Driver);
+       Con_Printf("DriverVersion: %x\n", d3d9adapteridentifier.DriverVersion);
+       Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
+       Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
+
+       // clear the extension flags
+       memset(&vid.support, 0, sizeof(vid.support));
+       Cvar_SetQuick(&gl_info_extensions, "");
+
+       CHECKGLERROR
+
+       vid.forcevbo = true;
+       vid.support.arb_depth_texture = true;
+       vid.support.arb_draw_buffers = vid_d3d9caps.NumSimultaneousRTs > 1;
+       vid.support.arb_occlusion_query = true; // can't find a cap for this
+       vid.support.arb_shadow = true;
+       vid.support.arb_texture_compression = true;
+       vid.support.arb_texture_cube_map = true;
+       vid.support.arb_texture_non_power_of_two = (vid_d3d9caps.TextureCaps & D3DPTEXTURECAPS_POW2) == 0;
+       vid.support.arb_vertex_buffer_object = true;
+       vid.support.ext_blend_subtract = true;
+       vid.support.ext_draw_range_elements = true;
+       vid.support.ext_framebuffer_object = true;
+       vid.support.ext_texture_3d = true;
+       vid.support.ext_texture_compression_s3tc = true;
+       vid.support.ext_texture_filter_anisotropic = true;
+       vid.support.ati_separate_stencil = (vid_d3d9caps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) != 0;
+
+       vid.maxtexturesize_2d = min(vid_d3d9caps.MaxTextureWidth, vid_d3d9caps.MaxTextureHeight);
+       vid.maxtexturesize_3d = vid_d3d9caps.MaxVolumeExtent;
+       vid.maxtexturesize_cubemap = vid.maxtexturesize_2d;
+       vid.texunits = 4;
+       vid.teximageunits = vid_d3d9caps.MaxSimultaneousTextures;
+       vid.texarrayunits = 8; // can't find a caps field for this?
+       vid.max_anisotropy = vid_d3d9caps.MaxAnisotropy;
+       vid.maxdrawbuffers = vid_d3d9caps.NumSimultaneousRTs;
+
+       vid.texunits = bound(4, vid.texunits, MAX_TEXTUREUNITS);
+       vid.teximageunits = bound(16, vid.teximageunits, MAX_TEXTUREUNITS);
+       vid.texarrayunits = bound(8, vid.texarrayunits, MAX_TEXTUREUNITS);
+       Con_DPrintf("Using D3D9.0 rendering path - %i texture matrix, %i texture images, %i texcoords, shadowmapping supported%s\n", vid.texunits, vid.teximageunits, vid.texarrayunits, vid.maxdrawbuffers > 1 ? ", MRT detected (allows prepass deferred lighting)" : "");
+       vid.renderpath = RENDERPATH_D3D9;
+
+       Cvar_SetQuick(&gl_info_vendor, gl_vendor);
+       Cvar_SetQuick(&gl_info_renderer, gl_renderer);
+       Cvar_SetQuick(&gl_info_version, gl_version);
+       Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
+       Cvar_SetQuick(&gl_info_driver, gl_driver);
+
+       // LordHavoc: report supported extensions
+       Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
+
+       // clear to black (loading plaque will be seen over this)
+       IDirect3DDevice9_Clear(vid_d3d9dev, 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
+       IDirect3DDevice9_BeginScene(vid_d3d9dev);
+       IDirect3DDevice9_EndScene(vid_d3d9dev);
+       IDirect3DDevice9_Present(vid_d3d9dev, NULL, NULL, NULL, NULL);
+       // because the only time we end/begin scene is in VID_Finish, we'd better start a scene now...
+       IDirect3DDevice9_BeginScene(vid_d3d9dev);
+       vid_begunscene = true;
+
+       //vid_menudrawfn = VID_MenuDraw;
+       //vid_menukeyfn = VID_MenuKey;
+       vid_usingmouse = false;
+       vid_usinghidecursor = false;
+       vid_usingvsync = false;
+       vid_hidden = vid_reallyhidden = false;
+       vid_initialized = true;
+
+       IN_StartupMouse ();
+       IN_StartupJoystick ();
+
+       return true;
+}
+#endif
+
+qboolean VID_InitMode(viddef_mode_t *mode)
+{
+#ifdef SUPPORTD3D
+//     if (vid_dx11.integer)
+//             return VID_InitModeDX(mode, 11);
+//     if (vid_dx10.integer)
+//             return VID_InitModeDX(mode, 10);
+       if (vid_dx9.integer)
+               return VID_InitModeDX(mode, 9);
+#endif
+       return VID_InitModeGL(mode);
+}
+
+
 static void IN_Shutdown(void);
 void VID_Shutdown (void)
 {
+       qboolean isgl;
        if(vid_initialized == false)
                return;
 
@@ -1260,11 +1610,33 @@ void VID_Shutdown (void)
        VID_RestoreSystemGamma();
 
        vid_initialized = false;
+       isgl = gldll != NULL;
        IN_Shutdown();
+       gl_driver[0] = 0;
+       gl_extensions = "";
+       gl_platform = "";
+       gl_platformextensions = "";
+#ifdef SUPPORTD3D
+       if (vid_d3d9dev)
+       {
+               if (vid_begunscene)
+                       IDirect3DDevice9_EndScene(vid_d3d9dev);
+               vid_begunscene = false;
+//             Cmd_ExecuteString("r_texturestats", src_command);
+//             Cmd_ExecuteString("memlist", src_command);
+               IDirect3DDevice9_Release(vid_d3d9dev);
+       }
+       vid_d3d9dev = NULL;
+       if (vid_d3d9)
+               IDirect3D9_Release(vid_d3d9);
+       vid_d3d9 = NULL;
+#endif
        if (qwglMakeCurrent)
                qwglMakeCurrent(NULL, NULL);
+       qwglMakeCurrent = NULL;
        if (baseRC && qwglDeleteContext)
                qwglDeleteContext(baseRC);
+       qwglDeleteContext = NULL;
        // close the library before we get rid of the window
        GL_CloseLibrary();
        if (baseDC && mainwindow)
@@ -1273,7 +1645,7 @@ void VID_Shutdown (void)
        if (mainwindow)
                DestroyWindow(mainwindow);
        mainwindow = 0;
-       if (vid_isfullscreen)
+       if (vid_isfullscreen && isgl)
                ChangeDisplaySettings (NULL, 0);
        vid_isfullscreen = false;
 }
@@ -1605,7 +1977,7 @@ IN_Move
 */
 void IN_Move (void)
 {
-       if (vid_activewindow && !vid_hidden)
+       if (vid_activewindow && !vid_reallyhidden)
        {
                IN_MouseMove ();
                IN_JoyMove ();