device.c 162 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * IDirect3DDevice8 implementation
 *
 * Copyright 2002 Jason Edmeades
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

21 22
#include "config.h"

23
#include <math.h>
24
#include <stdarg.h>
25 26 27

#define NONAMELESSUNION
#define NONAMELESSSTRUCT
28 29 30 31 32 33
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "wingdi.h"
#include "wine/debug.h"

34
/** define  GL_GLEXT_PROTOTYPES for having extensions prototypes defined */
35
/*#define GL_GLEXT_PROTOTYPES*/
36
/*#undef  GLX_GLXEXT_LEGACY*/
37 38
#include "d3d8_private.h"

39 40 41
/** currently desactiving 1_4 support as mesa doesn't implement all 1_4 support while defining it */
#undef GL_VERSION_1_4

42
WINE_DEFAULT_DEBUG_CHANNEL(d3d);
43
WINE_DECLARE_DEBUG_CHANNEL(d3d_shader);
44
WINE_DECLARE_DEBUG_CHANNEL(fps);
45

46 47 48 49
IDirect3DVertexShaderImpl*            VertexShaders[64];
IDirect3DVertexShaderDeclarationImpl* VertexShaderDeclarations[64];
IDirect3DPixelShaderImpl*             PixelShaders[64];

50
/* Debugging aids: */
51 52 53 54
#ifdef FRAME_DEBUGGING
BOOL isOn             = FALSE;
BOOL isDumpingFrames  = FALSE;
LONG primCounter      = 0;
55 56
#endif

57 58 59
/*
 * Utility functions or macros
 */
60 61
#define conv_mat(mat,gl_mat)                                                                \
do {                                                                                        \
62 63 64 65
    TRACE("%f %f %f %f\n", (mat)->u.s._11, (mat)->u.s._12, (mat)->u.s._13, (mat)->u.s._14); \
    TRACE("%f %f %f %f\n", (mat)->u.s._21, (mat)->u.s._22, (mat)->u.s._23, (mat)->u.s._24); \
    TRACE("%f %f %f %f\n", (mat)->u.s._31, (mat)->u.s._32, (mat)->u.s._33, (mat)->u.s._34); \
    TRACE("%f %f %f %f\n", (mat)->u.s._41, (mat)->u.s._42, (mat)->u.s._43, (mat)->u.s._44); \
66 67
    memcpy(gl_mat, (mat), 16 * sizeof(float));                                              \
} while (0)
68

69
/* Apply the current values to the specified texture stage */
70
void setupTextureStates(LPDIRECT3DDEVICE8 iface, DWORD Stage, DWORD Flags) {
71
    ICOM_THIS(IDirect3DDevice8Impl,iface);
72
    int i = 0;
73
    float col[4];
74
    BOOL changeTexture = TRUE;
75 76

    TRACE("-----------------------> Updating the texture at stage %ld to have new texture state information\n", Stage);
77
    for (i = 1; i < HIGHEST_TEXTURE_STATE; i++) {
78

79 80 81
        BOOL skip = FALSE;

        switch (i) {
82 83 84 85 86 87 88 89
        /* Performance: For texture states where multiples effect the outcome, only bother
              applying the last one as it will pick up all the other values                */
        case D3DTSS_COLORARG0:  /* Will be picked up when setting color op */
        case D3DTSS_COLORARG1:  /* Will be picked up when setting color op */
        case D3DTSS_COLORARG2:  /* Will be picked up when setting color op */
        case D3DTSS_ALPHAARG0:  /* Will be picked up when setting alpha op */
        case D3DTSS_ALPHAARG1:  /* Will be picked up when setting alpha op */
        case D3DTSS_ALPHAARG2:  /* Will be picked up when setting alpha op */
90
           skip = TRUE;
91
           break;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

        /* Performance: If the texture states only impact settings for the texture unit 
             (compared to the texture object) then there is no need to reapply them. The
             only time they need applying is the first time, since we cheat and put the  
             values into the stateblock without applying.                                
             Per-texture unit: texture function (eg. combine), ops and args
                               texture env color                                               
                               texture generation settings                               
           Note: Due to some special conditions there may be a need to do particular ones
             of these, which is what the Flags allows                                     */
        case D3DTSS_COLOROP:       
        case D3DTSS_TEXCOORDINDEX:
            if (!(Flags == REAPPLY_ALL)) skip=TRUE;
            break;

        case D3DTSS_ALPHAOP:       
            if (!(Flags & REAPPLY_ALPHAOP)) skip=TRUE;
            break;

111
        default:
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
            skip = FALSE;
        }

        if (skip == FALSE) {
           /* Performance: Only change to this texture if we have to */
           if (changeTexture) {
               /* Make appropriate texture active */
               if (GL_SUPPORT(ARB_MULTITEXTURE)) {
#if defined(GL_VERSION_1_3)
                   glActiveTexture(GL_TEXTURE0 + Stage);
#else
                   glActiveTextureARB(GL_TEXTURE0_ARB + Stage);
#endif
                   checkGLcall("glActiveTextureARB");
                } else if (Stage > 0) {
                    FIXME("Program using multiple concurrent textures which this opengl implementation doesnt support\n");
                }
                changeTexture = FALSE;
           }

           /* Now apply the change */
133 134
           IDirect3DDevice8Impl_SetTextureStageState(iface, Stage, i, This->StateBlock->texture_state[Stage][i]);
        }
135 136 137
    }

    /* Note the D3DRS value applies to all textures, but GL has one
138 139
     *  per texture, so apply it now ready to be used!
     */
140
    D3DCOLORTOGLFLOAT4(This->StateBlock->renderstate[D3DRS_TEXTUREFACTOR], col);
141 142 143 144 145 146
    glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, &col[0]);
    checkGLcall("glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color);");

    TRACE("-----------------------> Updated the texture at stage %ld to have new texture state information\n", Stage);
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
/* Setup this textures matrix */
static void set_texture_matrix(float *smat, DWORD flags)
{
    float mat[16];

    glMatrixMode(GL_TEXTURE);

    if (flags == D3DTTFF_DISABLE) {
        glLoadIdentity();
        checkGLcall("glLoadIdentity()");
        return;
    }

    if (flags == (D3DTTFF_COUNT1|D3DTTFF_PROJECTED)) {
        ERR("Invalid texture transform flags: D3DTTFF_COUNT1|D3DTTFF_PROJECTED\n");
        checkGLcall("glLoadIdentity()");
        return;
    }

    memcpy(mat, smat, 16*sizeof(float));

    switch (flags & ~D3DTTFF_PROJECTED) {
    case D3DTTFF_COUNT1: mat[1] = mat[5] = mat[9] = mat[13] = 0;
    case D3DTTFF_COUNT2: mat[2] = mat[6] = mat[10] = mat[14] = 0;
    default: mat[3] = mat[7] = mat[11] = 0, mat[15] = 1;
    }
    
    if (flags & D3DTTFF_PROJECTED) switch (flags & ~D3DTTFF_PROJECTED) {
    case D3DTTFF_COUNT2:
        mat[3] = mat[1], mat[7] = mat[5], mat[11] = mat[9], mat[15] = mat[13];
        mat[1] = mat[5] = mat[9] = mat[13] = 0;
        break;
    case D3DTTFF_COUNT3:
        mat[3] = mat[2], mat[7] = mat[6], mat[11] = mat[10], mat[15] = mat[14];
        mat[2] = mat[6] = mat[10] = mat[14] = 0;
        break;
    }
    glLoadMatrixf(mat);
    checkGLcall("glLoadMatrixf(mat)");
}

188 189 190 191 192 193
/* IDirect3D IUnknown parts follow: */
HRESULT WINAPI IDirect3DDevice8Impl_QueryInterface(LPDIRECT3DDEVICE8 iface,REFIID riid,LPVOID *ppobj)
{
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    if (IsEqualGUID(riid, &IID_IUnknown)
Raphael Junqueira's avatar
Raphael Junqueira committed
194
        || IsEqualGUID(riid, &IID_IDirect3DDevice8)) {
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        IDirect3DDevice8Impl_AddRef(iface);
        *ppobj = This;
        return D3D_OK;
    }

    WARN("(%p)->(%s,%p),not found\n",This,debugstr_guid(riid),ppobj);
    return E_NOINTERFACE;
}

ULONG WINAPI IDirect3DDevice8Impl_AddRef(LPDIRECT3DDEVICE8 iface) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : AddRef from %ld\n", This, This->ref);
    return ++(This->ref);
}

ULONG WINAPI IDirect3DDevice8Impl_Release(LPDIRECT3DDEVICE8 iface) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    ULONG ref = --This->ref;
    TRACE("(%p) : ReleaseRef to %ld\n", This, This->ref);
    if (ref == 0) {
215 216
      IDirect3DDevice8Impl_CleanRender(iface);
      HeapFree(GetProcessHeap(), 0, This);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    }
    return ref;
}

/* IDirect3DDevice Interface follow: */
HRESULT  WINAPI  IDirect3DDevice8Impl_TestCooperativeLevel(LPDIRECT3DDEVICE8 iface) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : stub\n", This);    /* No way of notifying yet! */
    return D3D_OK;
}

UINT     WINAPI  IDirect3DDevice8Impl_GetAvailableTextureMem(LPDIRECT3DDEVICE8 iface) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : stub, emulating 32Mb for now\n", This);
    /*
     * pretend we have 32MB of any type of memory queried.
     */
    return (1024*1024*32);
}

HRESULT  WINAPI  IDirect3DDevice8Impl_ResourceManagerDiscardBytes(LPDIRECT3DDEVICE8 iface, DWORD Bytes) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetDirect3D(LPDIRECT3DDEVICE8 iface, IDirect3D8** ppD3D8) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : returning %p\n", This, This->direct3d8);

    /* Inc ref count */
    IDirect3D8_AddRef((LPDIRECT3D8) This->direct3d8);

    *ppD3D8 = (IDirect3D8 *)This->direct3d8;
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetDeviceCaps(LPDIRECT3DDEVICE8 iface, D3DCAPS8* pCaps) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub, calling idirect3d for now\n", This);
    IDirect3D8Impl_GetDeviceCaps((LPDIRECT3D8) This->direct3d8, This->adapterNo, This->devType, pCaps);
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetDisplayMode(LPDIRECT3DDEVICE8 iface, D3DDISPLAYMODE* pMode) {

    HDC hdc;
    int bpp = 0;

    ICOM_THIS(IDirect3DDevice8Impl,iface);
    pMode->Width        = GetSystemMetrics(SM_CXSCREEN);
    pMode->Height       = GetSystemMetrics(SM_CYSCREEN);
    pMode->RefreshRate  = 85; /*FIXME: How to identify? */

    hdc = CreateDCA("DISPLAY", NULL, NULL, NULL);
    bpp = GetDeviceCaps(hdc, BITSPIXEL);
    DeleteDC(hdc);

    switch (bpp) {
    case  8: pMode->Format       = D3DFMT_R8G8B8; break;
    case 16: pMode->Format       = D3DFMT_R5G6B5; break;
274
    case 24: /*pMode->Format       = D3DFMT_R8G8B8; break; */
275
    case 32: pMode->Format       = D3DFMT_A8R8G8B8; break;
276 277 278
    default: 
       FIXME("Unrecognized display mode format\n");
       pMode->Format       = D3DFMT_UNKNOWN;
279 280
    }

281 282
    FIXME("(%p) : returning w(%d) h(%d) rr(%d) fmt(%u,%s)\n", This, pMode->Width, pMode->Height, pMode->RefreshRate, 
	  pMode->Format, debug_d3dformat(pMode->Format));
283 284 285 286
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetCreationParameters(LPDIRECT3DDEVICE8 iface, D3DDEVICE_CREATION_PARAMETERS *pParameters) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
287 288 289
    TRACE("(%p) copying to %p\n", This, pParameters);    
    memcpy(pParameters, &This->CreateParms, sizeof(D3DDEVICE_CREATION_PARAMETERS));
    return D3D_OK;
290 291
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetCursorProperties(LPDIRECT3DDEVICE8 iface, UINT XHotSpot, UINT YHotSpot, IDirect3DSurface8* pCursorBitmap) {
292
    IDirect3DSurface8Impl* pSur = (IDirect3DSurface8Impl*) pCursorBitmap;
293
    ICOM_THIS(IDirect3DDevice8Impl,iface);
294 295 296 297 298 299 300 301 302 303 304 305 306 307
    TRACE("(%p) : Spot Pos(%u,%u)\n", This, XHotSpot, YHotSpot);

    if (D3DFMT_A8R8G8B8 != pSur->myDesc.Format) {
      ERR("(%p) : surface(%p) have a invalid format\n", This, pCursorBitmap);
      return D3DERR_INVALIDCALL;
    }
    if (32 != pSur->myDesc.Height || 32 != pSur->myDesc.Width) {
      ERR("(%p) : surface(%p) have a invalid size\n", This, pCursorBitmap);
      return D3DERR_INVALIDCALL;
    }

    This->xHotSpot = XHotSpot;
    This->yHotSpot = YHotSpot;
    return D3D_OK;
308
}
309
void     WINAPI  IDirect3DDevice8Impl_SetCursorPosition(LPDIRECT3DDEVICE8 iface, UINT XScreenSpace, UINT YScreenSpace, DWORD Flags) {
310
    ICOM_THIS(IDirect3DDevice8Impl,iface);
311 312 313 314
    TRACE("(%p) : SetPos to (%u,%u)\n", This, XScreenSpace, YScreenSpace);
    This->xScreenSpace = XScreenSpace;
    This->yScreenSpace = YScreenSpace;
    return;
315 316 317
}
BOOL     WINAPI  IDirect3DDevice8Impl_ShowCursor(LPDIRECT3DDEVICE8 iface, BOOL bShow) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
318 319 320
    TRACE("(%p) : visible(%d)\n", This, bShow); 
    This->bCursorVisible = bShow;
    return D3D_OK;
321 322
}
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateAdditionalSwapChain(LPDIRECT3DDEVICE8 iface, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain8** pSwapChain) {
323
    IDirect3DSwapChain8Impl* object;
324
    ICOM_THIS(IDirect3DDevice8Impl,iface);
325
    FIXME("(%p) : stub\n", This);
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DDevice8Impl));
    if (NULL == object) {
      return D3DERR_OUTOFVIDEOMEMORY;
    }
    object->lpVtbl = &Direct3DSwapChain8_Vtbl;
    object->ref = 1;

    TRACE("(%p)->(DepthStencil:(%u,%s), BackBufferFormat:(%u,%s))\n", This, 
	  pPresentationParameters->AutoDepthStencilFormat, debug_d3dformat(pPresentationParameters->AutoDepthStencilFormat),
	  pPresentationParameters->BackBufferFormat, debug_d3dformat(pPresentationParameters->BackBufferFormat));

    if (pPresentationParameters->Windowed && ((pPresentationParameters->BackBufferWidth  == 0) ||
                                              (pPresentationParameters->BackBufferHeight == 0))) {
      RECT Rect;
      
      GetClientRect(This->win_handle, &Rect);
      
      if (pPresentationParameters->BackBufferWidth == 0) {
	pPresentationParameters->BackBufferWidth = Rect.right;
	TRACE("Updating width to %d\n", pPresentationParameters->BackBufferWidth);
      }
      if (pPresentationParameters->BackBufferHeight == 0) {
	pPresentationParameters->BackBufferHeight = Rect.bottom;
	TRACE("Updating height to %d\n", pPresentationParameters->BackBufferHeight);
      }
    }
    
    /* Save the presentation parms now filled in correctly */
    memcpy(&object->PresentParms, pPresentationParameters, sizeof(D3DPRESENT_PARAMETERS));

    IDirect3DDevice8Impl_CreateRenderTarget((LPDIRECT3DDEVICE8) object,
                                            pPresentationParameters->BackBufferWidth,
                                            pPresentationParameters->BackBufferHeight,
                                            pPresentationParameters->BackBufferFormat,
					    pPresentationParameters->MultiSampleType,
					    TRUE,
                                            (LPDIRECT3DSURFACE8*) &object->frontBuffer);
    
    IDirect3DDevice8Impl_CreateRenderTarget((LPDIRECT3DDEVICE8) object,
                                            pPresentationParameters->BackBufferWidth,
                                            pPresentationParameters->BackBufferHeight,
                                            pPresentationParameters->BackBufferFormat,
					    pPresentationParameters->MultiSampleType,
					    TRUE,
                                            (LPDIRECT3DSURFACE8*) &object->backBuffer);

    if (pPresentationParameters->EnableAutoDepthStencil) {
       IDirect3DDevice8Impl_CreateDepthStencilSurface((LPDIRECT3DDEVICE8) object,
	  					      pPresentationParameters->BackBufferWidth,
						      pPresentationParameters->BackBufferHeight,
						      pPresentationParameters->AutoDepthStencilFormat,
						      D3DMULTISAMPLE_NONE,
						      (LPDIRECT3DSURFACE8*) &object->depthStencilBuffer);
    } else {
      object->depthStencilBuffer = NULL;
    }

    *pSwapChain = (IDirect3DSwapChain8*) object;
385
    return D3D_OK;
386 387 388 389 390 391 392 393 394 395 396
}
HRESULT  WINAPI  IDirect3DDevice8Impl_Reset(LPDIRECT3DDEVICE8 iface, D3DPRESENT_PARAMETERS* pPresentationParameters) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_Present(LPDIRECT3DDEVICE8 iface, CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : complete stub!\n", This);

    ENTER_GL();

397
    glXSwapBuffers(This->display, This->drawable);
398
    /* Dont call checkGLcall, as glGetError is not applicable here */
399 400
    TRACE("glXSwapBuffers called, Starting new frame\n");

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    /* FPS support */
    if (TRACE_ON(fps))
    {
        static long prev_time, frames;

        DWORD time = GetTickCount();
        frames++;
        /* every 1.5 seconds */
        if (time - prev_time > 1500) {
            TRACE_(fps)("@@@ %.2ffps\n", 1000.0*frames/(time - prev_time));
            prev_time = time;
            frames = 0;
        }
    }

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
#if defined(FRAME_DEBUGGING)
{
    if (GetFileAttributesA("C:\\D3DTRACE") != INVALID_FILE_ATTRIBUTES) {
        if (!isOn) {
            isOn = TRUE;
            FIXME("Enabling D3D Trace\n");
            __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 1);
#if defined(SHOW_FRAME_MAKEUP)
            FIXME("Singe Frame snapshots Starting\n");
            isDumpingFrames = TRUE;
            glClear(GL_COLOR_BUFFER_BIT);
#endif

#if defined(SINGLE_FRAME_DEBUGGING)
        } else {
#if defined(SHOW_FRAME_MAKEUP)
            FIXME("Singe Frame snapshots Finishing\n");
            isDumpingFrames = FALSE;
#endif
            FIXME("Singe Frame trace complete\n");
            DeleteFileA("C:\\D3DTRACE");
            __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
#endif
        }
    } else {
        if (isOn) {
            isOn = FALSE;
#if defined(SHOW_FRAME_MAKEUP)
            FIXME("Singe Frame snapshots Finishing\n");
            isDumpingFrames = FALSE;
#endif
            FIXME("Disabling D3D Trace\n");
            __WINE_SET_DEBUGGING(__WINE_DBCL_TRACE, __wine_dbch_d3d, 0);
        }
    }
}
#endif
453 454 455 456 457

    LEAVE_GL();

    return D3D_OK;
}
458
HRESULT  WINAPI  IDirect3DDevice8Impl_GetBackBuffer(LPDIRECT3DDEVICE8 iface, UINT BackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface8** ppBackBuffer) {
459 460 461 462
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    *ppBackBuffer = (LPDIRECT3DSURFACE8) This->backBuffer;
    TRACE("(%p) : BackBuf %d Type %d returning %p\n", This, BackBuffer, Type, *ppBackBuffer);

463
    if (BackBuffer > This->PresentParms.BackBufferCount - 1) {
464 465
        FIXME("Only one backBuffer currently supported\n");
        return D3DERR_INVALIDCALL;
466 467
    }

468 469 470 471 472 473 474
    /* Note inc ref on returned surface */
    IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) *ppBackBuffer);

    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetRasterStatus(LPDIRECT3DDEVICE8 iface, D3DRASTER_STATUS* pRasterStatus) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
475 476
    FIXME("(%p) : stub\n", This);    
    return D3D_OK;
477
}
478
void     WINAPI  IDirect3DDevice8Impl_SetGammaRamp(LPDIRECT3DDEVICE8 iface, DWORD Flags, CONST D3DGAMMARAMP* pRamp) {
479
    HDC hDC;
480
    ICOM_THIS(IDirect3DDevice8Impl,iface);
481 482 483 484 485

    FIXME("(%p) : pRamp@%p\n", This, pRamp);
    hDC = GetDC(This->win_handle);
    SetDeviceGammaRamp(hDC, (LPVOID) pRamp);
    ReleaseDC(This->win_handle, hDC);
486
    return;
487 488
}
void     WINAPI  IDirect3DDevice8Impl_GetGammaRamp(LPDIRECT3DDEVICE8 iface, D3DGAMMARAMP* pRamp) {
489
    HDC hDC;
490
    ICOM_THIS(IDirect3DDevice8Impl,iface);
491 492 493 494 495

    FIXME("(%p) : pRamp@%p\n", This, pRamp);
    hDC = GetDC(This->win_handle);
    GetDeviceGammaRamp(hDC, pRamp);
    ReleaseDC(This->win_handle, hDC);
496
    return;
497 498
}
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateTexture(LPDIRECT3DDEVICE8 iface, UINT Width, UINT Height, UINT Levels, DWORD Usage,
499
                                                    D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture8** ppTexture) {
500 501 502 503 504 505 506 507
    IDirect3DTexture8Impl *object;
    int i;
    UINT tmpW;
    UINT tmpH;

    ICOM_THIS(IDirect3DDevice8Impl,iface);

    /* Allocate the storage for the device */
508
    TRACE("(%p) : W(%d) H(%d), Lvl(%d) Usage(%ld), Fmt(%u,%s), Pool(%d)\n", This, Width, Height, Levels, Usage, Format, debug_d3dformat(Format), Pool);
509 510
    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DTexture8Impl));
    object->lpVtbl = &Direct3DTexture8_Vtbl;
511
    object->Device = This;
512 513 514 515 516 517 518
    object->ResourceType = D3DRTYPE_TEXTURE;
    object->ref = 1;
    object->width = Width;
    object->height = Height;
    object->levels = Levels;
    object->usage = Usage;
    object->format = Format;
519

520 521 522 523 524 525
    /* Calculate levels for mip mapping */
    if (Levels == 0) {
        object->levels++;
        tmpW = Width;
        tmpH = Height;
        while (tmpW > 1 && tmpH > 1) {
526
            tmpW = max(1, tmpW / 2);
527 528 529 530 531 532 533 534 535
            tmpH = max(1, tmpH / 2);
            object->levels++;
        }
        TRACE("Calculated levels = %d\n", object->levels);
    }

    /* Generate all the surfaces */
    tmpW = Width;
    tmpH = Height;
536
    for (i = 0; i < object->levels; i++) 
537 538
    {
        IDirect3DDevice8Impl_CreateImageSurface(iface, tmpW, tmpH, Format, (LPDIRECT3DSURFACE8*) &object->surfaces[i]);
539
        object->surfaces[i]->Container = (IUnknown*) object;
540
        object->surfaces[i]->myDesc.Usage = Usage;
541 542
        object->surfaces[i]->myDesc.Pool = Pool;
	/** 
543
	 * As written in msdn in IDirect3DTexture8::LockRect
544 545 546 547 548
	 *  Textures created in D3DPOOL_DEFAULT are not lockable.
	 */
	if (D3DPOOL_DEFAULT == Pool) {
	  object->surfaces[i]->lockable = FALSE;
	}
549 550

        TRACE("Created surface level %d @ %p, memory at %p\n", i, object->surfaces[i], object->surfaces[i]->allocatedMemory);
551
        tmpW = max(1, tmpW / 2);
552 553 554
        tmpH = max(1, tmpH / 2);
    }

555
    *ppTexture = (LPDIRECT3DTEXTURE8) object;
556
    TRACE("(%p) : Created texture %p\n", This, object);
557 558
    return D3D_OK;
}
559 560 561
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateVolumeTexture(LPDIRECT3DDEVICE8 iface, 
                                                          UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, 
                                                          D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture8** ppVolumeTexture) {
562 563

    IDirect3DVolumeTexture8Impl *object;
564 565 566 567 568
    int i;
    UINT tmpW;
    UINT tmpH;
    UINT tmpD;

569 570 571
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    /* Allocate the storage for it */
572
    TRACE("(%p) : W(%d) H(%d) D(%d), Lvl(%d) Usage(%ld), Fmt(%u,%s), Pool(%s)\n", This, Width, Height, Depth, Levels, Usage, Format, debug_d3dformat(Format), debug_d3dpool(Pool));
573 574 575
    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DVolumeTexture8Impl));
    object->lpVtbl = &Direct3DVolumeTexture8_Vtbl;
    object->ResourceType = D3DRTYPE_VOLUMETEXTURE;
576
    object->Device = This;
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
    object->ref = 1;

    object->width = Width;
    object->height = Height;
    object->depth = Depth;
    object->levels = Levels;
    object->usage = Usage;
    object->format = Format;

    /* Calculate levels for mip mapping */
    if (Levels == 0) {
        object->levels++;
        tmpW = Width;
        tmpH = Height;
        tmpD = Depth;
        while (tmpW > 1 && tmpH > 1 && tmpD > 1) {
593
            tmpW = max(1, tmpW / 2);
594 595 596 597 598 599 600 601 602 603 604 605
            tmpH = max(1, tmpH / 2);
            tmpD = max(1, tmpD / 2);
            object->levels++;
        }
        TRACE("Calculated levels = %d\n", object->levels);
    }

    /* Generate all the surfaces */
    tmpW = Width;
    tmpH = Height;
    tmpD = Depth;

