Merge branch 'blender2.7'
[blender.git] / source / blender / gpu / intern / gpu_codegen.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2005 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup gpu
22  *
23  * Convert material node-trees to GLSL.
24  */
25
26 #include "MEM_guardedalloc.h"
27
28 #include "DNA_customdata_types.h"
29 #include "DNA_image_types.h"
30 #include "DNA_material_types.h"
31 #include "DNA_node_types.h"
32
33 #include "BLI_blenlib.h"
34 #include "BLI_hash_mm2a.h"
35 #include "BLI_link_utils.h"
36 #include "BLI_utildefines.h"
37 #include "BLI_dynstr.h"
38 #include "BLI_ghash.h"
39 #include "BLI_threads.h"
40
41 #include "PIL_time.h"
42
43 #include "GPU_extensions.h"
44 #include "GPU_glew.h"
45 #include "GPU_material.h"
46 #include "GPU_shader.h"
47 #include "GPU_texture.h"
48 #include "GPU_uniformbuffer.h"
49
50 #include "BLI_sys_types.h" /* for intptr_t support */
51
52 #include "gpu_codegen.h"
53
54 #include <string.h>
55 #include <stdarg.h>
56
57 extern char datatoc_gpu_shader_material_glsl[];
58 extern char datatoc_gpu_shader_geometry_glsl[];
59
60 static char *glsl_material_library = NULL;
61
62 /* -------------------- GPUPass Cache ------------------ */
63 /**
64  * Internal shader cache: This prevent the shader recompilation / stall when
65  * using undo/redo AND also allows for GPUPass reuse if the Shader code is the
66  * same for 2 different Materials. Unused GPUPasses are free by Garbage collection.
67  */
68
69 /* Only use one linklist that contains the GPUPasses grouped by hash. */
70 static GPUPass *pass_cache = NULL;
71 static SpinLock pass_cache_spin;
72
73 static uint32_t gpu_pass_hash(const char *frag_gen, const char *defs, GPUVertAttrLayers *attrs)
74 {
75         BLI_HashMurmur2A hm2a;
76         BLI_hash_mm2a_init(&hm2a, 0);
77         BLI_hash_mm2a_add(&hm2a, (uchar *)frag_gen, strlen(frag_gen));
78         if (attrs) {
79                 for (int att_idx = 0; att_idx < attrs->totlayer; att_idx++) {
80                         char *name = attrs->layer[att_idx].name;
81                         BLI_hash_mm2a_add(&hm2a, (uchar *)name, strlen(name));
82                 }
83         }
84         if (defs)
85                 BLI_hash_mm2a_add(&hm2a, (uchar *)defs, strlen(defs));
86
87         return BLI_hash_mm2a_end(&hm2a);
88 }
89
90 /* Search by hash only. Return first pass with the same hash.
91  * There is hash collision if (pass->next && pass->next->hash == hash) */
92 static GPUPass *gpu_pass_cache_lookup(uint32_t hash)
93 {
94         BLI_spin_lock(&pass_cache_spin);
95         /* Could be optimized with a Lookup table. */
96         for (GPUPass *pass = pass_cache; pass; pass = pass->next) {
97                 if (pass->hash == hash) {
98                         BLI_spin_unlock(&pass_cache_spin);
99                         return pass;
100                 }
101         }
102         BLI_spin_unlock(&pass_cache_spin);
103         return NULL;
104 }
105
106 /* Check all possible passes with the same hash. */
107 static GPUPass *gpu_pass_cache_resolve_collision(
108         GPUPass *pass, const char *vert, const char *geom, const char *frag, const char *defs, uint32_t hash)
109 {
110         BLI_spin_lock(&pass_cache_spin);
111         /* Collision, need to strcmp the whole shader. */
112         for (; pass && (pass->hash == hash); pass = pass->next) {
113                 if ((defs != NULL) && (strcmp(pass->defines, defs) != 0)) { /* Pass */ }
114                 else if ((geom != NULL) && (strcmp(pass->geometrycode, geom) != 0)) { /* Pass */ }
115                 else if ((strcmp(pass->fragmentcode, frag) == 0) &&
116                          (strcmp(pass->vertexcode, vert) == 0))
117                 {
118                         BLI_spin_unlock(&pass_cache_spin);
119                         return pass;
120                 }
121         }
122         BLI_spin_unlock(&pass_cache_spin);
123         return NULL;
124 }
125
126 /* -------------------- GPU Codegen ------------------ */
127
128 /* type definitions and constants */
129
130 #define MAX_FUNCTION_NAME    64
131 #define MAX_PARAMETER        32
132
133 typedef enum {
134         FUNCTION_QUAL_IN,
135         FUNCTION_QUAL_OUT,
136         FUNCTION_QUAL_INOUT
137 } GPUFunctionQual;
138
139 typedef struct GPUFunction {
140         char name[MAX_FUNCTION_NAME];
141         eGPUType paramtype[MAX_PARAMETER];
142         GPUFunctionQual paramqual[MAX_PARAMETER];
143         int totparam;
144 } GPUFunction;
145
146 /* Indices match the eGPUType enum */
147 static const char *GPU_DATATYPE_STR[17] = {
148         "", "float", "vec2", "vec3", "vec4",
149         NULL, NULL, NULL, NULL, "mat3", NULL, NULL, NULL, NULL, NULL, NULL, "mat4",
150 };
151
152 /* GLSL code parsing for finding function definitions.
153  * These are stored in a hash for lookup when creating a material. */
154
155 static GHash *FUNCTION_HASH = NULL;
156 #if 0
157 static char *FUNCTION_PROTOTYPES = NULL;
158 static GPUShader *FUNCTION_LIB = NULL;
159 #endif
160
161 static int gpu_str_prefix(const char *str, const char *prefix)
162 {
163         while (*str && *prefix) {
164                 if (*str != *prefix)
165                         return 0;
166
167                 str++;
168                 prefix++;
169         }
170
171         return (*prefix == '\0');
172 }
173
174 static char *gpu_str_skip_token(char *str, char *token, int max)
175 {
176         int len = 0;
177
178         /* skip a variable/function name */
179         while (*str) {
180                 if (ELEM(*str, ' ', '(', ')', ',', ';', '\t', '\n', '\r'))
181                         break;
182                 else {
183                         if (token && len < max - 1) {
184                                 *token = *str;
185                                 token++;
186                                 len++;
187                         }
188                         str++;
189                 }
190         }
191
192         if (token)
193                 *token = '\0';
194
195         /* skip the next special characters:
196          * note the missing ')' */
197         while (*str) {
198                 if (ELEM(*str, ' ', '(', ',', ';', '\t', '\n', '\r'))
199                         str++;
200                 else
201                         break;
202         }
203
204         return str;
205 }
206
207 static void gpu_parse_functions_string(GHash *hash, char *code)
208 {
209         GPUFunction *function;
210         eGPUType type;
211         GPUFunctionQual qual;
212         int i;
213
214         while ((code = strstr(code, "void "))) {
215                 function = MEM_callocN(sizeof(GPUFunction), "GPUFunction");
216
217                 code = gpu_str_skip_token(code, NULL, 0);
218                 code = gpu_str_skip_token(code, function->name, MAX_FUNCTION_NAME);
219
220                 /* get parameters */
221                 while (*code && *code != ')') {
222                         /* test if it's an input or output */
223                         qual = FUNCTION_QUAL_IN;
224                         if (gpu_str_prefix(code, "out "))
225                                 qual = FUNCTION_QUAL_OUT;
226                         if (gpu_str_prefix(code, "inout "))
227                                 qual = FUNCTION_QUAL_INOUT;
228                         if ((qual != FUNCTION_QUAL_IN) || gpu_str_prefix(code, "in "))
229                                 code = gpu_str_skip_token(code, NULL, 0);
230
231                         /* test for type */
232                         type = GPU_NONE;
233                         for (i = 1; i < ARRAY_SIZE(GPU_DATATYPE_STR); i++) {
234                                 if (GPU_DATATYPE_STR[i] && gpu_str_prefix(code, GPU_DATATYPE_STR[i])) {
235                                         type = i;
236                                         break;
237                                 }
238                         }
239
240                         if (!type && gpu_str_prefix(code, "samplerCube")) {
241                                 type = GPU_TEXCUBE;
242                         }
243                         if (!type && gpu_str_prefix(code, "sampler2DShadow")) {
244                                 type = GPU_SHADOW2D;
245                         }
246                         if (!type && gpu_str_prefix(code, "sampler1DArray")) {
247                                 type = GPU_TEX1D_ARRAY;
248                         }
249                         if (!type && gpu_str_prefix(code, "sampler2D")) {
250                                 type = GPU_TEX2D;
251                         }
252                         if (!type && gpu_str_prefix(code, "sampler3D")) {
253                                 type = GPU_TEX3D;
254                         }
255
256                         if (!type && gpu_str_prefix(code, "Closure")) {
257                                 type = GPU_CLOSURE;
258                         }
259
260                         if (type) {
261                                 /* add parameter */
262                                 code = gpu_str_skip_token(code, NULL, 0);
263                                 code = gpu_str_skip_token(code, NULL, 0);
264                                 function->paramqual[function->totparam] = qual;
265                                 function->paramtype[function->totparam] = type;
266                                 function->totparam++;
267                         }
268                         else {
269                                 fprintf(stderr, "GPU invalid function parameter in %s.\n", function->name);
270                                 break;
271                         }
272                 }
273
274                 if (function->name[0] == '\0' || function->totparam == 0) {
275                         fprintf(stderr, "GPU functions parse error.\n");
276                         MEM_freeN(function);
277                         break;
278                 }
279
280                 BLI_ghash_insert(hash, function->name, function);
281         }
282 }
283
284 #if 0
285 static char *gpu_generate_function_prototyps(GHash *hash)
286 {
287         DynStr *ds = BLI_dynstr_new();
288         GHashIterator *ghi;
289         GPUFunction *function;
290         char *name, *prototypes;
291         int a;
292
293         /* automatically generate function prototypes to add to the top of the
294          * generated code, to avoid have to add the actual code & recompile all */
295         ghi = BLI_ghashIterator_new(hash);
296
297         for (; !BLI_ghashIterator_done(ghi); BLI_ghashIterator_step(ghi)) {
298                 name = BLI_ghashIterator_getValue(ghi);
299                 function = BLI_ghashIterator_getValue(ghi);
300
301                 BLI_dynstr_appendf(ds, "void %s(", name);
302                 for (a = 0; a < function->totparam; a++) {
303                         if (function->paramqual[a] == FUNCTION_QUAL_OUT)
304                                 BLI_dynstr_append(ds, "out ");
305                         else if (function->paramqual[a] == FUNCTION_QUAL_INOUT)
306                                 BLI_dynstr_append(ds, "inout ");
307
308                         if (function->paramtype[a] == GPU_TEX2D)
309                                 BLI_dynstr_append(ds, "sampler2D");
310                         else if (function->paramtype[a] == GPU_SHADOW2D)
311                                 BLI_dynstr_append(ds, "sampler2DShadow");
312                         else
313                                 BLI_dynstr_append(ds, GPU_DATATYPE_STR[function->paramtype[a]]);
314 #  if 0
315                         BLI_dynstr_appendf(ds, " param%d", a);
316 #  endif
317
318                         if (a != function->totparam - 1)
319                                 BLI_dynstr_append(ds, ", ");
320                 }
321                 BLI_dynstr_append(ds, ");\n");
322         }
323
324         BLI_dynstr_append(ds, "\n");
325
326         prototypes = BLI_dynstr_get_cstring(ds);
327         BLI_dynstr_free(ds);
328
329         return prototypes;
330 }
331 #endif
332
333 static GPUFunction *gpu_lookup_function(const char *name)
334 {
335         if (!FUNCTION_HASH) {
336                 FUNCTION_HASH = BLI_ghash_str_new("GPU_lookup_function gh");
337                 gpu_parse_functions_string(FUNCTION_HASH, glsl_material_library);
338         }
339
340         return BLI_ghash_lookup(FUNCTION_HASH, (const void *)name);
341 }
342
343 void gpu_codegen_init(void)
344 {
345         GPU_code_generate_glsl_lib();
346 }
347
348 void gpu_codegen_exit(void)
349 {
350         extern Material defmaterial; /* render module abuse... */
351
352         if (defmaterial.gpumaterial.first)
353                 GPU_material_free(&defmaterial.gpumaterial);
354
355         if (FUNCTION_HASH) {
356                 BLI_ghash_free(FUNCTION_HASH, NULL, MEM_freeN);
357                 FUNCTION_HASH = NULL;
358         }
359
360         GPU_shader_free_builtin_shaders();
361
362         if (glsl_material_library) {
363                 MEM_freeN(glsl_material_library);
364                 glsl_material_library = NULL;
365         }
366
367 #if 0
368         if (FUNCTION_PROTOTYPES) {
369                 MEM_freeN(FUNCTION_PROTOTYPES);
370                 FUNCTION_PROTOTYPES = NULL;
371         }
372         if (FUNCTION_LIB) {
373                 GPU_shader_free(FUNCTION_LIB);
374                 FUNCTION_LIB = NULL;
375         }
376 #endif
377 }
378
379 /* GLSL code generation */
380
381 static void codegen_convert_datatype(DynStr *ds, int from, int to, const char *tmp, int id)
382 {
383         char name[1024];
384
385         BLI_snprintf(name, sizeof(name), "%s%d", tmp, id);
386
387         if (from == to) {
388                 BLI_dynstr_append(ds, name);
389         }
390         else if (to == GPU_FLOAT) {
391                 if (from == GPU_VEC4)
392                         BLI_dynstr_appendf(ds, "convert_rgba_to_float(%s)", name);
393                 else if (from == GPU_VEC3)
394                         BLI_dynstr_appendf(ds, "(%s.r + %s.g + %s.b) / 3.0", name, name, name);
395                 else if (from == GPU_VEC2)
396                         BLI_dynstr_appendf(ds, "%s.r", name);
397         }
398         else if (to == GPU_VEC2) {
399                 if (from == GPU_VEC4)
400                         BLI_dynstr_appendf(ds, "vec2((%s.r + %s.g + %s.b) / 3.0, %s.a)", name, name, name, name);
401                 else if (from == GPU_VEC3)
402                         BLI_dynstr_appendf(ds, "vec2((%s.r + %s.g + %s.b) / 3.0, 1.0)", name, name, name);
403                 else if (from == GPU_FLOAT)
404                         BLI_dynstr_appendf(ds, "vec2(%s, 1.0)", name);
405         }
406         else if (to == GPU_VEC3) {
407                 if (from == GPU_VEC4)
408                         BLI_dynstr_appendf(ds, "%s.rgb", name);
409                 else if (from == GPU_VEC2)
410                         BLI_dynstr_appendf(ds, "vec3(%s.r, %s.r, %s.r)", name, name, name);
411                 else if (from == GPU_FLOAT)
412                         BLI_dynstr_appendf(ds, "vec3(%s, %s, %s)", name, name, name);
413         }
414         else if (to == GPU_VEC4) {
415                 if (from == GPU_VEC3)
416                         BLI_dynstr_appendf(ds, "vec4(%s, 1.0)", name);
417                 else if (from == GPU_VEC2)
418                         BLI_dynstr_appendf(ds, "vec4(%s.r, %s.r, %s.r, %s.g)", name, name, name, name);
419                 else if (from == GPU_FLOAT)
420                         BLI_dynstr_appendf(ds, "vec4(%s, %s, %s, 1.0)", name, name, name);
421         }
422         else if (to == GPU_CLOSURE) {
423                 if (from == GPU_VEC4)
424                         BLI_dynstr_appendf(ds, "closure_emission(%s.rgb)", name);
425                 else if (from == GPU_VEC3)
426                         BLI_dynstr_appendf(ds, "closure_emission(%s.rgb)", name);
427                 else if (from == GPU_VEC2)
428                         BLI_dynstr_appendf(ds, "closure_emission(%s.rrr)", name);
429                 else if (from == GPU_FLOAT)
430                         BLI_dynstr_appendf(ds, "closure_emission(vec3(%s, %s, %s))", name, name, name);
431         }
432         else {
433                 BLI_dynstr_append(ds, name);
434         }
435 }
436
437 static void codegen_print_datatype(DynStr *ds, const eGPUType type, float *data)
438 {
439         int i;
440
441         BLI_dynstr_appendf(ds, "%s(", GPU_DATATYPE_STR[type]);
442
443         for (i = 0; i < type; i++) {
444                 BLI_dynstr_appendf(ds, "%.12f", data[i]);
445                 if (i == type - 1)
446                         BLI_dynstr_append(ds, ")");
447                 else
448                         BLI_dynstr_append(ds, ", ");
449         }
450 }
451
452 static int codegen_input_has_texture(GPUInput *input)
453 {
454         if (input->link)
455                 return 0;
456         else
457                 return (input->source == GPU_SOURCE_TEX);
458 }
459
460 const char *GPU_builtin_name(eGPUBuiltin builtin)
461 {
462         if (builtin == GPU_VIEW_MATRIX)
463                 return "unfviewmat";
464         else if (builtin == GPU_OBJECT_MATRIX)
465                 return "unfobmat";
466         else if (builtin == GPU_INVERSE_VIEW_MATRIX)
467                 return "unfinvviewmat";
468         else if (builtin == GPU_INVERSE_OBJECT_MATRIX)
469                 return "unfinvobmat";
470         else if (builtin == GPU_LOC_TO_VIEW_MATRIX)
471                 return "unflocaltoviewmat";
472         else if (builtin == GPU_INVERSE_LOC_TO_VIEW_MATRIX)
473                 return "unfinvlocaltoviewmat";
474         else if (builtin == GPU_VIEW_POSITION)
475                 return "varposition";
476         else if (builtin == GPU_VIEW_NORMAL)
477                 return "varnormal";
478         else if (builtin == GPU_OBCOLOR)
479                 return "unfobcolor";
480         else if (builtin == GPU_AUTO_BUMPSCALE)
481                 return "unfobautobumpscale";
482         else if (builtin == GPU_CAMERA_TEXCO_FACTORS)
483                 return "unfcameratexfactors";
484         else if (builtin == GPU_PARTICLE_SCALAR_PROPS)
485                 return "unfparticlescalarprops";
486         else if (builtin == GPU_PARTICLE_LOCATION)
487                 return "unfparticleco";
488         else if (builtin == GPU_PARTICLE_VELOCITY)
489                 return "unfparticlevel";
490         else if (builtin == GPU_PARTICLE_ANG_VELOCITY)
491                 return "unfparticleangvel";
492         else if (builtin == GPU_OBJECT_INFO)
493                 return "unfobjectinfo";
494         else if (builtin == GPU_VOLUME_DENSITY)
495                 return "sampdensity";
496         else if (builtin == GPU_VOLUME_FLAME)
497                 return "sampflame";
498         else if (builtin == GPU_VOLUME_TEMPERATURE)
499                 return "unftemperature";
500         else if (builtin == GPU_BARYCENTRIC_TEXCO)
501                 return "unfbarycentrictex";
502         else if (builtin == GPU_BARYCENTRIC_DIST)
503                 return "unfbarycentricdist";
504         else
505                 return "";
506 }
507
508 /* assign only one texid per buffer to avoid sampling the same texture twice */
509 static void codegen_set_texid(GHash *bindhash, GPUInput *input, int *texid, void *key)
510 {
511         if (BLI_ghash_haskey(bindhash, key)) {
512                 /* Reuse existing texid */
513                 input->texid = POINTER_AS_INT(BLI_ghash_lookup(bindhash, key));
514         }
515         else {
516                 /* Allocate new texid */
517                 input->texid = *texid;
518                 (*texid)++;
519                 input->bindtex = true;
520                 BLI_ghash_insert(bindhash, key, POINTER_FROM_INT(input->texid));
521         }
522 }
523
524 static void codegen_set_unique_ids(ListBase *nodes)
525 {
526         GHash *bindhash;
527         GPUNode *node;
528         GPUInput *input;
529         GPUOutput *output;
530         int id = 1, texid = 0;
531
532         bindhash = BLI_ghash_ptr_new("codegen_set_unique_ids1 gh");
533
534         for (node = nodes->first; node; node = node->next) {
535                 for (input = node->inputs.first; input; input = input->next) {
536                         /* set id for unique names of uniform variables */
537                         input->id = id++;
538
539                         /* set texid used for settings texture slot */
540                         if (codegen_input_has_texture(input)) {
541                                 input->bindtex = false;
542                                 if (input->ima) {
543                                         /* input is texture from image */
544                                         codegen_set_texid(bindhash, input, &texid, input->ima);
545                                 }
546                                 else if (input->coba) {
547                                         /* input is color band texture, check coba pointer */
548                                         codegen_set_texid(bindhash, input, &texid, input->coba);
549                                 }
550                                 else {
551                                         /* Either input->ima or input->coba should be non-NULL. */
552                                         BLI_assert(0);
553                                 }
554                         }
555                 }
556
557                 for (output = node->outputs.first; output; output = output->next) {
558                         /* set id for unique names of tmp variables storing output */
559                         output->id = id++;
560                 }
561         }
562
563         BLI_ghash_free(bindhash, NULL, NULL);
564 }
565
566 /**
567  * It will create an UBO for GPUMaterial if there is any GPU_DYNAMIC_UBO.
568  */
569 static int codegen_process_uniforms_functions(GPUMaterial *material, DynStr *ds, ListBase *nodes)
570 {
571         GPUNode *node;
572         GPUInput *input;
573         const char *name;
574         int builtins = 0;
575         ListBase ubo_inputs = {NULL, NULL};
576
577         /* print uniforms */
578         for (node = nodes->first; node; node = node->next) {
579                 for (input = node->inputs.first; input; input = input->next) {
580                         if (input->source == GPU_SOURCE_TEX) {
581                                 /* create exactly one sampler for each texture */
582                                 if (codegen_input_has_texture(input) && input->bindtex) {
583                                         BLI_dynstr_appendf(
584                                                 ds, "uniform %s samp%d;\n",
585                                                 (input->coba) ? "sampler1DArray" : "sampler2D",
586                                                 input->texid);
587                                 }
588                         }
589                         else if (input->source == GPU_SOURCE_BUILTIN) {
590                                 /* only define each builtin uniform/varying once */
591                                 if (!(builtins & input->builtin)) {
592                                         builtins |= input->builtin;
593                                         name = GPU_builtin_name(input->builtin);
594
595                                         if (gpu_str_prefix(name, "samp")) {
596                                                 if ((input->builtin == GPU_VOLUME_DENSITY) ||
597                                                     (input->builtin == GPU_VOLUME_FLAME))
598                                                 {
599                                                         BLI_dynstr_appendf(ds, "uniform sampler3D %s;\n", name);
600                                                 }
601                                         }
602                                         else if (gpu_str_prefix(name, "unf")) {
603                                                 BLI_dynstr_appendf(
604                                                         ds, "uniform %s %s;\n",
605                                                         GPU_DATATYPE_STR[input->type], name);
606                                         }
607                                         else {
608                                                 BLI_dynstr_appendf(
609                                                         ds, "in %s %s;\n",
610                                                         GPU_DATATYPE_STR[input->type], name);
611                                         }
612                                 }
613                         }
614                         else if (input->source == GPU_SOURCE_STRUCT) {
615                                 /* Add other struct here if needed. */
616                                 BLI_dynstr_appendf(ds, "Closure strct%d = CLOSURE_DEFAULT;\n", input->id);
617                         }
618                         else if (input->source == GPU_SOURCE_UNIFORM) {
619                                 if (!input->link) {
620                                         /* We handle the UBOuniforms separately. */
621                                         BLI_addtail(&ubo_inputs, BLI_genericNodeN(input));
622                                 }
623                         }
624                         else if (input->source == GPU_SOURCE_CONSTANT) {
625                                 BLI_dynstr_appendf(
626                                         ds, "const %s cons%d = ",
627                                         GPU_DATATYPE_STR[input->type], input->id);
628                                 codegen_print_datatype(ds, input->type, input->vec);
629                                 BLI_dynstr_append(ds, ";\n");
630                         }
631                         else if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
632                                 BLI_dynstr_appendf(
633                                         ds, "in %s var%d;\n",
634                                         GPU_DATATYPE_STR[input->type], input->attr_id);
635                         }
636                 }
637         }
638
639         /* Handle the UBO block separately. */
640         if ((material != NULL) && !BLI_listbase_is_empty(&ubo_inputs)) {
641                 GPU_material_uniform_buffer_create(material, &ubo_inputs);
642
643                 /* Inputs are sorted */
644                 BLI_dynstr_appendf(ds, "\nlayout (std140) uniform %s {\n", GPU_UBO_BLOCK_NAME);
645
646                 for (LinkData *link = ubo_inputs.first; link; link = link->next) {
647                         input = link->data;
648                         BLI_dynstr_appendf(
649                                 ds, "\t%s unf%d;\n",
650                                 GPU_DATATYPE_STR[input->type], input->id);
651                 }
652                 BLI_dynstr_append(ds, "};\n");
653                 BLI_freelistN(&ubo_inputs);
654         }
655
656         BLI_dynstr_append(ds, "\n");
657
658         return builtins;
659 }
660
661 static void codegen_declare_tmps(DynStr *ds, ListBase *nodes)
662 {
663         GPUNode *node;
664         GPUOutput *output;
665
666         for (node = nodes->first; node; node = node->next) {
667                 /* declare temporary variables for node output storage */
668                 for (output = node->outputs.first; output; output = output->next) {
669                         if (output->type == GPU_CLOSURE) {
670                                 BLI_dynstr_appendf(
671                                         ds, "\tClosure tmp%d;\n", output->id);
672                         }
673                         else {
674                                 BLI_dynstr_appendf(
675                                         ds, "\t%s tmp%d;\n",
676                                         GPU_DATATYPE_STR[output->type], output->id);
677                         }
678                 }
679         }
680
681         BLI_dynstr_append(ds, "\n");
682 }
683
684 static void codegen_call_functions(DynStr *ds, ListBase *nodes, GPUOutput *finaloutput)
685 {
686         GPUNode *node;
687         GPUInput *input;
688         GPUOutput *output;
689
690         for (node = nodes->first; node; node = node->next) {
691                 BLI_dynstr_appendf(ds, "\t%s(", node->name);
692
693                 for (input = node->inputs.first; input; input = input->next) {
694                         if (input->source == GPU_SOURCE_TEX) {
695                                 BLI_dynstr_appendf(ds, "samp%d", input->texid);
696                         }
697                         else if (input->source == GPU_SOURCE_OUTPUT) {
698                                 codegen_convert_datatype(
699                                         ds, input->link->output->type, input->type,
700                                         "tmp", input->link->output->id);
701                         }
702                         else if (input->source == GPU_SOURCE_BUILTIN) {
703                                 /* TODO(fclem) get rid of that. */
704                                 if (input->builtin == GPU_INVERSE_VIEW_MATRIX)
705                                         BLI_dynstr_append(ds, "viewinv");
706                                 else if (input->builtin == GPU_VIEW_MATRIX)
707                                         BLI_dynstr_append(ds, "viewmat");
708                                 else if (input->builtin == GPU_CAMERA_TEXCO_FACTORS)
709                                         BLI_dynstr_append(ds, "camtexfac");
710                                 else if (input->builtin == GPU_LOC_TO_VIEW_MATRIX)
711                                         BLI_dynstr_append(ds, "localtoviewmat");
712                                 else if (input->builtin == GPU_INVERSE_LOC_TO_VIEW_MATRIX)
713                                         BLI_dynstr_append(ds, "invlocaltoviewmat");
714                                 else if (input->builtin == GPU_BARYCENTRIC_DIST)
715                                         BLI_dynstr_append(ds, "barycentricDist");
716                                 else if (input->builtin == GPU_BARYCENTRIC_TEXCO)
717                                         BLI_dynstr_append(ds, "barytexco");
718                                 else if (input->builtin == GPU_OBJECT_MATRIX)
719                                         BLI_dynstr_append(ds, "objmat");
720                                 else if (input->builtin == GPU_INVERSE_OBJECT_MATRIX)
721                                         BLI_dynstr_append(ds, "objinv");
722                                 else if (input->builtin == GPU_VIEW_POSITION)
723                                         BLI_dynstr_append(ds, "viewposition");
724                                 else if (input->builtin == GPU_VIEW_NORMAL)
725                                         BLI_dynstr_append(ds, "facingnormal");
726                                 else
727                                         BLI_dynstr_append(ds, GPU_builtin_name(input->builtin));
728                         }
729                         else if (input->source == GPU_SOURCE_STRUCT) {
730                                 BLI_dynstr_appendf(ds, "strct%d", input->id);
731                         }
732                         else if (input->source == GPU_SOURCE_UNIFORM) {
733                                 BLI_dynstr_appendf(ds, "unf%d", input->id);
734                         }
735                         else if (input->source == GPU_SOURCE_CONSTANT) {
736                                 BLI_dynstr_appendf(ds, "cons%d", input->id);
737                         }
738                         else if (input->source == GPU_SOURCE_ATTR) {
739                                 BLI_dynstr_appendf(ds, "var%d", input->attr_id);
740                         }
741
742                         BLI_dynstr_append(ds, ", ");
743                 }
744
745                 for (output = node->outputs.first; output; output = output->next) {
746                         BLI_dynstr_appendf(ds, "tmp%d", output->id);
747                         if (output->next)
748                                 BLI_dynstr_append(ds, ", ");
749                 }
750
751                 BLI_dynstr_append(ds, ");\n");
752         }
753
754         BLI_dynstr_appendf(ds, "\n\treturn tmp%d", finaloutput->id);
755         BLI_dynstr_append(ds, ";\n");
756 }
757
758 static char *code_generate_fragment(GPUMaterial *material, ListBase *nodes, GPUOutput *output, int *rbuiltins)
759 {
760         DynStr *ds = BLI_dynstr_new();
761         char *code;
762         int builtins;
763
764 #if 0
765         BLI_dynstr_append(ds, FUNCTION_PROTOTYPES);
766 #endif
767
768         codegen_set_unique_ids(nodes);
769         *rbuiltins = builtins = codegen_process_uniforms_functions(material, ds, nodes);
770
771         if (builtins & GPU_BARYCENTRIC_TEXCO)
772                 BLI_dynstr_append(ds, "in vec2 barycentricTexCo;\n");
773
774         if (builtins & GPU_BARYCENTRIC_DIST)
775                 BLI_dynstr_append(ds, "flat in vec3 barycentricDist;\n");
776
777         BLI_dynstr_append(ds, "Closure nodetree_exec(void)\n{\n");
778
779         if (builtins & GPU_BARYCENTRIC_TEXCO) {
780                 BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
781                 BLI_dynstr_append(ds, "\tvec2 barytexco = vec2((fract(barycentricTexCo.y) != 0.0)\n"
782                                       "\t                      ? barycentricTexCo.x\n"
783                                       "\t                      : 1.0 - barycentricTexCo.x,\n"
784                                       "\t                      0.0);\n");
785                 BLI_dynstr_append(ds, "#else\n");
786                 BLI_dynstr_append(ds, "\tvec2 barytexco = barycentricTexCo;\n");
787                 BLI_dynstr_append(ds, "#endif\n");
788         }
789         /* TODO(fclem) get rid of that. */
790         if (builtins & GPU_VIEW_MATRIX)
791                 BLI_dynstr_append(ds, "\t#define viewmat ViewMatrix\n");
792         if (builtins & GPU_CAMERA_TEXCO_FACTORS)
793                 BLI_dynstr_append(ds, "\t#define camtexfac CameraTexCoFactors\n");
794         if (builtins & GPU_OBJECT_MATRIX)
795                 BLI_dynstr_append(ds, "\t#define objmat ModelMatrix\n");
796         if (builtins & GPU_INVERSE_OBJECT_MATRIX)
797                 BLI_dynstr_append(ds, "\t#define objinv ModelMatrixInverse\n");
798         if (builtins & GPU_INVERSE_VIEW_MATRIX)
799                 BLI_dynstr_append(ds, "\t#define viewinv ViewMatrixInverse\n");
800         if (builtins & GPU_LOC_TO_VIEW_MATRIX)
801                 BLI_dynstr_append(ds, "\t#define localtoviewmat ModelViewMatrix\n");
802         if (builtins & GPU_INVERSE_LOC_TO_VIEW_MATRIX)
803                 BLI_dynstr_append(ds, "\t#define invlocaltoviewmat ModelViewMatrixInverse\n");
804         if (builtins & GPU_VIEW_NORMAL)
805                 BLI_dynstr_append(ds, "\tvec3 facingnormal = gl_FrontFacing? viewNormal: -viewNormal;\n");
806         if (builtins & GPU_VIEW_POSITION)
807                 BLI_dynstr_append(ds, "\t#define viewposition viewPosition\n");
808
809         codegen_declare_tmps(ds, nodes);
810         codegen_call_functions(ds, nodes, output);
811
812         BLI_dynstr_append(ds, "}\n");
813
814         /* XXX This cannot go into gpu_shader_material.glsl because main() would be parsed and generate error */
815         /* Old glsl mode compat. */
816         BLI_dynstr_append(ds, "#ifndef NODETREE_EXEC\n");
817         BLI_dynstr_append(ds, "out vec4 fragColor;\n");
818         BLI_dynstr_append(ds, "void main()\n");
819         BLI_dynstr_append(ds, "{\n");
820         BLI_dynstr_append(ds, "\tClosure cl = nodetree_exec();\n");
821         BLI_dynstr_append(ds, "\tfragColor = vec4(cl.radiance, cl.opacity);\n");
822         BLI_dynstr_append(ds, "}\n");
823         BLI_dynstr_append(ds, "#endif\n\n");
824
825         /* create shader */
826         code = BLI_dynstr_get_cstring(ds);
827         BLI_dynstr_free(ds);
828
829 #if 0
830         if (G.debug & G_DEBUG) printf("%s\n", code);
831 #endif
832
833         return code;
834 }
835
836 static const char *attr_prefix_get(CustomDataType type)
837 {
838         switch (type) {
839                 case CD_ORCO:           return "orco";
840                 case CD_MTFACE:         return "u";
841                 case CD_TANGENT:        return "t";
842                 case CD_MCOL:           return "c";
843                 case CD_AUTO_FROM_NAME: return "a";
844                 default: BLI_assert(false && "GPUVertAttr Prefix type not found : This should not happen!"); return "";
845         }
846 }
847
848 static char *code_generate_vertex(ListBase *nodes, const char *vert_code, bool use_geom)
849 {
850         DynStr *ds = BLI_dynstr_new();
851         GPUNode *node;
852         GPUInput *input;
853         char *code;
854         int builtins = 0;
855
856         /* Hairs uv and col attributes are passed by bufferTextures. */
857         BLI_dynstr_append(
858                 ds,
859                 "#ifdef HAIR_SHADER\n"
860                 "#define DEFINE_ATTR(type, attr) uniform samplerBuffer attr\n"
861                 "#else\n"
862                 "#define DEFINE_ATTR(type, attr) in type attr\n"
863                 "#endif\n"
864         );
865
866         for (node = nodes->first; node; node = node->next) {
867                 for (input = node->inputs.first; input; input = input->next) {
868                         if (input->source == GPU_SOURCE_BUILTIN) {
869                                 builtins |= input->builtin;
870                         }
871                         if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
872                                 /* XXX FIXME : see notes in mesh_render_data_create() */
873                                 /* NOTE : Replicate changes to mesh_render_data_create() in draw_cache_impl_mesh.c */
874                                 if (input->attr_type == CD_ORCO) {
875                                         /* orco is computed from local positions, see below */
876                                         BLI_dynstr_append(ds, "uniform vec3 OrcoTexCoFactors[2];\n");
877                                 }
878                                 else if (input->attr_name[0] == '\0') {
879                                         BLI_dynstr_appendf(ds, "DEFINE_ATTR(%s, %s);\n", GPU_DATATYPE_STR[input->type], attr_prefix_get(input->attr_type));
880                                         BLI_dynstr_appendf(ds, "#define att%d %s\n", input->attr_id, attr_prefix_get(input->attr_type));
881                                 }
882                                 else {
883                                         uint hash = BLI_ghashutil_strhash_p(input->attr_name);
884                                         BLI_dynstr_appendf(
885                                                 ds, "DEFINE_ATTR(%s, %s%u);\n",
886                                                 GPU_DATATYPE_STR[input->type], attr_prefix_get(input->attr_type), hash);
887                                         BLI_dynstr_appendf(
888                                                 ds, "#define att%d %s%u\n",
889                                                 input->attr_id, attr_prefix_get(input->attr_type), hash);
890                                         /* Auto attribute can be vertex color byte buffer.
891                                          * We need to know and convert them to linear space in VS. */
892                                         if (input->attr_type == CD_AUTO_FROM_NAME) {
893                                                 BLI_dynstr_appendf(ds, "uniform bool ba%u;\n", hash);
894                                                 BLI_dynstr_appendf(ds, "#define att%d_is_srgb ba%u\n", input->attr_id, hash);
895                                         }
896                                 }
897                                 BLI_dynstr_appendf(
898                                         ds, "out %s var%d%s;\n",
899                                         GPU_DATATYPE_STR[input->type], input->attr_id, use_geom ? "g" : "");
900                         }
901                 }
902         }
903
904         if (builtins & GPU_BARYCENTRIC_TEXCO) {
905                 BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
906                 BLI_dynstr_appendf(
907                         ds, "out vec2 barycentricTexCo%s;\n",
908                         use_geom ? "g" : "");
909                 BLI_dynstr_append(ds, "#endif\n");
910         }
911
912         if (builtins & GPU_BARYCENTRIC_DIST) {
913                 BLI_dynstr_append(ds, "out vec3 barycentricPosg;\n");
914         }
915
916
917         BLI_dynstr_append(ds, "\n");
918
919         BLI_dynstr_append(
920                 ds,
921                 "#define USE_ATTR\n"
922                 "uniform mat3 NormalMatrix;\n"
923                 "uniform mat4 ModelMatrixInverse;\n"
924                 "uniform mat4 ModelMatrix;\n"
925                 "vec3 srgb_to_linear_attr(vec3 c) {\n"
926                 "\tc = max(c, vec3(0.0));\n"
927                 "\tvec3 c1 = c * (1.0 / 12.92);\n"
928                 "\tvec3 c2 = pow((c + 0.055) * (1.0 / 1.055), vec3(2.4));\n"
929                 "\treturn mix(c1, c2, step(vec3(0.04045), c));\n"
930                 "}\n\n"
931         );
932
933         /* Prototype because defined later. */
934         BLI_dynstr_append(
935                 ds,
936                 "vec2 hair_get_customdata_vec2(const samplerBuffer);\n"
937                 "vec3 hair_get_customdata_vec3(const samplerBuffer);\n"
938                 "vec4 hair_get_customdata_vec4(const samplerBuffer);\n"
939                 "vec3 hair_get_strand_pos(void);\n"
940                 "int hair_get_base_id(void);\n"
941                 "\n"
942         );
943
944         BLI_dynstr_append(ds, "void pass_attr(in vec3 position) {\n");
945
946         BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
947
948         if (builtins & GPU_BARYCENTRIC_TEXCO) {
949                 /* To match cycles without breaking into individual segment we encode if we need to invert
950                  * the first component into the second component. We invert if the barycentricTexCo.y
951                  * is NOT 0.0 or 1.0. */
952                 BLI_dynstr_append(
953                         ds, "\tint _base_id = hair_get_base_id();\n");
954                 BLI_dynstr_appendf(
955                         ds, "\tbarycentricTexCo%s.x = float((_base_id %% 2) == 1);\n",
956                         use_geom ? "g" : "");
957                 BLI_dynstr_appendf(
958                         ds, "\tbarycentricTexCo%s.y = float(((_base_id %% 4) %% 3) > 0);\n",
959                         use_geom ? "g" : "");
960         }
961
962         if (builtins & GPU_BARYCENTRIC_DIST) {
963                 BLI_dynstr_append(ds, "\tbarycentricPosg = position;\n");
964         }
965
966         for (node = nodes->first; node; node = node->next) {
967                 for (input = node->inputs.first; input; input = input->next) {
968                         if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
969                                 if (input->attr_type == CD_TANGENT) {
970                                         /* Not supported by hairs */
971                                         BLI_dynstr_appendf(
972                                                 ds, "\tvar%d%s = vec4(0.0);\n",
973                                                 input->attr_id, use_geom ? "g" : "");
974                                 }
975                                 else if (input->attr_type == CD_ORCO) {
976                                         BLI_dynstr_appendf(
977                                                 ds, "\tvar%d%s = OrcoTexCoFactors[0] + (ModelMatrixInverse * vec4(hair_get_strand_pos(), 1.0)).xyz * OrcoTexCoFactors[1];\n",
978                                                 input->attr_id, use_geom ? "g" : "");
979                                 }
980                                 else {
981                                         BLI_dynstr_appendf(
982                                                 ds, "\tvar%d%s = hair_get_customdata_%s(att%d);\n",
983                                                 input->attr_id, use_geom ? "g" : "", GPU_DATATYPE_STR[input->type], input->attr_id);
984                                 }
985                         }
986                 }
987         }
988
989         BLI_dynstr_append(ds, "#else /* MESH_SHADER */\n");
990
991         /* GPU_BARYCENTRIC_TEXCO cannot be computed based on gl_VertexID
992          * for MESH_SHADER because of indexed drawing. In this case a
993          * geometry shader is needed. */
994
995         if (builtins & GPU_BARYCENTRIC_DIST) {
996                 BLI_dynstr_append(ds, "\tbarycentricPosg = (ModelMatrix * vec4(position, 1.0)).xyz;\n");
997         }
998
999         for (node = nodes->first; node; node = node->next) {
1000                 for (input = node->inputs.first; input; input = input->next) {
1001                         if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
1002                                 if (input->attr_type == CD_TANGENT) { /* silly exception */
1003                                         BLI_dynstr_appendf(
1004                                                 ds, "\tvar%d%s.xyz = NormalMatrix * att%d.xyz;\n",
1005                                                 input->attr_id, use_geom ? "g" : "", input->attr_id);
1006                                         BLI_dynstr_appendf(
1007                                                 ds, "\tvar%d%s.w = att%d.w;\n",
1008                                                 input->attr_id, use_geom ? "g" : "", input->attr_id);
1009                                         /* Normalize only if vector is not null. */
1010                                         BLI_dynstr_appendf(
1011                                                 ds, "\tfloat lvar%d = dot(var%d%s.xyz, var%d%s.xyz);\n",
1012                                                 input->attr_id, input->attr_id, use_geom ? "g" : "", input->attr_id, use_geom ? "g" : "");
1013                                         BLI_dynstr_appendf(
1014                                                 ds, "\tvar%d%s.xyz *= (lvar%d > 0.0) ? inversesqrt(lvar%d) : 1.0;\n",
1015                                                 input->attr_id, use_geom ? "g" : "", input->attr_id, input->attr_id);
1016                                 }
1017                                 else if (input->attr_type == CD_ORCO) {
1018                                         BLI_dynstr_appendf(
1019                                                 ds, "\tvar%d%s = OrcoTexCoFactors[0] + position * OrcoTexCoFactors[1];\n",
1020                                                 input->attr_id, use_geom ? "g" : "");
1021                                 }
1022                                 else if (input->attr_type == CD_MCOL) {
1023                                         BLI_dynstr_appendf(
1024                                                 ds, "\tvar%d%s = srgb_to_linear_attr(att%d);\n",
1025                                                 input->attr_id, use_geom ? "g" : "", input->attr_id);
1026                                 }
1027                                 else if (input->attr_type == CD_AUTO_FROM_NAME) {
1028                                         BLI_dynstr_appendf(
1029                                                 ds, "\tvar%d%s = (att%d_is_srgb) ? srgb_to_linear_attr(att%d) : att%d;\n",
1030                                                 input->attr_id, use_geom ? "g" : "",
1031                                                 input->attr_id, input->attr_id, input->attr_id);
1032                                 }
1033                                 else {
1034                                         BLI_dynstr_appendf(
1035                                                 ds, "\tvar%d%s = att%d;\n",
1036                                                 input->attr_id, use_geom ? "g" : "", input->attr_id);
1037                                 }
1038                         }
1039                 }
1040         }
1041         BLI_dynstr_append(ds, "#endif /* HAIR_SHADER */\n");
1042
1043         BLI_dynstr_append(ds, "}\n");
1044
1045         if (use_geom) {
1046                 /* XXX HACK: Eevee specific. */
1047                 char *vert_new, *vert_new2;
1048                 vert_new = BLI_str_replaceN(vert_code, "worldPosition", "worldPositiong");
1049                 vert_new2 = vert_new;
1050                 vert_new = BLI_str_replaceN(vert_new2, "viewPosition", "viewPositiong");
1051                 MEM_freeN(vert_new2);
1052                 vert_new2 = vert_new;
1053                 vert_new = BLI_str_replaceN(vert_new2, "worldNormal", "worldNormalg");
1054                 MEM_freeN(vert_new2);
1055                 vert_new2 = vert_new;
1056                 vert_new = BLI_str_replaceN(vert_new2, "viewNormal", "viewNormalg");
1057                 MEM_freeN(vert_new2);
1058
1059                 BLI_dynstr_append(ds, vert_new);
1060
1061                 MEM_freeN(vert_new);
1062         }
1063         else {
1064                 BLI_dynstr_append(ds, vert_code);
1065         }
1066
1067         code = BLI_dynstr_get_cstring(ds);
1068
1069         BLI_dynstr_free(ds);
1070
1071 #if 0
1072         if (G.debug & G_DEBUG) printf("%s\n", code);
1073 #endif
1074
1075         return code;
1076 }
1077
1078 static char *code_generate_geometry(ListBase *nodes, const char *geom_code, const char *defines)
1079 {
1080         DynStr *ds = BLI_dynstr_new();
1081         GPUNode *node;
1082         GPUInput *input;
1083         char *code;
1084         int builtins = 0;
1085
1086         /* XXX we should not make specific eevee cases here. */
1087         bool is_hair_shader = (strstr(defines, "HAIR_SHADER") != NULL);
1088
1089         /* Create prototype because attributes cannot be declared before layout. */
1090         BLI_dynstr_append(ds, "void pass_attr(in int vert);\n");
1091         BLI_dynstr_append(ds, "void calc_barycentric_distances(vec3 pos0, vec3 pos1, vec3 pos2);\n");
1092         BLI_dynstr_append(ds, "#define USE_ATTR\n");
1093
1094         /* Generate varying declarations. */
1095         for (node = nodes->first; node; node = node->next) {
1096                 for (input = node->inputs.first; input; input = input->next) {
1097                         if (input->source == GPU_SOURCE_BUILTIN) {
1098                                 builtins |= input->builtin;
1099                         }
1100                         if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
1101                                 BLI_dynstr_appendf(
1102                                         ds, "in %s var%dg[];\n",
1103                                         GPU_DATATYPE_STR[input->type],
1104                                         input->attr_id);
1105                                 BLI_dynstr_appendf(
1106                                         ds, "out %s var%d;\n",
1107                                         GPU_DATATYPE_STR[input->type],
1108                                         input->attr_id);
1109                         }
1110                 }
1111         }
1112
1113         if (builtins & GPU_BARYCENTRIC_TEXCO) {
1114                 BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
1115                 BLI_dynstr_append(ds, "in vec2 barycentricTexCog[];\n");
1116                 BLI_dynstr_append(ds, "#endif\n");
1117
1118                 BLI_dynstr_append(ds, "out vec2 barycentricTexCo;\n");
1119         }
1120
1121         if (builtins & GPU_BARYCENTRIC_DIST) {
1122                 BLI_dynstr_append(ds, "in vec3 barycentricPosg[];\n");
1123                 BLI_dynstr_append(ds, "flat out vec3 barycentricDist;\n");
1124         }
1125
1126         if (geom_code == NULL) {
1127                 /* Force geometry usage if GPU_BARYCENTRIC_DIST or GPU_BARYCENTRIC_TEXCO are used.
1128                  * Note: GPU_BARYCENTRIC_TEXCO only requires it if the shader is not drawing hairs. */
1129                 if ((builtins & (GPU_BARYCENTRIC_DIST | GPU_BARYCENTRIC_TEXCO)) == 0 || is_hair_shader) {
1130                         /* Early out */
1131                         BLI_dynstr_free(ds);
1132                         return NULL;
1133                 }
1134                 else {
1135                         /* Force geom shader usage */
1136                         /* TODO put in external file. */
1137                         BLI_dynstr_append(ds, "layout(triangles) in;\n");
1138                         BLI_dynstr_append(ds, "layout(triangle_strip, max_vertices=3) out;\n");
1139
1140                         BLI_dynstr_append(ds, "in vec3 worldPositiong[];\n");
1141                         BLI_dynstr_append(ds, "in vec3 viewPositiong[];\n");
1142                         BLI_dynstr_append(ds, "in vec3 worldNormalg[];\n");
1143                         BLI_dynstr_append(ds, "in vec3 viewNormalg[];\n");
1144
1145                         BLI_dynstr_append(ds, "out vec3 worldPosition;\n");
1146                         BLI_dynstr_append(ds, "out vec3 viewPosition;\n");
1147                         BLI_dynstr_append(ds, "out vec3 worldNormal;\n");
1148                         BLI_dynstr_append(ds, "out vec3 viewNormal;\n");
1149
1150                         BLI_dynstr_append(ds, "void main(){\n");
1151
1152                         if (builtins & GPU_BARYCENTRIC_DIST) {
1153                                 BLI_dynstr_append(ds, "\tcalc_barycentric_distances(barycentricPosg[0], barycentricPosg[1], barycentricPosg[2]);\n");
1154                         }
1155
1156                         BLI_dynstr_append(ds, "\tgl_Position = gl_in[0].gl_Position;\n");
1157                         BLI_dynstr_append(ds, "\tpass_attr(0);\n");
1158                         BLI_dynstr_append(ds, "\tEmitVertex();\n");
1159
1160                         BLI_dynstr_append(ds, "\tgl_Position = gl_in[1].gl_Position;\n");
1161                         BLI_dynstr_append(ds, "\tpass_attr(1);\n");
1162                         BLI_dynstr_append(ds, "\tEmitVertex();\n");
1163
1164                         BLI_dynstr_append(ds, "\tgl_Position = gl_in[2].gl_Position;\n");
1165                         BLI_dynstr_append(ds, "\tpass_attr(2);\n");
1166                         BLI_dynstr_append(ds, "\tEmitVertex();\n");
1167                         BLI_dynstr_append(ds, "};\n");
1168                 }
1169         }
1170         else {
1171                 BLI_dynstr_append(ds, geom_code);
1172         }
1173
1174         if (builtins & GPU_BARYCENTRIC_DIST) {
1175                 BLI_dynstr_append(ds, "void calc_barycentric_distances(vec3 pos0, vec3 pos1, vec3 pos2) {\n");
1176                 BLI_dynstr_append(ds, "\tvec3 edge21 = pos2 - pos1;\n");
1177                 BLI_dynstr_append(ds, "\tvec3 edge10 = pos1 - pos0;\n");
1178                 BLI_dynstr_append(ds, "\tvec3 edge02 = pos0 - pos2;\n");
1179                 BLI_dynstr_append(ds, "\tvec3 d21 = normalize(edge21);\n");
1180                 BLI_dynstr_append(ds, "\tvec3 d10 = normalize(edge10);\n");
1181                 BLI_dynstr_append(ds, "\tvec3 d02 = normalize(edge02);\n");
1182
1183                 BLI_dynstr_append(ds, "\tfloat d = dot(d21, edge02);\n");
1184                 BLI_dynstr_append(ds, "\tbarycentricDist.x = sqrt(dot(edge02, edge02) - d * d);\n");
1185                 BLI_dynstr_append(ds, "\td = dot(d02, edge10);\n");
1186                 BLI_dynstr_append(ds, "\tbarycentricDist.y = sqrt(dot(edge10, edge10) - d * d);\n");
1187                 BLI_dynstr_append(ds, "\td = dot(d10, edge21);\n");
1188                 BLI_dynstr_append(ds, "\tbarycentricDist.z = sqrt(dot(edge21, edge21) - d * d);\n");
1189                 BLI_dynstr_append(ds, "}\n");
1190         }
1191
1192         /* Generate varying assignments. */
1193         BLI_dynstr_append(ds, "void pass_attr(in int vert) {\n");
1194
1195         /* XXX HACK: Eevee specific. */
1196         if (geom_code == NULL) {
1197                 BLI_dynstr_append(ds, "\tworldPosition = worldPositiong[vert];\n");
1198                 BLI_dynstr_append(ds, "\tviewPosition = viewPositiong[vert];\n");
1199                 BLI_dynstr_append(ds, "\tworldNormal = worldNormalg[vert];\n");
1200                 BLI_dynstr_append(ds, "\tviewNormal = viewNormalg[vert];\n");
1201         }
1202
1203         if (builtins & GPU_BARYCENTRIC_TEXCO) {
1204                 BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
1205                 BLI_dynstr_append(ds, "\tbarycentricTexCo = barycentricTexCog[vert];\n");
1206                 BLI_dynstr_append(ds, "#else\n");
1207                 BLI_dynstr_append(ds, "\tbarycentricTexCo.x = float((vert %% 3) == 0);\n");
1208                 BLI_dynstr_append(ds, "\tbarycentricTexCo.y = float((vert %% 3) == 1);\n");
1209                 BLI_dynstr_append(ds, "#endif\n");
1210         }
1211
1212         for (node = nodes->first; node; node = node->next) {
1213                 for (input = node->inputs.first; input; input = input->next) {
1214                         if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
1215                                 /* TODO let shader choose what to do depending on what the attribute is. */
1216                                 BLI_dynstr_appendf(ds, "\tvar%d = var%dg[vert];\n", input->attr_id, input->attr_id);
1217                         }
1218                 }
1219         }
1220         BLI_dynstr_append(ds, "}\n");
1221
1222         code = BLI_dynstr_get_cstring(ds);
1223         BLI_dynstr_free(ds);
1224
1225         return code;
1226 }
1227
1228 void GPU_code_generate_glsl_lib(void)
1229 {
1230         DynStr *ds;
1231
1232         /* only initialize the library once */
1233         if (glsl_material_library)
1234                 return;
1235
1236         ds = BLI_dynstr_new();
1237
1238         BLI_dynstr_append(ds, datatoc_gpu_shader_material_glsl);
1239
1240
1241         glsl_material_library = BLI_dynstr_get_cstring(ds);
1242
1243         BLI_dynstr_free(ds);
1244 }
1245
1246
1247 /* GPU pass binding/unbinding */
1248
1249 GPUShader *GPU_pass_shader_get(GPUPass *pass)
1250 {
1251         return pass->shader;
1252 }
1253
1254 void GPU_nodes_extract_dynamic_inputs(GPUShader *shader, ListBase *inputs, ListBase *nodes)
1255 {
1256         GPUNode *node;
1257         GPUInput *next, *input;
1258
1259         BLI_listbase_clear(inputs);
1260
1261         if (!shader)
1262                 return;
1263
1264         for (node = nodes->first; node; node = node->next) {
1265                 int z = 0;
1266                 for (input = node->inputs.first; input; input = next, z++) {
1267                         next = input->next;
1268
1269                         /* attributes don't need to be bound, they already have
1270                          * an id that the drawing functions will use. Builtins have
1271                          * constant names. */
1272                         if (ELEM(input->source, GPU_SOURCE_ATTR, GPU_SOURCE_BUILTIN)) {
1273                                 continue;
1274                         }
1275
1276                         if (input->source == GPU_SOURCE_TEX)
1277                                 BLI_snprintf(input->shadername, sizeof(input->shadername), "samp%d", input->texid);
1278                         else {
1279                                 BLI_snprintf(input->shadername, sizeof(input->shadername), "unf%d", input->id);
1280                         }
1281
1282                         if (input->source == GPU_SOURCE_TEX) {
1283                                 if (input->bindtex) {
1284                                         input->shaderloc = GPU_shader_get_uniform_ensure(shader, input->shadername);
1285                                         /* extract nodes */
1286                                         BLI_remlink(&node->inputs, input);
1287                                         BLI_addtail(inputs, input);
1288                                 }
1289                         }
1290                 }
1291         }
1292 }
1293
1294 /* Node Link Functions */
1295
1296 static GPUNodeLink *GPU_node_link_create(void)
1297 {
1298         GPUNodeLink *link = MEM_callocN(sizeof(GPUNodeLink), "GPUNodeLink");
1299         link->users++;
1300
1301         return link;
1302 }
1303
1304 static void gpu_node_link_free(GPUNodeLink *link)
1305 {
1306         link->users--;
1307
1308         if (link->users < 0)
1309                 fprintf(stderr, "GPU_node_link_free: negative refcount\n");
1310
1311         if (link->users == 0) {
1312                 if (link->output)
1313                         link->output->link = NULL;
1314                 MEM_freeN(link);
1315         }
1316 }
1317
1318 /* Node Functions */
1319
1320 static GPUNode *GPU_node_begin(const char *name)
1321 {
1322         GPUNode *node = MEM_callocN(sizeof(GPUNode), "GPUNode");
1323
1324         node->name = name;
1325
1326         return node;
1327 }
1328
1329 static void gpu_node_input_link(GPUNode *node, GPUNodeLink *link, const eGPUType type)
1330 {
1331         GPUInput *input;
1332         GPUNode *outnode;
1333         const char *name;
1334
1335         if (link->link_type == GPU_NODE_LINK_OUTPUT) {
1336                 outnode = link->output->node;
1337                 name = outnode->name;
1338                 input = outnode->inputs.first;
1339
1340                 if ((STREQ(name, "set_value") || STREQ(name, "set_rgb") || STREQ(name, "set_rgba")) &&
1341                     (input->type == type))
1342                 {
1343                         input = MEM_dupallocN(outnode->inputs.first);
1344                         if (input->link)
1345                                 input->link->users++;
1346                         BLI_addtail(&node->inputs, input);
1347                         return;
1348                 }
1349         }
1350
1351         input = MEM_callocN(sizeof(GPUInput), "GPUInput");
1352         input->node = node;
1353         input->type = type;
1354
1355         switch (link->link_type) {
1356                 case GPU_NODE_LINK_BUILTIN:
1357                         input->source = GPU_SOURCE_BUILTIN;
1358                         input->builtin = link->builtin;
1359                         break;
1360                 case GPU_NODE_LINK_OUTPUT:
1361                         input->source = GPU_SOURCE_OUTPUT;
1362                         input->link = link;
1363                         link->users++;
1364                         break;
1365                 case GPU_NODE_LINK_COLORBAND:
1366                         input->source = GPU_SOURCE_TEX;
1367                         input->coba = link->coba;
1368                         break;
1369                 case GPU_NODE_LINK_IMAGE_BLENDER:
1370                         input->source = GPU_SOURCE_TEX;
1371                         input->ima = link->ima;
1372                         input->iuser = link->iuser;
1373                         input->image_isdata = link->image_isdata;
1374                         break;
1375                 case GPU_NODE_LINK_ATTR:
1376                         input->source = GPU_SOURCE_ATTR;
1377                         input->attr_type = link->attr_type;
1378                         BLI_strncpy(input->attr_name, link->attr_name, sizeof(input->attr_name));
1379                         break;
1380                 case GPU_NODE_LINK_CONSTANT:
1381                         input->source = (type == GPU_CLOSURE) ? GPU_SOURCE_STRUCT : GPU_SOURCE_CONSTANT;
1382                         break;
1383                 case GPU_NODE_LINK_UNIFORM:
1384                         input->source = GPU_SOURCE_UNIFORM;
1385                         break;
1386                 default:
1387                         break;
1388         }
1389
1390         if (ELEM(input->source, GPU_SOURCE_CONSTANT, GPU_SOURCE_UNIFORM)) {
1391                 memcpy(input->vec, link->data, type * sizeof(float));
1392         }
1393
1394         if (link->link_type != GPU_NODE_LINK_OUTPUT) {
1395                 MEM_freeN(link);
1396         }
1397         BLI_addtail(&node->inputs, input);
1398 }
1399
1400
1401 static const char *gpu_uniform_set_function_from_type(eNodeSocketDatatype type)
1402 {
1403         switch (type) {
1404                 /* For now INT is supported as float. */
1405                 case SOCK_INT:
1406                 case SOCK_FLOAT:
1407                         return "set_value";
1408                 case SOCK_VECTOR:
1409                         return "set_rgb";
1410                 case SOCK_RGBA:
1411                         return "set_rgba";
1412                 default:
1413                         BLI_assert(!"No gpu function for non-supported eNodeSocketDatatype");
1414                         return NULL;
1415         }
1416 }
1417
1418 /**
1419  * Link stack uniform buffer.
1420  * This is called for the input/output sockets that are note connected.
1421  */
1422 static GPUNodeLink *gpu_uniformbuffer_link(
1423         GPUMaterial *mat, bNode *node, GPUNodeStack *stack, const int index, const eNodeSocketInOut in_out)
1424 {
1425         bNodeSocket *socket;
1426
1427         if (in_out == SOCK_IN) {
1428                 socket = BLI_findlink(&node->inputs, index);
1429         }
1430         else {
1431                 socket = BLI_findlink(&node->outputs, index);
1432         }
1433
1434         BLI_assert(socket != NULL);
1435         BLI_assert(socket->in_out == in_out);
1436
1437         if ((socket->flag & SOCK_HIDE_VALUE) == 0) {
1438                 GPUNodeLink *link;
1439                 switch (socket->type) {
1440                         case SOCK_FLOAT:
1441                         {
1442                                 bNodeSocketValueFloat *socket_data = socket->default_value;
1443                                 link = GPU_uniform(&socket_data->value);
1444                                 break;
1445                         }
1446                         case SOCK_VECTOR:
1447                         {
1448                                 bNodeSocketValueVector *socket_data = socket->default_value;
1449                                 link = GPU_uniform(socket_data->value);
1450                                 break;
1451                         }
1452                         case SOCK_RGBA:
1453                         {
1454                                 bNodeSocketValueRGBA *socket_data = socket->default_value;
1455                                 link = GPU_uniform(socket_data->value);
1456                                 break;
1457                         }
1458                         default:
1459                                 return NULL;
1460                                 break;
1461                 }
1462
1463                 if (in_out == SOCK_IN) {
1464                         GPU_link(mat, gpu_uniform_set_function_from_type(socket->type), link, &stack->link);
1465                 }
1466                 return link;
1467         }
1468         return NULL;
1469 }
1470
1471 static void gpu_node_input_socket(GPUMaterial *material, bNode *bnode, GPUNode *node, GPUNodeStack *sock, const int index)
1472 {
1473         if (sock->link) {
1474                 gpu_node_input_link(node, sock->link, sock->type);
1475         }
1476         else if ((material != NULL) && (gpu_uniformbuffer_link(material, bnode, sock, index, SOCK_IN) != NULL)) {
1477                 gpu_node_input_link(node, sock->link, sock->type);
1478         }
1479         else {
1480                 gpu_node_input_link(node, GPU_constant(sock->vec), sock->type);
1481         }
1482 }
1483
1484 static void gpu_node_output(GPUNode *node, const eGPUType type, GPUNodeLink **link)
1485 {
1486         GPUOutput *output = MEM_callocN(sizeof(GPUOutput), "GPUOutput");
1487
1488         output->type = type;
1489         output->node = node;
1490
1491         if (link) {
1492                 *link = output->link = GPU_node_link_create();
1493                 output->link->link_type = GPU_NODE_LINK_OUTPUT;
1494                 output->link->output = output;
1495
1496                 /* note: the caller owns the reference to the link, GPUOutput
1497                  * merely points to it, and if the node is destroyed it will
1498                  * set that pointer to NULL */
1499         }
1500
1501         BLI_addtail(&node->outputs, output);
1502 }
1503
1504 void GPU_inputs_free(ListBase *inputs)
1505 {
1506         GPUInput *input;
1507
1508         for (input = inputs->first; input; input = input->next) {
1509                 if (input->link)
1510                         gpu_node_link_free(input->link);
1511         }
1512
1513         BLI_freelistN(inputs);
1514 }
1515
1516 static void gpu_node_free(GPUNode *node)
1517 {
1518         GPUOutput *output;
1519
1520         GPU_inputs_free(&node->inputs);
1521
1522         for (output = node->outputs.first; output; output = output->next)
1523                 if (output->link) {
1524                         output->link->output = NULL;
1525                         gpu_node_link_free(output->link);
1526                 }
1527
1528         BLI_freelistN(&node->outputs);
1529         MEM_freeN(node);
1530 }
1531
1532 static void gpu_nodes_free(ListBase *nodes)
1533 {
1534         GPUNode *node;
1535
1536         while ((node = BLI_pophead(nodes))) {
1537                 gpu_node_free(node);
1538         }
1539 }
1540
1541 /* vertex attributes */
1542
1543 void GPU_nodes_get_vertex_attrs(ListBase *nodes, GPUVertAttrLayers *attrs)
1544 {
1545         GPUNode *node;
1546         GPUInput *input;
1547         int a;
1548
1549         /* convert attributes requested by node inputs to an array of layers,
1550          * checking for duplicates and assigning id's starting from zero. */
1551
1552         memset(attrs, 0, sizeof(*attrs));
1553
1554         for (node = nodes->first; node; node = node->next) {
1555                 for (input = node->inputs.first; input; input = input->next) {
1556                         if (input->source == GPU_SOURCE_ATTR) {
1557                                 for (a = 0; a < attrs->totlayer; a++) {
1558                                         if (attrs->layer[a].type == input->attr_type &&
1559                                             STREQ(attrs->layer[a].name, input->attr_name))
1560                                         {
1561                                                 break;
1562                                         }
1563                                 }
1564
1565                                 if (a < GPU_MAX_ATTR) {
1566                                         if (a == attrs->totlayer) {
1567                                                 input->attr_id = attrs->totlayer++;
1568                                                 input->attr_first = true;
1569
1570                                                 attrs->layer[a].type = input->attr_type;
1571                                                 attrs->layer[a].attr_id = input->attr_id;
1572                                                 BLI_strncpy(
1573                                                         attrs->layer[a].name, input->attr_name,
1574                                                         sizeof(attrs->layer[a].name));
1575                                         }
1576                                         else {
1577                                                 input->attr_id = attrs->layer[a].attr_id;
1578                                         }
1579                                 }
1580                         }
1581                 }
1582         }
1583 }
1584
1585 /* varargs linking  */
1586
1587 GPUNodeLink *GPU_attribute(const CustomDataType type, const char *name)
1588 {
1589         GPUNodeLink *link = GPU_node_link_create();
1590         link->link_type = GPU_NODE_LINK_ATTR;
1591         link->attr_name = name;
1592         /* Fall back to the UV layer, which matches old behavior. */
1593         if (type == CD_AUTO_FROM_NAME && name[0] == '\0') {
1594                 link->attr_type = CD_MTFACE;
1595         }
1596         else {
1597                 link->attr_type = type;
1598         }
1599         return link;
1600 }
1601
1602 GPUNodeLink *GPU_constant(float *num)
1603 {
1604         GPUNodeLink *link = GPU_node_link_create();
1605         link->link_type = GPU_NODE_LINK_CONSTANT;
1606         link->data = num;
1607         return link;
1608 }
1609
1610 GPUNodeLink *GPU_uniform(float *num)
1611 {
1612         GPUNodeLink *link = GPU_node_link_create();
1613         link->link_type = GPU_NODE_LINK_UNIFORM;
1614         link->data = num;
1615         return link;
1616 }
1617
1618 GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser, bool is_data)
1619 {
1620         GPUNodeLink *link = GPU_node_link_create();
1621         link->link_type = GPU_NODE_LINK_IMAGE_BLENDER;
1622         link->ima = ima;
1623         link->iuser = iuser;
1624         link->image_isdata = is_data;
1625         return link;
1626 }
1627
1628 GPUNodeLink *GPU_color_band(GPUMaterial *mat, int size, float *pixels, float *row)
1629 {
1630         GPUNodeLink *link = GPU_node_link_create();
1631         link->link_type = GPU_NODE_LINK_COLORBAND;
1632         link->coba = gpu_material_ramp_texture_row_set(mat, size, pixels, row);
1633         MEM_freeN(pixels);
1634         return link;
1635 }
1636
1637 GPUNodeLink *GPU_builtin(eGPUBuiltin builtin)
1638 {
1639         GPUNodeLink *link = GPU_node_link_create();
1640         link->link_type = GPU_NODE_LINK_BUILTIN;
1641         link->builtin = builtin;
1642         return link;
1643 }
1644
1645 bool GPU_link(GPUMaterial *mat, const char *name, ...)
1646 {
1647         GPUNode *node;
1648         GPUFunction *function;
1649         GPUNodeLink *link, **linkptr;
1650         va_list params;
1651         int i;
1652
1653         function = gpu_lookup_function(name);
1654         if (!function) {
1655                 fprintf(stderr, "GPU failed to find function %s\n", name);
1656                 return false;
1657         }
1658
1659         node = GPU_node_begin(name);
1660
1661         va_start(params, name);
1662         for (i = 0; i < function->totparam; i++) {
1663                 if (function->paramqual[i] != FUNCTION_QUAL_IN) {
1664                         linkptr = va_arg(params, GPUNodeLink **);
1665                         gpu_node_output(node, function->paramtype[i], linkptr);
1666                 }
1667                 else {
1668                         link = va_arg(params, GPUNodeLink *);
1669                         gpu_node_input_link(node, link, function->paramtype[i]);
1670                 }
1671         }
1672         va_end(params);
1673
1674         gpu_material_add_node(mat, node);
1675
1676         return true;
1677 }
1678
1679 bool GPU_stack_link(GPUMaterial *material, bNode *bnode, const char *name, GPUNodeStack *in, GPUNodeStack *out, ...)
1680 {
1681         GPUNode *node;
1682         GPUFunction *function;
1683         GPUNodeLink *link, **linkptr;
1684         va_list params;
1685         int i, totin, totout;
1686
1687         function = gpu_lookup_function(name);
1688         if (!function) {
1689                 fprintf(stderr, "GPU failed to find function %s\n", name);
1690                 return false;
1691         }
1692
1693         node = GPU_node_begin(name);
1694         totin = 0;
1695         totout = 0;
1696
1697         if (in) {
1698                 for (i = 0; !in[i].end; i++) {
1699                         if (in[i].type != GPU_NONE) {
1700                                 gpu_node_input_socket(material, bnode, node, &in[i], i);
1701                                 totin++;
1702                         }
1703                 }
1704         }
1705
1706         if (out) {
1707                 for (i = 0; !out[i].end; i++) {
1708                         if (out[i].type != GPU_NONE) {
1709                                 gpu_node_output(node, out[i].type, &out[i].link);
1710                                 totout++;
1711                         }
1712                 }
1713         }
1714
1715         va_start(params, out);
1716         for (i = 0; i < function->totparam; i++) {
1717                 if (function->paramqual[i] != FUNCTION_QUAL_IN) {
1718                         if (totout == 0) {
1719                                 linkptr = va_arg(params, GPUNodeLink **);
1720                                 gpu_node_output(node, function->paramtype[i], linkptr);
1721                         }
1722                         else
1723                                 totout--;
1724                 }
1725                 else {
1726                         if (totin == 0) {
1727                                 link = va_arg(params, GPUNodeLink *);
1728                                 if (link->socket)
1729                                         gpu_node_input_socket(NULL, NULL, node, link->socket, -1);
1730                                 else
1731                                         gpu_node_input_link(node, link, function->paramtype[i]);
1732                         }
1733                         else
1734                                 totin--;
1735                 }
1736         }
1737         va_end(params);
1738
1739         gpu_material_add_node(material, node);
1740
1741         return true;
1742 }
1743
1744 GPUNodeLink *GPU_uniformbuffer_link_out(GPUMaterial *mat, bNode *node, GPUNodeStack *stack, const int index)
1745 {
1746         return gpu_uniformbuffer_link(mat, node, stack, index, SOCK_OUT);
1747 }
1748
1749 /* Pass create/free */
1750
1751 static void gpu_nodes_tag(GPUNodeLink *link)
1752 {
1753         GPUNode *node;
1754         GPUInput *input;
1755
1756         if (!link->output)
1757                 return;
1758
1759         node = link->output->node;
1760         if (node->tag)
1761                 return;
1762
1763         node->tag = true;
1764         for (input = node->inputs.first; input; input = input->next)
1765                 if (input->link)
1766                         gpu_nodes_tag(input->link);
1767 }
1768
1769 void GPU_nodes_prune(ListBase *nodes, GPUNodeLink *outlink)
1770 {
1771         GPUNode *node, *next;
1772
1773         for (node = nodes->first; node; node = node->next)
1774                 node->tag = false;
1775
1776         gpu_nodes_tag(outlink);
1777
1778         for (node = nodes->first; node; node = next) {
1779                 next = node->next;
1780
1781                 if (!node->tag) {
1782                         BLI_remlink(nodes, node);
1783                         gpu_node_free(node);
1784                 }
1785         }
1786 }
1787
1788 static bool gpu_pass_is_valid(GPUPass *pass)
1789 {
1790         /* Shader is not null if compilation is successful. */
1791         return (pass->compiled == false || pass->shader != NULL);
1792 }
1793
1794 GPUPass *GPU_generate_pass(
1795         GPUMaterial *material,
1796         GPUNodeLink *frag_outlink,
1797         struct GPUVertAttrLayers *attrs,
1798         ListBase *nodes,
1799         int *builtins,
1800         const char *vert_code,
1801         const char *geom_code,
1802         const char *frag_lib,
1803         const char *defines)
1804 {
1805         char *vertexcode, *geometrycode, *fragmentcode;
1806         GPUPass *pass = NULL, *pass_hash = NULL;
1807
1808         /* prune unused nodes */
1809         GPU_nodes_prune(nodes, frag_outlink);
1810
1811         GPU_nodes_get_vertex_attrs(nodes, attrs);
1812
1813         /* generate code */
1814         char *fragmentgen = code_generate_fragment(material, nodes, frag_outlink->output, builtins);
1815
1816         /* Cache lookup: Reuse shaders already compiled */
1817         uint32_t hash = gpu_pass_hash(fragmentgen, defines, attrs);
1818         pass_hash = gpu_pass_cache_lookup(hash);
1819
1820         if (pass_hash && (pass_hash->next == NULL || pass_hash->next->hash != hash)) {
1821                 /* No collision, just return the pass. */
1822                 MEM_freeN(fragmentgen);
1823                 if (!gpu_pass_is_valid(pass_hash)) {
1824                         /* Shader has already been created but failed to compile. */
1825                         return NULL;
1826                 }
1827                 pass_hash->refcount += 1;
1828                 return pass_hash;
1829         }
1830
1831         /* Either the shader is not compiled or there is a hash collision...
1832          * continue generating the shader strings. */
1833         char *tmp = BLI_strdupcat(frag_lib, glsl_material_library);
1834
1835         geometrycode = code_generate_geometry(nodes, geom_code, defines);
1836         vertexcode = code_generate_vertex(nodes, vert_code, (geometrycode != NULL));
1837         fragmentcode = BLI_strdupcat(tmp, fragmentgen);
1838
1839         MEM_freeN(fragmentgen);
1840         MEM_freeN(tmp);
1841
1842         if (pass_hash) {
1843                 /* Cache lookup: Reuse shaders already compiled */
1844                 pass = gpu_pass_cache_resolve_collision(pass_hash, vertexcode, geometrycode, fragmentcode, defines, hash);
1845         }
1846
1847         if (pass) {
1848                 /* Cache hit. Reuse the same GPUPass and GPUShader. */
1849                 if (!gpu_pass_is_valid(pass)) {
1850                         /* Shader has already been created but failed to compile. */
1851                         return NULL;
1852                 }
1853
1854                 MEM_SAFE_FREE(vertexcode);
1855                 MEM_SAFE_FREE(fragmentcode);
1856                 MEM_SAFE_FREE(geometrycode);
1857
1858                 pass->refcount += 1;
1859         }
1860         else {
1861                 /* We still create a pass even if shader compilation
1862                  * fails to avoid trying to compile again and again. */
1863                 pass = MEM_callocN(sizeof(GPUPass), "GPUPass");
1864                 pass->shader = NULL;
1865                 pass->refcount = 1;
1866                 pass->hash = hash;
1867                 pass->vertexcode = vertexcode;
1868                 pass->fragmentcode = fragmentcode;
1869                 pass->geometrycode = geometrycode;
1870                 pass->defines = (defines) ? BLI_strdup(defines) : NULL;
1871                 pass->compiled = false;
1872
1873                 BLI_spin_lock(&pass_cache_spin);
1874                 if (pass_hash != NULL) {
1875                         /* Add after the first pass having the same hash. */
1876                         pass->next = pass_hash->next;
1877                         pass_hash->next = pass;
1878                 }
1879                 else {
1880                         /* No other pass have same hash, just prepend to the list. */
1881                         BLI_LINKS_PREPEND(pass_cache, pass);
1882                 }
1883                 BLI_spin_unlock(&pass_cache_spin);
1884         }
1885
1886         return pass;
1887 }
1888
1889 static int count_active_texture_sampler(GPUShader *shader, char *source)
1890 {
1891         char *code = source;
1892         int samplers_id[64]; /* Remember this is per stage. */
1893         int sampler_len = 0;
1894
1895         while ((code = strstr(code, "uniform "))) {
1896                 /* Move past "uniform". */
1897                 code += 7;
1898                 /* Skip following spaces. */
1899                 while (*code == ' ') { code++; }
1900                 /* Skip "i" from potential isamplers. */
1901                 if (*code == 'i') { code++; }
1902                 /* Skip following spaces. */
1903                 if (gpu_str_prefix(code, "sampler")) {
1904                         /* Move past "uniform". */
1905                         code += 7;
1906                         /* Skip sampler type suffix. */
1907                         while (*code != ' ' && *code != '\0') { code++; }
1908                         /* Skip following spaces. */
1909                         while (*code == ' ') { code++; }
1910
1911                         if (*code != '\0') {
1912                                 char sampler_name[64];
1913                                 code = gpu_str_skip_token(code, sampler_name, sizeof(sampler_name));
1914                                 int id = GPU_shader_get_uniform_ensure(shader, sampler_name);
1915
1916                                 if (id == -1) {
1917                                         continue;
1918                                 }
1919                                 /* Catch duplicates. */
1920                                 bool is_duplicate = false;
1921                                 for (int i = 0; i < sampler_len; ++i) {
1922                                         if (samplers_id[i] == id) {
1923                                                 is_duplicate = true;
1924                                         }
1925                                 }
1926
1927                                 if (!is_duplicate) {
1928                                         samplers_id[sampler_len] = id;
1929                                         sampler_len++;
1930                                 }
1931                         }
1932                 }
1933         }
1934
1935         return sampler_len;
1936 }
1937
1938 static bool gpu_pass_shader_validate(GPUPass *pass)
1939 {
1940         if (pass->shader == NULL) {
1941                 return false;
1942         }
1943
1944         /* NOTE: The only drawback of this method is that it will count a sampler
1945          * used in the fragment shader and only declared (but not used) in the vertex
1946          * shader as used by both. But this corner case is not happening for now. */
1947         int vert_samplers_len = count_active_texture_sampler(pass->shader, pass->vertexcode);
1948         int frag_samplers_len = count_active_texture_sampler(pass->shader, pass->fragmentcode);
1949
1950         int total_samplers_len = vert_samplers_len + frag_samplers_len;
1951
1952         /* Validate against opengl limit. */
1953         if ((frag_samplers_len > GPU_max_textures_frag()) ||
1954             (frag_samplers_len > GPU_max_textures_vert()))
1955         {
1956                 return false;
1957         }
1958
1959         if (pass->geometrycode) {
1960                 int geom_samplers_len = count_active_texture_sampler(pass->shader, pass->geometrycode);
1961                 total_samplers_len += geom_samplers_len;
1962                 if (geom_samplers_len > GPU_max_textures_geom()) {
1963                         return false;
1964                 }
1965         }
1966
1967         return (total_samplers_len <= GPU_max_textures());
1968 }
1969
1970 void GPU_pass_compile(GPUPass *pass, const char *shname)
1971 {
1972         if (!pass->compiled) {
1973                 pass->shader = GPU_shader_create(
1974                         pass->vertexcode,
1975                         pass->fragmentcode,
1976                         pass->geometrycode,
1977                         NULL,
1978                         pass->defines,
1979                         shname);
1980
1981                 /* NOTE: Some drivers / gpu allows more active samplers than the opengl limit.
1982                  * We need to make sure to count active samplers to avoid undefined behavior. */
1983                 if (!gpu_pass_shader_validate(pass)) {
1984                         if (pass->shader != NULL) {
1985                                 fprintf(stderr, "GPUShader: error: too many samplers in shader.\n");
1986                                 GPU_shader_free(pass->shader);
1987                         }
1988                         pass->shader = NULL;
1989                 }
1990                 else if (!BLI_thread_is_main()) {
1991                         /* For some Intel drivers, you must use the program at least once
1992                          * in the rendering context that it is linked. */
1993                         glUseProgram(GPU_shader_get_program(pass->shader));
1994                         glUseProgram(0);
1995                 }
1996
1997                 pass->compiled = true;
1998         }
1999 }
2000
2001 void GPU_pass_release(GPUPass *pass)
2002 {
2003         BLI_assert(pass->refcount > 0);
2004         pass->refcount--;
2005 }
2006
2007 static void gpu_pass_free(GPUPass *pass)
2008 {
2009         BLI_assert(pass->refcount == 0);
2010         if (pass->shader) {
2011                 GPU_shader_free(pass->shader);
2012         }
2013         MEM_SAFE_FREE(pass->fragmentcode);
2014         MEM_SAFE_FREE(pass->geometrycode);
2015         MEM_SAFE_FREE(pass->vertexcode);
2016         MEM_SAFE_FREE(pass->defines);
2017         MEM_freeN(pass);
2018 }
2019
2020 void GPU_pass_free_nodes(ListBase *nodes)
2021 {
2022         gpu_nodes_free(nodes);
2023 }
2024
2025 void GPU_pass_cache_garbage_collect(void)
2026 {
2027         static int lasttime = 0;
2028         const int shadercollectrate = 60; /* hardcoded for now. */
2029         int ctime = (int)PIL_check_seconds_timer();
2030
2031         if (ctime < shadercollectrate + lasttime)
2032                 return;
2033
2034         lasttime = ctime;
2035
2036         BLI_spin_lock(&pass_cache_spin);
2037         GPUPass *next, **prev_pass = &pass_cache;
2038         for (GPUPass *pass = pass_cache; pass; pass = next) {
2039                 next = pass->next;
2040                 if (pass->refcount == 0) {
2041                         /* Remove from list */
2042                         *prev_pass = next;
2043                         gpu_pass_free(pass);
2044                 }
2045                 else {
2046                         prev_pass = &pass->next;
2047                 }
2048         }
2049         BLI_spin_unlock(&pass_cache_spin);
2050 }
2051
2052 void GPU_pass_cache_init(void)
2053 {
2054         BLI_spin_init(&pass_cache_spin);
2055 }
2056
2057 void GPU_pass_cache_free(void)
2058 {
2059         BLI_spin_lock(&pass_cache_spin);
2060         while (pass_cache) {
2061                 GPUPass *next = pass_cache->next;
2062                 gpu_pass_free(pass_cache);
2063                 pass_cache = next;
2064         }
2065         BLI_spin_unlock(&pass_cache_spin);
2066
2067         BLI_spin_end(&pass_cache_spin);
2068 }