wined3d: Rename resource functions to reflect that they're not COM functions.
[wine] / dlls / wined3d / wined3d_private.h
1 /*
2  * Direct3D wine internal private include file
3  *
4  * Copyright 2002-2003 The wine-d3d team
5  * Copyright 2002-2003 Raphael Junqueira
6  * Copyright 2004 Jason Edmeades
7  * Copyright 2005 Oliver Stieber
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #ifndef __WINE_WINED3D_PRIVATE_H
25 #define __WINE_WINED3D_PRIVATE_H
26
27 #include <stdarg.h>
28 #include <math.h>
29 #define NONAMELESSUNION
30 #define NONAMELESSSTRUCT
31 #define COBJMACROS
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winreg.h"
35 #include "wingdi.h"
36 #include "winuser.h"
37 #include "wine/debug.h"
38 #include "wine/unicode.h"
39
40 #include "objbase.h"
41 #include "wined3d_private_types.h"
42 #include "wine/wined3d.h"
43 #include "wined3d_gl.h"
44 #include "wine/list.h"
45
46 /* Hash table functions */
47 typedef unsigned int (hash_function_t)(const void *key);
48 typedef BOOL (compare_function_t)(const void *keya, const void *keyb);
49
50 struct hash_table_entry_t {
51     void *key;
52     void *value;
53     unsigned int hash;
54     struct list entry;
55 };
56
57 struct hash_table_t {
58     hash_function_t *hash_function;
59     compare_function_t *compare_function;
60     struct list *buckets;
61     unsigned int bucket_count;
62     struct hash_table_entry_t *entries;
63     unsigned int entry_count;
64     struct list free_entries;
65     unsigned int count;
66     unsigned int grow_size;
67     unsigned int shrink_size;
68 };
69
70 struct hash_table_t *hash_table_create(hash_function_t *hash_function, compare_function_t *compare_function);
71 void hash_table_destroy(struct hash_table_t *table, void (*free_value)(void *value, void *cb), void *cb);
72 void *hash_table_get(const struct hash_table_t *table, const void *key);
73 void hash_table_put(struct hash_table_t *table, void *key, void *value);
74 void hash_table_remove(struct hash_table_t *table, void *key);
75
76 /* Device caps */
77 #define MAX_PALETTES            65536
78 #define MAX_STREAMS             16
79 #define MAX_TEXTURES            8
80 #define MAX_FRAGMENT_SAMPLERS   16
81 #define MAX_VERTEX_SAMPLERS     4
82 #define MAX_COMBINED_SAMPLERS   (MAX_FRAGMENT_SAMPLERS + MAX_VERTEX_SAMPLERS)
83 #define MAX_ACTIVE_LIGHTS       8
84 #define MAX_CLIPPLANES          WINED3DMAXUSERCLIPPLANES
85 #define MAX_LEVELS              256
86
87 #define MAX_CONST_I 16
88 #define MAX_CONST_B 16
89
90 /* Used for CreateStateBlock */
91 #define NUM_SAVEDPIXELSTATES_R     35
92 #define NUM_SAVEDPIXELSTATES_T     18
93 #define NUM_SAVEDPIXELSTATES_S     12
94 #define NUM_SAVEDVERTEXSTATES_R    34
95 #define NUM_SAVEDVERTEXSTATES_T    2
96 #define NUM_SAVEDVERTEXSTATES_S    1
97
98 extern const DWORD SavedPixelStates_R[NUM_SAVEDPIXELSTATES_R];
99 extern const DWORD SavedPixelStates_T[NUM_SAVEDPIXELSTATES_T];
100 extern const DWORD SavedPixelStates_S[NUM_SAVEDPIXELSTATES_S];
101 extern const DWORD SavedVertexStates_R[NUM_SAVEDVERTEXSTATES_R];
102 extern const DWORD SavedVertexStates_T[NUM_SAVEDVERTEXSTATES_T];
103 extern const DWORD SavedVertexStates_S[NUM_SAVEDVERTEXSTATES_S];
104
105 typedef enum _WINELOOKUP {
106     WINELOOKUP_WARPPARAM = 0,
107     MAX_LOOKUPS          = 1
108 } WINELOOKUP;
109
110 extern const int minLookup[MAX_LOOKUPS];
111 extern const int maxLookup[MAX_LOOKUPS];
112 extern DWORD *stateLookup[MAX_LOOKUPS];
113
114 struct min_lookup
115 {
116     GLenum mip[WINED3DTEXF_LINEAR + 1];
117 };
118
119 struct min_lookup minMipLookup[WINED3DTEXF_ANISOTROPIC + 1];
120 const struct min_lookup minMipLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1];
121 GLenum magLookup[WINED3DTEXF_ANISOTROPIC + 1];
122 const GLenum magLookup_noFilter[WINED3DTEXF_ANISOTROPIC + 1];
123
124 extern const struct filter_lookup filter_lookup_nofilter;
125 extern struct filter_lookup filter_lookup;
126
127 void init_type_lookup(WineD3D_GL_Info *gl_info);
128 #define WINED3D_ATR_TYPE(type)          GLINFO_LOCATION.glTypeLookup[type].d3dType
129 #define WINED3D_ATR_SIZE(type)          GLINFO_LOCATION.glTypeLookup[type].size
130 #define WINED3D_ATR_GLTYPE(type)        GLINFO_LOCATION.glTypeLookup[type].glType
131 #define WINED3D_ATR_NORMALIZED(type)    GLINFO_LOCATION.glTypeLookup[type].normalized
132 #define WINED3D_ATR_TYPESIZE(type)      GLINFO_LOCATION.glTypeLookup[type].typesize
133
134 /* float_16_to_32() and float_32_to_16() (see implementation in
135  * surface_base.c) convert 16 bit floats in the FLOAT16 data type
136  * to standard C floats and vice versa. They do not depend on the encoding
137  * of the C float, so they are platform independent, but slow. On x86 and
138  * other IEEE 754 compliant platforms the conversion can be accelerated by
139  * bit shifting the exponent and mantissa. There are also some SSE-based
140  * assembly routines out there.
141  *
142  * See GL_NV_half_float for a reference of the FLOAT16 / GL_HALF format
143  */
144 static inline float float_16_to_32(const unsigned short *in) {
145     const unsigned short s = ((*in) & 0x8000);
146     const unsigned short e = ((*in) & 0x7C00) >> 10;
147     const unsigned short m = (*in) & 0x3FF;
148     const float sgn = (s ? -1.0 : 1.0);
149
150     if(e == 0) {
151         if(m == 0) return sgn * 0.0; /* +0.0 or -0.0 */
152         else return sgn * pow(2, -14.0) * ( (float) m / 1024.0);
153     } else if(e < 31) {
154         return sgn * pow(2, (float) e-15.0) * (1.0 + ((float) m / 1024.0));
155     } else {
156         if(m == 0) return sgn / 0.0; /* +INF / -INF */
157         else return 0.0 / 0.0; /* NAN */
158     }
159 }
160
161 /**
162  * Settings 
163  */
164 #define VS_NONE    0
165 #define VS_HW      1
166
167 #define PS_NONE    0
168 #define PS_HW      1
169
170 #define VBO_NONE   0
171 #define VBO_HW     1
172
173 #define NP2_NONE   0
174 #define NP2_REPACK 1
175 #define NP2_NATIVE 2
176
177 #define ORM_BACKBUFFER  0
178 #define ORM_PBUFFER     1
179 #define ORM_FBO         2
180
181 #define SHADER_ARB  1
182 #define SHADER_GLSL 2
183 #define SHADER_ATI  3
184 #define SHADER_NONE 4
185
186 #define RTL_DISABLE   -1
187 #define RTL_AUTO       0
188 #define RTL_READDRAW   1
189 #define RTL_READTEX    2
190 #define RTL_TEXDRAW    3
191 #define RTL_TEXTEX     4
192
193 #define PCI_VENDOR_NONE 0xffff /* e.g. 0x8086 for Intel and 0x10de for Nvidia */
194 #define PCI_DEVICE_NONE 0xffff /* e.g. 0x14f for a Geforce6200 */
195
196 /* NOTE: When adding fields to this structure, make sure to update the default
197  * values in wined3d_main.c as well. */
198 typedef struct wined3d_settings_s {
199 /* vertex and pixel shader modes */
200   int vs_mode;
201   int ps_mode;
202   int vbo_mode;
203 /* Ideally, we don't want the user to have to request GLSL.  If the hardware supports GLSL,
204     we should use it.  However, until it's fully implemented, we'll leave it as a registry
205     setting for developers. */
206   BOOL glslRequested;
207   int offscreen_rendering_mode;
208   int rendertargetlock_mode;
209   unsigned short pci_vendor_id;
210   unsigned short pci_device_id;
211 /* Memory tracking and object counting */
212   unsigned int emulated_textureram;
213   char *logo;
214   int allow_multisampling;
215 } wined3d_settings_t;
216
217 extern wined3d_settings_t wined3d_settings;
218
219 /* Shader backends */
220 struct SHADER_OPCODE_ARG;
221
222 #define SHADER_PGMSIZE 65535
223 typedef struct SHADER_BUFFER {
224     char* buffer;
225     unsigned int bsize;
226     unsigned int lineNo;
227     BOOL newline;
228 } SHADER_BUFFER;
229
230 enum WINED3D_SHADER_INSTRUCTION_HANDLER
231 {
232     WINED3DSIH_ABS,
233     WINED3DSIH_ADD,
234     WINED3DSIH_BEM,
235     WINED3DSIH_BREAK,
236     WINED3DSIH_BREAKC,
237     WINED3DSIH_BREAKP,
238     WINED3DSIH_CALL,
239     WINED3DSIH_CALLNZ,
240     WINED3DSIH_CMP,
241     WINED3DSIH_CND,
242     WINED3DSIH_CRS,
243     WINED3DSIH_DCL,
244     WINED3DSIH_DEF,
245     WINED3DSIH_DEFB,
246     WINED3DSIH_DEFI,
247     WINED3DSIH_DP2ADD,
248     WINED3DSIH_DP3,
249     WINED3DSIH_DP4,
250     WINED3DSIH_DST,
251     WINED3DSIH_DSX,
252     WINED3DSIH_DSY,
253     WINED3DSIH_ELSE,
254     WINED3DSIH_ENDIF,
255     WINED3DSIH_ENDLOOP,
256     WINED3DSIH_ENDREP,
257     WINED3DSIH_EXP,
258     WINED3DSIH_EXPP,
259     WINED3DSIH_FRC,
260     WINED3DSIH_IF,
261     WINED3DSIH_IFC,
262     WINED3DSIH_LABEL,
263     WINED3DSIH_LIT,
264     WINED3DSIH_LOG,
265     WINED3DSIH_LOGP,
266     WINED3DSIH_LOOP,
267     WINED3DSIH_LRP,
268     WINED3DSIH_M3x2,
269     WINED3DSIH_M3x3,
270     WINED3DSIH_M3x4,
271     WINED3DSIH_M4x3,
272     WINED3DSIH_M4x4,
273     WINED3DSIH_MAD,
274     WINED3DSIH_MAX,
275     WINED3DSIH_MIN,
276     WINED3DSIH_MOV,
277     WINED3DSIH_MOVA,
278     WINED3DSIH_MUL,
279     WINED3DSIH_NOP,
280     WINED3DSIH_NRM,
281     WINED3DSIH_PHASE,
282     WINED3DSIH_POW,
283     WINED3DSIH_RCP,
284     WINED3DSIH_REP,
285     WINED3DSIH_RET,
286     WINED3DSIH_RSQ,
287     WINED3DSIH_SETP,
288     WINED3DSIH_SGE,
289     WINED3DSIH_SGN,
290     WINED3DSIH_SINCOS,
291     WINED3DSIH_SLT,
292     WINED3DSIH_SUB,
293     WINED3DSIH_TEX,
294     WINED3DSIH_TEXBEM,
295     WINED3DSIH_TEXBEML,
296     WINED3DSIH_TEXCOORD,
297     WINED3DSIH_TEXDEPTH,
298     WINED3DSIH_TEXDP3,
299     WINED3DSIH_TEXDP3TEX,
300     WINED3DSIH_TEXKILL,
301     WINED3DSIH_TEXLDD,
302     WINED3DSIH_TEXLDL,
303     WINED3DSIH_TEXM3x2DEPTH,
304     WINED3DSIH_TEXM3x2PAD,
305     WINED3DSIH_TEXM3x2TEX,
306     WINED3DSIH_TEXM3x3,
307     WINED3DSIH_TEXM3x3DIFF,
308     WINED3DSIH_TEXM3x3PAD,
309     WINED3DSIH_TEXM3x3SPEC,
310     WINED3DSIH_TEXM3x3TEX,
311     WINED3DSIH_TEXM3x3VSPEC,
312     WINED3DSIH_TEXREG2AR,
313     WINED3DSIH_TEXREG2GB,
314     WINED3DSIH_TEXREG2RGB,
315     WINED3DSIH_TABLE_SIZE
316 };
317
318 typedef void (*SHADER_HANDLER)(const struct SHADER_OPCODE_ARG *);
319
320 struct shader_caps {
321     DWORD               VertexShaderVersion;
322     DWORD               MaxVertexShaderConst;
323
324     DWORD               PixelShaderVersion;
325     float               PixelShader1xMaxValue;
326
327     WINED3DVSHADERCAPS2_0   VS20Caps;
328     WINED3DPSHADERCAPS2_0   PS20Caps;
329
330     DWORD               MaxVShaderInstructionsExecuted;
331     DWORD               MaxPShaderInstructionsExecuted;
332     DWORD               MaxVertexShader30InstructionSlots;
333     DWORD               MaxPixelShader30InstructionSlots;
334 };
335
336 enum tex_types
337 {
338     tex_1d       = 0,
339     tex_2d       = 1,
340     tex_3d       = 2,
341     tex_cube     = 3,
342     tex_rect     = 4,
343     tex_type_count = 5,
344 };
345
346 typedef struct {
347     const SHADER_HANDLER *shader_instruction_handler_table;
348     void (*shader_select)(IWineD3DDevice *iface, BOOL usePS, BOOL useVS);
349     void (*shader_select_depth_blt)(IWineD3DDevice *iface, enum tex_types tex_type);
350     void (*shader_deselect_depth_blt)(IWineD3DDevice *iface);
351     void (*shader_load_constants)(IWineD3DDevice *iface, char usePS, char useVS);
352     void (*shader_cleanup)(IWineD3DDevice *iface);
353     void (*shader_color_correction)(const struct SHADER_OPCODE_ARG *arg);
354     void (*shader_destroy)(IWineD3DBaseShader *iface);
355     HRESULT (*shader_alloc_private)(IWineD3DDevice *iface);
356     void (*shader_free_private)(IWineD3DDevice *iface);
357     BOOL (*shader_dirtifyable_constants)(IWineD3DDevice *iface);
358     GLuint (*shader_generate_pshader)(IWineD3DPixelShader *iface, SHADER_BUFFER *buffer);
359     void (*shader_generate_vshader)(IWineD3DVertexShader *iface, SHADER_BUFFER *buffer);
360     void (*shader_get_caps)(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct shader_caps *caps);
361     BOOL (*shader_conv_supported)(WINED3DFORMAT conv);
362 } shader_backend_t;
363
364 extern const shader_backend_t glsl_shader_backend;
365 extern const shader_backend_t arb_program_shader_backend;
366 extern const shader_backend_t none_shader_backend;
367
368 /* X11 locking */
369
370 extern void (*wine_tsx11_lock_ptr)(void);
371 extern void (*wine_tsx11_unlock_ptr)(void);
372
373 /* As GLX relies on X, this is needed */
374 extern int num_lock;
375
376 #if 0
377 #define ENTER_GL() ++num_lock; if (num_lock > 1) FIXME("Recursive use of GL lock to: %d\n", num_lock); wine_tsx11_lock_ptr()
378 #define LEAVE_GL() if (num_lock != 1) FIXME("Recursive use of GL lock: %d\n", num_lock); --num_lock; wine_tsx11_unlock_ptr()
379 #else
380 #define ENTER_GL() wine_tsx11_lock_ptr()
381 #define LEAVE_GL() wine_tsx11_unlock_ptr()
382 #endif
383
384 /*****************************************************************************
385  * Defines
386  */
387
388 /* GL related defines */
389 /* ------------------ */
390 #define GL_SUPPORT(ExtName)           (GLINFO_LOCATION.supported[ExtName] != 0)
391 #define GL_LIMITS(ExtName)            (GLINFO_LOCATION.max_##ExtName)
392 #define GL_EXTCALL(FuncName)          (GLINFO_LOCATION.FuncName)
393 #define GL_VEND(_VendName)            (GLINFO_LOCATION.gl_vendor == VENDOR_##_VendName ? TRUE : FALSE)
394
395 #define D3DCOLOR_B_R(dw) (((dw) >> 16) & 0xFF)
396 #define D3DCOLOR_B_G(dw) (((dw) >>  8) & 0xFF)
397 #define D3DCOLOR_B_B(dw) (((dw) >>  0) & 0xFF)
398 #define D3DCOLOR_B_A(dw) (((dw) >> 24) & 0xFF)
399
400 #define D3DCOLOR_R(dw) (((float) (((dw) >> 16) & 0xFF)) / 255.0f)
401 #define D3DCOLOR_G(dw) (((float) (((dw) >>  8) & 0xFF)) / 255.0f)
402 #define D3DCOLOR_B(dw) (((float) (((dw) >>  0) & 0xFF)) / 255.0f)
403 #define D3DCOLOR_A(dw) (((float) (((dw) >> 24) & 0xFF)) / 255.0f)
404
405 #define D3DCOLORTOGLFLOAT4(dw, vec) \
406   (vec)[0] = D3DCOLOR_R(dw); \
407   (vec)[1] = D3DCOLOR_G(dw); \
408   (vec)[2] = D3DCOLOR_B(dw); \
409   (vec)[3] = D3DCOLOR_A(dw);
410
411 /* DirectX Device Limits */
412 /* --------------------- */
413 #define MAX_LEVELS  256  /* Maximum number of mipmap levels. Guessed at 256 */
414
415 #define MAX_STREAMS  16  /* Maximum possible streams - used for fixed size arrays
416                             See MaxStreams in MSDN under GetDeviceCaps */
417                          /* Maximum number of constants provided to the shaders */
418 #define HIGHEST_TRANSFORMSTATE 512 
419                          /* Highest value in WINED3DTRANSFORMSTATETYPE */
420
421 /* Checking of API calls */
422 /* --------------------- */
423 #define checkGLcall(A)                                          \
424 {                                                               \
425     GLint err = glGetError();                                   \
426     if (err == GL_NO_ERROR) {                                   \
427        TRACE("%s call ok %s / %d\n", A, __FILE__, __LINE__);    \
428                                                                 \
429     } else do {                                                 \
430         FIXME(">>>>>>>>>>>>>>>>> %s (%#x) from %s @ %s / %d\n", \
431             debug_glerror(err), err, A, __FILE__, __LINE__);    \
432        err = glGetError();                                      \
433     } while (err != GL_NO_ERROR);                               \
434
435
436 /* Trace routines / diagnostics */
437 /* ---------------------------- */
438
439 /* Dump out a matrix and copy it */
440 #define conv_mat(mat,gl_mat)                                                                \
441 do {                                                                                        \
442     TRACE("%f %f %f %f\n", (mat)->u.s._11, (mat)->u.s._12, (mat)->u.s._13, (mat)->u.s._14); \
443     TRACE("%f %f %f %f\n", (mat)->u.s._21, (mat)->u.s._22, (mat)->u.s._23, (mat)->u.s._24); \
444     TRACE("%f %f %f %f\n", (mat)->u.s._31, (mat)->u.s._32, (mat)->u.s._33, (mat)->u.s._34); \
445     TRACE("%f %f %f %f\n", (mat)->u.s._41, (mat)->u.s._42, (mat)->u.s._43, (mat)->u.s._44); \
446     memcpy(gl_mat, (mat), 16 * sizeof(float));                                              \
447 } while (0)
448
449 /* Macro to dump out the current state of the light chain */
450 #define DUMP_LIGHT_CHAIN()                    \
451 {                                             \
452   PLIGHTINFOEL *el = This->stateBlock->lights;\
453   while (el) {                                \
454     TRACE("Light %p (glIndex %ld, d3dIndex %ld, enabled %d)\n", el, el->glIndex, el->OriginalIndex, el->lightEnabled);\
455     el = el->next;                            \
456   }                                           \
457 }
458
459 /* Trace vector and strided data information */
460 #define TRACE_VECTOR(name) TRACE( #name "=(%f, %f, %f, %f)\n", name.x, name.y, name.z, name.w);
461 #define TRACE_STRIDED(sd,name) TRACE( #name "=(data:%p, stride:%d, type:%d, vbo %d, stream %u)\n", \
462         sd->u.s.name.lpData, sd->u.s.name.dwStride, sd->u.s.name.dwType, sd->u.s.name.VBO, sd->u.s.name.streamNo);
463
464 /* Defines used for optimizations */
465
466 /*    Only reapply what is necessary */
467 #define REAPPLY_ALPHAOP  0x0001
468 #define REAPPLY_ALL      0xFFFF
469
470 /* Advance declaration of structures to satisfy compiler */
471 typedef struct IWineD3DStateBlockImpl IWineD3DStateBlockImpl;
472 typedef struct IWineD3DSurfaceImpl    IWineD3DSurfaceImpl;
473 typedef struct IWineD3DPaletteImpl    IWineD3DPaletteImpl;
474 typedef struct IWineD3DDeviceImpl     IWineD3DDeviceImpl;
475
476 /* Global variables */
477 extern const float identity[16];
478
479 /*****************************************************************************
480  * Compilable extra diagnostics
481  */
482
483 /* Trace information per-vertex: (extremely high amount of trace) */
484 #if 0 /* NOTE: Must be 0 in cvs */
485 # define VTRACE(A) TRACE A
486 #else 
487 # define VTRACE(A) 
488 #endif
489
490 /* Checking of per-vertex related GL calls */
491 /* --------------------- */
492 #define vcheckGLcall(A)                                         \
493 {                                                               \
494     GLint err = glGetError();                                   \
495     if (err == GL_NO_ERROR) {                                   \
496        VTRACE(("%s call ok %s / %d\n", A, __FILE__, __LINE__)); \
497                                                                 \
498     } else do {                                                 \
499         FIXME(">>>>>>>>>>>>>>>>> %s (%#x) from %s @ %s / %d\n", \
500             debug_glerror(err), err, A, __FILE__, __LINE__);    \
501        err = glGetError();                                      \
502     } while (err != GL_NO_ERROR);                               \
503 }
504
505 /* TODO: Confirm each of these works when wined3d move completed */
506 #if 0 /* NOTE: Must be 0 in cvs */
507   /* To avoid having to get gigabytes of trace, the following can be compiled in, and at the start
508      of each frame, a check is made for the existence of C:\D3DTRACE, and if it exists d3d trace
509      is enabled, and if it doesn't exist it is disabled. */
510 # define FRAME_DEBUGGING
511   /*  Adding in the SINGLE_FRAME_DEBUGGING gives a trace of just what makes up a single frame, before
512       the file is deleted                                                                            */
513 # if 1 /* NOTE: Must be 1 in cvs, as this is mostly more useful than a trace from program start */
514 #  define SINGLE_FRAME_DEBUGGING
515 # endif  
516   /* The following, when enabled, lets you see the makeup of the frame, by drawprimitive calls.
517      It can only be enabled when FRAME_DEBUGGING is also enabled                               
518      The contents of the back buffer are written into /tmp/backbuffer_* after each primitive 
519      array is drawn.                                                                            */
520 # if 0 /* NOTE: Must be 0 in cvs, as this give a lot of ppm files when compiled in */                                                                                       
521 #  define SHOW_FRAME_MAKEUP 1
522 # endif  
523   /* The following, when enabled, lets you see the makeup of the all the textures used during each
524      of the drawprimitive calls. It can only be enabled when SHOW_FRAME_MAKEUP is also enabled.
525      The contents of the textures assigned to each stage are written into 
526      /tmp/texture_*_<Stage>.ppm after each primitive array is drawn.                            */
527 # if 0 /* NOTE: Must be 0 in cvs, as this give a lot of ppm files when compiled in */
528 #  define SHOW_TEXTURE_MAKEUP 0
529 # endif  
530 extern BOOL isOn;
531 extern BOOL isDumpingFrames;
532 extern LONG primCounter;
533 #endif
534
535 /*****************************************************************************
536  * Prototypes
537  */
538
539 /* Routine common to the draw primitive and draw indexed primitive routines */
540 void drawPrimitive(IWineD3DDevice *iface,
541                     int PrimitiveType,
542                     long NumPrimitives,
543                     /* for Indexed: */
544                     long  StartVertexIndex,
545                     UINT  numberOfVertices,
546                     long  StartIdx,
547                     short idxBytes,
548                     const void *idxData,
549                     int   minIndex);
550
551 void primitiveDeclarationConvertToStridedData(
552      IWineD3DDevice *iface,
553      BOOL useVertexShaderFunction,
554      WineDirect3DVertexStridedData *strided,
555      BOOL *fixup);
556
557 DWORD get_flexible_vertex_size(DWORD d3dvtVertexType);
558
559 typedef void (WINE_GLAPI *glAttribFunc)(const void *data);
560 typedef void (WINE_GLAPI *glMultiTexCoordFunc)(GLenum unit, const void *data);
561 extern glAttribFunc position_funcs[WINED3DDECLTYPE_UNUSED];
562 extern glAttribFunc diffuse_funcs[WINED3DDECLTYPE_UNUSED];
563 extern glAttribFunc specular_funcs[WINED3DDECLTYPE_UNUSED];
564 extern glAttribFunc normal_funcs[WINED3DDECLTYPE_UNUSED];
565 extern glMultiTexCoordFunc multi_texcoord_funcs[WINED3DDECLTYPE_UNUSED];
566 extern glAttribFunc texcoord_funcs[WINED3DDECLTYPE_UNUSED];
567
568 #define eps 1e-8
569
570 #define GET_TEXCOORD_SIZE_FROM_FVF(d3dvtVertexType, tex_num) \
571     (((((d3dvtVertexType) >> (16 + (2 * (tex_num)))) + 1) & 0x03) + 1)
572
573 /* Routines and structures related to state management */
574 typedef struct WineD3DContext WineD3DContext;
575 typedef void (*APPLYSTATEFUNC)(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *ctx);
576
577 #define STATE_RENDER(a) (a)
578 #define STATE_IS_RENDER(a) ((a) >= STATE_RENDER(1) && (a) <= STATE_RENDER(WINEHIGHEST_RENDER_STATE))
579
580 #define STATE_TEXTURESTAGE(stage, num) (STATE_RENDER(WINEHIGHEST_RENDER_STATE) + (stage) * WINED3D_HIGHEST_TEXTURE_STATE + (num))
581 #define STATE_IS_TEXTURESTAGE(a) ((a) >= STATE_TEXTURESTAGE(0, 1) && (a) <= STATE_TEXTURESTAGE(MAX_TEXTURES - 1, WINED3D_HIGHEST_TEXTURE_STATE))
582
583 /* + 1 because samplers start with 0 */
584 #define STATE_SAMPLER(num) (STATE_TEXTURESTAGE(MAX_TEXTURES - 1, WINED3D_HIGHEST_TEXTURE_STATE) + 1 + (num))
585 #define STATE_IS_SAMPLER(num) ((num) >= STATE_SAMPLER(0) && (num) <= STATE_SAMPLER(MAX_COMBINED_SAMPLERS - 1))
586
587 #define STATE_PIXELSHADER (STATE_SAMPLER(MAX_COMBINED_SAMPLERS - 1) + 1)
588 #define STATE_IS_PIXELSHADER(a) ((a) == STATE_PIXELSHADER)
589
590 #define STATE_TRANSFORM(a) (STATE_PIXELSHADER + (a))
591 #define STATE_IS_TRANSFORM(a) ((a) >= STATE_TRANSFORM(1) && (a) <= STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(255)))
592
593 #define STATE_STREAMSRC (STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(255)) + 1)
594 #define STATE_IS_STREAMSRC(a) ((a) == STATE_STREAMSRC)
595 #define STATE_INDEXBUFFER (STATE_STREAMSRC + 1)
596 #define STATE_IS_INDEXBUFFER(a) ((a) == STATE_INDEXBUFFER)
597
598 #define STATE_VDECL (STATE_INDEXBUFFER + 1)
599 #define STATE_IS_VDECL(a) ((a) == STATE_VDECL)
600
601 #define STATE_VSHADER (STATE_VDECL + 1)
602 #define STATE_IS_VSHADER(a) ((a) == STATE_VSHADER)
603
604 #define STATE_VIEWPORT (STATE_VSHADER + 1)
605 #define STATE_IS_VIEWPORT(a) ((a) == STATE_VIEWPORT)
606
607 #define STATE_VERTEXSHADERCONSTANT (STATE_VIEWPORT + 1)
608 #define STATE_PIXELSHADERCONSTANT (STATE_VERTEXSHADERCONSTANT + 1)
609 #define STATE_IS_VERTEXSHADERCONSTANT(a) ((a) == STATE_VERTEXSHADERCONSTANT)
610 #define STATE_IS_PIXELSHADERCONSTANT(a) ((a) == STATE_PIXELSHADERCONSTANT)
611
612 #define STATE_ACTIVELIGHT(a) (STATE_PIXELSHADERCONSTANT + (a) + 1)
613 #define STATE_IS_ACTIVELIGHT(a) ((a) >= STATE_ACTIVELIGHT(0) && (a) < STATE_ACTIVELIGHT(MAX_ACTIVE_LIGHTS))
614
615 #define STATE_SCISSORRECT (STATE_ACTIVELIGHT(MAX_ACTIVE_LIGHTS - 1) + 1)
616 #define STATE_IS_SCISSORRECT(a) ((a) == STATE_SCISSORRECT)
617
618 #define STATE_CLIPPLANE(a) (STATE_SCISSORRECT + 1 + (a))
619 #define STATE_IS_CLIPPLANE(a) ((a) >= STATE_CLIPPLANE(0) && (a) <= STATE_CLIPPLANE(MAX_CLIPPLANES - 1))
620
621 #define STATE_MATERIAL (STATE_CLIPPLANE(MAX_CLIPPLANES))
622
623 #define STATE_FRONTFACE (STATE_MATERIAL + 1)
624
625 #define STATE_HIGHEST (STATE_FRONTFACE)
626
627 struct StateEntry
628 {
629     DWORD               representative;
630     APPLYSTATEFUNC      apply;
631 };
632
633 struct StateEntryTemplate
634 {
635     DWORD               state;
636     struct StateEntry   content;
637     GL_SupportedExt     extension;
638 };
639
640 struct fragment_caps {
641     DWORD               PrimitiveMiscCaps;
642
643     DWORD               TextureOpCaps;
644     DWORD               MaxTextureBlendStages;
645     DWORD               MaxSimultaneousTextures;
646 };
647
648 struct fragment_pipeline {
649     void (*enable_extension)(IWineD3DDevice *iface, BOOL enable);
650     void (*get_caps)(WINED3DDEVTYPE devtype, const WineD3D_GL_Info *gl_info, struct fragment_caps *caps);
651     HRESULT (*alloc_private)(IWineD3DDevice *iface);
652     void (*free_private)(IWineD3DDevice *iface);
653     BOOL (*conv_supported)(WINED3DFORMAT conv);
654     const struct StateEntryTemplate *states;
655     BOOL ffp_proj_control;
656 };
657
658 extern const struct StateEntryTemplate misc_state_template[];
659 extern const struct StateEntryTemplate ffp_vertexstate_template[];
660 extern const struct fragment_pipeline ffp_fragment_pipeline;
661 extern const struct fragment_pipeline atifs_fragment_pipeline;
662 extern const struct fragment_pipeline arbfp_fragment_pipeline;
663 extern const struct fragment_pipeline nvts_fragment_pipeline;
664 extern const struct fragment_pipeline nvrc_fragment_pipeline;
665
666 /* "Base" state table */
667 void compile_state_table(struct StateEntry *StateTable, APPLYSTATEFUNC **dev_multistate_funcs,
668         const WineD3D_GL_Info *gl_info, const struct StateEntryTemplate *vertex,
669         const struct fragment_pipeline *fragment, const struct StateEntryTemplate *misc);
670
671 /* Shaders for color conversions in blits */
672 struct blit_shader {
673     HRESULT (*alloc_private)(IWineD3DDevice *iface);
674     void (*free_private)(IWineD3DDevice *iface);
675     HRESULT (*set_shader)(IWineD3DDevice *iface, WINED3DFORMAT fmt, GLenum textype, UINT width, UINT height);
676     void (*unset_shader)(IWineD3DDevice *iface);
677     BOOL (*conv_supported)(WINED3DFORMAT conv);
678 };
679
680 extern const struct blit_shader ffp_blit;
681 extern const struct blit_shader arbfp_blit;
682
683 /* The new context manager that should deal with onscreen and offscreen rendering */
684 struct WineD3DContext {
685     /* State dirtification
686      * dirtyArray is an array that contains markers for dirty states. numDirtyEntries states are dirty, their numbers are in indices
687      * 0...numDirtyEntries - 1. isStateDirty is a redundant copy of the dirtyArray. Technically only one of them would be needed,
688      * but with the help of both it is easy to find out if a state is dirty(just check the array index), and for applying dirty states
689      * only numDirtyEntries array elements have to be checked, not STATE_HIGHEST states.
690      */
691     DWORD                   dirtyArray[STATE_HIGHEST + 1]; /* Won't get bigger than that, a state is never marked dirty 2 times */
692     DWORD                   numDirtyEntries;
693     DWORD                   isStateDirty[STATE_HIGHEST/32 + 1]; /* Bitmap to find out quickly if a state is dirty */
694
695     IWineD3DSurface         *surface;
696     DWORD                   tid;    /* Thread ID which owns this context at the moment */
697
698     /* Stores some information about the context state for optimization */
699     BOOL                    draw_buffer_dirty;
700     BOOL                    last_was_rhw;      /* true iff last draw_primitive was in xyzrhw mode */
701     BOOL                    last_was_pshader;
702     BOOL                    last_was_vshader;
703     BOOL                    last_was_foggy_shader;
704     BOOL                    namedArraysLoaded, numberedArraysLoaded;
705     BOOL                    lastWasPow2Texture[MAX_TEXTURES];
706     GLenum                  tracking_parm;     /* Which source is tracking current colour         */
707     unsigned char           num_untracked_materials;
708     GLenum                  untracked_materials[2];
709     BOOL                    last_was_blit, last_was_ckey;
710     UINT                    blit_w, blit_h;
711     char                    texShaderBumpMap;
712     BOOL                    fog_coord;
713
714     char                    *vshader_const_dirty, *pshader_const_dirty;
715
716     /* The actual opengl context */
717     HGLRC                   glCtx;
718     HWND                    win_handle;
719     HDC                     hdc;
720     HPBUFFERARB             pbuffer;
721     BOOL                    isPBuffer;
722     GLint                   aux_buffers;
723
724     /* FBOs */
725     struct list             fbo_list;
726     struct fbo_entry        *current_fbo;
727     GLuint                  src_fbo;
728     GLuint                  dst_fbo;
729 };
730
731 typedef enum ContextUsage {
732     CTXUSAGE_RESOURCELOAD       = 1,    /* Only loads textures: No State is applied */
733     CTXUSAGE_DRAWPRIM           = 2,    /* OpenGL states are set up for blitting DirectDraw surfaces */
734     CTXUSAGE_BLIT               = 3,    /* OpenGL states are set up 3D drawing */
735     CTXUSAGE_CLEAR              = 4,    /* Drawable and states are set up for clearing */
736 } ContextUsage;
737
738 void ActivateContext(IWineD3DDeviceImpl *device, IWineD3DSurface *target, ContextUsage usage);
739 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms);
740 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context);
741 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type);
742 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo);
743 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer);
744 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface);
745
746 void delete_opengl_contexts(IWineD3DDevice *iface, IWineD3DSwapChain *swapchain);
747 HRESULT create_primary_opengl_context(IWineD3DDevice *iface, IWineD3DSwapChain *swapchain);
748
749 /* Macros for doing basic GPU detection based on opengl capabilities */
750 #define WINE_D3D6_CAPABLE(gl_info) (gl_info->supported[ARB_MULTITEXTURE])
751 #define WINE_D3D7_CAPABLE(gl_info) (gl_info->supported[ARB_TEXTURE_COMPRESSION] && gl_info->supported[ARB_TEXTURE_CUBE_MAP] && gl_info->supported[ARB_TEXTURE_ENV_DOT3])
752 #define WINE_D3D8_CAPABLE(gl_info) WINE_D3D7_CAPABLE(gl_info) && (gl_info->supported[ARB_MULTISAMPLE] && gl_info->supported[ARB_TEXTURE_BORDER_CLAMP])
753 #define WINE_D3D9_CAPABLE(gl_info) WINE_D3D8_CAPABLE(gl_info) && (gl_info->supported[ARB_FRAGMENT_PROGRAM] && gl_info->supported[ARB_VERTEX_SHADER])
754
755 /* Default callbacks for implicit object destruction */
756 extern ULONG WINAPI D3DCB_DefaultDestroySurface(IWineD3DSurface *pSurface);
757
758 extern ULONG WINAPI D3DCB_DefaultDestroyVolume(IWineD3DVolume *pSurface);
759
760 /*****************************************************************************
761  * Internal representation of a light
762  */
763 typedef struct PLIGHTINFOEL PLIGHTINFOEL;
764 struct PLIGHTINFOEL {
765     WINED3DLIGHT OriginalParms; /* Note D3D8LIGHT == D3D9LIGHT */
766     DWORD        OriginalIndex;
767     LONG         glIndex;
768     BOOL         changed;
769     BOOL         enabledChanged;
770     BOOL         enabled;
771
772     /* Converted parms to speed up swapping lights */
773     float                         lightPosn[4];
774     float                         lightDirn[4];
775     float                         exponent;
776     float                         cutoff;
777
778     struct list entry;
779 };
780
781 /* The default light parameters */
782 extern const WINED3DLIGHT WINED3D_default_light;
783
784 typedef struct WineD3D_PixelFormat
785 {
786     int iPixelFormat; /* WGL pixel format */
787     int iPixelType; /* WGL pixel type e.g. WGL_TYPE_RGBA_ARB, WGL_TYPE_RGBA_FLOAT_ARB or WGL_TYPE_COLORINDEX_ARB */
788     int redSize, greenSize, blueSize, alphaSize;
789     int depthSize, stencilSize;
790     BOOL windowDrawable;
791     BOOL pbufferDrawable;
792     BOOL doubleBuffer;
793     int auxBuffers;
794     int numSamples;
795 } WineD3D_PixelFormat;
796
797 /* The adapter structure */
798 struct WineD3DAdapter
799 {
800     UINT                    num;
801     BOOL                    opengl;
802     POINT                   monitorPoint;
803     WineD3D_GL_Info         gl_info;
804     const char              *driver;
805     const char              *description;
806     WCHAR                   DeviceName[CCHDEVICENAME]; /* DeviceName for use with e.g. ChangeDisplaySettings */
807     int                     nCfgs;
808     WineD3D_PixelFormat     *cfgs;
809     BOOL                    brokenStencil; /* Set on cards which only offer mixed depth+stencil */
810     unsigned int            TextureRam; /* Amount of texture memory both video ram + AGP/TurboCache/HyperMemory/.. */
811     unsigned int            UsedTextureRam;
812 };
813
814 extern BOOL InitAdapters(void);
815 extern BOOL initPixelFormats(WineD3D_GL_Info *gl_info);
816 extern long WineD3DAdapterChangeGLRam(IWineD3DDeviceImpl *D3DDevice, long glram);
817
818 /*****************************************************************************
819  * High order patch management
820  */
821 struct WineD3DRectPatch
822 {
823     UINT                            Handle;
824     float                          *mem;
825     WineDirect3DVertexStridedData   strided;
826     WINED3DRECTPATCH_INFO           RectPatchInfo;
827     float                           numSegs[4];
828     char                            has_normals, has_texcoords;
829     struct list                     entry;
830 };
831
832 HRESULT tesselate_rectpatch(IWineD3DDeviceImpl *This, struct WineD3DRectPatch *patch);
833
834 enum projection_types
835 {
836     proj_none    = 0,
837     proj_count3  = 1,
838     proj_count4  = 2
839 };
840
841 enum dst_arg
842 {
843     resultreg    = 0,
844     tempreg      = 1
845 };
846
847 /*****************************************************************************
848  * Fixed function pipeline replacements
849  */
850 struct texture_stage_op
851 {
852     unsigned                cop : 5, aop : 5;
853 #define ARG_UNUSED          0x3f
854     unsigned                carg1 : 6, carg2 : 6, carg0 : 6;
855     unsigned                tex_type : 3;
856     unsigned                dst : 1;                        /* Total of 32 bits */
857     unsigned                aarg1 : 6, aarg2 : 6, aarg0 : 6;
858     unsigned                projected : 2;
859     unsigned                padding : 12;                   /* Total of 64 bits */
860     WINED3DFORMAT           color_correction;
861 };
862
863 struct ffp_frag_settings {
864     struct texture_stage_op     op[MAX_TEXTURES];
865     enum {
866         FOG_OFF,
867         FOG_LINEAR,
868         FOG_EXP,
869         FOG_EXP2
870     } fog;
871     /* Use an int instead of a char to get dword alignment */
872     unsigned int sRGB_write;
873 };
874
875 struct ffp_frag_desc
876 {
877     struct ffp_frag_settings    settings;
878 };
879
880 void gen_ffp_frag_op(IWineD3DStateBlockImpl *stateblock, struct ffp_frag_settings *settings, BOOL ignore_textype);
881 const struct ffp_frag_desc *find_ffp_frag_shader(const struct hash_table_t *fragment_shaders,
882         const struct ffp_frag_settings *settings);
883 void add_ffp_frag_shader(struct hash_table_t *shaders, struct ffp_frag_desc *desc);
884 BOOL ffp_frag_program_key_compare(const void *keya, const void *keyb);
885 unsigned int ffp_frag_program_key_hash(const void *key);
886
887 /*****************************************************************************
888  * IWineD3D implementation structure
889  */
890 typedef struct IWineD3DImpl
891 {
892     /* IUnknown fields */
893     const IWineD3DVtbl     *lpVtbl;
894     LONG                    ref;     /* Note: Ref counting not required */
895
896     /* WineD3D Information */
897     IUnknown               *parent;
898     UINT                    dxVersion;
899 } IWineD3DImpl;
900
901 extern const IWineD3DVtbl IWineD3D_Vtbl;
902
903 /* TODO: setup some flags in the registry to enable, disable pbuffer support
904 (since it will break quite a few things until contexts are managed properly!) */
905 extern BOOL pbuffer_support;
906 /* allocate one pbuffer per surface */
907 extern BOOL pbuffer_per_surface;
908
909 /* A helper function that dumps a resource list */
910 void dumpResources(struct list *list);
911
912 /*****************************************************************************
913  * IWineD3DDevice implementation structure
914  */
915 struct IWineD3DDeviceImpl
916 {
917     /* IUnknown fields      */
918     const IWineD3DDeviceVtbl *lpVtbl;
919     LONG                    ref;     /* Note: Ref counting not required */
920
921     /* WineD3D Information  */
922     IUnknown               *parent;
923     IWineD3D               *wineD3D;
924     struct WineD3DAdapter  *adapter;
925
926     /* Window styles to restore when switching fullscreen mode */
927     LONG                    style;
928     LONG                    exStyle;
929
930     /* X and GL Information */
931     GLint                   maxConcurrentLights;
932     GLenum                  offscreenBuffer;
933
934     /* Selected capabilities */
935     int vs_selected_mode;
936     int ps_selected_mode;
937     const shader_backend_t *shader_backend;
938     void *shader_priv;
939     void *fragment_priv;
940     void *blit_priv;
941     struct StateEntry StateTable[STATE_HIGHEST + 1];
942     /* Array of functions for states which are handled by more than one pipeline part */
943     APPLYSTATEFUNC *multistate_funcs[STATE_HIGHEST + 1];
944     const struct fragment_pipeline *frag_pipe;
945     const struct blit_shader *blitter;
946
947     unsigned int max_ffp_textures, max_ffp_texture_stages;
948
949     /* To store */
950     BOOL                    view_ident;        /* true iff view matrix is identity                */
951     BOOL                    untransformed;
952     BOOL                    vertexBlendUsed;   /* To avoid needless setting of the blend matrices */
953 #define DDRAW_PITCH_ALIGNMENT 8
954 #define D3D8_PITCH_ALIGNMENT 4
955     unsigned char           surface_alignment; /* Line Alignment of surfaces                      */
956
957     /* State block related */
958     BOOL                    isRecordingState;
959     IWineD3DStateBlockImpl *stateBlock;
960     IWineD3DStateBlockImpl *updateStateBlock;
961     BOOL                   isInDraw;
962
963     /* Internal use fields  */
964     WINED3DDEVICE_CREATION_PARAMETERS createParms;
965     UINT                            adapterNo;
966     WINED3DDEVTYPE                  devType;
967
968     IWineD3DSwapChain     **swapchains;
969     UINT                    NumberOfSwapChains;
970
971     struct list             resources; /* a linked list to track resources created by the device */
972     struct list             shaders;   /* a linked list to track shaders (pixel and vertex)      */
973     unsigned int            highest_dirty_ps_const, highest_dirty_vs_const;
974
975     /* Render Target Support */
976     IWineD3DSurface       **render_targets;
977     IWineD3DSurface        *auto_depth_stencil_buffer;
978     IWineD3DSurface        *stencilBufferTarget;
979
980     /* Caches to avoid unneeded context changes */
981     IWineD3DSurface        *lastActiveRenderTarget;
982     IWineD3DSwapChain      *lastActiveSwapChain;
983
984     /* palettes texture management */
985     UINT                    NumberOfPalettes;
986     PALETTEENTRY            **palettes;
987     UINT                    currentPalette;
988     UINT                    paletteConversionShader;
989
990     /* For rendering to a texture using glCopyTexImage */
991     BOOL                    render_offscreen;
992     GLenum                  *draw_buffers;
993     GLuint                  depth_blt_texture;
994     GLuint                  depth_blt_rb;
995     UINT                    depth_blt_rb_w;
996     UINT                    depth_blt_rb_h;
997
998     /* Cursor management */
999     BOOL                    bCursorVisible;
1000     UINT                    xHotSpot;
1001     UINT                    yHotSpot;
1002     UINT                    xScreenSpace;
1003     UINT                    yScreenSpace;
1004     UINT                    cursorWidth, cursorHeight;
1005     GLuint                  cursorTexture;
1006     BOOL                    haveHardwareCursor;
1007     HCURSOR                 hardwareCursor;
1008
1009     /* The Wine logo surface */
1010     IWineD3DSurface        *logo_surface;
1011
1012     /* Textures for when no other textures are mapped */
1013     UINT                          dummyTextureName[MAX_TEXTURES];
1014
1015     /* Debug stream management */
1016     BOOL                     debug;
1017
1018     /* Device state management */
1019     HRESULT                 state;
1020     BOOL                    d3d_initialized;
1021
1022     /* A flag to check for proper BeginScene / EndScene call pairs */
1023     BOOL inScene;
1024
1025     /* process vertex shaders using software or hardware */
1026     BOOL softwareVertexProcessing;
1027
1028     /* DirectDraw stuff */
1029     DWORD ddraw_width, ddraw_height;
1030     WINED3DFORMAT ddraw_format;
1031
1032     /* Final position fixup constant */
1033     float                       posFixup[4];
1034
1035     /* With register combiners we can skip junk texture stages */
1036     DWORD                     texUnitMap[MAX_COMBINED_SAMPLERS];
1037     DWORD                     rev_tex_unit_map[MAX_COMBINED_SAMPLERS];
1038     BOOL                      fixed_function_usage_map[MAX_TEXTURES];
1039
1040     /* Stream source management */
1041     WineDirect3DVertexStridedData strided_streams;
1042     const WineDirect3DVertexStridedData *up_strided;
1043     BOOL                      useDrawStridedSlow;
1044     BOOL                      instancedDraw;
1045
1046     /* Context management */
1047     WineD3DContext          **contexts;                  /* Dynamic array containing pointers to context structures */
1048     WineD3DContext          *activeContext;
1049     DWORD                   lastThread;
1050     UINT                    numContexts;
1051     WineD3DContext          *pbufferContext;             /* The context that has a pbuffer as drawable */
1052     DWORD                   pbufferWidth, pbufferHeight; /* Size of the buffer drawable */
1053
1054     /* High level patch management */
1055 #define PATCHMAP_SIZE 43
1056 #define PATCHMAP_HASHFUNC(x) ((x) % PATCHMAP_SIZE) /* Primitive and simple function */
1057     struct list             patches[PATCHMAP_SIZE];
1058     struct WineD3DRectPatch *currentPatch;
1059 };
1060
1061 extern const IWineD3DDeviceVtbl IWineD3DDevice_Vtbl, IWineD3DDevice_DirtyConst_Vtbl;
1062
1063 HRESULT IWineD3DDeviceImpl_ClearSurface(IWineD3DDeviceImpl *This,  IWineD3DSurfaceImpl *target, DWORD Count,
1064                                         CONST WINED3DRECT* pRects, DWORD Flags, WINED3DCOLOR Color,
1065                                         float Z, DWORD Stencil);
1066 void IWineD3DDeviceImpl_FindTexUnitMap(IWineD3DDeviceImpl *This);
1067 void IWineD3DDeviceImpl_MarkStateDirty(IWineD3DDeviceImpl *This, DWORD state);
1068 static inline BOOL isStateDirty(WineD3DContext *context, DWORD state) {
1069     DWORD idx = state >> 5;
1070     BYTE shift = state & 0x1f;
1071     return context->isStateDirty[idx] & (1 << shift);
1072 }
1073
1074 /* Support for IWineD3DResource ::Set/Get/FreePrivateData. */
1075 typedef struct PrivateData
1076 {
1077     struct list entry;
1078
1079     GUID tag;
1080     DWORD flags; /* DDSPD_* */
1081
1082     union
1083     {
1084         LPVOID data;
1085         LPUNKNOWN object;
1086     } ptr;
1087
1088     DWORD size;
1089 } PrivateData;
1090
1091 /*****************************************************************************
1092  * IWineD3DResource implementation structure
1093  */
1094 typedef struct IWineD3DResourceClass
1095 {
1096     /* IUnknown fields */
1097     LONG                    ref;     /* Note: Ref counting not required */
1098
1099     /* WineD3DResource Information */
1100     IUnknown               *parent;
1101     WINED3DRESOURCETYPE     resourceType;
1102     IWineD3DDeviceImpl     *wineD3DDevice;
1103     WINED3DPOOL             pool;
1104     UINT                    size;
1105     DWORD                   usage;
1106     WINED3DFORMAT           format;
1107     DWORD                   priority;
1108     BYTE                   *allocatedMemory; /* Pointer to the real data location */
1109     BYTE                   *heapMemory; /* Pointer to the HeapAlloced block of memory */
1110     struct list             privateData;
1111     struct list             resource_list_entry;
1112
1113 } IWineD3DResourceClass;
1114
1115 typedef struct IWineD3DResourceImpl
1116 {
1117     /* IUnknown & WineD3DResource Information     */
1118     const IWineD3DResourceVtbl *lpVtbl;
1119     IWineD3DResourceClass   resource;
1120 } IWineD3DResourceImpl;
1121
1122 void resource_cleanup(IWineD3DResource *iface);
1123 HRESULT resource_free_private_data(IWineD3DResource *iface, REFGUID guid);
1124 HRESULT resource_get_device(IWineD3DResource *iface, IWineD3DDevice **device);
1125 HRESULT resource_get_parent(IWineD3DResource *iface, IUnknown **parent);
1126 DWORD resource_get_priority(IWineD3DResource *iface);
1127 HRESULT resource_get_private_data(IWineD3DResource *iface, REFGUID guid,
1128         void *data, DWORD *data_size);
1129 WINED3DRESOURCETYPE resource_get_type(IWineD3DResource *iface);
1130 DWORD resource_set_priority(IWineD3DResource *iface, DWORD new_priority);
1131 HRESULT resource_set_private_data(IWineD3DResource *iface, REFGUID guid,
1132         const void *data, DWORD data_size, DWORD flags);
1133
1134 /* Tests show that the start address of resources is 32 byte aligned */
1135 #define RESOURCE_ALIGNMENT 32
1136
1137 /*****************************************************************************
1138  * IWineD3DVertexBuffer implementation structure (extends IWineD3DResourceImpl)
1139  */
1140 enum vbo_conversion_type {
1141     CONV_NONE               = 0,
1142     CONV_D3DCOLOR           = 1,
1143     CONV_POSITIONT          = 2,
1144     CONV_FLOAT16_2          = 3 /* Also handles FLOAT16_4 */
1145
1146     /* TODO: Add tests and support for FLOAT16_4 POSITIONT, D3DCOLOR position, other
1147      * fixed function semantics as D3DCOLOR or FLOAT16
1148      */
1149 };
1150
1151 typedef struct IWineD3DVertexBufferImpl
1152 {
1153     /* IUnknown & WineD3DResource Information     */
1154     const IWineD3DVertexBufferVtbl *lpVtbl;
1155     IWineD3DResourceClass     resource;
1156
1157     /* WineD3DVertexBuffer specifics */
1158     DWORD                     fvf;
1159
1160     /* Vertex buffer object support */
1161     GLuint                    vbo;
1162     BYTE                      Flags;
1163     LONG                      bindCount;
1164     LONG                      vbo_size;
1165     GLenum                    vbo_usage;
1166
1167     UINT                      dirtystart, dirtyend;
1168     LONG                      lockcount;
1169
1170     LONG                      declChanges, draws;
1171     /* Last description of the buffer */
1172     DWORD                     stride;       /* 0 if no conversion               */
1173     enum vbo_conversion_type  *conv_map;    /* NULL if no conversion            */
1174
1175     /* Extra load offsets, for FLOAT16 conversion */
1176     DWORD                     *conv_shift;  /* NULL if no shifted conversion    */
1177     DWORD                     conv_stride;  /* 0 if no shifted conversion       */
1178 } IWineD3DVertexBufferImpl;
1179
1180 extern const IWineD3DVertexBufferVtbl IWineD3DVertexBuffer_Vtbl;
1181
1182 #define VBFLAG_OPTIMIZED      0x01    /* Optimize has been called for the VB */
1183 #define VBFLAG_DIRTY          0x02    /* Buffer data has been modified */
1184 #define VBFLAG_HASDESC        0x04    /* A vertex description has been found */
1185 #define VBFLAG_CREATEVBO      0x08    /* Attempt to create a VBO next PreLoad */
1186
1187 /*****************************************************************************
1188  * IWineD3DIndexBuffer implementation structure (extends IWineD3DResourceImpl)
1189  */
1190 typedef struct IWineD3DIndexBufferImpl
1191 {
1192     /* IUnknown & WineD3DResource Information     */
1193     const IWineD3DIndexBufferVtbl *lpVtbl;
1194     IWineD3DResourceClass     resource;
1195
1196     GLuint                    vbo;
1197     UINT                      dirtystart, dirtyend;
1198     LONG                      lockcount;
1199
1200     /* WineD3DVertexBuffer specifics */
1201 } IWineD3DIndexBufferImpl;
1202
1203 extern const IWineD3DIndexBufferVtbl IWineD3DIndexBuffer_Vtbl;
1204
1205 /*****************************************************************************
1206  * IWineD3DBaseTexture D3D- > openGL state map lookups
1207  */
1208 #define WINED3DFUNC_NOTSUPPORTED  -2
1209 #define WINED3DFUNC_UNIMPLEMENTED -1
1210
1211 typedef enum winetexturestates {
1212     WINED3DTEXSTA_ADDRESSU       = 0,
1213     WINED3DTEXSTA_ADDRESSV       = 1,
1214     WINED3DTEXSTA_ADDRESSW       = 2,
1215     WINED3DTEXSTA_BORDERCOLOR    = 3,
1216     WINED3DTEXSTA_MAGFILTER      = 4,
1217     WINED3DTEXSTA_MINFILTER      = 5,
1218     WINED3DTEXSTA_MIPFILTER      = 6,
1219     WINED3DTEXSTA_MAXMIPLEVEL    = 7,
1220     WINED3DTEXSTA_MAXANISOTROPY  = 8,
1221     WINED3DTEXSTA_SRGBTEXTURE    = 9,
1222     WINED3DTEXSTA_ELEMENTINDEX   = 10,
1223     WINED3DTEXSTA_DMAPOFFSET     = 11,
1224     WINED3DTEXSTA_TSSADDRESSW    = 12,
1225     MAX_WINETEXTURESTATES        = 13,
1226 } winetexturestates;
1227
1228 /*****************************************************************************
1229  * IWineD3DBaseTexture implementation structure (extends IWineD3DResourceImpl)
1230  */
1231 typedef struct IWineD3DBaseTextureClass
1232 {
1233     UINT                    levels;
1234     BOOL                    dirty;
1235     UINT                    textureName;
1236     UINT                    LOD;
1237     WINED3DTEXTUREFILTERTYPE filterType;
1238     DWORD                   states[MAX_WINETEXTURESTATES];
1239     LONG                    bindCount;
1240     DWORD                   sampler;
1241     BOOL                    is_srgb;
1242     UINT                    srgb_mode_change_count;
1243     WINED3DFORMAT           shader_conversion_group;
1244     float                   pow2Matrix[16];
1245     const struct min_lookup *minMipLookup;
1246     const GLenum            *magLookup;
1247 } IWineD3DBaseTextureClass;
1248
1249 typedef struct IWineD3DBaseTextureImpl
1250 {
1251     /* IUnknown & WineD3DResource Information     */
1252     const IWineD3DBaseTextureVtbl *lpVtbl;
1253     IWineD3DResourceClass     resource;
1254     IWineD3DBaseTextureClass  baseTexture;
1255
1256 } IWineD3DBaseTextureImpl;
1257
1258 void basetexture_apply_state_changes(IWineD3DBaseTexture *iface,
1259         const DWORD texture_states[WINED3D_HIGHEST_TEXTURE_STATE + 1],
1260         const DWORD sampler_states[WINED3D_HIGHEST_SAMPLER_STATE + 1]);
1261 HRESULT basetexture_bind(IWineD3DBaseTexture *iface);
1262 void basetexture_cleanup(IWineD3DBaseTexture *iface);
1263 void basetexture_generate_mipmaps(IWineD3DBaseTexture *iface);
1264 WINED3DTEXTUREFILTERTYPE basetexture_get_autogen_filter_type(IWineD3DBaseTexture *iface);
1265 BOOL basetexture_get_dirty(IWineD3DBaseTexture *iface);
1266 DWORD basetexture_get_level_count(IWineD3DBaseTexture *iface);
1267 DWORD basetexture_get_lod(IWineD3DBaseTexture *iface);
1268 HRESULT basetexture_set_autogen_filter_type(IWineD3DBaseTexture *iface, WINED3DTEXTUREFILTERTYPE filter_type);
1269 BOOL basetexture_set_dirty(IWineD3DBaseTexture *iface, BOOL dirty);
1270 DWORD basetexture_set_lod(IWineD3DBaseTexture *iface, DWORD new_lod);
1271 void basetexture_unload(IWineD3DBaseTexture *iface);
1272
1273 /*****************************************************************************
1274  * IWineD3DTexture implementation structure (extends IWineD3DBaseTextureImpl)
1275  */
1276 typedef struct IWineD3DTextureImpl
1277 {
1278     /* IUnknown & WineD3DResource/WineD3DBaseTexture Information     */
1279     const IWineD3DTextureVtbl *lpVtbl;
1280     IWineD3DResourceClass     resource;
1281     IWineD3DBaseTextureClass  baseTexture;
1282
1283     /* IWineD3DTexture */
1284     IWineD3DSurface          *surfaces[MAX_LEVELS];
1285     
1286     UINT                      width;
1287     UINT                      height;
1288     UINT                      target;
1289     BOOL                      cond_np2;
1290
1291 } IWineD3DTextureImpl;
1292
1293 extern const IWineD3DTextureVtbl IWineD3DTexture_Vtbl;
1294
1295 /*****************************************************************************
1296  * IWineD3DCubeTexture implementation structure (extends IWineD3DBaseTextureImpl)
1297  */
1298 typedef struct IWineD3DCubeTextureImpl
1299 {
1300     /* IUnknown & WineD3DResource/WineD3DBaseTexture Information     */
1301     const IWineD3DCubeTextureVtbl *lpVtbl;
1302     IWineD3DResourceClass     resource;
1303     IWineD3DBaseTextureClass  baseTexture;
1304
1305     /* IWineD3DCubeTexture */
1306     IWineD3DSurface          *surfaces[6][MAX_LEVELS];
1307 } IWineD3DCubeTextureImpl;
1308
1309 extern const IWineD3DCubeTextureVtbl IWineD3DCubeTexture_Vtbl;
1310
1311 typedef struct _WINED3DVOLUMET_DESC
1312 {
1313     UINT                    Width;
1314     UINT                    Height;
1315     UINT                    Depth;
1316 } WINED3DVOLUMET_DESC;
1317
1318 /*****************************************************************************
1319  * IWineD3DVolume implementation structure (extends IUnknown)
1320  */
1321 typedef struct IWineD3DVolumeImpl
1322 {
1323     /* IUnknown & WineD3DResource fields */
1324     const IWineD3DVolumeVtbl  *lpVtbl;
1325     IWineD3DResourceClass      resource;
1326
1327     /* WineD3DVolume Information */
1328     WINED3DVOLUMET_DESC      currentDesc;
1329     IWineD3DBase            *container;
1330     UINT                    bytesPerPixel;
1331
1332     BOOL                    lockable;
1333     BOOL                    locked;
1334     WINED3DBOX              lockedBox;
1335     WINED3DBOX              dirtyBox;
1336     BOOL                    dirty;
1337
1338
1339 } IWineD3DVolumeImpl;
1340
1341 extern const IWineD3DVolumeVtbl IWineD3DVolume_Vtbl;
1342
1343 /*****************************************************************************
1344  * IWineD3DVolumeTexture implementation structure (extends IWineD3DBaseTextureImpl)
1345  */
1346 typedef struct IWineD3DVolumeTextureImpl
1347 {
1348     /* IUnknown & WineD3DResource/WineD3DBaseTexture Information     */
1349     const IWineD3DVolumeTextureVtbl *lpVtbl;
1350     IWineD3DResourceClass     resource;
1351     IWineD3DBaseTextureClass  baseTexture;
1352
1353     /* IWineD3DVolumeTexture */
1354     IWineD3DVolume           *volumes[MAX_LEVELS];
1355 } IWineD3DVolumeTextureImpl;
1356
1357 extern const IWineD3DVolumeTextureVtbl IWineD3DVolumeTexture_Vtbl;
1358
1359 typedef struct _WINED3DSURFACET_DESC
1360 {
1361     WINED3DMULTISAMPLE_TYPE MultiSampleType;
1362     DWORD                   MultiSampleQuality;
1363     UINT                    Width;
1364     UINT                    Height;
1365 } WINED3DSURFACET_DESC;
1366
1367 /*****************************************************************************
1368  * Structure for DIB Surfaces (GetDC and GDI surfaces)
1369  */
1370 typedef struct wineD3DSurface_DIB {
1371     HBITMAP DIBsection;
1372     void* bitmap_data;
1373     UINT bitmap_size;
1374     HGDIOBJ holdbitmap;
1375     BOOL client_memory;
1376 } wineD3DSurface_DIB;
1377
1378 typedef struct {
1379     struct list entry;
1380     GLuint id;
1381     UINT width;
1382     UINT height;
1383 } renderbuffer_entry_t;
1384
1385 struct fbo_entry
1386 {
1387     struct list entry;
1388     IWineD3DSurface **render_targets;
1389     IWineD3DSurface *depth_stencil;
1390     BOOL attached;
1391     GLuint id;
1392 };
1393
1394 /*****************************************************************************
1395  * IWineD3DClipp implementation structure
1396  */
1397 typedef struct IWineD3DClipperImpl
1398 {
1399     const IWineD3DClipperVtbl *lpVtbl;
1400     LONG ref;
1401
1402     IUnknown *Parent;
1403     HWND hWnd;
1404 } IWineD3DClipperImpl;
1405
1406
1407 /*****************************************************************************
1408  * IWineD3DSurface implementation structure
1409  */
1410 struct IWineD3DSurfaceImpl
1411 {
1412     /* IUnknown & IWineD3DResource Information     */
1413     const IWineD3DSurfaceVtbl *lpVtbl;
1414     IWineD3DResourceClass     resource;
1415
1416     /* IWineD3DSurface fields */
1417     IWineD3DBase              *container;
1418     WINED3DSURFACET_DESC      currentDesc;
1419     IWineD3DPaletteImpl       *palette; /* D3D7 style palette handling */
1420     PALETTEENTRY              *palette9; /* D3D8/9 style palette handling */
1421
1422     UINT                      bytesPerPixel;
1423
1424     /* TODO: move this off into a management class(maybe!) */
1425     DWORD                      Flags;
1426
1427     UINT                      pow2Width;
1428     UINT                      pow2Height;
1429     float                     heightscale;
1430
1431     /* A method to retrieve the drawable size. Not in the Vtable to make it changeable */
1432     void (*get_drawable_size)(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
1433
1434     /* Oversized texture */
1435     RECT                      glRect;
1436
1437     /* PBO */
1438     GLuint                    pbo;
1439
1440     RECT                      lockedRect;
1441     RECT                      dirtyRect;
1442     int                       lockCount;
1443 #define MAXLOCKCOUNT          50 /* After this amount of locks do not free the sysmem copy */
1444
1445     glDescriptor              glDescription;
1446     BOOL                      srgb;
1447
1448     /* For GetDC */
1449     wineD3DSurface_DIB        dib;
1450     HDC                       hDC;
1451
1452     /* Color keys for DDraw */
1453     WINEDDCOLORKEY            DestBltCKey;
1454     WINEDDCOLORKEY            DestOverlayCKey;
1455     WINEDDCOLORKEY            SrcOverlayCKey;
1456     WINEDDCOLORKEY            SrcBltCKey;
1457     DWORD                     CKeyFlags;
1458
1459     WINEDDCOLORKEY            glCKey;
1460
1461     struct list               renderbuffers;
1462     renderbuffer_entry_t      *current_renderbuffer;
1463
1464     /* DirectDraw clippers */
1465     IWineD3DClipper           *clipper;
1466
1467     /* DirectDraw Overlay handling */
1468     RECT                      overlay_srcrect;
1469     RECT                      overlay_destrect;
1470     IWineD3DSurfaceImpl       *overlay_dest;
1471     struct list               overlays;
1472     struct list               overlay_entry;
1473 };
1474
1475 extern const IWineD3DSurfaceVtbl IWineD3DSurface_Vtbl;
1476 extern const IWineD3DSurfaceVtbl IWineGDISurface_Vtbl;
1477
1478 /* Predeclare the shared Surface functions */
1479 HRESULT WINAPI IWineD3DBaseSurfaceImpl_QueryInterface(IWineD3DSurface *iface, REFIID riid, LPVOID *ppobj);
1480 ULONG WINAPI IWineD3DBaseSurfaceImpl_AddRef(IWineD3DSurface *iface);
1481 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetParent(IWineD3DSurface *iface, IUnknown **pParent);
1482 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetDevice(IWineD3DSurface *iface, IWineD3DDevice** ppDevice);
1483 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetPrivateData(IWineD3DSurface *iface, REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags);
1484 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetPrivateData(IWineD3DSurface *iface, REFGUID refguid, void* pData, DWORD* pSizeOfData);
1485 HRESULT WINAPI IWineD3DBaseSurfaceImpl_FreePrivateData(IWineD3DSurface *iface, REFGUID refguid);
1486 DWORD   WINAPI IWineD3DBaseSurfaceImpl_SetPriority(IWineD3DSurface *iface, DWORD PriorityNew);
1487 DWORD   WINAPI IWineD3DBaseSurfaceImpl_GetPriority(IWineD3DSurface *iface);
1488 WINED3DRESOURCETYPE WINAPI IWineD3DBaseSurfaceImpl_GetType(IWineD3DSurface *iface);
1489 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetContainer(IWineD3DSurface* iface, REFIID riid, void** ppContainer);
1490 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetDesc(IWineD3DSurface *iface, WINED3DSURFACE_DESC *pDesc);
1491 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetBltStatus(IWineD3DSurface *iface, DWORD Flags);
1492 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetFlipStatus(IWineD3DSurface *iface, DWORD Flags);
1493 HRESULT WINAPI IWineD3DBaseSurfaceImpl_IsLost(IWineD3DSurface *iface);
1494 HRESULT WINAPI IWineD3DBaseSurfaceImpl_Restore(IWineD3DSurface *iface);
1495 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetPalette(IWineD3DSurface *iface, IWineD3DPalette **Pal);
1496 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetPalette(IWineD3DSurface *iface, IWineD3DPalette *Pal);
1497 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetColorKey(IWineD3DSurface *iface, DWORD Flags, const WINEDDCOLORKEY *CKey);
1498 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetContainer(IWineD3DSurface *iface, IWineD3DBase *container);
1499 DWORD WINAPI IWineD3DBaseSurfaceImpl_GetPitch(IWineD3DSurface *iface);
1500 HRESULT WINAPI IWineD3DBaseSurfaceImpl_RealizePalette(IWineD3DSurface *iface);
1501 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetOverlayPosition(IWineD3DSurface *iface, LONG X, LONG Y);
1502 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetOverlayPosition(IWineD3DSurface *iface, LONG *X, LONG *Y);
1503 HRESULT WINAPI IWineD3DBaseSurfaceImpl_UpdateOverlayZOrder(IWineD3DSurface *iface, DWORD Flags, IWineD3DSurface *Ref);
1504 HRESULT WINAPI IWineD3DBaseSurfaceImpl_UpdateOverlay(IWineD3DSurface *iface, const RECT *SrcRect,
1505         IWineD3DSurface *DstSurface, const RECT *DstRect, DWORD Flags, const WINEDDOVERLAYFX *FX);
1506 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetClipper(IWineD3DSurface *iface, IWineD3DClipper *clipper);
1507 HRESULT WINAPI IWineD3DBaseSurfaceImpl_GetClipper(IWineD3DSurface *iface, IWineD3DClipper **clipper);
1508 HRESULT WINAPI IWineD3DBaseSurfaceImpl_SetFormat(IWineD3DSurface *iface, WINED3DFORMAT format);
1509 HRESULT IWineD3DBaseSurfaceImpl_CreateDIBSection(IWineD3DSurface *iface);
1510 HRESULT WINAPI IWineD3DBaseSurfaceImpl_Blt(IWineD3DSurface *iface, const RECT *DestRect, IWineD3DSurface *SrcSurface,
1511         const RECT *SrcRect, DWORD Flags, const WINEDDBLTFX *DDBltFx, WINED3DTEXTUREFILTERTYPE Filter);
1512 HRESULT WINAPI IWineD3DBaseSurfaceImpl_BltFast(IWineD3DSurface *iface, DWORD dstx, DWORD dsty,
1513         IWineD3DSurface *Source, const RECT *rsrc, DWORD trans);
1514 HRESULT WINAPI IWineD3DBaseSurfaceImpl_LockRect(IWineD3DSurface *iface, WINED3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags);
1515 void WINAPI IWineD3DBaseSurfaceImpl_BindTexture(IWineD3DSurface *iface);
1516 const void *WINAPI IWineD3DBaseSurfaceImpl_GetData(IWineD3DSurface *iface);
1517
1518 void get_drawable_size_swapchain(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
1519 void get_drawable_size_backbuffer(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
1520 void get_drawable_size_pbuffer(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
1521 void get_drawable_size_fbo(IWineD3DSurfaceImpl *This, UINT *width, UINT *height);
1522
1523 void flip_surface(IWineD3DSurfaceImpl *front, IWineD3DSurfaceImpl *back);
1524
1525 /* Surface flags: */
1526 #define SFLAG_OVERSIZE      0x00000001 /* Surface is bigger than gl size, blts only */
1527 #define SFLAG_CONVERTED     0x00000002 /* Converted for color keying or Palettized */
1528 #define SFLAG_DIBSECTION    0x00000004 /* Has a DIB section attached for GetDC */
1529 #define SFLAG_LOCKABLE      0x00000008 /* Surface can be locked */
1530 #define SFLAG_DISCARD       0x00000010 /* ??? */
1531 #define SFLAG_LOCKED        0x00000020 /* Surface is locked atm */
1532 #define SFLAG_INTEXTURE     0x00000040 /* The GL texture contains the newest surface content */
1533 #define SFLAG_INDRAWABLE    0x00000080 /* The gl drawable contains the most up to date data */
1534 #define SFLAG_INSYSMEM      0x00000100 /* The system memory copy is most up to date */
1535 #define SFLAG_NONPOW2       0x00000200 /* Surface sizes are not a power of 2 */
1536 #define SFLAG_DYNLOCK       0x00000400 /* Surface is often locked by the app */
1537 #define SFLAG_DYNCHANGE     0x00000C00 /* Surface contents are changed very often, implies DYNLOCK */
1538 #define SFLAG_DCINUSE       0x00001000 /* Set between GetDC and ReleaseDC calls */
1539 #define SFLAG_LOST          0x00002000 /* Surface lost flag for DDraw */
1540 #define SFLAG_USERPTR       0x00004000 /* The application allocated the memory for this surface */
1541 #define SFLAG_GLCKEY        0x00008000 /* The gl texture was created with a color key */
1542 #define SFLAG_CLIENT        0x00010000 /* GL_APPLE_client_storage is used on that texture */
1543 #define SFLAG_ALLOCATED     0x00020000 /* A gl texture is allocated for this surface */
1544 #define SFLAG_PBO           0x00040000 /* Has a PBO attached for speeding up data transfers for dynamically locked surfaces */
1545 #define SFLAG_NORMCOORD     0x00080000 /* Set if the GL texture coords are normalized(non-texture rectangle) */
1546 #define SFLAG_DS_ONSCREEN   0x00100000 /* Is a depth stencil, last modified onscreen */
1547 #define SFLAG_DS_OFFSCREEN  0x00200000 /* Is a depth stencil, last modified offscreen */
1548 #define SFLAG_INOVERLAYDRAW 0x00400000 /* Overlay drawing is in progress. Recursion prevention */
1549
1550 /* In some conditions the surface memory must not be freed:
1551  * SFLAG_OVERSIZE: Not all data can be kept in GL
1552  * SFLAG_CONVERTED: Converting the data back would take too long
1553  * SFLAG_DIBSECTION: The dib code manages the memory
1554  * SFLAG_LOCKED: The app requires access to the surface data
1555  * SFLAG_DYNLOCK: Avoid freeing the data for performance
1556  * SFLAG_DYNCHANGE: Same reason as DYNLOCK
1557  * SFLAG_PBO: PBOs don't use 'normal' memory. It is either allocated by the driver or must be NULL.
1558  * SFLAG_CLIENT: OpenGL uses our memory as backup
1559  */
1560 #define SFLAG_DONOTFREE     (SFLAG_OVERSIZE   | \
1561                              SFLAG_CONVERTED  | \
1562                              SFLAG_DIBSECTION | \
1563                              SFLAG_LOCKED     | \
1564                              SFLAG_DYNLOCK    | \
1565                              SFLAG_DYNCHANGE  | \
1566                              SFLAG_USERPTR    | \
1567                              SFLAG_PBO        | \
1568                              SFLAG_CLIENT)
1569
1570 #define SFLAG_LOCATIONS     (SFLAG_INSYSMEM   | \
1571                              SFLAG_INTEXTURE  | \
1572                              SFLAG_INDRAWABLE)
1573
1574 #define SFLAG_DS_LOCATIONS  (SFLAG_DS_ONSCREEN | \
1575                              SFLAG_DS_OFFSCREEN)
1576 #define SFLAG_DS_DISCARDED   SFLAG_DS_LOCATIONS
1577
1578 BOOL CalculateTexRect(IWineD3DSurfaceImpl *This, RECT *Rect, float glTexCoord[4]);
1579
1580 typedef enum {
1581     NO_CONVERSION,
1582     CONVERT_PALETTED,
1583     CONVERT_PALETTED_CK,
1584     CONVERT_CK_565,
1585     CONVERT_CK_5551,
1586     CONVERT_CK_4444,
1587     CONVERT_CK_4444_ARGB,
1588     CONVERT_CK_1555,
1589     CONVERT_555,
1590     CONVERT_CK_RGB24,
1591     CONVERT_CK_8888,
1592     CONVERT_CK_8888_ARGB,
1593     CONVERT_RGB32_888,
1594     CONVERT_V8U8,
1595     CONVERT_L6V5U5,
1596     CONVERT_X8L8V8U8,
1597     CONVERT_Q8W8V8U8,
1598     CONVERT_V16U16,
1599     CONVERT_A4L4,
1600     CONVERT_R32F,
1601     CONVERT_R16F,
1602     CONVERT_G16R16,
1603 } CONVERT_TYPES;
1604
1605 HRESULT d3dfmt_get_conv(IWineD3DSurfaceImpl *This, BOOL need_alpha_ck, BOOL use_texturing, GLenum *format, GLenum *internal, GLenum *type, CONVERT_TYPES *convert, int *target_bpp, BOOL srgb_mode);
1606
1607 BOOL palette9_changed(IWineD3DSurfaceImpl *This);
1608
1609 /*****************************************************************************
1610  * IWineD3DVertexDeclaration implementation structure
1611  */
1612 typedef struct attrib_declaration {
1613     DWORD usage;
1614     DWORD idx;
1615 } attrib_declaration;
1616
1617 #define MAX_ATTRIBS 16
1618
1619 typedef struct IWineD3DVertexDeclarationImpl {
1620     /* IUnknown  Information */
1621     const IWineD3DVertexDeclarationVtbl *lpVtbl;
1622     LONG                    ref;
1623
1624     IUnknown                *parent;
1625     IWineD3DDeviceImpl      *wineD3DDevice;
1626
1627     WINED3DVERTEXELEMENT    *pDeclarationWine;
1628     BOOL                    *ffp_valid;
1629     UINT                    declarationWNumElements;
1630
1631     DWORD                   streams[MAX_STREAMS];
1632     UINT                    num_streams;
1633     BOOL                    position_transformed;
1634     BOOL                    half_float_conv_needed;
1635
1636     /* Ordered array of declaration types that need swizzling in a vshader */
1637     attrib_declaration      swizzled_attribs[MAX_ATTRIBS];
1638     UINT                    num_swizzled_attribs;
1639 } IWineD3DVertexDeclarationImpl;
1640
1641 extern const IWineD3DVertexDeclarationVtbl IWineD3DVertexDeclaration_Vtbl;
1642
1643 /*****************************************************************************
1644  * IWineD3DStateBlock implementation structure
1645  */
1646
1647 /* Internal state Block for Begin/End/Capture/Create/Apply info  */
1648 /*   Note: Very long winded but gl Lists are not flexible enough */
1649 /*   to resolve everything we need, so doing it manually for now */
1650 typedef struct SAVEDSTATES {
1651         BOOL                      indices;
1652         BOOL                      material;
1653         BOOL                      fvf;
1654         BOOL                      streamSource[MAX_STREAMS];
1655         BOOL                      streamFreq[MAX_STREAMS];
1656         BOOL                      textures[MAX_COMBINED_SAMPLERS];
1657         BOOL                      transform[HIGHEST_TRANSFORMSTATE + 1];
1658         BOOL                      viewport;
1659         BOOL                      renderState[WINEHIGHEST_RENDER_STATE + 1];
1660         BOOL                      textureState[MAX_TEXTURES][WINED3D_HIGHEST_TEXTURE_STATE + 1];
1661         BOOL                      samplerState[MAX_COMBINED_SAMPLERS][WINED3D_HIGHEST_SAMPLER_STATE + 1];
1662         BOOL                      clipplane[MAX_CLIPPLANES];
1663         BOOL                      vertexDecl;
1664         BOOL                      pixelShader;
1665         BOOL                      pixelShaderConstantsB[MAX_CONST_B];
1666         BOOL                      pixelShaderConstantsI[MAX_CONST_I];
1667         BOOL                     *pixelShaderConstantsF;
1668         BOOL                      vertexShader;
1669         BOOL                      vertexShaderConstantsB[MAX_CONST_B];
1670         BOOL                      vertexShaderConstantsI[MAX_CONST_I];
1671         BOOL                     *vertexShaderConstantsF;
1672         BOOL                      scissorRect;
1673 } SAVEDSTATES;
1674
1675 typedef struct {
1676     struct  list entry;
1677     DWORD   count;
1678     DWORD   idx[13];
1679 } constants_entry;
1680
1681 struct StageState {
1682     DWORD stage;
1683     DWORD state;
1684 };
1685
1686 struct IWineD3DStateBlockImpl
1687 {
1688     /* IUnknown fields */
1689     const IWineD3DStateBlockVtbl *lpVtbl;
1690     LONG                      ref;     /* Note: Ref counting not required */
1691
1692     /* IWineD3DStateBlock information */
1693     IUnknown                 *parent;
1694     IWineD3DDeviceImpl       *wineD3DDevice;
1695     WINED3DSTATEBLOCKTYPE     blockType;
1696
1697     /* Array indicating whether things have been set or changed */
1698     SAVEDSTATES               changed;
1699     struct list               set_vconstantsF;
1700     struct list               set_pconstantsF;
1701
1702     /* Drawing - Vertex Shader or FVF related */
1703     DWORD                     fvf;
1704     /* Vertex Shader Declaration */
1705     IWineD3DVertexDeclaration *vertexDecl;
1706
1707     IWineD3DVertexShader      *vertexShader;
1708
1709     /* Vertex Shader Constants */
1710     BOOL                       vertexShaderConstantB[MAX_CONST_B];
1711     INT                        vertexShaderConstantI[MAX_CONST_I * 4];
1712     float                     *vertexShaderConstantF;
1713
1714     /* Stream Source */
1715     BOOL                      streamIsUP;
1716     UINT                      streamStride[MAX_STREAMS];
1717     UINT                      streamOffset[MAX_STREAMS + 1 /* tesselated pseudo-stream */ ];
1718     IWineD3DVertexBuffer     *streamSource[MAX_STREAMS];
1719     UINT                      streamFreq[MAX_STREAMS + 1];
1720     UINT                      streamFlags[MAX_STREAMS + 1];     /*0 | WINED3DSTREAMSOURCE_INSTANCEDATA | WINED3DSTREAMSOURCE_INDEXEDDATA  */
1721
1722     /* Indices */
1723     IWineD3DIndexBuffer*      pIndexData;
1724     INT                       baseVertexIndex;
1725     INT                       loadBaseVertexIndex; /* non-indexed drawing needs 0 here, indexed baseVertexIndex */
1726
1727     /* Transform */
1728     WINED3DMATRIX             transforms[HIGHEST_TRANSFORMSTATE + 1];
1729
1730     /* Light hashmap . Collisions are handled using standard wine double linked lists */
1731 #define LIGHTMAP_SIZE 43 /* Use of a prime number recommended. Set to 1 for a linked list! */
1732 #define LIGHTMAP_HASHFUNC(x) ((x) % LIGHTMAP_SIZE) /* Primitive and simple function */
1733     struct list               lightMap[LIGHTMAP_SIZE]; /* Mashmap containing the lights */
1734     PLIGHTINFOEL             *activeLights[MAX_ACTIVE_LIGHTS]; /* Map of opengl lights to d3d lights */
1735
1736     /* Clipping */
1737     double                    clipplane[MAX_CLIPPLANES][4];
1738     WINED3DCLIPSTATUS         clip_status;
1739
1740     /* ViewPort */
1741     WINED3DVIEWPORT           viewport;
1742
1743     /* Material */
1744     WINED3DMATERIAL           material;
1745
1746     /* Pixel Shader */
1747     IWineD3DPixelShader      *pixelShader;
1748
1749     /* Pixel Shader Constants */
1750     BOOL                       pixelShaderConstantB[MAX_CONST_B];
1751     INT                        pixelShaderConstantI[MAX_CONST_I * 4];
1752     float                     *pixelShaderConstantF;
1753
1754     /* RenderState */
1755     DWORD                     renderState[WINEHIGHEST_RENDER_STATE + 1];
1756
1757     /* Texture */
1758     IWineD3DBaseTexture      *textures[MAX_COMBINED_SAMPLERS];
1759     int                       textureDimensions[MAX_COMBINED_SAMPLERS];
1760
1761     /* Texture State Stage */
1762     DWORD                     textureState[MAX_TEXTURES][WINED3D_HIGHEST_TEXTURE_STATE + 1];
1763     DWORD                     lowest_disabled_stage;
1764     /* Sampler States */
1765     DWORD                     samplerState[MAX_COMBINED_SAMPLERS][WINED3D_HIGHEST_SAMPLER_STATE + 1];
1766
1767     /* Scissor test rectangle */
1768     RECT                      scissorRect;
1769
1770     /* Contained state management */
1771     DWORD                     contained_render_states[WINEHIGHEST_RENDER_STATE + 1];
1772     unsigned int              num_contained_render_states;
1773     DWORD                     contained_transform_states[HIGHEST_TRANSFORMSTATE + 1];
1774     unsigned int              num_contained_transform_states;
1775     DWORD                     contained_vs_consts_i[MAX_CONST_I];
1776     unsigned int              num_contained_vs_consts_i;
1777     DWORD                     contained_vs_consts_b[MAX_CONST_B];
1778     unsigned int              num_contained_vs_consts_b;
1779     DWORD                     *contained_vs_consts_f;
1780     unsigned int              num_contained_vs_consts_f;
1781     DWORD                     contained_ps_consts_i[MAX_CONST_I];
1782     unsigned int              num_contained_ps_consts_i;
1783     DWORD                     contained_ps_consts_b[MAX_CONST_B];
1784     unsigned int              num_contained_ps_consts_b;
1785     DWORD                     *contained_ps_consts_f;
1786     unsigned int              num_contained_ps_consts_f;
1787     struct StageState         contained_tss_states[MAX_TEXTURES * (WINED3D_HIGHEST_TEXTURE_STATE)];
1788     unsigned int              num_contained_tss_states;
1789     struct StageState         contained_sampler_states[MAX_COMBINED_SAMPLERS * WINED3D_HIGHEST_SAMPLER_STATE];
1790     unsigned int              num_contained_sampler_states;
1791 };
1792
1793 extern void stateblock_savedstates_set(
1794     IWineD3DStateBlock* iface,
1795     SAVEDSTATES* states,
1796     BOOL value);
1797
1798 extern void stateblock_savedstates_copy(IWineD3DStateBlock *iface, SAVEDSTATES *dest, const SAVEDSTATES *source);
1799
1800 extern void stateblock_copy(
1801     IWineD3DStateBlock* destination,
1802     IWineD3DStateBlock* source);
1803
1804 extern const IWineD3DStateBlockVtbl IWineD3DStateBlock_Vtbl;
1805
1806 /* Direct3D terminology with little modifications. We do not have an issued state
1807  * because only the driver knows about it, but we have a created state because d3d
1808  * allows GetData on a created issue, but opengl doesn't
1809  */
1810 enum query_state {
1811     QUERY_CREATED,
1812     QUERY_SIGNALLED,
1813     QUERY_BUILDING
1814 };
1815 /*****************************************************************************
1816  * IWineD3DQueryImpl implementation structure (extends IUnknown)
1817  */
1818 typedef struct IWineD3DQueryImpl
1819 {
1820     const IWineD3DQueryVtbl  *lpVtbl;
1821     LONG                      ref;     /* Note: Ref counting not required */
1822     
1823     IUnknown                 *parent;
1824     /*TODO: replace with iface usage */
1825 #if 0
1826     IWineD3DDevice         *wineD3DDevice;
1827 #else
1828     IWineD3DDeviceImpl       *wineD3DDevice;
1829 #endif
1830
1831     /* IWineD3DQuery fields */
1832     enum query_state         state;
1833     WINED3DQUERYTYPE         type;
1834     /* TODO: Think about using a IUnknown instead of a void* */
1835     void                     *extendedData;
1836     
1837   
1838 } IWineD3DQueryImpl;
1839
1840 extern const IWineD3DQueryVtbl IWineD3DQuery_Vtbl;
1841 extern const IWineD3DQueryVtbl IWineD3DEventQuery_Vtbl;
1842 extern const IWineD3DQueryVtbl IWineD3DOcclusionQuery_Vtbl;
1843
1844 /* Datastructures for IWineD3DQueryImpl.extendedData */
1845 typedef struct  WineQueryOcclusionData {
1846     GLuint  queryId;
1847     WineD3DContext *ctx;
1848 } WineQueryOcclusionData;
1849
1850 typedef struct  WineQueryEventData {
1851     GLuint  fenceId;
1852     WineD3DContext *ctx;
1853 } WineQueryEventData;
1854
1855 /*****************************************************************************
1856  * IWineD3DSwapChainImpl implementation structure (extends IUnknown)
1857  */
1858
1859 typedef struct IWineD3DSwapChainImpl
1860 {
1861     /*IUnknown part*/
1862     const IWineD3DSwapChainVtbl *lpVtbl;
1863     LONG                      ref;     /* Note: Ref counting not required */
1864
1865     IUnknown                 *parent;
1866     IWineD3DDeviceImpl       *wineD3DDevice;
1867
1868     /* IWineD3DSwapChain fields */
1869     IWineD3DSurface         **backBuffer;
1870     IWineD3DSurface          *frontBuffer;
1871     WINED3DPRESENT_PARAMETERS presentParms;
1872     DWORD                     orig_width, orig_height;
1873     WINED3DFORMAT             orig_fmt;
1874     WINED3DGAMMARAMP          orig_gamma;
1875
1876     long prev_time, frames;   /* Performance tracking */
1877     unsigned int vSyncCounter;
1878
1879     WineD3DContext        **context; /* Later a array for multithreading */
1880     unsigned int            num_contexts;
1881
1882     HWND                    win_handle;
1883 } IWineD3DSwapChainImpl;
1884
1885 extern const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl;
1886 const IWineD3DSwapChainVtbl IWineGDISwapChain_Vtbl;
1887 void x11_copy_to_screen(IWineD3DSwapChainImpl *This, const RECT *rc);
1888
1889 HRESULT WINAPI IWineD3DBaseSwapChainImpl_QueryInterface(IWineD3DSwapChain *iface, REFIID riid, LPVOID *ppobj);
1890 ULONG WINAPI IWineD3DBaseSwapChainImpl_AddRef(IWineD3DSwapChain *iface);
1891 ULONG WINAPI IWineD3DBaseSwapChainImpl_Release(IWineD3DSwapChain *iface);
1892 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetParent(IWineD3DSwapChain *iface, IUnknown ** ppParent);
1893 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetFrontBufferData(IWineD3DSwapChain *iface, IWineD3DSurface *pDestSurface);
1894 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetBackBuffer(IWineD3DSwapChain *iface, UINT iBackBuffer, WINED3DBACKBUFFER_TYPE Type, IWineD3DSurface **ppBackBuffer);
1895 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetRasterStatus(IWineD3DSwapChain *iface, WINED3DRASTER_STATUS *pRasterStatus);
1896 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetDisplayMode(IWineD3DSwapChain *iface, WINED3DDISPLAYMODE*pMode);
1897 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetDevice(IWineD3DSwapChain *iface, IWineD3DDevice**ppDevice);
1898 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetPresentParameters(IWineD3DSwapChain *iface, WINED3DPRESENT_PARAMETERS *pPresentationParameters);
1899 HRESULT WINAPI IWineD3DBaseSwapChainImpl_SetGammaRamp(IWineD3DSwapChain *iface, DWORD Flags, CONST WINED3DGAMMARAMP *pRamp);
1900 HRESULT WINAPI IWineD3DBaseSwapChainImpl_GetGammaRamp(IWineD3DSwapChain *iface, WINED3DGAMMARAMP *pRamp);
1901
1902 WineD3DContext *IWineD3DSwapChainImpl_CreateContextForThread(IWineD3DSwapChain *iface);
1903
1904 /*****************************************************************************
1905  * Utility function prototypes 
1906  */
1907
1908 /* Trace routines */
1909 const char* debug_d3dformat(WINED3DFORMAT fmt);
1910 const char* debug_d3ddevicetype(WINED3DDEVTYPE devtype);
1911 const char* debug_d3dresourcetype(WINED3DRESOURCETYPE res);
1912 const char* debug_d3dusage(DWORD usage);
1913 const char* debug_d3dusagequery(DWORD usagequery);
1914 const char* debug_d3ddeclmethod(WINED3DDECLMETHOD method);
1915 const char* debug_d3ddecltype(WINED3DDECLTYPE type);
1916 const char* debug_d3ddeclusage(BYTE usage);
1917 const char* debug_d3dprimitivetype(WINED3DPRIMITIVETYPE PrimitiveType);
1918 const char* debug_d3drenderstate(DWORD state);
1919 const char* debug_d3dsamplerstate(DWORD state);
1920 const char* debug_d3dtexturefiltertype(WINED3DTEXTUREFILTERTYPE filter_type);
1921 const char* debug_d3dtexturestate(DWORD state);
1922 const char* debug_d3dtstype(WINED3DTRANSFORMSTATETYPE tstype);
1923 const char* debug_d3dpool(WINED3DPOOL pool);
1924 const char *debug_fbostatus(GLenum status);
1925 const char *debug_glerror(GLenum error);
1926 const char *debug_d3dbasis(WINED3DBASISTYPE basis);
1927 const char *debug_d3ddegree(WINED3DDEGREETYPE order);
1928 const char* debug_d3dtop(WINED3DTEXTUREOP d3dtop);
1929
1930 /* Routines for GL <-> D3D values */
1931 GLenum StencilOp(DWORD op);
1932 GLenum CompareFunc(DWORD func);
1933 BOOL is_invalid_op(IWineD3DDeviceImpl *This, int stage, WINED3DTEXTUREOP op, DWORD arg1, DWORD arg2, DWORD arg3);
1934 void   set_tex_op_nvrc(IWineD3DDevice *iface, BOOL is_alpha, int stage, WINED3DTEXTUREOP op, DWORD arg1, DWORD arg2, DWORD arg3, INT texture_idx, DWORD dst);
1935 void   set_texture_matrix(const float *smat, DWORD flags, BOOL calculatedCoords, BOOL transformed, DWORD coordtype, BOOL ffp_can_disable_proj);
1936 void texture_activate_dimensions(DWORD stage, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
1937 void sampler_texdim(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
1938 void tex_alphaop(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
1939 void apply_pixelshader(DWORD state, IWineD3DStateBlockImpl *stateblock, WineD3DContext *context);
1940
1941 void surface_force_reload(IWineD3DSurface *iface);
1942 GLenum surface_get_gl_buffer(IWineD3DSurface *iface, IWineD3DSwapChain *swapchain);
1943 void surface_load_ds_location(IWineD3DSurface *iface, DWORD location);
1944 void surface_modify_ds_location(IWineD3DSurface *iface, DWORD location);
1945 void surface_set_compatible_renderbuffer(IWineD3DSurface *iface, unsigned int width, unsigned int height);
1946 void surface_set_texture_name(IWineD3DSurface *iface, GLuint name);
1947 void surface_set_texture_target(IWineD3DSurface *iface, GLenum target);
1948
1949 BOOL getColorBits(WINED3DFORMAT fmt, short *redSize, short *greenSize, short *blueSize, short *alphaSize, short *totalSize);
1950 BOOL getDepthStencilBits(WINED3DFORMAT fmt, short *depthSize, short *stencilSize);
1951
1952 /* Math utils */
1953 void multiply_matrix(WINED3DMATRIX *dest, const WINED3DMATRIX *src1, const WINED3DMATRIX *src2);
1954 unsigned int count_bits(unsigned int mask);
1955
1956 /*****************************************************************************
1957  * To enable calling of inherited functions, requires prototypes 
1958  *
1959  * Note: Only require classes which are subclassed, ie resource, basetexture, 
1960  */
1961
1962     /* IWineD3DVertexBuffer */
1963     extern const BYTE *IWineD3DVertexBufferImpl_GetMemory(IWineD3DVertexBuffer* iface, DWORD iOffset, GLint *vbo);
1964
1965 /* TODO: Make this dynamic, based on shader limits ? */
1966 #define MAX_REG_ADDR 1
1967 #define MAX_REG_TEMP 32
1968 #define MAX_REG_TEXCRD 8
1969 #define MAX_REG_INPUT 12
1970 #define MAX_REG_OUTPUT 12
1971 #define MAX_CONST_I 16
1972 #define MAX_CONST_B 16
1973
1974 /* FIXME: This needs to go up to 2048 for
1975  * Shader model 3 according to msdn (and for software shaders) */
1976 #define MAX_LABELS 16
1977
1978 typedef struct semantic {
1979     DWORD usage;
1980     DWORD reg;
1981 } semantic;
1982
1983 typedef struct local_constant {
1984     struct list entry;
1985     unsigned int idx;
1986     DWORD value[4];
1987 } local_constant;
1988
1989 typedef struct shader_reg_maps {
1990
1991     char texcoord[MAX_REG_TEXCRD];          /* pixel < 3.0 */
1992     char temporary[MAX_REG_TEMP];           /* pixel, vertex */
1993     char address[MAX_REG_ADDR];             /* vertex */
1994     char packed_input[MAX_REG_INPUT];       /* pshader >= 3.0 */
1995     char packed_output[MAX_REG_OUTPUT];     /* vertex >= 3.0 */
1996     char attributes[MAX_ATTRIBS];           /* vertex */
1997     char labels[MAX_LABELS];                /* pixel, vertex */
1998     DWORD texcoord_mask[MAX_REG_TEXCRD];    /* vertex < 3.0 */
1999
2000     /* Sampler usage tokens 
2001      * Use 0 as default (bit 31 is always 1 on a valid token) */
2002     DWORD samplers[max(MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS)];
2003     BOOL bumpmat[MAX_TEXTURES], luminanceparams[MAX_TEXTURES];
2004     char usesnrm, vpos, usesdsy;
2005     char usesrelconstF;
2006
2007     /* Whether or not loops are used in this shader, and nesting depth */
2008     unsigned loop_depth;
2009
2010     /* Whether or not this shader uses fog */
2011     char fog;
2012
2013 } shader_reg_maps;
2014
2015 /* Undocumented opcode controls */
2016 #define INST_CONTROLS_SHIFT 16
2017 #define INST_CONTROLS_MASK 0x00ff0000
2018
2019 typedef enum COMPARISON_TYPE {
2020     COMPARISON_GT = 1,
2021     COMPARISON_EQ = 2,
2022     COMPARISON_GE = 3,
2023     COMPARISON_LT = 4,
2024     COMPARISON_NE = 5,
2025     COMPARISON_LE = 6
2026 } COMPARISON_TYPE;
2027
2028 typedef struct SHADER_OPCODE {
2029     unsigned int  opcode;
2030     const char*   name;
2031     const char*   glname;
2032     char          dst_token;
2033     CONST UINT    num_params;
2034     enum WINED3D_SHADER_INSTRUCTION_HANDLER handler_idx;
2035     DWORD         min_version;
2036     DWORD         max_version;
2037 } SHADER_OPCODE;
2038
2039 typedef struct SHADER_OPCODE_ARG {
2040     IWineD3DBaseShader* shader;
2041     const shader_reg_maps *reg_maps;
2042     CONST SHADER_OPCODE* opcode;
2043     DWORD opcode_token;
2044     DWORD dst;
2045     DWORD dst_addr;
2046     DWORD predicate;
2047     DWORD src[4];
2048     DWORD src_addr[4];
2049     SHADER_BUFFER* buffer;
2050 } SHADER_OPCODE_ARG;
2051
2052 typedef struct SHADER_LIMITS {
2053     unsigned int temporary;
2054     unsigned int texcoord;
2055     unsigned int sampler;
2056     unsigned int constant_int;
2057     unsigned int constant_float;
2058     unsigned int constant_bool;
2059     unsigned int address;
2060     unsigned int packed_output;
2061     unsigned int packed_input;
2062     unsigned int attributes;
2063     unsigned int label;
2064 } SHADER_LIMITS;
2065
2066 /** Keeps track of details for TEX_M#x# shader opcodes which need to 
2067     maintain state information between multiple codes */
2068 typedef struct SHADER_PARSE_STATE {
2069     unsigned int current_row;
2070     DWORD texcoord_w[2];
2071 } SHADER_PARSE_STATE;
2072
2073 #ifdef __GNUC__
2074 #define PRINTF_ATTR(fmt,args) __attribute__((format (printf,fmt,args)))
2075 #else
2076 #define PRINTF_ATTR(fmt,args)
2077 #endif
2078
2079 /* Base Shader utility functions. 
2080  * (may move callers into the same file in the future) */
2081 extern int shader_addline(
2082     SHADER_BUFFER* buffer,
2083     const char* fmt, ...) PRINTF_ATTR(2,3);
2084
2085 extern const SHADER_OPCODE* shader_get_opcode(
2086     IWineD3DBaseShader *iface, 
2087     const DWORD code);
2088
2089 /* Vertex shader utility functions */
2090 extern BOOL vshader_get_input(
2091     IWineD3DVertexShader* iface,
2092     BYTE usage_req, BYTE usage_idx_req,
2093     unsigned int* regnum);
2094
2095 extern BOOL vshader_input_is_color(
2096     IWineD3DVertexShader* iface,
2097     unsigned int regnum);
2098
2099 extern HRESULT allocate_shader_constants(IWineD3DStateBlockImpl* object);
2100
2101 /* GLSL helper functions */
2102 extern void shader_glsl_add_instruction_modifiers(const SHADER_OPCODE_ARG *arg);
2103
2104 /*****************************************************************************
2105  * IDirect3DBaseShader implementation structure
2106  */
2107 typedef struct IWineD3DBaseShaderClass
2108 {
2109     LONG                            ref;
2110     DWORD                           hex_version;
2111     SHADER_LIMITS                   limits;
2112     SHADER_PARSE_STATE              parse_state;
2113     CONST SHADER_OPCODE             *shader_ins;
2114     DWORD                          *function;
2115     UINT                            functionLength;
2116     BOOL                            is_compiled;
2117     UINT                            cur_loop_depth, cur_loop_regno;
2118     BOOL                            load_local_constsF;
2119
2120     /* Type of shader backend */
2121     int shader_mode;
2122
2123     /* Programs this shader is linked with */
2124     struct list linked_programs;
2125
2126     /* Immediate constants (override global ones) */
2127     struct list constantsB;
2128     struct list constantsF;
2129     struct list constantsI;
2130     shader_reg_maps reg_maps;
2131
2132     /* Pixel formats of sampled textures, for format conversion. This
2133      * represents the formats found during compilation, it is not initialized
2134      * on the first parser pass. It is needed to check if the shader
2135      * needs recompilation to adjust the format conversion
2136      */
2137     WINED3DFORMAT       sampled_format[MAX_COMBINED_SAMPLERS];
2138     UINT                sampled_samplers[MAX_COMBINED_SAMPLERS];
2139     UINT                num_sampled_samplers;
2140
2141     UINT recompile_count;
2142
2143     /* Pointer to the parent device */
2144     IWineD3DDevice *device;
2145     struct list     shader_list_entry;
2146
2147 } IWineD3DBaseShaderClass;
2148
2149 typedef struct IWineD3DBaseShaderImpl {
2150     /* IUnknown */
2151     const IWineD3DBaseShaderVtbl    *lpVtbl;
2152
2153     /* IWineD3DBaseShader */
2154     IWineD3DBaseShaderClass         baseShader;
2155 } IWineD3DBaseShaderImpl;
2156
2157 HRESULT  WINAPI IWineD3DBaseShaderImpl_QueryInterface(IWineD3DBaseShader *iface, REFIID riid, LPVOID *ppobj);
2158 ULONG  WINAPI IWineD3DBaseShaderImpl_AddRef(IWineD3DBaseShader *iface);
2159 ULONG  WINAPI IWineD3DBaseShaderImpl_Release(IWineD3DBaseShader *iface);
2160
2161 extern HRESULT shader_get_registers_used(
2162     IWineD3DBaseShader *iface,
2163     shader_reg_maps* reg_maps,
2164     semantic* semantics_in,
2165     semantic* semantics_out,
2166     CONST DWORD* pToken,
2167     IWineD3DStateBlockImpl *stateBlock);
2168
2169 extern void shader_generate_main(IWineD3DBaseShader *iface, SHADER_BUFFER *buffer,
2170         const shader_reg_maps *reg_maps, const DWORD *pFunction);
2171
2172 extern void shader_dump_ins_modifiers(
2173     const DWORD output);
2174
2175 extern void shader_dump_param(
2176     IWineD3DBaseShader *iface,
2177     const DWORD param,
2178     const DWORD addr_token,
2179     int input);
2180
2181 extern void shader_trace_init(
2182     IWineD3DBaseShader *iface,
2183     const DWORD* pFunction);
2184
2185 extern int shader_get_param(
2186     IWineD3DBaseShader* iface,
2187     const DWORD* pToken,
2188     DWORD* param,
2189     DWORD* addr_token);
2190
2191 extern int shader_skip_unrecognized(
2192     IWineD3DBaseShader* iface,
2193     const DWORD* pToken);
2194
2195 static inline int shader_get_regtype(const DWORD param) {
2196     return (((param & WINED3DSP_REGTYPE_MASK) >> WINED3DSP_REGTYPE_SHIFT) |
2197             ((param & WINED3DSP_REGTYPE_MASK2) >> WINED3DSP_REGTYPE_SHIFT2));
2198 }
2199
2200 static inline int shader_get_writemask(const DWORD param) {
2201     return param & WINED3DSP_WRITEMASK_ALL;
2202 }
2203
2204 extern unsigned int shader_get_float_offset(const DWORD reg);
2205
2206 static inline BOOL shader_is_pshader_version(DWORD token) {
2207     return 0xFFFF0000 == (token & 0xFFFF0000);
2208 }
2209
2210 static inline BOOL shader_is_vshader_version(DWORD token) {
2211     return 0xFFFE0000 == (token & 0xFFFF0000);
2212 }
2213
2214 static inline BOOL shader_is_comment(DWORD token) {
2215     return WINED3DSIO_COMMENT == (token & WINED3DSI_OPCODE_MASK);
2216 }
2217
2218 static inline BOOL shader_is_scalar(DWORD param) {
2219     DWORD reg_type = shader_get_regtype(param);
2220     DWORD reg_num;
2221
2222     switch (reg_type) {
2223         case WINED3DSPR_RASTOUT:
2224             if ((param & WINED3DSP_REGNUM_MASK) != 0) {
2225                 /* oFog & oPts */
2226                 return TRUE;
2227             }
2228             /* oPos */
2229             return FALSE;
2230
2231         case WINED3DSPR_DEPTHOUT:   /* oDepth */
2232         case WINED3DSPR_CONSTBOOL:  /* b# */
2233         case WINED3DSPR_LOOP:       /* aL */
2234         case WINED3DSPR_PREDICATE:  /* p0 */
2235             return TRUE;
2236
2237         case WINED3DSPR_MISCTYPE:
2238             reg_num = param & WINED3DSP_REGNUM_MASK;
2239             switch(reg_num) {
2240                 case 0: /* vPos */
2241                     return FALSE;
2242                 case 1: /* vFace */
2243                     return TRUE;
2244                 default:
2245                     return FALSE;
2246             }
2247
2248         default:
2249             return FALSE;
2250     }
2251 }
2252
2253 static inline BOOL shader_constant_is_local(IWineD3DBaseShaderImpl* This, DWORD reg) {
2254     local_constant* lconst;
2255
2256     if(This->baseShader.load_local_constsF) return FALSE;
2257     LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
2258         if(lconst->idx == reg) return TRUE;
2259     }
2260     return FALSE;
2261
2262 }
2263
2264 /*****************************************************************************
2265  * IDirect3DVertexShader implementation structure
2266  */
2267 typedef struct IWineD3DVertexShaderImpl {
2268     /* IUnknown parts*/   
2269     const IWineD3DVertexShaderVtbl *lpVtbl;
2270
2271     /* IWineD3DBaseShader */
2272     IWineD3DBaseShaderClass     baseShader;
2273
2274     /* IWineD3DVertexShaderImpl */
2275     IUnknown                    *parent;
2276
2277     DWORD                       usage;
2278
2279     /* The GL shader */
2280     GLuint                          prgId;
2281
2282     /* Vertex shader input and output semantics */
2283     semantic semantics_in [MAX_ATTRIBS];
2284     semantic semantics_out [MAX_REG_OUTPUT];
2285
2286     /* Ordered array of attributes that are swizzled */
2287     attrib_declaration          swizzled_attribs [MAX_ATTRIBS];
2288     UINT                        num_swizzled_attribs;
2289
2290     UINT                       min_rel_offset, max_rel_offset;
2291     UINT                       rel_offset;
2292
2293     UINT                       recompile_count;
2294 } IWineD3DVertexShaderImpl;
2295 extern const SHADER_OPCODE IWineD3DVertexShaderImpl_shader_ins[];
2296 extern const IWineD3DVertexShaderVtbl IWineD3DVertexShader_Vtbl;
2297 HRESULT IWineD3DVertexShaderImpl_CompileShader(IWineD3DVertexShader *iface);
2298
2299 /*****************************************************************************
2300  * IDirect3DPixelShader implementation structure
2301  */
2302
2303 enum vertexprocessing_mode {
2304     fixedfunction,
2305     vertexshader,
2306     pretransformed
2307 };
2308
2309 struct stb_const_desc {
2310     char                    texunit;
2311     UINT                    const_num;
2312 };
2313
2314 /* Stateblock dependent parameters which have to be hardcoded
2315  * into the shader code
2316  */
2317 struct ps_compile_args {
2318     BOOL                        srgb_correction;
2319     WINED3DFORMAT               format_conversion[MAX_FRAGMENT_SAMPLERS];
2320     enum vertexprocessing_mode  vp_mode;
2321     /* Projected textures(ps 1.0-1.3) */
2322     /* Texture types(2D, Cube, 3D) in ps 1.x */
2323 };
2324
2325 struct ps_compiled_shader {
2326     struct ps_compile_args      args;
2327     GLuint                      prgId;
2328 };
2329
2330 typedef struct IWineD3DPixelShaderImpl {
2331     /* IUnknown parts */
2332     const IWineD3DPixelShaderVtbl *lpVtbl;
2333
2334     /* IWineD3DBaseShader */
2335     IWineD3DBaseShaderClass     baseShader;
2336
2337     /* IWineD3DPixelShaderImpl */
2338     IUnknown                   *parent;
2339
2340     /* Pixel shader input semantics */
2341     semantic semantics_in [MAX_REG_INPUT];
2342     DWORD                 input_reg_map[MAX_REG_INPUT];
2343     BOOL                  input_reg_used[MAX_REG_INPUT];
2344     int                         declared_in_count;
2345
2346     /* The GL shader */
2347     struct ps_compiled_shader   *gl_shaders;
2348     UINT                        num_gl_shaders;
2349
2350     /* Some information about the shader behavior */
2351     struct stb_const_desc       bumpenvmatconst[MAX_TEXTURES];
2352     char                        numbumpenvmatconsts;
2353     struct stb_const_desc       luminanceconst[MAX_TEXTURES];
2354     char                        vpos_uniform;
2355 } IWineD3DPixelShaderImpl;
2356
2357 extern const SHADER_OPCODE IWineD3DPixelShaderImpl_shader_ins[];
2358 extern const IWineD3DPixelShaderVtbl IWineD3DPixelShader_Vtbl;
2359 GLuint find_gl_pshader(IWineD3DPixelShaderImpl *shader, const struct ps_compile_args *args);
2360 void find_ps_compile_args(IWineD3DPixelShaderImpl *shader, IWineD3DStateBlockImpl *stateblock, struct ps_compile_args *args);
2361
2362 /* sRGB correction constants */
2363 static const float srgb_cmp = 0.0031308;
2364 static const float srgb_mul_low = 12.92;
2365 static const float srgb_pow = 0.41666;
2366 static const float srgb_mul_high = 1.055;
2367 static const float srgb_sub_high = 0.055;
2368
2369 /*****************************************************************************
2370  * IWineD3DPalette implementation structure
2371  */
2372 struct IWineD3DPaletteImpl {
2373     /* IUnknown parts */
2374     const IWineD3DPaletteVtbl  *lpVtbl;
2375     LONG                       ref;
2376
2377     IUnknown                   *parent;
2378     IWineD3DDeviceImpl         *wineD3DDevice;
2379
2380     /* IWineD3DPalette */
2381     HPALETTE                   hpal;
2382     WORD                       palVersion;     /*|               */
2383     WORD                       palNumEntries;  /*|  LOGPALETTE   */
2384     PALETTEENTRY               palents[256];   /*|               */
2385     /* This is to store the palette in 'screen format' */
2386     int                        screen_palents[256];
2387     DWORD                      Flags;
2388 };
2389
2390 extern const IWineD3DPaletteVtbl IWineD3DPalette_Vtbl;
2391 DWORD IWineD3DPaletteImpl_Size(DWORD dwFlags);
2392
2393 /* DirectDraw utility functions */
2394 extern WINED3DFORMAT pixelformat_for_depth(DWORD depth);
2395
2396 /*****************************************************************************
2397  * Pixel format management
2398  */
2399 typedef struct {
2400     WINED3DFORMAT           format;
2401     DWORD                   alphaMask, redMask, greenMask, blueMask;
2402     UINT                    bpp;
2403     short                   depthSize, stencilSize;
2404     BOOL                    isFourcc;
2405 } StaticPixelFormatDesc;
2406
2407 const StaticPixelFormatDesc *getFormatDescEntry(WINED3DFORMAT fmt,
2408         const WineD3D_GL_Info *gl_info, const GlPixelFormatDesc **glDesc);
2409
2410 static inline BOOL use_vs(IWineD3DDeviceImpl *device) {
2411     return (device->vs_selected_mode != SHADER_NONE
2412             && device->stateBlock->vertexShader
2413             && ((IWineD3DVertexShaderImpl *)device->stateBlock->vertexShader)->baseShader.function
2414             && !device->strided_streams.u.s.position_transformed);
2415 }
2416
2417 static inline BOOL use_ps(IWineD3DDeviceImpl *device) {
2418     return (device->ps_selected_mode != SHADER_NONE
2419             && device->stateBlock->pixelShader
2420             && ((IWineD3DPixelShaderImpl *)device->stateBlock->pixelShader)->baseShader.function);
2421 }
2422
2423 void stretch_rect_fbo(IWineD3DDevice *iface, IWineD3DSurface *src_surface, WINED3DRECT *src_rect,
2424         IWineD3DSurface *dst_surface, WINED3DRECT *dst_rect, const WINED3DTEXTUREFILTERTYPE filter, BOOL flip);
2425 #endif