606
    for (i = 0; i < object->levels; i++) 
607
    {
608
        IDirect3DVolume8Impl* volume;
609 610 611 612 613 614

        /* Create the volume - No entry point for this seperately?? */
        volume  = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DVolume8Impl));
        object->volumes[i] = (IDirect3DVolume8Impl *) volume;

        volume->lpVtbl = &Direct3DVolume8_Vtbl;
615
        volume->Device = This;
616
        volume->ResourceType = D3DRTYPE_VOLUME;
617
        volume->Container = (IUnknown*) object;
618 619
        volume->ref = 1;

620 621 622 623 624 625 626
        volume->myDesc.Width  = Width;
        volume->myDesc.Height = Height;
        volume->myDesc.Depth  = Depth;
        volume->myDesc.Format = Format;
        volume->myDesc.Type   = D3DRTYPE_VOLUME;
        volume->myDesc.Pool   = Pool;
        volume->myDesc.Usage  = Usage;
Raphael Junqueira's avatar
Raphael Junqueira committed
627
        volume->bytesPerPixel   = D3DFmtGetBpp(This, Format);
628 629 630
        volume->myDesc.Size     = (Width * volume->bytesPerPixel) * Height * Depth;
        volume->allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, volume->myDesc.Size);

631 632 633 634 635 636
	volume->lockable = TRUE;
	volume->locked = FALSE;
	memset(&volume->lockedBox, 0, sizeof(D3DBOX));
	volume->Dirty = FALSE;
	IDirect3DVolume8Impl_CleanDirtyBox((LPDIRECT3DVOLUME8) volume);

637 638 639
        TRACE("(%p) : Volume at w(%d) h(%d) d(%d) fmt(%u,%s) surf@%p, surfmem@%p, %d bytes\n", 
              This, Width, Height, Depth, Format, debug_d3dformat(Format),
              volume, volume->allocatedMemory, volume->myDesc.Size);
640

641
        tmpW = max(1, tmpW / 2);
642 643 644 645
        tmpH = max(1, tmpH / 2);
        tmpD = max(1, tmpD / 2);
    }

646
    *ppVolumeTexture = (LPDIRECT3DVOLUMETEXTURE8) object;
647
    TRACE("(%p) : Created volume texture %p\n", This, object);
648 649
    return D3D_OK;
}
650 651
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateCubeTexture(LPDIRECT3DDEVICE8 iface, UINT EdgeLength, UINT Levels, DWORD Usage, 
                                                        D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture8** ppCubeTexture) {
652 653 654 655 656 657 658

    IDirect3DCubeTexture8Impl *object;
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    int i,j;
    UINT tmpW;

    /* Allocate the storage for it */
659
    TRACE("(%p) : Len(%d), Lvl(%d) Usage(%ld), Fmt(%u,%s), Pool(%s)\n", This, EdgeLength, Levels, Usage, Format, debug_d3dformat(Format), debug_d3dpool(Pool));
660 661 662
    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DCubeTexture8Impl));
    object->lpVtbl = &Direct3DCubeTexture8_Vtbl;
    object->ref = 1;
663
    object->Device = This;
664 665 666 667 668 669 670 671 672 673 674 675
    object->ResourceType = D3DRTYPE_CUBETEXTURE;

    object->edgeLength = EdgeLength;
    object->levels = Levels;
    object->usage = Usage;
    object->format = Format;

    /* Calculate levels for mip mapping */
    if (Levels == 0) {
        object->levels++;
        tmpW = EdgeLength;
        while (tmpW > 1) {
676
            tmpW = max(1, tmpW / 2);
677 678 679 680 681 682 683
            object->levels++;
        }
        TRACE("Calculated levels = %d\n", object->levels);
    }

    /* Generate all the surfaces */
    tmpW = EdgeLength;
684
    for (i = 0; i < object->levels; i++) {
685
        /* Create the 6 faces */
686
        for (j = 0; j < 6; j++) {
687
           IDirect3DDevice8Impl_CreateImageSurface(iface, tmpW, tmpW, Format, (LPDIRECT3DSURFACE8*) &object->surfaces[j][i]);
688
           object->surfaces[j][i]->Container = (IUnknown*) object;
689
           object->surfaces[j][i]->myDesc.Usage = Usage;
690
           object->surfaces[j][i]->myDesc.Pool = Pool;
691
	   /** 
692
	    * As written in msdn in IDirect3DCubeTexture8::LockRect
693 694 695 696 697
	    *  Textures created in D3DPOOL_DEFAULT are not lockable.
	    */
	   if (D3DPOOL_DEFAULT == Pool) {
	     object->surfaces[j][i]->lockable = FALSE;
	   }
698 699 700

           TRACE("Created surface level %d @ %p, memory at %p\n", i, object->surfaces[j][i], object->surfaces[j][i]->allocatedMemory);
        }
Raphael Junqueira's avatar
Raphael Junqueira committed
701
        tmpW = max(1, tmpW / 2);
702 703 704
    }

    TRACE("(%p) : Iface@%p\n", This, object);
705
    *ppCubeTexture = (LPDIRECT3DCUBETEXTURE8) object;
706 707
    return D3D_OK;
}
708
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateVertexBuffer(LPDIRECT3DDEVICE8 iface, UINT Size, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer8** ppVertexBuffer) {
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
    IDirect3DVertexBuffer8Impl *object;

    ICOM_THIS(IDirect3DDevice8Impl,iface);

    /* Allocate the storage for the device */
    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DVertexBuffer8Impl));
    object->lpVtbl = &Direct3DVertexBuffer8_Vtbl;
    object->Device = This;
    object->ResourceType = D3DRTYPE_VERTEXBUFFER;
    object->ref = 1;
    object->allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Size);
    object->currentDesc.Usage = Usage;
    object->currentDesc.Pool  = Pool;
    object->currentDesc.FVF   = FVF;
    object->currentDesc.Size  = Size;

    TRACE("(%p) : Size=%d, Usage=%ld, FVF=%lx, Pool=%d - Memory@%p, Iface@%p\n", This, Size, Usage, FVF, Pool, object->allocatedMemory, object);

727
    *ppVertexBuffer = (LPDIRECT3DVERTEXBUFFER8) object;
728 729 730

    return D3D_OK;
}
731
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateIndexBuffer(LPDIRECT3DDEVICE8 iface, UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer8** ppIndexBuffer) {
732 733 734
    IDirect3DIndexBuffer8Impl *object;

    ICOM_THIS(IDirect3DDevice8Impl,iface);
735
    TRACE("(%p) : Len=%d, Use=%lx, Format=(%u,%s), Pool=%d\n", This, Length, Usage, Format, debug_d3dformat(Format), Pool);
736 737 738 739 740

    /* Allocate the storage for the device */
    object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DIndexBuffer8Impl));
    object->lpVtbl = &Direct3DIndexBuffer8_Vtbl;
    object->Device = This;
741
    object->ref = 1;
742 743 744 745 746 747 748 749 750 751 752 753
    object->ResourceType = D3DRTYPE_INDEXBUFFER;

    object->currentDesc.Type = D3DRTYPE_INDEXBUFFER;
    object->currentDesc.Usage = Usage;
    object->currentDesc.Pool  = Pool;
    object->currentDesc.Format  = Format;
    object->currentDesc.Size  = Length;

    object->allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, Length);

    TRACE("(%p) : Iface@%p allocatedMem @ %p\n", This, object, object->allocatedMemory);

754
    *ppIndexBuffer = (LPDIRECT3DINDEXBUFFER8) object;
755 756 757

    return D3D_OK;
}
758 759
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateRenderTarget(LPDIRECT3DDEVICE8 iface, UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, BOOL Lockable, IDirect3DSurface8** ppSurface) {
    IDirect3DSurface8Impl *object;
760
    ICOM_THIS(IDirect3DDevice8Impl,iface);
761
    
762
    object  = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DSurface8Impl));
763 764 765 766
    if (NULL == object) {
      *ppSurface = NULL;
      return D3DERR_OUTOFVIDEOMEMORY;
    }
767 768 769 770 771 772 773 774 775 776 777 778
    *ppSurface = (LPDIRECT3DSURFACE8) object;
    object->lpVtbl = &Direct3DSurface8_Vtbl;
    object->Device = This;
    object->ResourceType = D3DRTYPE_SURFACE;
    object->Container = (IUnknown*) This;

    object->ref = 1;
    object->myDesc.Width  = Width;
    object->myDesc.Height = Height;
    object->myDesc.Format = Format;
    object->myDesc.Type = D3DRTYPE_SURFACE;
    object->myDesc.Usage = D3DUSAGE_RENDERTARGET;
779
    object->myDesc.Pool = D3DPOOL_DEFAULT;
780
    object->myDesc.MultiSampleType = MultiSample;
Raphael Junqueira's avatar
Raphael Junqueira committed
781
    object->bytesPerPixel = D3DFmtGetBpp(This, Format);
782 783 784 785
    object->myDesc.Size = (Width * object->bytesPerPixel) * Height;
    object->allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, object->myDesc.Size);
    object->lockable = Lockable;
    object->locked = FALSE;
786 787 788
    memset(&object->lockedRect, 0, sizeof(RECT));
    IDirect3DSurface8Impl_CleanDirtyRect((LPDIRECT3DSURFACE8) object);

789
    TRACE("(%p) : w(%d) h(%d) fmt(%d,%s) lockable(%d) surf@%p, surfmem@%p, %d bytes\n", This, Width, Height, Format, debug_d3dformat(Format), Lockable, *ppSurface, object->allocatedMemory, object->myDesc.Size);
790
    return D3D_OK;
791
}
792 793 794
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateDepthStencilSurface(LPDIRECT3DDEVICE8 iface, UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, IDirect3DSurface8** ppSurface) {
    IDirect3DSurface8Impl *object;

795
    ICOM_THIS(IDirect3DDevice8Impl,iface);
796 797

    object  = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DSurface8Impl));
798 799 800 801
    if (NULL == object) {
      *ppSurface = NULL;
      return D3DERR_OUTOFVIDEOMEMORY;
    }
802 803 804 805 806 807 808 809 810 811 812 813
    *ppSurface = (LPDIRECT3DSURFACE8) object;
    object->lpVtbl = &Direct3DSurface8_Vtbl;
    object->Device = This;
    object->ResourceType = D3DRTYPE_SURFACE;
    object->Container = (IUnknown*) This;

    object->ref = 1;
    object->myDesc.Width  = Width;
    object->myDesc.Height = Height;
    object->myDesc.Format = Format;
    object->myDesc.Type = D3DRTYPE_SURFACE;
    object->myDesc.Usage = D3DUSAGE_DEPTHSTENCIL;
814
    object->myDesc.Pool = D3DPOOL_DEFAULT;
815
    object->myDesc.MultiSampleType = MultiSample;
Raphael Junqueira's avatar
Raphael Junqueira committed
816
    object->bytesPerPixel = D3DFmtGetBpp(This, Format);
817 818
    object->myDesc.Size = (Width * object->bytesPerPixel) * Height;
    object->allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, object->myDesc.Size);
819
    object->lockable = (D3DFMT_D16_LOCKABLE == Format) ? TRUE : FALSE;
820
    object->locked = FALSE;
821 822 823
    memset(&object->lockedRect, 0, sizeof(RECT));
    IDirect3DSurface8Impl_CleanDirtyRect((LPDIRECT3DSURFACE8) object);

824
    TRACE("(%p) : w(%d) h(%d) fmt(%d,%s) surf@%p, surfmem@%p, %d bytes\n", This, Width, Height, Format, debug_d3dformat(Format), *ppSurface, object->allocatedMemory, object->myDesc.Size);
825
    return D3D_OK;
826
}
827
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateImageSurface(LPDIRECT3DDEVICE8 iface, UINT Width, UINT Height, D3DFORMAT Format, IDirect3DSurface8** ppSurface) {
828 829 830 831 832 833 834 835 836
    IDirect3DSurface8Impl *object;

    ICOM_THIS(IDirect3DDevice8Impl,iface);

    object  = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirect3DSurface8Impl));
    *ppSurface = (LPDIRECT3DSURFACE8) object;
    object->lpVtbl = &Direct3DSurface8_Vtbl;
    object->Device = This;
    object->ResourceType = D3DRTYPE_SURFACE;
837
    object->Container = (IUnknown*) This;
838 839

    object->ref = 1;
840 841 842
    object->myDesc.Width  = Width;
    object->myDesc.Height = Height;
    object->myDesc.Format = Format;
843
    object->myDesc.Type = D3DRTYPE_SURFACE;
844 845
    object->myDesc.Usage = 0;
    object->myDesc.Pool = D3DPOOL_SYSTEMMEM;
Raphael Junqueira's avatar
Raphael Junqueira committed
846
    object->bytesPerPixel = D3DFmtGetBpp(This, Format);
847 848
    object->myDesc.Size = (Width * object->bytesPerPixel) * Height;
    object->allocatedMemory = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, object->myDesc.Size);
849 850
    object->lockable = TRUE;
    object->locked = FALSE;
851 852
    memset(&object->lockedRect, 0, sizeof(RECT));
    IDirect3DSurface8Impl_CleanDirtyRect((LPDIRECT3DSURFACE8) object);
853

854
    TRACE("(%p) : w(%d) h(%d) fmt(%d,%s) surf@%p, surfmem@%p, %d bytes\n", This, Width, Height, Format, debug_d3dformat(Format), *ppSurface, object->allocatedMemory, object->myDesc.Size);
855 856
    return D3D_OK;
}
857 858 859
HRESULT  WINAPI  IDirect3DDevice8Impl_CopyRects(LPDIRECT3DDEVICE8 iface, 
                                                IDirect3DSurface8* pSourceSurface, CONST RECT* pSourceRectsArray, UINT cRects,
                                                IDirect3DSurface8* pDestinationSurface, CONST POINT* pDestPointsArray) {
860

861
    HRESULT rc = D3D_OK;
862
    IDirect3DBaseTexture8* texture = NULL;
863

864

865 866
    IDirect3DSurface8Impl* src = (IDirect3DSurface8Impl*) pSourceSurface;
    IDirect3DSurface8Impl* dst = (IDirect3DSurface8Impl*) pDestinationSurface;
867 868

    ICOM_THIS(IDirect3DDevice8Impl,iface);
869
    TRACE("(%p) pSrcSur=%p, pSourceRects=%p, cRects=%d, pDstSur=%p, pDestPtsArr=%p\n", This,
870 871
          pSourceSurface, pSourceRectsArray, cRects, pDestinationSurface, pDestPointsArray);

872 873 874
    /* Note: Not sure about the d3dfmt_unknown bit, but seems to avoid a problem inside
         a sample and doesnt seem to break anything as far as I can tell               */
    if (src->myDesc.Format != dst->myDesc.Format && (dst->myDesc.Format != D3DFMT_UNKNOWN)) {
875 876 877
        TRACE("Formats do not match (%x,%s) / (%x,%s)\n", 
               src->myDesc.Format, debug_d3dformat(src->myDesc.Format), 
               dst->myDesc.Format, debug_d3dformat(dst->myDesc.Format));
878
        rc = D3DERR_INVALIDCALL;
879

880
    } else if (dst->myDesc.Format == D3DFMT_UNKNOWN) {
881 882 883 884
        TRACE("Converting dest to same format as source, since dest was unknown\n");
        dst->myDesc.Format = src->myDesc.Format;

        /* Convert container as well */
885
        IDirect3DSurface8Impl_GetContainer((LPDIRECT3DSURFACE8) dst, &IID_IDirect3DBaseTexture8, (void**) &texture); /* FIXME: Which refid? */
886
        if (texture != NULL) {
887
            ((IDirect3DBaseTexture8Impl*) texture)->format = src->myDesc.Format;
888
	    /** Releasing texture after GetContainer */
889 890
	    IDirect3DBaseTexture8_Release(texture);
	    texture = NULL;
891
        }
892 893 894
    }

    /* Quick if complete copy ... */
895
    if (rc == D3D_OK && cRects == 0 && pSourceRectsArray == NULL && pDestPointsArray == NULL) {
896

897
      if (src->myDesc.Width == dst->myDesc.Width && src->myDesc.Height == dst->myDesc.Height) {
898

899 900 901 902 903
        D3DLOCKED_RECT lrSrc;
        D3DLOCKED_RECT lrDst;
        IDirect3DSurface8Impl_LockRect((LPDIRECT3DSURFACE8) src, &lrSrc, NULL, D3DLOCK_READONLY);
	IDirect3DSurface8Impl_LockRect((LPDIRECT3DSURFACE8) dst, &lrDst, NULL, 0L);
        TRACE("Locked src and dst, Direct copy as surfaces are equal, w=%d, h=%d\n", dst->myDesc.Width, dst->myDesc.Height);
904

905 906 907
	memcpy(lrDst.pBits, lrSrc.pBits, src->myDesc.Size);
 
        IDirect3DSurface8Impl_UnlockRect((LPDIRECT3DSURFACE8) src);
908
        rc = IDirect3DSurface8Impl_UnlockRect((LPDIRECT3DSURFACE8) dst);
909 910
        TRACE("Unlocked src and dst\n");

911 912 913 914 915 916 917
      } else {

	FIXME("Wanted to copy all surfaces but size not compatible\n");
        rc = D3DERR_INVALIDCALL;

      }

918
    } else {
919 920 921

      if (NULL != pSourceRectsArray && NULL != pDestPointsArray) {

922
        int bytesPerPixel = ((IDirect3DSurface8Impl*) pSourceSurface)->bytesPerPixel;
923
        int i;
Jason Edmeades's avatar
Jason Edmeades committed
924
        /* Copy rect by rect */
925 926 927 928
        for (i = 0; i < cRects; i++) {
            CONST RECT*  r = &pSourceRectsArray[i];
            CONST POINT* p = &pDestPointsArray[i];
            int copyperline = (r->right - r->left) * bytesPerPixel;
Jason Edmeades's avatar
Jason Edmeades committed
929
            int j;
930 931 932 933
            D3DLOCKED_RECT lrSrc;
            D3DLOCKED_RECT lrDst;
            RECT dest_rect;
 
Jason Edmeades's avatar
Jason Edmeades committed
934

935
            TRACE("Copying rect %d (%ld,%ld),(%ld,%ld) -> (%ld,%ld)\n", i, r->left, r->top, r->right, r->bottom, p->x, p->y);
Jason Edmeades's avatar
Jason Edmeades committed
936

937 938 939
            IDirect3DSurface8Impl_LockRect((LPDIRECT3DSURFACE8) src, &lrSrc, r, D3DLOCK_READONLY);
            dest_rect.left  = p->x;
            dest_rect.top   = p->y;
940
            dest_rect.right = p->x + (r->right - r->left);
941 942
            dest_rect.left  = p->y + (r->bottom - r->top);
            IDirect3DSurface8Impl_LockRect((LPDIRECT3DSURFACE8) dst, &lrDst, &dest_rect, 0L);
943 944
            TRACE("Locked src and dst\n");

Jason Edmeades's avatar
Jason Edmeades committed
945
            /* Find where to start */
946
#if 0
Jason Edmeades's avatar
Jason Edmeades committed
947
            from = copyfrom + (r->top * pitchFrom) + (r->left * bytesPerPixel);
948
            to   = copyto   + (p->y * pitchTo) + (p->x * bytesPerPixel);
Jason Edmeades's avatar
Jason Edmeades committed
949
            /* Copy line by line */
950 951
            for (j = 0; j < (r->bottom - r->top); j++) {
               memcpy(to + (j * pitchTo), from + (j * pitchFrom), copyperline);
Jason Edmeades's avatar
Jason Edmeades committed
952
            }
953
#endif
954

955 956 957 958 959
	    for (j = 0; j < (r->bottom - r->top); j++) {
               memcpy((char*) lrDst.pBits + (j * lrDst.Pitch), (char*) lrSrc.pBits + (j * lrSrc.Pitch), copyperline);
	    }

            IDirect3DSurface8Impl_UnlockRect((LPDIRECT3DSURFACE8) src);
960
            rc = IDirect3DSurface8Impl_UnlockRect((LPDIRECT3DSURFACE8) dst);
961
            TRACE("Unlocked src and dst\n");
Jason Edmeades's avatar
Jason Edmeades committed
962
        }
963 964 965 966 967 968 969
      
      } else {
      
	FIXME("Wanted to copy partial surfaces not implemented\n");
        rc = D3DERR_INVALIDCALL;	
	
      }
970
    }
971

972
    return rc;
973
}
974
HRESULT  WINAPI  IDirect3DDevice8Impl_UpdateTexture(LPDIRECT3DDEVICE8 iface, IDirect3DBaseTexture8* pSourceTexture, IDirect3DBaseTexture8* pDestinationTexture) {
975 976 977 978 979
    IDirect3DBaseTexture8Impl* src = (IDirect3DBaseTexture8Impl*) pSourceTexture;
    IDirect3DBaseTexture8Impl* dst = (IDirect3DBaseTexture8Impl*) pDestinationTexture;
    D3DRESOURCETYPE srcType;
    D3DRESOURCETYPE dstType;

980
    ICOM_THIS(IDirect3DDevice8Impl,iface);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    TRACE("(%p) : first try\n", This);

    srcType = IDirect3DBaseTexture8Impl_GetType(pSourceTexture);
    dstType = IDirect3DBaseTexture8Impl_GetType(pDestinationTexture);

    if (srcType != dstType) {
      return D3DERR_INVALIDCALL;
    }
    if (D3DPOOL_SYSTEMMEM != IDirect3DResource8Impl_GetPool((LPDIRECT3DRESOURCE8) src)) {
      return D3DERR_INVALIDCALL;
    }
    if (D3DPOOL_DEFAULT != IDirect3DResource8Impl_GetPool((LPDIRECT3DRESOURCE8) dst)) {
      return D3DERR_INVALIDCALL;
    }
    if (IDirect3DBaseTexture8Impl_IsDirty(pSourceTexture)) {
      /** Only copy Dirty textures */
      DWORD srcLevelCnt = IDirect3DBaseTexture8Impl_GetLevelCount(pSourceTexture);
      DWORD dstLevelCnt = IDirect3DBaseTexture8Impl_GetLevelCount(pDestinationTexture);
      DWORD skipLevels = (dstLevelCnt < srcLevelCnt) ? srcLevelCnt - dstLevelCnt : 0;
      UINT i, j;

      for (i = skipLevels; i < srcLevelCnt; ++i) {
	HRESULT hr;

	switch (srcType) { 
	case D3DRTYPE_TEXTURE:
	  {
	    IDirect3DSurface8* srcSur = NULL;
	    IDirect3DSurface8* dstSur = NULL;
	    hr = IDirect3DTexture8Impl_GetSurfaceLevel((LPDIRECT3DTEXTURE8) src, i, &srcSur);
	    hr = IDirect3DTexture8Impl_GetSurfaceLevel((LPDIRECT3DTEXTURE8) dst, i - skipLevels, &dstSur);
1012 1013 1014 1015 1016

            /* Fixme: Work out how to just do the dirty regions (src or dst dirty region, and what
                        about dst with less levels than the source?)                               */
	    IDirect3DDevice8Impl_CopyRects(iface, srcSur, NULL, 0, dstSur, NULL);

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
	    IDirect3DSurface8Impl_Release(srcSur);
	    IDirect3DSurface8Impl_Release(dstSur);
	  }
	  break;
	case D3DRTYPE_VOLUMETEXTURE:
	  {
	    FIXME("D3DRTYPE_VOLUMETEXTURE reload currently not implemented\n");
	  }
	  break;
	case D3DRTYPE_CUBETEXTURE:
	  {
	    IDirect3DSurface8* srcSur = NULL;
	    IDirect3DSurface8* dstSur = NULL;
	    for (j = 0; j < 5; ++j) {
	      hr = IDirect3DCubeTexture8Impl_GetCubeMapSurface((LPDIRECT3DCUBETEXTURE8) src, j, i, &srcSur);
	      hr = IDirect3DCubeTexture8Impl_GetCubeMapSurface((LPDIRECT3DCUBETEXTURE8) dst, j, i - skipLevels, &srcSur);
1033
	      FIXME("D3DRTYPE_CUBETEXTURE does not support UpdateTexture yet\n");
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
	      IDirect3DSurface8Impl_Release(srcSur);
	      IDirect3DSurface8Impl_Release(dstSur);
	    }
	  }
	  break;
	default:
	  break;
	}
      }
      IDirect3DBaseTexture8Impl_SetDirty(pSourceTexture, FALSE);
    }
    
1046
    return D3D_OK;
1047 1048
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetFrontBuffer(LPDIRECT3DDEVICE8 iface, IDirect3DSurface8* pDestSurface) {
1049 1050
    HRESULT hr;
    D3DLOCKED_RECT lockedRect;
1051
    RECT wantedRect;
1052 1053 1054
    GLint  prev_store;
    GLenum prev_read;

1055
    ICOM_THIS(IDirect3DDevice8Impl,iface);
1056

1057
    FIXME("(%p) : see if behavior correct\n", This);
1058 1059

    if (D3DFMT_A8R8G8B8 != ((IDirect3DSurface8Impl*) pDestSurface)->myDesc.Format) {
1060
      ERR("(%p) : surface(%p) have a invalid format\n", This, pDestSurface);
1061 1062
      return D3DERR_INVALIDCALL;
    }
1063 1064 1065 1066 1067 1068 1069
    
    wantedRect.left = 0;
    wantedRect.top = 0;
    wantedRect.right = This->PresentParms.BackBufferWidth;
    wantedRect.bottom = This->PresentParms.BackBufferHeight;
    
    hr = IDirect3DSurface8Impl_LockRect(pDestSurface, &lockedRect, &wantedRect, 0);
1070
    if (FAILED(hr)) {
1071
      ERR("(%p) : cannot lock surface\n", This);
1072 1073 1074 1075 1076
      return D3DERR_INVALIDCALL;
    }

    ENTER_GL();

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    /*
    {
      IDirect3DSurface8Impl* tmp = ((IDirect3DSurface8Impl*) pDestSurface);
      FIXME("dest:%u,%u,bpp:%u\n", tmp->myDesc.Width, tmp->myDesc.Height, tmp->bytesPerPixel);
      FIXME("dest2:pitch%u\n", lockedRect.Pitch);
      FIXME("src:%u,%u\n", This->PresentParms.BackBufferWidth, This->PresentParms.BackBufferHeight);
      tmp = This->frontBuffer;
      FIXME("src2:%u,%u,bpp:%u\n", tmp->myDesc.Width, tmp->myDesc.Height, tmp->bytesPerPixel);
    }
    */

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    glFlush();
    vcheckGLcall("glFlush");
    glGetIntegerv(GL_READ_BUFFER, &prev_read);
    vcheckGLcall("glIntegerv");
    glGetIntegerv(GL_PACK_SWAP_BYTES, &prev_store);
    vcheckGLcall("glIntegerv");
 
    glReadBuffer(GL_FRONT);
    vcheckGLcall("glReadBuffer");
    glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);
    vcheckGLcall("glPixelStorei");
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    /* stupid copy */
    {
      long j;
      for (j = 0; j < This->PresentParms.BackBufferHeight; ++j) {
	/*memcpy(lockedRect.pBits + (j * lockedRect.Pitch), This->frontBuffer->allocatedMemory + (j * i), i);*/
	glReadPixels(0, This->PresentParms.BackBufferHeight - j - 1, This->PresentParms.BackBufferWidth, 1,
		     GL_BGRA, GL_UNSIGNED_BYTE, ((char*) lockedRect.pBits) + (j * lockedRect.Pitch));
	vcheckGLcall("glReadPixels");
      }
    }
1109 1110 1111 1112
    glPixelStorei(GL_PACK_SWAP_BYTES, prev_store);
    vcheckGLcall("glPixelStorei");
    glReadBuffer(prev_read);
    vcheckGLcall("glReadBuffer");
1113

1114 1115 1116 1117
    LEAVE_GL();

    hr = IDirect3DSurface8Impl_UnlockRect(pDestSurface);
    return hr;
1118
}
1119
HRESULT  WINAPI  IDirect3DDevice8Impl_SetRenderTarget(LPDIRECT3DDEVICE8 iface, IDirect3DSurface8* pRenderTarget, IDirect3DSurface8* pNewZStencil) {
1120 1121
    HRESULT hr;

1122
    ICOM_THIS(IDirect3DDevice8Impl,iface);
1123

1124
    if ((IDirect3DSurface8Impl*) pRenderTarget == This->renderTarget && (IDirect3DSurface8Impl*) pNewZStencil == This->stencilBufferTarget) {
1125 1126 1127
      TRACE("Trying to do a NOP SetRenderTarget operation\n");
      return D3D_OK;
    }
1128

1129 1130 1131
    IDirect3DDevice8Impl_CleanRender(iface);

    if ((IDirect3DSurface8Impl*) pRenderTarget == This->frontBuffer && (IDirect3DSurface8Impl*) pNewZStencil == This->depthStencilBuffer) {
Raphael Junqueira's avatar
Raphael Junqueira committed
1132 1133
      IDirect3DSurface8Impl* tmp;

1134
      TRACE("retoring SetRenderTarget defaults\n");
Raphael Junqueira's avatar
Raphael Junqueira committed
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145

      tmp = This->renderTarget;
      This->renderTarget = (IDirect3DSurface8Impl*) This->frontBuffer;
      IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) This->renderTarget);
      IDirect3DSurface8Impl_Release((LPDIRECT3DSURFACE8) tmp);
      
      tmp = This->stencilBufferTarget;
      This->stencilBufferTarget = (IDirect3DSurface8Impl*) This->depthStencilBuffer;
      if (NULL != This->stencilBufferTarget) IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) This->stencilBufferTarget);
      if (NULL != tmp) IDirect3DSurface8Impl_Release((LPDIRECT3DSURFACE8) tmp);

