VirtualBox

source: vbox/trunk/src/VBox/Devices/Graphics/shaderlib/glsl_shader.c@ 80547

Last change on this file since 80547 was 80547, checked in by vboxsync, 5 years ago

Devices/Graphics/shaderlib: print OpenGL shader compiler messages.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 219.0 KB
Line 
1/*
2 * GLSL pixel and vertex shader implementation
3 *
4 * Copyright 2006 Jason Green
5 * Copyright 2006-2007 Henri Verbeet
6 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
7 * Copyright 2009 Henri Verbeet for CodeWeavers
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/*
25 * Oracle LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
26 * other than GPL or LGPL is available it will apply instead, Oracle elects to use only
27 * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
28 * a choice of LGPL license versions is made available with the language indicating
29 * that LGPLv2 or any later version may be used, or where a choice of which version
30 * of the LGPL is applied is otherwise unspecified.
31 */
32
33/*
34 * D3D shader asm has swizzles on source parameters, and write masks for
35 * destination parameters. GLSL uses swizzles for both. The result of this is
36 * that for example "mov dst.xw, src.zyxw" becomes "dst.xw = src.zw" in GLSL.
37 * Ie, to generate a proper GLSL source swizzle, we need to take the D3D write
38 * mask for the destination parameter into account.
39 */
40
41#include "config.h"
42#include "wine/port.h"
43#include <limits.h>
44#include <stdio.h>
45#include "wined3d_private.h"
46
47WINE_DEFAULT_DEBUG_CHANNEL(d3d_shader);
48WINE_DECLARE_DEBUG_CHANNEL(d3d_constants);
49WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
50WINE_DECLARE_DEBUG_CHANNEL(d3d);
51
52#ifdef VBOX_WITH_VMSVGA
53#define LOG_GROUP LOG_GROUP_DEV_VMSVGA
54#include <VBox/log.h>
55#undef WDLOG
56#define WDLOG(_m) Log(_m)
57#undef CONST
58#define CONST const
59#endif
60
61#define GLINFO_LOCATION (*gl_info)
62
63#define WINED3D_GLSL_SAMPLE_PROJECTED 0x1
64#define WINED3D_GLSL_SAMPLE_RECT 0x2
65#define WINED3D_GLSL_SAMPLE_LOD 0x4
66#define WINED3D_GLSL_SAMPLE_GRAD 0x8
67
68typedef struct {
69 char reg_name[150];
70 char mask_str[6];
71} glsl_dst_param_t;
72
73typedef struct {
74 char reg_name[150];
75 char param_str[200];
76} glsl_src_param_t;
77
78typedef struct {
79 const char *name;
80 DWORD coord_mask;
81} glsl_sample_function_t;
82
83enum heap_node_op
84{
85 HEAP_NODE_TRAVERSE_LEFT,
86 HEAP_NODE_TRAVERSE_RIGHT,
87 HEAP_NODE_POP,
88};
89
90struct constant_entry
91{
92 unsigned int idx;
93 unsigned int version;
94};
95
96struct constant_heap
97{
98 struct constant_entry *entries;
99 unsigned int *positions;
100 unsigned int size;
101};
102
103/* GLSL shader private data */
104struct shader_glsl_priv {
105 struct wined3d_shader_buffer shader_buffer;
106 struct wine_rb_tree program_lookup;
107 struct glsl_shader_prog_link *glsl_program;
108 struct constant_heap vconst_heap;
109 struct constant_heap pconst_heap;
110 unsigned char *stack;
111 GLhandleARB depth_blt_program[tex_type_count];
112 UINT next_constant_version;
113};
114
115/* Struct to maintain data about a linked GLSL program */
116struct glsl_shader_prog_link {
117 struct wine_rb_entry program_lookup_entry;
118 struct list vshader_entry;
119 struct list pshader_entry;
120 GLhandleARB programId;
121 GLint *vuniformF_locations;
122 GLint *puniformF_locations;
123 GLint vuniformI_locations[MAX_CONST_I];
124 GLint puniformI_locations[MAX_CONST_I];
125 GLint posFixup_location;
126 GLint np2Fixup_location;
127 GLint bumpenvmat_location[MAX_TEXTURES];
128 GLint luminancescale_location[MAX_TEXTURES];
129 GLint luminanceoffset_location[MAX_TEXTURES];
130 GLint ycorrection_location;
131 GLenum vertex_color_clamp;
132 IWineD3DVertexShader *vshader;
133 IWineD3DPixelShader *pshader;
134 struct vs_compile_args vs_args;
135 struct ps_compile_args ps_args;
136 UINT constant_version;
137 const struct wined3d_context *context;
138 UINT inp2Fixup_info;
139};
140
141#ifdef VBOX_WITH_VMSVGA
142# define WINEFIXUPINFO_NOINDEX (~0U)
143#else
144#define WINEFIXUPINFO_NOINDEX (~0UL)
145#endif
146#define WINEFIXUPINFO_GET(_p) get_fixup_info((const IWineD3DPixelShaderImpl*)(_p)->pshader, (_p)->inp2Fixup_info)
147#define WINEFIXUPINFO_ISVALID(_p) ((_p)->inp2Fixup_info != WINEFIXUPINFO_NOINDEX)
148#ifdef VBOX_WITH_VMSVGA
149# define WINEFIXUPINFO_INIT(_p) do { (_p)->inp2Fixup_info = WINEFIXUPINFO_NOINDEX; } while (0)
150#else
151#define WINEFIXUPINFO_INIT(_p) ((_p)->inp2Fixup_info == WINEFIXUPINFO_NOINDEX)
152#endif
153
154typedef struct {
155 IWineD3DVertexShader *vshader;
156 IWineD3DPixelShader *pshader;
157 struct ps_compile_args ps_args;
158 struct vs_compile_args vs_args;
159 const struct wined3d_context *context;
160} glsl_program_key_t;
161
162struct shader_glsl_ctx_priv {
163 const struct vs_compile_args *cur_vs_args;
164 const struct ps_compile_args *cur_ps_args;
165 struct ps_np2fixup_info *cur_np2fixup_info;
166};
167
168struct glsl_ps_compiled_shader
169{
170 struct ps_compile_args args;
171 struct ps_np2fixup_info np2fixup;
172 GLhandleARB prgId;
173 const struct wined3d_context *context;
174};
175
176struct glsl_pshader_private
177{
178 struct glsl_ps_compiled_shader *gl_shaders;
179 UINT num_gl_shaders, shader_array_size;
180};
181
182struct glsl_vs_compiled_shader
183{
184 struct vs_compile_args args;
185 GLhandleARB prgId;
186 const struct wined3d_context *context;
187};
188
189struct glsl_vshader_private
190{
191 struct glsl_vs_compiled_shader *gl_shaders;
192 UINT num_gl_shaders, shader_array_size;
193};
194
195static const char *debug_gl_shader_type(GLenum type)
196{
197 switch (type)
198 {
199#define WINED3D_TO_STR(u) case u: return #u
200 WINED3D_TO_STR(GL_VERTEX_SHADER_ARB);
201 WINED3D_TO_STR(GL_GEOMETRY_SHADER_ARB);
202 WINED3D_TO_STR(GL_FRAGMENT_SHADER_ARB);
203#undef WINED3D_TO_STR
204 default:
205 return wine_dbg_sprintf("UNKNOWN(%#x)", type);
206 }
207}
208
209/* Extract a line from the info log.
210 * Note that this modifies the source string. */
211static char *get_info_log_line(char **ptr, int *pcbStr)
212{
213 char *p, *q;
214 const int cbStr = *pcbStr;
215
216 if (!cbStr)
217 {
218 /* zero-length string */
219 return NULL;
220 }
221
222 if ((*ptr)[cbStr-1] != '\0')
223 {
224 ERR("string should be null-rerminated, forcing it!");
225 (*ptr)[cbStr-1] = '\0';
226 }
227 p = *ptr;
228 if (!*p)
229 {
230 *pcbStr = 0;
231 return NULL;
232 }
233
234 if (!(q = strstr(p, "\n")))
235 {
236 /* the string contains a single line! */
237 *ptr += strlen(p);
238 *pcbStr = 0;
239 return p;
240 }
241
242 *q = '\0';
243 *pcbStr = cbStr - (((uintptr_t)q) - ((uintptr_t)p)) - 1;
244 Assert((*pcbStr) >= 0);
245 Assert((*pcbStr) < cbStr);
246 *ptr = q + 1;
247
248 return p;
249}
250
251/** Prints the GLSL info log which will contain error messages if they exist */
252/* GL locking is done by the caller */
253static void print_glsl_info_log(const struct wined3d_gl_info *gl_info, GLhandleARB obj)
254{
255 int infologLength = 0;
256 char *infoLog;
257 unsigned int i;
258 BOOL is_spam;
259
260 static const char * const spam[] =
261 {
262 "Vertex shader was successfully compiled to run on hardware.\n", /* fglrx */
263 "Fragment shader was successfully compiled to run on hardware.\n", /* fglrx, with \n */
264 "Fragment shader was successfully compiled to run on hardware.", /* fglrx, no \n */
265 "Fragment shader(s) linked, vertex shader(s) linked. \n ", /* fglrx, with \n */
266 "Fragment shader(s) linked, vertex shader(s) linked.", /* fglrx, no \n */
267 "Vertex shader(s) linked, no fragment shader(s) defined. \n ", /* fglrx, with \n */
268 "Vertex shader(s) linked, no fragment shader(s) defined.", /* fglrx, no \n */
269 "Fragment shader(s) linked, no vertex shader(s) defined. \n ", /* fglrx, with \n */
270 "Fragment shader(s) linked, no vertex shader(s) defined.", /* fglrx, no \n */
271 };
272
273#ifndef VBOXWINEDBG_SHADERS
274 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
275#endif
276
277 GL_EXTCALL(glGetObjectParameterivARB(obj,
278 GL_OBJECT_INFO_LOG_LENGTH_ARB,
279 &infologLength));
280
281 /* A size of 1 is just a null-terminated string, so the log should be bigger than
282 * that if there are errors. */
283 if (infologLength > 1)
284 {
285 char *ptr, *line;
286 int cbPtr;
287
288 /* Fglrx doesn't terminate the string properly, but it tells us the proper length.
289 * So use HEAP_ZERO_MEMORY to avoid uninitialized bytes
290 */
291 infoLog = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, infologLength);
292 GL_EXTCALL(glGetInfoLogARB(obj, infologLength, NULL, infoLog));
293 is_spam = FALSE;
294
295 for(i = 0; i < sizeof(spam) / sizeof(spam[0]); i++) {
296 if(strcmp(infoLog, spam[i]) == 0) {
297 is_spam = TRUE;
298 break;
299 }
300 }
301
302 ptr = infoLog;
303 cbPtr = infologLength;
304 if (is_spam)
305 {
306 WDLOG(("Spam received from GLSL shader #%u:\n", obj));
307 while ((line = get_info_log_line(&ptr, &cbPtr))) WDLOG((" %s\n", line));
308 }
309 else
310 {
311 WDLOG(("Error received from GLSL shader #%u:\n", obj));
312 while ((line = get_info_log_line(&ptr, &cbPtr))) WDLOG((" %s\n", line));
313 }
314 HeapFree(GetProcessHeap(), 0, infoLog);
315 }
316}
317
318static void shader_glsl_dump_shader_source(const struct wined3d_gl_info *gl_info, GLhandleARB shader)
319{
320 char *ptr;
321 GLint tmp, source_size;
322 char *source = NULL;
323 int cbPtr;
324
325 GL_EXTCALL(glGetObjectParameterivARB(shader, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &tmp));
326
327 source = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, tmp);
328 if (!source)
329 {
330 ERR("Failed to allocate %d bytes for shader source.\n", tmp);
331 return;
332 }
333
334 source_size = tmp;
335
336 WDLOG(("Object %u:\n", shader));
337 GL_EXTCALL(glGetObjectParameterivARB(shader, GL_OBJECT_SUBTYPE_ARB, &tmp));
338 WDLOG((" GL_OBJECT_SUBTYPE_ARB: %s.\n", debug_gl_shader_type(tmp)));
339 GL_EXTCALL(glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
340 WDLOG((" GL_OBJECT_COMPILE_STATUS_ARB: %d.\n", tmp));
341 WDLOG(("\n"));
342
343 if (tmp == 0)
344 {
345 /* Compilation error, print the compiler's error messages. */
346 print_glsl_info_log(gl_info, shader);
347 }
348
349 ptr = source;
350 cbPtr = source_size;
351 GL_EXTCALL(glGetShaderSourceARB(shader, source_size, NULL, source));
352#if 0
353 while ((line = get_info_log_line(&ptr, &cbPtr))) WDLOG((" %s\n", line));
354#else
355 WDLOG(("*****shader source***\n"));
356 WDLOG((" %s\n", source));
357 WDLOG(("\n*****END shader source***\n\n"));
358#endif
359 WDLOG(("\n"));
360}
361
362/* GL locking is done by the caller. */
363static void shader_glsl_dump_program_source(const struct wined3d_gl_info *gl_info, GLhandleARB program)
364{
365 GLint i, object_count;
366 GLhandleARB *objects;
367 char *source = NULL;
368
369 WDLOG(("\n***************************dumping program %d******************************\n", program));
370
371 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_ATTACHED_OBJECTS_ARB, &object_count));
372 objects = HeapAlloc(GetProcessHeap(), 0, object_count * sizeof(*objects));
373 if (!objects)
374 {
375 ERR("Failed to allocate object array memory.\n");
376 return;
377 }
378
379 GL_EXTCALL(glGetAttachedObjectsARB(program, object_count, NULL, objects));
380 for (i = 0; i < object_count; ++i)
381 {
382 shader_glsl_dump_shader_source(gl_info, objects[i]);
383 }
384
385 HeapFree(GetProcessHeap(), 0, source);
386 HeapFree(GetProcessHeap(), 0, objects);
387
388 WDLOG(("\n***************************END dumping program %d******************************\n\n", program));
389}
390
391/* GL locking is done by the caller. */
392static void shader_glsl_validate_compile_link(const struct wined3d_gl_info *gl_info, GLhandleARB program, GLboolean fIsProgram)
393{
394 GLint tmp = -1;
395
396#ifndef VBOXWINEDBG_SHADERS
397 if (!TRACE_ON(d3d_shader) && !FIXME_ON(d3d_shader)) return;
398#endif
399
400 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_TYPE_ARB, &tmp));
401 if (tmp == GL_PROGRAM_OBJECT_ARB)
402 {
403 if (!fIsProgram)
404 {
405 ERR("this is a program, but shader expected");
406 }
407 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &tmp));
408 if (!tmp)
409 {
410 ERR("Program %p link status invalid.\n", (void *)(uintptr_t)program);
411#ifndef VBOXWINEDBG_SHADERS
412 shader_glsl_dump_program_source(gl_info, program);
413#endif
414 }
415#if defined(VBOX_WITH_VMSVGA) && defined(DEBUG)
416 shader_glsl_dump_program_source(gl_info, program);
417#endif
418 }
419 else if (tmp == GL_SHADER_OBJECT_ARB)
420 {
421 if (fIsProgram)
422 {
423 ERR("this is a shader, but program expected");
424 }
425
426 GL_EXTCALL(glGetObjectParameterivARB(program, GL_OBJECT_COMPILE_STATUS_ARB, &tmp));
427 if (!tmp)
428 {
429 ERR("Shader %p compile status invalid.\n", (void *)(uintptr_t)program);
430 shader_glsl_dump_shader_source(gl_info, program);
431 }
432 }
433 else
434 {
435 ERR("unexpected oject type(%d)!", tmp);
436 }
437
438 print_glsl_info_log(gl_info, program);
439}
440
441/**
442 * Loads (pixel shader) samplers
443 */
444/* GL locking is done by the caller */
445static void shader_glsl_load_psamplers(const struct wined3d_gl_info *gl_info,
446 DWORD *tex_unit_map, GLhandleARB programId)
447{
448 GLint name_loc;
449 int i;
450 char sampler_name[20];
451
452 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i) {
453 snprintf(sampler_name, sizeof(sampler_name), "Psampler%d", i);
454 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
455 if (name_loc != -1) {
456 DWORD mapped_unit = tex_unit_map[i];
457 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.fragment_samplers)
458 {
459 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
460 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
461 checkGLcall("glUniform1iARB");
462 } else {
463 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
464 }
465 }
466 }
467}
468
469/* GL locking is done by the caller */
470static void shader_glsl_load_vsamplers(const struct wined3d_gl_info *gl_info,
471 DWORD *tex_unit_map, GLhandleARB programId)
472{
473 GLint name_loc;
474 char sampler_name[20];
475 int i;
476
477 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
478 snprintf(sampler_name, sizeof(sampler_name), "Vsampler%d", i);
479 name_loc = GL_EXTCALL(glGetUniformLocationARB(programId, sampler_name));
480 if (name_loc != -1) {
481 DWORD mapped_unit = tex_unit_map[MAX_FRAGMENT_SAMPLERS + i];
482 if (mapped_unit != WINED3D_UNMAPPED_STAGE && mapped_unit < gl_info->limits.combined_samplers)
483 {
484 TRACE("Loading %s for texture %d\n", sampler_name, mapped_unit);
485 GL_EXTCALL(glUniform1iARB(name_loc, mapped_unit));
486 checkGLcall("glUniform1iARB");
487 } else {
488 ERR("Trying to load sampler %s on unsupported unit %d\n", sampler_name, mapped_unit);
489 }
490 }
491 }
492}
493
494/* GL locking is done by the caller */
495static inline void walk_constant_heap(const struct wined3d_gl_info *gl_info, const float *constants,
496 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
497{
498 int stack_idx = 0;
499 unsigned int heap_idx = 1;
500 unsigned int idx;
501
502 if (heap->entries[heap_idx].version <= version) return;
503
504 idx = heap->entries[heap_idx].idx;
505 if (constant_locations[idx] != -1) GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
506 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
507
508 while (stack_idx >= 0)
509 {
510 /* Note that we fall through to the next case statement. */
511 switch(stack[stack_idx])
512 {
513 case HEAP_NODE_TRAVERSE_LEFT:
514 {
515 unsigned int left_idx = heap_idx << 1;
516 if (left_idx < heap->size && heap->entries[left_idx].version > version)
517 {
518 heap_idx = left_idx;
519 idx = heap->entries[heap_idx].idx;
520 if (constant_locations[idx] != -1)
521 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
522
523 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
524 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
525 break;
526 }
527 } RT_FALL_THRU();
528
529 case HEAP_NODE_TRAVERSE_RIGHT:
530 {
531 unsigned int right_idx = (heap_idx << 1) + 1;
532 if (right_idx < heap->size && heap->entries[right_idx].version > version)
533 {
534 heap_idx = right_idx;
535 idx = heap->entries[heap_idx].idx;
536 if (constant_locations[idx] != -1)
537 GL_EXTCALL(glUniform4fvARB(constant_locations[idx], 1, &constants[idx * 4]));
538
539 stack[stack_idx++] = HEAP_NODE_POP;
540 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
541 break;
542 }
543 } RT_FALL_THRU();
544
545 case HEAP_NODE_POP:
546 {
547 heap_idx >>= 1;
548 --stack_idx;
549 break;
550 }
551 }
552 }
553 checkGLcall("walk_constant_heap()");
554}
555
556/* GL locking is done by the caller */
557static inline void apply_clamped_constant(const struct wined3d_gl_info *gl_info, GLint location, const GLfloat *data)
558{
559 GLfloat clamped_constant[4];
560
561 if (location == -1) return;
562
563 clamped_constant[0] = data[0] < -1.0f ? -1.0f : data[0] > 1.0f ? 1.0f : data[0];
564 clamped_constant[1] = data[1] < -1.0f ? -1.0f : data[1] > 1.0f ? 1.0f : data[1];
565 clamped_constant[2] = data[2] < -1.0f ? -1.0f : data[2] > 1.0f ? 1.0f : data[2];
566 clamped_constant[3] = data[3] < -1.0f ? -1.0f : data[3] > 1.0f ? 1.0f : data[3];
567
568 GL_EXTCALL(glUniform4fvARB(location, 1, clamped_constant));
569}
570
571/* GL locking is done by the caller */
572static inline void walk_constant_heap_clamped(const struct wined3d_gl_info *gl_info, const float *constants,
573 const GLint *constant_locations, const struct constant_heap *heap, unsigned char *stack, DWORD version)
574{
575 int stack_idx = 0;
576 unsigned int heap_idx = 1;
577 unsigned int idx;
578
579 if (heap->entries[heap_idx].version <= version) return;
580
581 idx = heap->entries[heap_idx].idx;
582 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
583 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
584
585 while (stack_idx >= 0)
586 {
587 /* Note that we fall through to the next case statement. */
588 switch(stack[stack_idx])
589 {
590 case HEAP_NODE_TRAVERSE_LEFT:
591 {
592 unsigned int left_idx = heap_idx << 1;
593 if (left_idx < heap->size && heap->entries[left_idx].version > version)
594 {
595 heap_idx = left_idx;
596 idx = heap->entries[heap_idx].idx;
597 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
598
599 stack[stack_idx++] = HEAP_NODE_TRAVERSE_RIGHT;
600 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
601 break;
602 }
603 } RT_FALL_THRU();
604
605 case HEAP_NODE_TRAVERSE_RIGHT:
606 {
607 unsigned int right_idx = (heap_idx << 1) + 1;
608 if (right_idx < heap->size && heap->entries[right_idx].version > version)
609 {
610 heap_idx = right_idx;
611 idx = heap->entries[heap_idx].idx;
612 apply_clamped_constant(gl_info, constant_locations[idx], &constants[idx * 4]);
613
614 stack[stack_idx++] = HEAP_NODE_POP;
615 stack[stack_idx] = HEAP_NODE_TRAVERSE_LEFT;
616 break;
617 }
618 } RT_FALL_THRU();
619
620 case HEAP_NODE_POP:
621 {
622 heap_idx >>= 1;
623 --stack_idx;
624 break;
625 }
626 }
627 }
628 checkGLcall("walk_constant_heap_clamped()");
629}
630
631/* Loads floating point constants (aka uniforms) into the currently set GLSL program. */
632/* GL locking is done by the caller */
633static void shader_glsl_load_constantsF(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
634 const float *constants, const GLint *constant_locations, const struct constant_heap *heap,
635 unsigned char *stack, UINT version)
636{
637 const local_constant *lconst;
638
639 /* 1.X pshaders have the constants clamped to [-1;1] implicitly. */
640 if (This->baseShader.reg_maps.shader_version.major == 1
641 && shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type))
642 walk_constant_heap_clamped(gl_info, constants, constant_locations, heap, stack, version);
643 else
644 walk_constant_heap(gl_info, constants, constant_locations, heap, stack, version);
645
646 if (!This->baseShader.load_local_constsF)
647 {
648 TRACE("No need to load local float constants for this shader\n");
649 return;
650 }
651
652 /* Immediate constants are clamped to [-1;1] at shader creation time if needed */
653 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry)
654 {
655 GLint location = constant_locations[lconst->idx];
656 /* We found this uniform name in the program - go ahead and send the data */
657 if (location != -1) GL_EXTCALL(glUniform4fvARB(location, 1, (const GLfloat *)lconst->value));
658 }
659 checkGLcall("glUniform4fvARB()");
660}
661
662/* Loads integer constants (aka uniforms) into the currently set GLSL program. */
663/* GL locking is done by the caller */
664static void shader_glsl_load_constantsI(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
665 const GLint locations[MAX_CONST_I], const int *constants, WORD constants_set)
666{
667 unsigned int i;
668 struct list* ptr;
669
670 for (i = 0; constants_set; constants_set >>= 1, ++i)
671 {
672 if (!(constants_set & 1)) continue;
673
674 TRACE_(d3d_constants)("Loading constants %u: %i, %i, %i, %i\n",
675 i, constants[i*4], constants[i*4+1], constants[i*4+2], constants[i*4+3]);
676
677 /* We found this uniform name in the program - go ahead and send the data */
678 GL_EXTCALL(glUniform4ivARB(locations[i], 1, &constants[i*4]));
679 checkGLcall("glUniform4ivARB");
680 }
681
682 /* Load immediate constants */
683 ptr = list_head(&This->baseShader.constantsI);
684 while (ptr) {
685 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
686 unsigned int idx = lconst->idx;
687 const GLint *values = (const GLint *)lconst->value;
688
689 TRACE_(d3d_constants)("Loading local constants %i: %i, %i, %i, %i\n", idx,
690 values[0], values[1], values[2], values[3]);
691
692 /* We found this uniform name in the program - go ahead and send the data */
693 GL_EXTCALL(glUniform4ivARB(locations[idx], 1, values));
694 checkGLcall("glUniform4ivARB");
695 ptr = list_next(&This->baseShader.constantsI, ptr);
696 }
697}
698
699/* Loads boolean constants (aka uniforms) into the currently set GLSL program. */
700/* GL locking is done by the caller */
701static void shader_glsl_load_constantsB(IWineD3DBaseShaderImpl *This, const struct wined3d_gl_info *gl_info,
702 GLhandleARB programId, const BOOL *constants, WORD constants_set)
703{
704 GLint tmp_loc;
705 unsigned int i;
706 char tmp_name[8];
707 const char *prefix;
708 struct list* ptr;
709
710 switch (This->baseShader.reg_maps.shader_version.type)
711 {
712 case WINED3D_SHADER_TYPE_VERTEX:
713 prefix = "VB";
714 break;
715
716 case WINED3D_SHADER_TYPE_GEOMETRY:
717 prefix = "GB";
718 break;
719
720 case WINED3D_SHADER_TYPE_PIXEL:
721 prefix = "PB";
722 break;
723
724 default:
725 FIXME("Unknown shader type %#x.\n",
726 This->baseShader.reg_maps.shader_version.type);
727 prefix = "UB";
728 break;
729 }
730
731 /* TODO: Benchmark and see if it would be beneficial to store the
732 * locations of the constants to avoid looking up each time */
733 for (i = 0; constants_set; constants_set >>= 1, ++i)
734 {
735 if (!(constants_set & 1)) continue;
736
737 TRACE_(d3d_constants)("Loading constants %i: %i;\n", i, constants[i]);
738
739 /* TODO: Benchmark and see if it would be beneficial to store the
740 * locations of the constants to avoid looking up each time */
741 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, i);
742 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
743 if (tmp_loc != -1)
744 {
745 /* We found this uniform name in the program - go ahead and send the data */
746 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, &constants[i]));
747 checkGLcall("glUniform1ivARB");
748 }
749 }
750
751 /* Load immediate constants */
752 ptr = list_head(&This->baseShader.constantsB);
753 while (ptr) {
754 const struct local_constant *lconst = LIST_ENTRY(ptr, const struct local_constant, entry);
755 unsigned int idx = lconst->idx;
756 const GLint *values = (const GLint *)lconst->value;
757
758 TRACE_(d3d_constants)("Loading local constants %i: %i\n", idx, values[0]);
759
760 snprintf(tmp_name, sizeof(tmp_name), "%s[%i]", prefix, idx);
761 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, tmp_name));
762 if (tmp_loc != -1) {
763 /* We found this uniform name in the program - go ahead and send the data */
764 GL_EXTCALL(glUniform1ivARB(tmp_loc, 1, values));
765 checkGLcall("glUniform1ivARB");
766 }
767 ptr = list_next(&This->baseShader.constantsB, ptr);
768 }
769}
770
771static void reset_program_constant_version(struct wine_rb_entry *entry, void *context)
772{
773 WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry)->constant_version = 0;
774}
775
776static const struct ps_np2fixup_info * get_fixup_info(const IWineD3DPixelShaderImpl *shader, UINT inp2fixup_info)
777{
778 struct glsl_pshader_private *shader_data = shader->baseShader.backend_data;
779
780 if (inp2fixup_info == WINEFIXUPINFO_NOINDEX)
781 return NULL;
782
783 if (!shader->baseShader.backend_data)
784 {
785 ERR("no backend data\n");
786 return NULL;
787 }
788 shader_data = shader->baseShader.backend_data;
789
790 if (inp2fixup_info >= shader_data->num_gl_shaders)
791 {
792 ERR("invalid index\n");
793 return NULL;
794 }
795
796 return &shader_data->gl_shaders[inp2fixup_info].np2fixup;
797}
798
799/**
800 * Loads the texture dimensions for NP2 fixup into the currently set GLSL program.
801 */
802/* GL locking is done by the caller (state handler) */
803static void shader_glsl_load_np2fixup_constants(
804 IWineD3DDevice* device,
805 char usePixelShader,
806 char useVertexShader) {
807
808 const IWineD3DDeviceImpl* deviceImpl = (const IWineD3DDeviceImpl*) device;
809 const struct glsl_shader_prog_link* prog = ((struct shader_glsl_priv *)(deviceImpl->shader_priv))->glsl_program;
810
811 if (!prog) {
812 /* No GLSL program set - nothing to do. */
813 return;
814 }
815
816 if (!usePixelShader) {
817 /* NP2 texcoord fixup is (currently) only done for pixelshaders. */
818 return;
819 }
820
821 if (prog->ps_args.np2_fixup && -1 != prog->np2Fixup_location) {
822 const struct wined3d_gl_info *gl_info = &deviceImpl->adapter->gl_info;
823 const IWineD3DStateBlockImpl* stateBlock = (const IWineD3DStateBlockImpl*) deviceImpl->stateBlock;
824 UINT i;
825 UINT fixup = prog->ps_args.np2_fixup;
826 GLfloat np2fixup_constants[4 * MAX_FRAGMENT_SAMPLERS];
827
828 const struct ps_np2fixup_info *np2Fixup_info = WINEFIXUPINFO_GET(prog);
829
830 for (i = 0; fixup; fixup >>= 1, ++i) {
831 const unsigned char idx = np2Fixup_info->idx[i];
832 const IWineD3DBaseTextureImpl* const tex = (const IWineD3DBaseTextureImpl*) stateBlock->textures[i];
833 GLfloat* tex_dim = &np2fixup_constants[(idx >> 1) * 4];
834
835 if (!tex) {
836 FIXME("Nonexistent texture is flagged for NP2 texcoord fixup\n");
837 continue;
838 }
839
840 if (idx % 2) {
841 tex_dim[2] = tex->baseTexture.pow2Matrix[0]; tex_dim[3] = tex->baseTexture.pow2Matrix[5];
842 } else {
843 tex_dim[0] = tex->baseTexture.pow2Matrix[0]; tex_dim[1] = tex->baseTexture.pow2Matrix[5];
844 }
845 }
846
847 GL_EXTCALL(glUniform4fvARB(prog->np2Fixup_location, np2Fixup_info->num_consts, np2fixup_constants));
848 }
849}
850
851/**
852 * Loads the app-supplied constants into the currently set GLSL program.
853 */
854/* GL locking is done by the caller (state handler) */
855static void shader_glsl_load_constants(const struct wined3d_context *context,
856 char usePixelShader, char useVertexShader)
857{
858 const struct wined3d_gl_info *gl_info = context->gl_info;
859 IWineD3DDeviceImpl *device = context_get_device(context);
860 IWineD3DStateBlockImpl* stateBlock = device->stateBlock;
861 struct shader_glsl_priv *priv = device->shader_priv;
862
863 GLhandleARB programId;
864 struct glsl_shader_prog_link *prog = priv->glsl_program;
865 UINT constant_version;
866 int i;
867
868 if (!prog) {
869 /* No GLSL program set - nothing to do. */
870 return;
871 }
872 programId = prog->programId;
873 constant_version = prog->constant_version;
874
875 if (useVertexShader) {
876 IWineD3DBaseShaderImpl* vshader = (IWineD3DBaseShaderImpl*) stateBlock->vertexShader;
877
878 /* Load DirectX 9 float constants/uniforms for vertex shader */
879 shader_glsl_load_constantsF(vshader, gl_info, stateBlock->vertexShaderConstantF,
880 prog->vuniformF_locations, &priv->vconst_heap, priv->stack, constant_version);
881
882 /* Load DirectX 9 integer constants/uniforms for vertex shader */
883 shader_glsl_load_constantsI(vshader, gl_info, prog->vuniformI_locations, stateBlock->vertexShaderConstantI,
884 stateBlock->changed.vertexShaderConstantsI & vshader->baseShader.reg_maps.integer_constants);
885
886 /* Load DirectX 9 boolean constants/uniforms for vertex shader */
887 shader_glsl_load_constantsB(vshader, gl_info, programId, stateBlock->vertexShaderConstantB,
888 stateBlock->changed.vertexShaderConstantsB & vshader->baseShader.reg_maps.boolean_constants);
889
890 /* Upload the position fixup params */
891 GL_EXTCALL(glUniform4fvARB(prog->posFixup_location, 1, &device->posFixup[0]));
892 checkGLcall("glUniform4fvARB");
893 }
894
895 if (usePixelShader) {
896
897 IWineD3DBaseShaderImpl* pshader = (IWineD3DBaseShaderImpl*) stateBlock->pixelShader;
898
899 /* Load DirectX 9 float constants/uniforms for pixel shader */
900 shader_glsl_load_constantsF(pshader, gl_info, stateBlock->pixelShaderConstantF,
901 prog->puniformF_locations, &priv->pconst_heap, priv->stack, constant_version);
902
903 /* Load DirectX 9 integer constants/uniforms for pixel shader */
904 shader_glsl_load_constantsI(pshader, gl_info, prog->puniformI_locations, stateBlock->pixelShaderConstantI,
905 stateBlock->changed.pixelShaderConstantsI & pshader->baseShader.reg_maps.integer_constants);
906
907 /* Load DirectX 9 boolean constants/uniforms for pixel shader */
908 shader_glsl_load_constantsB(pshader, gl_info, programId, stateBlock->pixelShaderConstantB,
909 stateBlock->changed.pixelShaderConstantsB & pshader->baseShader.reg_maps.boolean_constants);
910
911 /* Upload the environment bump map matrix if needed. The needsbumpmat member specifies the texture stage to load the matrix from.
912 * It can't be 0 for a valid texbem instruction.
913 */
914 for(i = 0; i < MAX_TEXTURES; i++) {
915 const float *data;
916
917 if(prog->bumpenvmat_location[i] == -1) continue;
918
919 data = (const float *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVMAT00];
920 GL_EXTCALL(glUniformMatrix2fvARB(prog->bumpenvmat_location[i], 1, 0, data));
921 checkGLcall("glUniformMatrix2fvARB");
922
923 /* texbeml needs the luminance scale and offset too. If texbeml is used, needsbumpmat
924 * is set too, so we can check that in the needsbumpmat check
925 */
926 if(prog->luminancescale_location[i] != -1) {
927 const GLfloat *scale = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLSCALE];
928 const GLfloat *offset = (const GLfloat *)&stateBlock->textureState[i][WINED3DTSS_BUMPENVLOFFSET];
929
930 GL_EXTCALL(glUniform1fvARB(prog->luminancescale_location[i], 1, scale));
931 checkGLcall("glUniform1fvARB");
932 GL_EXTCALL(glUniform1fvARB(prog->luminanceoffset_location[i], 1, offset));
933 checkGLcall("glUniform1fvARB");
934 }
935 }
936
937 if(((IWineD3DPixelShaderImpl *) pshader)->vpos_uniform) {
938 float correction_params[4];
939
940 if (context->render_offscreen)
941 {
942 correction_params[0] = 0.0f;
943 correction_params[1] = 1.0f;
944 } else {
945 /* position is window relative, not viewport relative */
946#ifdef VBOX_WITH_VMSVGA
947 correction_params[0] = device->rtHeight;
948#else
949 correction_params[0] = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
950#endif
951 correction_params[1] = -1.0f;
952 }
953 GL_EXTCALL(glUniform4fvARB(prog->ycorrection_location, 1, correction_params));
954 }
955 }
956
957 if (priv->next_constant_version == UINT_MAX)
958 {
959 TRACE("Max constant version reached, resetting to 0.\n");
960 wine_rb_for_each_entry(&priv->program_lookup, reset_program_constant_version, NULL);
961 priv->next_constant_version = 1;
962 }
963 else
964 {
965 prog->constant_version = priv->next_constant_version++;
966 }
967}
968
969static inline void update_heap_entry(struct constant_heap *heap, unsigned int idx,
970 unsigned int heap_idx, DWORD new_version)
971{
972 struct constant_entry *entries = heap->entries;
973 unsigned int *positions = heap->positions;
974 unsigned int parent_idx;
975
976 while (heap_idx > 1)
977 {
978 parent_idx = heap_idx >> 1;
979
980 if (new_version <= entries[parent_idx].version) break;
981
982 entries[heap_idx] = entries[parent_idx];
983 positions[entries[parent_idx].idx] = heap_idx;
984 heap_idx = parent_idx;
985 }
986
987 entries[heap_idx].version = new_version;
988 entries[heap_idx].idx = idx;
989 positions[idx] = heap_idx;
990}
991
992static void shader_glsl_update_float_vertex_constants(IWineD3DDevice *iface, UINT start, UINT count)
993{
994 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
995 struct shader_glsl_priv *priv = This->shader_priv;
996 struct constant_heap *heap = &priv->vconst_heap;
997 UINT i;
998
999 for (i = start; i < count + start; ++i)
1000 {
1001 if (!This->stateBlock->changed.vertexShaderConstantsF[i])
1002 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
1003 else
1004 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
1005 }
1006}
1007
1008static void shader_glsl_update_float_pixel_constants(IWineD3DDevice *iface, UINT start, UINT count)
1009{
1010 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
1011 struct shader_glsl_priv *priv = This->shader_priv;
1012 struct constant_heap *heap = &priv->pconst_heap;
1013 UINT i;
1014
1015 for (i = start; i < count + start; ++i)
1016 {
1017 if (!This->stateBlock->changed.pixelShaderConstantsF[i])
1018 update_heap_entry(heap, i, heap->size++, priv->next_constant_version);
1019 else
1020 update_heap_entry(heap, i, heap->positions[i], priv->next_constant_version);
1021 }
1022}
1023
1024static unsigned int vec4_varyings(DWORD shader_major, const struct wined3d_gl_info *gl_info)
1025{
1026 unsigned int ret = gl_info->limits.glsl_varyings / 4;
1027 /* 4.0 shaders do not write clip coords because d3d10 does not support user clipplanes */
1028 if(shader_major > 3) return ret;
1029
1030 /* 3.0 shaders may need an extra varying for the clip coord on some cards(mostly dx10 ones) */
1031 if (gl_info->quirks & WINED3D_QUIRK_GLSL_CLIP_VARYING) ret -= 1;
1032 return ret;
1033}
1034
1035/** Generate the variable & register declarations for the GLSL output target */
1036static void shader_generate_glsl_declarations(const struct wined3d_context *context,
1037 struct wined3d_shader_buffer *buffer, IWineD3DBaseShader *iface,
1038 const shader_reg_maps *reg_maps, struct shader_glsl_ctx_priv *ctx_priv)
1039{
1040 IWineD3DBaseShaderImpl* This = (IWineD3DBaseShaderImpl*) iface;
1041 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *) This->baseShader.device;
1042 const struct ps_compile_args *ps_args = ctx_priv->cur_ps_args;
1043 const struct wined3d_gl_info *gl_info = context->gl_info;
1044 unsigned int i, extra_constants_needed = 0;
1045 const local_constant *lconst;
1046 DWORD map;
1047
1048 /* There are some minor differences between pixel and vertex shaders */
1049 char pshader = shader_is_pshader_version(reg_maps->shader_version.type);
1050 char prefix = pshader ? 'P' : 'V';
1051
1052 /* Prototype the subroutines */
1053 for (i = 0, map = reg_maps->labels; map; map >>= 1, ++i)
1054 {
1055 if (map & 1) shader_addline(buffer, "void subroutine%u();\n", i);
1056 }
1057
1058 /* Declare the constants (aka uniforms) */
1059 if (This->baseShader.limits.constant_float > 0) {
1060 unsigned max_constantsF;
1061 /* Unless the shader uses indirect addressing, always declare the maximum array size and ignore that we need some
1062 * uniforms privately. E.g. if GL supports 256 uniforms, and we need 2 for the pos fixup and immediate values, still
1063 * declare VC[256]. If the shader needs more uniforms than we have it won't work in any case. If it uses less, the
1064 * compiler will figure out which uniforms are really used and strip them out. This allows a shader to use c255 on
1065 * a dx9 card, as long as it doesn't also use all the other constants.
1066 *
1067 * If the shader uses indirect addressing the compiler must assume that all declared uniforms are used. In this case,
1068 * declare only the amount that we're assured to have.
1069 *
1070 * Thus we run into problems in these two cases:
1071 * 1) The shader really uses more uniforms than supported
1072 * 2) The shader uses indirect addressing, less constants than supported, but uses a constant index > #supported consts
1073 */
1074 if (pshader)
1075 {
1076 /* No indirect addressing here. */
1077 max_constantsF = gl_info->limits.glsl_ps_float_constants;
1078 }
1079 else
1080 {
1081#ifndef VBOX_WITH_VMSVGA
1082 if(This->baseShader.reg_maps.usesrelconstF) {
1083#else
1084 /* If GL supports only 256 constants (seen on macOS drivers for compatibility profile, which we use),
1085 * then ignore the need for potential uniforms and always declare VC[256].
1086 * This allows to compile Windows 10 shader which use hardcoded constants at 250+ index range.
1087 * Fixes drawing problems on Windows 10 desktop.
1088 *
1089 * This hack is normally active only on macOS, because Windows and Linux OpenGL drivers
1090 * have a more usable limit for GL compatibility context (1024+).
1091 */
1092 if (This->baseShader.reg_maps.usesrelconstF && gl_info->limits.glsl_vs_float_constants > 256) {
1093#endif
1094 /* Subtract the other potential uniforms from the max available (bools, ints, and 1 row of projection matrix).
1095 * Subtract another uniform for immediate values, which have to be loaded via uniform by the driver as well.
1096 * The shader code only uses 0.5, 2.0, 1.0, 128 and -128 in vertex shader code, so one vec4 should be enough
1097 * (Unfortunately the Nvidia driver doesn't store 128 and -128 in one float).
1098 *
1099 * Writing gl_ClipVertex requires one uniform for each clipplane as well.
1100 */
1101#ifdef VBOX_WITH_WDDM
1102 if (gl_info->limits.glsl_vs_float_constants == 256)
1103 {
1104 DWORD dwVersion = GetVersion();
1105 DWORD dwMajor = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1106 DWORD dwMinor = (DWORD)(HIBYTE(LOWORD(dwVersion)));
1107 /* tmp workaround Win8 Aero requirement for 256 */
1108 if (dwMajor > 6 || dwMinor > 1)
1109 {
1110 /* tmp work-around to make Internet Explorer in win8 work with GPU supporting only with 256 shader uniform vars
1111 * @todo: make it more robust */
1112 max_constantsF = gl_info->limits.glsl_vs_float_constants - 1;
1113 }
1114 else
1115 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
1116 }
1117 else
1118#endif
1119 {
1120 max_constantsF = gl_info->limits.glsl_vs_float_constants - 3;
1121 }
1122
1123 if(ctx_priv->cur_vs_args->clip_enabled)
1124 {
1125 max_constantsF -= gl_info->limits.clipplanes;
1126 }
1127 max_constantsF -= count_bits(This->baseShader.reg_maps.integer_constants);
1128 /* Strictly speaking a bool only uses one scalar, but the nvidia(Linux) compiler doesn't pack them properly,
1129 * so each scalar requires a full vec4. We could work around this by packing the booleans ourselves, but
1130 * for now take this into account when calculating the number of available constants
1131 */
1132 max_constantsF -= count_bits(This->baseShader.reg_maps.boolean_constants);
1133 /* Set by driver quirks in directx.c */
1134 max_constantsF -= gl_info->reserved_glsl_constants;
1135 }
1136 else
1137 {
1138 max_constantsF = gl_info->limits.glsl_vs_float_constants;
1139 }
1140 }
1141 max_constantsF = min(This->baseShader.limits.constant_float, max_constantsF);
1142 shader_addline(buffer, "uniform vec4 %cC[%u];\n", prefix, max_constantsF);
1143 }
1144
1145 /* Always declare the full set of constants, the compiler can remove the unused ones because d3d doesn't(yet)
1146 * support indirect int and bool constant addressing. This avoids problems if the app uses e.g. i0 and i9.
1147 */
1148 if (This->baseShader.limits.constant_int > 0 && This->baseShader.reg_maps.integer_constants)
1149 shader_addline(buffer, "uniform ivec4 %cI[%u];\n", prefix, This->baseShader.limits.constant_int);
1150
1151 if (This->baseShader.limits.constant_bool > 0 && This->baseShader.reg_maps.boolean_constants)
1152 shader_addline(buffer, "uniform bool %cB[%u];\n", prefix, This->baseShader.limits.constant_bool);
1153
1154 if(!pshader) {
1155 shader_addline(buffer, "uniform vec4 posFixup;\n");
1156 /* Predeclaration; This function is added at link time based on the pixel shader.
1157 * VS 3.0 shaders have an array OUT[] the shader writes to, earlier versions don't have
1158 * that. We know the input to the reorder function at vertex shader compile time, so
1159 * we can deal with that. The reorder function for a 1.x and 2.x vertex shader can just
1160 * read gl_FrontColor. The output depends on the pixel shader. The reorder function for a
1161 * 1.x and 2.x pshader or for fixed function will write gl_FrontColor, and for a 3.0 shader
1162 * it will write to the varying array. Here we depend on the shader optimizer on sorting that
1163 * out. The nvidia driver only does that if the parameter is inout instead of out, hence the
1164 * inout.
1165 */
1166 if (reg_maps->shader_version.major >= 3)
1167 {
1168 shader_addline(buffer, "void order_ps_input(in vec4[%u]);\n", MAX_REG_OUTPUT);
1169 } else {
1170 shader_addline(buffer, "void order_ps_input();\n");
1171 }
1172 } else {
1173 for (i = 0, map = reg_maps->bumpmat; map; map >>= 1, ++i)
1174 {
1175 if (!(map & 1)) continue;
1176
1177 shader_addline(buffer, "uniform mat2 bumpenvmat%d;\n", i);
1178
1179 if (reg_maps->luminanceparams & (1 << i))
1180 {
1181 shader_addline(buffer, "uniform float luminancescale%d;\n", i);
1182 shader_addline(buffer, "uniform float luminanceoffset%d;\n", i);
1183 extra_constants_needed++;
1184 }
1185
1186 extra_constants_needed++;
1187 }
1188
1189 if (ps_args->srgb_correction)
1190 {
1191 shader_addline(buffer, "const vec4 srgb_const0 = vec4(%.8e, %.8e, %.8e, %.8e);\n",
1192 srgb_pow, srgb_mul_high, srgb_sub_high, srgb_mul_low);
1193 shader_addline(buffer, "const vec4 srgb_const1 = vec4(%.8e, 0.0, 0.0, 0.0);\n",
1194 srgb_cmp);
1195 }
1196 if (reg_maps->vpos || reg_maps->usesdsy)
1197 {
1198 if (This->baseShader.limits.constant_float + extra_constants_needed
1199 + 1 < gl_info->limits.glsl_ps_float_constants)
1200 {
1201 shader_addline(buffer, "uniform vec4 ycorrection;\n");
1202 ((IWineD3DPixelShaderImpl *) This)->vpos_uniform = 1;
1203 extra_constants_needed++;
1204 } else {
1205 /* This happens because we do not have proper tracking of the constant registers that are
1206 * actually used, only the max limit of the shader version
1207 */
1208 FIXME("Cannot find a free uniform for vpos correction params\n");
1209 AssertFailed();
1210 shader_addline(buffer, "const vec4 ycorrection = vec4(%f, %f, 0.0, 0.0);\n",
1211 context->render_offscreen ? 0.0f : ((IWineD3DSurfaceImpl *)device->render_targets[0])->currentDesc.Height,
1212 context->render_offscreen ? 1.0f : -1.0f);
1213 }
1214 shader_addline(buffer, "vec4 vpos;\n");
1215 }
1216 }
1217
1218 /* Declare texture samplers */
1219 for (i = 0; i < This->baseShader.limits.sampler; i++) {
1220 if (reg_maps->sampler_type[i])
1221 {
1222 switch (reg_maps->sampler_type[i])
1223 {
1224 case WINED3DSTT_1D:
1225 shader_addline(buffer, "uniform sampler1D %csampler%u;\n", prefix, i);
1226 break;
1227 case WINED3DSTT_2D:
1228 if(device->stateBlock->textures[i] &&
1229 IWineD3DBaseTexture_GetTextureDimensions(device->stateBlock->textures[i]) == GL_TEXTURE_RECTANGLE_ARB) {
1230 shader_addline(buffer, "uniform sampler2DRect %csampler%u;\n", prefix, i);
1231 } else {
1232 shader_addline(buffer, "uniform sampler2D %csampler%u;\n", prefix, i);
1233 }
1234 break;
1235 case WINED3DSTT_CUBE:
1236 shader_addline(buffer, "uniform samplerCube %csampler%u;\n", prefix, i);
1237 break;
1238 case WINED3DSTT_VOLUME:
1239 shader_addline(buffer, "uniform sampler3D %csampler%u;\n", prefix, i);
1240 break;
1241 default:
1242 shader_addline(buffer, "uniform unsupported_sampler %csampler%u;\n", prefix, i);
1243 FIXME("Unrecognized sampler type: %#x\n", reg_maps->sampler_type[i]);
1244 break;
1245 }
1246 }
1247 }
1248
1249 /* Declare uniforms for NP2 texcoord fixup:
1250 * This is NOT done inside the loop that declares the texture samplers since the NP2 fixup code
1251 * is currently only used for the GeforceFX series and when forcing the ARB_npot extension off.
1252 * Modern cards just skip the code anyway, so put it inside a separate loop. */
1253 if (pshader && ps_args->np2_fixup) {
1254
1255 struct ps_np2fixup_info* const fixup = ctx_priv->cur_np2fixup_info;
1256 UINT cur = 0;
1257
1258 /* NP2/RECT textures in OpenGL use texcoords in the range [0,width]x[0,height]
1259 * while D3D has them in the (normalized) [0,1]x[0,1] range.
1260 * samplerNP2Fixup stores texture dimensions and is updated through
1261 * shader_glsl_load_np2fixup_constants when the sampler changes. */
1262
1263 for (i = 0; i < This->baseShader.limits.sampler; ++i) {
1264 if (reg_maps->sampler_type[i]) {
1265 if (!(ps_args->np2_fixup & (1 << i))) continue;
1266
1267 if (WINED3DSTT_2D != reg_maps->sampler_type[i]) {
1268 FIXME("Non-2D texture is flagged for NP2 texcoord fixup.\n");
1269 continue;
1270 }
1271
1272 fixup->idx[i] = cur++;
1273 }
1274 }
1275
1276 fixup->num_consts = (cur + 1) >> 1;
1277 shader_addline(buffer, "uniform vec4 %csamplerNP2Fixup[%u];\n", prefix, fixup->num_consts);
1278 }
1279
1280 /* Declare address variables */
1281 for (i = 0, map = reg_maps->address; map; map >>= 1, ++i)
1282 {
1283 if (map & 1) shader_addline(buffer, "ivec4 A%u;\n", i);
1284 }
1285
1286 /* Declare texture coordinate temporaries and initialize them */
1287 for (i = 0, map = reg_maps->texcoord; map; map >>= 1, ++i)
1288 {
1289 if (map & 1) shader_addline(buffer, "vec4 T%u = gl_TexCoord[%u];\n", i, i);
1290 }
1291
1292 /* Declare input register varyings. Only pixel shader, vertex shaders have that declared in the
1293 * helper function shader that is linked in at link time
1294 */
1295 if (pshader && reg_maps->shader_version.major >= 3)
1296 {
1297 if (use_vs(device->stateBlock))
1298 {
1299 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1300 } else {
1301 /* TODO: Write a replacement shader for the fixed function vertex pipeline, so this isn't needed.
1302 * For fixed function vertex processing + 3.0 pixel shader we need a separate function in the
1303 * pixel shader that reads the fixed function color into the packed input registers.
1304 */
1305 shader_addline(buffer, "vec4 IN[%u];\n", vec4_varyings(reg_maps->shader_version.major, gl_info));
1306 }
1307 }
1308
1309 /* Declare output register temporaries */
1310 if(This->baseShader.limits.packed_output) {
1311 shader_addline(buffer, "vec4 OUT[%u];\n", This->baseShader.limits.packed_output);
1312 }
1313
1314 /* Declare temporary variables */
1315 for (i = 0, map = reg_maps->temporary; map; map >>= 1, ++i)
1316 {
1317 if (map & 1) shader_addline(buffer, "vec4 R%u;\n", i);
1318 }
1319
1320 /* Declare attributes */
1321 if (reg_maps->shader_version.type == WINED3D_SHADER_TYPE_VERTEX)
1322 {
1323 for (i = 0, map = reg_maps->input_registers; map; map >>= 1, ++i)
1324 {
1325 if (map & 1) shader_addline(buffer, "attribute vec4 attrib%i;\n", i);
1326 }
1327 }
1328
1329 /* Declare loop registers aLx */
1330 for (i = 0; i < reg_maps->loop_depth; i++) {
1331 shader_addline(buffer, "int aL%u;\n", i);
1332 shader_addline(buffer, "int tmpInt%u;\n", i);
1333 }
1334
1335 /* Temporary variables for matrix operations */
1336 shader_addline(buffer, "vec4 tmp0;\n");
1337 shader_addline(buffer, "vec4 tmp1;\n");
1338#ifdef VBOX_WITH_VMSVGA
1339 shader_addline(buffer, "bool p0[4];\n");
1340#endif
1341
1342 /* Local constants use a different name so they can be loaded once at shader link time
1343 * They can't be hardcoded into the shader text via LC = {x, y, z, w}; because the
1344 * float -> string conversion can cause precision loss.
1345 */
1346 if(!This->baseShader.load_local_constsF) {
1347 LIST_FOR_EACH_ENTRY(lconst, &This->baseShader.constantsF, local_constant, entry) {
1348 shader_addline(buffer, "uniform vec4 %cLC%u;\n", prefix, lconst->idx);
1349 }
1350 }
1351
1352 shader_addline(buffer, "const float FLT_MAX = 1e38;\n");
1353
1354 /* Start the main program */
1355 shader_addline(buffer, "void main() {\n");
1356 if(pshader && reg_maps->vpos) {
1357 /* DirectX apps expect integer values, while OpenGL drivers add approximately 0.5. This causes
1358 * off-by-one problems as spotted by the vPos d3d9 visual test. Unfortunately the ATI cards do
1359 * not add exactly 0.5, but rather something like 0.49999999 or 0.50000001, which still causes
1360 * precision troubles when we just substract 0.5.
1361 *
1362 * To deal with that just floor() the position. This will eliminate the fraction on all cards.
1363 *
1364 * TODO: Test how that behaves with multisampling once we can enable multisampling in winex11.
1365 *
1366 * An advantage of floor is that it works even if the driver doesn't add 1/2. It is somewhat
1367 * questionable if 1.5, 2.5, ... are the proper values to return in gl_FragCoord, even though
1368 * coordinates specify the pixel centers instead of the pixel corners. This code will behave
1369 * correctly on drivers that returns integer values.
1370 */
1371 shader_addline(buffer, "vpos = floor(vec4(0, ycorrection[0], 0, 0) + gl_FragCoord * vec4(1, ycorrection[1], 1, 1));\n");
1372 }
1373}
1374
1375/*****************************************************************************
1376 * Functions to generate GLSL strings from DirectX Shader bytecode begin here.
1377 *
1378 * For more information, see http://wiki.winehq.org/DirectX-Shaders
1379 ****************************************************************************/
1380
1381/* Prototypes */
1382static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1383 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src);
1384
1385/** Used for opcode modifiers - They multiply the result by the specified amount */
1386static const char * const shift_glsl_tab[] = {
1387 "", /* 0 (none) */
1388 "2.0 * ", /* 1 (x2) */
1389 "4.0 * ", /* 2 (x4) */
1390 "8.0 * ", /* 3 (x8) */
1391 "16.0 * ", /* 4 (x16) */
1392 "32.0 * ", /* 5 (x32) */
1393 "", /* 6 (x64) */
1394 "", /* 7 (x128) */
1395 "", /* 8 (d256) */
1396 "", /* 9 (d128) */
1397 "", /* 10 (d64) */
1398 "", /* 11 (d32) */
1399 "0.0625 * ", /* 12 (d16) */
1400 "0.125 * ", /* 13 (d8) */
1401 "0.25 * ", /* 14 (d4) */
1402 "0.5 * " /* 15 (d2) */
1403};
1404
1405/* Generate a GLSL parameter that does the input modifier computation and return the input register/mask to use */
1406static void shader_glsl_gen_modifier(DWORD src_modifier, const char *in_reg, const char *in_regswizzle, char *out_str)
1407{
1408 out_str[0] = 0;
1409
1410 switch (src_modifier)
1411 {
1412 case WINED3DSPSM_DZ: /* Need to handle this in the instructions itself (texld & texcrd). */
1413 case WINED3DSPSM_DW:
1414 case WINED3DSPSM_NONE:
1415 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1416 break;
1417 case WINED3DSPSM_NEG:
1418 sprintf(out_str, "-%s%s", in_reg, in_regswizzle);
1419 break;
1420 case WINED3DSPSM_NOT:
1421 sprintf(out_str, "!%s%s", in_reg, in_regswizzle);
1422 break;
1423 case WINED3DSPSM_BIAS:
1424 sprintf(out_str, "(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1425 break;
1426 case WINED3DSPSM_BIASNEG:
1427 sprintf(out_str, "-(%s%s - vec4(0.5)%s)", in_reg, in_regswizzle, in_regswizzle);
1428 break;
1429 case WINED3DSPSM_SIGN:
1430 sprintf(out_str, "(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1431 break;
1432 case WINED3DSPSM_SIGNNEG:
1433 sprintf(out_str, "-(2.0 * (%s%s - 0.5))", in_reg, in_regswizzle);
1434 break;
1435 case WINED3DSPSM_COMP:
1436 sprintf(out_str, "(1.0 - %s%s)", in_reg, in_regswizzle);
1437 break;
1438 case WINED3DSPSM_X2:
1439 sprintf(out_str, "(2.0 * %s%s)", in_reg, in_regswizzle);
1440 break;
1441 case WINED3DSPSM_X2NEG:
1442 sprintf(out_str, "-(2.0 * %s%s)", in_reg, in_regswizzle);
1443 break;
1444 case WINED3DSPSM_ABS:
1445 sprintf(out_str, "abs(%s%s)", in_reg, in_regswizzle);
1446 break;
1447 case WINED3DSPSM_ABSNEG:
1448 sprintf(out_str, "-abs(%s%s)", in_reg, in_regswizzle);
1449 break;
1450 default:
1451 FIXME("Unhandled modifier %u\n", src_modifier);
1452 sprintf(out_str, "%s%s", in_reg, in_regswizzle);
1453 }
1454}
1455
1456/** Writes the GLSL variable name that corresponds to the register that the
1457 * DX opcode parameter is trying to access */
1458static void shader_glsl_get_register_name(const struct wined3d_shader_register *reg,
1459 char *register_name, BOOL *is_color, const struct wined3d_shader_instruction *ins)
1460{
1461 /* oPos, oFog and oPts in D3D */
1462 static const char * const hwrastout_reg_names[] = { "gl_Position", "gl_FogFragCoord", "gl_PointSize" };
1463
1464 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
1465 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
1466 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
1467
1468 *is_color = FALSE;
1469
1470 switch (reg->type)
1471 {
1472 case WINED3DSPR_TEMP:
1473 sprintf(register_name, "R%u", reg->idx);
1474 break;
1475
1476 case WINED3DSPR_INPUT:
1477 /* vertex shaders */
1478 if (!pshader)
1479 {
1480 struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
1481 if (priv->cur_vs_args->swizzle_map & (1 << reg->idx)) *is_color = TRUE;
1482 sprintf(register_name, "attrib%u", reg->idx);
1483 break;
1484 }
1485
1486 /* pixel shaders >= 3.0 */
1487 if (This->baseShader.reg_maps.shader_version.major >= 3)
1488 {
1489 DWORD idx = ((IWineD3DPixelShaderImpl *)This)->input_reg_map[reg->idx];
1490 unsigned int in_count = vec4_varyings(This->baseShader.reg_maps.shader_version.major, gl_info);
1491
1492 if (reg->rel_addr)
1493 {
1494 glsl_src_param_t rel_param;
1495
1496 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1497
1498 /* Removing a + 0 would be an obvious optimization, but macos doesn't see the NOP
1499 * operation there */
1500 if (idx)
1501 {
1502 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1503 {
1504 sprintf(register_name,
1505 "((%s + %u) > %d ? (%s + %u) > %d ? gl_SecondaryColor : gl_Color : IN[%s + %u])",
1506 rel_param.param_str, idx, in_count - 1, rel_param.param_str, idx, in_count,
1507 rel_param.param_str, idx);
1508 }
1509 else
1510 {
1511 sprintf(register_name, "IN[%s + %u]", rel_param.param_str, idx);
1512 }
1513 }
1514 else
1515 {
1516 if (((IWineD3DPixelShaderImpl *)This)->declared_in_count > in_count)
1517 {
1518 sprintf(register_name, "((%s) > %d ? (%s) > %d ? gl_SecondaryColor : gl_Color : IN[%s])",
1519 rel_param.param_str, in_count - 1, rel_param.param_str, in_count,
1520 rel_param.param_str);
1521 }
1522 else
1523 {
1524 sprintf(register_name, "IN[%s]", rel_param.param_str);
1525 }
1526 }
1527 }
1528 else
1529 {
1530 if (idx == in_count) sprintf(register_name, "gl_Color");
1531 else if (idx == in_count + 1) sprintf(register_name, "gl_SecondaryColor");
1532 else sprintf(register_name, "IN[%u]", idx);
1533 }
1534 }
1535 else
1536 {
1537 if (reg->idx == 0) strcpy(register_name, "gl_Color");
1538 else strcpy(register_name, "gl_SecondaryColor");
1539 break;
1540 }
1541 break;
1542
1543 case WINED3DSPR_CONST:
1544 {
1545 const char prefix = pshader ? 'P' : 'V';
1546
1547 /* Relative addressing */
1548 if (reg->rel_addr)
1549 {
1550 glsl_src_param_t rel_param;
1551 shader_glsl_add_src_param(ins, reg->rel_addr, WINED3DSP_WRITEMASK_0, &rel_param);
1552 if (reg->idx) sprintf(register_name, "%cC[%s + %u]", prefix, rel_param.param_str, reg->idx);
1553 else sprintf(register_name, "%cC[%s]", prefix, rel_param.param_str);
1554 }
1555 else
1556 {
1557 if (shader_constant_is_local(This, reg->idx))
1558 sprintf(register_name, "%cLC%u", prefix, reg->idx);
1559 else
1560 sprintf(register_name, "%cC[%u]", prefix, reg->idx);
1561 }
1562 }
1563 break;
1564
1565 case WINED3DSPR_CONSTINT:
1566 if (pshader) sprintf(register_name, "PI[%u]", reg->idx);
1567 else sprintf(register_name, "VI[%u]", reg->idx);
1568 break;
1569
1570 case WINED3DSPR_CONSTBOOL:
1571 if (pshader) sprintf(register_name, "PB[%u]", reg->idx);
1572 else sprintf(register_name, "VB[%u]", reg->idx);
1573 break;
1574
1575 case WINED3DSPR_TEXTURE: /* case WINED3DSPR_ADDR: */
1576 if (pshader) sprintf(register_name, "T%u", reg->idx);
1577 else sprintf(register_name, "A%u", reg->idx);
1578 break;
1579
1580 case WINED3DSPR_LOOP:
1581 sprintf(register_name, "aL%u", This->baseShader.cur_loop_regno - 1);
1582 break;
1583
1584 case WINED3DSPR_SAMPLER:
1585 if (pshader) sprintf(register_name, "Psampler%u", reg->idx);
1586 else sprintf(register_name, "Vsampler%u", reg->idx);
1587 break;
1588
1589 case WINED3DSPR_COLOROUT:
1590 if (reg->idx >= gl_info->limits.buffers)
1591 WARN("Write to render target %u, only %d supported.\n", reg->idx, gl_info->limits.buffers);
1592
1593 sprintf(register_name, "gl_FragData[%u]", reg->idx);
1594 break;
1595
1596 case WINED3DSPR_RASTOUT:
1597 sprintf(register_name, "%s", hwrastout_reg_names[reg->idx]);
1598 break;
1599
1600 case WINED3DSPR_DEPTHOUT:
1601 sprintf(register_name, "gl_FragDepth");
1602 break;
1603
1604 case WINED3DSPR_ATTROUT:
1605 if (reg->idx == 0) sprintf(register_name, "gl_FrontColor");
1606 else sprintf(register_name, "gl_FrontSecondaryColor");
1607 break;
1608
1609 case WINED3DSPR_TEXCRDOUT:
1610 /* Vertex shaders >= 3.0: WINED3DSPR_OUTPUT */
1611 if (This->baseShader.reg_maps.shader_version.major >= 3) sprintf(register_name, "OUT[%u]", reg->idx);
1612 else sprintf(register_name, "gl_TexCoord[%u]", reg->idx);
1613 break;
1614
1615 case WINED3DSPR_MISCTYPE:
1616 if (reg->idx == 0)
1617 {
1618 /* vPos */
1619 sprintf(register_name, "vpos");
1620 }
1621 else if (reg->idx == 1)
1622 {
1623 /* Note that gl_FrontFacing is a bool, while vFace is
1624 * a float for which the sign determines front/back */
1625 sprintf(register_name, "(gl_FrontFacing ? 1.0 : -1.0)");
1626 }
1627 else
1628 {
1629 FIXME("Unhandled misctype register %d\n", reg->idx);
1630 sprintf(register_name, "unrecognized_register");
1631 }
1632 break;
1633
1634 case WINED3DSPR_IMMCONST:
1635 switch (reg->immconst_type)
1636 {
1637 case WINED3D_IMMCONST_FLOAT:
1638 sprintf(register_name, "%.8e", *(const float *)reg->immconst_data);
1639 break;
1640
1641 case WINED3D_IMMCONST_FLOAT4:
1642 sprintf(register_name, "vec4(%.8e, %.8e, %.8e, %.8e)",
1643 *(const float *)&reg->immconst_data[0], *(const float *)&reg->immconst_data[1],
1644 *(const float *)&reg->immconst_data[2], *(const float *)&reg->immconst_data[3]);
1645 break;
1646
1647 default:
1648 FIXME("Unhandled immconst type %#x\n", reg->immconst_type);
1649 sprintf(register_name, "<unhandled_immconst_type %#x>", reg->immconst_type);
1650 }
1651 break;
1652
1653#ifdef VBOX_WITH_VMSVGA
1654 case WINED3DSPR_PREDICATE:
1655 sprintf(register_name, "p0");
1656 break;
1657#endif
1658
1659 default:
1660 FIXME("Unhandled register name Type(%d)\n", reg->type);
1661 sprintf(register_name, "unrecognized_register");
1662 break;
1663 }
1664}
1665
1666static void shader_glsl_write_mask_to_str(DWORD write_mask, char *str)
1667{
1668 *str++ = '.';
1669 if (write_mask & WINED3DSP_WRITEMASK_0) *str++ = 'x';
1670 if (write_mask & WINED3DSP_WRITEMASK_1) *str++ = 'y';
1671 if (write_mask & WINED3DSP_WRITEMASK_2) *str++ = 'z';
1672 if (write_mask & WINED3DSP_WRITEMASK_3) *str++ = 'w';
1673 *str = '\0';
1674}
1675
1676/* Get the GLSL write mask for the destination register */
1677static DWORD shader_glsl_get_write_mask(const struct wined3d_shader_dst_param *param, char *write_mask)
1678{
1679 DWORD mask = param->write_mask;
1680
1681 if (shader_is_scalar(&param->reg))
1682 {
1683 mask = WINED3DSP_WRITEMASK_0;
1684 *write_mask = '\0';
1685 }
1686 else
1687 {
1688#ifdef VBOX_WITH_VMSVGA
1689 if (param->reg.type == WINED3DSPR_PREDICATE)
1690 {
1691 *write_mask++ = '[';
1692 if (mask & WINED3DSP_WRITEMASK_0) *write_mask++ = '0';
1693 else
1694 if (mask & WINED3DSP_WRITEMASK_1) *write_mask++ = '1';
1695 else
1696 if (mask & WINED3DSP_WRITEMASK_2) *write_mask++ = '2';
1697 else
1698 if (mask & WINED3DSP_WRITEMASK_3) *write_mask++ = '3';
1699 *write_mask++ = ']';
1700 *write_mask = '\0';
1701 }
1702 else
1703#endif
1704 shader_glsl_write_mask_to_str(mask, write_mask);
1705 }
1706
1707 return mask;
1708}
1709
1710static unsigned int shader_glsl_get_write_mask_size(DWORD write_mask) {
1711 unsigned int size = 0;
1712
1713 if (write_mask & WINED3DSP_WRITEMASK_0) ++size;
1714 if (write_mask & WINED3DSP_WRITEMASK_1) ++size;
1715 if (write_mask & WINED3DSP_WRITEMASK_2) ++size;
1716 if (write_mask & WINED3DSP_WRITEMASK_3) ++size;
1717
1718 return size;
1719}
1720
1721static void shader_glsl_swizzle_to_str(const DWORD swizzle, BOOL fixup, DWORD mask, char *str)
1722{
1723 /* For registers of type WINED3DDECLTYPE_D3DCOLOR, data is stored as "bgra",
1724 * but addressed as "rgba". To fix this we need to swap the register's x
1725 * and z components. */
1726 const char *swizzle_chars = fixup ? "zyxw" : "xyzw";
1727
1728 *str++ = '.';
1729 /* swizzle bits fields: wwzzyyxx */
1730 if (mask & WINED3DSP_WRITEMASK_0) *str++ = swizzle_chars[swizzle & 0x03];
1731 if (mask & WINED3DSP_WRITEMASK_1) *str++ = swizzle_chars[(swizzle >> 2) & 0x03];
1732 if (mask & WINED3DSP_WRITEMASK_2) *str++ = swizzle_chars[(swizzle >> 4) & 0x03];
1733 if (mask & WINED3DSP_WRITEMASK_3) *str++ = swizzle_chars[(swizzle >> 6) & 0x03];
1734 *str = '\0';
1735}
1736
1737static void shader_glsl_get_swizzle(const struct wined3d_shader_src_param *param,
1738 BOOL fixup, DWORD mask, char *swizzle_str)
1739{
1740 if (shader_is_scalar(&param->reg))
1741 *swizzle_str = '\0';
1742 else
1743 shader_glsl_swizzle_to_str(param->swizzle, fixup, mask, swizzle_str);
1744}
1745
1746/* From a given parameter token, generate the corresponding GLSL string.
1747 * Also, return the actual register name and swizzle in case the
1748 * caller needs this information as well. */
1749static void shader_glsl_add_src_param(const struct wined3d_shader_instruction *ins,
1750 const struct wined3d_shader_src_param *wined3d_src, DWORD mask, glsl_src_param_t *glsl_src)
1751{
1752 BOOL is_color = FALSE;
1753 char swizzle_str[6];
1754
1755 glsl_src->reg_name[0] = '\0';
1756 glsl_src->param_str[0] = '\0';
1757 swizzle_str[0] = '\0';
1758
1759 shader_glsl_get_register_name(&wined3d_src->reg, glsl_src->reg_name, &is_color, ins);
1760 shader_glsl_get_swizzle(wined3d_src, is_color, mask, swizzle_str);
1761 shader_glsl_gen_modifier(wined3d_src->modifiers, glsl_src->reg_name, swizzle_str, glsl_src->param_str);
1762}
1763
1764/* From a given parameter token, generate the corresponding GLSL string.
1765 * Also, return the actual register name and swizzle in case the
1766 * caller needs this information as well. */
1767static DWORD shader_glsl_add_dst_param(const struct wined3d_shader_instruction *ins,
1768 const struct wined3d_shader_dst_param *wined3d_dst, glsl_dst_param_t *glsl_dst)
1769{
1770 BOOL is_color = FALSE;
1771
1772 glsl_dst->mask_str[0] = '\0';
1773 glsl_dst->reg_name[0] = '\0';
1774
1775 shader_glsl_get_register_name(&wined3d_dst->reg, glsl_dst->reg_name, &is_color, ins);
1776 return shader_glsl_get_write_mask(wined3d_dst, glsl_dst->mask_str);
1777}
1778
1779/* Append the destination part of the instruction to the buffer, return the effective write mask */
1780static DWORD shader_glsl_append_dst_ext(struct wined3d_shader_buffer *buffer,
1781 const struct wined3d_shader_instruction *ins, const struct wined3d_shader_dst_param *dst)
1782{
1783 glsl_dst_param_t glsl_dst;
1784 DWORD mask;
1785
1786 mask = shader_glsl_add_dst_param(ins, dst, &glsl_dst);
1787 if (mask) shader_addline(buffer, "%s%s = %s(", glsl_dst.reg_name, glsl_dst.mask_str, shift_glsl_tab[dst->shift]);
1788
1789 return mask;
1790}
1791
1792/* Append the destination part of the instruction to the buffer, return the effective write mask */
1793static DWORD shader_glsl_append_dst(struct wined3d_shader_buffer *buffer, const struct wined3d_shader_instruction *ins)
1794{
1795 return shader_glsl_append_dst_ext(buffer, ins, &ins->dst[0]);
1796}
1797
1798/** Process GLSL instruction modifiers */
1799static void shader_glsl_add_instruction_modifiers(const struct wined3d_shader_instruction *ins)
1800{
1801 glsl_dst_param_t dst_param;
1802 DWORD modifiers;
1803
1804 if (!ins->dst_count) return;
1805
1806 modifiers = ins->dst[0].modifiers;
1807 if (!modifiers) return;
1808
1809 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
1810
1811 if (modifiers & WINED3DSPDM_SATURATE)
1812 {
1813 /* _SAT means to clamp the value of the register to between 0 and 1 */
1814 shader_addline(ins->ctx->buffer, "%s%s = clamp(%s%s, 0.0, 1.0);\n", dst_param.reg_name,
1815 dst_param.mask_str, dst_param.reg_name, dst_param.mask_str);
1816 }
1817
1818 if (modifiers & WINED3DSPDM_MSAMPCENTROID)
1819 {
1820 FIXME("_centroid modifier not handled\n");
1821 }
1822
1823 if (modifiers & WINED3DSPDM_PARTIALPRECISION)
1824 {
1825 /* MSDN says this modifier can be safely ignored, so that's what we'll do. */
1826 }
1827}
1828
1829static inline const char *shader_get_comp_op(DWORD op)
1830{
1831 switch (op) {
1832 case COMPARISON_GT: return ">";
1833 case COMPARISON_EQ: return "==";
1834 case COMPARISON_GE: return ">=";
1835 case COMPARISON_LT: return "<";
1836 case COMPARISON_NE: return "!=";
1837 case COMPARISON_LE: return "<=";
1838 default:
1839 FIXME("Unrecognized comparison value: %u\n", op);
1840 return "(\?\?)";
1841 }
1842}
1843
1844static void shader_glsl_get_sample_function(const struct wined3d_gl_info *gl_info,
1845 DWORD sampler_type, DWORD flags, glsl_sample_function_t *sample_function)
1846{
1847 BOOL projected = flags & WINED3D_GLSL_SAMPLE_PROJECTED;
1848 BOOL texrect = flags & WINED3D_GLSL_SAMPLE_RECT;
1849 BOOL lod = flags & WINED3D_GLSL_SAMPLE_LOD;
1850 BOOL grad = flags & WINED3D_GLSL_SAMPLE_GRAD;
1851
1852 /* Note that there's no such thing as a projected cube texture. */
1853 switch(sampler_type) {
1854 case WINED3DSTT_1D:
1855 if(lod) {
1856 sample_function->name = projected ? "texture1DProjLod" : "texture1DLod";
1857 }
1858 else if (grad)
1859 {
1860 if (gl_info->supported[EXT_GPU_SHADER4])
1861 sample_function->name = projected ? "texture1DProjGrad" : "texture1DGrad";
1862 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1863 sample_function->name = projected ? "texture1DProjGradARB" : "texture1DGradARB";
1864 else
1865 {
1866 FIXME("Unsupported 1D grad function.\n");
1867 sample_function->name = "unsupported1DGrad";
1868 }
1869 }
1870 else
1871 {
1872 sample_function->name = projected ? "texture1DProj" : "texture1D";
1873 }
1874 sample_function->coord_mask = WINED3DSP_WRITEMASK_0;
1875 break;
1876 case WINED3DSTT_2D:
1877 if(texrect) {
1878 if(lod) {
1879 sample_function->name = projected ? "texture2DRectProjLod" : "texture2DRectLod";
1880 }
1881 else if (grad)
1882 {
1883 if (gl_info->supported[EXT_GPU_SHADER4])
1884 sample_function->name = projected ? "texture2DRectProjGrad" : "texture2DRectGrad";
1885 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1886 sample_function->name = projected ? "texture2DRectProjGradARB" : "texture2DRectGradARB";
1887 else
1888 {
1889 FIXME("Unsupported RECT grad function.\n");
1890 sample_function->name = "unsupported2DRectGrad";
1891 }
1892 }
1893 else
1894 {
1895 sample_function->name = projected ? "texture2DRectProj" : "texture2DRect";
1896 }
1897 } else {
1898 if(lod) {
1899 sample_function->name = projected ? "texture2DProjLod" : "texture2DLod";
1900 }
1901 else if (grad)
1902 {
1903 if (gl_info->supported[EXT_GPU_SHADER4])
1904 sample_function->name = projected ? "texture2DProjGrad" : "texture2DGrad";
1905 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1906 sample_function->name = projected ? "texture2DProjGradARB" : "texture2DGradARB";
1907 else
1908 {
1909 FIXME("Unsupported 2D grad function.\n");
1910 sample_function->name = "unsupported2DGrad";
1911 }
1912 }
1913 else
1914 {
1915 sample_function->name = projected ? "texture2DProj" : "texture2D";
1916 }
1917 }
1918 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1;
1919 break;
1920 case WINED3DSTT_CUBE:
1921 if(lod) {
1922 sample_function->name = "textureCubeLod";
1923 }
1924 else if (grad)
1925 {
1926 if (gl_info->supported[EXT_GPU_SHADER4])
1927 sample_function->name = "textureCubeGrad";
1928 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1929 sample_function->name = "textureCubeGradARB";
1930 else
1931 {
1932 FIXME("Unsupported Cube grad function.\n");
1933 sample_function->name = "unsupportedCubeGrad";
1934 }
1935 }
1936 else
1937 {
1938 sample_function->name = "textureCube";
1939 }
1940 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1941 break;
1942 case WINED3DSTT_VOLUME:
1943 if(lod) {
1944 sample_function->name = projected ? "texture3DProjLod" : "texture3DLod";
1945 }
1946 else if (grad)
1947 {
1948 if (gl_info->supported[EXT_GPU_SHADER4])
1949 sample_function->name = projected ? "texture3DProjGrad" : "texture3DGrad";
1950 else if (gl_info->supported[ARB_SHADER_TEXTURE_LOD])
1951 sample_function->name = projected ? "texture3DProjGradARB" : "texture3DGradARB";
1952 else
1953 {
1954 FIXME("Unsupported 3D grad function.\n");
1955 sample_function->name = "unsupported3DGrad";
1956 }
1957 }
1958 else
1959 {
1960 sample_function->name = projected ? "texture3DProj" : "texture3D";
1961 }
1962 sample_function->coord_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
1963 break;
1964 default:
1965 sample_function->name = "";
1966 sample_function->coord_mask = 0;
1967 FIXME("Unrecognized sampler type: %#x;\n", sampler_type);
1968 break;
1969 }
1970}
1971
1972static void shader_glsl_append_fixup_arg(char *arguments, const char *reg_name,
1973 BOOL sign_fixup, enum fixup_channel_source channel_source)
1974{
1975 switch(channel_source)
1976 {
1977 case CHANNEL_SOURCE_ZERO:
1978 strcat(arguments, "0.0");
1979 break;
1980
1981 case CHANNEL_SOURCE_ONE:
1982 strcat(arguments, "1.0");
1983 break;
1984
1985 case CHANNEL_SOURCE_X:
1986 strcat(arguments, reg_name);
1987 strcat(arguments, ".x");
1988 break;
1989
1990 case CHANNEL_SOURCE_Y:
1991 strcat(arguments, reg_name);
1992 strcat(arguments, ".y");
1993 break;
1994
1995 case CHANNEL_SOURCE_Z:
1996 strcat(arguments, reg_name);
1997 strcat(arguments, ".z");
1998 break;
1999
2000 case CHANNEL_SOURCE_W:
2001 strcat(arguments, reg_name);
2002 strcat(arguments, ".w");
2003 break;
2004
2005 default:
2006 FIXME("Unhandled channel source %#x\n", channel_source);
2007 strcat(arguments, "undefined");
2008 break;
2009 }
2010
2011 if (sign_fixup) strcat(arguments, " * 2.0 - 1.0");
2012}
2013
2014static void shader_glsl_color_correction(const struct wined3d_shader_instruction *ins, struct color_fixup_desc fixup)
2015{
2016 struct wined3d_shader_dst_param dst;
2017 unsigned int mask_size, remaining;
2018 glsl_dst_param_t dst_param;
2019 char arguments[256];
2020 DWORD mask;
2021
2022 mask = 0;
2023 if (fixup.x_sign_fixup || fixup.x_source != CHANNEL_SOURCE_X) mask |= WINED3DSP_WRITEMASK_0;
2024 if (fixup.y_sign_fixup || fixup.y_source != CHANNEL_SOURCE_Y) mask |= WINED3DSP_WRITEMASK_1;
2025 if (fixup.z_sign_fixup || fixup.z_source != CHANNEL_SOURCE_Z) mask |= WINED3DSP_WRITEMASK_2;
2026 if (fixup.w_sign_fixup || fixup.w_source != CHANNEL_SOURCE_W) mask |= WINED3DSP_WRITEMASK_3;
2027 mask &= ins->dst[0].write_mask;
2028
2029 if (!mask) return; /* Nothing to do */
2030
2031 if (is_complex_fixup(fixup))
2032 {
2033 enum complex_fixup complex_fixup = get_complex_fixup(fixup);
2034 FIXME("Complex fixup (%#x) not supported\n",complex_fixup); (void)complex_fixup;
2035 return;
2036 }
2037
2038 mask_size = shader_glsl_get_write_mask_size(mask);
2039
2040 dst = ins->dst[0];
2041 dst.write_mask = mask;
2042 shader_glsl_add_dst_param(ins, &dst, &dst_param);
2043
2044 arguments[0] = '\0';
2045 remaining = mask_size;
2046 if (mask & WINED3DSP_WRITEMASK_0)
2047 {
2048 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.x_sign_fixup, fixup.x_source);
2049 if (--remaining) strcat(arguments, ", ");
2050 }
2051 if (mask & WINED3DSP_WRITEMASK_1)
2052 {
2053 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.y_sign_fixup, fixup.y_source);
2054 if (--remaining) strcat(arguments, ", ");
2055 }
2056 if (mask & WINED3DSP_WRITEMASK_2)
2057 {
2058 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.z_sign_fixup, fixup.z_source);
2059 if (--remaining) strcat(arguments, ", ");
2060 }
2061 if (mask & WINED3DSP_WRITEMASK_3)
2062 {
2063 shader_glsl_append_fixup_arg(arguments, dst_param.reg_name, fixup.w_sign_fixup, fixup.w_source);
2064 if (--remaining) strcat(arguments, ", ");
2065 }
2066
2067 if (mask_size > 1)
2068 {
2069 shader_addline(ins->ctx->buffer, "%s%s = vec%u(%s);\n",
2070 dst_param.reg_name, dst_param.mask_str, mask_size, arguments);
2071 }
2072 else
2073 {
2074 shader_addline(ins->ctx->buffer, "%s%s = %s;\n", dst_param.reg_name, dst_param.mask_str, arguments);
2075 }
2076}
2077
2078static void PRINTF_ATTR(8, 9) shader_glsl_gen_sample_code(const struct wined3d_shader_instruction *ins,
2079 DWORD sampler, const glsl_sample_function_t *sample_function, DWORD swizzle,
2080 const char *dx, const char *dy,
2081 const char *bias, const char *coord_reg_fmt, ...)
2082{
2083 const char *sampler_base;
2084 char dst_swizzle[6];
2085 struct color_fixup_desc fixup;
2086 BOOL np2_fixup = FALSE;
2087 BOOL tmirror_tmp_reg = FALSE;
2088 va_list args;
2089
2090 shader_glsl_swizzle_to_str(swizzle, FALSE, ins->dst[0].write_mask, dst_swizzle);
2091
2092 if (shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
2093 {
2094 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2095 fixup = priv->cur_ps_args->color_fixup[sampler];
2096 sampler_base = "Psampler";
2097
2098 if (priv->cur_ps_args->np2_fixup & (1 << sampler)) {
2099 if(bias) {
2100 FIXME("Biased sampling from NP2 textures is unsupported\n");
2101 } else {
2102 np2_fixup = TRUE;
2103 }
2104 }
2105
2106 if (priv->cur_ps_args->t_mirror & (1 << sampler))
2107 {
2108 if (ins->ctx->reg_maps->sampler_type[sampler]==WINED3DSTT_2D)
2109 {
2110 if (sample_function->coord_mask & WINED3DSP_WRITEMASK_1)
2111 {
2112 glsl_src_param_t coord_param;
2113 shader_glsl_add_src_param(ins, &ins->src[0], sample_function->coord_mask, &coord_param);
2114
2115 if (ins->src[0].reg.type != WINED3DSPR_INPUT)
2116 {
2117 shader_addline(ins->ctx->buffer, "%s.y=1.0-%s.y;\n",
2118 coord_param.reg_name, coord_param.reg_name);
2119 }
2120 else
2121 {
2122 tmirror_tmp_reg = TRUE;
2123 shader_addline(ins->ctx->buffer, "tmp0.xy=vec2(%s.x, 1.0-%s.y).xy;\n",
2124 coord_param.reg_name, coord_param.reg_name);
2125 }
2126 }
2127 else
2128 {
2129 DebugBreak();
2130 FIXME("Unexpected coord_mask with t_mirror\n");
2131 }
2132 }
2133 }
2134 } else {
2135 sampler_base = "Vsampler";
2136 fixup = COLOR_FIXUP_IDENTITY; /* FIXME: Vshader color fixup */
2137 }
2138
2139 shader_glsl_append_dst(ins->ctx->buffer, ins);
2140
2141 shader_addline(ins->ctx->buffer, "%s(%s%u, ", sample_function->name, sampler_base, sampler);
2142
2143 if (tmirror_tmp_reg)
2144 {
2145 shader_addline(ins->ctx->buffer, "%s", "tmp0.xy");
2146 }
2147 else
2148 {
2149 va_start(args, coord_reg_fmt);
2150 shader_vaddline(ins->ctx->buffer, coord_reg_fmt, args);
2151 va_end(args);
2152 }
2153
2154 if(bias) {
2155 shader_addline(ins->ctx->buffer, ", %s)%s);\n", bias, dst_swizzle);
2156 } else {
2157 if (np2_fixup) {
2158 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
2159 const unsigned char idx = priv->cur_np2fixup_info->idx[sampler];
2160
2161 shader_addline(ins->ctx->buffer, " * PsamplerNP2Fixup[%u].%s)%s);\n", idx >> 1,
2162 (idx % 2) ? "zw" : "xy", dst_swizzle);
2163 } else if(dx && dy) {
2164 shader_addline(ins->ctx->buffer, ", %s, %s)%s);\n", dx, dy, dst_swizzle);
2165 } else {
2166 shader_addline(ins->ctx->buffer, ")%s);\n", dst_swizzle);
2167 }
2168 }
2169
2170 if(!is_identity_fixup(fixup)) {
2171 shader_glsl_color_correction(ins, fixup);
2172 }
2173}
2174
2175/*****************************************************************************
2176 * Begin processing individual instruction opcodes
2177 ****************************************************************************/
2178
2179/* Generate GLSL arithmetic functions (dst = src1 + src2) */
2180static void shader_glsl_arith(const struct wined3d_shader_instruction *ins)
2181{
2182 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2183 glsl_src_param_t src0_param;
2184 glsl_src_param_t src1_param;
2185 DWORD write_mask;
2186 char op;
2187
2188 /* Determine the GLSL operator to use based on the opcode */
2189 switch (ins->handler_idx)
2190 {
2191 case WINED3DSIH_MUL: op = '*'; break;
2192 case WINED3DSIH_ADD: op = '+'; break;
2193 case WINED3DSIH_SUB: op = '-'; break;
2194 default:
2195 op = ' ';
2196 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2197 break;
2198 }
2199
2200 write_mask = shader_glsl_append_dst(buffer, ins);
2201 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2202 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2203 shader_addline(buffer, "%s %c %s);\n", src0_param.param_str, op, src1_param.param_str);
2204}
2205
2206#ifdef VBOX_WITH_VMSVGA
2207static void shader_glsl_mov_impl(const struct wined3d_shader_instruction *ins, int p0_idx);
2208
2209/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2210static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2211{
2212 if (ins->predicate)
2213 {
2214 int i;
2215 DWORD dst_mask = ins->dst[0].write_mask;
2216 struct wined3d_shader_dst_param *dst = (struct wined3d_shader_dst_param *)&ins->dst[0];
2217
2218 for (i = 0; i < 4; i++)
2219 {
2220 if (dst_mask & RT_BIT(i))
2221 {
2222 dst->write_mask = RT_BIT(i);
2223
2224 shader_glsl_mov_impl(ins, i);
2225 }
2226 }
2227 dst->write_mask = dst_mask;
2228 }
2229 else
2230 shader_glsl_mov_impl(ins, 0);
2231}
2232
2233/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2234static void shader_glsl_mov_impl(const struct wined3d_shader_instruction *ins, int p0_idx)
2235
2236#else
2237/* Process the WINED3DSIO_MOV opcode using GLSL (dst = src) */
2238static void shader_glsl_mov(const struct wined3d_shader_instruction *ins)
2239#endif
2240{
2241 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
2242 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2243 glsl_src_param_t src0_param;
2244 DWORD write_mask;
2245
2246#ifdef VBOX_WITH_VMSVGA
2247 if (ins->predicate)
2248 {
2249 shader_addline(buffer, "if (p0[%d]) {\n", p0_idx);
2250 }
2251#endif
2252
2253 write_mask = shader_glsl_append_dst(buffer, ins);
2254 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2255
2256 /* In vs_1_1 WINED3DSIO_MOV can write to the address register. In later
2257 * shader versions WINED3DSIO_MOVA is used for this. */
2258 if (ins->ctx->reg_maps->shader_version.major == 1
2259 && !shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type)
2260 && ins->dst[0].reg.type == WINED3DSPR_ADDR)
2261 {
2262 /* This is a simple floor() */
2263 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2264 if (mask_size > 1) {
2265 shader_addline(buffer, "ivec%d(floor(%s)));\n", mask_size, src0_param.param_str);
2266 } else {
2267 shader_addline(buffer, "int(floor(%s)));\n", src0_param.param_str);
2268 }
2269 }
2270 else if(ins->handler_idx == WINED3DSIH_MOVA)
2271 {
2272 /* We need to *round* to the nearest int here. */
2273 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
2274
2275 if (gl_info->supported[EXT_GPU_SHADER4])
2276 {
2277 if (mask_size > 1)
2278 shader_addline(buffer, "ivec%d(round(%s)));\n", mask_size, src0_param.param_str);
2279 else
2280 shader_addline(buffer, "int(round(%s)));\n", src0_param.param_str);
2281 }
2282 else
2283 {
2284 if (mask_size > 1)
2285 shader_addline(buffer, "ivec%d(floor(abs(%s) + vec%d(0.5)) * sign(%s)));\n",
2286 mask_size, src0_param.param_str, mask_size, src0_param.param_str);
2287 else
2288 shader_addline(buffer, "int(floor(abs(%s) + 0.5) * sign(%s)));\n",
2289 src0_param.param_str, src0_param.param_str);
2290 }
2291 }
2292 else
2293 {
2294 shader_addline(buffer, "%s);\n", src0_param.param_str);
2295 }
2296#ifdef VBOX_WITH_VMSVGA
2297 if (ins->predicate)
2298 {
2299 shader_addline(buffer, "}\n");
2300 }
2301#endif
2302}
2303
2304/* Process the dot product operators DP3 and DP4 in GLSL (dst = dot(src0, src1)) */
2305static void shader_glsl_dot(const struct wined3d_shader_instruction *ins)
2306{
2307 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2308 glsl_src_param_t src0_param;
2309 glsl_src_param_t src1_param;
2310 DWORD dst_write_mask, src_write_mask;
2311 unsigned int dst_size = 0;
2312
2313 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2314 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2315
2316 /* dp3 works on vec3, dp4 on vec4 */
2317 if (ins->handler_idx == WINED3DSIH_DP4)
2318 {
2319 src_write_mask = WINED3DSP_WRITEMASK_ALL;
2320 } else {
2321 src_write_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2322 }
2323
2324 shader_glsl_add_src_param(ins, &ins->src[0], src_write_mask, &src0_param);
2325 shader_glsl_add_src_param(ins, &ins->src[1], src_write_mask, &src1_param);
2326
2327 if (dst_size > 1) {
2328 shader_addline(buffer, "vec%d(dot(%s, %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2329 } else {
2330 shader_addline(buffer, "dot(%s, %s));\n", src0_param.param_str, src1_param.param_str);
2331 }
2332}
2333
2334/* Note that this instruction has some restrictions. The destination write mask
2335 * can't contain the w component, and the source swizzles have to be .xyzw */
2336static void shader_glsl_cross(const struct wined3d_shader_instruction *ins)
2337{
2338 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
2339 glsl_src_param_t src0_param;
2340 glsl_src_param_t src1_param;
2341 char dst_mask[6];
2342
2343 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2344 shader_glsl_append_dst(ins->ctx->buffer, ins);
2345 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
2346 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
2347 shader_addline(ins->ctx->buffer, "cross(%s, %s)%s);\n", src0_param.param_str, src1_param.param_str, dst_mask);
2348}
2349
2350/* Process the WINED3DSIO_POW instruction in GLSL (dst = |src0|^src1)
2351 * Src0 and src1 are scalars. Note that D3D uses the absolute of src0, while
2352 * GLSL uses the value as-is. */
2353static void shader_glsl_pow(const struct wined3d_shader_instruction *ins)
2354{
2355 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2356 glsl_src_param_t src0_param;
2357 glsl_src_param_t src1_param;
2358 DWORD dst_write_mask;
2359 unsigned int dst_size;
2360
2361 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2362 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2363
2364 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2365 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
2366
2367 if (dst_size > 1) {
2368 shader_addline(buffer, "vec%d(pow(abs(%s), %s)));\n", dst_size, src0_param.param_str, src1_param.param_str);
2369 } else {
2370 shader_addline(buffer, "pow(abs(%s), %s));\n", src0_param.param_str, src1_param.param_str);
2371 }
2372}
2373
2374/* Process the WINED3DSIO_LOG instruction in GLSL (dst = log2(|src0|))
2375 * Src0 is a scalar. Note that D3D uses the absolute of src0, while
2376 * GLSL uses the value as-is. */
2377static void shader_glsl_log(const struct wined3d_shader_instruction *ins)
2378{
2379 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2380 glsl_src_param_t src0_param;
2381 DWORD dst_write_mask;
2382 unsigned int dst_size;
2383
2384 dst_write_mask = shader_glsl_append_dst(buffer, ins);
2385 dst_size = shader_glsl_get_write_mask_size(dst_write_mask);
2386
2387 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2388
2389 if (dst_size > 1)
2390 {
2391 shader_addline(buffer, "vec%d(%s == 0.0 ? -FLT_MAX : log2(abs(%s))));\n",
2392 dst_size, src0_param.param_str, src0_param.param_str);
2393 }
2394 else
2395 {
2396 shader_addline(buffer, "%s == 0.0 ? -FLT_MAX : log2(abs(%s)));\n",
2397 src0_param.param_str, src0_param.param_str);
2398 }
2399}
2400
2401/* Map the opcode 1-to-1 to the GL code (arg->dst = instruction(src0, src1, ...) */
2402static void shader_glsl_map2gl(const struct wined3d_shader_instruction *ins)
2403{
2404 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2405 glsl_src_param_t src_param;
2406 const char *instruction;
2407 DWORD write_mask;
2408 unsigned i;
2409
2410 /* Determine the GLSL function to use based on the opcode */
2411 /* TODO: Possibly make this a table for faster lookups */
2412 switch (ins->handler_idx)
2413 {
2414 case WINED3DSIH_MIN: instruction = "min"; break;
2415 case WINED3DSIH_MAX: instruction = "max"; break;
2416 case WINED3DSIH_ABS: instruction = "abs"; break;
2417 case WINED3DSIH_FRC: instruction = "fract"; break;
2418 case WINED3DSIH_EXP: instruction = "exp2"; break;
2419 case WINED3DSIH_DSX: instruction = "dFdx"; break;
2420 case WINED3DSIH_DSY: instruction = "ycorrection.y * dFdy"; break;
2421 default: instruction = "";
2422 FIXME("Opcode %#x not yet handled in GLSL\n", ins->handler_idx);
2423 break;
2424 }
2425
2426 write_mask = shader_glsl_append_dst(buffer, ins);
2427
2428 shader_addline(buffer, "%s(", instruction);
2429
2430 if (ins->src_count)
2431 {
2432 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2433 shader_addline(buffer, "%s", src_param.param_str);
2434 for (i = 1; i < ins->src_count; ++i)
2435 {
2436 shader_glsl_add_src_param(ins, &ins->src[i], write_mask, &src_param);
2437 shader_addline(buffer, ", %s", src_param.param_str);
2438 }
2439 }
2440
2441 shader_addline(buffer, "));\n");
2442}
2443
2444static void shader_glsl_nrm(const struct wined3d_shader_instruction *ins)
2445{
2446 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2447 glsl_src_param_t src_param;
2448 unsigned int mask_size;
2449 DWORD write_mask;
2450 char dst_mask[6];
2451
2452 write_mask = shader_glsl_get_write_mask(ins->dst, dst_mask);
2453 mask_size = shader_glsl_get_write_mask_size(write_mask);
2454 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param);
2455
2456 shader_addline(buffer, "tmp0.x = length(%s);\n", src_param.param_str);
2457 shader_glsl_append_dst(buffer, ins);
2458 if (mask_size > 1)
2459 {
2460 shader_addline(buffer, "tmp0.x == 0.0 ? vec%u(0.0) : (%s / tmp0.x));\n",
2461 mask_size, src_param.param_str);
2462 }
2463 else
2464 {
2465 shader_addline(buffer, "tmp0.x == 0.0 ? 0.0 : (%s / tmp0.x));\n",
2466 src_param.param_str);
2467 }
2468}
2469
2470/** Process the WINED3DSIO_EXPP instruction in GLSL:
2471 * For shader model 1.x, do the following (and honor the writemask, so use a temporary variable):
2472 * dst.x = 2^(floor(src))
2473 * dst.y = src - floor(src)
2474 * dst.z = 2^src (partial precision is allowed, but optional)
2475 * dst.w = 1.0;
2476 * For 2.0 shaders, just do this (honoring writemask and swizzle):
2477 * dst = 2^src; (partial precision is allowed, but optional)
2478 */
2479static void shader_glsl_expp(const struct wined3d_shader_instruction *ins)
2480{
2481 glsl_src_param_t src_param;
2482
2483 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src_param);
2484
2485 if (ins->ctx->reg_maps->shader_version.major < 2)
2486 {
2487 char dst_mask[6];
2488
2489 shader_addline(ins->ctx->buffer, "tmp0.x = exp2(floor(%s));\n", src_param.param_str);
2490 shader_addline(ins->ctx->buffer, "tmp0.y = %s - floor(%s);\n", src_param.param_str, src_param.param_str);
2491 shader_addline(ins->ctx->buffer, "tmp0.z = exp2(%s);\n", src_param.param_str);
2492 shader_addline(ins->ctx->buffer, "tmp0.w = 1.0;\n");
2493
2494 shader_glsl_append_dst(ins->ctx->buffer, ins);
2495 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2496 shader_addline(ins->ctx->buffer, "tmp0%s);\n", dst_mask);
2497 } else {
2498 DWORD write_mask;
2499 unsigned int mask_size;
2500
2501 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2502 mask_size = shader_glsl_get_write_mask_size(write_mask);
2503
2504 if (mask_size > 1) {
2505 shader_addline(ins->ctx->buffer, "vec%d(exp2(%s)));\n", mask_size, src_param.param_str);
2506 } else {
2507 shader_addline(ins->ctx->buffer, "exp2(%s));\n", src_param.param_str);
2508 }
2509 }
2510}
2511
2512/** Process the RCP (reciprocal or inverse) opcode in GLSL (dst = 1 / src) */
2513static void shader_glsl_rcp(const struct wined3d_shader_instruction *ins)
2514{
2515 glsl_src_param_t src_param;
2516 DWORD write_mask;
2517 unsigned int mask_size;
2518
2519 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2520 mask_size = shader_glsl_get_write_mask_size(write_mask);
2521 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2522
2523 if (mask_size > 1)
2524 {
2525 shader_addline(ins->ctx->buffer, "vec%d(%s == 0.0 ? FLT_MAX : 1.0 / %s));\n",
2526 mask_size, src_param.param_str, src_param.param_str);
2527 }
2528 else
2529 {
2530 shader_addline(ins->ctx->buffer, "%s == 0.0 ? FLT_MAX : 1.0 / %s);\n",
2531 src_param.param_str, src_param.param_str);
2532 }
2533}
2534
2535static void shader_glsl_rsq(const struct wined3d_shader_instruction *ins)
2536{
2537 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2538 glsl_src_param_t src_param;
2539 DWORD write_mask;
2540 unsigned int mask_size;
2541
2542 write_mask = shader_glsl_append_dst(buffer, ins);
2543 mask_size = shader_glsl_get_write_mask_size(write_mask);
2544
2545 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src_param);
2546
2547 if (mask_size > 1)
2548 {
2549 shader_addline(buffer, "vec%d(%s == 0.0 ? FLT_MAX : inversesqrt(abs(%s))));\n",
2550 mask_size, src_param.param_str, src_param.param_str);
2551 }
2552 else
2553 {
2554 shader_addline(buffer, "%s == 0.0 ? FLT_MAX : inversesqrt(abs(%s)));\n",
2555 src_param.param_str, src_param.param_str);
2556 }
2557}
2558
2559#ifdef VBOX_WITH_VMSVGA
2560static void shader_glsl_setp(const struct wined3d_shader_instruction *ins)
2561{
2562 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
2563 glsl_src_param_t src_param1, src_param2;
2564 DWORD write_mask;
2565
2566 int i;
2567 DWORD dst_mask = ins->dst[0].write_mask;
2568 struct wined3d_shader_dst_param dst = ins->dst[0];
2569
2570 /* Cycle through all source0 channels */
2571 for (i=0; i<4; i++) {
2572 if (dst_mask & RT_BIT(i))
2573 {
2574 write_mask = WINED3DSP_WRITEMASK_0 << i;
2575 dst.write_mask = dst_mask & write_mask;
2576
2577 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2578 Assert(write_mask);
2579
2580 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src_param1);
2581 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src_param2);
2582
2583 shader_addline(buffer, "%s %s %s);\n",
2584 src_param1.param_str, shader_get_comp_op(ins->flags), src_param2.param_str);
2585 }
2586 }
2587}
2588#endif
2589
2590/** Process signed comparison opcodes in GLSL. */
2591static void shader_glsl_compare(const struct wined3d_shader_instruction *ins)
2592{
2593 glsl_src_param_t src0_param;
2594 glsl_src_param_t src1_param;
2595 DWORD write_mask;
2596 unsigned int mask_size;
2597
2598 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2599 mask_size = shader_glsl_get_write_mask_size(write_mask);
2600 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2601 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2602
2603 if (mask_size > 1) {
2604 const char *compare;
2605
2606 switch(ins->handler_idx)
2607 {
2608 case WINED3DSIH_SLT: compare = "lessThan"; break;
2609 case WINED3DSIH_SGE: compare = "greaterThanEqual"; break;
2610 default: compare = "";
2611 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2612 }
2613
2614 shader_addline(ins->ctx->buffer, "vec%d(%s(%s, %s)));\n", mask_size, compare,
2615 src0_param.param_str, src1_param.param_str);
2616 } else {
2617 switch(ins->handler_idx)
2618 {
2619 case WINED3DSIH_SLT:
2620 /* Step(src0, src1) is not suitable here because if src0 == src1 SLT is supposed,
2621 * to return 0.0 but step returns 1.0 because step is not < x
2622 * An alternative is a bvec compare padded with an unused second component.
2623 * step(src1 * -1.0, src0 * -1.0) is not an option because it suffers from the same
2624 * issue. Playing with not() is not possible either because not() does not accept
2625 * a scalar.
2626 */
2627 shader_addline(ins->ctx->buffer, "(%s < %s) ? 1.0 : 0.0);\n",
2628 src0_param.param_str, src1_param.param_str);
2629 break;
2630 case WINED3DSIH_SGE:
2631 /* Here we can use the step() function and safe a conditional */
2632 shader_addline(ins->ctx->buffer, "step(%s, %s));\n", src1_param.param_str, src0_param.param_str);
2633 break;
2634 default:
2635 FIXME("Can't handle opcode %#x\n", ins->handler_idx);
2636 }
2637
2638 }
2639}
2640
2641/** Process CMP instruction in GLSL (dst = src0 >= 0.0 ? src1 : src2), per channel */
2642static void shader_glsl_cmp(const struct wined3d_shader_instruction *ins)
2643{
2644 glsl_src_param_t src0_param;
2645 glsl_src_param_t src1_param;
2646 glsl_src_param_t src2_param;
2647 DWORD write_mask, cmp_channel = 0;
2648 unsigned int i, j;
2649 char mask_char[6];
2650 BOOL temp_destination = FALSE;
2651
2652 if (shader_is_scalar(&ins->src[0].reg))
2653 {
2654 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2655
2656 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
2657 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2658 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2659
2660 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2661 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2662 } else {
2663 DWORD dst_mask = ins->dst[0].write_mask;
2664 struct wined3d_shader_dst_param dst = ins->dst[0];
2665
2666 /* Cycle through all source0 channels */
2667 for (i=0; i<4; i++) {
2668 write_mask = 0;
2669 /* Find the destination channels which use the current source0 channel */
2670 for (j=0; j<4; j++) {
2671 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2672 {
2673 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2674 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2675 }
2676 }
2677 dst.write_mask = dst_mask & write_mask;
2678
2679 /* Splitting the cmp instruction up in multiple lines imposes a problem:
2680 * The first lines may overwrite source parameters of the following lines.
2681 * Deal with that by using a temporary destination register if needed
2682 */
2683 if ((ins->src[0].reg.idx == ins->dst[0].reg.idx
2684 && ins->src[0].reg.type == ins->dst[0].reg.type)
2685 || (ins->src[1].reg.idx == ins->dst[0].reg.idx
2686 && ins->src[1].reg.type == ins->dst[0].reg.type)
2687 || (ins->src[2].reg.idx == ins->dst[0].reg.idx
2688 && ins->src[2].reg.type == ins->dst[0].reg.type))
2689 {
2690 write_mask = shader_glsl_get_write_mask(&dst, mask_char);
2691 if (!write_mask) continue;
2692 shader_addline(ins->ctx->buffer, "tmp0%s = (", mask_char);
2693 temp_destination = TRUE;
2694 } else {
2695 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2696 if (!write_mask) continue;
2697 }
2698
2699 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2700 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2701 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2702
2703 shader_addline(ins->ctx->buffer, "%s >= 0.0 ? %s : %s);\n",
2704 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2705 }
2706
2707 if(temp_destination) {
2708 shader_glsl_get_write_mask(&ins->dst[0], mask_char);
2709 shader_glsl_append_dst(ins->ctx->buffer, ins);
2710 shader_addline(ins->ctx->buffer, "tmp0%s);\n", mask_char);
2711 }
2712 }
2713
2714}
2715
2716/** Process the CND opcode in GLSL (dst = (src0 > 0.5) ? src1 : src2) */
2717/* For ps 1.1-1.3, only a single component of src0 is used. For ps 1.4
2718 * the compare is done per component of src0. */
2719static void shader_glsl_cnd(const struct wined3d_shader_instruction *ins)
2720{
2721 struct wined3d_shader_dst_param dst;
2722 glsl_src_param_t src0_param;
2723 glsl_src_param_t src1_param;
2724 glsl_src_param_t src2_param;
2725 DWORD write_mask, cmp_channel = 0;
2726 unsigned int i, j;
2727 DWORD dst_mask;
2728 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
2729 ins->ctx->reg_maps->shader_version.minor);
2730
2731 if (shader_version < WINED3D_SHADER_VERSION(1, 4))
2732 {
2733 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2734 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2735 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2736 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2737
2738 /* Fun: The D3DSI_COISSUE flag changes the semantic of the cnd instruction for < 1.4 shaders */
2739 if (ins->coissue)
2740 {
2741 shader_addline(ins->ctx->buffer, "%s /* COISSUE! */);\n", src1_param.param_str);
2742 } else {
2743 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2744 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2745 }
2746 return;
2747 }
2748 /* Cycle through all source0 channels */
2749 dst_mask = ins->dst[0].write_mask;
2750 dst = ins->dst[0];
2751 for (i=0; i<4; i++) {
2752 write_mask = 0;
2753 /* Find the destination channels which use the current source0 channel */
2754 for (j=0; j<4; j++) {
2755 if (((ins->src[0].swizzle >> (2 * j)) & 0x3) == i)
2756 {
2757 write_mask |= WINED3DSP_WRITEMASK_0 << j;
2758 cmp_channel = WINED3DSP_WRITEMASK_0 << j;
2759 }
2760 }
2761
2762 dst.write_mask = dst_mask & write_mask;
2763 write_mask = shader_glsl_append_dst_ext(ins->ctx->buffer, ins, &dst);
2764 if (!write_mask) continue;
2765
2766 shader_glsl_add_src_param(ins, &ins->src[0], cmp_channel, &src0_param);
2767 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2768 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2769
2770 shader_addline(ins->ctx->buffer, "%s > 0.5 ? %s : %s);\n",
2771 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2772 }
2773}
2774
2775/** GLSL code generation for WINED3DSIO_MAD: Multiply the first 2 opcodes, then add the last */
2776static void shader_glsl_mad(const struct wined3d_shader_instruction *ins)
2777{
2778 glsl_src_param_t src0_param;
2779 glsl_src_param_t src1_param;
2780 glsl_src_param_t src2_param;
2781 DWORD write_mask;
2782
2783 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2784 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2785 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2786 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2787 shader_addline(ins->ctx->buffer, "(%s * %s) + %s);\n",
2788 src0_param.param_str, src1_param.param_str, src2_param.param_str);
2789}
2790
2791/* Handles transforming all WINED3DSIO_M?x? opcodes for
2792 Vertex shaders to GLSL codes */
2793static void shader_glsl_mnxn(const struct wined3d_shader_instruction *ins)
2794{
2795 int i;
2796 int nComponents = 0;
2797 struct wined3d_shader_dst_param tmp_dst = {{0}};
2798 struct wined3d_shader_src_param tmp_src[2] = {{{0}}};
2799 struct wined3d_shader_instruction tmp_ins;
2800
2801 memset(&tmp_ins, 0, sizeof(tmp_ins));
2802
2803 /* Set constants for the temporary argument */
2804 tmp_ins.ctx = ins->ctx;
2805 tmp_ins.dst_count = 1;
2806 tmp_ins.dst = &tmp_dst;
2807 tmp_ins.src_count = 2;
2808 tmp_ins.src = tmp_src;
2809
2810 switch(ins->handler_idx)
2811 {
2812 case WINED3DSIH_M4x4:
2813 nComponents = 4;
2814 tmp_ins.handler_idx = WINED3DSIH_DP4;
2815 break;
2816 case WINED3DSIH_M4x3:
2817 nComponents = 3;
2818 tmp_ins.handler_idx = WINED3DSIH_DP4;
2819 break;
2820 case WINED3DSIH_M3x4:
2821 nComponents = 4;
2822 tmp_ins.handler_idx = WINED3DSIH_DP3;
2823 break;
2824 case WINED3DSIH_M3x3:
2825 nComponents = 3;
2826 tmp_ins.handler_idx = WINED3DSIH_DP3;
2827 break;
2828 case WINED3DSIH_M3x2:
2829 nComponents = 2;
2830 tmp_ins.handler_idx = WINED3DSIH_DP3;
2831 break;
2832 default:
2833 break;
2834 }
2835
2836 tmp_dst = ins->dst[0];
2837 tmp_src[0] = ins->src[0];
2838 tmp_src[1] = ins->src[1];
2839 for (i = 0; i < nComponents; ++i)
2840 {
2841 tmp_dst.write_mask = WINED3DSP_WRITEMASK_0 << i;
2842 shader_glsl_dot(&tmp_ins);
2843 ++tmp_src[1].reg.idx;
2844 }
2845}
2846
2847/**
2848 The LRP instruction performs a component-wise linear interpolation
2849 between the second and third operands using the first operand as the
2850 blend factor. Equation: (dst = src2 + src0 * (src1 - src2))
2851 This is equivalent to mix(src2, src1, src0);
2852*/
2853static void shader_glsl_lrp(const struct wined3d_shader_instruction *ins)
2854{
2855 glsl_src_param_t src0_param;
2856 glsl_src_param_t src1_param;
2857 glsl_src_param_t src2_param;
2858 DWORD write_mask;
2859
2860 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2861
2862 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2863 shader_glsl_add_src_param(ins, &ins->src[1], write_mask, &src1_param);
2864 shader_glsl_add_src_param(ins, &ins->src[2], write_mask, &src2_param);
2865
2866 shader_addline(ins->ctx->buffer, "mix(%s, %s, %s));\n",
2867 src2_param.param_str, src1_param.param_str, src0_param.param_str);
2868}
2869
2870/** Process the WINED3DSIO_LIT instruction in GLSL:
2871 * dst.x = dst.w = 1.0
2872 * dst.y = (src0.x > 0) ? src0.x
2873 * dst.z = (src0.x > 0) ? ((src0.y > 0) ? pow(src0.y, src.w) : 0) : 0
2874 * where src.w is clamped at +- 128
2875 */
2876static void shader_glsl_lit(const struct wined3d_shader_instruction *ins)
2877{
2878 glsl_src_param_t src0_param;
2879 glsl_src_param_t src1_param;
2880 glsl_src_param_t src3_param;
2881 char dst_mask[6];
2882
2883 shader_glsl_append_dst(ins->ctx->buffer, ins);
2884 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2885
2886 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2887 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src1_param);
2888 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &src3_param);
2889
2890 /* The sdk specifies the instruction like this
2891 * dst.x = 1.0;
2892 * if(src.x > 0.0) dst.y = src.x
2893 * else dst.y = 0.0.
2894 * if(src.x > 0.0 && src.y > 0.0) dst.z = pow(src.y, power);
2895 * else dst.z = 0.0;
2896 * dst.w = 1.0;
2897 *
2898 * Obviously that has quite a few conditionals in it which we don't like. So the first step is this:
2899 * dst.x = 1.0 ... No further explanation needed
2900 * dst.y = max(src.y, 0.0); ... If x < 0.0, use 0.0, otherwise x. Same as the conditional
2901 * dst.z = x > 0.0 ? pow(max(y, 0.0), p) : 0; ... 0 ^ power is 0, and otherwise we use y anyway
2902 * dst.w = 1.0. ... Nothing fancy.
2903 *
2904 * So we still have one conditional in there. So do this:
2905 * dst.z = pow(max(0.0, src.y) * step(0.0, src.x), power);
2906 *
2907 * step(0.0, x) will return 1 if src.x > 0.0, and 0 otherwise. So if y is 0 we get pow(0.0 * 1.0, power),
2908 * which sets dst.z to 0. If y > 0, but x = 0.0, we get pow(y * 0.0, power), which results in 0 too.
2909 * if both x and y are > 0, we get pow(y * 1.0, power), as it is supposed to
2910 */
2911 shader_addline(ins->ctx->buffer,
2912 "vec4(1.0, max(%s, 0.0), pow(max(0.0, %s) * step(0.0, %s), clamp(%s, -128.0, 128.0)), 1.0)%s);\n",
2913 src0_param.param_str, src1_param.param_str, src0_param.param_str, src3_param.param_str, dst_mask);
2914}
2915
2916/** Process the WINED3DSIO_DST instruction in GLSL:
2917 * dst.x = 1.0
2918 * dst.y = src0.x * src0.y
2919 * dst.z = src0.z
2920 * dst.w = src1.w
2921 */
2922static void shader_glsl_dst(const struct wined3d_shader_instruction *ins)
2923{
2924 glsl_src_param_t src0y_param;
2925 glsl_src_param_t src0z_param;
2926 glsl_src_param_t src1y_param;
2927 glsl_src_param_t src1w_param;
2928 char dst_mask[6];
2929
2930 shader_glsl_append_dst(ins->ctx->buffer, ins);
2931 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
2932
2933 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_1, &src0y_param);
2934 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &src0z_param);
2935 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_1, &src1y_param);
2936 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_3, &src1w_param);
2937
2938 shader_addline(ins->ctx->buffer, "vec4(1.0, %s * %s, %s, %s))%s;\n",
2939 src0y_param.param_str, src1y_param.param_str, src0z_param.param_str, src1w_param.param_str, dst_mask);
2940}
2941
2942/** Process the WINED3DSIO_SINCOS instruction in GLSL:
2943 * VS 2.0 requires that specific cosine and sine constants be passed to this instruction so the hardware
2944 * can handle it. But, these functions are built-in for GLSL, so we can just ignore the last 2 params.
2945 *
2946 * dst.x = cos(src0.?)
2947 * dst.y = sin(src0.?)
2948 * dst.z = dst.z
2949 * dst.w = dst.w
2950 */
2951static void shader_glsl_sincos(const struct wined3d_shader_instruction *ins)
2952{
2953 glsl_src_param_t src0_param;
2954 DWORD write_mask;
2955
2956 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2957 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
2958
2959 switch (write_mask) {
2960 case WINED3DSP_WRITEMASK_0:
2961 shader_addline(ins->ctx->buffer, "cos(%s));\n", src0_param.param_str);
2962 break;
2963
2964 case WINED3DSP_WRITEMASK_1:
2965 shader_addline(ins->ctx->buffer, "sin(%s));\n", src0_param.param_str);
2966 break;
2967
2968 case (WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1):
2969 shader_addline(ins->ctx->buffer, "vec2(cos(%s), sin(%s)));\n", src0_param.param_str, src0_param.param_str);
2970 break;
2971
2972 default:
2973 ERR("Write mask should be .x, .y or .xy\n");
2974 break;
2975 }
2976}
2977
2978/* sgn in vs_2_0 has 2 extra parameters(registers for temporary storage) which we don't use
2979 * here. But those extra parameters require a dedicated function for sgn, since map2gl would
2980 * generate invalid code
2981 */
2982static void shader_glsl_sgn(const struct wined3d_shader_instruction *ins)
2983{
2984 glsl_src_param_t src0_param;
2985 DWORD write_mask;
2986
2987 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
2988 shader_glsl_add_src_param(ins, &ins->src[0], write_mask, &src0_param);
2989
2990 shader_addline(ins->ctx->buffer, "sign(%s));\n", src0_param.param_str);
2991}
2992
2993/** Process the WINED3DSIO_LOOP instruction in GLSL:
2994 * Start a for() loop where src1.y is the initial value of aL,
2995 * increment aL by src1.z for a total of src1.x iterations.
2996 * Need to use a temporary variable for this operation.
2997 */
2998/* FIXME: I don't think nested loops will work correctly this way. */
2999static void shader_glsl_loop(const struct wined3d_shader_instruction *ins)
3000{
3001 glsl_src_param_t src1_param;
3002 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3003 const DWORD *control_values = NULL;
3004 const local_constant *constant;
3005
3006 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_ALL, &src1_param);
3007
3008 /* Try to hardcode the loop control parameters if possible. Direct3D 9 class hardware doesn't support real
3009 * varying indexing, but Microsoft designed this feature for Shader model 2.x+. If the loop control is
3010 * known at compile time, the GLSL compiler can unroll the loop, and replace indirect addressing with direct
3011 * addressing.
3012 */
3013 if (ins->src[1].reg.type == WINED3DSPR_CONSTINT)
3014 {
3015 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry) {
3016 if (constant->idx == ins->src[1].reg.idx)
3017 {
3018 control_values = constant->value;
3019 break;
3020 }
3021 }
3022 }
3023
3024 if (control_values)
3025 {
3026 struct wined3d_shader_loop_control loop_control;
3027 loop_control.count = control_values[0];
3028 loop_control.start = control_values[1];
3029 loop_control.step = (int)control_values[2];
3030
3031 if (loop_control.step > 0)
3032 {
3033 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u < (%u * %d + %u); aL%u += %d) {\n",
3034 shader->baseShader.cur_loop_depth, loop_control.start,
3035 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
3036 shader->baseShader.cur_loop_depth, loop_control.step);
3037 }
3038 else if (loop_control.step < 0)
3039 {
3040 shader_addline(ins->ctx->buffer, "for (aL%u = %u; aL%u > (%u * %d + %u); aL%u += %d) {\n",
3041 shader->baseShader.cur_loop_depth, loop_control.start,
3042 shader->baseShader.cur_loop_depth, loop_control.count, loop_control.step, loop_control.start,
3043 shader->baseShader.cur_loop_depth, loop_control.step);
3044 }
3045 else
3046 {
3047 shader_addline(ins->ctx->buffer, "for (aL%u = %u, tmpInt%u = 0; tmpInt%u < %u; tmpInt%u++) {\n",
3048 shader->baseShader.cur_loop_depth, loop_control.start, shader->baseShader.cur_loop_depth,
3049 shader->baseShader.cur_loop_depth, loop_control.count,
3050 shader->baseShader.cur_loop_depth);
3051 }
3052 } else {
3053 shader_addline(ins->ctx->buffer,
3054 "for (tmpInt%u = 0, aL%u = %s.y; tmpInt%u < %s.x; tmpInt%u++, aL%u += %s.z) {\n",
3055 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno,
3056 src1_param.reg_name, shader->baseShader.cur_loop_depth, src1_param.reg_name,
3057 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_regno, src1_param.reg_name);
3058 }
3059
3060 shader->baseShader.cur_loop_depth++;
3061 shader->baseShader.cur_loop_regno++;
3062}
3063
3064static void shader_glsl_end(const struct wined3d_shader_instruction *ins)
3065{
3066 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3067
3068 shader_addline(ins->ctx->buffer, "}\n");
3069
3070 if (ins->handler_idx == WINED3DSIH_ENDLOOP)
3071 {
3072 shader->baseShader.cur_loop_depth--;
3073 shader->baseShader.cur_loop_regno--;
3074 }
3075
3076 if (ins->handler_idx == WINED3DSIH_ENDREP)
3077 {
3078 shader->baseShader.cur_loop_depth--;
3079 }
3080}
3081
3082static void shader_glsl_rep(const struct wined3d_shader_instruction *ins)
3083{
3084 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3085 glsl_src_param_t src0_param;
3086 const DWORD *control_values = NULL;
3087 const local_constant *constant;
3088
3089 /* Try to hardcode local values to help the GLSL compiler to unroll and optimize the loop */
3090 if (ins->src[0].reg.type == WINED3DSPR_CONSTINT)
3091 {
3092 LIST_FOR_EACH_ENTRY(constant, &shader->baseShader.constantsI, local_constant, entry)
3093 {
3094 if (constant->idx == ins->src[0].reg.idx)
3095 {
3096 control_values = constant->value;
3097 break;
3098 }
3099 }
3100 }
3101
3102 if(control_values) {
3103 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %d; tmpInt%d++) {\n",
3104 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
3105 control_values[0], shader->baseShader.cur_loop_depth);
3106 } else {
3107 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3108 shader_addline(ins->ctx->buffer, "for (tmpInt%d = 0; tmpInt%d < %s; tmpInt%d++) {\n",
3109 shader->baseShader.cur_loop_depth, shader->baseShader.cur_loop_depth,
3110 src0_param.param_str, shader->baseShader.cur_loop_depth);
3111 }
3112 shader->baseShader.cur_loop_depth++;
3113}
3114
3115static void shader_glsl_if(const struct wined3d_shader_instruction *ins)
3116{
3117 glsl_src_param_t src0_param;
3118
3119 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3120 shader_addline(ins->ctx->buffer, "if (%s) {\n", src0_param.param_str);
3121}
3122
3123static void shader_glsl_ifc(const struct wined3d_shader_instruction *ins)
3124{
3125 glsl_src_param_t src0_param;
3126 glsl_src_param_t src1_param;
3127
3128 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3129 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3130
3131 shader_addline(ins->ctx->buffer, "if (%s %s %s) {\n",
3132 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
3133}
3134
3135static void shader_glsl_else(const struct wined3d_shader_instruction *ins)
3136{
3137 shader_addline(ins->ctx->buffer, "} else {\n");
3138}
3139
3140static void shader_glsl_break(const struct wined3d_shader_instruction *ins)
3141{
3142 shader_addline(ins->ctx->buffer, "break;\n");
3143}
3144
3145/* FIXME: According to MSDN the compare is done per component. */
3146static void shader_glsl_breakc(const struct wined3d_shader_instruction *ins)
3147{
3148 glsl_src_param_t src0_param;
3149 glsl_src_param_t src1_param;
3150
3151 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0, &src0_param);
3152 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3153
3154 shader_addline(ins->ctx->buffer, "if (%s %s %s) break;\n",
3155 src0_param.param_str, shader_get_comp_op(ins->flags), src1_param.param_str);
3156}
3157
3158static void shader_glsl_label(const struct wined3d_shader_instruction *ins)
3159{
3160 shader_addline(ins->ctx->buffer, "}\n");
3161 shader_addline(ins->ctx->buffer, "void subroutine%u () {\n", ins->src[0].reg.idx);
3162}
3163
3164static void shader_glsl_call(const struct wined3d_shader_instruction *ins)
3165{
3166 shader_addline(ins->ctx->buffer, "subroutine%u();\n", ins->src[0].reg.idx);
3167}
3168
3169static void shader_glsl_callnz(const struct wined3d_shader_instruction *ins)
3170{
3171 glsl_src_param_t src1_param;
3172
3173 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0, &src1_param);
3174 shader_addline(ins->ctx->buffer, "if (%s) subroutine%u();\n", src1_param.param_str, ins->src[0].reg.idx);
3175}
3176
3177static void shader_glsl_ret(const struct wined3d_shader_instruction *ins)
3178{
3179 /* No-op. The closing } is written when a new function is started, and at the end of the shader. This
3180 * function only suppresses the unhandled instruction warning
3181 */
3182}
3183
3184/*********************************************
3185 * Pixel Shader Specific Code begins here
3186 ********************************************/
3187static void shader_glsl_tex(const struct wined3d_shader_instruction *ins)
3188{
3189 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3190 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device;
3191 DWORD shader_version = WINED3D_SHADER_VERSION(ins->ctx->reg_maps->shader_version.major,
3192 ins->ctx->reg_maps->shader_version.minor);
3193 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3194 glsl_sample_function_t sample_function;
3195 DWORD sample_flags = 0;
3196 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3197 DWORD sampler_idx;
3198 DWORD mask = 0, swizzle;
3199
3200 /* 1.0-1.4: Use destination register as sampler source.
3201 * 2.0+: Use provided sampler source. */
3202 if (shader_version < WINED3D_SHADER_VERSION(2,0)) sampler_idx = ins->dst[0].reg.idx;
3203 else sampler_idx = ins->src[1].reg.idx;
3204 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3205
3206 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3207 {
3208 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3209 DWORD flags = (priv->cur_ps_args->tex_transform >> (sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT))
3210 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3211
3212 /* Projected cube textures don't make a lot of sense, the resulting coordinates stay the same. */
3213 if (flags & WINED3D_PSARGS_PROJECTED && sampler_type != WINED3DSTT_CUBE) {
3214 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3215 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3216 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3217 case WINED3DTTFF_COUNT2: mask = WINED3DSP_WRITEMASK_1; break;
3218 case WINED3DTTFF_COUNT3: mask = WINED3DSP_WRITEMASK_2; break;
3219 case WINED3DTTFF_COUNT4:
3220 case WINED3DTTFF_DISABLE: mask = WINED3DSP_WRITEMASK_3; break;
3221 }
3222 }
3223 }
3224 else if (shader_version < WINED3D_SHADER_VERSION(2,0))
3225 {
3226 DWORD src_mod = ins->src[0].modifiers;
3227
3228 if (src_mod == WINED3DSPSM_DZ) {
3229 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3230 mask = WINED3DSP_WRITEMASK_2;
3231 } else if (src_mod == WINED3DSPSM_DW) {
3232 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3233 mask = WINED3DSP_WRITEMASK_3;
3234 }
3235 } else {
3236 if (ins->flags & WINED3DSI_TEXLD_PROJECT)
3237 {
3238 /* ps 2.0 texldp instruction always divides by the fourth component. */
3239 sample_flags |= WINED3D_GLSL_SAMPLE_PROJECTED;
3240 mask = WINED3DSP_WRITEMASK_3;
3241 }
3242 }
3243
3244 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3245 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3246 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3247 }
3248
3249 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3250 mask |= sample_function.coord_mask;
3251
3252 if (shader_version < WINED3D_SHADER_VERSION(2,0)) swizzle = WINED3DSP_NOSWIZZLE;
3253 else swizzle = ins->src[1].swizzle;
3254
3255 /* 1.0-1.3: Use destination register as coordinate source.
3256 1.4+: Use provided coordinate source register. */
3257 if (shader_version < WINED3D_SHADER_VERSION(1,4))
3258 {
3259 char coord_mask[6];
3260 shader_glsl_write_mask_to_str(mask, coord_mask);
3261 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3262 "T%u%s", sampler_idx, coord_mask);
3263 } else {
3264 glsl_src_param_t coord_param;
3265 shader_glsl_add_src_param(ins, &ins->src[0], mask, &coord_param);
3266 if (ins->flags & WINED3DSI_TEXLD_BIAS)
3267 {
3268 glsl_src_param_t bias;
3269 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &bias);
3270 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, bias.param_str,
3271 "%s", coord_param.param_str);
3272 } else {
3273 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, NULL,
3274 "%s", coord_param.param_str);
3275 }
3276 }
3277}
3278
3279static void shader_glsl_texldd(const struct wined3d_shader_instruction *ins)
3280{
3281 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3282 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3283 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3284 glsl_sample_function_t sample_function;
3285 glsl_src_param_t coord_param, dx_param, dy_param;
3286 DWORD sample_flags = WINED3D_GLSL_SAMPLE_GRAD;
3287 DWORD sampler_type;
3288 DWORD sampler_idx;
3289 DWORD swizzle = ins->src[1].swizzle;
3290
3291 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4])
3292 {
3293 FIXME("texldd used, but not supported by hardware. Falling back to regular tex\n");
3294 shader_glsl_tex(ins);
3295 return;
3296 }
3297
3298 sampler_idx = ins->src[1].reg.idx;
3299 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3300 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3301 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3302 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3303 }
3304
3305 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3306 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3307 shader_glsl_add_src_param(ins, &ins->src[2], sample_function.coord_mask, &dx_param);
3308 shader_glsl_add_src_param(ins, &ins->src[3], sample_function.coord_mask, &dy_param);
3309
3310 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, dx_param.param_str, dy_param.param_str, NULL,
3311 "%s", coord_param.param_str);
3312}
3313
3314static void shader_glsl_texldl(const struct wined3d_shader_instruction *ins)
3315{
3316 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3317 IWineD3DDeviceImpl* deviceImpl = (IWineD3DDeviceImpl*) This->baseShader.device;
3318 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3319 glsl_sample_function_t sample_function;
3320 glsl_src_param_t coord_param, lod_param;
3321 DWORD sample_flags = WINED3D_GLSL_SAMPLE_LOD;
3322 DWORD sampler_type;
3323 DWORD sampler_idx;
3324 DWORD swizzle = ins->src[1].swizzle;
3325
3326 sampler_idx = ins->src[1].reg.idx;
3327 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3328 if(deviceImpl->stateBlock->textures[sampler_idx] &&
3329 IWineD3DBaseTexture_GetTextureDimensions(deviceImpl->stateBlock->textures[sampler_idx]) == GL_TEXTURE_RECTANGLE_ARB) {
3330 sample_flags |= WINED3D_GLSL_SAMPLE_RECT;
3331 }
3332 shader_glsl_get_sample_function(gl_info, sampler_type, sample_flags, &sample_function);
3333 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &coord_param);
3334
3335 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &lod_param);
3336
3337 if (!gl_info->supported[ARB_SHADER_TEXTURE_LOD] && !gl_info->supported[EXT_GPU_SHADER4]
3338 && shader_is_pshader_version(ins->ctx->reg_maps->shader_version.type))
3339 {
3340 /* The GLSL spec claims the Lod sampling functions are only supported in vertex shaders.
3341 * However, they seem to work just fine in fragment shaders as well. */
3342 WARN("Using %s in fragment shader.\n", sample_function.name);
3343 }
3344 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, swizzle, NULL, NULL, lod_param.param_str,
3345 "%s", coord_param.param_str);
3346}
3347
3348static void shader_glsl_texcoord(const struct wined3d_shader_instruction *ins)
3349{
3350 /* FIXME: Make this work for more than just 2D textures */
3351 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3352 DWORD write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3353
3354 if (!(ins->ctx->reg_maps->shader_version.major == 1 && ins->ctx->reg_maps->shader_version.minor == 4))
3355 {
3356 char dst_mask[6];
3357
3358 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3359 shader_addline(buffer, "clamp(gl_TexCoord[%u], 0.0, 1.0)%s);\n",
3360 ins->dst[0].reg.idx, dst_mask);
3361 } else {
3362 DWORD reg = ins->src[0].reg.idx;
3363 DWORD src_mod = ins->src[0].modifiers;
3364 char dst_swizzle[6];
3365
3366 shader_glsl_get_swizzle(&ins->src[0], FALSE, write_mask, dst_swizzle);
3367
3368 if (src_mod == WINED3DSPSM_DZ) {
3369 glsl_src_param_t div_param;
3370 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3371 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &div_param);
3372
3373 if (mask_size > 1) {
3374 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3375 } else {
3376 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3377 }
3378 } else if (src_mod == WINED3DSPSM_DW) {
3379 glsl_src_param_t div_param;
3380 unsigned int mask_size = shader_glsl_get_write_mask_size(write_mask);
3381 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_3, &div_param);
3382
3383 if (mask_size > 1) {
3384 shader_addline(buffer, "gl_TexCoord[%u]%s / vec%d(%s));\n", reg, dst_swizzle, mask_size, div_param.param_str);
3385 } else {
3386 shader_addline(buffer, "gl_TexCoord[%u]%s / %s);\n", reg, dst_swizzle, div_param.param_str);
3387 }
3388 } else {
3389 shader_addline(buffer, "gl_TexCoord[%u]%s);\n", reg, dst_swizzle);
3390 }
3391 }
3392}
3393
3394/** Process the WINED3DSIO_TEXDP3TEX instruction in GLSL:
3395 * Take a 3-component dot product of the TexCoord[dstreg] and src,
3396 * then perform a 1D texture lookup from stage dstregnum, place into dst. */
3397static void shader_glsl_texdp3tex(const struct wined3d_shader_instruction *ins)
3398{
3399 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3400 glsl_src_param_t src0_param;
3401 glsl_sample_function_t sample_function;
3402 DWORD sampler_idx = ins->dst[0].reg.idx;
3403 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3404 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3405 UINT mask_size;
3406
3407 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3408
3409 /* Do I have to take care about the projected bit? I don't think so, since the dp3 returns only one
3410 * scalar, and projected sampling would require 4.
3411 *
3412 * It is a dependent read - not valid with conditional NP2 textures
3413 */
3414 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3415 mask_size = shader_glsl_get_write_mask_size(sample_function.coord_mask);
3416
3417 switch(mask_size)
3418 {
3419 case 1:
3420 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3421 "dot(gl_TexCoord[%u].xyz, %s)", sampler_idx, src0_param.param_str);
3422 break;
3423
3424 case 2:
3425 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3426 "vec2(dot(gl_TexCoord[%u].xyz, %s), 0.0)", sampler_idx, src0_param.param_str);
3427 break;
3428
3429 case 3:
3430 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3431 "vec3(dot(gl_TexCoord[%u].xyz, %s), 0.0, 0.0)", sampler_idx, src0_param.param_str);
3432 break;
3433
3434 default:
3435 FIXME("Unexpected mask size %u\n", mask_size);
3436 break;
3437 }
3438}
3439
3440/** Process the WINED3DSIO_TEXDP3 instruction in GLSL:
3441 * Take a 3-component dot product of the TexCoord[dstreg] and src. */
3442static void shader_glsl_texdp3(const struct wined3d_shader_instruction *ins)
3443{
3444 glsl_src_param_t src0_param;
3445 DWORD dstreg = ins->dst[0].reg.idx;
3446 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3447 DWORD dst_mask;
3448 unsigned int mask_size;
3449
3450 dst_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3451 mask_size = shader_glsl_get_write_mask_size(dst_mask);
3452 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3453
3454 if (mask_size > 1) {
3455 shader_addline(ins->ctx->buffer, "vec%d(dot(T%u.xyz, %s)));\n", mask_size, dstreg, src0_param.param_str);
3456 } else {
3457 shader_addline(ins->ctx->buffer, "dot(T%u.xyz, %s));\n", dstreg, src0_param.param_str);
3458 }
3459}
3460
3461/** Process the WINED3DSIO_TEXDEPTH instruction in GLSL:
3462 * Calculate the depth as dst.x / dst.y */
3463static void shader_glsl_texdepth(const struct wined3d_shader_instruction *ins)
3464{
3465 glsl_dst_param_t dst_param;
3466
3467 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3468
3469 /* Tests show that texdepth never returns anything below 0.0, and that r5.y is clamped to 1.0.
3470 * Negative input is accepted, -0.25 / -0.5 returns 0.5. GL should clamp gl_FragDepth to [0;1], but
3471 * this doesn't always work, so clamp the results manually. Whether or not the x value is clamped at 1
3472 * too is irrelevant, since if x = 0, any y value < 1.0 (and > 1.0 is not allowed) results in a result
3473 * >= 1.0 or < 0.0
3474 */
3475 shader_addline(ins->ctx->buffer, "gl_FragDepth = clamp((%s.x / min(%s.y, 1.0)), 0.0, 1.0);\n",
3476 dst_param.reg_name, dst_param.reg_name);
3477}
3478
3479/** Process the WINED3DSIO_TEXM3X2DEPTH instruction in GLSL:
3480 * Last row of a 3x2 matrix multiply, use the result to calculate the depth:
3481 * Calculate tmp0.y = TexCoord[dstreg] . src.xyz; (tmp0.x has already been calculated)
3482 * depth = (tmp0.y == 0.0) ? 1.0 : tmp0.x / tmp0.y
3483 */
3484static void shader_glsl_texm3x2depth(const struct wined3d_shader_instruction *ins)
3485{
3486 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3487 DWORD dstreg = ins->dst[0].reg.idx;
3488 glsl_src_param_t src0_param;
3489
3490 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3491
3492 shader_addline(ins->ctx->buffer, "tmp0.y = dot(T%u.xyz, %s);\n", dstreg, src0_param.param_str);
3493 shader_addline(ins->ctx->buffer, "gl_FragDepth = (tmp0.y == 0.0) ? 1.0 : clamp(tmp0.x / tmp0.y, 0.0, 1.0);\n");
3494}
3495
3496/** Process the WINED3DSIO_TEXM3X2PAD instruction in GLSL
3497 * Calculate the 1st of a 2-row matrix multiplication. */
3498static void shader_glsl_texm3x2pad(const struct wined3d_shader_instruction *ins)
3499{
3500 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3501 DWORD reg = ins->dst[0].reg.idx;
3502 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3503 glsl_src_param_t src0_param;
3504
3505 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3506 shader_addline(buffer, "tmp0.x = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3507}
3508
3509/** Process the WINED3DSIO_TEXM3X3PAD instruction in GLSL
3510 * Calculate the 1st or 2nd row of a 3-row matrix multiplication. */
3511static void shader_glsl_texm3x3pad(const struct wined3d_shader_instruction *ins)
3512{
3513 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3514 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3515 DWORD reg = ins->dst[0].reg.idx;
3516 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3517 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3518 glsl_src_param_t src0_param;
3519
3520 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3521 shader_addline(buffer, "tmp0.%c = dot(T%u.xyz, %s);\n", 'x' + current_state->current_row, reg, src0_param.param_str);
3522 current_state->texcoord_w[current_state->current_row++] = reg;
3523}
3524
3525static void shader_glsl_texm3x2tex(const struct wined3d_shader_instruction *ins)
3526{
3527 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3528 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3529 DWORD reg = ins->dst[0].reg.idx;
3530 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3531 glsl_src_param_t src0_param;
3532 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3533 glsl_sample_function_t sample_function;
3534
3535 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3536 shader_addline(buffer, "tmp0.y = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3537
3538 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3539
3540 /* Sample the texture using the calculated coordinates */
3541 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xy");
3542}
3543
3544/** Process the WINED3DSIO_TEXM3X3TEX instruction in GLSL
3545 * Perform the 3rd row of a 3x3 matrix multiply, then sample the texture using the calculated coordinates */
3546static void shader_glsl_texm3x3tex(const struct wined3d_shader_instruction *ins)
3547{
3548 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3549 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3550 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3551 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3552 glsl_src_param_t src0_param;
3553 DWORD reg = ins->dst[0].reg.idx;
3554 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3555 glsl_sample_function_t sample_function;
3556
3557 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3558 shader_addline(ins->ctx->buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3559
3560 /* Dependent read, not valid with conditional NP2 */
3561 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3562
3563 /* Sample the texture using the calculated coordinates */
3564 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3565
3566 current_state->current_row = 0;
3567}
3568
3569/** Process the WINED3DSIO_TEXM3X3 instruction in GLSL
3570 * Perform the 3rd row of a 3x3 matrix multiply */
3571static void shader_glsl_texm3x3(const struct wined3d_shader_instruction *ins)
3572{
3573 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3574 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3575 SHADER_PARSE_STATE *current_state = &shader->baseShader.parse_state;
3576 glsl_src_param_t src0_param;
3577 char dst_mask[6];
3578 DWORD reg = ins->dst[0].reg.idx;
3579
3580 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3581
3582 shader_glsl_append_dst(ins->ctx->buffer, ins);
3583 shader_glsl_get_write_mask(&ins->dst[0], dst_mask);
3584 shader_addline(ins->ctx->buffer, "vec4(tmp0.xy, dot(T%u.xyz, %s), 1.0)%s);\n", reg, src0_param.param_str, dst_mask);
3585
3586 current_state->current_row = 0;
3587}
3588
3589/* Process the WINED3DSIO_TEXM3X3SPEC instruction in GLSL
3590 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3591static void shader_glsl_texm3x3spec(const struct wined3d_shader_instruction *ins)
3592{
3593 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3594 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3595 DWORD reg = ins->dst[0].reg.idx;
3596 glsl_src_param_t src0_param;
3597 glsl_src_param_t src1_param;
3598 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3599 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3600 WINED3DSAMPLER_TEXTURE_TYPE stype = ins->ctx->reg_maps->sampler_type[reg];
3601 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3602 glsl_sample_function_t sample_function;
3603
3604 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3605 shader_glsl_add_src_param(ins, &ins->src[1], src_mask, &src1_param);
3606
3607 /* Perform the last matrix multiply operation */
3608 shader_addline(buffer, "tmp0.z = dot(T%u.xyz, %s);\n", reg, src0_param.param_str);
3609 /* Reflection calculation */
3610 shader_addline(buffer, "tmp0.xyz = -reflect((%s), normalize(tmp0.xyz));\n", src1_param.param_str);
3611
3612 /* Dependent read, not valid with conditional NP2 */
3613 shader_glsl_get_sample_function(gl_info, stype, 0, &sample_function);
3614
3615 /* Sample the texture */
3616 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3617
3618 current_state->current_row = 0;
3619}
3620
3621/* Process the WINED3DSIO_TEXM3X3VSPEC instruction in GLSL
3622 * Perform the final texture lookup based on the previous 2 3x3 matrix multiplies */
3623static void shader_glsl_texm3x3vspec(const struct wined3d_shader_instruction *ins)
3624{
3625 IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3626 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3627 DWORD reg = ins->dst[0].reg.idx;
3628 struct wined3d_shader_buffer *buffer = ins->ctx->buffer;
3629 SHADER_PARSE_STATE* current_state = &shader->baseShader.parse_state;
3630 glsl_src_param_t src0_param;
3631 DWORD src_mask = WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1 | WINED3DSP_WRITEMASK_2;
3632 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[reg];
3633 glsl_sample_function_t sample_function;
3634
3635 shader_glsl_add_src_param(ins, &ins->src[0], src_mask, &src0_param);
3636
3637 /* Perform the last matrix multiply operation */
3638 shader_addline(buffer, "tmp0.z = dot(vec3(T%u), vec3(%s));\n", reg, src0_param.param_str);
3639
3640 /* Construct the eye-ray vector from w coordinates */
3641 shader_addline(buffer, "tmp1.xyz = normalize(vec3(gl_TexCoord[%u].w, gl_TexCoord[%u].w, gl_TexCoord[%u].w));\n",
3642 current_state->texcoord_w[0], current_state->texcoord_w[1], reg);
3643 shader_addline(buffer, "tmp0.xyz = -reflect(tmp1.xyz, normalize(tmp0.xyz));\n");
3644
3645 /* Dependent read, not valid with conditional NP2 */
3646 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3647
3648 /* Sample the texture using the calculated coordinates */
3649 shader_glsl_gen_sample_code(ins, reg, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL, "tmp0.xyz");
3650
3651 current_state->current_row = 0;
3652}
3653
3654/** Process the WINED3DSIO_TEXBEM instruction in GLSL.
3655 * Apply a fake bump map transform.
3656 * texbem is pshader <= 1.3 only, this saves a few version checks
3657 */
3658static void shader_glsl_texbem(const struct wined3d_shader_instruction *ins)
3659{
3660 /*IWineD3DBaseShaderImpl *shader = (IWineD3DBaseShaderImpl *)ins->ctx->shader;
3661 IWineD3DDeviceImpl *deviceImpl = (IWineD3DDeviceImpl *)shader->baseShader.device; - unused */
3662 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3663 const struct shader_glsl_ctx_priv *priv = ins->ctx->backend_data;
3664 glsl_sample_function_t sample_function;
3665 glsl_src_param_t coord_param;
3666 WINED3DSAMPLER_TEXTURE_TYPE sampler_type;
3667 DWORD sampler_idx;
3668 DWORD mask;
3669 DWORD flags;
3670 char coord_mask[6];
3671
3672 sampler_idx = ins->dst[0].reg.idx;
3673 flags = (priv->cur_ps_args->tex_transform >> (sampler_idx * WINED3D_PSARGS_TEXTRANSFORM_SHIFT))
3674 & WINED3D_PSARGS_TEXTRANSFORM_MASK;
3675
3676 sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3677 /* Dependent read, not valid with conditional NP2 */
3678 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3679 mask = sample_function.coord_mask;
3680
3681 shader_glsl_write_mask_to_str(mask, coord_mask);
3682
3683 /* with projective textures, texbem only divides the static texture coord, not the displacement,
3684 * so we can't let the GL handle this.
3685 */
3686 if (flags & WINED3D_PSARGS_PROJECTED) {
3687 DWORD div_mask=0;
3688 char coord_div_mask[3];
3689 switch (flags & ~WINED3D_PSARGS_PROJECTED) {
3690 case WINED3DTTFF_COUNT1: FIXME("WINED3DTTFF_PROJECTED with WINED3DTTFF_COUNT1?\n"); break;
3691 case WINED3DTTFF_COUNT2: div_mask = WINED3DSP_WRITEMASK_1; break;
3692 case WINED3DTTFF_COUNT3: div_mask = WINED3DSP_WRITEMASK_2; break;
3693 case WINED3DTTFF_COUNT4:
3694 case WINED3DTTFF_DISABLE: div_mask = WINED3DSP_WRITEMASK_3; break;
3695 }
3696 shader_glsl_write_mask_to_str(div_mask, coord_div_mask);
3697 shader_addline(ins->ctx->buffer, "T%u%s /= T%u%s;\n", sampler_idx, coord_mask, sampler_idx, coord_div_mask);
3698 }
3699
3700 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &coord_param);
3701
3702 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3703 "T%u%s + vec4(bumpenvmat%d * %s, 0.0, 0.0)%s", sampler_idx, coord_mask, sampler_idx,
3704 coord_param.param_str, coord_mask);
3705
3706 if (ins->handler_idx == WINED3DSIH_TEXBEML)
3707 {
3708 glsl_src_param_t luminance_param;
3709 glsl_dst_param_t dst_param;
3710
3711 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_2, &luminance_param);
3712 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3713
3714 shader_addline(ins->ctx->buffer, "%s%s *= (%s * luminancescale%d + luminanceoffset%d);\n",
3715 dst_param.reg_name, dst_param.mask_str,
3716 luminance_param.param_str, sampler_idx, sampler_idx);
3717 }
3718}
3719
3720static void shader_glsl_bem(const struct wined3d_shader_instruction *ins)
3721{
3722 glsl_src_param_t src0_param, src1_param;
3723 DWORD sampler_idx = ins->dst[0].reg.idx;
3724
3725 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3726 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3727
3728 shader_glsl_append_dst(ins->ctx->buffer, ins);
3729 shader_addline(ins->ctx->buffer, "%s + bumpenvmat%d * %s);\n",
3730 src0_param.param_str, sampler_idx, src1_param.param_str);
3731}
3732
3733/** Process the WINED3DSIO_TEXREG2AR instruction in GLSL
3734 * Sample 2D texture at dst using the alpha & red (wx) components of src as texture coordinates */
3735static void shader_glsl_texreg2ar(const struct wined3d_shader_instruction *ins)
3736{
3737 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3738 glsl_src_param_t src0_param;
3739 DWORD sampler_idx = ins->dst[0].reg.idx;
3740 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3741 glsl_sample_function_t sample_function;
3742
3743 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3744
3745 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3746 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3747 "%s.wx", src0_param.reg_name);
3748}
3749
3750/** Process the WINED3DSIO_TEXREG2GB instruction in GLSL
3751 * Sample 2D texture at dst using the green & blue (yz) components of src as texture coordinates */
3752static void shader_glsl_texreg2gb(const struct wined3d_shader_instruction *ins)
3753{
3754 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3755 glsl_src_param_t src0_param;
3756 DWORD sampler_idx = ins->dst[0].reg.idx;
3757 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3758 glsl_sample_function_t sample_function;
3759
3760 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_ALL, &src0_param);
3761
3762 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3763 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3764 "%s.yz", src0_param.reg_name);
3765}
3766
3767/** Process the WINED3DSIO_TEXREG2RGB instruction in GLSL
3768 * Sample texture at dst using the rgb (xyz) components of src as texture coordinates */
3769static void shader_glsl_texreg2rgb(const struct wined3d_shader_instruction *ins)
3770{
3771 const struct wined3d_gl_info *gl_info = ins->ctx->gl_info;
3772 glsl_src_param_t src0_param;
3773 DWORD sampler_idx = ins->dst[0].reg.idx;
3774 WINED3DSAMPLER_TEXTURE_TYPE sampler_type = ins->ctx->reg_maps->sampler_type[sampler_idx];
3775 glsl_sample_function_t sample_function;
3776
3777 /* Dependent read, not valid with conditional NP2 */
3778 shader_glsl_get_sample_function(gl_info, sampler_type, 0, &sample_function);
3779 shader_glsl_add_src_param(ins, &ins->src[0], sample_function.coord_mask, &src0_param);
3780
3781 shader_glsl_gen_sample_code(ins, sampler_idx, &sample_function, WINED3DSP_NOSWIZZLE, NULL, NULL, NULL,
3782 "%s", src0_param.param_str);
3783}
3784
3785/** Process the WINED3DSIO_TEXKILL instruction in GLSL.
3786 * If any of the first 3 components are < 0, discard this pixel */
3787static void shader_glsl_texkill(const struct wined3d_shader_instruction *ins)
3788{
3789 glsl_dst_param_t dst_param;
3790
3791 /* The argument is a destination parameter, and no writemasks are allowed */
3792 shader_glsl_add_dst_param(ins, &ins->dst[0], &dst_param);
3793 if (ins->ctx->reg_maps->shader_version.major >= 2)
3794 {
3795 /* 2.0 shaders compare all 4 components in texkill */
3796 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyzw, vec4(0.0)))) discard;\n", dst_param.reg_name);
3797 } else {
3798 /* 1.X shaders only compare the first 3 components, probably due to the nature of the texkill
3799 * instruction as a tex* instruction, and phase, which kills all a / w components. Even if all
3800 * 4 components are defined, only the first 3 are used
3801 */
3802 shader_addline(ins->ctx->buffer, "if (any(lessThan(%s.xyz, vec3(0.0)))) discard;\n", dst_param.reg_name);
3803 }
3804}
3805
3806/** Process the WINED3DSIO_DP2ADD instruction in GLSL.
3807 * dst = dot2(src0, src1) + src2 */
3808static void shader_glsl_dp2add(const struct wined3d_shader_instruction *ins)
3809{
3810 glsl_src_param_t src0_param;
3811 glsl_src_param_t src1_param;
3812 glsl_src_param_t src2_param;
3813 DWORD write_mask;
3814 unsigned int mask_size;
3815
3816 write_mask = shader_glsl_append_dst(ins->ctx->buffer, ins);
3817 mask_size = shader_glsl_get_write_mask_size(write_mask);
3818
3819 shader_glsl_add_src_param(ins, &ins->src[0], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src0_param);
3820 shader_glsl_add_src_param(ins, &ins->src[1], WINED3DSP_WRITEMASK_0 | WINED3DSP_WRITEMASK_1, &src1_param);
3821 shader_glsl_add_src_param(ins, &ins->src[2], WINED3DSP_WRITEMASK_0, &src2_param);
3822
3823 if (mask_size > 1) {
3824 shader_addline(ins->ctx->buffer, "vec%d(dot(%s, %s) + %s));\n",
3825 mask_size, src0_param.param_str, src1_param.param_str, src2_param.param_str);
3826 } else {
3827 shader_addline(ins->ctx->buffer, "dot(%s, %s) + %s);\n",
3828 src0_param.param_str, src1_param.param_str, src2_param.param_str);
3829 }
3830}
3831
3832static void shader_glsl_input_pack(IWineD3DPixelShader *iface, struct wined3d_shader_buffer *buffer,
3833 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps,
3834 enum vertexprocessing_mode vertexprocessing)
3835{
3836 unsigned int i;
3837 IWineD3DPixelShaderImpl *This = (IWineD3DPixelShaderImpl *)iface;
3838 WORD map = reg_maps->input_registers;
3839
3840 for (i = 0; map; map >>= 1, ++i)
3841 {
3842 const char *semantic_name;
3843 UINT semantic_idx;
3844 char reg_mask[6];
3845
3846 /* Unused */
3847 if (!(map & 1)) continue;
3848
3849 semantic_name = input_signature[i].semantic_name;
3850 semantic_idx = input_signature[i].semantic_idx;
3851 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3852
3853 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
3854 {
3855 if (semantic_idx < 8 && vertexprocessing == pretransformed)
3856 shader_addline(buffer, "IN[%u]%s = gl_TexCoord[%u]%s;\n",
3857 This->input_reg_map[i], reg_mask, semantic_idx, reg_mask);
3858 else
3859 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3860 This->input_reg_map[i], reg_mask, reg_mask);
3861 }
3862 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
3863 {
3864 if (semantic_idx == 0)
3865 shader_addline(buffer, "IN[%u]%s = vec4(gl_Color)%s;\n",
3866 This->input_reg_map[i], reg_mask, reg_mask);
3867 else if (semantic_idx == 1)
3868 shader_addline(buffer, "IN[%u]%s = vec4(gl_SecondaryColor)%s;\n",
3869 This->input_reg_map[i], reg_mask, reg_mask);
3870 else
3871 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3872 This->input_reg_map[i], reg_mask, reg_mask);
3873 }
3874 else
3875 {
3876 shader_addline(buffer, "IN[%u]%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
3877 This->input_reg_map[i], reg_mask, reg_mask);
3878 }
3879 }
3880}
3881
3882/*********************************************
3883 * Vertex Shader Specific Code begins here
3884 ********************************************/
3885
3886static void add_glsl_program_entry(struct shader_glsl_priv *priv, struct glsl_shader_prog_link *entry) {
3887 glsl_program_key_t key;
3888
3889 key.vshader = entry->vshader;
3890 key.pshader = entry->pshader;
3891 key.vs_args = entry->vs_args;
3892 key.ps_args = entry->ps_args;
3893 key.context = entry->context;
3894
3895 if (wine_rb_put(&priv->program_lookup, &key, &entry->program_lookup_entry) == -1)
3896 {
3897 ERR("Failed to insert program entry.\n");
3898 }
3899}
3900
3901static struct glsl_shader_prog_link *get_glsl_program_entry(struct shader_glsl_priv *priv,
3902 IWineD3DVertexShader *vshader, IWineD3DPixelShader *pshader, struct vs_compile_args *vs_args,
3903 struct ps_compile_args *ps_args, const struct wined3d_context *context) {
3904 struct wine_rb_entry *entry;
3905 glsl_program_key_t key;
3906
3907 key.vshader = vshader;
3908 key.pshader = pshader;
3909 key.vs_args = *vs_args;
3910 key.ps_args = *ps_args;
3911 key.context = context;
3912
3913 entry = wine_rb_get(&priv->program_lookup, &key);
3914 return entry ? WINE_RB_ENTRY_VALUE(entry, struct glsl_shader_prog_link, program_lookup_entry) : NULL;
3915}
3916
3917/* GL locking is done by the caller */
3918static void delete_glsl_program_entry(struct shader_glsl_priv *priv, const struct wined3d_gl_info *gl_info,
3919 struct glsl_shader_prog_link *entry)
3920{
3921 glsl_program_key_t key;
3922
3923 key.vshader = entry->vshader;
3924 key.pshader = entry->pshader;
3925 key.vs_args = entry->vs_args;
3926 key.ps_args = entry->ps_args;
3927 key.context = entry->context;
3928 wine_rb_remove(&priv->program_lookup, &key);
3929
3930 if (context_get_current() == entry->context)
3931 {
3932 TRACE("deleting program %p\n", (void *)(uintptr_t)entry->programId);
3933 GL_EXTCALL(glDeleteObjectARB(entry->programId));
3934 checkGLcall("glDeleteObjectARB");
3935 }
3936 else
3937 {
3938 WARN("Attempting to delete program %p created in ctx %p from ctx %p\n", (void *)(uintptr_t)entry->programId, entry->context, context_get_current());
3939 }
3940
3941 if (entry->vshader) list_remove(&entry->vshader_entry);
3942 if (entry->pshader) list_remove(&entry->pshader_entry);
3943 HeapFree(GetProcessHeap(), 0, entry->vuniformF_locations);
3944 HeapFree(GetProcessHeap(), 0, entry->puniformF_locations);
3945 HeapFree(GetProcessHeap(), 0, entry);
3946}
3947
3948static void handle_ps3_input(struct wined3d_shader_buffer *buffer, const struct wined3d_gl_info *gl_info, const DWORD *map,
3949 const struct wined3d_shader_signature_element *input_signature, const struct shader_reg_maps *reg_maps_in,
3950 const struct wined3d_shader_signature_element *output_signature, const struct shader_reg_maps *reg_maps_out)
3951{
3952 unsigned int i, j;
3953 const char *semantic_name_in, *semantic_name_out;
3954 UINT semantic_idx_in, semantic_idx_out;
3955 DWORD *set;
3956 DWORD in_idx;
3957 unsigned int in_count = vec4_varyings(3, gl_info);
3958 char reg_mask[6], reg_mask_out[6];
3959 char destination[50];
3960 WORD input_map, output_map;
3961
3962 set = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*set) * (in_count + 2));
3963
3964 if (!output_signature)
3965 {
3966 /* Save gl_FrontColor & gl_FrontSecondaryColor before overwriting them. */
3967 shader_addline(buffer, "vec4 front_color = gl_FrontColor;\n");
3968 shader_addline(buffer, "vec4 front_secondary_color = gl_FrontSecondaryColor;\n");
3969 }
3970
3971 input_map = reg_maps_in->input_registers;
3972 for (i = 0; input_map; input_map >>= 1, ++i)
3973 {
3974 if (!(input_map & 1)) continue;
3975
3976 in_idx = map[i];
3977 if (in_idx >= (in_count + 2)) {
3978 FIXME("More input varyings declared than supported, expect issues\n");
3979 continue;
3980 }
3981 else if (map[i] == ~0U)
3982 {
3983 /* Declared, but not read register */
3984 continue;
3985 }
3986
3987 if (in_idx == in_count) {
3988 sprintf(destination, "gl_FrontColor");
3989 } else if (in_idx == in_count + 1) {
3990 sprintf(destination, "gl_FrontSecondaryColor");
3991 } else {
3992 sprintf(destination, "IN[%u]", in_idx);
3993 }
3994
3995 semantic_name_in = input_signature[i].semantic_name;
3996 semantic_idx_in = input_signature[i].semantic_idx;
3997 set[map[i]] = input_signature[i].mask;
3998 shader_glsl_write_mask_to_str(input_signature[i].mask, reg_mask);
3999
4000 if (!output_signature)
4001 {
4002 if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_COLOR))
4003 {
4004 if (semantic_idx_in == 0)
4005 shader_addline(buffer, "%s%s = front_color%s;\n",
4006 destination, reg_mask, reg_mask);
4007 else if (semantic_idx_in == 1)
4008 shader_addline(buffer, "%s%s = front_secondary_color%s;\n",
4009 destination, reg_mask, reg_mask);
4010 else
4011 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4012 destination, reg_mask, reg_mask);
4013 }
4014 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_TEXCOORD))
4015 {
4016 if (semantic_idx_in < 8)
4017 {
4018 shader_addline(buffer, "%s%s = gl_TexCoord[%u]%s;\n",
4019 destination, reg_mask, semantic_idx_in, reg_mask);
4020 }
4021 else
4022 {
4023 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4024 destination, reg_mask, reg_mask);
4025 }
4026 }
4027 else if (shader_match_semantic(semantic_name_in, WINED3DDECLUSAGE_FOG))
4028 {
4029 shader_addline(buffer, "%s%s = vec4(gl_FogFragCoord, 0.0, 0.0, 0.0)%s;\n",
4030 destination, reg_mask, reg_mask);
4031 }
4032 else
4033 {
4034 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4035 destination, reg_mask, reg_mask);
4036 }
4037 } else {
4038 BOOL found = FALSE;
4039
4040 output_map = reg_maps_out->output_registers;
4041 for (j = 0; output_map; output_map >>= 1, ++j)
4042 {
4043 if (!(output_map & 1)) continue;
4044
4045 semantic_name_out = output_signature[j].semantic_name;
4046 semantic_idx_out = output_signature[j].semantic_idx;
4047 shader_glsl_write_mask_to_str(output_signature[j].mask, reg_mask_out);
4048
4049 if (semantic_idx_in == semantic_idx_out
4050 && !strcmp(semantic_name_in, semantic_name_out))
4051 {
4052 shader_addline(buffer, "%s%s = OUT[%u]%s;\n",
4053 destination, reg_mask, j, reg_mask);
4054 found = TRUE;
4055 }
4056 }
4057 if(!found) {
4058 shader_addline(buffer, "%s%s = vec4(0.0, 0.0, 0.0, 0.0)%s;\n",
4059 destination, reg_mask, reg_mask);
4060 }
4061 }
4062 }
4063
4064 /* This is solely to make the compiler / linker happy and avoid warning about undefined
4065 * varyings. It shouldn't result in any real code executed on the GPU, since all read
4066 * input varyings are assigned above, if the optimizer works properly.
4067 */
4068 for(i = 0; i < in_count + 2; i++) {
4069 if (set[i] && set[i] != WINED3DSP_WRITEMASK_ALL)
4070 {
4071 unsigned int size = 0;
4072 memset(reg_mask, 0, sizeof(reg_mask));
4073 if(!(set[i] & WINED3DSP_WRITEMASK_0)) {
4074 reg_mask[size] = 'x';
4075 size++;
4076 }
4077 if(!(set[i] & WINED3DSP_WRITEMASK_1)) {
4078 reg_mask[size] = 'y';
4079 size++;
4080 }
4081 if(!(set[i] & WINED3DSP_WRITEMASK_2)) {
4082 reg_mask[size] = 'z';
4083 size++;
4084 }
4085 if(!(set[i] & WINED3DSP_WRITEMASK_3)) {
4086 reg_mask[size] = 'w';
4087 size++;
4088 }
4089
4090 if (i == in_count) {
4091 sprintf(destination, "gl_FrontColor");
4092 } else if (i == in_count + 1) {
4093 sprintf(destination, "gl_FrontSecondaryColor");
4094 } else {
4095 sprintf(destination, "IN[%u]", i);
4096 }
4097
4098 if (size == 1) {
4099 shader_addline(buffer, "%s.%s = 0.0;\n", destination, reg_mask);
4100 } else {
4101 shader_addline(buffer, "%s.%s = vec%u(0.0);\n", destination, reg_mask, size);
4102 }
4103 }
4104 }
4105
4106 HeapFree(GetProcessHeap(), 0, set);
4107}
4108
4109static void generate_texcoord_assignment(struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *vs, IWineD3DPixelShaderImpl *ps)
4110{
4111 DWORD map;
4112 unsigned int i;
4113 char reg_mask[6];
4114
4115 if (!ps)
4116 return;
4117
4118 for (i = 0, map = ps->baseShader.reg_maps.texcoord; map && i < min(8, MAX_REG_TEXCRD); map >>= 1, ++i)
4119 {
4120 if (!(map & 1))
4121 continue;
4122
4123 /* so far we assume that if texcoord_mask has any write flags, they are assigned appropriately with pixel shader */
4124 if ((vs->baseShader.reg_maps.texcoord_mask[i]) & WINED3DSP_WRITEMASK_ALL)
4125 continue;
4126
4127 shader_glsl_write_mask_to_str(WINED3DSP_WRITEMASK_ALL, reg_mask);
4128 shader_addline(buffer, "gl_TexCoord[%u]%s = gl_MultiTexCoord%u%s;\n", i, reg_mask, i, reg_mask);
4129 }
4130}
4131
4132/* GL locking is done by the caller */
4133static GLhandleARB generate_param_reorder_function(struct wined3d_shader_buffer *buffer,
4134 IWineD3DVertexShader *a_vertexshader, IWineD3DPixelShader *pixelshader, const struct wined3d_gl_info *gl_info)
4135{
4136 GLhandleARB ret = 0;
4137 IWineD3DVertexShaderImpl *vs = (IWineD3DVertexShaderImpl *) a_vertexshader;
4138 IWineD3DPixelShaderImpl *ps = (IWineD3DPixelShaderImpl *) pixelshader;
4139 IWineD3DDeviceImpl *device;
4140 DWORD vs_major = vs->baseShader.reg_maps.shader_version.major;
4141 DWORD ps_major = ps ? ps->baseShader.reg_maps.shader_version.major : 0;
4142 unsigned int i;
4143 const char *semantic_name;
4144 UINT semantic_idx;
4145 char reg_mask[6];
4146 const struct wined3d_shader_signature_element *output_signature;
4147
4148 shader_buffer_clear(buffer);
4149
4150 shader_addline(buffer, "#version 120\n");
4151
4152 if(vs_major < 3 && ps_major < 3) {
4153 /* That one is easy: The vertex shader writes to the builtin varyings, the pixel shader reads from them.
4154 * Take care about the texcoord .w fixup though if we're using the fixed function fragment pipeline
4155 */
4156 device = (IWineD3DDeviceImpl *) vs->baseShader.device;
4157 if ((gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W)
4158 && ps_major == 0 && vs_major > 0 && !device->frag_pipe->ffp_proj_control)
4159 {
4160 shader_addline(buffer, "void order_ps_input() {\n");
4161 for(i = 0; i < min(8, MAX_REG_TEXCRD); i++) {
4162 if(vs->baseShader.reg_maps.texcoord_mask[i] != 0 &&
4163 vs->baseShader.reg_maps.texcoord_mask[i] != WINED3DSP_WRITEMASK_ALL) {
4164 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", i);
4165 }
4166 }
4167 shader_addline(buffer, "}\n");
4168 } else {
4169 shader_addline(buffer, "void order_ps_input() {\n");
4170 generate_texcoord_assignment(buffer, vs, ps);
4171 shader_addline(buffer, "}\n");
4172 }
4173 } else if(ps_major < 3 && vs_major >= 3) {
4174 WORD map = vs->baseShader.reg_maps.output_registers;
4175
4176 /* The vertex shader writes to its own varyings, the pixel shader needs them in the builtin ones */
4177 output_signature = vs->baseShader.output_signature;
4178
4179 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
4180 for (i = 0; map; map >>= 1, ++i)
4181 {
4182 DWORD write_mask;
4183
4184 if (!(map & 1)) continue;
4185
4186 semantic_name = output_signature[i].semantic_name;
4187 semantic_idx = output_signature[i].semantic_idx;
4188 write_mask = output_signature[i].mask;
4189 shader_glsl_write_mask_to_str(write_mask, reg_mask);
4190
4191 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_COLOR))
4192 {
4193 if (semantic_idx == 0)
4194 shader_addline(buffer, "gl_FrontColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4195 else if (semantic_idx == 1)
4196 shader_addline(buffer, "gl_FrontSecondaryColor%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4197 }
4198 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
4199 {
4200 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4201 }
4202 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_TEXCOORD))
4203 {
4204 if (semantic_idx < 8)
4205 {
4206 if (!(gl_info->quirks & WINED3D_QUIRK_SET_TEXCOORD_W) || ps_major > 0)
4207 write_mask |= WINED3DSP_WRITEMASK_3;
4208
4209 shader_addline(buffer, "gl_TexCoord[%u]%s = OUT[%u]%s;\n",
4210 semantic_idx, reg_mask, i, reg_mask);
4211 if (!(write_mask & WINED3DSP_WRITEMASK_3))
4212 shader_addline(buffer, "gl_TexCoord[%u].w = 1.0;\n", semantic_idx);
4213 }
4214 }
4215 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
4216 {
4217 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
4218 }
4219 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_FOG))
4220 {
4221 shader_addline(buffer, "gl_FogFragCoord = OUT[%u].%c;\n", i, reg_mask[1]);
4222 }
4223 }
4224 shader_addline(buffer, "}\n");
4225
4226 } else if(ps_major >= 3 && vs_major >= 3) {
4227 WORD map = vs->baseShader.reg_maps.output_registers;
4228
4229 output_signature = vs->baseShader.output_signature;
4230
4231 /* This one is tricky: a 3.0 pixel shader reads from a 3.0 vertex shader */
4232 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
4233 shader_addline(buffer, "void order_ps_input(in vec4 OUT[%u]) {\n", MAX_REG_OUTPUT);
4234
4235 /* First, sort out position and point size. Those are not passed to the pixel shader */
4236 for (i = 0; map; map >>= 1, ++i)
4237 {
4238 if (!(map & 1)) continue;
4239
4240 semantic_name = output_signature[i].semantic_name;
4241 shader_glsl_write_mask_to_str(output_signature[i].mask, reg_mask);
4242
4243 if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_POSITION))
4244 {
4245 shader_addline(buffer, "gl_Position%s = OUT[%u]%s;\n", reg_mask, i, reg_mask);
4246 }
4247 else if (shader_match_semantic(semantic_name, WINED3DDECLUSAGE_PSIZE))
4248 {
4249 shader_addline(buffer, "gl_PointSize = OUT[%u].x;\n", i);
4250 }
4251 }
4252
4253 /* Then, fix the pixel shader input */
4254 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
4255 &ps->baseShader.reg_maps, output_signature, &vs->baseShader.reg_maps);
4256
4257 shader_addline(buffer, "}\n");
4258 } else if(ps_major >= 3 && vs_major < 3) {
4259 shader_addline(buffer, "varying vec4 IN[%u];\n", vec4_varyings(3, gl_info));
4260 shader_addline(buffer, "void order_ps_input() {\n");
4261 /* The vertex shader wrote to the builtin varyings. There is no need to figure out position and
4262 * point size, but we depend on the optimizers kindness to find out that the pixel shader doesn't
4263 * read gl_TexCoord and gl_ColorX, otherwise we'll run out of varyings
4264 */
4265 handle_ps3_input(buffer, gl_info, ps->input_reg_map, ps->baseShader.input_signature,
4266 &ps->baseShader.reg_maps, NULL, NULL);
4267 shader_addline(buffer, "}\n");
4268 } else {
4269 ERR("Unexpected vertex and pixel shader version condition: vs: %d, ps: %d\n", vs_major, ps_major);
4270 }
4271
4272 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4273 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4274 GL_EXTCALL(glShaderSourceARB(ret, 1, (const char**)&buffer->buffer, NULL));
4275 checkGLcall("glShaderSourceARB(ret, 1, &buffer->buffer, NULL)");
4276 GL_EXTCALL(glCompileShaderARB(ret));
4277 checkGLcall("glCompileShaderARB(ret)");
4278 shader_glsl_validate_compile_link(gl_info, ret, FALSE);
4279 return ret;
4280}
4281
4282#ifdef VBOX_WITH_VMSVGA
4283static GLhandleARB generate_passthrough_vshader(const struct wined3d_gl_info *gl_info)
4284{
4285 GLhandleARB ret = 0;
4286 static const char *passthrough_vshader[] =
4287 {
4288 "#version 120\n"
4289 "vec4 R0;\n"
4290 "void main(void)\n"
4291 "{\n"
4292 " R0 = gl_Vertex;\n"
4293 " R0.w = 1.0;\n"
4294 " R0.z = 0.0;\n"
4295 " gl_Position = gl_ModelViewProjectionMatrix * R0;\n"
4296 "}\n"
4297 };
4298
4299 ret = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4300 checkGLcall("glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)");
4301 GL_EXTCALL(glShaderSourceARB(ret, 1, passthrough_vshader, NULL));
4302 checkGLcall("glShaderSourceARB(ret, 1, passthrough_vshader, NULL)");
4303 GL_EXTCALL(glCompileShaderARB(ret));
4304 checkGLcall("glCompileShaderARB(ret)");
4305 shader_glsl_validate_compile_link(gl_info, ret, FALSE);
4306
4307 return ret;
4308}
4309
4310#endif
4311
4312/* GL locking is done by the caller */
4313static void hardcode_local_constants(IWineD3DBaseShaderImpl *shader, const struct wined3d_gl_info *gl_info,
4314 GLhandleARB programId, char prefix)
4315{
4316 const local_constant *lconst;
4317 GLint tmp_loc;
4318 const float *value;
4319 char glsl_name[8];
4320
4321 LIST_FOR_EACH_ENTRY(lconst, &shader->baseShader.constantsF, local_constant, entry) {
4322 value = (const float *)lconst->value;
4323 snprintf(glsl_name, sizeof(glsl_name), "%cLC%u", prefix, lconst->idx);
4324 tmp_loc = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4325 GL_EXTCALL(glUniform4fvARB(tmp_loc, 1, value));
4326 }
4327 checkGLcall("Hardcoding local constants");
4328}
4329
4330/* GL locking is done by the caller */
4331#ifdef VBOX_WITH_VMSVGA
4332static GLhandleARB shader_glsl_generate_pshader(const struct wined3d_context *context,
4333#else
4334static GLuint shader_glsl_generate_pshader(const struct wined3d_context *context,
4335#endif
4336 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *This,
4337 const struct ps_compile_args *args, struct ps_np2fixup_info *np2fixup_info)
4338{
4339 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4340 const struct wined3d_gl_info *gl_info = context->gl_info;
4341 CONST DWORD *function = This->baseShader.function;
4342 struct shader_glsl_ctx_priv priv_ctx;
4343
4344 /* Create the hw GLSL shader object and assign it as the shader->prgId */
4345 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4346
4347 memset(&priv_ctx, 0, sizeof(priv_ctx));
4348 priv_ctx.cur_ps_args = args;
4349 priv_ctx.cur_np2fixup_info = np2fixup_info;
4350
4351 shader_addline(buffer, "#version 120\n");
4352
4353 if (gl_info->supported[ARB_SHADER_TEXTURE_LOD] && reg_maps->usestexldd)
4354 {
4355 shader_addline(buffer, "#extension GL_ARB_shader_texture_lod : enable\n");
4356 }
4357 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
4358 {
4359 /* The spec says that it doesn't have to be explicitly enabled, but the nvidia
4360 * drivers write a warning if we don't do so
4361 */
4362 shader_addline(buffer, "#extension GL_ARB_texture_rectangle : enable\n");
4363 }
4364 if (gl_info->supported[EXT_GPU_SHADER4])
4365 {
4366 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4367 }
4368
4369 /* Base Declarations */
4370 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4371
4372 /* Pack 3.0 inputs */
4373 if (reg_maps->shader_version.major >= 3 && args->vp_mode != vertexshader)
4374 {
4375 shader_glsl_input_pack((IWineD3DPixelShader *) This, buffer,
4376 This->baseShader.input_signature, reg_maps, args->vp_mode);
4377 }
4378
4379 /* Base Shader Body */
4380 shader_generate_main((IWineD3DBaseShader *)This, buffer, reg_maps, function, &priv_ctx);
4381
4382 /* Pixel shaders < 2.0 place the resulting color in R0 implicitly */
4383 if (reg_maps->shader_version.major < 2)
4384 {
4385 /* Some older cards like GeforceFX ones don't support multiple buffers, so also not gl_FragData */
4386 shader_addline(buffer, "gl_FragData[0] = R0;\n");
4387 }
4388
4389 if (args->srgb_correction)
4390 {
4391 shader_addline(buffer, "tmp0.xyz = pow(gl_FragData[0].xyz, vec3(srgb_const0.x));\n");
4392 shader_addline(buffer, "tmp0.xyz = tmp0.xyz * vec3(srgb_const0.y) - vec3(srgb_const0.z);\n");
4393 shader_addline(buffer, "tmp1.xyz = gl_FragData[0].xyz * vec3(srgb_const0.w);\n");
4394 shader_addline(buffer, "bvec3 srgb_compare = lessThan(gl_FragData[0].xyz, vec3(srgb_const1.x));\n");
4395 shader_addline(buffer, "gl_FragData[0].xyz = mix(tmp0.xyz, tmp1.xyz, vec3(srgb_compare));\n");
4396 shader_addline(buffer, "gl_FragData[0] = clamp(gl_FragData[0], 0.0, 1.0);\n");
4397 }
4398 /* Pixel shader < 3.0 do not replace the fog stage.
4399 * This implements linear fog computation and blending.
4400 * TODO: non linear fog
4401 * NOTE: gl_Fog.start and gl_Fog.end don't hold fog start s and end e but
4402 * -1/(e-s) and e/(e-s) respectively.
4403 */
4404 if (reg_maps->shader_version.major < 3)
4405 {
4406 switch(args->fog) {
4407 case FOG_OFF: break;
4408 case FOG_LINEAR:
4409 shader_addline(buffer, "float fogstart = -1.0 / (gl_Fog.end - gl_Fog.start);\n");
4410 shader_addline(buffer, "float fogend = gl_Fog.end * -fogstart;\n");
4411 shader_addline(buffer, "float Fog = clamp(gl_FogFragCoord * fogstart + fogend, 0.0, 1.0);\n");
4412 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4413 break;
4414 case FOG_EXP:
4415 /* Fog = e^(-gl_Fog.density * gl_FogFragCoord) */
4416 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_FogFragCoord);\n");
4417 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4418 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4419 break;
4420 case FOG_EXP2:
4421 /* Fog = e^(-(gl_Fog.density * gl_FogFragCoord)^2) */
4422 shader_addline(buffer, "float Fog = exp(-gl_Fog.density * gl_Fog.density * gl_FogFragCoord * gl_FogFragCoord);\n");
4423 shader_addline(buffer, "Fog = clamp(Fog, 0.0, 1.0);\n");
4424 shader_addline(buffer, "gl_FragData[0].xyz = mix(gl_Fog.color.xyz, gl_FragData[0].xyz, Fog);\n");
4425 break;
4426 }
4427 }
4428
4429 shader_addline(buffer, "}\n");
4430
4431 TRACE("Compiling shader object %p\n", (void *)(uintptr_t)shader_obj);
4432 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4433 GL_EXTCALL(glCompileShaderARB(shader_obj));
4434 shader_glsl_validate_compile_link(gl_info, shader_obj, FALSE);
4435
4436 /* Store the shader object */
4437 return shader_obj;
4438}
4439
4440/* GL locking is done by the caller */
4441#ifdef VBOX_WITH_VMSVGA
4442static GLhandleARB shader_glsl_generate_vshader(const struct wined3d_context *context,
4443#else
4444static GLuint shader_glsl_generate_vshader(const struct wined3d_context *context,
4445#endif
4446 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *This,
4447 const struct vs_compile_args *args)
4448{
4449 const struct shader_reg_maps *reg_maps = &This->baseShader.reg_maps;
4450 const struct wined3d_gl_info *gl_info = context->gl_info;
4451 CONST DWORD *function = This->baseShader.function;
4452 struct shader_glsl_ctx_priv priv_ctx;
4453
4454 /* Create the hw GLSL shader program and assign it as the shader->prgId */
4455 GLhandleARB shader_obj = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4456
4457 shader_addline(buffer, "#version 120\n");
4458
4459 if (gl_info->supported[EXT_GPU_SHADER4])
4460 {
4461 shader_addline(buffer, "#extension GL_EXT_gpu_shader4 : enable\n");
4462 }
4463
4464 memset(&priv_ctx, 0, sizeof(priv_ctx));
4465 priv_ctx.cur_vs_args = args;
4466
4467 /* Base Declarations */
4468 shader_generate_glsl_declarations(context, buffer, (IWineD3DBaseShader *)This, reg_maps, &priv_ctx);
4469
4470 /* Base Shader Body */
4471 shader_generate_main((IWineD3DBaseShader*)This, buffer, reg_maps, function, &priv_ctx);
4472
4473 /* Unpack 3.0 outputs */
4474 if (reg_maps->shader_version.major >= 3) shader_addline(buffer, "order_ps_input(OUT);\n");
4475 else shader_addline(buffer, "order_ps_input();\n");
4476
4477 /* The D3DRS_FOGTABLEMODE render state defines if the shader-generated fog coord is used
4478 * or if the fragment depth is used. If the fragment depth is used(FOGTABLEMODE != NONE),
4479 * the fog frag coord is thrown away. If the fog frag coord is used, but not written by
4480 * the shader, it is set to 0.0(fully fogged, since start = 1.0, end = 0.0)
4481 */
4482 if(args->fog_src == VS_FOG_Z) {
4483 shader_addline(buffer, "gl_FogFragCoord = gl_Position.z;\n");
4484 } else if (!reg_maps->fog) {
4485 shader_addline(buffer, "gl_FogFragCoord = 0.0;\n");
4486 }
4487
4488 /* Write the final position.
4489 *
4490 * OpenGL coordinates specify the center of the pixel while d3d coords specify
4491 * the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
4492 * 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
4493 * contains 1.0 to allow a mad.
4494 */
4495 shader_addline(buffer, "gl_Position.y = gl_Position.y * posFixup.y;\n");
4496 shader_addline(buffer, "gl_Position.xy += posFixup.zw * gl_Position.ww;\n");
4497 if(args->clip_enabled) {
4498 shader_addline(buffer, "gl_ClipVertex = gl_Position;\n");
4499 }
4500
4501 /* Z coord [0;1]->[-1;1] mapping, see comment in transform_projection in state.c
4502 *
4503 * Basically we want (in homogeneous coordinates) z = z * 2 - 1. However, shaders are run
4504 * before the homogeneous divide, so we have to take the w into account: z = ((z / w) * 2 - 1) * w,
4505 * which is the same as z = z * 2 - w.
4506 */
4507 shader_addline(buffer, "gl_Position.z = gl_Position.z * 2.0 - gl_Position.w;\n");
4508
4509 shader_addline(buffer, "}\n");
4510
4511 TRACE("Compiling shader object %p\n", (void *)(uintptr_t)shader_obj);
4512 GL_EXTCALL(glShaderSourceARB(shader_obj, 1, (const char**)&buffer->buffer, NULL));
4513 GL_EXTCALL(glCompileShaderARB(shader_obj));
4514 shader_glsl_validate_compile_link(gl_info, shader_obj, FALSE);
4515
4516 return shader_obj;
4517}
4518
4519static GLhandleARB find_glsl_pshader(const struct wined3d_context *context,
4520 struct wined3d_shader_buffer *buffer, IWineD3DPixelShaderImpl *shader,
4521 const struct ps_compile_args *args,
4522 UINT *inp2fixup_info
4523 )
4524{
4525 UINT i;
4526 DWORD new_size;
4527 struct glsl_ps_compiled_shader *new_array;
4528 struct glsl_pshader_private *shader_data;
4529 struct ps_np2fixup_info *np2fixup = NULL;
4530 GLhandleARB ret;
4531
4532 if (!shader->baseShader.backend_data)
4533 {
4534 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4535 if (!shader->baseShader.backend_data)
4536 {
4537 ERR("Failed to allocate backend data.\n");
4538 return 0;
4539 }
4540 }
4541 shader_data = shader->baseShader.backend_data;
4542
4543 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4544 * so a linear search is more performant than a hashmap or a binary search
4545 * (cache coherency etc)
4546 */
4547 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4548 if(shader_data->gl_shaders[i].context==context
4549 && memcmp(&shader_data->gl_shaders[i].args, args, sizeof(*args)) == 0) {
4550 if(args->np2_fixup) {
4551 *inp2fixup_info = i;
4552 }
4553 return shader_data->gl_shaders[i].prgId;
4554 }
4555 }
4556
4557 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4558 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4559 if (shader_data->num_gl_shaders)
4560 {
4561 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4562 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4563 new_size * sizeof(*shader_data->gl_shaders));
4564 } else {
4565 new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4566 new_size = 1;
4567 }
4568
4569 if(!new_array) {
4570 ERR("Out of memory\n");
4571 return 0;
4572 }
4573 shader_data->gl_shaders = new_array;
4574 shader_data->shader_array_size = new_size;
4575 }
4576
4577 shader_data->gl_shaders[shader_data->num_gl_shaders].context = context;
4578 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4579
4580 memset(&shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup, 0, sizeof(struct ps_np2fixup_info));
4581 if (args->np2_fixup) np2fixup = &shader_data->gl_shaders[shader_data->num_gl_shaders].np2fixup;
4582
4583 pixelshader_update_samplers(&shader->baseShader.reg_maps,
4584 ((IWineD3DDeviceImpl *)shader->baseShader.device)->stateBlock->textures);
4585
4586 shader_buffer_clear(buffer);
4587 ret = shader_glsl_generate_pshader(context, buffer, shader, args, np2fixup);
4588 *inp2fixup_info = shader_data->num_gl_shaders;
4589 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4590
4591 return ret;
4592}
4593
4594static inline BOOL vs_args_equal(const struct vs_compile_args *stored, const struct vs_compile_args *new,
4595 const DWORD use_map) {
4596 if((stored->swizzle_map & use_map) != new->swizzle_map) return FALSE;
4597 if((stored->clip_enabled) != new->clip_enabled) return FALSE;
4598 return stored->fog_src == new->fog_src;
4599}
4600
4601static GLhandleARB find_glsl_vshader(const struct wined3d_context *context,
4602 struct wined3d_shader_buffer *buffer, IWineD3DVertexShaderImpl *shader,
4603 const struct vs_compile_args *args)
4604{
4605 UINT i;
4606 DWORD new_size;
4607 struct glsl_vs_compiled_shader *new_array;
4608 DWORD use_map = ((IWineD3DDeviceImpl *)shader->baseShader.device)->strided_streams.use_map;
4609 struct glsl_vshader_private *shader_data;
4610 GLhandleARB ret;
4611
4612 if (!shader->baseShader.backend_data)
4613 {
4614 shader->baseShader.backend_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data));
4615 if (!shader->baseShader.backend_data)
4616 {
4617 ERR("Failed to allocate backend data.\n");
4618 return 0;
4619 }
4620 }
4621 shader_data = shader->baseShader.backend_data;
4622
4623 /* Usually we have very few GL shaders for each d3d shader(just 1 or maybe 2),
4624 * so a linear search is more performant than a hashmap or a binary search
4625 * (cache coherency etc)
4626 */
4627 for(i = 0; i < shader_data->num_gl_shaders; i++) {
4628 if(shader_data->gl_shaders[i].context==context
4629 && vs_args_equal(&shader_data->gl_shaders[i].args, args, use_map)) {
4630 return shader_data->gl_shaders[i].prgId;
4631 }
4632 }
4633
4634 TRACE("No matching GL shader found for shader %p, compiling a new shader.\n", shader);
4635
4636 if(shader_data->shader_array_size == shader_data->num_gl_shaders) {
4637 if (shader_data->num_gl_shaders)
4638 {
4639 new_size = shader_data->shader_array_size + max(1, shader_data->shader_array_size / 2);
4640 new_array = HeapReAlloc(GetProcessHeap(), 0, shader_data->gl_shaders,
4641 new_size * sizeof(*shader_data->gl_shaders));
4642 } else {
4643 new_array = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*shader_data->gl_shaders));
4644 new_size = 1;
4645 }
4646
4647 if(!new_array) {
4648 ERR("Out of memory\n");
4649 return 0;
4650 }
4651 shader_data->gl_shaders = new_array;
4652 shader_data->shader_array_size = new_size;
4653 }
4654
4655 shader_data->gl_shaders[shader_data->num_gl_shaders].context = context;
4656 shader_data->gl_shaders[shader_data->num_gl_shaders].args = *args;
4657
4658 shader_buffer_clear(buffer);
4659 ret = shader_glsl_generate_vshader(context, buffer, shader, args);
4660 shader_data->gl_shaders[shader_data->num_gl_shaders++].prgId = ret;
4661
4662 return ret;
4663}
4664
4665/** Sets the GLSL program ID for the given pixel and vertex shader combination.
4666 * It sets the programId on the current StateBlock (because it should be called
4667 * inside of the DrawPrimitive() part of the render loop).
4668 *
4669 * If a program for the given combination does not exist, create one, and store
4670 * the program in the hash table. If it creates a program, it will link the
4671 * given objects, too.
4672 */
4673
4674/* GL locking is done by the caller */
4675static void set_glsl_shader_program(const struct wined3d_context *context,
4676 IWineD3DDeviceImpl *device, BOOL a_use_ps, BOOL a_use_vs)
4677{
4678 IWineD3DVertexShader *vshader = a_use_vs ? device->stateBlock->vertexShader : NULL;
4679 IWineD3DPixelShader *pshader = a_use_ps ? device->stateBlock->pixelShader : NULL;
4680 const struct wined3d_gl_info *gl_info = context->gl_info;
4681 struct shader_glsl_priv *priv = device->shader_priv;
4682 struct glsl_shader_prog_link *entry = NULL;
4683 GLhandleARB programId = 0;
4684 GLhandleARB reorder_shader_id = 0;
4685 unsigned int i;
4686 char glsl_name[8];
4687 struct ps_compile_args ps_compile_args;
4688 struct vs_compile_args vs_compile_args;
4689
4690 if (vshader) find_vs_compile_args((IWineD3DVertexShaderImpl *)vshader, device->stateBlock, &vs_compile_args);
4691 if (pshader) find_ps_compile_args((IWineD3DPixelShaderImpl *)pshader, device->stateBlock, &ps_compile_args);
4692
4693 entry = get_glsl_program_entry(priv, vshader, pshader, &vs_compile_args, &ps_compile_args, context);
4694 if (entry) {
4695 priv->glsl_program = entry;
4696 return;
4697 }
4698
4699 /* If we get to this point, then no matching program exists, so we create one */
4700 programId = GL_EXTCALL(glCreateProgramObjectARB());
4701 TRACE("Created new GLSL shader program %p\n", (void *)(uintptr_t)programId);
4702
4703 /* Create the entry */
4704 entry = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct glsl_shader_prog_link));
4705 entry->context = context;
4706 entry->programId = programId;
4707 entry->vshader = vshader;
4708 entry->pshader = pshader;
4709 entry->vs_args = vs_compile_args;
4710 entry->ps_args = ps_compile_args;
4711 entry->constant_version = 0;
4712 WINEFIXUPINFO_INIT(entry);
4713 /* Add the hash table entry */
4714 add_glsl_program_entry(priv, entry);
4715
4716 /* Set the current program */
4717 priv->glsl_program = entry;
4718
4719 /* Attach GLSL vshader */
4720 if (vshader)
4721 {
4722 GLhandleARB vshader_id = find_glsl_vshader(context, &priv->shader_buffer,
4723 (IWineD3DVertexShaderImpl *)vshader, &vs_compile_args);
4724 WORD map = ((IWineD3DBaseShaderImpl *)vshader)->baseShader.reg_maps.input_registers;
4725 char tmp_name[10];
4726
4727 reorder_shader_id = generate_param_reorder_function(&priv->shader_buffer, vshader, pshader, gl_info);
4728 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)reorder_shader_id, (void *)(uintptr_t)programId);
4729 GL_EXTCALL(glAttachObjectARB(programId, reorder_shader_id));
4730 checkGLcall("glAttachObjectARB");
4731 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4732 * is destroyed
4733 */
4734 GL_EXTCALL(glDeleteObjectARB(reorder_shader_id));
4735
4736 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)vshader_id, (void *)(uintptr_t)programId);
4737 GL_EXTCALL(glAttachObjectARB(programId, vshader_id));
4738 checkGLcall("glAttachObjectARB");
4739
4740 /* Bind vertex attributes to a corresponding index number to match
4741 * the same index numbers as ARB_vertex_programs (makes loading
4742 * vertex attributes simpler). With this method, we can use the
4743 * exact same code to load the attributes later for both ARB and
4744 * GLSL shaders.
4745 *
4746 * We have to do this here because we need to know the Program ID
4747 * in order to make the bindings work, and it has to be done prior
4748 * to linking the GLSL program. */
4749 for (i = 0; map; map >>= 1, ++i)
4750 {
4751 if (!(map & 1)) continue;
4752
4753 snprintf(tmp_name, sizeof(tmp_name), "attrib%u", i);
4754 GL_EXTCALL(glBindAttribLocationARB(programId, i, tmp_name));
4755 }
4756 checkGLcall("glBindAttribLocationARB");
4757
4758 list_add_head(&((IWineD3DBaseShaderImpl *)vshader)->baseShader.linked_programs, &entry->vshader_entry);
4759 }
4760#ifdef VBOX_WITH_VMSVGA
4761 else
4762 if (device->strided_streams.position_transformed)
4763 {
4764 GLhandleARB passthrough_vshader_id;
4765
4766 passthrough_vshader_id = generate_passthrough_vshader(gl_info);
4767 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)passthrough_vshader_id, (void *)(uintptr_t)programId);
4768 GL_EXTCALL(glAttachObjectARB(programId, passthrough_vshader_id));
4769 checkGLcall("glAttachObjectARB");
4770 /* Flag the reorder function for deletion, then it will be freed automatically when the program
4771 * is destroyed
4772 */
4773 GL_EXTCALL(glDeleteObjectARB(passthrough_vshader_id));
4774 }
4775#endif
4776
4777
4778 /* Attach GLSL pshader */
4779 if (pshader)
4780 {
4781 GLhandleARB pshader_id = find_glsl_pshader(context, &priv->shader_buffer,
4782 (IWineD3DPixelShaderImpl *)pshader, &ps_compile_args,
4783 &entry->inp2Fixup_info
4784 );
4785 TRACE("Attaching GLSL shader object %p to program %p\n", (void *)(uintptr_t)pshader_id, (void *)(uintptr_t)programId);
4786 GL_EXTCALL(glAttachObjectARB(programId, pshader_id));
4787 checkGLcall("glAttachObjectARB");
4788
4789 list_add_head(&((IWineD3DBaseShaderImpl *)pshader)->baseShader.linked_programs, &entry->pshader_entry);
4790 }
4791
4792 /* Link the program */
4793 TRACE("Linking GLSL shader program %p\n", (void *)(uintptr_t)programId);
4794 GL_EXTCALL(glLinkProgramARB(programId));
4795 shader_glsl_validate_compile_link(gl_info, programId, TRUE);
4796
4797 entry->vuniformF_locations = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4798 sizeof(GLhandleARB) * gl_info->limits.glsl_vs_float_constants);
4799 for (i = 0; i < gl_info->limits.glsl_vs_float_constants; ++i)
4800 {
4801 snprintf(glsl_name, sizeof(glsl_name), "VC[%i]", i);
4802 entry->vuniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4803 }
4804 for (i = 0; i < MAX_CONST_I; ++i)
4805 {
4806 snprintf(glsl_name, sizeof(glsl_name), "VI[%i]", i);
4807 entry->vuniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4808 }
4809 entry->puniformF_locations = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4810 sizeof(GLhandleARB) * gl_info->limits.glsl_ps_float_constants);
4811 for (i = 0; i < gl_info->limits.glsl_ps_float_constants; ++i)
4812 {
4813 snprintf(glsl_name, sizeof(glsl_name), "PC[%i]", i);
4814 entry->puniformF_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4815 }
4816 for (i = 0; i < MAX_CONST_I; ++i)
4817 {
4818 snprintf(glsl_name, sizeof(glsl_name), "PI[%i]", i);
4819 entry->puniformI_locations[i] = GL_EXTCALL(glGetUniformLocationARB(programId, glsl_name));
4820 }
4821
4822 if(pshader) {
4823 char name[32];
4824
4825 for(i = 0; i < MAX_TEXTURES; i++) {
4826 sprintf(name, "bumpenvmat%u", i);
4827 entry->bumpenvmat_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4828 sprintf(name, "luminancescale%u", i);
4829 entry->luminancescale_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4830 sprintf(name, "luminanceoffset%u", i);
4831 entry->luminanceoffset_location[i] = GL_EXTCALL(glGetUniformLocationARB(programId, name));
4832 }
4833
4834 if (ps_compile_args.np2_fixup) {
4835 if (WINEFIXUPINFO_ISVALID(entry)) {
4836 entry->np2Fixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "PsamplerNP2Fixup"));
4837 } else {
4838 FIXME("NP2 texcoord fixup needed for this pixelshader, but no fixup uniform found.\n");
4839 }
4840 }
4841 }
4842
4843 entry->posFixup_location = GL_EXTCALL(glGetUniformLocationARB(programId, "posFixup"));
4844 entry->ycorrection_location = GL_EXTCALL(glGetUniformLocationARB(programId, "ycorrection"));
4845 checkGLcall("Find glsl program uniform locations");
4846
4847 if (pshader
4848 && ((IWineD3DPixelShaderImpl *)pshader)->baseShader.reg_maps.shader_version.major >= 3
4849 && ((IWineD3DPixelShaderImpl *)pshader)->declared_in_count > vec4_varyings(3, gl_info))
4850 {
4851 TRACE("Shader %p needs vertex color clamping disabled\n", (void *)(uintptr_t)programId);
4852 entry->vertex_color_clamp = GL_FALSE;
4853 } else {
4854 entry->vertex_color_clamp = GL_FIXED_ONLY_ARB;
4855 }
4856
4857 /* Set the shader to allow uniform loading on it */
4858 GL_EXTCALL(glUseProgramObjectARB(programId));
4859 checkGLcall("glUseProgramObjectARB(programId)");
4860
4861#ifdef DEBUG_misha
4862 {
4863 GLint programIdTest = -1;
4864 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
4865 Assert(programIdTest == programId);
4866 }
4867#endif
4868
4869 /* Load the vertex and pixel samplers now. The function that finds the mappings makes sure
4870 * that it stays the same for each vertexshader-pixelshader pair(=linked glsl program). If
4871 * a pshader with fixed function pipeline is used there are no vertex samplers, and if a
4872 * vertex shader with fixed function pixel processing is used we make sure that the card
4873 * supports enough samplers to allow the max number of vertex samplers with all possible
4874 * fixed function fragment processing setups. So once the program is linked these samplers
4875 * won't change.
4876 */
4877 if (vshader) shader_glsl_load_vsamplers(gl_info, device->texUnitMap, programId);
4878 if (pshader) shader_glsl_load_psamplers(gl_info, device->texUnitMap, programId);
4879
4880 /* If the local constants do not have to be loaded with the environment constants,
4881 * load them now to have them hardcoded in the GLSL program. This saves some CPU cycles
4882 * later
4883 */
4884 if (pshader && !((IWineD3DBaseShaderImpl *)pshader)->baseShader.load_local_constsF)
4885 {
4886 hardcode_local_constants((IWineD3DBaseShaderImpl *) pshader, gl_info, programId, 'P');
4887 }
4888 if (vshader && !((IWineD3DBaseShaderImpl *)vshader)->baseShader.load_local_constsF)
4889 {
4890 hardcode_local_constants((IWineD3DBaseShaderImpl *) vshader, gl_info, programId, 'V');
4891 }
4892}
4893
4894/* GL locking is done by the caller */
4895static GLhandleARB create_glsl_blt_shader(const struct wined3d_gl_info *gl_info, enum tex_types tex_type)
4896{
4897 GLhandleARB program_id;
4898 GLhandleARB vshader_id, pshader_id;
4899 static const char *blt_vshader[] =
4900 {
4901 "#version 120\n"
4902 "void main(void)\n"
4903 "{\n"
4904 " gl_Position = gl_Vertex;\n"
4905 " gl_FrontColor = vec4(1.0);\n"
4906 " gl_TexCoord[0] = gl_MultiTexCoord0;\n"
4907 "}\n"
4908 };
4909
4910 static const char *blt_pshaders[tex_type_count] =
4911 {
4912 /* tex_1d */
4913 NULL,
4914 /* tex_2d */
4915 "#version 120\n"
4916 "uniform sampler2D sampler;\n"
4917 "void main(void)\n"
4918 "{\n"
4919 " gl_FragDepth = texture2D(sampler, gl_TexCoord[0].xy).x;\n"
4920 "}\n",
4921 /* tex_3d */
4922 NULL,
4923 /* tex_cube */
4924 "#version 120\n"
4925 "uniform samplerCube sampler;\n"
4926 "void main(void)\n"
4927 "{\n"
4928 " gl_FragDepth = textureCube(sampler, gl_TexCoord[0].xyz).x;\n"
4929 "}\n",
4930 /* tex_rect */
4931 "#version 120\n"
4932 "#extension GL_ARB_texture_rectangle : enable\n"
4933 "uniform sampler2DRect sampler;\n"
4934 "void main(void)\n"
4935 "{\n"
4936 " gl_FragDepth = texture2DRect(sampler, gl_TexCoord[0].xy).x;\n"
4937 "}\n",
4938 };
4939
4940 if (!blt_pshaders[tex_type])
4941 {
4942 FIXME("tex_type %#x not supported\n", tex_type);
4943 tex_type = tex_2d;
4944 }
4945
4946 vshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB));
4947 GL_EXTCALL(glShaderSourceARB(vshader_id, 1, blt_vshader, NULL));
4948 GL_EXTCALL(glCompileShaderARB(vshader_id));
4949 shader_glsl_validate_compile_link(gl_info, vshader_id, FALSE);
4950
4951 pshader_id = GL_EXTCALL(glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB));
4952 GL_EXTCALL(glShaderSourceARB(pshader_id, 1, &blt_pshaders[tex_type], NULL));
4953 GL_EXTCALL(glCompileShaderARB(pshader_id));
4954
4955 shader_glsl_validate_compile_link(gl_info, vshader_id, FALSE);
4956
4957 program_id = GL_EXTCALL(glCreateProgramObjectARB());
4958 GL_EXTCALL(glAttachObjectARB(program_id, vshader_id));
4959 GL_EXTCALL(glAttachObjectARB(program_id, pshader_id));
4960 GL_EXTCALL(glLinkProgramARB(program_id));
4961 shader_glsl_validate_compile_link(gl_info, program_id, TRUE);
4962
4963 /* Once linked we can mark the shaders for deletion. They will be deleted once the program
4964 * is destroyed
4965 */
4966 GL_EXTCALL(glDeleteObjectARB(vshader_id));
4967 GL_EXTCALL(glDeleteObjectARB(pshader_id));
4968 return program_id;
4969}
4970
4971/* GL locking is done by the caller */
4972static void shader_glsl_select(const struct wined3d_context *context, BOOL usePS, BOOL useVS)
4973{
4974 const struct wined3d_gl_info *gl_info = context->gl_info;
4975 IWineD3DDeviceImpl *device = context_get_device(context);
4976 struct shader_glsl_priv *priv = device->shader_priv;
4977 GLhandleARB program_id = 0;
4978 GLenum old_vertex_color_clamp, current_vertex_color_clamp;
4979
4980 old_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4981
4982 if (useVS || usePS) set_glsl_shader_program(context, device, usePS, useVS);
4983 else priv->glsl_program = NULL;
4984
4985 current_vertex_color_clamp = priv->glsl_program ? priv->glsl_program->vertex_color_clamp : GL_FIXED_ONLY_ARB;
4986
4987 if (old_vertex_color_clamp != current_vertex_color_clamp)
4988 {
4989 if (gl_info->supported[ARB_COLOR_BUFFER_FLOAT])
4990 {
4991 GL_EXTCALL(glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, current_vertex_color_clamp));
4992 checkGLcall("glClampColorARB");
4993 }
4994 else
4995 {
4996 FIXME("vertex color clamp needs to be changed, but extension not supported.\n");
4997 }
4998 }
4999
5000 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5001 if (program_id) TRACE("Using GLSL program %p\n", (void *)(uintptr_t)program_id);
5002 GL_EXTCALL(glUseProgramObjectARB(program_id));
5003 checkGLcall("glUseProgramObjectARB");
5004#ifdef DEBUG_misha
5005 {
5006 GLint programIdTest = -1;
5007 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5008 Assert(programIdTest == program_id);
5009 }
5010#endif
5011
5012 /* In case that NP2 texcoord fixup data is found for the selected program, trigger a reload of the
5013 * constants. This has to be done because it can't be guaranteed that sampler() (from state.c) is
5014 * called between selecting the shader and using it, which results in wrong fixup for some frames. */
5015 if (priv->glsl_program && WINEFIXUPINFO_ISVALID(priv->glsl_program))
5016 {
5017 shader_glsl_load_np2fixup_constants((IWineD3DDevice *)device, usePS, useVS);
5018 }
5019}
5020
5021/* GL locking is done by the caller */
5022static void shader_glsl_select_depth_blt(IWineD3DDevice *iface, enum tex_types tex_type) {
5023 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5024 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5025 struct shader_glsl_priv *priv = This->shader_priv;
5026 GLhandleARB *blt_program = &priv->depth_blt_program[tex_type];
5027
5028 if (!*blt_program) {
5029 GLint loc;
5030 *blt_program = create_glsl_blt_shader(gl_info, tex_type);
5031 loc = GL_EXTCALL(glGetUniformLocationARB(*blt_program, "sampler"));
5032 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5033#ifdef DEBUG_misha
5034 {
5035 GLint programIdTest = -1;
5036 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5037 Assert(programIdTest == *blt_program);
5038 }
5039#endif
5040 GL_EXTCALL(glUniform1iARB(loc, 0));
5041 } else {
5042 GL_EXTCALL(glUseProgramObjectARB(*blt_program));
5043#ifdef DEBUG_misha
5044 {
5045 GLint programIdTest = -1;
5046 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5047 Assert(programIdTest == *blt_program);
5048 }
5049#endif
5050 }
5051}
5052
5053/* GL locking is done by the caller */
5054static void shader_glsl_deselect_depth_blt(IWineD3DDevice *iface) {
5055 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5056 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5057 struct shader_glsl_priv *priv = This->shader_priv;
5058 GLhandleARB program_id;
5059
5060 program_id = priv->glsl_program ? priv->glsl_program->programId : 0;
5061 if (program_id) TRACE("Using GLSL program %p\n", (void *)(uintptr_t)program_id);
5062
5063 GL_EXTCALL(glUseProgramObjectARB(program_id));
5064 checkGLcall("glUseProgramObjectARB");
5065#ifdef DEBUG_misha
5066 {
5067 GLint programIdTest = -1;
5068 glGetIntegerv(GL_CURRENT_PROGRAM, &programIdTest);
5069 Assert(programIdTest == program_id);
5070 }
5071#endif
5072}
5073
5074static void shader_glsl_destroy(IWineD3DBaseShader *iface) {
5075 const struct list *linked_programs;
5076 IWineD3DBaseShaderImpl *This = (IWineD3DBaseShaderImpl *) iface;
5077 IWineD3DDeviceImpl *device = (IWineD3DDeviceImpl *)This->baseShader.device;
5078 struct shader_glsl_priv *priv = device->shader_priv;
5079 const struct wined3d_gl_info *gl_info;
5080 struct wined3d_context *context;
5081
5082 /* Note: Do not use QueryInterface here to find out which shader type this is because this code
5083 * can be called from IWineD3DBaseShader::Release
5084 */
5085 char pshader = shader_is_pshader_version(This->baseShader.reg_maps.shader_version.type);
5086
5087 if(pshader) {
5088 struct glsl_pshader_private *shader_data;
5089 shader_data = This->baseShader.backend_data;
5090 if(!shader_data || shader_data->num_gl_shaders == 0)
5091 {
5092 HeapFree(GetProcessHeap(), 0, shader_data);
5093 This->baseShader.backend_data = NULL;
5094 return;
5095 }
5096
5097 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
5098 gl_info = context->gl_info;
5099
5100 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->pshader == iface)
5101 {
5102 ENTER_GL();
5103 shader_glsl_select(context, FALSE, FALSE);
5104 LEAVE_GL();
5105 }
5106 } else {
5107 struct glsl_vshader_private *shader_data;
5108 shader_data = This->baseShader.backend_data;
5109 if(!shader_data || shader_data->num_gl_shaders == 0)
5110 {
5111 HeapFree(GetProcessHeap(), 0, shader_data);
5112 This->baseShader.backend_data = NULL;
5113 return;
5114 }
5115
5116 context = context_acquire(device, NULL, CTXUSAGE_RESOURCELOAD);
5117 gl_info = context->gl_info;
5118
5119 if (priv->glsl_program && (IWineD3DBaseShader *)priv->glsl_program->vshader == iface)
5120 {
5121 ENTER_GL();
5122 shader_glsl_select(context, FALSE, FALSE);
5123 LEAVE_GL();
5124 }
5125 }
5126
5127 linked_programs = &This->baseShader.linked_programs;
5128
5129 TRACE("Deleting linked programs\n");
5130 if (linked_programs->next) {
5131 struct glsl_shader_prog_link *entry, *entry2;
5132
5133 ENTER_GL();
5134 if(pshader) {
5135 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, pshader_entry) {
5136 delete_glsl_program_entry(priv, gl_info, entry);
5137 }
5138 } else {
5139 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, linked_programs, struct glsl_shader_prog_link, vshader_entry) {
5140 delete_glsl_program_entry(priv, gl_info, entry);
5141 }
5142 }
5143 LEAVE_GL();
5144 }
5145
5146 if(pshader) {
5147 UINT i;
5148 struct glsl_pshader_private *shader_data = This->baseShader.backend_data;
5149
5150 ENTER_GL();
5151 for(i = 0; i < shader_data->num_gl_shaders; i++) {
5152 if (shader_data->gl_shaders[i].context==context_get_current())
5153 {
5154 TRACE("deleting pshader %p\n", (void *)(uintptr_t)shader_data->gl_shaders[i].prgId);
5155 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
5156 checkGLcall("glDeleteObjectARB");
5157 }
5158 else
5159 {
5160 WARN("Attempting to delete pshader %p created in ctx %p from ctx %p\n",
5161 (void *)(uintptr_t)shader_data->gl_shaders[i].prgId, shader_data->gl_shaders[i].context, context_get_current());
5162 }
5163 }
5164 LEAVE_GL();
5165 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
5166 }
5167 else
5168 {
5169 UINT i;
5170 struct glsl_vshader_private *shader_data = This->baseShader.backend_data;
5171
5172 ENTER_GL();
5173 for(i = 0; i < shader_data->num_gl_shaders; i++) {
5174 if (shader_data->gl_shaders[i].context==context_get_current())
5175 {
5176 TRACE("deleting vshader %p\n", (void *)(uintptr_t)shader_data->gl_shaders[i].prgId);
5177 GL_EXTCALL(glDeleteObjectARB(shader_data->gl_shaders[i].prgId));
5178 checkGLcall("glDeleteObjectARB");
5179 }
5180 else
5181 {
5182 WARN("Attempting to delete vshader %p created in ctx %p from ctx %p\n",
5183 (void *)(uintptr_t)shader_data->gl_shaders[i].prgId, shader_data->gl_shaders[i].context, context_get_current());
5184 }
5185 }
5186 LEAVE_GL();
5187 HeapFree(GetProcessHeap(), 0, shader_data->gl_shaders);
5188 }
5189
5190 HeapFree(GetProcessHeap(), 0, This->baseShader.backend_data);
5191 This->baseShader.backend_data = NULL;
5192
5193 context_release(context);
5194}
5195
5196static int glsl_program_key_compare(const void *key, const struct wine_rb_entry *entry)
5197{
5198 const glsl_program_key_t *k = key;
5199 const struct glsl_shader_prog_link *prog = WINE_RB_ENTRY_VALUE(entry,
5200 const struct glsl_shader_prog_link, program_lookup_entry);
5201 int cmp;
5202
5203 if (k->context > prog->context) return 1;
5204 else if (k->context < prog->context) return -1;
5205
5206 if (k->vshader > prog->vshader) return 1;
5207 else if (k->vshader < prog->vshader) return -1;
5208
5209 if (k->pshader > prog->pshader) return 1;
5210 else if (k->pshader < prog->pshader) return -1;
5211
5212 if (k->vshader && (cmp = memcmp(&k->vs_args, &prog->vs_args, sizeof(prog->vs_args)))) return cmp;
5213 if (k->pshader && (cmp = memcmp(&k->ps_args, &prog->ps_args, sizeof(prog->ps_args)))) return cmp;
5214
5215 return 0;
5216}
5217
5218static BOOL constant_heap_init(struct constant_heap *heap, unsigned int constant_count)
5219{
5220#ifndef VBOX
5221 SIZE_T size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5222 void *mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
5223#else
5224 SIZE_T size;
5225 void *mem;
5226
5227 /* Don't trash the heap if the input is bogus. */
5228 if (constant_count == 0)
5229 constant_count = 1;
5230
5231 size = (constant_count + 1) * sizeof(*heap->entries) + constant_count * sizeof(*heap->positions);
5232 mem = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
5233#endif
5234
5235 if (!mem)
5236 {
5237 ERR("Failed to allocate memory\n");
5238 return FALSE;
5239 }
5240
5241 heap->entries = mem;
5242 heap->entries[1].version = 0;
5243 heap->positions = (unsigned int *)(heap->entries + constant_count + 1);
5244 heap->size = 1;
5245
5246 return TRUE;
5247}
5248
5249static void constant_heap_free(struct constant_heap *heap)
5250{
5251 HeapFree(GetProcessHeap(), 0, heap->entries);
5252}
5253
5254static const struct wine_rb_functions wined3d_glsl_program_rb_functions =
5255{
5256 wined3d_rb_alloc,
5257 wined3d_rb_realloc,
5258 wined3d_rb_free,
5259 glsl_program_key_compare,
5260};
5261
5262static HRESULT shader_glsl_alloc(IWineD3DDevice *iface) {
5263 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5264 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5265 struct shader_glsl_priv *priv = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(struct shader_glsl_priv));
5266 SIZE_T stack_size = wined3d_log2i(max(gl_info->limits.glsl_vs_float_constants,
5267 gl_info->limits.glsl_ps_float_constants)) + 1;
5268
5269 if (!shader_buffer_init(&priv->shader_buffer))
5270 {
5271 ERR("Failed to initialize shader buffer.\n");
5272 goto fail;
5273 }
5274
5275 priv->stack = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, stack_size * sizeof(*priv->stack));
5276 if (!priv->stack)
5277 {
5278 ERR("Failed to allocate memory.\n");
5279 goto fail;
5280 }
5281 if (!constant_heap_init(&priv->vconst_heap, gl_info->limits.glsl_vs_float_constants))
5282 {
5283 ERR("Failed to initialize vertex shader constant heap\n");
5284 goto fail;
5285 }
5286 if (!constant_heap_init(&priv->pconst_heap, gl_info->limits.glsl_ps_float_constants))
5287 {
5288 ERR("Failed to initialize pixel shader constant heap\n");
5289 goto fail;
5290 }
5291
5292 if (wine_rb_init(&priv->program_lookup, &wined3d_glsl_program_rb_functions) == -1)
5293 {
5294 ERR("Failed to initialize rbtree.\n");
5295 goto fail;
5296 }
5297
5298 priv->next_constant_version = 1;
5299
5300 This->shader_priv = priv;
5301 return WINED3D_OK;
5302
5303fail:
5304 constant_heap_free(&priv->pconst_heap);
5305 constant_heap_free(&priv->vconst_heap);
5306 HeapFree(GetProcessHeap(), 0, priv->stack);
5307 shader_buffer_free(&priv->shader_buffer);
5308 HeapFree(GetProcessHeap(), 0, priv);
5309 return E_OUTOFMEMORY;
5310}
5311
5312/* Context activation is done by the caller. */
5313static void shader_glsl_free(IWineD3DDevice *iface) {
5314 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
5315 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
5316 struct shader_glsl_priv *priv = This->shader_priv;
5317 int i;
5318
5319 ENTER_GL();
5320 for (i = 0; i < tex_type_count; ++i)
5321 {
5322 if (priv->depth_blt_program[i])
5323 {
5324 GL_EXTCALL(glDeleteObjectARB(priv->depth_blt_program[i]));
5325 }
5326 }
5327 LEAVE_GL();
5328
5329 wine_rb_destroy(&priv->program_lookup, NULL, NULL);
5330 constant_heap_free(&priv->pconst_heap);
5331 constant_heap_free(&priv->vconst_heap);
5332 HeapFree(GetProcessHeap(), 0, priv->stack);
5333 shader_buffer_free(&priv->shader_buffer);
5334
5335 HeapFree(GetProcessHeap(), 0, This->shader_priv);
5336 This->shader_priv = NULL;
5337}
5338
5339static BOOL shader_glsl_dirty_const(IWineD3DDevice *iface) {
5340 /* TODO: GL_EXT_bindable_uniform can be used to share constants across shaders */
5341 return FALSE;
5342}
5343
5344static void shader_glsl_get_caps(const struct wined3d_gl_info *gl_info, struct shader_caps *pCaps)
5345{
5346 /* Nvidia Geforce6/7 or Ati R4xx/R5xx cards with GLSL support, support VS 3.0 but older Nvidia/Ati
5347 * models with GLSL support only support 2.0. In case of nvidia we can detect VS 2.0 support based
5348 * on the version of NV_vertex_program.
5349 * For Ati cards there's no way using glsl (it abstracts the lowlevel info away) and also not
5350 * using ARB_vertex_program. It is safe to assume that when a card supports pixel shader 2.0 it
5351 * supports vertex shader 2.0 too and the way around. We can detect ps2.0 using the maximum number
5352 * of native instructions, so use that here. For more info see the pixel shader versioning code below.
5353 */
5354 if ((gl_info->supported[NV_VERTEX_PROGRAM2] && !gl_info->supported[NV_VERTEX_PROGRAM3])
5355 || gl_info->limits.arb_ps_instructions <= 512
5356 || gl_info->limits.glsl_vs_float_constants < 256)
5357 pCaps->VertexShaderVersion = WINED3DVS_VERSION(2,0);
5358 else
5359 pCaps->VertexShaderVersion = WINED3DVS_VERSION(3,0);
5360 TRACE_(d3d_caps)("Hardware vertex shader version %d.%d enabled (GLSL)\n", (pCaps->VertexShaderVersion >> 8) & 0xff, pCaps->VertexShaderVersion & 0xff);
5361 pCaps->MaxVertexShaderConst = gl_info->limits.glsl_vs_float_constants;
5362
5363 /* Older DX9-class videocards (GeforceFX / Radeon >9500/X*00) only support pixel shader 2.0/2.0a/2.0b.
5364 * In OpenGL the extensions related to GLSL abstract lowlevel GL info away which is needed
5365 * to distinguish between 2.0 and 3.0 (and 2.0a/2.0b). In case of Nvidia we use their fragment
5366 * program extensions. On other hardware including ATI GL_ARB_fragment_program offers the info
5367 * in max native instructions. Intel and others also offer the info in this extension but they
5368 * don't support GLSL (at least on Windows).
5369 *
5370 * PS2.0 requires at least 96 instructions, 2.0a/2.0b go up to 512. Assume that if the number
5371 * of instructions is 512 or less we have to do with ps2.0 hardware.
5372 * NOTE: ps3.0 hardware requires 512 or more instructions but ati and nvidia offer 'enough' (1024 vs 4096) on their most basic ps3.0 hardware.
5373 */
5374 if ((gl_info->supported[NV_FRAGMENT_PROGRAM] && !gl_info->supported[NV_FRAGMENT_PROGRAM2])
5375 || gl_info->limits.arb_ps_instructions <= 512
5376 || gl_info->limits.glsl_vs_float_constants < 256)
5377 pCaps->PixelShaderVersion = WINED3DPS_VERSION(2,0);
5378 else
5379 pCaps->PixelShaderVersion = WINED3DPS_VERSION(3,0);
5380
5381 pCaps->MaxPixelShaderConst = gl_info->limits.glsl_ps_float_constants;
5382
5383 /* FIXME: The following line is card dependent. -8.0 to 8.0 is the
5384 * Direct3D minimum requirement.
5385 *
5386 * Both GL_ARB_fragment_program and GLSL require a "maximum representable magnitude"
5387 * of colors to be 2^10, and 2^32 for other floats. Should we use 1024 here?
5388 *
5389 * The problem is that the refrast clamps temporary results in the shader to
5390 * [-MaxValue;+MaxValue]. If the card's max value is bigger than the one we advertize here,
5391 * then applications may miss the clamping behavior. On the other hand, if it is smaller,
5392 * the shader will generate incorrect results too. Unfortunately, GL deliberately doesn't
5393 * offer a way to query this.
5394 */
5395 pCaps->PixelShader1xMaxValue = 8.0;
5396 TRACE_(d3d_caps)("Hardware pixel shader version %d.%d enabled (GLSL)\n", (pCaps->PixelShaderVersion >> 8) & 0xff, pCaps->PixelShaderVersion & 0xff);
5397
5398 pCaps->VSClipping = TRUE;
5399}
5400
5401static BOOL shader_glsl_color_fixup_supported(struct color_fixup_desc fixup)
5402{
5403 if (TRACE_ON(d3d_shader) && TRACE_ON(d3d))
5404 {
5405 TRACE("Checking support for fixup:\n");
5406 dump_color_fixup_desc(fixup);
5407 }
5408
5409 /* We support everything except YUV conversions. */
5410 if (!is_complex_fixup(fixup))
5411 {
5412 TRACE("[OK]\n");
5413 return TRUE;
5414 }
5415
5416 TRACE("[FAILED]\n");
5417 return FALSE;
5418}
5419
5420static const SHADER_HANDLER shader_glsl_instruction_handler_table[WINED3DSIH_TABLE_SIZE] =
5421{
5422 /* WINED3DSIH_ABS */ shader_glsl_map2gl,
5423 /* WINED3DSIH_ADD */ shader_glsl_arith,
5424 /* WINED3DSIH_BEM */ shader_glsl_bem,
5425 /* WINED3DSIH_BREAK */ shader_glsl_break,
5426 /* WINED3DSIH_BREAKC */ shader_glsl_breakc,
5427 /* WINED3DSIH_BREAKP */ NULL,
5428 /* WINED3DSIH_CALL */ shader_glsl_call,
5429 /* WINED3DSIH_CALLNZ */ shader_glsl_callnz,
5430 /* WINED3DSIH_CMP */ shader_glsl_cmp,
5431 /* WINED3DSIH_CND */ shader_glsl_cnd,
5432 /* WINED3DSIH_CRS */ shader_glsl_cross,
5433 /* WINED3DSIH_CUT */ NULL,
5434 /* WINED3DSIH_DCL */ NULL,
5435 /* WINED3DSIH_DEF */ NULL,
5436 /* WINED3DSIH_DEFB */ NULL,
5437 /* WINED3DSIH_DEFI */ NULL,
5438 /* WINED3DSIH_DP2ADD */ shader_glsl_dp2add,
5439 /* WINED3DSIH_DP3 */ shader_glsl_dot,
5440 /* WINED3DSIH_DP4 */ shader_glsl_dot,
5441 /* WINED3DSIH_DST */ shader_glsl_dst,
5442 /* WINED3DSIH_DSX */ shader_glsl_map2gl,
5443 /* WINED3DSIH_DSY */ shader_glsl_map2gl,
5444 /* WINED3DSIH_ELSE */ shader_glsl_else,
5445 /* WINED3DSIH_EMIT */ NULL,
5446 /* WINED3DSIH_ENDIF */ shader_glsl_end,
5447 /* WINED3DSIH_ENDLOOP */ shader_glsl_end,
5448 /* WINED3DSIH_ENDREP */ shader_glsl_end,
5449 /* WINED3DSIH_EXP */ shader_glsl_map2gl,
5450 /* WINED3DSIH_EXPP */ shader_glsl_expp,
5451 /* WINED3DSIH_FRC */ shader_glsl_map2gl,
5452 /* WINED3DSIH_IADD */ NULL,
5453 /* WINED3DSIH_IF */ shader_glsl_if,
5454 /* WINED3DSIH_IFC */ shader_glsl_ifc,
5455 /* WINED3DSIH_IGE */ NULL,
5456 /* WINED3DSIH_LABEL */ shader_glsl_label,
5457 /* WINED3DSIH_LIT */ shader_glsl_lit,
5458 /* WINED3DSIH_LOG */ shader_glsl_log,
5459 /* WINED3DSIH_LOGP */ shader_glsl_log,
5460 /* WINED3DSIH_LOOP */ shader_glsl_loop,
5461 /* WINED3DSIH_LRP */ shader_glsl_lrp,
5462 /* WINED3DSIH_LT */ NULL,
5463 /* WINED3DSIH_M3x2 */ shader_glsl_mnxn,
5464 /* WINED3DSIH_M3x3 */ shader_glsl_mnxn,
5465 /* WINED3DSIH_M3x4 */ shader_glsl_mnxn,
5466 /* WINED3DSIH_M4x3 */ shader_glsl_mnxn,
5467 /* WINED3DSIH_M4x4 */ shader_glsl_mnxn,
5468 /* WINED3DSIH_MAD */ shader_glsl_mad,
5469 /* WINED3DSIH_MAX */ shader_glsl_map2gl,
5470 /* WINED3DSIH_MIN */ shader_glsl_map2gl,
5471 /* WINED3DSIH_MOV */ shader_glsl_mov,
5472 /* WINED3DSIH_MOVA */ shader_glsl_mov,
5473 /* WINED3DSIH_MUL */ shader_glsl_arith,
5474 /* WINED3DSIH_NOP */ NULL,
5475 /* WINED3DSIH_NRM */ shader_glsl_nrm,
5476 /* WINED3DSIH_PHASE */ NULL,
5477 /* WINED3DSIH_POW */ shader_glsl_pow,
5478 /* WINED3DSIH_RCP */ shader_glsl_rcp,
5479 /* WINED3DSIH_REP */ shader_glsl_rep,
5480 /* WINED3DSIH_RET */ shader_glsl_ret,
5481 /* WINED3DSIH_RSQ */ shader_glsl_rsq,
5482#ifdef VBOX_WITH_VMSVGA
5483 /* WINED3DSIH_SETP */ shader_glsl_setp,
5484#else
5485 /* WINED3DSIH_SETP */ NULL,
5486#endif
5487 /* WINED3DSIH_SGE */ shader_glsl_compare,
5488 /* WINED3DSIH_SGN */ shader_glsl_sgn,
5489 /* WINED3DSIH_SINCOS */ shader_glsl_sincos,
5490 /* WINED3DSIH_SLT */ shader_glsl_compare,
5491 /* WINED3DSIH_SUB */ shader_glsl_arith,
5492 /* WINED3DSIH_TEX */ shader_glsl_tex,
5493 /* WINED3DSIH_TEXBEM */ shader_glsl_texbem,
5494 /* WINED3DSIH_TEXBEML */ shader_glsl_texbem,
5495 /* WINED3DSIH_TEXCOORD */ shader_glsl_texcoord,
5496 /* WINED3DSIH_TEXDEPTH */ shader_glsl_texdepth,
5497 /* WINED3DSIH_TEXDP3 */ shader_glsl_texdp3,
5498 /* WINED3DSIH_TEXDP3TEX */ shader_glsl_texdp3tex,
5499 /* WINED3DSIH_TEXKILL */ shader_glsl_texkill,
5500 /* WINED3DSIH_TEXLDD */ shader_glsl_texldd,
5501 /* WINED3DSIH_TEXLDL */ shader_glsl_texldl,
5502 /* WINED3DSIH_TEXM3x2DEPTH */ shader_glsl_texm3x2depth,
5503 /* WINED3DSIH_TEXM3x2PAD */ shader_glsl_texm3x2pad,
5504 /* WINED3DSIH_TEXM3x2TEX */ shader_glsl_texm3x2tex,
5505 /* WINED3DSIH_TEXM3x3 */ shader_glsl_texm3x3,
5506 /* WINED3DSIH_TEXM3x3DIFF */ NULL,
5507 /* WINED3DSIH_TEXM3x3PAD */ shader_glsl_texm3x3pad,
5508 /* WINED3DSIH_TEXM3x3SPEC */ shader_glsl_texm3x3spec,
5509 /* WINED3DSIH_TEXM3x3TEX */ shader_glsl_texm3x3tex,
5510 /* WINED3DSIH_TEXM3x3VSPEC */ shader_glsl_texm3x3vspec,
5511 /* WINED3DSIH_TEXREG2AR */ shader_glsl_texreg2ar,
5512 /* WINED3DSIH_TEXREG2GB */ shader_glsl_texreg2gb,
5513 /* WINED3DSIH_TEXREG2RGB */ shader_glsl_texreg2rgb,
5514};
5515
5516static void shader_glsl_handle_instruction(const struct wined3d_shader_instruction *ins) {
5517 SHADER_HANDLER hw_fct;
5518
5519 /* Select handler */
5520 hw_fct = shader_glsl_instruction_handler_table[ins->handler_idx];
5521
5522 /* Unhandled opcode */
5523 if (!hw_fct)
5524 {
5525 FIXME("Backend can't handle opcode %#x\n", ins->handler_idx);
5526 return;
5527 }
5528 hw_fct(ins);
5529
5530 shader_glsl_add_instruction_modifiers(ins);
5531}
5532
5533const shader_backend_t glsl_shader_backend = {
5534 shader_glsl_handle_instruction,
5535 shader_glsl_select,
5536 shader_glsl_select_depth_blt,
5537 shader_glsl_deselect_depth_blt,
5538 shader_glsl_update_float_vertex_constants,
5539 shader_glsl_update_float_pixel_constants,
5540 shader_glsl_load_constants,
5541 shader_glsl_load_np2fixup_constants,
5542 shader_glsl_destroy,
5543 shader_glsl_alloc,
5544 shader_glsl_free,
5545 shader_glsl_dirty_const,
5546 shader_glsl_get_caps,
5547 shader_glsl_color_fixup_supported,
5548};
5549
5550#if defined(VBOXWINEDBG_SHADERS) || defined(VBOX_WINE_WITH_PROFILE)
5551void vboxWDbgPrintF(char * szString, ...)
5552{
5553 char szBuffer[4096*2] = {0};
5554 va_list pArgList;
5555 va_start(pArgList, szString);
5556 _vsnprintf(szBuffer, sizeof(szBuffer) / sizeof(szBuffer[0]), szString, pArgList);
5557 va_end(pArgList);
5558
5559 OutputDebugStringA(szBuffer);
5560}
5561#endif
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette