Release 1.5.29.
[wine] / dlls / d3dcompiler_43 / compiler.c
1 /*
2  * Copyright 2009 Matteo Bruni
3  * Copyright 2010 Matteo Bruni for CodeWeavers
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19
20 #define COBJMACROS
21 #include "config.h"
22 #include "wine/port.h"
23 #include "wine/debug.h"
24 #include "wine/unicode.h"
25
26 #include "d3dcompiler_private.h"
27 #include "wine/wpp.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(d3dcompiler);
30
31 #define D3DXERR_INVALIDDATA                      0x88760b59
32
33 #define BUFFER_INITIAL_CAPACITY 256
34
35 struct mem_file_desc
36 {
37     const char *buffer;
38     unsigned int size;
39     unsigned int pos;
40 };
41
42 static struct mem_file_desc current_shader;
43 static ID3DInclude *current_include;
44 static const char *initial_filename;
45
46 #define INCLUDES_INITIAL_CAPACITY 4
47
48 struct loaded_include
49 {
50     const char *name;
51     const char *data;
52 };
53
54 static struct loaded_include *includes;
55 static int includes_capacity, includes_size;
56 static const char *parent_include;
57
58 static char *wpp_output;
59 static int wpp_output_capacity, wpp_output_size;
60
61 static char *wpp_messages;
62 static int wpp_messages_capacity, wpp_messages_size;
63
64 /* Mutex used to guarantee a single invocation
65    of the D3DXAssembleShader function (or its variants) at a time.
66    This is needed as wpp isn't thread-safe */
67 static CRITICAL_SECTION wpp_mutex;
68 static CRITICAL_SECTION_DEBUG wpp_mutex_debug =
69 {
70     0, 0, &wpp_mutex,
71     { &wpp_mutex_debug.ProcessLocksList,
72       &wpp_mutex_debug.ProcessLocksList },
73       0, 0, { (DWORD_PTR)(__FILE__ ": wpp_mutex") }
74 };
75 static CRITICAL_SECTION wpp_mutex = { &wpp_mutex_debug, -1, 0, 0, 0, 0 };
76
77 /* Preprocessor error reporting functions */
78 static void wpp_write_message(const char *fmt, va_list args)
79 {
80     char* newbuffer;
81     int rc, newsize;
82
83     if(wpp_messages_capacity == 0)
84     {
85         wpp_messages = HeapAlloc(GetProcessHeap(), 0, MESSAGEBUFFER_INITIAL_SIZE);
86         if(wpp_messages == NULL)
87             return;
88
89         wpp_messages_capacity = MESSAGEBUFFER_INITIAL_SIZE;
90     }
91
92     while(1)
93     {
94         rc = vsnprintf(wpp_messages + wpp_messages_size,
95                        wpp_messages_capacity - wpp_messages_size, fmt, args);
96
97         if (rc < 0 ||                                           /* C89 */
98             rc >= wpp_messages_capacity - wpp_messages_size) {  /* C99 */
99             /* Resize the buffer */
100             newsize = wpp_messages_capacity * 2;
101             newbuffer = HeapReAlloc(GetProcessHeap(), 0, wpp_messages, newsize);
102             if(newbuffer == NULL)
103             {
104                 ERR("Error reallocating memory for parser messages\n");
105                 return;
106             }
107             wpp_messages = newbuffer;
108             wpp_messages_capacity = newsize;
109         }
110         else
111         {
112             wpp_messages_size += rc;
113             return;
114         }
115     }
116 }
117
118 static void PRINTF_ATTR(1,2) wpp_write_message_var(const char *fmt, ...)
119 {
120     va_list args;
121
122     va_start(args, fmt);
123     wpp_write_message(fmt, args);
124     va_end(args);
125 }
126
127 static void wpp_error(const char *file, int line, int col, const char *near,
128                       const char *msg, va_list ap)
129 {
130     wpp_write_message_var("%s:%d:%d: %s: ", file ? file : "'main file'",
131                           line, col, "Error");
132     wpp_write_message(msg, ap);
133     wpp_write_message_var("\n");
134 }
135
136 static void wpp_warning(const char *file, int line, int col, const char *near,
137                         const char *msg, va_list ap)
138 {
139     wpp_write_message_var("%s:%d:%d: %s: ", file ? file : "'main file'",
140                           line, col, "Warning");
141     wpp_write_message(msg, ap);
142     wpp_write_message_var("\n");
143 }
144
145 static char *wpp_lookup_mem(const char *filename, int type, const char *parent_name,
146                             char **include_path, int include_path_count)
147 {
148     /* Here we return always ok. We will maybe fail on the next wpp_open_mem */
149     char *path;
150     int i;
151
152     parent_include = NULL;
153     if(parent_name[0] != '\0')
154     {
155         for(i = 0; i < includes_size; i++)
156         {
157             if(!strcmp(parent_name, includes[i].name))
158             {
159                 parent_include = includes[i].data;
160                 break;
161             }
162         }
163         if(parent_include == NULL)
164         {
165             ERR("Parent include file missing\n");
166             return NULL;
167         }
168     }
169
170     path = malloc(strlen(filename) + 1);
171     if(path)
172         memcpy(path, filename, strlen(filename) + 1);
173     return path;
174 }
175
176 static void *wpp_open_mem(const char *filename, int type)
177 {
178     struct mem_file_desc *desc;
179     HRESULT hr;
180
181     if(!strcmp(filename, initial_filename))
182     {
183         current_shader.pos = 0;
184         return &current_shader;
185     }
186
187     if(current_include == NULL) return NULL;
188     desc = HeapAlloc(GetProcessHeap(), 0, sizeof(*desc));
189     if(!desc)
190         return NULL;
191
192     hr = ID3DInclude_Open(current_include,
193                           type ? D3D_INCLUDE_LOCAL : D3D_INCLUDE_SYSTEM,
194                           filename, parent_include, (LPCVOID *)&desc->buffer,
195                           &desc->size);
196     if(FAILED(hr))
197     {
198         HeapFree(GetProcessHeap(), 0, desc);
199         return NULL;
200     }
201
202     if(includes_capacity == includes_size)
203     {
204         if(includes_capacity == 0)
205         {
206             includes = HeapAlloc(GetProcessHeap(), 0, INCLUDES_INITIAL_CAPACITY * sizeof(*includes));
207             if(includes == NULL)
208             {
209                 ERR("Error allocating memory for the loaded includes structure\n");
210                 goto error;
211             }
212             includes_capacity = INCLUDES_INITIAL_CAPACITY * sizeof(*includes);
213         }
214         else
215         {
216             int newcapacity = includes_capacity * 2;
217             struct loaded_include *newincludes =
218                 HeapReAlloc(GetProcessHeap(), 0, includes, newcapacity);
219             if(newincludes == NULL)
220             {
221                 ERR("Error reallocating memory for the loaded includes structure\n");
222                 goto error;
223             }
224             includes = newincludes;
225             includes_capacity = newcapacity;
226         }
227     }
228     includes[includes_size].name = filename;
229     includes[includes_size++].data = desc->buffer;
230
231     desc->pos = 0;
232     return desc;
233
234 error:
235     ID3DInclude_Close(current_include, desc->buffer);
236     HeapFree(GetProcessHeap(), 0, desc);
237     return NULL;
238 }
239
240 static void wpp_close_mem(void *file)
241 {
242     struct mem_file_desc *desc = file;
243
244     if(desc != &current_shader)
245     {
246         if(current_include)
247             ID3DInclude_Close(current_include, desc->buffer);
248         else
249             ERR("current_include == NULL, desc == %p, buffer = %s\n",
250                 desc, desc->buffer);
251
252         HeapFree(GetProcessHeap(), 0, desc);
253     }
254 }
255
256 static int wpp_read_mem(void *file, char *buffer, unsigned int len)
257 {
258     struct mem_file_desc *desc = file;
259
260     len = min(len, desc->size - desc->pos);
261     memcpy(buffer, desc->buffer + desc->pos, len);
262     desc->pos += len;
263     return len;
264 }
265
266 static void wpp_write_mem(const char *buffer, unsigned int len)
267 {
268     char *new_wpp_output;
269
270     if(wpp_output_capacity == 0)
271     {
272         wpp_output = HeapAlloc(GetProcessHeap(), 0, BUFFER_INITIAL_CAPACITY);
273         if(!wpp_output)
274             return;
275
276         wpp_output_capacity = BUFFER_INITIAL_CAPACITY;
277     }
278     if(len > wpp_output_capacity - wpp_output_size)
279     {
280         while(len > wpp_output_capacity - wpp_output_size)
281         {
282             wpp_output_capacity *= 2;
283         }
284         new_wpp_output = HeapReAlloc(GetProcessHeap(), 0, wpp_output,
285                                      wpp_output_capacity);
286         if(!new_wpp_output)
287         {
288             ERR("Error allocating memory\n");
289             return;
290         }
291         wpp_output = new_wpp_output;
292     }
293     memcpy(wpp_output + wpp_output_size, buffer, len);
294     wpp_output_size += len;
295 }
296
297 static int wpp_close_output(void)
298 {
299     char *new_wpp_output = HeapReAlloc(GetProcessHeap(), 0, wpp_output,
300                                        wpp_output_size + 1);
301     if(!new_wpp_output) return 0;
302     wpp_output = new_wpp_output;
303     wpp_output[wpp_output_size]='\0';
304     wpp_output_size++;
305     return 1;
306 }
307
308 static HRESULT preprocess_shader(const void *data, SIZE_T data_size, const char *filename,
309         const D3D_SHADER_MACRO *defines, ID3DInclude *include, ID3DBlob **error_messages)
310 {
311     int ret;
312     HRESULT hr = S_OK;
313     const D3D_SHADER_MACRO *def = defines;
314
315     static const struct wpp_callbacks wpp_callbacks =
316     {
317         wpp_lookup_mem,
318         wpp_open_mem,
319         wpp_close_mem,
320         wpp_read_mem,
321         wpp_write_mem,
322         wpp_error,
323         wpp_warning,
324     };
325
326     if (def != NULL)
327     {
328         while (def->Name != NULL)
329         {
330             wpp_add_define(def->Name, def->Definition);
331             def++;
332         }
333     }
334     current_include = include;
335     includes_size = 0;
336
337     wpp_output_size = wpp_output_capacity = 0;
338     wpp_output = NULL;
339
340     wpp_set_callbacks(&wpp_callbacks);
341     wpp_messages_size = wpp_messages_capacity = 0;
342     wpp_messages = NULL;
343     current_shader.buffer = data;
344     current_shader.size = data_size;
345     initial_filename = filename ? filename : "";
346
347     ret = wpp_parse(initial_filename, NULL);
348     if (!wpp_close_output())
349         ret = 1;
350     if (ret)
351     {
352         TRACE("Error during shader preprocessing\n");
353         if (wpp_messages)
354         {
355             int size;
356             ID3DBlob *buffer;
357
358             TRACE("Preprocessor messages:\n%s\n", debugstr_a(wpp_messages));
359
360             if (error_messages)
361             {
362                 size = strlen(wpp_messages) + 1;
363                 hr = D3DCreateBlob(size, &buffer);
364                 if (FAILED(hr))
365                     goto cleanup;
366                 CopyMemory(ID3D10Blob_GetBufferPointer(buffer), wpp_messages, size);
367                 *error_messages = buffer;
368             }
369         }
370         if (data)
371             TRACE("Shader source:\n%s\n", debugstr_an(data, data_size));
372         hr = E_FAIL;
373     }
374
375 cleanup:
376     /* Remove the previously added defines */
377     if (defines != NULL)
378     {
379         while (defines->Name != NULL)
380         {
381             wpp_del_define(defines->Name);
382             defines++;
383         }
384     }
385     HeapFree(GetProcessHeap(), 0, wpp_messages);
386     return hr;
387 }
388
389 static HRESULT assemble_shader(const char *preproc_shader,
390         ID3DBlob **shader_blob, ID3DBlob **error_messages)
391 {
392     struct bwriter_shader *shader;
393     char *messages = NULL;
394     HRESULT hr;
395     DWORD *res, size;
396     ID3DBlob *buffer;
397     char *pos;
398
399     shader = SlAssembleShader(preproc_shader, &messages);
400
401     if (messages)
402     {
403         TRACE("Assembler messages:\n");
404         TRACE("%s\n", debugstr_a(messages));
405
406         TRACE("Shader source:\n");
407         TRACE("%s\n", debugstr_a(preproc_shader));
408
409         if (error_messages)
410         {
411             const char *preproc_messages = *error_messages ? ID3D10Blob_GetBufferPointer(*error_messages) : NULL;
412
413             size = strlen(messages) + (preproc_messages ? strlen(preproc_messages) : 0) + 1;
414             hr = D3DCreateBlob(size, &buffer);
415             if (FAILED(hr))
416             {
417                 HeapFree(GetProcessHeap(), 0, messages);
418                 if (shader) SlDeleteShader(shader);
419                 return hr;
420             }
421             pos = ID3D10Blob_GetBufferPointer(buffer);
422             if (preproc_messages)
423             {
424                 CopyMemory(pos, preproc_messages, strlen(preproc_messages) + 1);
425                 pos += strlen(preproc_messages);
426             }
427             CopyMemory(pos, messages, strlen(messages) + 1);
428
429             if (*error_messages) ID3D10Blob_Release(*error_messages);
430             *error_messages = buffer;
431         }
432         HeapFree(GetProcessHeap(), 0, messages);
433     }
434
435     if (shader == NULL)
436     {
437         ERR("Asm reading failed\n");
438         return D3DXERR_INVALIDDATA;
439     }
440
441     hr = SlWriteBytecode(shader, 9, &res, &size);
442     SlDeleteShader(shader);
443     if (FAILED(hr))
444     {
445         ERR("SlWriteBytecode failed with 0x%08x\n", hr);
446         return D3DXERR_INVALIDDATA;
447     }
448
449     if (shader_blob)
450     {
451         hr = D3DCreateBlob(size, &buffer);
452         if (FAILED(hr))
453         {
454             HeapFree(GetProcessHeap(), 0, res);
455             return hr;
456         }
457         CopyMemory(ID3D10Blob_GetBufferPointer(buffer), res, size);
458         *shader_blob = buffer;
459     }
460
461     HeapFree(GetProcessHeap(), 0, res);
462
463     return S_OK;
464 }
465
466 HRESULT WINAPI D3DAssemble(const void *data, SIZE_T datasize, const char *filename,
467         const D3D_SHADER_MACRO *defines, ID3DInclude *include, UINT flags,
468         ID3DBlob **shader, ID3DBlob **error_messages)
469 {
470     HRESULT hr;
471
472     TRACE("data %p, datasize %lu, filename %s, defines %p, include %p, sflags %#x,\n"
473             "shader %p, error_messages %p\n",
474             data, datasize, debugstr_a(filename), defines, include, flags, shader, error_messages);
475
476     EnterCriticalSection(&wpp_mutex);
477
478     /* TODO: flags */
479     if (flags) FIXME("flags %x\n", flags);
480
481     if (shader) *shader = NULL;
482     if (error_messages) *error_messages = NULL;
483
484     hr = preprocess_shader(data, datasize, filename, defines, include, error_messages);
485     if (SUCCEEDED(hr))
486         hr = assemble_shader(wpp_output, shader, error_messages);
487
488     HeapFree(GetProcessHeap(), 0, wpp_output);
489     LeaveCriticalSection(&wpp_mutex);
490     return hr;
491 }
492
493 static HRESULT compile_shader(const char *preproc_shader, const char *target, const char *entrypoint,
494         ID3DBlob **shader_blob, ID3DBlob **error_messages)
495 {
496     struct bwriter_shader *shader;
497     char *messages = NULL;
498     HRESULT hr;
499     DWORD *res, size, major, minor;
500     ID3DBlob *buffer;
501     char *pos;
502     enum shader_type shader_type;
503
504     TRACE("Preprocessed shader source: %s\n", debugstr_a(preproc_shader));
505
506     TRACE("Parsing compilation target %s.\n", debugstr_a(target));
507     if (strlen(target) != 6 || target[1] != 's' || target[2] != '_' || target[4] != '_')
508     {
509         FIXME("Unknown compilation target %s.\n", debugstr_a(target));
510         return D3DERR_INVALIDCALL;
511     }
512
513     if (target[0] == 'v')
514         shader_type = ST_VERTEX;
515     else if (target[0] == 'p')
516         shader_type = ST_PIXEL;
517     else
518     {
519         FIXME("Unsupported shader target type %s.\n", debugstr_a(target));
520         return D3DERR_INVALIDCALL;
521     }
522
523     major = target[3] - '0';
524     if (major == 0 || major > 5)
525     {
526         FIXME("Unsupported shader target major version %d.\n", major);
527         return D3DERR_INVALIDCALL;
528     }
529     minor = target[5] - '0';
530     if (minor > 1 || (minor == 1 && (shader_type != ST_VERTEX || major > 1)))
531     {
532         FIXME("Unsupported shader target minor version %d.\n", minor);
533         return D3DERR_INVALIDCALL;
534     }
535     shader = parse_hlsl_shader(preproc_shader, shader_type, major, minor, entrypoint, &messages);
536
537     if (messages)
538     {
539         TRACE("Compiler messages:\n");
540         TRACE("%s\n", debugstr_a(messages));
541
542         TRACE("Shader source:\n");
543         TRACE("%s\n", debugstr_a(preproc_shader));
544
545         if (error_messages)
546         {
547             const char *preproc_messages = *error_messages ? ID3D10Blob_GetBufferPointer(*error_messages) : NULL;
548
549             size = strlen(messages) + (preproc_messages ? strlen(preproc_messages) : 0) + 1;
550             hr = D3DCreateBlob(size, &buffer);
551             if (FAILED(hr))
552             {
553                 HeapFree(GetProcessHeap(), 0, messages);
554                 if (shader) SlDeleteShader(shader);
555                 return hr;
556             }
557             pos = ID3D10Blob_GetBufferPointer(buffer);
558             if (preproc_messages)
559             {
560                 memcpy(pos, preproc_messages, strlen(preproc_messages) + 1);
561                 pos += strlen(preproc_messages);
562             }
563             memcpy(pos, messages, strlen(messages) + 1);
564
565             if (*error_messages) ID3D10Blob_Release(*error_messages);
566             *error_messages = buffer;
567         }
568         HeapFree(GetProcessHeap(), 0, messages);
569     }
570
571     if (!shader)
572     {
573         ERR("HLSL shader parsing failed.\n");
574         return D3DXERR_INVALIDDATA;
575     }
576
577     hr = SlWriteBytecode(shader, 9, &res, &size);
578     SlDeleteShader(shader);
579     if (FAILED(hr))
580     {
581         ERR("SlWriteBytecode failed with error 0x%08x.\n", hr);
582         return D3DXERR_INVALIDDATA;
583     }
584
585     if (shader_blob)
586     {
587         hr = D3DCreateBlob(size, &buffer);
588         if (FAILED(hr))
589         {
590             HeapFree(GetProcessHeap(), 0, res);
591             return hr;
592         }
593         memcpy(ID3D10Blob_GetBufferPointer(buffer), res, size);
594         *shader_blob = buffer;
595     }
596
597     HeapFree(GetProcessHeap(), 0, res);
598
599     return S_OK;
600 }
601
602 HRESULT WINAPI D3DCompile(const void *data, SIZE_T data_size, const char *filename,
603         const D3D_SHADER_MACRO *defines, ID3DInclude *include, const char *entrypoint,
604         const char *target, UINT sflags, UINT eflags, ID3DBlob **shader, ID3DBlob **error_messages)
605 {
606     HRESULT hr;
607
608     TRACE("data %p, data_size %lu, filename %s, defines %p, include %p, entrypoint %s,\n"
609             "target %s, sflags %#x, eflags %#x, shader %p, error_messages %p\n",
610             data, data_size, debugstr_a(filename), defines, include, debugstr_a(entrypoint),
611             debugstr_a(target), sflags, eflags, shader, error_messages);
612
613     if (shader) *shader = NULL;
614     if (error_messages) *error_messages = NULL;
615
616     EnterCriticalSection(&wpp_mutex);
617
618     hr = preprocess_shader(data, data_size, filename, defines, include, error_messages);
619     if (SUCCEEDED(hr))
620         hr = compile_shader(wpp_output, target, entrypoint, shader, error_messages);
621
622     HeapFree(GetProcessHeap(), 0, wpp_output);
623     LeaveCriticalSection(&wpp_mutex);
624     return hr;
625 }
626
627 HRESULT WINAPI D3DPreprocess(const void *data, SIZE_T size, const char *filename,
628         const D3D_SHADER_MACRO *defines, ID3DInclude *include,
629         ID3DBlob **shader, ID3DBlob **error_messages)
630 {
631     HRESULT hr;
632     ID3DBlob *buffer;
633
634     if (!data)
635         return E_INVALIDARG;
636
637     EnterCriticalSection(&wpp_mutex);
638
639     if (shader) *shader = NULL;
640     if (error_messages) *error_messages = NULL;
641
642     hr = preprocess_shader(data, size, filename, defines, include, error_messages);
643
644     if (SUCCEEDED(hr))
645     {
646         if (shader)
647         {
648             hr = D3DCreateBlob(wpp_output_size, &buffer);
649             if (FAILED(hr))
650                 goto cleanup;
651             CopyMemory(ID3D10Blob_GetBufferPointer(buffer), wpp_output, wpp_output_size);
652             *shader = buffer;
653         }
654         else
655             hr = E_INVALIDARG;
656     }
657
658 cleanup:
659     HeapFree(GetProcessHeap(), 0, wpp_output);
660     LeaveCriticalSection(&wpp_mutex);
661     return hr;
662 }
663
664 HRESULT WINAPI D3DDisassemble(const void *data, SIZE_T size, UINT flags, const char *comments, ID3DBlob **disassembly)
665 {
666     FIXME("data %p, size %lu, flags %#x, comments %p, disassembly %p stub!\n",
667             data, size, flags, comments, disassembly);
668     return E_NOTIMPL;
669 }