1146 1147 1148 1149 1150 1151 1152 1153
      return D3D_OK;
    }

    TRACE("(%p) : expect crash newRender@%p newZStencil@%p\n", This, pRenderTarget, pNewZStencil);

    hr = IDirect3DDevice8Impl_ActiveRender(iface, pRenderTarget, pNewZStencil);
    
    return hr;
1154
}
1155

1156 1157 1158
HRESULT  WINAPI  IDirect3DDevice8Impl_GetRenderTarget(LPDIRECT3DDEVICE8 iface, IDirect3DSurface8** ppRenderTarget) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

1159
    TRACE("(%p)->(%p) default(%p)\n", This, This->renderTarget, This->frontBuffer);
1160
    
1161
    *ppRenderTarget = (LPDIRECT3DSURFACE8) This->renderTarget;
1162 1163
    IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) *ppRenderTarget);
    
1164 1165
    return D3D_OK;
}
1166

1167 1168 1169
HRESULT  WINAPI  IDirect3DDevice8Impl_GetDepthStencilSurface(LPDIRECT3DDEVICE8 iface, IDirect3DSurface8** ppZStencilSurface) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

1170
    TRACE("(%p)->(%p) default(%p)\n", This, This->stencilBufferTarget, This->depthStencilBuffer);
1171 1172
    
    /* Note inc ref on returned surface */
1173
    *ppZStencilSurface = (LPDIRECT3DSURFACE8) This->stencilBufferTarget;
Raphael Junqueira's avatar
Raphael Junqueira committed
1174
    if (NULL != *ppZStencilSurface) IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) *ppZStencilSurface);
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_BeginScene(LPDIRECT3DDEVICE8 iface) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : stub\n", This);
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_EndScene(LPDIRECT3DDEVICE8 iface) {
1185 1186
    IDirect3DBaseTexture8* cont = NULL;
    HRESULT hr;
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p)\n", This);

    ENTER_GL();

    glFlush();
    checkGLcall("glFlush");

    /* Useful for debugging sometimes!
    printf("Hit Enter ...\n");
    getchar(); */

1199
    if (This->frontBuffer != This->renderTarget) {
Raphael Junqueira's avatar
Raphael Junqueira committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
      {
	GLenum prev_read;
	glGetIntegerv(GL_READ_BUFFER, &prev_read);
	vcheckGLcall("glIntegerv");
	glReadBuffer(GL_BACK);
	vcheckGLcall("glReadBuffer");
	{
	  long j;
	  long pitch = This->renderTarget->myDesc.Width * This->renderTarget->bytesPerPixel;
	  for (j = 0; j < This->renderTarget->myDesc.Height; ++j) {
	    glReadPixels(0, 
			 This->renderTarget->myDesc.Height - j - 1, 
			 This->renderTarget->myDesc.Width, 
			 1,
			 D3DFmt2GLFmt(This, This->renderTarget->myDesc.Format), 
			 D3DFmt2GLType(This, This->renderTarget->myDesc.Format), 
			 This->renderTarget->allocatedMemory + j * pitch);
	    vcheckGLcall("glReadPixels");
	  }
	}      
	glReadBuffer(prev_read);
	vcheckGLcall("glReadBuffer");
      }

1224 1225
      hr = IDirect3DSurface8_GetContainer((LPDIRECT3DSURFACE8) This->renderTarget, &IID_IDirect3DBaseTexture8, (void**) &cont);
      if (SUCCEEDED(hr) && NULL != cont) {
Raphael Junqueira's avatar
Raphael Junqueira committed
1226 1227
	/** always dirtify for now. we must find a better way to see that surface have been modified */
	IDirect3DBaseTexture8Impl_SetDirty(cont, TRUE);
1228
	IDirect3DBaseTexture8_PreLoad(cont);
1229
	IDirect3DBaseTexture8Impl_Release(cont);
1230 1231 1232 1233
	cont = NULL;
      }
    }

1234 1235 1236
    LEAVE_GL();
    return D3D_OK;
}
1237
HRESULT  WINAPI  IDirect3DDevice8Impl_Clear(LPDIRECT3DDEVICE8 iface, DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil) {
1238 1239 1240 1241 1242 1243
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    /* TODO: From MSDN This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the
      render target does not have an attached depth buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag
      when the depth-buffer format does not contain stencil buffer information, this method fails. */
    GLbitfield glMask = 0;
1244 1245 1246 1247
    GLboolean old_ztest;
    GLfloat old_z_clear_value;
    GLint   old_stencil_clear_value;
    GLfloat old_color_clear_value[4];
1248
    int i;
1249
    CONST D3DRECT* curRect;
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262

    TRACE("(%p) Count (%ld), pRects (%p), Flags (%lx), Z (%f), Stencil (%ld)\n", This,
          Count, pRects, Flags, Z, Stencil);

    ENTER_GL();
    if (Count > 0 && pRects) {
        glEnable(GL_SCISSOR_TEST);
        checkGLcall("glEnable GL_SCISSOR_TEST");
        curRect = pRects;
    } else {
        curRect = NULL;
    }

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    /* Only set the values up once, as they are not changing */
    if (Flags & D3DCLEAR_STENCIL) {	
        glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &old_stencil_clear_value);
        glClearStencil(Stencil);
        checkGLcall("glClearStencil");
        glMask = glMask | GL_STENCIL_BUFFER_BIT;
    }

    if (Flags & D3DCLEAR_ZBUFFER) {
        glGetBooleanv(GL_DEPTH_WRITEMASK, &old_ztest);
        glDepthMask(GL_TRUE); 
        glGetFloatv(GL_DEPTH_CLEAR_VALUE, &old_z_clear_value);
        glClearDepth(Z);
        checkGLcall("glClearDepth");
        glMask = glMask | GL_DEPTH_BUFFER_BIT;
    }

    if (Flags & D3DCLEAR_TARGET) {
        TRACE("Clearing screen with glClear to color %lx\n", Color);
        glGetFloatv(GL_COLOR_CLEAR_VALUE, old_color_clear_value);
1283 1284 1285 1286
        glClearColor(((Color >> 16) & 0xFF) / 255.0f, 
		     ((Color >>  8) & 0xFF) / 255.0f,
                     ((Color >>  0) & 0xFF) / 255.0f, 
		     ((Color >> 24) & 0xFF) / 255.0f);
1287 1288 1289 1290 1291
        checkGLcall("glClearColor");
        glMask = glMask | GL_COLOR_BUFFER_BIT;
    }

    /* Now process each rect in turn */
1292
    for (i = 0; i < Count || i == 0; i++) {
1293 1294 1295 1296 1297

        if (curRect) {
            /* Note gl uses lower left, width/height */
            TRACE("(%p) %p Rect=(%ld,%ld)->(%ld,%ld) glRect=(%ld,%ld), len=%ld, hei=%ld\n", This, curRect,
                  curRect->x1, curRect->y1, curRect->x2, curRect->y2,
1298 1299 1300 1301
                  curRect->x1, (This->PresentParms.BackBufferHeight - curRect->y2), 
                  curRect->x2 - curRect->x1, curRect->y2 - curRect->y1);
            glScissor(curRect->x1, (This->PresentParms.BackBufferHeight - curRect->y2), 
                      curRect->x2 - curRect->x1, curRect->y2 - curRect->y1);
1302 1303 1304
            checkGLcall("glScissor");
        }

1305
        /* Clear the selected rectangle (or full screen) */
1306 1307 1308
        glClear(glMask);
        checkGLcall("glClear");

1309
        /* Step to the next rectangle */
1310 1311 1312
        if (curRect) curRect = curRect + sizeof(D3DRECT);
    }

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    /* Restore the old values (why..?) */
    if (Flags & D3DCLEAR_STENCIL) {
        glClearStencil(old_stencil_clear_value);
    }    
    if (Flags & D3DCLEAR_ZBUFFER) {
        glDepthMask(old_ztest);
        glClearDepth(old_z_clear_value);
    }
    if (Flags & D3DCLEAR_TARGET) {
        glClearColor(old_color_clear_value[0], 
                     old_color_clear_value[1],
                     old_color_clear_value[2], 
                     old_color_clear_value[3]);
    }

1328 1329 1330 1331 1332 1333 1334 1335
    if (Count > 0 && pRects) {
        glDisable(GL_SCISSOR_TEST);
        checkGLcall("glDisable");
    }
    LEAVE_GL();

    return D3D_OK;
}
1336
HRESULT  WINAPI  IDirect3DDevice8Impl_SetTransform(LPDIRECT3DDEVICE8 iface, D3DTRANSFORMSTATETYPE d3dts, CONST D3DMATRIX* lpmatrix) {
1337
    ICOM_THIS(IDirect3DDevice8Impl,iface);
1338
    int k;
1339 1340 1341 1342 1343 1344 1345

    /* Most of this routine, comments included copied from ddraw tree initially: */
    TRACE("(%p) : State=%d\n", This, d3dts);

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
1346 1347 1348
        This->UpdateStateBlock->Changed.transform[d3dts] = TRUE;
        This->UpdateStateBlock->Set.transform[d3dts] = TRUE;
        memcpy(&This->UpdateStateBlock->transforms[d3dts], lpmatrix, sizeof(D3DMATRIX));
1349 1350 1351 1352
        return D3D_OK;
    }

    /*
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
     * if the new matrix is the same as the current one,
     * we cut off any further processing. this seems to be a reasonable
     * optimization because as was noticed, some apps (warcraft3 for example)
     * tend towards setting the same matrix repeatedly for some dumb reason.
     *
     * From here on we assume that the new matrix is different, wherever it matters
     * but note
     */
    if (!memcmp(&This->StateBlock->transforms[d3dts].u.m[0][0], lpmatrix, sizeof(D3DMATRIX))) {
        TRACE("The app is setting the same matrix over again\n");
        return D3D_OK;
1364
    } else {
1365
        conv_mat(lpmatrix, &This->StateBlock->transforms[d3dts].u.m[0][0]);
1366 1367 1368
    }

    /*
1369 1370 1371 1372 1373
       ScreenCoord = ProjectionMat * ViewMat * WorldMat * ObjectCoord
       where ViewMat = Camera space, WorldMat = world space.

       In OpenGL, camera and world space is combined into GL_MODELVIEW
       matrix.  The Projection matrix stay projection matrix. 
1374 1375
     */

1376 1377 1378 1379
    /* Capture the times we can just ignore the change */
    if (d3dts == D3DTS_WORLDMATRIX(0)) {
        This->modelview_valid = FALSE;
        return D3D_OK;
1380

1381 1382 1383
    } else if (d3dts == D3DTS_PROJECTION) {
        This->proj_valid = FALSE;
        return D3D_OK;
1384

1385 1386 1387 1388 1389 1390 1391 1392
    } else if (d3dts >= D3DTS_WORLDMATRIX(1) && d3dts <= D3DTS_WORLDMATRIX(255)) { /* Indexed Vertex Blending Matrices 256 -> 511  */
        /* Use arb_vertex_blend or NV_VERTEX_WEIGHTING? */
        FIXME("D3DTS_WORLDMATRIX(1..255) not handled\n");
        return D3D_OK;
    } 
    
    /* Chances are we really are going to have to change a matrix */
    ENTER_GL();
1393

1394 1395 1396
    if (d3dts >= D3DTS_TEXTURE0 && d3dts <= D3DTS_TEXTURE7) { /* handle texture matrices */
        if (d3dts < GL_LIMITS(textures)) {
            int tex = d3dts - D3DTS_TEXTURE0;
1397
#if defined(GL_VERSION_1_3)
1398
            glActiveTexture(GL_TEXTURE0 + tex);
1399
#else 
1400
            glActiveTextureARB(GL_TEXTURE0_ARB + tex);
1401
#endif
1402 1403
            set_texture_matrix((float *)lpmatrix, This->UpdateStateBlock->texture_state[tex][D3DTSS_TEXTURETRANSFORMFLAGS]);
        }
1404

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    } else if (d3dts == D3DTS_VIEW) { /* handle the VIEW matrice */
        float identity[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
        This->modelview_valid = FALSE;
        This->view_ident = !memcmp(lpmatrix, identity, 16*sizeof(float));
        glMatrixMode(GL_MODELVIEW);
        checkGLcall("glMatrixMode(GL_MODELVIEW)");
        glPushMatrix();
        glLoadMatrixf((float *)lpmatrix);
        checkGLcall("glLoadMatrixf(...)");

        /* If we are changing the View matrix, reset the light and clipping planes to the new view   
         * NOTE: We have to reset the positions even if the light/plane is not currently
         *       enabled, since the call to enable it will not reset the position.                 
         * NOTE2: Apparently texture transforms do NOT need reapplying
         */
1420

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        /* Reset lights */
        for (k = 0; k < GL_LIMITS(lights); k++) {
            glLightfv(GL_LIGHT0 + k, GL_POSITION, This->lightPosn[k]);
            checkGLcall("glLightfv posn");
            glLightfv(GL_LIGHT0 + k, GL_SPOT_DIRECTION, This->lightDirn[k]);
            checkGLcall("glLightfv dirn");
        }
        /* Reset Clipping Planes if clipping is enabled */
        for (k = 0; k < GL_LIMITS(clipplanes); k++) {
            glClipPlane(GL_CLIP_PLANE0 + k, This->StateBlock->clipplane[k]);
            checkGLcall("glClipPlane");
1432
        }
1433
        glPopMatrix();
1434

1435 1436
    } else { /* What was requested!?? */
        WARN("invalid matrix specified: %i\n", d3dts);
1437

1438
    }
1439

1440
    /* Release lock, all done */
1441 1442 1443 1444 1445 1446 1447
    LEAVE_GL();
    return D3D_OK;

}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetTransform(LPDIRECT3DDEVICE8 iface, D3DTRANSFORMSTATETYPE State,D3DMATRIX* pMatrix) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : for State %d\n", This, State);
1448
    memcpy(pMatrix, &This->StateBlock->transforms[State], sizeof(D3DMATRIX));
1449 1450 1451 1452
    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_MultiplyTransform(LPDIRECT3DDEVICE8 iface, D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix) {
1453 1454 1455 1456 1457 1458
    D3DMATRIX *mat = NULL;
    D3DMATRIX temp;

    /* Note: Using UpdateStateBlock means it would be recorded in a state block change,
        but works regardless of recording being on. 
        If this is found to be wrong, change to StateBlock.                             */
1459
    ICOM_THIS(IDirect3DDevice8Impl,iface);
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    TRACE("(%p) : For state %u\n", This, State);

    if (State < HIGHEST_TRANSFORMSTATE)
    {
        mat = &This->UpdateStateBlock->transforms[State];
    } else {
        FIXME("Unhandled transform state!!\n");
    }

    /* Copied from ddraw code:  */
    temp.u.s._11 = (mat->u.s._11 * pMatrix->u.s._11) + (mat->u.s._21 * pMatrix->u.s._12) + (mat->u.s._31 * pMatrix->u.s._13) + (mat->u.s._41 * pMatrix->u.s._14);
    temp.u.s._21 = (mat->u.s._11 * pMatrix->u.s._21) + (mat->u.s._21 * pMatrix->u.s._22) + (mat->u.s._31 * pMatrix->u.s._23) + (mat->u.s._41 * pMatrix->u.s._24);
    temp.u.s._31 = (mat->u.s._11 * pMatrix->u.s._31) + (mat->u.s._21 * pMatrix->u.s._32) + (mat->u.s._31 * pMatrix->u.s._33) + (mat->u.s._41 * pMatrix->u.s._34);
    temp.u.s._41 = (mat->u.s._11 * pMatrix->u.s._41) + (mat->u.s._21 * pMatrix->u.s._42) + (mat->u.s._31 * pMatrix->u.s._43) + (mat->u.s._41 * pMatrix->u.s._44);

    temp.u.s._12 = (mat->u.s._12 * pMatrix->u.s._11) + (mat->u.s._22 * pMatrix->u.s._12) + (mat->u.s._32 * pMatrix->u.s._13) + (mat->u.s._42 * pMatrix->u.s._14);
    temp.u.s._22 = (mat->u.s._12 * pMatrix->u.s._21) + (mat->u.s._22 * pMatrix->u.s._22) + (mat->u.s._32 * pMatrix->u.s._23) + (mat->u.s._42 * pMatrix->u.s._24);
    temp.u.s._32 = (mat->u.s._12 * pMatrix->u.s._31) + (mat->u.s._22 * pMatrix->u.s._32) + (mat->u.s._32 * pMatrix->u.s._33) + (mat->u.s._42 * pMatrix->u.s._34);
    temp.u.s._42 = (mat->u.s._12 * pMatrix->u.s._41) + (mat->u.s._22 * pMatrix->u.s._42) + (mat->u.s._32 * pMatrix->u.s._43) + (mat->u.s._42 * pMatrix->u.s._44);

    temp.u.s._13 = (mat->u.s._13 * pMatrix->u.s._11) + (mat->u.s._23 * pMatrix->u.s._12) + (mat->u.s._33 * pMatrix->u.s._13) + (mat->u.s._43 * pMatrix->u.s._14);
    temp.u.s._23 = (mat->u.s._13 * pMatrix->u.s._21) + (mat->u.s._23 * pMatrix->u.s._22) + (mat->u.s._33 * pMatrix->u.s._23) + (mat->u.s._43 * pMatrix->u.s._24);
    temp.u.s._33 = (mat->u.s._13 * pMatrix->u.s._31) + (mat->u.s._23 * pMatrix->u.s._32) + (mat->u.s._33 * pMatrix->u.s._33) + (mat->u.s._43 * pMatrix->u.s._34);
    temp.u.s._43 = (mat->u.s._13 * pMatrix->u.s._41) + (mat->u.s._23 * pMatrix->u.s._42) + (mat->u.s._33 * pMatrix->u.s._43) + (mat->u.s._43 * pMatrix->u.s._44);

    temp.u.s._14 = (mat->u.s._14 * pMatrix->u.s._11) + (mat->u.s._24 * pMatrix->u.s._12) + (mat->u.s._34 * pMatrix->u.s._13) + (mat->u.s._44 * pMatrix->u.s._14);
    temp.u.s._24 = (mat->u.s._14 * pMatrix->u.s._21) + (mat->u.s._24 * pMatrix->u.s._22) + (mat->u.s._34 * pMatrix->u.s._23) + (mat->u.s._44 * pMatrix->u.s._24);
    temp.u.s._34 = (mat->u.s._14 * pMatrix->u.s._31) + (mat->u.s._24 * pMatrix->u.s._32) + (mat->u.s._34 * pMatrix->u.s._33) + (mat->u.s._44 * pMatrix->u.s._34);
    temp.u.s._44 = (mat->u.s._14 * pMatrix->u.s._41) + (mat->u.s._24 * pMatrix->u.s._42) + (mat->u.s._34 * pMatrix->u.s._43) + (mat->u.s._44 * pMatrix->u.s._44);

    /* Apply change via set transform - will reapply to eg. lights this way */
    IDirect3DDevice8Impl_SetTransform(iface, State, &temp);
    return D3D_OK;
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetViewport(LPDIRECT3DDEVICE8 iface, CONST D3DVIEWPORT8* pViewport) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    TRACE("(%p)\n", This);
    This->UpdateStateBlock->Changed.viewport = TRUE;
    This->UpdateStateBlock->Set.viewport = TRUE;
    memcpy(&This->UpdateStateBlock->viewport, pViewport, sizeof(D3DVIEWPORT8));

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

1508 1509
    ENTER_GL();

1510 1511 1512 1513 1514
    TRACE("(%p) : x=%ld, y=%ld, wid=%ld, hei=%ld, minz=%f, maxz=%f\n", This,
          pViewport->X, pViewport->Y, pViewport->Width, pViewport->Height, pViewport->MinZ, pViewport->MaxZ);

    glDepthRange(pViewport->MinZ, pViewport->MaxZ);
    checkGLcall("glDepthRange");
1515 1516 1517
    /* Note: GL requires lower left, DirectX supplies upper left */
    glViewport(pViewport->X, (This->PresentParms.BackBufferHeight - (pViewport->Y + pViewport->Height)), 
               pViewport->Width, pViewport->Height);
1518 1519
    checkGLcall("glViewport");

1520
    LEAVE_GL();
1521 1522 1523 1524 1525 1526 1527

    return D3D_OK;

}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetViewport(LPDIRECT3DDEVICE8 iface, D3DVIEWPORT8* pViewport) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p)\n", This);
1528
    memcpy(pViewport, &This->StateBlock->viewport, sizeof(D3DVIEWPORT8));
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_SetMaterial(LPDIRECT3DDEVICE8 iface, CONST D3DMATERIAL8* pMaterial) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    This->UpdateStateBlock->Changed.material = TRUE;
    This->UpdateStateBlock->Set.material = TRUE;
    memcpy(&This->UpdateStateBlock->material, pMaterial, sizeof(D3DMATERIAL8));

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

    ENTER_GL();
    TRACE("(%p) : Diffuse (%f,%f,%f,%f)\n", This, pMaterial->Diffuse.r, pMaterial->Diffuse.g, pMaterial->Diffuse.b, pMaterial->Diffuse.a);
    TRACE("(%p) : Ambient (%f,%f,%f,%f)\n", This, pMaterial->Ambient.r, pMaterial->Ambient.g, pMaterial->Ambient.b, pMaterial->Ambient.a);
    TRACE("(%p) : Specular (%f,%f,%f,%f)\n", This, pMaterial->Specular.r, pMaterial->Specular.g, pMaterial->Specular.b, pMaterial->Specular.a);
    TRACE("(%p) : Emissive (%f,%f,%f,%f)\n", This, pMaterial->Emissive.r, pMaterial->Emissive.g, pMaterial->Emissive.b, pMaterial->Emissive.a);
    TRACE("(%p) : Power (%f)\n", This, pMaterial->Power);

1552
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (float*) &This->UpdateStateBlock->material.Ambient);
1553
    checkGLcall("glMaterialfv");
1554
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, (float*) &This->UpdateStateBlock->material.Diffuse);
1555 1556
    checkGLcall("glMaterialfv");

