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