1557 1558 1559 1560 1561
    /* Only change material color if specular is enabled, otherwise it is set to black */
    if (This->StateBlock->renderstate[D3DRS_SPECULARENABLE]) {
       glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (float*) &This->UpdateStateBlock->material.Specular);
       checkGLcall("glMaterialfv");
    }
1562
    glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, (float*) &This->UpdateStateBlock->material.Emissive);
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
    checkGLcall("glMaterialfv");
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, This->UpdateStateBlock->material.Power);
    checkGLcall("glMaterialf");

    LEAVE_GL();
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetMaterial(LPDIRECT3DDEVICE8 iface, D3DMATERIAL8* pMaterial) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    memcpy(pMaterial, &This->UpdateStateBlock->material, sizeof (D3DMATERIAL8));
    TRACE("(%p) : Diffuse (%f,%f,%f,%f)\n", This, pMaterial->Diffuse.r, pMaterial->Diffuse.g, pMaterial->Diffuse.b, pMaterial->Diffuse.a);
    TRACE("(%p) : Ambient (%f,%f,%f,%f)\n", This, pMaterial->Ambient.r, pMaterial->Ambient.g, pMaterial->Ambient.b, pMaterial->Ambient.a);
    TRACE("(%p) : Specular (%f,%f,%f,%f)\n", This, pMaterial->Specular.r, pMaterial->Specular.g, pMaterial->Specular.b, pMaterial->Specular.a);
    TRACE("(%p) : Emissive (%f,%f,%f,%f)\n", This, pMaterial->Emissive.r, pMaterial->Emissive.g, pMaterial->Emissive.b, pMaterial->Emissive.a);
    TRACE("(%p) : Power (%f)\n", This, pMaterial->Power);
    return D3D_OK;
}

1581
HRESULT  WINAPI  IDirect3DDevice8Impl_SetLight(LPDIRECT3DDEVICE8 iface, DWORD Index, CONST D3DLIGHT8* pLight) {
1582
    float colRGBA[] = {0.0, 0.0, 0.0, 0.0};
1583 1584
    float rho;
    float quad_att;
1585 1586 1587 1588

    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : Idx(%ld), pLight(%p)\n", This, Index, pLight);

1589
    if (Index >= GL_LIMITS(lights)) {
1590
        TRACE("Cannot handle more lights than device supports\n");
1591 1592 1593
        return D3DERR_INVALIDCALL;
    }

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    TRACE("Light %ld setting to type %d, Diffuse(%f,%f,%f,%f), Specular(%f,%f,%f,%f), Ambient(%f,%f,%f,%f)\n", Index, pLight->Type,
          pLight->Diffuse.r, pLight->Diffuse.g, pLight->Diffuse.b, pLight->Diffuse.a,
          pLight->Specular.r, pLight->Specular.g, pLight->Specular.b, pLight->Specular.a,
          pLight->Ambient.r, pLight->Ambient.g, pLight->Ambient.b, pLight->Ambient.a);
    TRACE("... Pos(%f,%f,%f), Dirn(%f,%f,%f)\n", pLight->Position.x, pLight->Position.y, pLight->Position.z,
          pLight->Direction.x, pLight->Direction.y, pLight->Direction.z);
    TRACE("... Range(%f), Falloff(%f), Theta(%f), Phi(%f)\n", pLight->Range, pLight->Falloff, pLight->Theta, pLight->Phi);

    This->UpdateStateBlock->Changed.lights[Index] = TRUE;
    This->UpdateStateBlock->Set.lights[Index] = TRUE;
    memcpy(&This->UpdateStateBlock->lights[Index], pLight, sizeof(D3DLIGHT8));

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

1612 1613
    ENTER_GL();

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    /* Diffuse: */
    colRGBA[0] = pLight->Diffuse.r;
    colRGBA[1] = pLight->Diffuse.g;
    colRGBA[2] = pLight->Diffuse.b;
    colRGBA[3] = pLight->Diffuse.a;
    glLightfv(GL_LIGHT0+Index, GL_DIFFUSE, colRGBA);
    checkGLcall("glLightfv");

    /* Specular */
    colRGBA[0] = pLight->Specular.r;
    colRGBA[1] = pLight->Specular.g;
    colRGBA[2] = pLight->Specular.b;
    colRGBA[3] = pLight->Specular.a;
    glLightfv(GL_LIGHT0+Index, GL_SPECULAR, colRGBA);
    checkGLcall("glLightfv");

    /* Ambient */
    colRGBA[0] = pLight->Ambient.r;
    colRGBA[1] = pLight->Ambient.g;
    colRGBA[2] = pLight->Ambient.b;
    colRGBA[3] = pLight->Ambient.a;
    glLightfv(GL_LIGHT0+Index, GL_AMBIENT, colRGBA);
    checkGLcall("glLightfv");

1638
    /* Light settings are affected by the model view in OpenGL, the View transform in direct3d*/
1639 1640
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
1641
    glLoadMatrixf((float *) &This->StateBlock->transforms[D3DTS_VIEW].u.m[0][0]);
1642

1643 1644 1645 1646 1647
    /* Attenuation - Are these right? guessing... */
    glLightf(GL_LIGHT0+Index, GL_CONSTANT_ATTENUATION,  pLight->Attenuation0);
    checkGLcall("glLightf");
    glLightf(GL_LIGHT0+Index, GL_LINEAR_ATTENUATION,    pLight->Attenuation1);
    checkGLcall("glLightf");
1648 1649 1650 1651

    quad_att = 1.4/(pLight->Range*pLight->Range);
    if (quad_att < pLight->Attenuation2) quad_att = pLight->Attenuation2;
    glLightf(GL_LIGHT0+Index, GL_QUADRATIC_ATTENUATION, quad_att);
1652 1653 1654 1655 1656
    checkGLcall("glLightf");

    switch (pLight->Type) {
    case D3DLIGHT_POINT:
        /* Position */
1657 1658 1659 1660 1661
        This->lightPosn[Index][0] = pLight->Position.x;
        This->lightPosn[Index][1] = pLight->Position.y;
        This->lightPosn[Index][2] = pLight->Position.z;
        This->lightPosn[Index][3] = 1.0;
        glLightfv(GL_LIGHT0+Index, GL_POSITION, &This->lightPosn[Index][0]);
1662 1663
        checkGLcall("glLightfv");

1664 1665 1666
        glLightf(GL_LIGHT0 + Index, GL_SPOT_CUTOFF, 180);
        checkGLcall("glLightf");

1667 1668
        /* FIXME: Range */
        break;
1669

1670 1671
    case D3DLIGHT_SPOT:
        /* Position */
1672 1673 1674 1675 1676
        This->lightPosn[Index][0] = pLight->Position.x;
        This->lightPosn[Index][1] = pLight->Position.y;
        This->lightPosn[Index][2] = pLight->Position.z;
        This->lightPosn[Index][3] = 1.0;
        glLightfv(GL_LIGHT0+Index, GL_POSITION, &This->lightPosn[Index][0]);
1677 1678 1679
        checkGLcall("glLightfv");

        /* Direction */
1680 1681 1682 1683 1684
        This->lightDirn[Index][0] = pLight->Direction.x;
        This->lightDirn[Index][1] = pLight->Direction.y;
        This->lightDirn[Index][2] = pLight->Direction.z;
        This->lightDirn[Index][3] = 1.0;
        glLightfv(GL_LIGHT0+Index, GL_SPOT_DIRECTION, &This->lightDirn[Index][0]);
1685 1686
        checkGLcall("glLightfv");

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
        /*
         * opengl-ish and d3d-ish spot lights use too different models for the
         * light "intensity" as a function of the angle towards the main light direction,
         * so we only can approximate very roughly.
         * however spot lights are rather rarely used in games (if ever used at all).
         * furthermore if still used, probably nobody pays attention to such details.
         */
        if (pLight->Falloff == 0) {
            rho = 6.28f;
        } else {
            rho = pLight->Theta + (pLight->Phi - pLight->Theta)/(2*pLight->Falloff);
        }
        if (rho < 0.0001) rho = 0.0001f;
        glLightf(GL_LIGHT0 + Index, GL_SPOT_EXPONENT, -0.3/log(cos(rho/2)));
        glLightf(GL_LIGHT0 + Index, GL_SPOT_CUTOFF, pLight->Phi*90/M_PI);

1703 1704 1705 1706
        /* FIXME: Range */
        break;
    case D3DLIGHT_DIRECTIONAL:
        /* Direction */
1707 1708 1709 1710 1711
        This->lightPosn[Index][0] = -pLight->Direction.x;
        This->lightPosn[Index][1] = -pLight->Direction.y;
        This->lightPosn[Index][2] = -pLight->Direction.z;
        This->lightPosn[Index][3] = 0.0;
        glLightfv(GL_LIGHT0+Index, GL_POSITION, &This->lightPosn[Index][0]); /* Note gl uses w position of 0 for direction! */
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
        checkGLcall("glLightfv");

        glLightf(GL_LIGHT0+Index, GL_SPOT_CUTOFF, 180.0f);
        glLightf(GL_LIGHT0+Index, GL_SPOT_EXPONENT, 0.0f);


        break;
    default:
        FIXME("Unrecognized light type %d\n", pLight->Type);
    }

1723 1724 1725
    /* Restore the modelview matrix */
    glPopMatrix();

1726 1727
    LEAVE_GL();

1728 1729 1730 1731 1732
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetLight(LPDIRECT3DDEVICE8 iface, DWORD Index,D3DLIGHT8* pLight) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : Idx(%ld), pLight(%p)\n", This, Index, pLight);
1733
    
1734
    if (Index >= GL_LIMITS(lights)) {
1735
        TRACE("Cannot handle more lights than device supports\n");
1736 1737 1738
        return D3DERR_INVALIDCALL;
    }

1739
    memcpy(pLight, &This->StateBlock->lights[Index], sizeof(D3DLIGHT8));
1740 1741 1742 1743 1744 1745
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_LightEnable(LPDIRECT3DDEVICE8 iface, DWORD Index,BOOL Enable) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : Idx(%ld), enable? %d\n", This, Index, Enable);

1746
    if (Index >= GL_LIMITS(lights)) {
1747
        TRACE("Cannot handle more lights than device supports\n");
1748 1749 1750
        return D3DERR_INVALIDCALL;
    }

1751 1752 1753 1754 1755 1756 1757 1758 1759
    This->UpdateStateBlock->Changed.lightEnable[Index] = TRUE;
    This->UpdateStateBlock->Set.lightEnable[Index] = TRUE;
    This->UpdateStateBlock->lightEnable[Index] = Enable;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }
1760 1761
    
    ENTER_GL();
1762
    if (Enable) {
1763
        glEnable(GL_LIGHT0 + Index);
1764 1765
        checkGLcall("glEnable GL_LIGHT0+Index");
    } else {
1766
        glDisable(GL_LIGHT0 + Index);
1767 1768
        checkGLcall("glDisable GL_LIGHT0+Index");
    }
1769 1770
    LEAVE_GL();

1771 1772 1773 1774 1775
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetLightEnable(LPDIRECT3DDEVICE8 iface, DWORD Index,BOOL* pEnable) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : for idx(%ld)\n", This, Index);
1776

1777
    if (Index >= GL_LIMITS(lights)) {
1778
        TRACE("Cannot handle more lights than device supports\n");
1779 1780 1781
        return D3DERR_INVALIDCALL;
    }

1782
    *pEnable = This->StateBlock->lightEnable[Index];
1783 1784 1785 1786 1787 1788
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetClipPlane(LPDIRECT3DDEVICE8 iface, DWORD Index,CONST float* pPlane) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : for idx %ld, %p\n", This, Index, pPlane);

1789
    /* Validate Index */
1790
    if (Index >= GL_LIMITS(clipplanes)) {
1791 1792 1793 1794
        TRACE("Application has requested clipplane this device doesnt support\n");
        return D3DERR_INVALIDCALL;
    }

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
    This->UpdateStateBlock->Changed.clipplane[Index] = TRUE;
    This->UpdateStateBlock->Set.clipplane[Index] = TRUE;
    This->UpdateStateBlock->clipplane[Index][0] = pPlane[0];
    This->UpdateStateBlock->clipplane[Index][1] = pPlane[1];
    This->UpdateStateBlock->clipplane[Index][2] = pPlane[2];
    This->UpdateStateBlock->clipplane[Index][3] = pPlane[3];

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

    /* Apply it */
1809

1810 1811
    ENTER_GL();

1812
    /* Clip Plane settings are affected by the model view in OpenGL, the View transform in direct3d */
1813 1814
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
1815
    glLoadMatrixf((float *) &This->StateBlock->transforms[D3DTS_VIEW].u.m[0][0]);
1816

Raphael Junqueira's avatar
Raphael Junqueira committed
1817 1818 1819 1820 1821
    TRACE("Clipplane [%f,%f,%f,%f]\n", 
	  This->UpdateStateBlock->clipplane[Index][0], 
	  This->UpdateStateBlock->clipplane[Index][1],
          This->UpdateStateBlock->clipplane[Index][2], 
	  This->UpdateStateBlock->clipplane[Index][3]);
1822
    glClipPlane(GL_CLIP_PLANE0 + Index, This->UpdateStateBlock->clipplane[Index]);
1823
    checkGLcall("glClipPlane");
1824 1825

    glPopMatrix();
1826

1827 1828
    LEAVE_GL();

1829 1830 1831 1832 1833
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetClipPlane(LPDIRECT3DDEVICE8 iface, DWORD Index,float* pPlane) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) : for idx %ld\n", This, Index);
1834 1835

    /* Validate Index */
1836
    if (Index >= GL_LIMITS(clipplanes)) {
1837 1838 1839 1840
        TRACE("Application has requested clipplane this device doesnt support\n");
        return D3DERR_INVALIDCALL;
    }

1841
    pPlane[0] = This->StateBlock->clipplane[Index][0];
Raphael Junqueira's avatar
Raphael Junqueira committed
1842 1843 1844
    pPlane[1] = This->StateBlock->clipplane[Index][1];
    pPlane[2] = This->StateBlock->clipplane[Index][2];
    pPlane[3] = This->StateBlock->clipplane[Index][3];
1845 1846 1847 1848
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetRenderState(LPDIRECT3DDEVICE8 iface, D3DRENDERSTATETYPE State,DWORD Value) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
1849
    DWORD OldValue = This->StateBlock->renderstate[State];
1850
        
1851
    TRACE("(%p)->state = %s(%d), value = %ld\n", This, debug_d3drenderstate(State), State, Value);
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
    This->UpdateStateBlock->Changed.renderstate[State] = TRUE;
    This->UpdateStateBlock->Set.renderstate[State] = TRUE;
    This->UpdateStateBlock->renderstate[State] = Value;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

1862 1863
    ENTER_GL();

1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
    switch (State) {
    case D3DRS_FILLMODE                  :
        switch ((D3DFILLMODE) Value) {
        case D3DFILL_POINT               : glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); break;
        case D3DFILL_WIREFRAME           : glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); break;
        case D3DFILL_SOLID               : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); break;
        default:
            FIXME("Unrecognized D3DRS_FILLMODE value %ld\n", Value);
        }
        checkGLcall("glPolygonMode (fillmode)");
        break;

    case D3DRS_LIGHTING                  :
        if (Value) {
            glEnable(GL_LIGHTING);
            checkGLcall("glEnable GL_LIGHTING");
        } else {
            glDisable(GL_LIGHTING);
            checkGLcall("glDisable GL_LIGHTING");
        }
        break;

    case D3DRS_ZENABLE                   :
        switch ((D3DZBUFFERTYPE) Value) {
        case D3DZB_FALSE:
            glDisable(GL_DEPTH_TEST);
            checkGLcall("glDisable GL_DEPTH_TEST");
            break;
        case D3DZB_TRUE:
            glEnable(GL_DEPTH_TEST);
            checkGLcall("glEnable GL_DEPTH_TEST");
            break;

        case D3DZB_USEW:
        default:
            FIXME("Unrecognized/Unhandled D3DZBUFFERTYPE value %ld\n", Value);
        }
        break;

    case D3DRS_CULLMODE                  :
1904 1905 1906 1907

        /* If we are culling "back faces with clockwise vertices" then
           set front faces to be counter clockwise and enable culling  
           of back faces                                               */
1908 1909 1910 1911 1912 1913 1914 1915
        switch ((D3DCULL) Value) {
        case D3DCULL_NONE:
            glDisable(GL_CULL_FACE);
            checkGLcall("glDisable GL_CULL_FACE");
            break;
        case D3DCULL_CW:
            glEnable(GL_CULL_FACE);
            checkGLcall("glEnable GL_CULL_FACE");
1916 1917 1918
            glFrontFace(GL_CCW);
            checkGLcall("glFrontFace GL_CCW");
            glCullFace(GL_BACK);
1919 1920 1921 1922
            break;
        case D3DCULL_CCW:
            glEnable(GL_CULL_FACE);
            checkGLcall("glEnable GL_CULL_FACE");
1923 1924 1925
            glFrontFace(GL_CW); 
            checkGLcall("glFrontFace GL_CW");
            glCullFace(GL_BACK);
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
            break;
        default:
            FIXME("Unrecognized/Unhandled D3DCULL value %ld\n", Value);
        }
        break;

    case D3DRS_SHADEMODE                 :
        switch ((D3DSHADEMODE) Value) {
        case D3DSHADE_FLAT:
            glShadeModel(GL_FLAT);
            checkGLcall("glShadeModel");
            break;
        case D3DSHADE_GOURAUD:
            glShadeModel(GL_SMOOTH);
            checkGLcall("glShadeModel");
            break;
        case D3DSHADE_PHONG:
            FIXME("D3DSHADE_PHONG isnt supported?\n");
1944 1945

	    LEAVE_GL();
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
            return D3DERR_INVALIDCALL;
        default:
            FIXME("Unrecognized/Unhandled D3DSHADEMODE value %ld\n", Value);
        }
        break;

    case D3DRS_DITHERENABLE              :
        if (Value) {
            glEnable(GL_DITHER);
            checkGLcall("glEnable GL_DITHER");
        } else {
            glDisable(GL_DITHER);
            checkGLcall("glDisable GL_DITHER");
        }
        break;

    case D3DRS_ZWRITEENABLE              :
        if (Value) {
            glDepthMask(1);
            checkGLcall("glDepthMask");
        } else {
            glDepthMask(0);
            checkGLcall("glDepthMask");
        }
        break;

    case D3DRS_ZFUNC                     :
        {
            int glParm = GL_LESS;

            switch ((D3DCMPFUNC) Value) {
            case D3DCMP_NEVER:         glParm=GL_NEVER; break;
            case D3DCMP_LESS:          glParm=GL_LESS; break;
            case D3DCMP_EQUAL:         glParm=GL_EQUAL; break;
            case D3DCMP_LESSEQUAL:     glParm=GL_LEQUAL; break;
            case D3DCMP_GREATER:       glParm=GL_GREATER; break;
            case D3DCMP_NOTEQUAL:      glParm=GL_NOTEQUAL; break;
            case D3DCMP_GREATEREQUAL:  glParm=GL_GEQUAL; break;
            case D3DCMP_ALWAYS:        glParm=GL_ALWAYS; break;
            default:
                FIXME("Unrecognized/Unhandled D3DCMPFUNC value %ld\n", Value);
            }
            glDepthFunc(glParm);
            checkGLcall("glDepthFunc");
        }
        break;

    case D3DRS_AMBIENT                   :
        {
            float col[4];
1996 1997
	    D3DCOLORTOGLFLOAT4(Value, col);
            TRACE("Setting ambient to (%f,%f,%f,%f)\n", col[0], col[1], col[2], col[3]);
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
            glLightModelfv(GL_LIGHT_MODEL_AMBIENT, col);
            checkGLcall("glLightModel for MODEL_AMBIENT");

        }
        break;

    case D3DRS_ALPHABLENDENABLE          :
        if (Value) {
            glEnable(GL_BLEND);
            checkGLcall("glEnable GL_BLEND");
        } else {
            glDisable(GL_BLEND);
            checkGLcall("glDisable GL_BLEND");
        };
        break;

    case D3DRS_SRCBLEND                  :
    case D3DRS_DESTBLEND                 :
        {
            int newVal = GL_ZERO;
            switch (Value) {
            case D3DBLEND_ZERO               : newVal = GL_ZERO;  break;
            case D3DBLEND_ONE                : newVal = GL_ONE;  break;
            case D3DBLEND_SRCCOLOR           : newVal = GL_SRC_COLOR;  break;
            case D3DBLEND_INVSRCCOLOR        : newVal = GL_ONE_MINUS_SRC_COLOR;  break;
            case D3DBLEND_SRCALPHA           : newVal = GL_SRC_ALPHA;  break;
            case D3DBLEND_INVSRCALPHA        : newVal = GL_ONE_MINUS_SRC_ALPHA;  break;
            case D3DBLEND_DESTALPHA          : newVal = GL_DST_ALPHA;  break;
            case D3DBLEND_INVDESTALPHA       : newVal = GL_ONE_MINUS_DST_ALPHA;  break;
            case D3DBLEND_DESTCOLOR          : newVal = GL_DST_COLOR;  break;
            case D3DBLEND_INVDESTCOLOR       : newVal = GL_ONE_MINUS_DST_COLOR;  break;
            case D3DBLEND_SRCALPHASAT        : newVal = GL_SRC_ALPHA_SATURATE;  break;

            case D3DBLEND_BOTHSRCALPHA       : newVal = GL_SRC_ALPHA;
                This->srcBlend = newVal;
                This->dstBlend = newVal;
                break;

            case D3DBLEND_BOTHINVSRCALPHA    : newVal = GL_ONE_MINUS_SRC_ALPHA;
                This->srcBlend = newVal;
                This->dstBlend = newVal;
                break;
            default:
                FIXME("Unrecognized src/dest blend value %ld (%d)\n", Value, State);
            }

            if (State == D3DRS_SRCBLEND) This->srcBlend = newVal;
            if (State == D3DRS_DESTBLEND) This->dstBlend = newVal;
            TRACE("glBlendFunc src=%x, dst=%x\n", This->srcBlend, This->dstBlend);
            glBlendFunc(This->srcBlend, This->dstBlend);

            checkGLcall("glBlendFunc");
        }
        break;

    case D3DRS_ALPHATESTENABLE           :
        if (Value) {
            glEnable(GL_ALPHA_TEST);
            checkGLcall("glEnable GL_ALPHA_TEST");
        } else {
            glDisable(GL_ALPHA_TEST);
            checkGLcall("glDisable GL_ALPHA_TEST");
        }
        break;

2063
    case D3DRS_ALPHAFUNC                 :
2064 2065
        {
            int glParm = GL_LESS;
2066
            float ref = ((float) This->StateBlock->renderstate[D3DRS_ALPHAREF]) / 255.0f;
2067 2068

            switch ((D3DCMPFUNC) Value) {
Raphael Junqueira's avatar
Raphael Junqueira committed
2069 2070 2071 2072 2073 2074 2075 2076
            case D3DCMP_NEVER:         glParm = GL_NEVER; break;
            case D3DCMP_LESS:          glParm = GL_LESS; break;
            case D3DCMP_EQUAL:         glParm = GL_EQUAL; break;
            case D3DCMP_LESSEQUAL:     glParm = GL_LEQUAL; break;
            case D3DCMP_GREATER:       glParm = GL_GREATER; break;
            case D3DCMP_NOTEQUAL:      glParm = GL_NOTEQUAL; break;
            case D3DCMP_GREATEREQUAL:  glParm = GL_GEQUAL; break;
            case D3DCMP_ALWAYS:        glParm = GL_ALWAYS; break;
2077 2078 2079
            default:
                FIXME("Unrecognized/Unhandled D3DCMPFUNC value %ld\n", Value);
            }
2080
            TRACE("glAlphaFunc with Parm=%x, ref=%f\n", glParm, ref);
2081
            glAlphaFunc(glParm, ref);
2082
            This->alphafunc = glParm;
2083 2084 2085 2086
            checkGLcall("glAlphaFunc");
        }
        break;

2087
    case D3DRS_ALPHAREF                  :
2088
        {
2089
            int glParm = This->alphafunc;
2090
            float ref = 1.0f;
2091

2092
            ref = ((float) Value) / 255.0f;
2093
            TRACE("glAlphaFunc with Parm=%x, ref=%f\n", glParm, ref);
2094 2095 2096 2097 2098 2099
            glAlphaFunc(glParm, ref);
            checkGLcall("glAlphaFunc");
        }
        break;

    case D3DRS_CLIPPLANEENABLE           :
2100
    case D3DRS_CLIPPING                  :
2101
        {
2102
            /* Ensure we only do the changed clip planes */
2103 2104 2105 2106 2107 2108
            DWORD enable  = 0xFFFFFFFF;
            DWORD disable = 0x00000000;
            
            /* If enabling / disabling all */
            if (State == D3DRS_CLIPPING) {
                if (Value) {
2109
                    enable  = This->StateBlock->renderstate[D3DRS_CLIPPLANEENABLE];
2110 2111
                    disable = 0x00;
                } else {
2112
                    disable = This->StateBlock->renderstate[D3DRS_CLIPPLANEENABLE];
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
                    enable  = 0x00;
                }
            } else {
                enable =   Value & ~OldValue;
                disable = ~Value &  OldValue;
            }
            
            if (enable & D3DCLIPPLANE0)  { glEnable(GL_CLIP_PLANE0);  checkGLcall("glEnable(clip plane 0)"); }
            if (enable & D3DCLIPPLANE1)  { glEnable(GL_CLIP_PLANE1);  checkGLcall("glEnable(clip plane 1)"); }
            if (enable & D3DCLIPPLANE2)  { glEnable(GL_CLIP_PLANE2);  checkGLcall("glEnable(clip plane 2)"); }
            if (enable & D3DCLIPPLANE3)  { glEnable(GL_CLIP_PLANE3);  checkGLcall("glEnable(clip plane 3)"); }
            if (enable & D3DCLIPPLANE4)  { glEnable(GL_CLIP_PLANE4);  checkGLcall("glEnable(clip plane 4)"); }
            if (enable & D3DCLIPPLANE5)  { glEnable(GL_CLIP_PLANE5);  checkGLcall("glEnable(clip plane 5)"); }
            
            if (disable & D3DCLIPPLANE0) { glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)"); }
            if (disable & D3DCLIPPLANE1) { glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)"); }
            if (disable & D3DCLIPPLANE2) { glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)"); }
            if (disable & D3DCLIPPLANE3) { glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)"); }
            if (disable & D3DCLIPPLANE4) { glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)"); }
            if (disable & D3DCLIPPLANE5) { glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)"); }
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
        }
        break;

    case D3DRS_BLENDOP                   :
        {
            int glParm = GL_FUNC_ADD;

            switch ((D3DBLENDOP) Value) {
            case D3DBLENDOP_ADD              : glParm = GL_FUNC_ADD;              break;
            case D3DBLENDOP_SUBTRACT         : glParm = GL_FUNC_SUBTRACT;         break;
            case D3DBLENDOP_REVSUBTRACT      : glParm = GL_FUNC_REVERSE_SUBTRACT; break;
            case D3DBLENDOP_MIN              : glParm = GL_MIN;                   break;
            case D3DBLENDOP_MAX              : glParm = GL_MAX;                   break;
            default:
                FIXME("Unrecognized/Unhandled D3DBLENDOP value %ld\n", Value);
            }
2149
            TRACE("glBlendEquation(%x)\n", glParm);
2150 2151 2152 2153 2154 2155 2156
            glBlendEquation(glParm);
            checkGLcall("glBlendEquation");
        }
        break;

    case D3DRS_TEXTUREFACTOR             :
        {
2157 2158 2159 2160
            int i;

            /* Note the texture color applies to all textures whereas 
               GL_TEXTURE_ENV_COLOR applies to active only */
2161
            float col[4];
2162
	    D3DCOLORTOGLFLOAT4(Value, col);
2163 2164 2165 2166 2167
            /* Set the default alpha blend color */
            glBlendColor(col[0], col[1], col[2], col[3]);
            checkGLcall("glBlendColor");

            /* And now the default texture color as well */
2168
            for (i = 0; i < GL_LIMITS(textures); i++) {
2169

2170 2171
                /* Note the D3DRS value applies to all textures, but GL has one
                   per texture, so apply it now ready to be used!               */
2172
                if (GL_SUPPORT(ARB_MULTITEXTURE)) {
2173 2174 2175
#if defined(GL_VERSION_1_3)
                    glActiveTexture(GL_TEXTURE0 + i);
#else
2176
                    glActiveTextureARB(GL_TEXTURE0_ARB + i);
2177
#endif
2178
                    checkGLcall("Activate texture.. to update const color");
2179
                } else if (i>0) {
2180
                    FIXME("Program using multiple concurrent textures which this opengl implementation doesnt support\n");
2181
                }
2182

2183 2184
                glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, &col[0]);
                checkGLcall("glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color);");
2185
            }
2186 2187 2188
        }
        break;

2189
    case D3DRS_SPECULARENABLE            : 
2190
        {
2191 2192 2193
            /* Originally this used glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL,GL_SEPARATE_SPECULAR_COLOR)
               and (GL_LIGHT_MODEL_COLOR_CONTROL,GL_SINGLE_COLOR) to swap between enabled/disabled
               specular color. This is wrong:
2194
               Separate specular color means the specular colour is maintained separately, whereas
2195 2196 2197 2198 2199 2200
               single color means it is merged in. However in both cases they are being used to
               some extent.
               To disable specular color, set it explicitly to black and turn off GL_COLOR_SUM_EXT
               NOTE: If not supported dont give FIXME as very minimal impact and very few people are
                  yet running 1.4!
             */
Raphael Junqueira's avatar
Raphael Junqueira committed
2201
              if (Value) {
2202 2203
                glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (float*) &This->UpdateStateBlock->material.Specular);
                checkGLcall("glMaterialfv");
2204 2205 2206 2207 2208
		if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
		  glEnable(GL_COLOR_SUM_EXT);
		} else {
		  TRACE("Specular colors cannot be enabled in this version of opengl\n");
		}
2209
                checkGLcall("glEnable(GL_COLOR_SUM)");
Raphael Junqueira's avatar
Raphael Junqueira committed
2210
              } else {
2211
                float black[4] = {0.0f, 0.0f, 0.0f, 0.0f};
2212 2213 2214 2215 2216 2217

                /* for the case of enabled lighting: */
                glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, &black[0]);
                checkGLcall("glMaterialfv");

                /* for the case of disabled lighting: */
2218 2219 2220 2221 2222
		if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
		  glDisable(GL_COLOR_SUM_EXT);
		} else {
		  TRACE("Specular colors cannot be disabled in this version of opengl\n");
		}
2223
                checkGLcall("glDisable(GL_COLOR_SUM)");
Raphael Junqueira's avatar
Raphael Junqueira committed
2224
	      }
2225 2226 2227
        }
        break;

2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
    case D3DRS_STENCILENABLE             :
        if (Value) {
            glEnable(GL_STENCIL_TEST);
            checkGLcall("glEnable GL_STENCIL_TEST");
        } else {
            glDisable(GL_STENCIL_TEST);
            checkGLcall("glDisable GL_STENCIL_TEST");
        }
        break;

    case D3DRS_STENCILFUNC               :
        {
           int glParm = GL_ALWAYS;
2241 2242
           int ref = This->StateBlock->renderstate[D3DRS_STENCILREF];
           GLuint mask = This->StateBlock->renderstate[D3DRS_STENCILMASK];
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256

           switch ((D3DCMPFUNC) Value) {
           case D3DCMP_NEVER:         glParm=GL_NEVER; break;
           case D3DCMP_LESS:          glParm=GL_LESS; break;
           case D3DCMP_EQUAL:         glParm=GL_EQUAL; break;
           case D3DCMP_LESSEQUAL:     glParm=GL_LEQUAL; break;
           case D3DCMP_GREATER:       glParm=GL_GREATER; break;
           case D3DCMP_NOTEQUAL:      glParm=GL_NOTEQUAL; break;
           case D3DCMP_GREATEREQUAL:  glParm=GL_GEQUAL; break;
           case D3DCMP_ALWAYS:        glParm=GL_ALWAYS; break;
           default:
               FIXME("Unrecognized/Unhandled D3DCMPFUNC value %ld\n", Value);
           }
           TRACE("glStencilFunc with Parm=%x, ref=%d, mask=%x\n", glParm, ref, mask);
Raphael Junqueira's avatar
Raphael Junqueira committed
2257 2258
	   This->stencilfunc = glParm;
	   glStencilFunc(glParm, ref, mask);
2259 2260 2261 2262 2263 2264
           checkGLcall("glStencilFunc");
        }
        break;

    case D3DRS_STENCILREF                :
        {
2265
           int glParm = This->stencilfunc;
2266
           int ref = 0;
2267
           GLuint mask = This->StateBlock->renderstate[D3DRS_STENCILMASK];
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277

           ref = Value;
           TRACE("glStencilFunc with Parm=%x, ref=%d, mask=%x\n", glParm, ref, mask);
           glStencilFunc(glParm, ref, mask);
           checkGLcall("glStencilFunc");
        }
        break;

    case D3DRS_STENCILMASK               :
        {
2278 2279
           int glParm = This->stencilfunc;
           int ref = This->StateBlock->renderstate[D3DRS_STENCILREF];
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
           GLuint mask = Value;

           TRACE("glStencilFunc with Parm=%x, ref=%d, mask=%x\n", glParm, ref, mask);
           glStencilFunc(glParm, ref, mask);
           checkGLcall("glStencilFunc");
        }
        break;

    case D3DRS_STENCILFAIL               :
        {
            GLenum fail  ; 
            GLenum zpass ; 
            GLenum zfail ; 

            fail = StencilOp(Value);
            glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &zpass);
            checkGLcall("glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &zpass);");
            glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &zfail);
            checkGLcall("glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &zfail);");

            TRACE("StencilOp fail=%x, zfail=%x, zpass=%x\n", fail, zfail, zpass);
            glStencilOp(fail, zfail, zpass);
            checkGLcall("glStencilOp(fail, zfail, zpass);");
        }
        break;
    case D3DRS_STENCILZFAIL              :
        {
            GLenum fail  ; 
            GLenum zpass ; 
            GLenum zfail ; 

            glGetIntegerv(GL_STENCIL_FAIL, &fail);
            checkGLcall("glGetIntegerv(GL_STENCIL_FAIL, &fail);");
            glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &zpass);
            checkGLcall("glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &zpass);");
            zfail = StencilOp(Value);

            TRACE("StencilOp fail=%x, zfail=%x, zpass=%x\n", fail, zfail, zpass);
            glStencilOp(fail, zfail, zpass);
            checkGLcall("glStencilOp(fail, zfail, zpass);");
        }
        break;
    case D3DRS_STENCILPASS               :
        {
            GLenum fail  ; 
            GLenum zpass ; 
            GLenum zfail ; 

            glGetIntegerv(GL_STENCIL_FAIL, &fail);
            checkGLcall("glGetIntegerv(GL_STENCIL_FAIL, &fail);");
            zpass = StencilOp(Value);
            glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &zfail);
            checkGLcall("glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &zfail);");

            TRACE("StencilOp fail=%x, zfail=%x, zpass=%x\n", fail, zfail, zpass);
            glStencilOp(fail, zfail, zpass);
            checkGLcall("glStencilOp(fail, zfail, zpass);");
        }
        break;

    case D3DRS_STENCILWRITEMASK          :
        {
            glStencilMask(Value);
2343
            TRACE("glStencilMask(%lu)\n", Value);
2344 2345 2346
            checkGLcall("glStencilMask");
        }
        break;
2347

2348
    case D3DRS_FOGENABLE                 :
Jason Edmeades's avatar
Jason Edmeades committed
2349
        {
2350
            if (Value && This->StateBlock->renderstate[D3DRS_FOGTABLEMODE] != D3DFOG_NONE) {
Jason Edmeades's avatar
Jason Edmeades committed
2351
               glEnable(GL_FOG);
2352
               checkGLcall("glEnable GL_FOG");
Jason Edmeades's avatar
Jason Edmeades committed
2353 2354
            } else {
               glDisable(GL_FOG);
2355
               checkGLcall("glDisable GL_FOG");
Jason Edmeades's avatar
Jason Edmeades committed
2356 2357 2358 2359
            }
        }
        break;

2360
    case D3DRS_FOGCOLOR                  :
Jason Edmeades's avatar
Jason Edmeades committed
2361 2362
        {
            float col[4];
2363
	    D3DCOLORTOGLFLOAT4(Value, col);
Jason Edmeades's avatar
Jason Edmeades committed
2364 2365 2366 2367 2368 2369
            /* Set the default alpha blend color */
            glFogfv(GL_FOG_COLOR, &col[0]);
            checkGLcall("glFog GL_FOG_COLOR");
        }
        break;

2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    case D3DRS_FOGTABLEMODE              :
        {
	  switch (Value) {
	  case D3DFOG_NONE:    /* I don't know what to do here */ break;
	  case D3DFOG_EXP:     glFogi(GL_FOG_MODE, GL_EXP); checkGLcall("glFogi(GL_FOG_MODE, GL_EXP"); break; 
	  case D3DFOG_EXP2:    glFogi(GL_FOG_MODE, GL_EXP2); checkGLcall("glFogi(GL_FOG_MODE, GL_EXP2"); break; 
	  case D3DFOG_LINEAR:  glFogi(GL_FOG_MODE, GL_LINEAR); checkGLcall("glFogi(GL_FOG_MODE, GL_LINEAR"); break; 
	  default:
	    FIXME("Unsupported Value(%lu) for D3DRS_FOGTABLEMODE!\n", Value);
	  }
        }
	break;

2383
    case D3DRS_FOGSTART                  :
Jason Edmeades's avatar
Jason Edmeades committed
2384
        {
2385
            float *f = (float*) &Value;
Jason Edmeades's avatar
Jason Edmeades committed
2386 2387 2388 2389 2390 2391
            glFogfv(GL_FOG_START, f);
            checkGLcall("glFogf(GL_FOG_START, (float) Value)");
            TRACE("Fog Start == %f\n", *f);
        }
        break;

2392
    case D3DRS_FOGEND                    :
Jason Edmeades's avatar
Jason Edmeades committed
2393
        {
2394
            float *f = (float*) &Value;
Jason Edmeades's avatar
Jason Edmeades committed
2395 2396 2397 2398 2399 2400
            glFogfv(GL_FOG_END, f);
            checkGLcall("glFogf(GL_FOG_END, (float) Value)");
            TRACE("Fog End == %f\n", *f);
        }
        break;

2401
    case D3DRS_FOGDENSITY                :
Jason Edmeades's avatar
Jason Edmeades committed
2402
        {
2403 2404
            float *f = (float*) &Value;
            glFogfv(GL_FOG_DENSITY, f);
Jason Edmeades's avatar
Jason Edmeades committed
2405 2406 2407 2408
            checkGLcall("glFogf(GL_FOG_DENSITY, (float) Value)");
        }
        break;

2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
    case D3DRS_VERTEXBLEND               :
        {
	  This->UpdateStateBlock->vertex_blend = (D3DVERTEXBLENDFLAGS) Value;
	  TRACE("Vertex Blending state to %ld\n",  Value);
        }
	break;

    case D3DRS_TWEENFACTOR               :
        {
	  This->UpdateStateBlock->tween_factor = *((float*) &Value);
	  TRACE("Vertex Blending Tween Factor to %f\n", This->UpdateStateBlock->tween_factor);
        }
	break;

    case D3DRS_INDEXEDVERTEXBLENDENABLE  :
        {
	  TRACE("Indexed Vertex Blend Enable to %ul\n", (BOOL) Value);
        }
	break;

2429 2430 2431 2432 2433 2434 2435 2436
    case D3DRS_COLORVERTEX               :
    case D3DRS_DIFFUSEMATERIALSOURCE     :
    case D3DRS_SPECULARMATERIALSOURCE    :
    case D3DRS_AMBIENTMATERIALSOURCE     :
    case D3DRS_EMISSIVEMATERIALSOURCE    :
        {
            GLenum Parm = GL_AMBIENT_AND_DIFFUSE;

2437
            if (This->StateBlock->renderstate[D3DRS_COLORVERTEX]) {
2438
                TRACE("diff %ld, amb %ld, emis %ld, spec %ld\n",
2439 2440 2441 2442
                      This->StateBlock->renderstate[D3DRS_DIFFUSEMATERIALSOURCE],
                      This->StateBlock->renderstate[D3DRS_AMBIENTMATERIALSOURCE],
                      This->StateBlock->renderstate[D3DRS_EMISSIVEMATERIALSOURCE],
                      This->StateBlock->renderstate[D3DRS_SPECULARMATERIALSOURCE]);
2443

2444 2445
                if (This->StateBlock->renderstate[D3DRS_DIFFUSEMATERIALSOURCE] == D3DMCS_COLOR1) {
                    if (This->StateBlock->renderstate[D3DRS_AMBIENTMATERIALSOURCE] == D3DMCS_COLOR1) {
2446 2447 2448 2449
                        Parm = GL_AMBIENT_AND_DIFFUSE;
                    } else {
                        Parm = GL_DIFFUSE;
                    }
2450
                } else if (This->StateBlock->renderstate[D3DRS_AMBIENTMATERIALSOURCE] == D3DMCS_COLOR1) {
2451
                    Parm = GL_AMBIENT;
2452
                } else if (This->StateBlock->renderstate[D3DRS_EMISSIVEMATERIALSOURCE] == D3DMCS_COLOR1) {
2453
                    Parm = GL_EMISSION;
2454
                } else if (This->StateBlock->renderstate[D3DRS_SPECULARMATERIALSOURCE] == D3DMCS_COLOR1) {
2455 2456 2457 2458 2459 2460
                    Parm = GL_SPECULAR;
                } else {
                    Parm = -1;
                }

                if (Parm == -1) {
2461
                    if (This->tracking_color != DISABLED_TRACKING) This->tracking_color = NEEDS_DISABLE;
2462
                } else {
2463 2464
                    This->tracking_color = NEEDS_TRACKING;
                    This->tracking_parm  = Parm;
2465 2466 2467
                }

            } else {
2468
                if (This->tracking_color != DISABLED_TRACKING) This->tracking_color = NEEDS_DISABLE;
2469 2470 2471 2472
            }
        }
        break; 

Jason Edmeades's avatar
Jason Edmeades committed
2473
    case D3DRS_LINEPATTERN               :
2474 2475 2476 2477 2478 2479
        {
            D3DLINEPATTERN *pattern = (D3DLINEPATTERN *)&Value;
            TRACE("Line pattern: repeat %d bits %x\n", pattern->wRepeatFactor, pattern->wLinePattern);

            if (pattern->wRepeatFactor) {
                glLineStipple(pattern->wRepeatFactor, pattern->wLinePattern);
2480
                checkGLcall("glLineStipple(repeat, linepattern)");
2481
                glEnable(GL_LINE_STIPPLE);
2482
                checkGLcall("glEnable(GL_LINE_STIPPLE);");
2483 2484
            } else {
                glDisable(GL_LINE_STIPPLE);
2485
                checkGLcall("glDisable(GL_LINE_STIPPLE);");
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
            }
        }
        break;

    case D3DRS_ZBIAS                     :
        {
            if (Value) {
                TRACE("ZBias value %f\n", *((float*)&Value));
                glPolygonOffset(0, -*((float*)&Value));
                checkGLcall("glPolygonOffset(0, -Value)");
                glEnable(GL_POLYGON_OFFSET_FILL);
                checkGLcall("glEnable(GL_POLYGON_OFFSET_FILL);");
                glEnable(GL_POLYGON_OFFSET_LINE);
                checkGLcall("glEnable(GL_POLYGON_OFFSET_LINE);");
                glEnable(GL_POLYGON_OFFSET_POINT);
                checkGLcall("glEnable(GL_POLYGON_OFFSET_POINT);");
            } else {
                glDisable(GL_POLYGON_OFFSET_FILL);
                checkGLcall("glDisable(GL_POLYGON_OFFSET_FILL);");
                glDisable(GL_POLYGON_OFFSET_LINE);
                checkGLcall("glDisable(GL_POLYGON_OFFSET_LINE);");
                glDisable(GL_POLYGON_OFFSET_POINT);
                checkGLcall("glDisable(GL_POLYGON_OFFSET_POINT);");
            }
        }
        break;

    case D3DRS_NORMALIZENORMALS          :
        if (Value) {
            glEnable(GL_NORMALIZE);
            checkGLcall("glEnable(GL_NORMALIZE);");
        } else {
            glDisable(GL_NORMALIZE);
            checkGLcall("glDisable(GL_NORMALIZE);");
        }
        break;

    case D3DRS_POINTSIZE                 :
        TRACE("Set point size to %f\n", *((float*)&Value));
        glPointSize(*((float*)&Value));
2526
        checkGLcall("glPointSize(...);");
2527 2528 2529
        break;

    case D3DRS_POINTSIZE_MIN             :
2530 2531
        if (GL_SUPPORT(EXT_POINT_PARAMETERS)) {
	  GL_EXTCALL(glPointParameterfEXT)(GL_POINT_SIZE_MIN_EXT, *((float*)&Value));
2532
	  checkGLcall("glPointParameterfEXT(...);");
2533 2534 2535
	} else {
	  FIXME("D3DRS_POINTSIZE_MIN not supported on this opengl\n");
	}
2536 2537 2538
        break;

    case D3DRS_POINTSIZE_MAX             :
2539 2540
        if (GL_SUPPORT(EXT_POINT_PARAMETERS)) {
	  GL_EXTCALL(glPointParameterfEXT)(GL_POINT_SIZE_MAX_EXT, *((float*)&Value));
2541
	  checkGLcall("glPointParameterfEXT(...);");
2542 2543 2544
	} else {
	  FIXME("D3DRS_POINTSIZE_MAX not supported on this opengl\n");
	}
2545 2546 2547 2548 2549 2550 2551 2552 2553
        break;

    case D3DRS_POINTSCALE_A              :
    case D3DRS_POINTSCALE_B              :
    case D3DRS_POINTSCALE_C              :
    case D3DRS_POINTSCALEENABLE          :
        {
            /* If enabled, supply the parameters, otherwise fall back to defaults */
            if (This->StateBlock->renderstate[D3DRS_POINTSCALEENABLE]) {
2554
                GLfloat att[3] = {1.0f, 0.0f, 0.0f};
2555 2556 2557 2558
                att[0] = *((float*)&This->StateBlock->renderstate[D3DRS_POINTSCALE_A]);
                att[1] = *((float*)&This->StateBlock->renderstate[D3DRS_POINTSCALE_B]);
                att[2] = *((float*)&This->StateBlock->renderstate[D3DRS_POINTSCALE_C]);

2559 2560
		if (GL_SUPPORT(EXT_POINT_PARAMETERS)) {
                  GL_EXTCALL(glPointParameterfvEXT)(GL_DISTANCE_ATTENUATION_EXT, att);
2561
		  checkGLcall("glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, ...);");
2562 2563 2564
		} else {
		  TRACE("D3DRS_POINTSCALEENABLE not supported on this opengl\n");
		}
2565
            } else {
2566 2567 2568
                GLfloat att[3] = {1.0f, 0.0f, 0.0f};
		if (GL_SUPPORT(EXT_POINT_PARAMETERS)) {
		  GL_EXTCALL(glPointParameterfvEXT)(GL_DISTANCE_ATTENUATION_EXT, att);
2569
		  checkGLcall("glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, ...);");
2570 2571 2572 2573
		} else {
		  TRACE("D3DRS_POINTSCALEENABLE not supported, but not on either\n");
		}
	    }
2574 2575 2576 2577 2578
            break;
        }

    case D3DRS_COLORWRITEENABLE          :
        TRACE("Color mask: r(%d) g(%d) b(%d) a(%d)\n", 
Raphael Junqueira's avatar
Raphael Junqueira committed
2579 2580 2581 2582 2583
	      Value & D3DCOLORWRITEENABLE_RED   ? 1 : 0,
	      Value & D3DCOLORWRITEENABLE_GREEN ? 1 : 0,
	      Value & D3DCOLORWRITEENABLE_BLUE  ? 1 : 0,
	      Value & D3DCOLORWRITEENABLE_ALPHA ? 1 : 0); 
	glColorMask(Value & D3DCOLORWRITEENABLE_RED, 
2584
                    Value & D3DCOLORWRITEENABLE_GREEN,
Raphael Junqueira's avatar
Raphael Junqueira committed
2585
		    Value & D3DCOLORWRITEENABLE_BLUE, 
2586
                    Value & D3DCOLORWRITEENABLE_ALPHA);
2587
        checkGLcall("glColorMask(...)");
2588 2589 2590
		break;

        /* Unhandled yet...! */
Jason Edmeades's avatar
Jason Edmeades committed
2591 2592
    case D3DRS_LASTPIXEL                 :
    case D3DRS_ZVISIBLE                  :
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
    case D3DRS_EDGEANTIALIAS             :
    case D3DRS_RANGEFOGENABLE            :
    case D3DRS_WRAP0                     :
    case D3DRS_WRAP1                     :
    case D3DRS_WRAP2                     :
    case D3DRS_WRAP3                     :
    case D3DRS_WRAP4                     :
    case D3DRS_WRAP5                     :
    case D3DRS_WRAP6                     :
    case D3DRS_WRAP7                     :
    case D3DRS_FOGVERTEXMODE             :
    case D3DRS_LOCALVIEWER               :
    case D3DRS_SOFTWAREVERTEXPROCESSING  :
    case D3DRS_POINTSPRITEENABLE         :
    case D3DRS_MULTISAMPLEANTIALIAS      :
    case D3DRS_MULTISAMPLEMASK           :
    case D3DRS_PATCHEDGESTYLE            :
    case D3DRS_PATCHSEGMENTS             :
    case D3DRS_DEBUGMONITORTOKEN         :
2612 2613
    case D3DRS_POSITIONORDER             :
    case D3DRS_NORMALORDER               :
2614 2615
        /*Put back later: FIXME("(%p)->(%d,%ld) not handled yet\n", This, State, Value); */
        TRACE("(%p)->(%d,%ld) not handled yet\n", This, State, Value);
2616 2617 2618 2619 2620
        break;
    default:
        FIXME("(%p)->(%d,%ld) unrecognized\n", This, State, Value);
    }

2621 2622
    LEAVE_GL();

2623 2624 2625 2626 2627
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetRenderState(LPDIRECT3DDEVICE8 iface, D3DRENDERSTATETYPE State,DWORD* pValue) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    TRACE("(%p) for State %d = %ld\n", This, State, This->UpdateStateBlock->renderstate[State]);
2628
    *pValue = This->StateBlock->renderstate[State];
2629 2630 2631
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_BeginStateBlock(LPDIRECT3DDEVICE8 iface) {
2632 2633 2634 2635
  ICOM_THIS(IDirect3DDevice8Impl,iface);
  
  TRACE("(%p)\n", This);
  
2636
  return IDirect3DDeviceImpl_BeginStateBlock(This);
2637 2638
}
HRESULT  WINAPI  IDirect3DDevice8Impl_EndStateBlock(LPDIRECT3DDEVICE8 iface, DWORD* pToken) {
2639 2640 2641
  IDirect3DStateBlockImpl* pSB;
  ICOM_THIS(IDirect3DDevice8Impl,iface);
  HRESULT res;
2642

2643
  TRACE("(%p)\n", This);
2644

2645 2646 2647
  res = IDirect3DDeviceImpl_EndStateBlock(This, &pSB);
  *pToken = (DWORD) pSB;
  return res;
2648 2649 2650
}

HRESULT  WINAPI  IDirect3DDevice8Impl_ApplyStateBlock(LPDIRECT3DDEVICE8 iface, DWORD Token) {
2651 2652
  IDirect3DStateBlockImpl* pSB = (IDirect3DStateBlockImpl*) Token;
  ICOM_THIS(IDirect3DDevice8Impl,iface);
2653

2654
  TRACE("(%p)\n", This);
2655

2656
  return IDirect3DDeviceImpl_ApplyStateBlock(This, pSB);
2657 2658 2659

}
HRESULT  WINAPI  IDirect3DDevice8Impl_CaptureStateBlock(LPDIRECT3DDEVICE8 iface, DWORD Token) {
2660 2661
  IDirect3DStateBlockImpl* pSB = (IDirect3DStateBlockImpl*) Token;
  ICOM_THIS(IDirect3DDevice8Impl,iface);
2662

2663
  TRACE("(%p)\n", This);
2664

2665
  return IDirect3DDeviceImpl_CaptureStateBlock(This, pSB);
2666 2667
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DeleteStateBlock(LPDIRECT3DDEVICE8 iface, DWORD Token) {
2668 2669
  IDirect3DStateBlockImpl* pSB = (IDirect3DStateBlockImpl*) Token;
  ICOM_THIS(IDirect3DDevice8Impl,iface);
2670

2671
  TRACE("(%p)\n", This);
2672

2673 2674
  return IDirect3DDeviceImpl_DeleteStateBlock(This, pSB);
}
2675

2676 2677 2678 2679
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateStateBlock(LPDIRECT3DDEVICE8 iface, D3DSTATEBLOCKTYPE Type, DWORD* pToken) {
  IDirect3DStateBlockImpl* pSB;
  ICOM_THIS(IDirect3DDevice8Impl,iface);
  HRESULT res;
2680

2681
  TRACE("(%p) : for type %d\n", This, Type);
2682

2683 2684 2685
  res = IDirect3DDeviceImpl_CreateStateBlock(This, Type, &pSB);
  *pToken = (DWORD) pSB;
  return res;
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
}

HRESULT  WINAPI  IDirect3DDevice8Impl_SetClipStatus(LPDIRECT3DDEVICE8 iface, CONST D3DCLIPSTATUS8* pClipStatus) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetClipStatus(LPDIRECT3DDEVICE8 iface, D3DCLIPSTATUS8* pClipStatus) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetTexture(LPDIRECT3DDEVICE8 iface, DWORD Stage,IDirect3DBaseTexture8** ppTexture) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
2698
    TRACE("(%p) : returning %p for stage %ld\n", This, This->UpdateStateBlock->textures[Stage], Stage);
2699
    *ppTexture = (LPDIRECT3DBASETEXTURE8) This->UpdateStateBlock->textures[Stage];
2700 2701 2702
    IDirect3DBaseTexture8Impl_AddRef(*ppTexture);
    return D3D_OK;
}
2703
HRESULT  WINAPI  IDirect3DDevice8Impl_SetTexture(LPDIRECT3DDEVICE8 iface, DWORD Stage, IDirect3DBaseTexture8* pTexture) {
2704 2705

    IDirect3DBaseTexture8 *oldTxt;
2706
    BOOL reapplyStates = TRUE;
2707 2708
    DWORD oldTextureDimensions = -1;
    DWORD reapplyFlags = 0;
2709 2710 2711 2712

    ICOM_THIS(IDirect3DDevice8Impl,iface);
    D3DRESOURCETYPE textureType;

2713
    oldTxt = This->UpdateStateBlock->textures[Stage];
2714 2715
    TRACE("(%p) : Stage(%ld), Texture (%p)\n", This, Stage, pTexture);

2716
    /* Reject invalid texture units */
2717
    if (Stage >= GL_LIMITS(textures)) {
2718 2719 2720 2721
        TRACE("Attempt to access invalid texture rejected\n");
        return D3DERR_INVALIDCALL;
    }

2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
    This->UpdateStateBlock->Set.textures[Stage] = TRUE;
    This->UpdateStateBlock->Changed.textures[Stage] = TRUE;
    This->UpdateStateBlock->textures[Stage] = pTexture;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

2732
    oldTextureDimensions = This->UpdateStateBlock->textureDimensions[Stage];
2733 2734
    ENTER_GL();

2735
    /* Make appropriate texture active */
2736
    if (GL_SUPPORT(ARB_MULTITEXTURE)) {
2737 2738 2739
#if defined(GL_VERSION_1_3)
        glActiveTexture(GL_TEXTURE0 + Stage);
#else
2740
        glActiveTextureARB(GL_TEXTURE0_ARB + Stage);
2741
#endif
2742 2743 2744 2745
        checkGLcall("glActiveTextureARB");
    } else if (Stage>0) {
        FIXME("Program using multiple concurrent textures which this opengl implementation doesnt support\n");
    }
2746 2747

    /* Decrement the count of the previous texture */
2748
    if (NULL != oldTxt) {
2749 2750 2751
        IDirect3DBaseTexture8Impl_Release(oldTxt);
    }

2752 2753
    if (NULL != pTexture) {
        IDirect3DBaseTexture8Impl_AddRef((LPDIRECT3DBASETEXTURE8) This->UpdateStateBlock->textures[Stage]);
2754 2755 2756 2757 2758

        /* Now setup the texture appropraitly */
        textureType = IDirect3DBaseTexture8Impl_GetType(pTexture);

        if (textureType == D3DRTYPE_TEXTURE) {
2759 2760 2761
          if (oldTxt == pTexture && TRUE == IDirect3DBaseTexture8Impl_IsDirty(pTexture)) {
            TRACE("Skipping setting texture as old == new\n");
            reapplyStates = FALSE;
2762
          } else {
2763 2764
            /* Standard 2D texture */
            TRACE("Standard 2d texture\n");
2765
            This->UpdateStateBlock->textureDimensions[Stage] = GL_TEXTURE_2D;
2766

2767
            /* Load up the texture now */
2768
            IDirect3DTexture8Impl_PreLoad((LPDIRECT3DTEXTURE8) pTexture);
2769
          }
2770
        } else if (textureType == D3DRTYPE_VOLUMETEXTURE) {
2771 2772 2773 2774 2775
	  if (oldTxt == pTexture && TRUE == IDirect3DBaseTexture8Impl_IsDirty(pTexture)) {
	    TRACE("Skipping setting texture as old == new\n");
	    reapplyStates = FALSE;
          } else {
	    /* Standard 3D (volume) texture */
2776
            TRACE("Standard 3d texture\n");
2777
            This->UpdateStateBlock->textureDimensions[Stage] = GL_TEXTURE_3D;
2778

2779 2780
            /* Load up the texture now */
	    IDirect3DVolumeTexture8Impl_PreLoad((LPDIRECT3DVOLUMETEXTURE8) pTexture);
2781
	  }
2782
        } else if (textureType == D3DRTYPE_CUBETEXTURE) {
2783 2784 2785 2786
	  if (oldTxt == pTexture && TRUE == IDirect3DBaseTexture8Impl_IsDirty(pTexture)) {
	    TRACE("Skipping setting texture as old == new\n");
	    reapplyStates = FALSE;
          } else {
2787 2788 2789
	    /* Standard Cube texture */
	    TRACE("Standard Cube texture\n");
	    This->UpdateStateBlock->textureDimensions[Stage] = GL_TEXTURE_CUBE_MAP_ARB;
2790

2791 2792
	    /* Load up the texture now */
	    IDirect3DCubeTexture8Impl_PreLoad((LPDIRECT3DCUBETEXTURE8) pTexture);
2793
	  }
2794 2795
	} else {
            FIXME("(%p) : Incorrect type for a texture : (%d,%s)\n", This, textureType, debug_d3dressourcetype(textureType));
2796
        }
2797 2798
    } else {
        TRACE("Setting to no texture (ie default texture)\n");
2799
        This->UpdateStateBlock->textureDimensions[Stage] = GL_TEXTURE_1D;
2800 2801 2802
        glBindTexture(GL_TEXTURE_1D, This->dummyTextureName[Stage]);
        checkGLcall("glBindTexture");
        TRACE("Bound dummy Texture to stage %ld (gl name %d)\n", Stage, This->dummyTextureName[Stage]);
2803
    }
2804

2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
    /* Disable the old texture binding and enable the new one (unless operations are disabled) */
    if (oldTextureDimensions != This->UpdateStateBlock->textureDimensions[Stage]) {
       glDisable(oldTextureDimensions);
       checkGLcall("Disable oldTextureDimensions");
       if (This->StateBlock->texture_state[Stage][D3DTSS_COLOROP] != D3DTOP_DISABLE) {
          glEnable(This->UpdateStateBlock->textureDimensions[Stage]);
          checkGLcall("Disable new texture dimensions");
       }

       /* If Alpha arg1 is texture then handle the special case when there changes between a
          texture and no texture - See comments in set_tex_op                                  */
       if ((This->StateBlock->texture_state[Stage][D3DTSS_ALPHAARG1] == D3DTA_TEXTURE) && 
2817
           (((oldTxt == NULL) && (pTexture != NULL)) || ((pTexture == NULL) && (oldTxt != NULL))))
2818 2819 2820 2821 2822 2823
       {
           reapplyFlags |= REAPPLY_ALPHAOP;
       }
    }


2824 2825
    /* Even if the texture has been set to null, reapply the stages as a null texture to directx requires
       a dummy texture in opengl, and we always need to ensure the current view of the TextureStates apply */
2826
    if (reapplyStates) {
2827
       setupTextureStates(iface, Stage, reapplyFlags);
2828
    }
2829 2830 2831

    LEAVE_GL();   

2832 2833 2834 2835 2836
    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_GetTextureStageState(LPDIRECT3DDEVICE8 iface, DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD* pValue) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
2837 2838
    TRACE("(%p) : requesting Stage %ld, Type %d getting %ld\n", This, Stage, Type, This->UpdateStateBlock->texture_state[Stage][Type]);
    *pValue = This->UpdateStateBlock->texture_state[Stage][Type];
2839 2840 2841
    return D3D_OK;
}

2842
HRESULT  WINAPI  IDirect3DDevice8Impl_SetTextureStageState(LPDIRECT3DDEVICE8 iface, DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value) {
2843 2844
    ICOM_THIS(IDirect3DDevice8Impl,iface);

2845 2846
    /* FIXME: Handle 3d textures? What if TSS value set before set texture? Need to reapply all values? */
   
2847
    TRACE("(%p) : Stage=%ld, Type=%s(%d), Value=%ld\n", This, Stage, debug_d3dtexturestate(Type), Type, Value);
2848

2849
    /* Reject invalid texture units */
2850
    if (Stage >= GL_LIMITS(textures)) {
2851 2852 2853 2854
        TRACE("Attempt to access invalid texture rejected\n");
        return D3DERR_INVALIDCALL;
    }

2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
    This->UpdateStateBlock->Changed.texture_state[Stage][Type] = TRUE;
    This->UpdateStateBlock->Set.texture_state[Stage][Type] = TRUE;
    This->UpdateStateBlock->texture_state[Stage][Type] = Value;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

2865 2866
    ENTER_GL();

2867
    /* Make appropriate texture active */
2868
    VTRACE(("Activating appropriate texture state %ld\n", Stage));
2869
    if (GL_SUPPORT(ARB_MULTITEXTURE)) {
2870 2871
#if defined(GL_VERSION_1_3)
        glActiveTexture(GL_TEXTURE0 + Stage);
2872
        vcheckGLcall("glActiveTexture");
2873
#else
2874
        glActiveTextureARB(GL_TEXTURE0_ARB + Stage);
2875
        vcheckGLcall("glActiveTextureARB");
2876
#endif
2877
    } else if (Stage > 0) {
2878 2879
        FIXME("Program using multiple concurrent textures which this opengl implementation doesnt support\n");
    }
2880 2881 2882 2883

    switch (Type) {

    case D3DTSS_MINFILTER             :
2884 2885
    case D3DTSS_MIPFILTER             :
        {
2886 2887
            DWORD ValueMIN = This->StateBlock->texture_state[Stage][D3DTSS_MINFILTER];
            DWORD ValueMIP = This->StateBlock->texture_state[Stage][D3DTSS_MIPFILTER];
2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
            GLint realVal = GL_LINEAR;

            if (ValueMIN == D3DTEXF_POINT) {
                /* GL_NEAREST_* */
                if (ValueMIP == D3DTEXF_POINT) {
                    realVal = GL_NEAREST_MIPMAP_NEAREST;
                } else if (ValueMIP == D3DTEXF_LINEAR) {
                    realVal = GL_NEAREST_MIPMAP_LINEAR;
                } else if (ValueMIP == D3DTEXF_NONE) {
                    realVal = GL_NEAREST;
                } else {
                    FIXME("Unhandled D3DTSS_MIPFILTER value of %ld\n", ValueMIP);
                    realVal = GL_NEAREST_MIPMAP_LINEAR;
                }
            } else if (ValueMIN == D3DTEXF_LINEAR) {
                /* GL_LINEAR_* */
                if (ValueMIP == D3DTEXF_POINT) {
                    realVal = GL_LINEAR_MIPMAP_NEAREST;
                } else if (ValueMIP == D3DTEXF_LINEAR) {
                    realVal = GL_LINEAR_MIPMAP_LINEAR;
                } else if (ValueMIP == D3DTEXF_NONE) {
                    realVal = GL_LINEAR;
                } else {
                    FIXME("Unhandled D3DTSS_MIPFILTER value of %ld\n", ValueMIP);
                    realVal = GL_LINEAR_MIPMAP_LINEAR;
                }
            } else if (ValueMIN == D3DTEXF_NONE) {
                /* Doesnt really make sense - Windows just seems to disable
                   mipmapping when this occurs                              */
                FIXME("Odd - minfilter of none, just disabling mipmaps\n");
                realVal = GL_LINEAR;

            } else {
                FIXME("Unhandled D3DTSS_MINFILTER value of %ld\n", ValueMIN);
                realVal = GL_LINEAR_MIPMAP_LINEAR;
            }

            TRACE("ValueMIN=%ld, ValueMIP=%ld, setting MINFILTER to %x\n", ValueMIN, ValueMIP, realVal);
2926
            glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_MIN_FILTER, realVal);
2927
            checkGLcall("glTexParameter GL_TEXTURE_MINFILTER, ...");
2928 2929 2930
        }
        break;

Raphael Junqueira's avatar
Raphael Junqueira committed
2931 2932 2933 2934 2935 2936 2937 2938
    case D3DTSS_MAXANISOTROPY         :
      {	
	if (GL_SUPPORT(EXT_TEXTURE_FILTER_ANISOTROPIC)) {
	  glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_MAX_ANISOTROPY_EXT, This->StateBlock->texture_state[Stage][D3DTSS_MAXANISOTROPY]);
	  checkGLcall("glTexParameteri GL_TEXTURE_MAX_ANISOTROPY_EXT ...");
	}
      }
      break;
2939 2940 2941

    case D3DTSS_MAGFILTER             :
        if (Value == D3DTEXF_POINT) {
2942
            glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2943 2944
            checkGLcall("glTexParameter GL_TEXTURE_MAGFILTER, GL_NEAREST");
        } else if (Value == D3DTEXF_LINEAR) {
2945
            glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
            checkGLcall("glTexParameter GL_TEXTURE_MAGFILTER, GL_LINEAR");
        } else {
            FIXME("Unhandled D3DTSS_MAGFILTER value of %ld\n", Value);
        }
        break;

    case D3DTSS_ALPHAOP               :
    case D3DTSS_COLOROP               :
        {

2956
            if ((Value == D3DTOP_DISABLE) && (Type == D3DTSS_COLOROP)) {
2957
                /* TODO: Disable by making this and all later levels disabled */
2958 2959 2960 2961 2962 2963
                glDisable(GL_TEXTURE_1D);
                checkGLcall("Disable GL_TEXTURE_1D");
                glDisable(GL_TEXTURE_2D);
                checkGLcall("Disable GL_TEXTURE_2D");
                glDisable(GL_TEXTURE_3D);
                checkGLcall("Disable GL_TEXTURE_3D");
2964
                break; /* Dont bother setting the texture operations */
2965 2966
            } else {
                /* Enable only the appropriate texture dimension */
2967
                if (Type == D3DTSS_COLOROP) {
2968
                    if (This->StateBlock->textureDimensions[Stage] == GL_TEXTURE_1D) {
2969 2970 2971 2972 2973 2974
                        glEnable(GL_TEXTURE_1D);
                        checkGLcall("Enable GL_TEXTURE_1D");
                    } else {
                        glDisable(GL_TEXTURE_1D);
                        checkGLcall("Disable GL_TEXTURE_1D");
                    } 
2975
                    if (This->StateBlock->textureDimensions[Stage] == GL_TEXTURE_2D) {
2976 2977 2978 2979 2980 2981
                        glEnable(GL_TEXTURE_2D);
                        checkGLcall("Enable GL_TEXTURE_2D");
                    } else {
                        glDisable(GL_TEXTURE_2D);
                        checkGLcall("Disable GL_TEXTURE_2D");
                    }
2982
                    if (This->StateBlock->textureDimensions[Stage] == GL_TEXTURE_3D) {
2983 2984 2985 2986 2987 2988
                        glEnable(GL_TEXTURE_3D);
                        checkGLcall("Enable GL_TEXTURE_3D");
                    } else {
                        glDisable(GL_TEXTURE_3D);
                        checkGLcall("Disable GL_TEXTURE_3D");
                    }
2989 2990 2991 2992 2993 2994 2995
                    if (This->StateBlock->textureDimensions[Stage] == GL_TEXTURE_CUBE_MAP_ARB) {
                        glEnable(GL_TEXTURE_CUBE_MAP_ARB);
                        checkGLcall("Enable GL_TEXTURE_CUBE_MAP");
                    } else {
                        glDisable(GL_TEXTURE_CUBE_MAP_ARB);
                        checkGLcall("Disable GL_TEXTURE_CUBE_MAP");
                    }
2996
                }
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
            }
            /* Drop through... (Except disable case) */
        case D3DTSS_COLORARG0             :
        case D3DTSS_COLORARG1             :
        case D3DTSS_COLORARG2             :
        case D3DTSS_ALPHAARG0             :
        case D3DTSS_ALPHAARG1             :
        case D3DTSS_ALPHAARG2             :
            {
                BOOL isAlphaArg = (Type == D3DTSS_ALPHAOP || Type == D3DTSS_ALPHAARG1 || 
                                   Type == D3DTSS_ALPHAARG2 || Type == D3DTSS_ALPHAARG0);
                if (isAlphaArg) {
                    set_tex_op(iface, TRUE, Stage, This->StateBlock->texture_state[Stage][D3DTSS_ALPHAOP],
                               This->StateBlock->texture_state[Stage][D3DTSS_ALPHAARG1], 
                               This->StateBlock->texture_state[Stage][D3DTSS_ALPHAARG2], 
                               This->StateBlock->texture_state[Stage][D3DTSS_ALPHAARG0]);
                } else {
                    set_tex_op(iface, FALSE, Stage, This->StateBlock->texture_state[Stage][D3DTSS_COLOROP],
                               This->StateBlock->texture_state[Stage][D3DTSS_COLORARG1], 
                               This->StateBlock->texture_state[Stage][D3DTSS_COLORARG2], 
                               This->StateBlock->texture_state[Stage][D3DTSS_COLORARG0]);
3018
                }
3019 3020 3021 3022
            }
            break;
        }

3023 3024 3025 3026 3027 3028 3029
    case D3DTSS_ADDRESSU              :
    case D3DTSS_ADDRESSV              :
    case D3DTSS_ADDRESSW              :
        {
            GLint wrapParm = GL_REPEAT;
            switch (Value) {
            case D3DTADDRESS_WRAP:   wrapParm = GL_REPEAT; break;
3030 3031
            case D3DTADDRESS_CLAMP:  wrapParm = GL_CLAMP_TO_EDGE; break;      
            case D3DTADDRESS_BORDER: wrapParm = GL_REPEAT; break;      /* FIXME: Not right, but better */
3032 3033 3034
#if defined(GL_VERSION_1_4)
            case D3DTADDRESS_MIRROR: wrapParm = GL_MIRRORED_REPEAT; break;
#elif defined(GL_ARB_texture_mirrored_repeat)
3035 3036 3037 3038
            case D3DTADDRESS_MIRROR: wrapParm = GL_MIRRORED_REPEAT_ARB; break;
#else
            case D3DTADDRESS_MIRROR:      /* Unsupported in OpenGL pre-1.4 */
#endif
3039
            case D3DTADDRESS_MIRRORONCE:  /* Unsupported in OpenGL         */
3040 3041 3042 3043 3044 3045 3046
            default:
                FIXME("Unrecognized or unsupported D3DTADDRESS_* value %ld, state %d\n", Value, Type);
                wrapParm = GL_REPEAT; 
            }

            switch (Type) {
            case D3DTSS_ADDRESSU:
3047 3048
                TRACE("Setting WRAP_S to %d for %x\n", wrapParm, This->StateBlock->textureDimensions[Stage]);
                glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_WRAP_S, wrapParm);
3049 3050 3051
                checkGLcall("glTexParameteri(..., GL_TEXTURE_WRAP_S, wrapParm)");
                break;
            case D3DTSS_ADDRESSV:
3052 3053
                TRACE("Setting WRAP_T to %d for %x\n", wrapParm, This->StateBlock->textureDimensions[Stage]);
                glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_WRAP_T, wrapParm);
3054 3055 3056
                checkGLcall("glTexParameteri(..., GL_TEXTURE_WRAP_T, wrapParm)");
                break;
            case D3DTSS_ADDRESSW:
3057 3058
                TRACE("Setting WRAP_R to %d for %x\n", wrapParm, This->StateBlock->textureDimensions[Stage]);
                glTexParameteri(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_WRAP_R, wrapParm);
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
                checkGLcall("glTexParameteri(..., GL_TEXTURE_WRAP_R, wrapParm)");
                break;
            default: /* nop */
      	        break; /** stupic compilator */
            }
        }
        break;

    case D3DTSS_BORDERCOLOR           :
        {
            float col[4];
3070
	    D3DCOLORTOGLFLOAT4(Value, col);
3071 3072
            TRACE("Setting border color for %x to %lx\n", This->StateBlock->textureDimensions[Stage], Value); 
            glTexParameterfv(This->StateBlock->textureDimensions[Stage], GL_TEXTURE_BORDER_COLOR, &col[0]);
3073 3074 3075 3076
            checkGLcall("glTexParameteri(..., GL_TEXTURE_BORDER_COLOR, ...)");
        }
        break;

3077
    case D3DTSS_TEXCOORDINDEX         :
3078
        {
3079
            /* Values 0-7 are indexes into the FVF tex coords - See comments in DrawPrimitive */
3080 3081 3082 3083 3084 3085 3086 3087 3088

            /* FIXME: From MSDN: The D3DTSS_TCI_* flags are mutually exclusive. If you include 
                  one flag, you can still specify an index value, which the system uses to 
                  determine the texture wrapping mode.  
                  eg. SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION | 1 );
                  means use the vertex position (camera-space) as the input texture coordinates 
                  for this texture stage, and the wrap mode set in the D3DRS_WRAP1 render 
                  state. We do not (yet) support the D3DRENDERSTATE_WRAPx values, nor tie them up
                  to the TEXCOORDINDEX value */
3089 3090 3091 3092
          
            /** 
             * Be careful the value of the mask 0xF0000 come from d3d8types.h infos 
             */
3093
            switch (Value & 0xFFFF0000) {
3094 3095
            case D3DTSS_TCI_PASSTHRU:
              /*Use the specified texture coordinates contained within the vertex format. This value resolves to zero.*/
3096 3097 3098
	      glDisable(GL_TEXTURE_GEN_S);
	      glDisable(GL_TEXTURE_GEN_T);
	      glDisable(GL_TEXTURE_GEN_R);
3099
              checkGLcall("glDisable(GL_TEXTURE_GEN_S,T,R)");
3100
              break;
3101 3102

            case D3DTSS_TCI_CAMERASPACEPOSITION:
3103 3104 3105 3106
              /* CameraSpacePosition means use the vertex position, transformed to camera space, 
                 as the input texture coordinates for this stage's texture transformation. This 
                 equates roughly to EYE_LINEAR                                                  */
              {
3107 3108 3109 3110 3111 3112
                float s_plane[] = { 1.0, 0.0, 0.0, 0.0 };
                float t_plane[] = { 0.0, 1.0, 0.0, 0.0 };
                float r_plane[] = { 0.0, 0.0, 1.0, 0.0 };
                float q_plane[] = { 0.0, 0.0, 0.0, 1.0 };
                TRACE("D3DTSS_TCI_CAMERASPACEPOSITION - Set eye plane\n");

3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();
                glLoadIdentity();
                glTexGenfv(GL_S, GL_EYE_PLANE, s_plane);
                glTexGenfv(GL_T, GL_EYE_PLANE, t_plane);
                glTexGenfv(GL_R, GL_EYE_PLANE, r_plane);
                glTexGenfv(GL_Q, GL_EYE_PLANE, q_plane);
                glPopMatrix();
                
                TRACE("D3DTSS_TCI_CAMERASPACEPOSITION - Set GL_TEXTURE_GEN_x and GL_x, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR\n");
                glEnable(GL_TEXTURE_GEN_S);
                checkGLcall("glEnable(GL_TEXTURE_GEN_S);");
                glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
                checkGLcall("glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR)");
                glEnable(GL_TEXTURE_GEN_T);
                checkGLcall("glEnable(GL_TEXTURE_GEN_T);");
                glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
                checkGLcall("glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR)");
                glEnable(GL_TEXTURE_GEN_R);
                checkGLcall("glEnable(GL_TEXTURE_GEN_R);");
                glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
                checkGLcall("glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR)");
              }
              break;

3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
#if defined(GL_ARB_texture_cube_map) || defined(GL_NV_texgen_reflection)
	    case D3DTSS_TCI_CAMERASPACENORMAL:
	      {
		float s_plane[] = { 1.0, 0.0, 0.0, 0.0 };
                float t_plane[] = { 0.0, 1.0, 0.0, 0.0 };
                float r_plane[] = { 0.0, 0.0, 1.0, 0.0 };
                float q_plane[] = { 0.0, 0.0, 0.0, 1.0 };
                TRACE("D3DTSS_TCI_CAMERASPACEPOSITION - Set eye plane\n");

                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();
                glLoadIdentity();
                glTexGenfv(GL_S, GL_EYE_PLANE, s_plane);
                glTexGenfv(GL_T, GL_EYE_PLANE, t_plane);
                glTexGenfv(GL_R, GL_EYE_PLANE, r_plane);
                glTexGenfv(GL_Q, GL_EYE_PLANE, q_plane);
                glPopMatrix();

		glEnable(GL_TEXTURE_GEN_S);
		checkGLcall("glEnable(GL_TEXTURE_GEN_S);");
		glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB);
                checkGLcall("glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB)");
		glEnable(GL_TEXTURE_GEN_T);
		checkGLcall("glEnable(GL_TEXTURE_GEN_T);");
		glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB);
                checkGLcall("glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB)");
		glEnable(GL_TEXTURE_GEN_R);
		checkGLcall("glEnable(GL_TEXTURE_GEN_R);");
		glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB);
                checkGLcall("glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB)");
	      }
	      break;
#endif

#if defined(GL_ARB_texture_cube_map) || defined(GL_NV_texgen_reflection)
	    case D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR:
	      {

		float s_plane[] = { 1.0, 0.0, 0.0, 0.0 };
                float t_plane[] = { 0.0, 1.0, 0.0, 0.0 };
                float r_plane[] = { 0.0, 0.0, 1.0, 0.0 };
                float q_plane[] = { 0.0, 0.0, 0.0, 1.0 };
                TRACE("D3DTSS_TCI_CAMERASPACEPOSITION - Set eye plane\n");

                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();
                glLoadIdentity();
                glTexGenfv(GL_S, GL_EYE_PLANE, s_plane);
                glTexGenfv(GL_T, GL_EYE_PLANE, t_plane);
                glTexGenfv(GL_R, GL_EYE_PLANE, r_plane);
                glTexGenfv(GL_Q, GL_EYE_PLANE, q_plane);
                glPopMatrix();
		
		glEnable(GL_TEXTURE_GEN_S);
		checkGLcall("glEnable(GL_TEXTURE_GEN_S);");
		glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB);
                checkGLcall("glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB)");
		glEnable(GL_TEXTURE_GEN_T);
		checkGLcall("glEnable(GL_TEXTURE_GEN_T);");
		glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB);
                checkGLcall("glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB)");
		glEnable(GL_TEXTURE_GEN_R);
		checkGLcall("glEnable(GL_TEXTURE_GEN_R);");
		glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB);
                checkGLcall("glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB)");
	      }
	      break;
#endif

3207
            /* Unhandled types: */
3208 3209
            default:
                /* Todo: */
3210 3211 3212 3213
                /* ? disable GL_TEXTURE_GEN_n ? */ 
	        glDisable(GL_TEXTURE_GEN_S);
	        glDisable(GL_TEXTURE_GEN_T);
	        glDisable(GL_TEXTURE_GEN_R);
3214 3215 3216
                FIXME("Unhandled D3DTSS_TEXCOORDINDEX %lx\n", Value);
                break;
            }
3217 3218 3219
        }
        break;

3220 3221 3222
        /* Unhandled */
    case D3DTSS_BUMPENVMAT00          :
    case D3DTSS_BUMPENVMAT01          :
3223 3224
        TRACE("BUMPENVMAT0%u Still a stub, Stage=%ld, Type=%d, Value =%ld\n", Type - D3DTSS_BUMPENVMAT00, Stage, Type, Value);
        break;
3225 3226
    case D3DTSS_BUMPENVMAT10          :
    case D3DTSS_BUMPENVMAT11          :
3227 3228 3229 3230
        TRACE("BUMPENVMAT1%u Still a stub, Stage=%ld, Type=%d, Value =%ld\n", Type - D3DTSS_BUMPENVMAT10, Stage, Type, Value);
        break;

    case D3DTSS_TEXTURETRANSFORMFLAGS :
3231
        set_texture_matrix((float *)&This->StateBlock->transforms[D3DTS_TEXTURE0 + Stage].u.m[0][0], Value);
3232
        break; 
3233

3234 3235 3236 3237 3238 3239
    case D3DTSS_MIPMAPLODBIAS         :
    case D3DTSS_MAXMIPLEVEL           :
    case D3DTSS_BUMPENVLSCALE         :
    case D3DTSS_BUMPENVLOFFSET        :
    case D3DTSS_RESULTARG             :
    default:
3240 3241
        /* Put back later: FIXME("(%p) : stub, Stage=%ld, Type=%d, Value =%ld\n", This, Stage, Type, Value); */
        TRACE("Still a stub, Stage=%ld, Type=%d, Value =%ld\n", Stage, Type, Value);
3242
    }
3243 3244 3245

    LEAVE_GL();

3246 3247 3248 3249
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_ValidateDevice(LPDIRECT3DDEVICE8 iface, DWORD* pNumPasses) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3250 3251
    TRACE("(%p) : stub\n", This);    /* FIXME: Needs doing, but called often and is harmless */
    return D3D_OK;
3252
}
3253
HRESULT  WINAPI  IDirect3DDevice8Impl_GetInfo(LPDIRECT3DDEVICE8 iface, DWORD DevInfoID, void* pDevInfoStruct, DWORD DevInfoStructSize) {
3254
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3255 3256
    FIXME("(%p) : stub\n", This);    
    return D3D_OK;
3257
}
3258
HRESULT  WINAPI  IDirect3DDevice8Impl_SetPaletteEntries(LPDIRECT3DDEVICE8 iface, UINT PaletteNumber, CONST PALETTEENTRY* pEntries) {
3259
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3260 3261
    FIXME("(%p) : setting p[%u] <= RGBA(%02x,%02x,%02x,%02x)\n", This, PaletteNumber,
          pEntries->peRed, pEntries->peGreen, pEntries->peBlue, pEntries->peFlags);
Raphael Junqueira's avatar
Raphael Junqueira committed
3262
    memcpy(This->palettes[PaletteNumber], pEntries, 256 * sizeof(PALETTEENTRY));
3263
    return D3D_OK;
3264
}
3265
HRESULT  WINAPI  IDirect3DDevice8Impl_GetPaletteEntries(LPDIRECT3DDEVICE8 iface, UINT PaletteNumber, PALETTEENTRY* pEntries) {
3266
    ICOM_THIS(IDirect3DDevice8Impl,iface);
Raphael Junqueira's avatar
Raphael Junqueira committed
3267
    memcpy(pEntries, This->palettes[PaletteNumber], 256 * sizeof(PALETTEENTRY));
3268 3269 3270
    FIXME("(%p) : returning p[%u] => RGBA(%02x,%02x,%02x,%02x)\n", This, PaletteNumber,
          pEntries->peRed, pEntries->peGreen, pEntries->peBlue, pEntries->peFlags);
    return D3D_OK;
3271 3272 3273
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetCurrentTexturePalette(LPDIRECT3DDEVICE8 iface, UINT PaletteNumber) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3274 3275
    FIXME("(%p) : Setting to (%u)\n", This, PaletteNumber);
    This->currentPalette = PaletteNumber;
3276

3277
#if defined(GL_EXT_paletted_texture)
3278
    if (GL_SUPPORT(EXT_PALETTED_TEXTURE)) {
3279 3280 3281

      ENTER_GL();

3282 3283 3284 3285 3286 3287
      GL_EXTCALL(glColorTableEXT)(GL_TEXTURE_2D,    /* target */
				  GL_RGBA,          /* internal format */
				  256,              /* table size */
				  GL_RGBA,          /* table format */
				  GL_UNSIGNED_BYTE, /* table type */
				  This->palettes[PaletteNumber]);
3288
      checkGLcall("glColorTableEXT");
3289 3290 3291

      LEAVE_GL();

3292 3293 3294
    } else {
      /* Delayed palette handling ... waiting for software emulation into preload code */
    }
3295 3296
#endif
    return D3D_OK;
3297 3298 3299
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetCurrentTexturePalette(LPDIRECT3DDEVICE8 iface, UINT *PaletteNumber) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3300 3301 3302
    *PaletteNumber = This->currentPalette;
    FIXME("(%p) : Returning (%u)\n", This, *PaletteNumber);
    return D3D_OK;
3303
}
3304
HRESULT  WINAPI  IDirect3DDevice8Impl_DrawPrimitive(LPDIRECT3DDEVICE8 iface, D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount) {
3305 3306

    ICOM_THIS(IDirect3DDevice8Impl,iface);
3307
    This->StateBlock->streamIsUP = FALSE;
3308

3309
    TRACE("(%p) : Type=(%d,%s), Start=%d, Count=%d\n", This, PrimitiveType, debug_d3dprimitivetype(PrimitiveType), StartVertex, PrimitiveCount);
3310
    drawPrimitive(iface, PrimitiveType, PrimitiveCount, StartVertex, -1, 0, NULL, 0);
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320

    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DrawIndexedPrimitive(LPDIRECT3DDEVICE8 iface, D3DPRIMITIVETYPE PrimitiveType,
                                                           UINT minIndex,UINT NumVertices,UINT startIndex,UINT primCount) {
    UINT idxStride = 2;
    IDirect3DIndexBuffer8      *pIB;
    D3DINDEXBUFFER_DESC         IdxBufDsc;

    ICOM_THIS(IDirect3DDevice8Impl,iface);
3321
    pIB = This->StateBlock->pIndexData;
3322
    This->StateBlock->streamIsUP = FALSE;
3323

3324 3325
    TRACE("(%p) : Type=(%d,%s), min=%d, CountV=%d, startIdx=%d, countP=%d \n", This, 
          PrimitiveType, debug_d3dprimitivetype(PrimitiveType),
3326 3327 3328 3329 3330 3331 3332 3333 3334
          minIndex, NumVertices, startIndex, primCount);

    IDirect3DIndexBuffer8Impl_GetDesc(pIB, &IdxBufDsc);
    if (IdxBufDsc.Format == D3DFMT_INDEX16) {
        idxStride = 2;
    } else {
        idxStride = 4;
    }

3335
    drawPrimitive(iface, PrimitiveType, primCount, This->StateBlock->baseVertexIndex, startIndex, idxStride, ((IDirect3DIndexBuffer8Impl *) pIB)->allocatedMemory,
3336
                   minIndex);
3337 3338 3339 3340 3341 3342

    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DrawPrimitiveUP(LPDIRECT3DDEVICE8 iface, D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

3343 3344
    TRACE("(%p) : Type=(%d,%s), pCount=%d, pVtxData=%p, Stride=%d\n", This, PrimitiveType, debug_d3dprimitivetype(PrimitiveType), 
          PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
3345

3346
    if (This->StateBlock->stream_source[0] != NULL) IDirect3DVertexBuffer8Impl_Release(This->StateBlock->stream_source[0]);
3347

3348 3349
    /* Note in the following, its not this type, but thats the purpose of streamIsUP */
    This->StateBlock->stream_source[0] = (IDirect3DVertexBuffer8 *)pVertexStreamZeroData; 
3350
    This->StateBlock->stream_stride[0] = VertexStreamZeroStride;
3351 3352
    This->StateBlock->streamIsUP = TRUE;
    drawPrimitive(iface, PrimitiveType, PrimitiveCount, 0, 0, 0, NULL, 0);
3353
    This->StateBlock->stream_stride[0] = 0;
3354
    This->StateBlock->stream_source[0] = NULL;
3355 3356 3357 3358 3359 3360 3361 3362 3363 3364

    /*stream zero settings set to null at end */
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DrawIndexedPrimitiveUP(LPDIRECT3DDEVICE8 iface, D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,
                                                             UINT NumVertexIndices,UINT PrimitiveCount,CONST void* pIndexData,
                                                             D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,
                                                             UINT VertexStreamZeroStride) {
    int idxStride;
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3365
    TRACE("(%p) : Type=(%d,%s), MinVtxIdx=%d, NumVIdx=%d, PCount=%d, pidxdata=%p, IdxFmt=%d, pVtxdata=%p, stride=%d\n", This, PrimitiveType, debug_d3dprimitivetype(PrimitiveType),
3366 3367
          MinVertexIndex, NumVertexIndices, PrimitiveCount, pIndexData,  IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);

3368
    if (This->StateBlock->stream_source[0] != NULL) IDirect3DVertexBuffer8Impl_Release(This->StateBlock->stream_source[0]);
3369 3370 3371 3372 3373 3374
    if (IndexDataFormat == D3DFMT_INDEX16) {
        idxStride = 2;
    } else {
        idxStride = 4;
    }

3375 3376 3377
    /* Note in the following, its not this type, but thats the purpose of streamIsUP */
    This->StateBlock->stream_source[0] = (IDirect3DVertexBuffer8 *)pVertexStreamZeroData;
    This->StateBlock->streamIsUP = TRUE;
3378
    This->StateBlock->stream_stride[0] = VertexStreamZeroStride;
3379
    drawPrimitive(iface, PrimitiveType, PrimitiveCount, This->StateBlock->baseVertexIndex, 0, idxStride, pIndexData, MinVertexIndex);
3380 3381

    /*stream zero settings set to null at end */
3382
    This->StateBlock->stream_source[0] = NULL;
3383
    This->StateBlock->stream_stride[0] = 0;
3384 3385 3386 3387 3388 3389 3390 3391
    IDirect3DDevice8Impl_SetIndices(iface, NULL, 0);

    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_ProcessVertices(LPDIRECT3DDEVICE8 iface, UINT SrcStartIndex,UINT DestIndex,UINT VertexCount,IDirect3DVertexBuffer8* pDestBuffer,DWORD Flags) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3392
HRESULT  WINAPI  IDirect3DDevice8Impl_CreateVertexShader(LPDIRECT3DDEVICE8 iface, CONST DWORD* pDeclaration, CONST DWORD* pFunction, DWORD* pHandle, DWORD Usage) {
3393
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3394 3395 3396
    IDirect3DVertexShaderImpl* object;
    IDirect3DVertexShaderDeclarationImpl* attached_decl;
    HRESULT res;
Raphael Junqueira's avatar
Raphael Junqueira committed
3397 3398
    UINT i;

3399
    TRACE_(d3d_shader)("(%p) : VertexShader not fully supported yet : Decl=%p, Func=%p, Usage=%lu\n", This, pDeclaration, pFunction, Usage);
Raphael Junqueira's avatar
Raphael Junqueira committed
3400 3401 3402
    if (NULL == pDeclaration || NULL == pHandle) { /* pFunction can be NULL see MSDN */
      return D3DERR_INVALIDCALL;
    }
3403 3404
    for (i = 1; NULL != VertexShaders[i] && i < sizeof(VertexShaders) / sizeof(IDirect3DVertexShaderImpl*); ++i) ;
    if (i >= sizeof(VertexShaders) / sizeof(IDirect3DVertexShaderImpl*)) {
Raphael Junqueira's avatar
Raphael Junqueira committed
3405 3406 3407
      return D3DERR_OUTOFVIDEOMEMORY;
    }

3408 3409 3410 3411 3412 3413 3414
    /** Create the Vertex Shader */
    res = IDirect3DDeviceImpl_CreateVertexShader(This, pFunction, Usage, &object);
    /** TODO: check FAILED(res) */

    /** Create and Bind the Vertex Shader Declaration */
    res = IDirect3DDeviceImpl_CreateVertexShaderDeclaration8(This, pDeclaration, &attached_decl);
    /** TODO: check FAILED(res) */
Raphael Junqueira's avatar
Raphael Junqueira committed
3415 3416

    VertexShaders[i] = object;
3417
    VertexShaderDeclarations[i] = attached_decl;
Raphael Junqueira's avatar
Raphael Junqueira committed
3418
    *pHandle = VS_HIGHESTFIXEDFXF + i;
3419
    TRACE("Finished creating vertex shader %lx\n", *pHandle);
Raphael Junqueira's avatar
Raphael Junqueira committed
3420 3421

    return D3D_OK;
3422 3423 3424 3425 3426 3427 3428
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetVertexShader(LPDIRECT3DDEVICE8 iface, DWORD Handle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    This->UpdateStateBlock->VertexShader = Handle;
    This->UpdateStateBlock->Changed.vertexShader = TRUE;
    This->UpdateStateBlock->Set.vertexShader = TRUE;
3429 3430
    
    if (Handle > VS_HIGHESTFIXEDFXF) { /* only valid with non FVF shaders */
3431
      TRACE_(d3d_shader)("(%p) : Created shader, Handle=%lx\n", This, Handle);
3432 3433 3434 3435 3436 3437 3438 3439 3440
      This->UpdateStateBlock->vertexShaderDecl = VERTEX_SHADER_DECL(Handle);
      This->UpdateStateBlock->Changed.vertexShaderDecl = TRUE;
      This->UpdateStateBlock->Set.vertexShaderDecl = TRUE;
    } else { /* use a fvf, so desactivate the vshader decl */
      TRACE("(%p) : FVF Shader, Handle=%lx\n", This, Handle);
      This->UpdateStateBlock->vertexShaderDecl = NULL;
      This->UpdateStateBlock->Changed.vertexShaderDecl = TRUE;
      This->UpdateStateBlock->Set.vertexShaderDecl = TRUE;
    }
3441 3442
    /* Handle recording of state blocks */
    if (This->isRecordingState) {
3443 3444
      TRACE("Recording... not performing anything\n");
      return D3D_OK;
3445
    }
3446 3447 3448 3449
    /**
     * TODO: merge HAL shaders context switching from prototype
     */
    return D3D_OK;
3450 3451 3452
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetVertexShader(LPDIRECT3DDEVICE8 iface, DWORD* pHandle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3453
    TRACE_(d3d_shader)("(%p) : GetVertexShader returning %ld\n", This, This->StateBlock->VertexShader);
3454
    *pHandle = This->StateBlock->VertexShader;
3455 3456 3457 3458 3459
    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_DeleteVertexShader(LPDIRECT3DDEVICE8 iface, DWORD Handle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3460 3461
    IDirect3DVertexShaderImpl* object; 
    IDirect3DVertexShaderDeclarationImpl* attached_decl;
Raphael Junqueira's avatar
Raphael Junqueira committed
3462 3463 3464 3465

    if (Handle <= VS_HIGHESTFIXEDFXF) { /* only delete user defined shaders */
      return D3DERR_INVALIDCALL;
    }
3466 3467 3468 3469

    /**
     * Delete Vertex Shader
     */
Raphael Junqueira's avatar
Raphael Junqueira committed
3470
    object = VertexShaders[Handle - VS_HIGHESTFIXEDFXF];
3471 3472 3473
    if (NULL == object) {
      return D3DERR_INVALIDCALL;
    }
3474
    TRACE_(d3d_shader)("(%p) : freing VertexShader %p\n", This, object);
Raphael Junqueira's avatar
Raphael Junqueira committed
3475
    /* TODO: check validity of object */
3476 3477
    if (NULL != object->function) HeapFree(GetProcessHeap(), 0, (void *)object->function);
    HeapFree(GetProcessHeap(), 0, (void *)object->data);
Raphael Junqueira's avatar
Raphael Junqueira committed
3478
    HeapFree(GetProcessHeap(), 0, (void *)object);
3479
    VertexShaders[Handle - VS_HIGHESTFIXEDFXF] = NULL;
3480 3481 3482 3483 3484 3485 3486 3487

    /**
     * Delete Vertex Shader Declaration
     */
    attached_decl = VertexShaderDeclarations[Handle - VS_HIGHESTFIXEDFXF];
    if (NULL == attached_decl) {
      return D3DERR_INVALIDCALL;
    } 
3488
    TRACE_(d3d_shader)("(%p) : freing VertexShaderDeclaration %p\n", This, attached_decl);
3489 3490 3491 3492 3493
    /* TODO: check validity of object */
    HeapFree(GetProcessHeap(), 0, (void *)attached_decl->pDeclaration8);
    HeapFree(GetProcessHeap(), 0, (void *)attached_decl);
    VertexShaderDeclarations[Handle - VS_HIGHESTFIXEDFXF] = NULL;

Raphael Junqueira's avatar
Raphael Junqueira committed
3494
    return D3D_OK;
3495
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3496 3497 3498 3499

HRESULT  WINAPI  IDirect3DDevice8Impl_SetVertexShaderConstant(LPDIRECT3DDEVICE8 iface, DWORD Register, CONST void* pConstantData, DWORD ConstantCount) {
  ICOM_THIS(IDirect3DDevice8Impl,iface);

3500
  if (Register + ConstantCount > D3D8_VSHADER_MAX_CONSTANTS) {
3501
    ERR_(d3d_shader)("(%p) : SetVertexShaderConstant C[%lu] invalid\n", This, Register);
Raphael Junqueira's avatar
Raphael Junqueira committed
3502 3503
    return D3DERR_INVALIDCALL;
  }
3504
  if (NULL == pConstantData) {
Raphael Junqueira's avatar
Raphael Junqueira committed
3505 3506
    return D3DERR_INVALIDCALL;
  }
3507 3508 3509
  if (ConstantCount > 1) {
    FLOAT* f = (FLOAT*)pConstantData;
    UINT i;
3510
    TRACE_(d3d_shader)("(%p) : SetVertexShaderConstant C[%lu..%lu]=\n", This, Register, Register + ConstantCount - 1);
3511
    for (i = 0; i < ConstantCount; ++i) {
3512
      TRACE_(d3d_shader)("{%f, %f, %f, %f}\n", f[0], f[1], f[2], f[3]);
3513 3514 3515
      f += 4;
    }
  } else { 
3516 3517
    FLOAT* f = (FLOAT*) pConstantData;
    TRACE_(d3d_shader)("(%p) : SetVertexShaderConstant, C[%lu]={%f, %f, %f, %f}\n", This, Register, f[0], f[1], f[2], f[3]);
3518
  }
3519 3520 3521
  This->UpdateStateBlock->Changed.vertexShaderConstant = TRUE;
  memcpy(&This->UpdateStateBlock->vertexShaderConstant[Register], pConstantData, ConstantCount * 4 * sizeof(FLOAT));
  return D3D_OK;
3522
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3523 3524 3525
HRESULT  WINAPI  IDirect3DDevice8Impl_GetVertexShaderConstant(LPDIRECT3DDEVICE8 iface, DWORD Register, void* pConstantData, DWORD ConstantCount) {
  ICOM_THIS(IDirect3DDevice8Impl,iface);

3526
  TRACE_(d3d_shader)("(%p) : C[%lu] count=%ld\n", This, Register, ConstantCount);
3527
  if (Register + ConstantCount > D3D8_VSHADER_MAX_CONSTANTS) {
Raphael Junqueira's avatar
Raphael Junqueira committed
3528 3529
    return D3DERR_INVALIDCALL;
  }
3530
  if (NULL == pConstantData) {
Raphael Junqueira's avatar
Raphael Junqueira committed
3531 3532
    return D3DERR_INVALIDCALL;
  }
3533 3534
  memcpy(pConstantData, &This->UpdateStateBlock->vertexShaderConstant[Register], ConstantCount * 4 * sizeof(FLOAT));
  return D3D_OK;
3535
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3536
HRESULT  WINAPI  IDirect3DDevice8Impl_GetVertexShaderDeclaration(LPDIRECT3DDEVICE8 iface, DWORD Handle, void* pData, DWORD* pSizeOfData) {
3537 3538 3539 3540 3541 3542 3543 3544
  /*ICOM_THIS(IDirect3DDevice8Impl,iface);*/
  IDirect3DVertexShaderDeclarationImpl* attached_decl;
  
  attached_decl = VERTEX_SHADER_DECL(Handle);
  if (NULL == attached_decl) {
    return D3DERR_INVALIDCALL;
  }
  return IDirect3DVertexShaderDeclarationImpl_GetDeclaration8(attached_decl, pData, (UINT*) pSizeOfData);
3545
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3546
HRESULT  WINAPI  IDirect3DDevice8Impl_GetVertexShaderFunction(LPDIRECT3DDEVICE8 iface, DWORD Handle, void* pData, DWORD* pSizeOfData) {
3547 3548 3549 3550 3551 3552 3553 3554
  /*ICOM_THIS(IDirect3DDevice8Impl,iface);*/
  IDirect3DVertexShaderImpl* object;
  
  object = VERTEX_SHADER(Handle);
  if (NULL == object) {
    return D3DERR_INVALIDCALL;
  }
  return IDirect3DVertexShaderImpl_GetFunction(object, pData, (UINT*) pSizeOfData);
3555 3556
}

3557
HRESULT  WINAPI  IDirect3DDevice8Impl_SetIndices(LPDIRECT3DDEVICE8 iface, IDirect3DIndexBuffer8* pIndexData, UINT BaseVertexIndex) {
3558
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3559 3560 3561
    IDirect3DIndexBuffer8 *oldIdxs;

    TRACE("(%p) : Setting to %p, base %d\n", This, pIndexData, BaseVertexIndex);
3562
    oldIdxs = This->StateBlock->pIndexData;
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575

    This->UpdateStateBlock->Changed.Indices = TRUE;
    This->UpdateStateBlock->Set.Indices = TRUE;
    This->UpdateStateBlock->pIndexData = pIndexData;
    This->UpdateStateBlock->baseVertexIndex = BaseVertexIndex;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

    if (oldIdxs) IDirect3DIndexBuffer8Impl_Release(oldIdxs);
3576
    if (pIndexData) IDirect3DIndexBuffer8Impl_AddRef(This->StateBlock->pIndexData);
3577 3578 3579 3580 3581 3582
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetIndices(LPDIRECT3DDEVICE8 iface, IDirect3DIndexBuffer8** ppIndexData,UINT* pBaseVertexIndex) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);

3583
    *ppIndexData = This->StateBlock->pIndexData;
3584 3585
    /* up ref count on ppindexdata */
    if (*ppIndexData) IDirect3DIndexBuffer8Impl_AddRef(*ppIndexData);
3586
    *pBaseVertexIndex = This->StateBlock->baseVertexIndex;
3587 3588 3589

    return D3D_OK;
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3590
HRESULT  WINAPI  IDirect3DDevice8Impl_CreatePixelShader(LPDIRECT3DDEVICE8 iface, CONST DWORD* pFunction, DWORD* pHandle) {
3591
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3592
    IDirect3DPixelShaderImpl* object;
3593
    HRESULT res;
Raphael Junqueira's avatar
Raphael Junqueira committed
3594 3595
    UINT i;

3596
    TRACE_(d3d_shader)("(%p) : PixelShader not fully supported yet : Func=%p\n", This, pFunction);
Raphael Junqueira's avatar
Raphael Junqueira committed
3597 3598 3599
    if (NULL == pFunction || NULL == pHandle) {
      return D3DERR_INVALIDCALL;
    }
3600 3601
    for (i = 1; NULL != PixelShaders[i] && i < sizeof(PixelShaders) / sizeof(IDirect3DPixelShaderImpl*); ++i) ;
    if (i >= sizeof(PixelShaders) / sizeof(IDirect3DPixelShaderImpl*)) {
Raphael Junqueira's avatar
Raphael Junqueira committed
3602 3603 3604
      return D3DERR_OUTOFVIDEOMEMORY;
    }

3605 3606 3607 3608 3609 3610 3611 3612 3613
    /** Create the Pixel Shader */
    res = IDirect3DDeviceImpl_CreatePixelShader(This, pFunction, &object);
    if (SUCCEEDED(res)) {
      PixelShaders[i] = object;
      *pHandle = VS_HIGHESTFIXEDFXF + i;
      return D3D_OK;
    } 
    *pHandle = 0xFFFFFFFF;
    return res;
3614 3615 3616 3617 3618 3619 3620 3621 3622 3623
}
HRESULT  WINAPI  IDirect3DDevice8Impl_SetPixelShader(LPDIRECT3DDEVICE8 iface, DWORD Handle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);

    This->UpdateStateBlock->PixelShader = Handle;
    This->UpdateStateBlock->Changed.pixelShader = TRUE;
    This->UpdateStateBlock->Set.pixelShader = TRUE;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
3624
        TRACE_(d3d_shader)("Recording... not performing anything\n");
3625 3626 3627
        return D3D_OK;
    }

3628 3629
    /* FIXME: Quieten when not being used */
    if (Handle != 0) {
3630
      FIXME_(d3d_shader)("(%p) : stub %ld\n", This, Handle);
3631
    } else {
3632
      TRACE_(d3d_shader)("(%p) : stub %ld\n", This, Handle);
3633
    }
3634 3635 3636 3637 3638

    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetPixelShader(LPDIRECT3DDEVICE8 iface, DWORD* pHandle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3639
    TRACE_(d3d_shader)("(%p) : GetPixelShader returning %ld\n", This, This->StateBlock->PixelShader);
3640
    *pHandle = This->StateBlock->PixelShader;
3641 3642 3643 3644 3645
    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_DeletePixelShader(LPDIRECT3DDEVICE8 iface, DWORD Handle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3646
    IDirect3DPixelShaderImpl* object;   
Raphael Junqueira's avatar
Raphael Junqueira committed
3647 3648 3649 3650 3651

    if (Handle <= VS_HIGHESTFIXEDFXF) { /* only delete user defined shaders */
      return D3DERR_INVALIDCALL;
    }
    object = PixelShaders[Handle - VS_HIGHESTFIXEDFXF];
3652
    TRACE_(d3d_shader)("(%p) : freeing PixelShader %p\n", This, object);
Raphael Junqueira's avatar
Raphael Junqueira committed
3653
    /* TODO: check validity of object before free */
3654 3655
    if (NULL != object->function) HeapFree(GetProcessHeap(), 0, (void *)object->function);
    HeapFree(GetProcessHeap(), 0, (void *)object->data);
Raphael Junqueira's avatar
Raphael Junqueira committed
3656
    HeapFree(GetProcessHeap(), 0, (void *)object);
3657 3658
    PixelShaders[Handle - VS_HIGHESTFIXEDFXF] = NULL;

Raphael Junqueira's avatar
Raphael Junqueira committed
3659
    return D3D_OK;
3660
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3661

3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
HRESULT  WINAPI  IDirect3DDevice8Impl_SetPixelShaderConstant(LPDIRECT3DDEVICE8 iface, DWORD Register, CONST void* pConstantData, DWORD ConstantCount) {
  ICOM_THIS(IDirect3DDevice8Impl,iface);

  if (Register + ConstantCount > D3D8_PSHADER_MAX_CONSTANTS) {
    ERR_(d3d_shader)("(%p) : SetPixelShaderConstant C[%lu] invalid\n", This, Register);
    return D3DERR_INVALIDCALL;
  }
  if (NULL == pConstantData) {
    return D3DERR_INVALIDCALL;
  }
  if (ConstantCount > 1) {
    FLOAT* f = (FLOAT*)pConstantData;
    UINT i;
    TRACE_(d3d_shader)("(%p) : SetPixelShaderConstant C[%lu..%lu]=\n", This, Register, Register + ConstantCount - 1);
    for (i = 0; i < ConstantCount; ++i) {
      TRACE_(d3d_shader)("{%f, %f, %f, %f}\n", f[0], f[1], f[2], f[3]);
      f += 4;
    }
  } else { 
    FLOAT* f = (FLOAT*) pConstantData;
    TRACE_(d3d_shader)("(%p) : SetPixelShaderConstant, C[%lu]={%f, %f, %f, %f}\n", This, Register, f[0], f[1], f[2], f[3]);
  }
  This->UpdateStateBlock->Changed.pixelShaderConstant = TRUE;
  memcpy(&This->UpdateStateBlock->pixelShaderConstant[Register], pConstantData, ConstantCount * 4 * sizeof(FLOAT));
  return D3D_OK;
3687
}
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699
HRESULT  WINAPI  IDirect3DDevice8Impl_GetPixelShaderConstant(LPDIRECT3DDEVICE8 iface, DWORD Register, void* pConstantData, DWORD ConstantCount) {
  ICOM_THIS(IDirect3DDevice8Impl,iface);

  TRACE_(d3d_shader)("(%p) : C[%lu] count=%ld\n", This, Register, ConstantCount);
  if (Register + ConstantCount > D3D8_PSHADER_MAX_CONSTANTS) {
    return D3DERR_INVALIDCALL;
  }
  if (NULL == pConstantData) {
    return D3DERR_INVALIDCALL;
  }
  memcpy(pConstantData, &This->UpdateStateBlock->pixelShaderConstant[Register], ConstantCount * 4 * sizeof(FLOAT));
  return D3D_OK;
3700
}
Raphael Junqueira's avatar
Raphael Junqueira committed
3701
HRESULT  WINAPI  IDirect3DDevice8Impl_GetPixelShaderFunction(LPDIRECT3DDEVICE8 iface, DWORD Handle, void* pData, DWORD* pSizeOfData) {
3702
    IDirect3DPixelShaderImpl* object;
Raphael Junqueira's avatar
Raphael Junqueira committed
3703 3704 3705 3706

    object = PIXEL_SHADER(Handle);
    if (NULL == object) {
      return D3DERR_INVALIDCALL;
3707 3708
    } 
    return IDirect3DPixelShaderImpl_GetFunction(object, pData, (UINT*) pSizeOfData);
3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DrawRectPatch(LPDIRECT3DDEVICE8 iface, UINT Handle,CONST float* pNumSegs,CONST D3DRECTPATCH_INFO* pRectPatchInfo) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DrawTriPatch(LPDIRECT3DDEVICE8 iface, UINT Handle,CONST float* pNumSegs,CONST D3DTRIPATCH_INFO* pTriPatchInfo) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_DeletePatch(LPDIRECT3DDEVICE8 iface, UINT Handle) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
    FIXME("(%p) : stub\n", This);    return D3D_OK;
}

HRESULT  WINAPI  IDirect3DDevice8Impl_SetStreamSource(LPDIRECT3DDEVICE8 iface, UINT StreamNumber,IDirect3DVertexBuffer8* pStreamData,UINT Stride) {
    IDirect3DVertexBuffer8 *oldSrc;
    ICOM_THIS(IDirect3DDevice8Impl,iface);

3727
    oldSrc = This->StateBlock->stream_source[StreamNumber];
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
    TRACE("(%p) : StreamNo: %d, OldStream (%p), NewStream (%p), NewStride %d\n", This, StreamNumber, oldSrc, pStreamData, Stride);

    This->UpdateStateBlock->Changed.stream_source[StreamNumber] = TRUE;
    This->UpdateStateBlock->Set.stream_source[StreamNumber] = TRUE;
    This->UpdateStateBlock->stream_stride[StreamNumber] = Stride;
    This->UpdateStateBlock->stream_source[StreamNumber] = pStreamData;

    /* Handle recording of state blocks */
    if (This->isRecordingState) {
        TRACE("Recording... not performing anything\n");
        return D3D_OK;
    }

    if (oldSrc != NULL) IDirect3DVertexBuffer8Impl_Release(oldSrc);
    if (pStreamData != NULL) IDirect3DVertexBuffer8Impl_AddRef(pStreamData);
    return D3D_OK;
}
HRESULT  WINAPI  IDirect3DDevice8Impl_GetStreamSource(LPDIRECT3DDEVICE8 iface, UINT StreamNumber,IDirect3DVertexBuffer8** pStream,UINT* pStride) {
    ICOM_THIS(IDirect3DDevice8Impl,iface);
3747 3748 3749
    TRACE("(%p) : StreamNo: %d, Stream (%p), Stride %d\n", This, StreamNumber, This->StateBlock->stream_source[StreamNumber], This->StateBlock->stream_stride[StreamNumber]);
    *pStream = This->StateBlock->stream_source[StreamNumber];
    *pStride = This->StateBlock->stream_stride[StreamNumber];
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855
    IDirect3DVertexBuffer8Impl_AddRef((LPDIRECT3DVERTEXBUFFER8) *pStream);
    return D3D_OK;
}


ICOM_VTABLE(IDirect3DDevice8) Direct3DDevice8_Vtbl =
{
    ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
    IDirect3DDevice8Impl_QueryInterface,
    IDirect3DDevice8Impl_AddRef,
    IDirect3DDevice8Impl_Release,
    IDirect3DDevice8Impl_TestCooperativeLevel,
    IDirect3DDevice8Impl_GetAvailableTextureMem,
    IDirect3DDevice8Impl_ResourceManagerDiscardBytes,
    IDirect3DDevice8Impl_GetDirect3D,
    IDirect3DDevice8Impl_GetDeviceCaps,
    IDirect3DDevice8Impl_GetDisplayMode,
    IDirect3DDevice8Impl_GetCreationParameters,
    IDirect3DDevice8Impl_SetCursorProperties,
    IDirect3DDevice8Impl_SetCursorPosition,
    IDirect3DDevice8Impl_ShowCursor,
    IDirect3DDevice8Impl_CreateAdditionalSwapChain,
    IDirect3DDevice8Impl_Reset,
    IDirect3DDevice8Impl_Present,
    IDirect3DDevice8Impl_GetBackBuffer,
    IDirect3DDevice8Impl_GetRasterStatus,
    IDirect3DDevice8Impl_SetGammaRamp,
    IDirect3DDevice8Impl_GetGammaRamp,
    IDirect3DDevice8Impl_CreateTexture,
    IDirect3DDevice8Impl_CreateVolumeTexture,
    IDirect3DDevice8Impl_CreateCubeTexture,
    IDirect3DDevice8Impl_CreateVertexBuffer,
    IDirect3DDevice8Impl_CreateIndexBuffer,
    IDirect3DDevice8Impl_CreateRenderTarget,
    IDirect3DDevice8Impl_CreateDepthStencilSurface,
    IDirect3DDevice8Impl_CreateImageSurface,
    IDirect3DDevice8Impl_CopyRects,
    IDirect3DDevice8Impl_UpdateTexture,
    IDirect3DDevice8Impl_GetFrontBuffer,
    IDirect3DDevice8Impl_SetRenderTarget,
    IDirect3DDevice8Impl_GetRenderTarget,
    IDirect3DDevice8Impl_GetDepthStencilSurface,
    IDirect3DDevice8Impl_BeginScene,
    IDirect3DDevice8Impl_EndScene,
    IDirect3DDevice8Impl_Clear,
    IDirect3DDevice8Impl_SetTransform,
    IDirect3DDevice8Impl_GetTransform,
    IDirect3DDevice8Impl_MultiplyTransform,
    IDirect3DDevice8Impl_SetViewport,
    IDirect3DDevice8Impl_GetViewport,
    IDirect3DDevice8Impl_SetMaterial,
    IDirect3DDevice8Impl_GetMaterial,
    IDirect3DDevice8Impl_SetLight,
    IDirect3DDevice8Impl_GetLight,
    IDirect3DDevice8Impl_LightEnable,
    IDirect3DDevice8Impl_GetLightEnable,
    IDirect3DDevice8Impl_SetClipPlane,
    IDirect3DDevice8Impl_GetClipPlane,
    IDirect3DDevice8Impl_SetRenderState,
    IDirect3DDevice8Impl_GetRenderState,
    IDirect3DDevice8Impl_BeginStateBlock,
    IDirect3DDevice8Impl_EndStateBlock,
    IDirect3DDevice8Impl_ApplyStateBlock,
    IDirect3DDevice8Impl_CaptureStateBlock,
    IDirect3DDevice8Impl_DeleteStateBlock,
    IDirect3DDevice8Impl_CreateStateBlock,
    IDirect3DDevice8Impl_SetClipStatus,
    IDirect3DDevice8Impl_GetClipStatus,
    IDirect3DDevice8Impl_GetTexture,
    IDirect3DDevice8Impl_SetTexture,
    IDirect3DDevice8Impl_GetTextureStageState,
    IDirect3DDevice8Impl_SetTextureStageState,
    IDirect3DDevice8Impl_ValidateDevice,
    IDirect3DDevice8Impl_GetInfo,
    IDirect3DDevice8Impl_SetPaletteEntries,
    IDirect3DDevice8Impl_GetPaletteEntries,
    IDirect3DDevice8Impl_SetCurrentTexturePalette,
    IDirect3DDevice8Impl_GetCurrentTexturePalette,
    IDirect3DDevice8Impl_DrawPrimitive,
    IDirect3DDevice8Impl_DrawIndexedPrimitive,
    IDirect3DDevice8Impl_DrawPrimitiveUP,
    IDirect3DDevice8Impl_DrawIndexedPrimitiveUP,
    IDirect3DDevice8Impl_ProcessVertices,
    IDirect3DDevice8Impl_CreateVertexShader,
    IDirect3DDevice8Impl_SetVertexShader,
    IDirect3DDevice8Impl_GetVertexShader,
    IDirect3DDevice8Impl_DeleteVertexShader,
    IDirect3DDevice8Impl_SetVertexShaderConstant,
    IDirect3DDevice8Impl_GetVertexShaderConstant,
    IDirect3DDevice8Impl_GetVertexShaderDeclaration,
    IDirect3DDevice8Impl_GetVertexShaderFunction,
    IDirect3DDevice8Impl_SetStreamSource,
    IDirect3DDevice8Impl_GetStreamSource,
    IDirect3DDevice8Impl_SetIndices,
    IDirect3DDevice8Impl_GetIndices,
    IDirect3DDevice8Impl_CreatePixelShader,
    IDirect3DDevice8Impl_SetPixelShader,
    IDirect3DDevice8Impl_GetPixelShader,
    IDirect3DDevice8Impl_DeletePixelShader,
    IDirect3DDevice8Impl_SetPixelShaderConstant,
    IDirect3DDevice8Impl_GetPixelShaderConstant,
    IDirect3DDevice8Impl_GetPixelShaderFunction,
    IDirect3DDevice8Impl_DrawRectPatch,
    IDirect3DDevice8Impl_DrawTriPatch,
    IDirect3DDevice8Impl_DeletePatch
};
3856

Alexandre Julliard's avatar
Alexandre Julliard committed
3857 3858
HRESULT WINAPI IDirect3DDevice8Impl_CleanRender(LPDIRECT3DDEVICE8 iface)
{
3859
#if defined(GL_VERSION_1_3) /* @see comments on ActiveRender */
Alexandre Julliard's avatar
Alexandre Julliard committed
3860
  ICOM_THIS(IDirect3DDevice8Impl,iface);
3861 3862 3863

  ENTER_GL();

3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
#if 0
  if (This->glCtx != This->render_ctx) {
    glXDestroyContext(This->display, This->render_ctx);
    This->render_ctx = This->glCtx;
  }
#endif
  if (This->win != This->drawable) {
    glXDestroyPbuffer(This->display, This->drawable);
    This->drawable = This->win;
  }
3874 3875 3876

  LEAVE_GL();

3877 3878 3879 3880 3881 3882 3883 3884
#endif
  return D3D_OK;
}

HRESULT WINAPI IDirect3DDevice8Impl_ActiveRender(LPDIRECT3DDEVICE8 iface,
						IDirect3DSurface8* RenderSurface, 
						IDirect3DSurface8* StencilSurface) {

3885
  HRESULT ret =  D3DERR_INVALIDCALL; 
3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
  /**
   * Currently only active for GLX >= 1.3
   * for others versions we'll have to use GLXPixmaps
   *
   * normally we must test GLX_VERSION_1_3 but nvidia headers are not correct
   * as they implements GLX 1.3 but only define GLX_VERSION_1_2
   * so only check OpenGL version
   */
#if defined(GL_VERSION_1_3) 
  GLXFBConfig* cfgs = NULL;
  int nCfgs = 0;
  int attribs[256];
  int nAttribs = 0;
  D3DFORMAT BackBufferFormat = ((IDirect3DSurface8Impl*) RenderSurface)->myDesc.Format;
Raphael Junqueira's avatar
Raphael Junqueira committed
3900
  D3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IDirect3DSurface8Impl*) StencilSurface)->myDesc.Format : 0;
3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997
  UINT Width = ((IDirect3DSurface8Impl*) RenderSurface)->myDesc.Width;
  UINT Height = ((IDirect3DSurface8Impl*) RenderSurface)->myDesc.Height;
  IDirect3DSurface8Impl* tmp;

  ICOM_THIS(IDirect3DDevice8Impl,iface);
 
#define PUSH1(att)        attribs[nAttribs++] = (att); 
#define PUSH2(att,value)  attribs[nAttribs++] = (att); attribs[nAttribs++] = (value);

  PUSH2(GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT | GLX_WINDOW | GLX_PBUFFER_BIT);
  PUSH2(GLX_X_RENDERABLE,  TRUE);
  PUSH2(GLX_DOUBLEBUFFER, TRUE);
  
  switch (BackBufferFormat) {
    /* color buffer */
  case D3DFMT_P8:
    PUSH2(GLX_RENDER_TYPE,  GLX_COLOR_INDEX_BIT);
    PUSH2(GLX_BUFFER_SIZE,  8);
    PUSH2(GLX_DOUBLEBUFFER, TRUE);
    break;
    
  case D3DFMT_R3G3B2:
    PUSH2(GLX_RENDER_TYPE,  GLX_RGBA_BIT);
    PUSH2(GLX_RED_SIZE,     3);
    PUSH2(GLX_GREEN_SIZE,   3);
    PUSH2(GLX_BLUE_SIZE,    2);
    break;
    
  case D3DFMT_A1R5G5B5:
    PUSH2(GLX_ALPHA_SIZE,   1);
  case D3DFMT_X1R5G5B5:
    PUSH2(GLX_RED_SIZE,     5);
    PUSH2(GLX_GREEN_SIZE,   5);
    PUSH2(GLX_BLUE_SIZE,    5);
    break;
    
  case D3DFMT_R5G6B5:
    PUSH2(GLX_RED_SIZE,     5);
    PUSH2(GLX_GREEN_SIZE,   6);
    PUSH2(GLX_BLUE_SIZE,    5);
    break;
    
  case D3DFMT_A4R4G4B4:
    PUSH2(GLX_ALPHA_SIZE,   4);
  case D3DFMT_X4R4G4B4:
    PUSH2(GLX_RED_SIZE,     4);
    PUSH2(GLX_GREEN_SIZE,   4);
    PUSH2(GLX_BLUE_SIZE,    4);
    break;
    
  case D3DFMT_A8R8G8B8:
    PUSH2(GLX_ALPHA_SIZE,   8);
  case D3DFMT_R8G8B8:
  case D3DFMT_X8R8G8B8:
    PUSH2(GLX_RED_SIZE,     8);
    PUSH2(GLX_GREEN_SIZE,   8);
    PUSH2(GLX_BLUE_SIZE,    8);
    break;

  default:
    break;
  }
   
  switch (StencilBufferFormat) { 
  case D3DFMT_D16_LOCKABLE:
  case D3DFMT_D16:
    PUSH2(GLX_DEPTH_SIZE,   16);
    break;
    
  case D3DFMT_D15S1:
    PUSH2(GLX_DEPTH_SIZE,   15);
    break;
    
  case D3DFMT_D24X8:
    PUSH2(GLX_DEPTH_SIZE,   24);
    break;
    
  case D3DFMT_D24X4S4:
    PUSH2(GLX_DEPTH_SIZE,   24);
    PUSH2(GLX_STENCIL_SIZE, 4);
    break;
    
  case D3DFMT_D24S8:
    PUSH2(GLX_DEPTH_SIZE,   24);
    PUSH2(GLX_STENCIL_SIZE, 8);
    break;
    
  case D3DFMT_D32:
    PUSH2(GLX_DEPTH_SIZE,   32);
    break;

  default:
    break;
  }

  PUSH1(None);
  
3998 3999
  ENTER_GL();

4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
  cfgs = glXChooseFBConfig(This->display, DefaultScreen(This->display), attribs, &nCfgs);
  if (NULL != cfgs) {
#if 0
    int i;
    for (i = 0; i < nCfgs; ++i) {
      TRACE("for (%u,%s)/(%u,%s) found config[%d]@%p\n", BackBufferFormat, debug_d3dformat(BackBufferFormat), StencilBufferFormat, debug_d3dformat(StencilBufferFormat), i, cfgs[i]);
    }
#endif

    if (NULL != This->renderTarget) {
      GLenum prev_read;      
      glFlush();
      vcheckGLcall("glFlush");

#if 0
      /** very very usefull debug code */
      glXSwapBuffers(This->display, This->drawable);   
      printf("Hit Enter to get next frame ...\n");
      getchar();
#endif

      glGetIntegerv(GL_READ_BUFFER, &prev_read);
      vcheckGLcall("glIntegerv");
      glReadBuffer(GL_BACK);
      vcheckGLcall("glReadBuffer");
      {
	long j;
Raphael Junqueira's avatar
Raphael Junqueira committed
4027
	long pitch = This->renderTarget->myDesc.Width * This->renderTarget->bytesPerPixel;
4028 4029 4030 4031 4032
	for (j = 0; j < This->renderTarget->myDesc.Height; ++j) {
	  glReadPixels(0, 
		       This->renderTarget->myDesc.Height - j - 1, 
		       This->renderTarget->myDesc.Width, 
		       1,
Raphael Junqueira's avatar
Raphael Junqueira committed
4033 4034 4035
		       D3DFmt2GLFmt(This, This->renderTarget->myDesc.Format), 
		       D3DFmt2GLType(This, This->renderTarget->myDesc.Format), 
		       This->renderTarget->allocatedMemory + j * pitch);
4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
	  vcheckGLcall("glReadPixels");
	}
      }      
      glReadBuffer(prev_read);
      vcheckGLcall("glReadBuffer");
    }

    if (BackBufferFormat != This->renderTarget->myDesc.Format && 
	StencilBufferFormat != This->stencilBufferTarget->myDesc.Format) {
      nAttribs = 0;
      PUSH2(GLX_PBUFFER_WIDTH,  Width);
      PUSH2(GLX_PBUFFER_HEIGHT, Height);
      PUSH1(None);
      This->drawable = glXCreatePbuffer(This->display, cfgs[0], attribs);
            
      This->render_ctx = glXCreateNewContext(This->display, cfgs[0], GLX_RGBA_TYPE, This->glCtx, TRUE);
      if (NULL == This->render_ctx) {
	ERR("cannot create glxContext\n"); 
      }

      glFlush();
      glXSwapBuffers(This->display, This->drawable);
      if (glXMakeContextCurrent(This->display, This->drawable, This->drawable, This->render_ctx) == False) {
	TRACE("Error in setting current context: context %p drawable %ld (default %ld)!\n", This->glCtx, This->drawable, This->win);
      }
      checkGLcall("glXMakeContextCurrent");
    }

    tmp = This->renderTarget;
    This->renderTarget = (IDirect3DSurface8Impl*) RenderSurface;
    IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) This->renderTarget);
    IDirect3DSurface8Impl_Release((LPDIRECT3DSURFACE8) tmp);

    tmp = This->stencilBufferTarget;
    This->stencilBufferTarget = (IDirect3DSurface8Impl*) StencilSurface;
Raphael Junqueira's avatar
Raphael Junqueira committed
4071 4072
    if (NULL != This->stencilBufferTarget) IDirect3DSurface8Impl_AddRef((LPDIRECT3DSURFACE8) This->stencilBufferTarget);
    if (NULL != tmp) IDirect3DSurface8Impl_Release((LPDIRECT3DSURFACE8) tmp);
4073

4074
    ret = D3D_OK;
4075 4076 4077 4078 4079 4080 4081 4082

  } else {
    ERR("cannot get valides GLXFBConfig for (%u,%s)/(%u,%s)\n", BackBufferFormat, debug_d3dformat(BackBufferFormat), StencilBufferFormat, debug_d3dformat(StencilBufferFormat));
  }

#undef PUSH1
#undef PUSH2

4083 4084
  LEAVE_GL();

4085 4086
#endif

4087
  return ret;
4088
}