Fix T43427: Particle system children sometimes not generated on reload
[blender.git] / source / blender / render / intern / source / render_texture.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): 2004-2006, Blender Foundation, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/render/intern/source/render_texture.c
27  *  \ingroup render
28  */
29
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <math.h>
35
36 #include "BLI_math.h"
37 #include "BLI_noise.h"
38 #include "BLI_rand.h"
39 #include "BLI_utildefines.h"
40
41 #include "DNA_anim_types.h"
42 #include "DNA_texture_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_lamp_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_image_types.h"
48 #include "DNA_node_types.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_colormanagement.h"
52
53 #include "BKE_image.h"
54 #include "BKE_node.h"
55
56 #include "BKE_animsys.h"
57 #include "BKE_DerivedMesh.h"
58 #include "BKE_global.h"
59 #include "BKE_main.h"
60 #include "BKE_material.h"
61 #include "BKE_scene.h"
62
63 #include "BKE_texture.h"
64
65 #include "MEM_guardedalloc.h"
66
67 #include "envmap.h"
68 #include "pointdensity.h"
69 #include "voxeldata.h"
70 #include "render_types.h"
71 #include "shading.h"
72 #include "texture.h"
73 #include "texture_ocean.h"
74
75 #include "renderdatabase.h" /* needed for UV */
76
77 #include "RE_render_ext.h"
78
79 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
80 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
81 /* only to be used here in this file, it's for speed */
82 extern struct Render R;
83 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
84
85 static RNG_THREAD_ARRAY *random_tex_array;
86
87
88 void RE_init_texture_rng(void)
89 {
90         random_tex_array = BLI_rng_threaded_new();
91 }
92
93 void RE_exit_texture_rng(void)
94 {
95         BLI_rng_threaded_free(random_tex_array);
96 }
97
98
99 static void init_render_texture(Render *re, Tex *tex)
100 {
101         /* imap test */
102         if (tex->ima && BKE_image_is_animated(tex->ima)) {
103                 BKE_image_user_frame_calc(&tex->iuser, re ? re->r.cfra : 0, re ? re->flag & R_SEC_FIELD:0);
104         }
105         
106         else if (tex->type==TEX_ENVMAP) {
107                 /* just in case */
108                 tex->imaflag |= TEX_INTERPOL | TEX_MIPMAP;
109                 tex->extend= TEX_CLIP;
110                 
111                 if (tex->env) {
112                         if (tex->env->type==ENV_PLANE)
113                                 tex->extend= TEX_EXTEND;
114                         
115                         /* only free envmap when rendermode was set to render envmaps, for previewrender */
116                         if (G.is_rendering && re) {
117                                 if (re->r.mode & R_ENVMAP)
118                                         if (tex->env->stype==ENV_ANIM)
119                                                 BKE_free_envmapdata(tex->env);
120                         }
121                 }
122         }
123         
124         if (tex->nodetree && tex->use_nodes) {
125                 ntreeTexBeginExecTree(tex->nodetree); /* has internal flag to detect it only does it once */
126         }
127 }
128
129 /* ------------------------------------------------------------------------- */
130
131 void init_render_textures(Render *re)
132 {
133         Tex *tex;
134         
135         tex= re->main->tex.first;
136         while (tex) {
137                 if (tex->id.us) init_render_texture(re, tex);
138                 tex= tex->id.next;
139         }
140 }
141
142 static void end_render_texture(Tex *tex)
143 {
144         if (tex && tex->use_nodes && tex->nodetree && tex->nodetree->execdata)
145                 ntreeTexEndExecTree(tex->nodetree->execdata);
146 }
147
148 void end_render_textures(Render *re)
149 {
150         Tex *tex;
151         for (tex= re->main->tex.first; tex; tex= tex->id.next)
152                 if (tex->id.us)
153                         end_render_texture(tex);
154 }
155
156 /* ------------------------------------------------------------------------- */
157
158
159 /* this allows colorbanded textures to control normals as well */
160 static void tex_normal_derivate(Tex *tex, TexResult *texres)
161 {
162         if (tex->flag & TEX_COLORBAND) {
163                 float col[4];
164                 if (do_colorband(tex->coba, texres->tin, col)) {
165                         float fac0, fac1, fac2, fac3;
166                         
167                         fac0= (col[0]+col[1]+col[2]);
168                         do_colorband(tex->coba, texres->nor[0], col);
169                         fac1= (col[0]+col[1]+col[2]);
170                         do_colorband(tex->coba, texres->nor[1], col);
171                         fac2= (col[0]+col[1]+col[2]);
172                         do_colorband(tex->coba, texres->nor[2], col);
173                         fac3= (col[0]+col[1]+col[2]);
174                         
175                         texres->nor[0]= (fac0 - fac1) / 3.0f;
176                         texres->nor[1]= (fac0 - fac2) / 3.0f;
177                         texres->nor[2]= (fac0 - fac3) / 3.0f;
178                         
179                         return;
180                 }
181         }
182         texres->nor[0]= texres->tin - texres->nor[0];
183         texres->nor[1]= texres->tin - texres->nor[1];
184         texres->nor[2]= texres->tin - texres->nor[2];
185 }
186
187
188
189 static int blend(Tex *tex, const float texvec[3], TexResult *texres)
190 {
191         float x, y, t;
192
193         if (tex->flag & TEX_FLIPBLEND) {
194                 x= texvec[1];
195                 y= texvec[0];
196         }
197         else {
198                 x= texvec[0];
199                 y= texvec[1];
200         }
201
202         if (tex->stype==TEX_LIN) {      /* lin */
203                 texres->tin= (1.0f+x)/2.0f;
204         }
205         else if (tex->stype==TEX_QUAD) {        /* quad */
206                 texres->tin= (1.0f+x)/2.0f;
207                 if (texres->tin<0.0f) texres->tin= 0.0f;
208                 else texres->tin*= texres->tin;
209         }
210         else if (tex->stype==TEX_EASE) {        /* ease */
211                 texres->tin= (1.0f+x)/2.0f;
212                 if (texres->tin<=0.0f) texres->tin= 0.0f;
213                 else if (texres->tin>=1.0f) texres->tin= 1.0f;
214                 else {
215                         t= texres->tin*texres->tin;
216                         texres->tin= (3.0f*t-2.0f*t*texres->tin);
217                 }
218         }
219         else if (tex->stype==TEX_DIAG) { /* diag */
220                 texres->tin= (2.0f+x+y)/4.0f;
221         }
222         else if (tex->stype==TEX_RAD) { /* radial */
223                 texres->tin = (atan2f(y, x) / (2 * M_PI) + 0.5f);
224         }
225         else {  /* sphere TEX_SPHERE */
226                 texres->tin = 1.0 - sqrtf(x * x + y * y + texvec[2] * texvec[2]);
227                 if (texres->tin<0.0f) texres->tin= 0.0f;
228                 if (tex->stype==TEX_HALO) texres->tin*= texres->tin;  /* halo */
229         }
230
231         BRICONT;
232
233         return TEX_INT;
234 }
235
236 /* ------------------------------------------------------------------------- */
237 /* ************************************************************************* */
238
239 /* newnoise: all noisebased types now have different noisebases to choose from */
240
241 static int clouds(Tex *tex, const float texvec[3], TexResult *texres)
242 {
243         int rv = TEX_INT;
244         
245         texres->tin = BLI_gTurbulence(tex->noisesize, texvec[0], texvec[1], texvec[2], tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
246
247         if (texres->nor!=NULL) {
248                 /* calculate bumpnormal */
249                 texres->nor[0] = BLI_gTurbulence(tex->noisesize, texvec[0] + tex->nabla, texvec[1], texvec[2], tex->noisedepth,  (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
250                 texres->nor[1] = BLI_gTurbulence(tex->noisesize, texvec[0], texvec[1] + tex->nabla, texvec[2], tex->noisedepth,  (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
251                 texres->nor[2] = BLI_gTurbulence(tex->noisesize, texvec[0], texvec[1], texvec[2] + tex->nabla, tex->noisedepth,  (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
252                 
253                 tex_normal_derivate(tex, texres);
254                 rv |= TEX_NOR;
255         }
256
257         if (tex->stype==TEX_COLOR) {
258                 /* in this case, int. value should really be computed from color,
259                  * and bumpnormal from that, would be too slow, looks ok as is */
260                 texres->tr = texres->tin;
261                 texres->tg = BLI_gTurbulence(tex->noisesize, texvec[1], texvec[0], texvec[2], tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
262                 texres->tb = BLI_gTurbulence(tex->noisesize, texvec[1], texvec[2], texvec[0], tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
263                 BRICONTRGB;
264                 texres->ta = 1.0;
265                 return (rv | TEX_RGB);
266         }
267
268         BRICONT;
269
270         return rv;
271
272 }
273
274 /* creates a sine wave */
275 static float tex_sin(float a)
276 {
277         a = 0.5 + 0.5 * sinf(a);
278
279         return a;
280 }
281
282 /* creates a saw wave */
283 static float tex_saw(float a)
284 {
285         const float b = 2*M_PI;
286         
287         int n = (int)(a / b);
288         a -= n*b;
289         if (a < 0) a += b;
290         return a / b;
291 }
292
293 /* creates a triangle wave */
294 static float tex_tri(float a)
295 {
296         const float b = 2*M_PI;
297         const float rmax = 1.0;
298         
299         a = rmax - 2.0f*fabsf(floorf((a*(1.0f/b))+0.5f) - (a*(1.0f/b)));
300         
301         return a;
302 }
303
304 /* computes basic wood intensity value at x,y,z */
305 static float wood_int(Tex *tex, float x, float y, float z)
306 {
307         float wi = 0;
308         short wf = tex->noisebasis2;    /* wave form:   TEX_SIN=0,  TEX_SAW=1,  TEX_TRI=2                                                */
309         short wt = tex->stype;                  /* wood type:   TEX_BAND=0, TEX_RING=1, TEX_BANDNOISE=2, TEX_RINGNOISE=3 */
310
311         float (*waveform[3])(float);    /* create array of pointers to waveform functions */
312         waveform[0] = tex_sin;                  /* assign address of tex_sin() function to pointer array */
313         waveform[1] = tex_saw;
314         waveform[2] = tex_tri;
315         
316         if ((wf>TEX_TRI) || (wf<TEX_SIN)) wf=0; /* check to be sure noisebasis2 is initialized ahead of time */
317                 
318         if (wt==TEX_BAND) {
319                 wi = waveform[wf]((x + y + z)*10.0f);
320         }
321         else if (wt==TEX_RING) {
322                 wi = waveform[wf](sqrtf(x*x + y*y + z*z)*20.0f);
323         }
324         else if (wt==TEX_BANDNOISE) {
325                 wi = tex->turbul*BLI_gNoise(tex->noisesize, x, y, z, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
326                 wi = waveform[wf]((x + y + z)*10.0f + wi);
327         }
328         else if (wt==TEX_RINGNOISE) {
329                 wi = tex->turbul*BLI_gNoise(tex->noisesize, x, y, z, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
330                 wi = waveform[wf](sqrtf(x*x + y*y + z*z)*20.0f + wi);
331         }
332         
333         return wi;
334 }
335
336 static int wood(Tex *tex, const float texvec[3], TexResult *texres)
337 {
338         int rv=TEX_INT;
339
340         texres->tin = wood_int(tex, texvec[0], texvec[1], texvec[2]);
341         if (texres->nor!=NULL) {
342                 /* calculate bumpnormal */
343                 texres->nor[0] = wood_int(tex, texvec[0] + tex->nabla, texvec[1], texvec[2]);
344                 texres->nor[1] = wood_int(tex, texvec[0], texvec[1] + tex->nabla, texvec[2]);
345                 texres->nor[2] = wood_int(tex, texvec[0], texvec[1], texvec[2] + tex->nabla);
346                 
347                 tex_normal_derivate(tex, texres);
348                 rv |= TEX_NOR;
349         }
350
351         BRICONT;
352
353         return rv;
354 }
355
356 /* computes basic marble intensity at x,y,z */
357 static float marble_int(Tex *tex, float x, float y, float z)
358 {
359         float n, mi;
360         short wf = tex->noisebasis2;    /* wave form:   TEX_SIN=0,  TEX_SAW=1,  TEX_TRI=2                                               */
361         short mt = tex->stype;                  /* marble type: TEX_SOFT=0,     TEX_SHARP=1,TEX_SHAPER=2                                        */
362         
363         float (*waveform[3])(float);    /* create array of pointers to waveform functions */
364         waveform[0] = tex_sin;                  /* assign address of tex_sin() function to pointer array */
365         waveform[1] = tex_saw;
366         waveform[2] = tex_tri;
367         
368         if ((wf>TEX_TRI) || (wf<TEX_SIN)) wf=0; /* check to be sure noisebasis2 isn't initialized ahead of time */
369         
370         n = 5.0f * (x + y + z);
371         
372         mi = n + tex->turbul * BLI_gTurbulence(tex->noisesize, x, y, z, tex->noisedepth, (tex->noisetype!=TEX_NOISESOFT),  tex->noisebasis);
373
374         if (mt>=TEX_SOFT) {  /* TEX_SOFT always true */
375                 mi = waveform[wf](mi);
376                 if (mt==TEX_SHARP) {
377                         mi = sqrtf(mi);
378                 }
379                 else if (mt==TEX_SHARPER) {
380                         mi = sqrtf(sqrtf(mi));
381                 }
382         }
383
384         return mi;
385 }
386
387 static int marble(Tex *tex, const float texvec[3], TexResult *texres)
388 {
389         int rv=TEX_INT;
390
391         texres->tin = marble_int(tex, texvec[0], texvec[1], texvec[2]);
392
393         if (texres->nor!=NULL) {
394                 /* calculate bumpnormal */
395                 texres->nor[0] = marble_int(tex, texvec[0] + tex->nabla, texvec[1], texvec[2]);
396                 texres->nor[1] = marble_int(tex, texvec[0], texvec[1] + tex->nabla, texvec[2]);
397                 texres->nor[2] = marble_int(tex, texvec[0], texvec[1], texvec[2] + tex->nabla);
398                 
399                 tex_normal_derivate(tex, texres);
400                 
401                 rv |= TEX_NOR;
402         }
403
404         BRICONT;
405
406         return rv;
407 }
408
409 /* ------------------------------------------------------------------------- */
410
411 static int magic(Tex *tex, const float texvec[3], TexResult *texres)
412 {
413         float x, y, z, turb;
414         int n;
415
416         n= tex->noisedepth;
417         turb= tex->turbul/5.0f;
418
419         x =  sinf(( texvec[0] + texvec[1] + texvec[2]) * 5.0f);
420         y =  cosf((-texvec[0] + texvec[1] - texvec[2]) * 5.0f);
421         z = -cosf((-texvec[0] - texvec[1] + texvec[2]) * 5.0f);
422         if (n>0) {
423                 x*= turb;
424                 y*= turb;
425                 z*= turb;
426                 y= -cosf(x-y+z);
427                 y*= turb;
428                 if (n>1) {
429                         x= cosf(x-y-z);
430                         x*= turb;
431                         if (n>2) {
432                                 z= sinf(-x-y-z);
433                                 z*= turb;
434                                 if (n>3) {
435                                         x= -cosf(-x+y-z);
436                                         x*= turb;
437                                         if (n>4) {
438                                                 y= -sinf(-x+y+z);
439                                                 y*= turb;
440                                                 if (n>5) {
441                                                         y= -cosf(-x+y+z);
442                                                         y*= turb;
443                                                         if (n>6) {
444                                                                 x= cosf(x+y+z);
445                                                                 x*= turb;
446                                                                 if (n>7) {
447                                                                         z= sinf(x+y-z);
448                                                                         z*= turb;
449                                                                         if (n>8) {
450                                                                                 x= -cosf(-x-y+z);
451                                                                                 x*= turb;
452                                                                                 if (n>9) {
453                                                                                         y= -sinf(x-y+z);
454                                                                                         y*= turb;
455                                                                                 }
456                                                                         }
457                                                                 }
458                                                         }
459                                                 }
460                                         }
461                                 }
462                         }
463                 }
464         }
465
466         if (turb!=0.0f) {
467                 turb*= 2.0f;
468                 x/= turb; 
469                 y/= turb; 
470                 z/= turb;
471         }
472         texres->tr = 0.5f - x;
473         texres->tg = 0.5f - y;
474         texres->tb = 0.5f - z;
475
476         texres->tin= (1.0f / 3.0f) * (texres->tr + texres->tg + texres->tb);
477         
478         BRICONTRGB;
479         texres->ta = 1.0f;
480         
481         return TEX_RGB;
482 }
483
484 /* ------------------------------------------------------------------------- */
485
486 /* newnoise: stucci also modified to use different noisebasis */
487 static int stucci(Tex *tex, const float texvec[3], TexResult *texres)
488 {
489         float nor[3], b2, ofs;
490         int retval= TEX_INT;
491         
492         b2= BLI_gNoise(tex->noisesize, texvec[0], texvec[1], texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
493         
494         ofs= tex->turbul/200.0f;
495
496         if (tex->stype) ofs*=(b2*b2);
497         nor[0] = BLI_gNoise(tex->noisesize, texvec[0]+ofs, texvec[1], texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
498         nor[1] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1]+ofs, texvec[2], (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
499         nor[2] = BLI_gNoise(tex->noisesize, texvec[0], texvec[1], texvec[2]+ofs, (tex->noisetype!=TEX_NOISESOFT), tex->noisebasis);
500
501         texres->tin= nor[2];
502         
503         if (texres->nor) {
504                 
505                 copy_v3_v3(texres->nor, nor);
506                 tex_normal_derivate(tex, texres);
507                 
508                 if (tex->stype==TEX_WALLOUT) {
509                         texres->nor[0]= -texres->nor[0];
510                         texres->nor[1]= -texres->nor[1];
511                         texres->nor[2]= -texres->nor[2];
512                 }
513                 
514                 retval |= TEX_NOR;
515         }
516         
517         if (tex->stype==TEX_WALLOUT)
518                 texres->tin= 1.0f-texres->tin;
519         
520         if (texres->tin<0.0f)
521                 texres->tin= 0.0f;
522         
523         return retval;
524 }
525
526 /* ------------------------------------------------------------------------- */
527 /* newnoise: musgrave terrain noise types */
528
529 static float mg_mFractalOrfBmTex(Tex *tex, const float texvec[3], TexResult *texres)
530 {
531         int rv = TEX_INT;
532         float (*mgravefunc)(float, float, float, float, float, float, int);
533
534         if (tex->stype==TEX_MFRACTAL)
535                 mgravefunc = mg_MultiFractal;
536         else
537                 mgravefunc = mg_fBm;
538
539         texres->tin = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
540
541         if (texres->nor!=NULL) {
542                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
543
544                 /* calculate bumpnormal */
545                 texres->nor[0] = tex->ns_outscale*mgravefunc(texvec[0] + offs, texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
546                 texres->nor[1] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1] + offs, texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
547                 texres->nor[2] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2] + offs, tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->noisebasis);
548                 
549                 tex_normal_derivate(tex, texres);
550                 rv |= TEX_NOR;
551         }
552
553         BRICONT;
554
555         return rv;
556
557 }
558
559 static float mg_ridgedOrHybridMFTex(Tex *tex, const float texvec[3], TexResult *texres)
560 {
561         int rv = TEX_INT;
562         float (*mgravefunc)(float, float, float, float, float, float, float, float, int);
563
564         if (tex->stype==TEX_RIDGEDMF)
565                 mgravefunc = mg_RidgedMultiFractal;
566         else
567                 mgravefunc = mg_HybridMultiFractal;
568
569         texres->tin = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
570
571         if (texres->nor!=NULL) {
572                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
573
574                 /* calculate bumpnormal */
575                 texres->nor[0] = tex->ns_outscale*mgravefunc(texvec[0] + offs, texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
576                 texres->nor[1] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1] + offs, texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
577                 texres->nor[2] = tex->ns_outscale*mgravefunc(texvec[0], texvec[1], texvec[2] + offs, tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->mg_gain, tex->noisebasis);
578                 
579                 tex_normal_derivate(tex, texres);
580                 rv |= TEX_NOR;
581         }
582
583         BRICONT;
584
585         return rv;
586
587 }
588
589
590 static float mg_HTerrainTex(Tex *tex, const float texvec[3], TexResult *texres)
591 {
592         int rv = TEX_INT;
593
594         texres->tin = tex->ns_outscale*mg_HeteroTerrain(texvec[0], texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
595
596         if (texres->nor!=NULL) {
597                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
598
599                 /* calculate bumpnormal */
600                 texres->nor[0] = tex->ns_outscale*mg_HeteroTerrain(texvec[0] + offs, texvec[1], texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
601                 texres->nor[1] = tex->ns_outscale*mg_HeteroTerrain(texvec[0], texvec[1] + offs, texvec[2], tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
602                 texres->nor[2] = tex->ns_outscale*mg_HeteroTerrain(texvec[0], texvec[1], texvec[2] + offs, tex->mg_H, tex->mg_lacunarity, tex->mg_octaves, tex->mg_offset, tex->noisebasis);
603                 
604                 tex_normal_derivate(tex, texres);
605                 rv |= TEX_NOR;
606         }
607
608         BRICONT;
609
610         return rv;
611
612 }
613
614
615 static float mg_distNoiseTex(Tex *tex, const float texvec[3], TexResult *texres)
616 {
617         int rv = TEX_INT;
618
619         texres->tin = mg_VLNoise(texvec[0], texvec[1], texvec[2], tex->dist_amount, tex->noisebasis, tex->noisebasis2);
620
621         if (texres->nor!=NULL) {
622                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
623
624                 /* calculate bumpnormal */
625                 texres->nor[0] = mg_VLNoise(texvec[0] + offs, texvec[1], texvec[2], tex->dist_amount, tex->noisebasis, tex->noisebasis2);
626                 texres->nor[1] = mg_VLNoise(texvec[0], texvec[1] + offs, texvec[2], tex->dist_amount, tex->noisebasis, tex->noisebasis2);
627                 texres->nor[2] = mg_VLNoise(texvec[0], texvec[1], texvec[2] + offs, tex->dist_amount, tex->noisebasis, tex->noisebasis2);
628
629                 tex_normal_derivate(tex, texres);
630                 rv |= TEX_NOR;
631         }
632
633         BRICONT;
634
635
636         return rv;
637
638 }
639
640
641 /* ------------------------------------------------------------------------- */
642 /* newnoise: Voronoi texture type, probably the slowest, especially with minkovsky, bumpmapping, could be done another way */
643
644 static float voronoiTex(Tex *tex, const float texvec[3], TexResult *texres)
645 {
646         int rv = TEX_INT;
647         float da[4], pa[12];    /* distance and point coordinate arrays of 4 nearest neighbors */
648         float aw1 = fabsf(tex->vn_w1);
649         float aw2 = fabsf(tex->vn_w2);
650         float aw3 = fabsf(tex->vn_w3);
651         float aw4 = fabsf(tex->vn_w4);
652         float sc = (aw1 + aw2 + aw3 + aw4);
653         if (sc!=0.f) sc =  tex->ns_outscale/sc;
654
655         voronoi(texvec[0], texvec[1], texvec[2], da, pa, tex->vn_mexp, tex->vn_distm);
656         texres->tin = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
657
658         if (tex->vn_coltype) {
659                 float ca[3];    /* cell color */
660                 cellNoiseV(pa[0], pa[1], pa[2], ca);
661                 texres->tr = aw1*ca[0];
662                 texres->tg = aw1*ca[1];
663                 texres->tb = aw1*ca[2];
664                 cellNoiseV(pa[3], pa[4], pa[5], ca);
665                 texres->tr += aw2*ca[0];
666                 texres->tg += aw2*ca[1];
667                 texres->tb += aw2*ca[2];
668                 cellNoiseV(pa[6], pa[7], pa[8], ca);
669                 texres->tr += aw3*ca[0];
670                 texres->tg += aw3*ca[1];
671                 texres->tb += aw3*ca[2];
672                 cellNoiseV(pa[9], pa[10], pa[11], ca);
673                 texres->tr += aw4*ca[0];
674                 texres->tg += aw4*ca[1];
675                 texres->tb += aw4*ca[2];
676                 if (tex->vn_coltype>=2) {
677                         float t1 = (da[1]-da[0])*10;
678                         if (t1>1) t1=1;
679                         if (tex->vn_coltype==3) t1*=texres->tin; else t1*=sc;
680                         texres->tr *= t1;
681                         texres->tg *= t1;
682                         texres->tb *= t1;
683                 }
684                 else {
685                         texres->tr *= sc;
686                         texres->tg *= sc;
687                         texres->tb *= sc;
688                 }
689         }
690
691         if (texres->nor!=NULL) {
692                 float offs= tex->nabla/tex->noisesize;  /* also scaling of texvec */
693
694                 /* calculate bumpnormal */
695                 voronoi(texvec[0] + offs, texvec[1], texvec[2], da, pa, tex->vn_mexp,  tex->vn_distm);
696                 texres->nor[0] = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
697                 voronoi(texvec[0], texvec[1] + offs, texvec[2], da, pa, tex->vn_mexp,  tex->vn_distm);
698                 texres->nor[1] = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
699                 voronoi(texvec[0], texvec[1], texvec[2] + offs, da, pa, tex->vn_mexp,  tex->vn_distm);
700                 texres->nor[2] = sc * fabsf(tex->vn_w1*da[0] + tex->vn_w2*da[1] + tex->vn_w3*da[2] + tex->vn_w4*da[3]);
701                 
702                 tex_normal_derivate(tex, texres);
703                 rv |= TEX_NOR;
704         }
705
706         if (tex->vn_coltype) {
707                 BRICONTRGB;
708                 texres->ta = 1.0;
709                 return (rv | TEX_RGB);
710         }
711         
712         BRICONT;
713
714         return rv;
715
716 }
717
718 /* ------------------------------------------------------------------------- */
719
720 static int texnoise(Tex *tex, TexResult *texres, int thread)
721 {
722         float div=3.0;
723         int val, ran, loop, shift = 29;
724         
725         ran=  BLI_rng_thread_rand(random_tex_array, thread);
726         
727         loop= tex->noisedepth;
728
729         /* start from top bits since they have more variance */
730         val= ((ran >> shift) & 3);
731         
732         while (loop--) {
733                 shift -= 2;             
734                 val *= ((ran >> shift) & 3);
735                 div *= 3.0f;
736         }
737         
738         texres->tin= ((float)val)/div;
739
740         BRICONT;
741         return TEX_INT;
742 }
743
744 /* ------------------------------------------------------------------------- */
745
746 static int cubemap_glob(const float n[3], float x, float y, float z, float *adr1, float *adr2)
747 {
748         float x1, y1, z1, nor[3];
749         int ret;
750         
751         if (n==NULL) {
752                 nor[0]= x; nor[1]= y; nor[2]= z;        /* use local render coord */
753         }
754         else {
755                 copy_v3_v3(nor, n);
756         }
757         mul_mat3_m4_v3(R.viewinv, nor);
758
759         x1 = fabsf(nor[0]);
760         y1 = fabsf(nor[1]);
761         z1 = fabsf(nor[2]);
762         
763         if (z1>=x1 && z1>=y1) {
764                 *adr1 = (x + 1.0f) / 2.0f;
765                 *adr2 = (y + 1.0f) / 2.0f;
766                 ret= 0;
767         }
768         else if (y1>=x1 && y1>=z1) {
769                 *adr1 = (x + 1.0f) / 2.0f;
770                 *adr2 = (z + 1.0f) / 2.0f;
771                 ret= 1;
772         }
773         else {
774                 *adr1 = (y + 1.0f) / 2.0f;
775                 *adr2 = (z + 1.0f) / 2.0f;
776                 ret= 2;
777         }
778         return ret;
779 }
780
781 /* ------------------------------------------------------------------------- */
782
783 /* mtex argument only for projection switches */
784 static int cubemap(MTex *mtex, VlakRen *vlr, const float n[3], float x, float y, float z, float *adr1, float *adr2)
785 {
786         int proj[4]={0, ME_PROJXY, ME_PROJXZ, ME_PROJYZ}, ret= 0;
787         
788         if (vlr) {
789                 int index;
790                 
791                 /* Mesh vertices have such flags, for others we calculate it once based on orco */
792                 if ((vlr->puno & (ME_PROJXY|ME_PROJXZ|ME_PROJYZ))==0) {
793                         /* test for v1, vlr can be faked for baking */
794                         if (vlr->v1 && vlr->v1->orco) {
795                                 float nor[3];
796                                 normal_tri_v3(nor, vlr->v1->orco, vlr->v2->orco, vlr->v3->orco);
797                                 
798                                 if      (fabsf(nor[0]) < fabsf(nor[2]) && fabsf(nor[1]) < fabsf(nor[2])) vlr->puno |= ME_PROJXY;
799                                 else if (fabsf(nor[0]) < fabsf(nor[1]) && fabsf(nor[2]) < fabsf(nor[1])) vlr->puno |= ME_PROJXZ;
800                                 else                                                                     vlr->puno |= ME_PROJYZ;
801                         }
802                         else return cubemap_glob(n, x, y, z, adr1, adr2);
803                 }
804                 
805                 if (mtex) {
806                         /* the mtex->proj{xyz} have type char. maybe this should be wider? */
807                         /* casting to int ensures that the index type is right.            */
808                         index = (int) mtex->projx;
809                         proj[index]= ME_PROJXY;
810
811                         index = (int) mtex->projy;
812                         proj[index]= ME_PROJXZ;
813
814                         index = (int) mtex->projz;
815                         proj[index]= ME_PROJYZ;
816                 }
817                 
818                 if (vlr->puno & proj[1]) {
819                         *adr1 = (x + 1.0f) / 2.0f;
820                         *adr2 = (y + 1.0f) / 2.0f;
821                 }
822                 else if (vlr->puno & proj[2]) {
823                         *adr1 = (x + 1.0f) / 2.0f;
824                         *adr2 = (z + 1.0f) / 2.0f;
825                         ret= 1;
826                 }
827                 else {
828                         *adr1 = (y + 1.0f) / 2.0f;
829                         *adr2 = (z + 1.0f) / 2.0f;
830                         ret= 2;
831                 }
832         }
833         else {
834                 return cubemap_glob(n, x, y, z, adr1, adr2);
835         }
836         
837         return ret;
838 }
839
840 /* ------------------------------------------------------------------------- */
841
842 static int cubemap_ob(Object *ob, const float n[3], float x, float y, float z, float *adr1, float *adr2)
843 {
844         float x1, y1, z1, nor[3];
845         int ret;
846         
847         if (n==NULL) return 0;
848         
849         copy_v3_v3(nor, n);
850         if (ob) mul_mat3_m4_v3(ob->imat, nor);
851         
852         x1 = fabsf(nor[0]);
853         y1 = fabsf(nor[1]);
854         z1 = fabsf(nor[2]);
855         
856         if (z1>=x1 && z1>=y1) {
857                 *adr1 = (x + 1.0f) / 2.0f;
858                 *adr2 = (y + 1.0f) / 2.0f;
859                 ret= 0;
860         }
861         else if (y1>=x1 && y1>=z1) {
862                 *adr1 = (x + 1.0f) / 2.0f;
863                 *adr2 = (z + 1.0f) / 2.0f;
864                 ret= 1;
865         }
866         else {
867                 *adr1 = (y + 1.0f) / 2.0f;
868                 *adr2 = (z + 1.0f) / 2.0f;
869                 ret= 2;
870         }
871         return ret;
872 }
873
874 /* ------------------------------------------------------------------------- */
875
876 static void do_2d_mapping(MTex *mtex, float texvec[3], VlakRen *vlr, const float n[3], float dxt[3], float dyt[3])
877 {
878         Tex *tex;
879         Object *ob= NULL;
880         float fx, fy, fac1, area[8];
881         int ok, proj, areaflag= 0, wrap, texco;
882         
883         /* mtex variables localized, only cubemap doesn't cooperate yet... */
884         wrap= mtex->mapping;
885         tex= mtex->tex;
886         ob= mtex->object;
887         texco= mtex->texco;
888
889         if (R.osa==0) {
890                 
891                 if (wrap==MTEX_FLAT) {
892                         fx = (texvec[0] + 1.0f) / 2.0f;
893                         fy = (texvec[1] + 1.0f) / 2.0f;
894                 }
895                 else if (wrap == MTEX_TUBE)   map_to_tube( &fx, &fy, texvec[0], texvec[1], texvec[2]);
896                 else if (wrap == MTEX_SPHERE) map_to_sphere(&fx, &fy, texvec[0], texvec[1], texvec[2]);
897                 else {
898                         if      (texco == TEXCO_OBJECT) cubemap_ob(ob, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
899                         else if (texco == TEXCO_GLOB)   cubemap_glob(n, texvec[0], texvec[1], texvec[2], &fx, &fy);
900                         else                            cubemap(mtex, vlr, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
901                 }
902                 
903                 /* repeat */
904                 if (tex->extend==TEX_REPEAT) {
905                         if (tex->xrepeat>1) {
906                                 float origf= fx *= tex->xrepeat;
907                                 
908                                 if (fx>1.0f) fx -= (int)(fx);
909                                 else if (fx<0.0f) fx+= 1-(int)(fx);
910                                 
911                                 if (tex->flag & TEX_REPEAT_XMIR) {
912                                         int orig= (int)floor(origf);
913                                         if (orig & 1)
914                                                 fx= 1.0f-fx;
915                                 }
916                         }
917                         if (tex->yrepeat>1) {
918                                 float origf= fy *= tex->yrepeat;
919                                 
920                                 if (fy>1.0f) fy -= (int)(fy);
921                                 else if (fy<0.0f) fy+= 1-(int)(fy);
922                                 
923                                 if (tex->flag & TEX_REPEAT_YMIR) {
924                                         int orig= (int)floor(origf);
925                                         if (orig & 1)
926                                                 fy= 1.0f-fy;
927                                 }
928                         }
929                 }
930                 /* crop */
931                 if (tex->cropxmin!=0.0f || tex->cropxmax!=1.0f) {
932                         fac1= tex->cropxmax - tex->cropxmin;
933                         fx= tex->cropxmin+ fx*fac1;
934                 }
935                 if (tex->cropymin!=0.0f || tex->cropymax!=1.0f) {
936                         fac1= tex->cropymax - tex->cropymin;
937                         fy= tex->cropymin+ fy*fac1;
938                 }
939
940                 texvec[0]= fx;
941                 texvec[1]= fy;
942         }
943         else {
944                 
945                 if (wrap==MTEX_FLAT) {
946                         fx= (texvec[0] + 1.0f) / 2.0f;
947                         fy= (texvec[1] + 1.0f) / 2.0f;
948                         dxt[0]/= 2.0f;
949                         dxt[1]/= 2.0f;
950                         dxt[2]/= 2.0f;
951                         dyt[0]/= 2.0f;
952                         dyt[1]/= 2.0f;
953                         dyt[2]/= 2.0f;
954                 }
955                 else if (ELEM(wrap, MTEX_TUBE, MTEX_SPHERE)) {
956                         /* exception: the seam behind (y<0.0) */
957                         ok= 1;
958                         if (texvec[1]<=0.0f) {
959                                 fx= texvec[0]+dxt[0];
960                                 fy= texvec[0]+dyt[0];
961                                 if (fx>=0.0f && fy>=0.0f && texvec[0]>=0.0f) {
962                                         /* pass */
963                                 }
964                                 else if (fx<=0.0f && fy<=0.0f && texvec[0]<=0.0f) {
965                                         /* pass */
966                                 }
967                                 else {
968                                         ok = 0;
969                                 }
970                         }
971
972                         if (ok) {
973                                 if (wrap==MTEX_TUBE) {
974                                         map_to_tube(area, area+1, texvec[0], texvec[1], texvec[2]);
975                                         map_to_tube(area + 2, area + 3, texvec[0] + dxt[0], texvec[1] + dxt[1], texvec[2] + dxt[2]);
976                                         map_to_tube(area + 4, area + 5, texvec[0] + dyt[0], texvec[1] + dyt[1], texvec[2] + dyt[2]);
977                                 }
978                                 else {
979                                         map_to_sphere(area, area+1, texvec[0], texvec[1], texvec[2]);
980                                         map_to_sphere(area + 2, area + 3, texvec[0] + dxt[0], texvec[1] + dxt[1], texvec[2] + dxt[2]);
981                                         map_to_sphere(area + 4, area + 5, texvec[0] + dyt[0], texvec[1] + dyt[1], texvec[2] + dyt[2]);
982                                 }
983                                 areaflag= 1;
984                         }
985                         else {
986                                 if (wrap==MTEX_TUBE) map_to_tube( &fx, &fy, texvec[0], texvec[1], texvec[2]);
987                                 else map_to_sphere(&fx, &fy, texvec[0], texvec[1], texvec[2]);
988                                 dxt[0]/= 2.0f;
989                                 dxt[1]/= 2.0f;
990                                 dyt[0]/= 2.0f;
991                                 dyt[1]/= 2.0f;
992                         }
993                 }
994                 else {
995
996                         if (texco==TEXCO_OBJECT) proj = cubemap_ob(ob, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
997                         else if (texco==TEXCO_GLOB) proj = cubemap_glob(n, texvec[0], texvec[1], texvec[2], &fx, &fy);
998                         else proj = cubemap(mtex, vlr, n, texvec[0], texvec[1], texvec[2], &fx, &fy);
999
1000                         if (proj==1) {
1001                                 SWAP(float, dxt[1], dxt[2]);
1002                                 SWAP(float, dyt[1], dyt[2]);
1003                         }
1004                         else if (proj==2) {
1005                                 float f1= dxt[0], f2= dyt[0];
1006                                 dxt[0]= dxt[1];
1007                                 dyt[0]= dyt[1];
1008                                 dxt[1]= dxt[2];
1009                                 dyt[1]= dyt[2];
1010                                 dxt[2]= f1;
1011                                 dyt[2]= f2;
1012                         }
1013
1014                         dxt[0] *= 0.5f;
1015                         dxt[1] *= 0.5f;
1016                         dxt[2] *= 0.5f;
1017
1018                         dyt[0] *= 0.5f;
1019                         dyt[1] *= 0.5f;
1020                         dyt[2] *= 0.5f;
1021
1022                 }
1023                 
1024                 /* if area, then reacalculate dxt[] and dyt[] */
1025                 if (areaflag) {
1026                         fx= area[0]; 
1027                         fy= area[1];
1028                         dxt[0]= area[2]-fx;
1029                         dxt[1]= area[3]-fy;
1030                         dyt[0]= area[4]-fx;
1031                         dyt[1]= area[5]-fy;
1032                 }
1033                 
1034                 /* repeat */
1035                 if (tex->extend==TEX_REPEAT) {
1036                         float max= 1.0f;
1037                         if (tex->xrepeat>1) {
1038                                 float origf= fx *= tex->xrepeat;
1039                                 
1040                                 /* TXF: omit mirror here, see comments in do_material_tex() after do_2d_mapping() call */
1041                                 if (tex->texfilter == TXF_BOX) {
1042                                         if (fx>1.0f) fx -= (int)(fx);
1043                                         else if (fx<0.0f) fx+= 1-(int)(fx);
1044                                 
1045                                         if (tex->flag & TEX_REPEAT_XMIR) {
1046                                                 int orig= (int)floor(origf);
1047                                                 if (orig & 1)
1048                                                         fx= 1.0f-fx;
1049                                         }
1050                                 }
1051                                 
1052                                 max= tex->xrepeat;
1053                                 
1054                                 dxt[0]*= tex->xrepeat;
1055                                 dyt[0]*= tex->xrepeat;
1056                         }
1057                         if (tex->yrepeat>1) {
1058                                 float origf= fy *= tex->yrepeat;
1059                                 
1060                                 /* TXF: omit mirror here, see comments in do_material_tex() after do_2d_mapping() call */
1061                                 if (tex->texfilter == TXF_BOX) {
1062                                         if (fy>1.0f) fy -= (int)(fy);
1063                                         else if (fy<0.0f) fy+= 1-(int)(fy);
1064                                 
1065                                         if (tex->flag & TEX_REPEAT_YMIR) {
1066                                                 int orig= (int)floor(origf);
1067                                                 if (orig & 1)
1068                                                         fy= 1.0f-fy;
1069                                         }
1070                                 }
1071                                 
1072                                 if (max<tex->yrepeat)
1073                                         max= tex->yrepeat;
1074
1075                                 dxt[1]*= tex->yrepeat;
1076                                 dyt[1]*= tex->yrepeat;
1077                         }
1078                         if (max!=1.0f) {
1079                                 dxt[2]*= max;
1080                                 dyt[2]*= max;
1081                         }
1082                         
1083                 }
1084                 /* crop */
1085                 if (tex->cropxmin!=0.0f || tex->cropxmax!=1.0f) {
1086                         fac1= tex->cropxmax - tex->cropxmin;
1087                         fx= tex->cropxmin+ fx*fac1;
1088                         dxt[0]*= fac1;
1089                         dyt[0]*= fac1;
1090                 }
1091                 if (tex->cropymin!=0.0f || tex->cropymax!=1.0f) {
1092                         fac1= tex->cropymax - tex->cropymin;
1093                         fy= tex->cropymin+ fy*fac1;
1094                         dxt[1]*= fac1;
1095                         dyt[1]*= fac1;
1096                 }
1097                 
1098                 texvec[0]= fx;
1099                 texvec[1]= fy;
1100
1101         }
1102 }
1103
1104 /* ************************************** */
1105
1106 static int multitex(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres, const short thread, short which_output, struct ImagePool *pool, const bool skip_load_image)
1107 {
1108         float tmpvec[3];
1109         int retval = 0; /* return value, int:0, col:1, nor:2, everything:3 */
1110
1111         texres->talpha = false;  /* is set when image texture returns alpha (considered premul) */
1112         
1113         if (tex->use_nodes && tex->nodetree) {
1114                 retval = ntreeTexExecTree(tex->nodetree, texres, texvec, dxt, dyt, osatex, thread,
1115                                           tex, which_output, R.r.cfra, (R.r.scemode & R_TEXNODE_PREVIEW) != 0, NULL, NULL);
1116         }
1117         else {
1118                 switch (tex->type) {
1119                         case 0:
1120                                 texres->tin= 0.0f;
1121                                 return 0;
1122                         case TEX_CLOUDS:
1123                                 retval = clouds(tex, texvec, texres);
1124                                 break;
1125                         case TEX_WOOD:
1126                                 retval = wood(tex, texvec, texres);
1127                                 break;
1128                         case TEX_MARBLE:
1129                                 retval = marble(tex, texvec, texres);
1130                                 break;
1131                         case TEX_MAGIC:
1132                                 retval = magic(tex, texvec, texres);
1133                                 break;
1134                         case TEX_BLEND:
1135                                 retval = blend(tex, texvec, texres);
1136                                 break;
1137                         case TEX_STUCCI:
1138                                 retval = stucci(tex, texvec, texres);
1139                                 break;
1140                         case TEX_NOISE:
1141                                 retval = texnoise(tex, texres, thread);
1142                                 break;
1143                         case TEX_IMAGE:
1144                                 if (osatex) retval = imagewraposa(tex, tex->ima, NULL, texvec, dxt, dyt, texres, pool, skip_load_image);
1145                                 else        retval = imagewrap(tex, tex->ima, NULL, texvec, texres, pool, skip_load_image);
1146                                 if (tex->ima) {
1147                                         BKE_image_tag_time(tex->ima);
1148                                 }
1149                                 break;
1150                         case TEX_ENVMAP:
1151                                 retval = envmaptex(tex, texvec, dxt, dyt, osatex, texres, pool, skip_load_image);
1152                                 break;
1153                         case TEX_MUSGRAVE:
1154                                 /* newnoise: musgrave types */
1155
1156                                 /* ton: added this, for Blender convention reason.
1157                                  * artificer: added the use of tmpvec to avoid scaling texvec
1158                                  */
1159                                 copy_v3_v3(tmpvec, texvec);
1160                                 mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
1161
1162                                 switch (tex->stype) {
1163                                         case TEX_MFRACTAL:
1164                                         case TEX_FBM:
1165                                                 retval = mg_mFractalOrfBmTex(tex, tmpvec, texres);
1166                                                 break;
1167                                         case TEX_RIDGEDMF:
1168                                         case TEX_HYBRIDMF:
1169                                                 retval = mg_ridgedOrHybridMFTex(tex, tmpvec, texres);
1170                                                 break;
1171                                         case TEX_HTERRAIN:
1172                                                 retval = mg_HTerrainTex(tex, tmpvec, texres);
1173                                                 break;
1174                                 }
1175                                 break;
1176                                 /* newnoise: voronoi type */
1177                         case TEX_VORONOI:
1178                                 /* ton: added this, for Blender convention reason.
1179                                  * artificer: added the use of tmpvec to avoid scaling texvec
1180                                  */
1181                                 copy_v3_v3(tmpvec, texvec);
1182                                 mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
1183
1184                                 retval = voronoiTex(tex, tmpvec, texres);
1185                                 break;
1186                         case TEX_DISTNOISE:
1187                                 /* ton: added this, for Blender convention reason.
1188                                  * artificer: added the use of tmpvec to avoid scaling texvec
1189                                  */
1190                                 copy_v3_v3(tmpvec, texvec);
1191                                 mul_v3_fl(tmpvec, 1.0f / tex->noisesize);
1192
1193                                 retval = mg_distNoiseTex(tex, tmpvec, texres);
1194                                 break;
1195                         case TEX_POINTDENSITY:
1196                                 retval = pointdensitytex(tex, texvec, texres);
1197                                 break;
1198                         case TEX_VOXELDATA:
1199                                 retval = voxeldatatex(tex, texvec, texres);
1200                                 break;
1201                         case TEX_OCEAN:
1202                                 retval = ocean_texture(tex, texvec, texres);
1203                                 break;
1204                 }
1205         }
1206
1207         if (tex->flag & TEX_COLORBAND) {
1208                 float col[4];
1209                 if (do_colorband(tex->coba, texres->tin, col)) {
1210                         texres->talpha = true;
1211                         texres->tr= col[0];
1212                         texres->tg= col[1];
1213                         texres->tb= col[2];
1214                         texres->ta= col[3];
1215                         retval |= TEX_RGB;
1216                 }
1217         }
1218         return retval;
1219 }
1220
1221 static int multitex_nodes_intern(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres,
1222                                  const short thread, short which_output, ShadeInput *shi, MTex *mtex, struct ImagePool *pool,
1223                                  bool scene_color_manage, const bool skip_load_image)
1224 {
1225         if (tex==NULL) {
1226                 memset(texres, 0, sizeof(TexResult));
1227                 return 0;
1228         }
1229
1230         if (mtex)
1231                 which_output= mtex->which_output;
1232         
1233         if (tex->type==TEX_IMAGE) {
1234                 int rgbnor;
1235
1236                 if (mtex) {
1237                         /* we have mtex, use it for 2d mapping images only */
1238                         do_2d_mapping(mtex, texvec, shi->vlr, shi->facenor, dxt, dyt);
1239                         rgbnor = multitex(tex, texvec, dxt, dyt, osatex, texres, thread, which_output, pool, skip_load_image);
1240
1241                         if (mtex->mapto & (MAP_COL+MAP_COLSPEC+MAP_COLMIR)) {
1242                                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1243                                 
1244                                 /* don't linearize float buffers, assumed to be linear */
1245                                 if (ibuf && !(ibuf->rect_float) && scene_color_manage)
1246                                         IMB_colormanagement_colorspace_to_scene_linear_v3(&texres->tr, ibuf->rect_colorspace);
1247
1248                                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1249                         }
1250                 }
1251                 else {
1252                         /* we don't have mtex, do default flat 2d projection */
1253                         MTex localmtex;
1254                         float texvec_l[3], dxt_l[3], dyt_l[3];
1255                         
1256                         localmtex.mapping= MTEX_FLAT;
1257                         localmtex.tex= tex;
1258                         localmtex.object= NULL;
1259                         localmtex.texco= TEXCO_ORCO;
1260                         
1261                         copy_v3_v3(texvec_l, texvec);
1262                         if (dxt && dyt) {
1263                                 copy_v3_v3(dxt_l, dxt);
1264                                 copy_v3_v3(dyt_l, dyt);
1265                         }
1266                         else {
1267                                 zero_v3(dxt_l);
1268                                 zero_v3(dyt_l);
1269                         }
1270                         
1271                         do_2d_mapping(&localmtex, texvec_l, NULL, NULL, dxt_l, dyt_l);
1272                         rgbnor = multitex(tex, texvec_l, dxt_l, dyt_l, osatex, texres, thread, which_output, pool, skip_load_image);
1273
1274                         {
1275                                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1276
1277                                 /* don't linearize float buffers, assumed to be linear */
1278                                 if (ibuf && !(ibuf->rect_float) && scene_color_manage)
1279                                         IMB_colormanagement_colorspace_to_scene_linear_v3(&texres->tr, ibuf->rect_colorspace);
1280
1281                                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1282                         }
1283                 }
1284
1285                 return rgbnor;
1286         }
1287         else {
1288                 return multitex(tex, texvec, dxt, dyt, osatex, texres, thread, which_output, pool, skip_load_image);
1289         }
1290 }
1291
1292 /* this is called from the shader and texture nodes
1293  * Use it from render pipeline only!
1294  */
1295 int multitex_nodes(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres,
1296                    const short thread, short which_output, ShadeInput *shi, MTex *mtex, struct ImagePool *pool)
1297 {
1298         return multitex_nodes_intern(tex, texvec, dxt, dyt, osatex, texres,
1299                                      thread, which_output, shi, mtex, pool, R.scene_color_manage,
1300                                      (R.r.scemode & R_NO_IMAGE_LOAD) != 0);
1301 }
1302
1303 /* this is called for surface shading */
1304 static int multitex_mtex(ShadeInput *shi, MTex *mtex, float texvec[3], float dxt[3], float dyt[3], TexResult *texres, struct ImagePool *pool, const bool skip_load_image)
1305 {
1306         Tex *tex = mtex->tex;
1307
1308         if (tex->use_nodes && tex->nodetree) {
1309                 /* stupid exception here .. but we have to pass shi and mtex to
1310                  * textures nodes for 2d mapping and color management for images */
1311                 return ntreeTexExecTree(tex->nodetree, texres, texvec, dxt, dyt, shi->osatex, shi->thread,
1312                                         tex, mtex->which_output, R.r.cfra, (R.r.scemode & R_TEXNODE_PREVIEW) != 0, shi, mtex);
1313         }
1314         else {
1315                 return multitex(mtex->tex, texvec, dxt, dyt, shi->osatex, texres, shi->thread, mtex->which_output, pool, skip_load_image);
1316         }
1317 }
1318
1319 /* Warning, if the texres's values are not declared zero, check the return value to be sure
1320  * the color values are set before using the r/g/b values, otherwise you may use uninitialized values - Campbell
1321  *
1322  * Use it for stuff which is out of render pipeline.
1323  */
1324 int multitex_ext(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int osatex, TexResult *texres, struct ImagePool *pool, bool scene_color_manage, const bool skip_load_image)
1325 {
1326         return multitex_nodes_intern(tex, texvec, dxt, dyt, osatex, texres, 0, 0, NULL, NULL, pool, scene_color_manage, skip_load_image);
1327 }
1328
1329 /* extern-tex doesn't support nodes (ntreeBeginExec() can't be called when rendering is going on)\
1330  *
1331  * Use it for stuff which is out of render pipeline.
1332  */
1333 int multitex_ext_safe(Tex *tex, float texvec[3], TexResult *texres, struct ImagePool *pool, bool scene_color_manage, const bool skip_load_image)
1334 {
1335         int use_nodes= tex->use_nodes, retval;
1336         
1337         tex->use_nodes = false;
1338         retval= multitex_nodes_intern(tex, texvec, NULL, NULL, 0, texres, 0, 0, NULL, NULL, pool, scene_color_manage, skip_load_image);
1339         tex->use_nodes= use_nodes;
1340         
1341         return retval;
1342 }
1343
1344
1345 /* ------------------------------------------------------------------------- */
1346
1347 /* in = destination, tex = texture, out = previous color */
1348 /* fact = texture strength, facg = button strength value */
1349 void texture_rgb_blend(float in[3], const float tex[3], const float out[3], float fact, float facg, int blendtype)
1350 {
1351         float facm, col;
1352         
1353         switch (blendtype) {
1354         case MTEX_BLEND:
1355                 fact*= facg;
1356                 facm= 1.0f-fact;
1357
1358                 in[0]= (fact*tex[0] + facm*out[0]);
1359                 in[1]= (fact*tex[1] + facm*out[1]);
1360                 in[2]= (fact*tex[2] + facm*out[2]);
1361                 break;
1362                 
1363         case MTEX_MUL:
1364                 fact*= facg;
1365                 facm= 1.0f-fact;
1366                 in[0]= (facm+fact*tex[0])*out[0];
1367                 in[1]= (facm+fact*tex[1])*out[1];
1368                 in[2]= (facm+fact*tex[2])*out[2];
1369                 break;
1370
1371         case MTEX_SCREEN:
1372                 fact*= facg;
1373                 facm= 1.0f-fact;
1374                 in[0]= 1.0f - (facm+fact*(1.0f-tex[0])) * (1.0f-out[0]);
1375                 in[1]= 1.0f - (facm+fact*(1.0f-tex[1])) * (1.0f-out[1]);
1376                 in[2]= 1.0f - (facm+fact*(1.0f-tex[2])) * (1.0f-out[2]);
1377                 break;
1378
1379         case MTEX_OVERLAY:
1380                 fact*= facg;
1381                 facm= 1.0f-fact;
1382                 
1383                 if (out[0] < 0.5f)
1384                         in[0] = out[0] * (facm + 2.0f*fact*tex[0]);
1385                 else
1386                         in[0] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[0])) * (1.0f - out[0]);
1387                 if (out[1] < 0.5f)
1388                         in[1] = out[1] * (facm + 2.0f*fact*tex[1]);
1389                 else
1390                         in[1] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[1])) * (1.0f - out[1]);
1391                 if (out[2] < 0.5f)
1392                         in[2] = out[2] * (facm + 2.0f*fact*tex[2]);
1393                 else
1394                         in[2] = 1.0f - (facm + 2.0f*fact*(1.0f - tex[2])) * (1.0f - out[2]);
1395                 break;
1396                 
1397         case MTEX_SUB:
1398                 fact= -fact;
1399         case MTEX_ADD:
1400                 fact*= facg;
1401                 in[0]= (fact*tex[0] + out[0]);
1402                 in[1]= (fact*tex[1] + out[1]);
1403                 in[2]= (fact*tex[2] + out[2]);
1404                 break;
1405
1406         case MTEX_DIV:
1407                 fact*= facg;
1408                 facm= 1.0f-fact;
1409                 
1410                 if (tex[0]!=0.0f)
1411                         in[0]= facm*out[0] + fact*out[0]/tex[0];
1412                 if (tex[1]!=0.0f)
1413                         in[1]= facm*out[1] + fact*out[1]/tex[1];
1414                 if (tex[2]!=0.0f)
1415                         in[2]= facm*out[2] + fact*out[2]/tex[2];
1416
1417                 break;
1418
1419         case MTEX_DIFF:
1420                 fact*= facg;
1421                 facm= 1.0f-fact;
1422                 in[0]= facm*out[0] + fact*fabsf(tex[0]-out[0]);
1423                 in[1]= facm*out[1] + fact*fabsf(tex[1]-out[1]);
1424                 in[2]= facm*out[2] + fact*fabsf(tex[2]-out[2]);
1425                 break;
1426
1427         case MTEX_DARK:
1428                 fact*= facg;
1429                 facm= 1.0f-fact;
1430                 
1431                 in[0] = min_ff(out[0], tex[0])*fact + out[0]*facm;
1432                 in[1] = min_ff(out[1], tex[1])*fact + out[1]*facm;
1433                 in[2] = min_ff(out[2], tex[2])*fact + out[2]*facm;
1434                 break;
1435
1436         case MTEX_LIGHT:
1437                 fact*= facg;
1438                 
1439                 col= fact*tex[0];
1440                 if (col > out[0]) in[0]= col; else in[0]= out[0];
1441                 col= fact*tex[1];
1442                 if (col > out[1]) in[1]= col; else in[1]= out[1];
1443                 col= fact*tex[2];
1444                 if (col > out[2]) in[2]= col; else in[2]= out[2];
1445                 break;
1446                 
1447         case MTEX_BLEND_HUE:
1448                 fact*= facg;
1449                 copy_v3_v3(in, out);
1450                 ramp_blend(MA_RAMP_HUE, in, fact, tex);
1451                 break;
1452         case MTEX_BLEND_SAT:
1453                 fact*= facg;
1454                 copy_v3_v3(in, out);
1455                 ramp_blend(MA_RAMP_SAT, in, fact, tex);
1456                 break;
1457         case MTEX_BLEND_VAL:
1458                 fact*= facg;
1459                 copy_v3_v3(in, out);
1460                 ramp_blend(MA_RAMP_VAL, in, fact, tex);
1461                 break;
1462         case MTEX_BLEND_COLOR:
1463                 fact*= facg;
1464                 copy_v3_v3(in, out);
1465                 ramp_blend(MA_RAMP_COLOR, in, fact, tex);
1466                 break;
1467         case MTEX_SOFT_LIGHT: 
1468                 fact*= facg; 
1469                 copy_v3_v3(in, out);
1470                 ramp_blend(MA_RAMP_SOFT, in, fact, tex);
1471                 break; 
1472         case MTEX_LIN_LIGHT: 
1473                 fact*= facg; 
1474                 copy_v3_v3(in, out);
1475                 ramp_blend(MA_RAMP_LINEAR, in, fact, tex);
1476                 break; 
1477         }
1478 }
1479
1480 float texture_value_blend(float tex, float out, float fact, float facg, int blendtype)
1481 {
1482         float in=0.0, facm, col, scf;
1483         int flip= (facg < 0.0f);
1484
1485         facg= fabsf(facg);
1486         
1487         fact*= facg;
1488         facm= 1.0f-fact;
1489         if (flip) SWAP(float, fact, facm);
1490
1491         switch (blendtype) {
1492         case MTEX_BLEND:
1493                 in= fact*tex + facm*out;
1494                 break;
1495
1496         case MTEX_MUL:
1497                 facm= 1.0f-facg;
1498                 in= (facm+fact*tex)*out;
1499                 break;
1500
1501         case MTEX_SCREEN:
1502                 facm= 1.0f-facg;
1503                 in= 1.0f-(facm+fact*(1.0f-tex))*(1.0f-out);
1504                 break;
1505
1506         case MTEX_OVERLAY:
1507                 facm= 1.0f-facg;
1508                 if (out < 0.5f)
1509                         in = out * (facm + 2.0f*fact*tex);
1510                 else
1511                         in = 1.0f - (facm + 2.0f*fact*(1.0f - tex)) * (1.0f - out);
1512                 break;
1513
1514         case MTEX_SUB:
1515                 fact= -fact;
1516         case MTEX_ADD:
1517                 in= fact*tex + out;
1518                 break;
1519
1520         case MTEX_DIV:
1521                 if (tex!=0.0f)
1522                         in= facm*out + fact*out/tex;
1523                 break;
1524
1525         case MTEX_DIFF:
1526                 in= facm*out + fact*fabsf(tex-out);
1527                 break;
1528
1529         case MTEX_DARK:
1530                 in = min_ff(out, tex)*fact + out*facm;
1531                 break;
1532
1533         case MTEX_LIGHT:
1534                 col= fact*tex;
1535                 if (col > out) in= col; else in= out;
1536                 break;
1537
1538         case MTEX_SOFT_LIGHT: 
1539                 scf=1.0f - (1.0f - tex) * (1.0f - out);
1540                 in= facm*out + fact * ((1.0f - out) * tex * out) + (out * scf);
1541                 break;       
1542
1543         case MTEX_LIN_LIGHT: 
1544                 if (tex > 0.5f)
1545                         in = out + fact*(2.0f*(tex - 0.5f));
1546                 else 
1547                         in = out + fact*(2.0f*tex - 1.0f);
1548                 break;
1549         }
1550         
1551         return in;
1552 }
1553
1554 static void texco_mapping(ShadeInput *shi, Tex *tex, MTex *mtex,
1555                           const float co[3], const float dx[3], const float dy[3], float texvec[3], float dxt[3], float dyt[3])
1556 {
1557         /* new: first swap coords, then map, then trans/scale */
1558         if (tex->type == TEX_IMAGE) {
1559                 /* placement */
1560                 texvec[0] = mtex->projx ? co[mtex->projx - 1] : 0.f;
1561                 texvec[1] = mtex->projy ? co[mtex->projy - 1] : 0.f;
1562                 texvec[2] = mtex->projz ? co[mtex->projz - 1] : 0.f;
1563
1564                 if (shi->osatex) {
1565                         if (mtex->projx) {
1566                                 dxt[0] = dx[mtex->projx - 1];
1567                                 dyt[0] = dy[mtex->projx - 1];
1568                         }
1569                         else dxt[0] = dyt[0] = 0.f;
1570                         if (mtex->projy) {
1571                                 dxt[1] = dx[mtex->projy - 1];
1572                                 dyt[1] = dy[mtex->projy - 1];
1573                         }
1574                         else dxt[1] = dyt[1] = 0.f;
1575                         if (mtex->projz) {
1576                                 dxt[2] = dx[mtex->projz - 1];
1577                                 dyt[2] = dy[mtex->projz - 1];
1578                         }
1579                         else dxt[2] = dyt[2] = 0.f;
1580                 }
1581                 do_2d_mapping(mtex, texvec, shi->vlr, shi->facenor, dxt, dyt);
1582
1583                 /* translate and scale */
1584                 texvec[0] = mtex->size[0]*(texvec[0] - 0.5f) + mtex->ofs[0] + 0.5f;
1585                 texvec[1] = mtex->size[1]*(texvec[1] - 0.5f) + mtex->ofs[1] + 0.5f;
1586                 if (shi->osatex) {
1587                         dxt[0] = mtex->size[0] * dxt[0];
1588                         dxt[1] = mtex->size[1] * dxt[1];
1589                         dyt[0] = mtex->size[0] * dyt[0];
1590                         dyt[1] = mtex->size[1] * dyt[1];
1591                 }
1592                 
1593                 /* problem: repeat-mirror is not a 'repeat' but 'extend' in imagetexture.c */
1594                 /* TXF: bug was here, only modify texvec when repeat mode set, old code affected other modes too.
1595                  * New texfilters solve mirroring differently so that it also works correctly when
1596                  * textures are scaled (sizeXYZ) as well as repeated. See also modification in do_2d_mapping().
1597                  * (since currently only done in osa mode, results will look incorrect without osa TODO) */
1598                 if (tex->extend == TEX_REPEAT && (tex->flag & TEX_REPEAT_XMIR)) {
1599                         if (tex->texfilter == TXF_BOX)
1600                                 texvec[0] -= floorf(texvec[0]);  /* this line equivalent to old code, same below */
1601                         else if (texvec[0] < 0.f || texvec[0] > 1.f) {
1602                                 const float tx = 0.5f*texvec[0];
1603                                 texvec[0] = 2.f*(tx - floorf(tx));
1604                                 if (texvec[0] > 1.f) texvec[0] = 2.f - texvec[0];
1605                         }
1606                 }
1607                 if (tex->extend == TEX_REPEAT && (tex->flag & TEX_REPEAT_YMIR)) {
1608                         if (tex->texfilter == TXF_BOX)
1609                                 texvec[1] -= floorf(texvec[1]);
1610                         else if (texvec[1] < 0.f || texvec[1] > 1.f) {
1611                                 const float ty = 0.5f*texvec[1];
1612                                 texvec[1] = 2.f*(ty - floorf(ty));
1613                                 if (texvec[1] > 1.f) texvec[1] = 2.f - texvec[1];
1614                         }
1615                 }
1616                 
1617         }
1618         else {  /* procedural */
1619                 /* placement */
1620                 texvec[0] = mtex->size[0]*(mtex->projx ? (co[mtex->projx - 1] + mtex->ofs[0]) : mtex->ofs[0]);
1621                 texvec[1] = mtex->size[1]*(mtex->projy ? (co[mtex->projy - 1] + mtex->ofs[1]) : mtex->ofs[1]);
1622                 texvec[2] = mtex->size[2]*(mtex->projz ? (co[mtex->projz - 1] + mtex->ofs[2]) : mtex->ofs[2]);
1623
1624                 if (shi->osatex) {
1625                         if (mtex->projx) {
1626                                 dxt[0] = mtex->size[0]*dx[mtex->projx - 1];
1627                                 dyt[0] = mtex->size[0]*dy[mtex->projx - 1];
1628                         }
1629                         else dxt[0] = dyt[0] = 0.f;
1630                         if (mtex->projy) {
1631                                 dxt[1] = mtex->size[1]*dx[mtex->projy - 1];
1632                                 dyt[1] = mtex->size[1]*dy[mtex->projy - 1];
1633                         }
1634                         else dxt[1] = dyt[1] = 0.f;
1635                         if (mtex->projz) {
1636                                 dxt[2] = mtex->size[2]*dx[mtex->projz - 1];
1637                                 dyt[2] = mtex->size[2]*dy[mtex->projz - 1];
1638                         }
1639                         else dxt[2]= dyt[2] = 0.f;
1640                 }
1641         }
1642 }
1643
1644 /* Bump code from 2.5 development cycle, has a number of bugs, but here for compatibility */
1645
1646 typedef struct CompatibleBump {
1647         float nu[3], nv[3], nn[3];
1648         float dudnu, dudnv, dvdnu, dvdnv;
1649         bool nunvdone;
1650 } CompatibleBump;
1651
1652 static void compatible_bump_init(CompatibleBump *compat_bump)
1653 {
1654         memset(compat_bump, 0, sizeof(*compat_bump));
1655
1656         compat_bump->dudnu = 1.0f;
1657         compat_bump->dvdnv = 1.0f;
1658 }
1659
1660 static void compatible_bump_uv_derivs(CompatibleBump *compat_bump, ShadeInput *shi, MTex *mtex, int i)
1661 {
1662         /* uvmapping only, calculation of normal tangent u/v partial derivatives
1663          * (should not be here, dudnu, dudnv, dvdnu & dvdnv should probably be part of ShadeInputUV struct,
1664          *  nu/nv in ShadeInput and this calculation should then move to shadeinput.c,
1665          * shade_input_set_shade_texco() func.) */
1666
1667         /* NOTE: test for shi->obr->ob here,
1668          * since vlr/obr/obi can be 'fake' when called from fastshade(), another reason to move it.. */
1669
1670         /* NOTE: shi->v1 is NULL when called from displace_render_vert,
1671          * assigning verts in this case is not trivial because the shi quad face side is not know. */
1672         if ((mtex->texflag & MTEX_COMPAT_BUMP) && shi->obr && shi->obr->ob && shi->v1) {
1673                 if (mtex->mapto & (MAP_NORM|MAP_WARP) && !((mtex->tex->type==TEX_IMAGE) && (mtex->tex->imaflag & TEX_NORMALMAP))) {
1674                         MTFace* tf = RE_vlakren_get_tface(shi->obr, shi->vlr, i, NULL, 0);
1675                         int j1 = shi->i1, j2 = shi->i2, j3 = shi->i3;
1676
1677                         vlr_set_uv_indices(shi->vlr, &j1, &j2, &j3);
1678
1679                         /* compute ortho basis around normal */
1680                         if (!compat_bump->nunvdone) {
1681                                 /* render normal is negated */
1682                                 compat_bump->nn[0] = -shi->vn[0];
1683                                 compat_bump->nn[1] = -shi->vn[1];
1684                                 compat_bump->nn[2] = -shi->vn[2];
1685                                 ortho_basis_v3v3_v3(compat_bump->nu, compat_bump->nv, compat_bump->nn);
1686                                 compat_bump->nunvdone = true;
1687                         }
1688
1689                         if (tf) {
1690                                 const float *uv1 = tf->uv[j1], *uv2 = tf->uv[j2], *uv3 = tf->uv[j3];
1691                                 const float an[3] = {fabsf(compat_bump->nn[0]), fabsf(compat_bump->nn[1]), fabsf(compat_bump->nn[2])};
1692                                 const int a1 = (an[0] > an[1] && an[0] > an[2]) ? 1 : 0;
1693                                 const int a2 = (an[2] > an[0] && an[2] > an[1]) ? 1 : 2;
1694                                 const float dp1_a1 = shi->v1->co[a1] - shi->v3->co[a1];
1695                                 const float dp1_a2 = shi->v1->co[a2] - shi->v3->co[a2];
1696                                 const float dp2_a1 = shi->v2->co[a1] - shi->v3->co[a1];
1697                                 const float dp2_a2 = shi->v2->co[a2] - shi->v3->co[a2];
1698                                 const float du1 = uv1[0] - uv3[0], du2 = uv2[0] - uv3[0];
1699                                 const float dv1 = uv1[1] - uv3[1], dv2 = uv2[1] - uv3[1];
1700                                 const float dpdu_a1 = dv2*dp1_a1 - dv1*dp2_a1;
1701                                 const float dpdu_a2 = dv2*dp1_a2 - dv1*dp2_a2;
1702                                 const float dpdv_a1 = du1*dp2_a1 - du2*dp1_a1;
1703                                 const float dpdv_a2 = du1*dp2_a2 - du2*dp1_a2;
1704                                 float d = dpdu_a1*dpdv_a2 - dpdv_a1*dpdu_a2;
1705                                 float uvd = du1*dv2 - dv1*du2;
1706
1707                                 if (uvd == 0.f) uvd = 1e-5f;
1708                                 if (d == 0.f) d = 1e-5f;
1709                                 d = uvd / d;
1710
1711                                 compat_bump->dudnu = (dpdv_a2*compat_bump->nu[a1] - dpdv_a1*compat_bump->nu[a2])*d;
1712                                 compat_bump->dvdnu = (dpdu_a1*compat_bump->nu[a2] - dpdu_a2*compat_bump->nu[a1])*d;
1713                                 compat_bump->dudnv = (dpdv_a2*compat_bump->nv[a1] - dpdv_a1*compat_bump->nv[a2])*d;
1714                                 compat_bump->dvdnv = (dpdu_a1*compat_bump->nv[a2] - dpdu_a2*compat_bump->nv[a1])*d;
1715                         }
1716                 }
1717         }
1718 }
1719
1720 static int compatible_bump_compute(CompatibleBump *compat_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres,
1721                                    float Tnor, const float co[3], const float dx[3], const float dy[3], float texvec[3], float dxt[3], float dyt[3],
1722                                    struct ImagePool *pool, const bool skip_load_image)
1723 {
1724         TexResult ttexr = {0, 0, 0, 0, 0, texres->talpha, NULL};  /* temp TexResult */
1725         float tco[3], texv[3], cd, ud, vd, du, dv, idu, idv;
1726         const int fromrgb = ((tex->type == TEX_IMAGE) || ((tex->flag & TEX_COLORBAND)!=0));
1727         const float bf = -0.04f*Tnor*mtex->norfac;
1728         int rgbnor;
1729         /* disable internal bump eval */
1730         float *nvec = texres->nor;
1731         texres->nor = NULL;
1732         /* du & dv estimates, constant value defaults */
1733         du = dv = 0.01f;
1734
1735         /* compute ortho basis around normal */
1736         if (!compat_bump->nunvdone) {
1737                 /* render normal is negated */
1738                 negate_v3_v3(compat_bump->nn, shi->vn);
1739                 ortho_basis_v3v3_v3(compat_bump->nu, compat_bump->nv, compat_bump->nn);
1740                 compat_bump->nunvdone = true;
1741         }
1742
1743         /* two methods, either constant based on main image resolution,
1744          * (which also works without osa, though of course not always good (or even very bad) results),
1745          * or based on tex derivative max values (osa only). Not sure which is best... */
1746
1747         if (!shi->osatex && (tex->type == TEX_IMAGE) && tex->ima) {
1748                 /* in case we have no proper derivatives, fall back to
1749                  * computing du/dv it based on image size */
1750                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1751                 if (ibuf) {
1752                         du = 1.f/(float)ibuf->x;
1753                         dv = 1.f/(float)ibuf->y;
1754                 }
1755                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1756         }
1757         else if (shi->osatex) {
1758                 /* we have derivatives, can compute proper du/dv */
1759                 if (tex->type == TEX_IMAGE) {   /* 2d image, use u & v max. of dx/dy 2d vecs */
1760                         const float adx[2] = {fabsf(dx[0]), fabsf(dx[1])};
1761                         const float ady[2] = {fabsf(dy[0]), fabsf(dy[1])};
1762                         du = MAX2(adx[0], ady[0]);
1763                         dv = MAX2(adx[1], ady[1]);
1764                 }
1765                 else {  /* 3d procedural, estimate from all dx/dy elems */
1766                         const float adx[3] = {fabsf(dx[0]), fabsf(dx[1]), fabsf(dx[2])};
1767                         const float ady[3] = {fabsf(dy[0]), fabsf(dy[1]), fabsf(dy[2])};
1768                         du = max_fff(adx[0], adx[1], adx[2]);
1769                         dv = max_fff(ady[0], ady[1], ady[2]);
1770                 }
1771         }
1772
1773         /* center, main return value */
1774         texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
1775         rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, texres, pool, skip_load_image);
1776         cd = fromrgb ? (texres->tr + texres->tg + texres->tb) / 3.0f : texres->tin;
1777
1778         if (mtex->texco == TEXCO_UV) {
1779                 /* for the uv case, use the same value for both du/dv,
1780                  * since individually scaling the normal derivatives makes them useless... */
1781                 du = min_ff(du, dv);
1782                 idu = (du < 1e-5f) ? bf : (bf/du);
1783
1784                 /* +u val */
1785                 tco[0] = co[0] + compat_bump->dudnu*du;
1786                 tco[1] = co[1] + compat_bump->dvdnu*du;
1787                 tco[2] = 0.f;
1788                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1789                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1790                 ud = idu*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1791
1792                 /* +v val */
1793                 tco[0] = co[0] + compat_bump->dudnv*du;
1794                 tco[1] = co[1] + compat_bump->dvdnv*du;
1795                 tco[2] = 0.f;
1796                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1797                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1798                 vd = idu*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1799         }
1800         else {
1801                 float tu[3], tv[3];
1802
1803                 copy_v3_v3(tu, compat_bump->nu);
1804                 copy_v3_v3(tv, compat_bump->nv);
1805
1806                 idu = (du < 1e-5f) ? bf : (bf/du);
1807                 idv = (dv < 1e-5f) ? bf : (bf/dv);
1808
1809                 if ((mtex->texco == TEXCO_ORCO) && shi->obr && shi->obr->ob) {
1810                         mul_mat3_m4_v3(shi->obr->ob->imat_ren, tu);
1811                         mul_mat3_m4_v3(shi->obr->ob->imat_ren, tv);
1812                         normalize_v3(tu);
1813                         normalize_v3(tv);
1814                 }
1815                 else if (mtex->texco == TEXCO_GLOB) {
1816                         mul_mat3_m4_v3(R.viewinv, tu);
1817                         mul_mat3_m4_v3(R.viewinv, tv);
1818                 }
1819                 else if (mtex->texco == TEXCO_OBJECT && mtex->object) {
1820                         mul_mat3_m4_v3(mtex->object->imat_ren, tu);
1821                         mul_mat3_m4_v3(mtex->object->imat_ren, tv);
1822                         normalize_v3(tu);
1823                         normalize_v3(tv);
1824                 }
1825
1826                 /* +u val */
1827                 tco[0] = co[0] + tu[0]*du;
1828                 tco[1] = co[1] + tu[1]*du;
1829                 tco[2] = co[2] + tu[2]*du;
1830                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1831                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1832                 ud = idu*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1833
1834                 /* +v val */
1835                 tco[0] = co[0] + tv[0]*dv;
1836                 tco[1] = co[1] + tv[1]*dv;
1837                 tco[2] = co[2] + tv[2]*dv;
1838                 texco_mapping(shi, tex, mtex, tco, dx, dy, texv, dxt, dyt);
1839                 multitex_mtex(shi, mtex, texv, dxt, dyt, &ttexr, pool, skip_load_image);
1840                 vd = idv*(cd - (fromrgb ? (ttexr.tr + ttexr.tg + ttexr.tb) / 3.0f : ttexr.tin));
1841         }
1842
1843         /* bumped normal */
1844         compat_bump->nu[0] += ud*compat_bump->nn[0];
1845         compat_bump->nu[1] += ud*compat_bump->nn[1];
1846         compat_bump->nu[2] += ud*compat_bump->nn[2];
1847         compat_bump->nv[0] += vd*compat_bump->nn[0];
1848         compat_bump->nv[1] += vd*compat_bump->nn[1];
1849         compat_bump->nv[2] += vd*compat_bump->nn[2];
1850         cross_v3_v3v3(nvec, compat_bump->nu, compat_bump->nv);
1851
1852         nvec[0] = -nvec[0];
1853         nvec[1] = -nvec[1];
1854         nvec[2] = -nvec[2];
1855         texres->nor = nvec;
1856
1857         rgbnor |= TEX_NOR;
1858         return rgbnor;
1859 }
1860
1861 /* Improved bump code from later in 2.5 development cycle */
1862
1863 typedef struct NTapBump {
1864         int init_done;
1865         int iPrevBumpSpace;     /* 0: uninitialized, 1: objectspace, 2: texturespace, 4: viewspace */
1866         /* bumpmapping */
1867         float vNorg[3]; /* backup copy of shi->vn */
1868         float vNacc[3]; /* original surface normal minus the surface gradient of every bump map which is encountered */
1869         float vR1[3], vR2[3]; /* cross products (sigma_y, original_normal), (original_normal, sigma_x) */
1870         float sgn_det; /* sign of the determinant of the matrix {sigma_x, sigma_y, original_normal} */
1871         float fPrevMagnitude; /* copy of previous magnitude, used for multiple bumps in different spaces */
1872 } NTapBump;
1873
1874 static void ntap_bump_init(NTapBump *ntap_bump)
1875 {
1876         memset(ntap_bump, 0, sizeof(*ntap_bump));
1877 }
1878
1879 static int ntap_bump_compute(NTapBump *ntap_bump, ShadeInput *shi, MTex *mtex, Tex *tex, TexResult *texres,
1880                              float Tnor, const float co[3], const float dx[3], const float dy[3],
1881                              float texvec[3], float dxt[3], float dyt[3], struct ImagePool *pool,
1882                              const bool skip_load_image)
1883 {
1884         TexResult ttexr = {0, 0, 0, 0, 0, texres->talpha, NULL};        /* temp TexResult */
1885
1886         const int fromrgb = ((tex->type == TEX_IMAGE) || ((tex->flag & TEX_COLORBAND)!=0));
1887
1888         /* The negate on Hscale is done because the
1889          * normal in the renderer points inward which corresponds
1890          * to inverting the bump map. The normals are generated
1891          * this way in calc_vertexnormals(). Should this ever change
1892          * this negate must be removed. */
1893         float Hscale = -Tnor*mtex->norfac;
1894
1895         int dimx=512, dimy=512;
1896         const int imag_tspace_dimension_x = 1024;  /* only used for texture space variant */
1897         float aspect = 1.0f;
1898
1899         /* 2 channels for 2D texture and 3 for 3D textures. */
1900         const int nr_channels = (mtex->texco == TEXCO_UV)? 2 : 3;
1901         int c, rgbnor, iBumpSpace;
1902         float dHdx, dHdy;
1903         int found_deriv_map = (tex->type==TEX_IMAGE) && (tex->imaflag & TEX_DERIVATIVEMAP);
1904
1905         /* disable internal bump eval in sampler, save pointer */
1906         float *nvec = texres->nor;
1907         texres->nor = NULL;
1908
1909         if (found_deriv_map==0) {
1910                 if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
1911                         if (tex->ima)
1912                                 Hscale *= 13.0f; /* appears to be a sensible default value */
1913                 }
1914                 else
1915                         Hscale *= 0.1f; /* factor 0.1 proved to look like the previous bump code */
1916         }
1917
1918         if ( !ntap_bump->init_done ) {
1919                 copy_v3_v3(ntap_bump->vNacc, shi->vn);
1920                 copy_v3_v3(ntap_bump->vNorg, shi->vn);
1921                 ntap_bump->fPrevMagnitude = 1.0f;
1922                 ntap_bump->iPrevBumpSpace = 0;
1923                 
1924                 ntap_bump->init_done = true;
1925         }
1926
1927         /* resolve image dimensions */
1928         if (found_deriv_map || (mtex->texflag&MTEX_BUMP_TEXTURESPACE)!=0) {
1929                 ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
1930                 if (ibuf) {
1931                         dimx = ibuf->x;
1932                         dimy = ibuf->y;
1933                         aspect = ((float) dimy) / dimx;
1934                 }
1935                 BKE_image_pool_release_ibuf(tex->ima, ibuf, pool);
1936         }
1937         
1938         if (found_deriv_map) {
1939                 float dBdu, dBdv, auto_bump = 1.0f;
1940                 float s = 1;            /* negate this if flipped texture coordinate */
1941                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
1942                 rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, texres, pool, skip_load_image);
1943
1944                 if (shi->obr->ob->derivedFinal) {
1945                         auto_bump = shi->obr->ob->derivedFinal->auto_bump_scale;
1946                 }
1947
1948                 {
1949                         float fVirtDim = sqrtf(fabsf((float) (dimx*dimy)*mtex->size[0]*mtex->size[1]));
1950                         auto_bump /= MAX2(fVirtDim, FLT_EPSILON);
1951                 }
1952
1953                 /* this variant using a derivative map is described here
1954                  * http://mmikkelsen3d.blogspot.com/2011/07/derivative-maps.html */
1955                 dBdu = auto_bump*Hscale*dimx*(2*texres->tr-1);
1956                 dBdv = auto_bump*Hscale*dimy*(2*texres->tg-1);
1957
1958                 dHdx = dBdu*dxt[0] + s * dBdv*dxt[1];
1959                 dHdy = dBdu*dyt[0] + s * dBdv*dyt[1];
1960         }
1961         else if (!(mtex->texflag & MTEX_5TAP_BUMP)) {
1962                 /* compute height derivatives with respect to output image pixel coordinates x and y */
1963                 float STll[3], STlr[3], STul[3];
1964                 float Hll, Hlr, Hul;
1965
1966                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
1967
1968                 for (c=0; c<nr_channels; c++) {
1969                         /* dx contains the derivatives (du/dx, dv/dx)
1970                          * dy contains the derivatives (du/dy, dv/dy) */
1971                         STll[c] = texvec[c];
1972                         STlr[c] = texvec[c]+dxt[c];
1973                         STul[c] = texvec[c]+dyt[c];
1974                 }
1975
1976                 /* clear unused derivatives */
1977                 for (c=nr_channels; c<3; c++) {
1978                         STll[c] = 0.0f;
1979                         STlr[c] = 0.0f;
1980                         STul[c] = 0.0f;
1981                 }
1982
1983                 /* use texres for the center sample, set rgbnor */
1984                 rgbnor = multitex_mtex(shi, mtex, STll, dxt, dyt, texres, pool, skip_load_image);
1985                 Hll = (fromrgb) ? rgb_to_grayscale(&texres->tr) : texres->tin;
1986
1987                 /* use ttexr for the other 2 taps */
1988                 multitex_mtex(shi, mtex, STlr, dxt, dyt, &ttexr, pool, skip_load_image);
1989                 Hlr = (fromrgb) ? rgb_to_grayscale(&ttexr.tr) : ttexr.tin;
1990
1991                 multitex_mtex(shi, mtex, STul, dxt, dyt, &ttexr, pool, skip_load_image);
1992                 Hul = (fromrgb) ? rgb_to_grayscale(&ttexr.tr) : ttexr.tin;
1993
1994                 dHdx = Hscale*(Hlr - Hll);
1995                 dHdy = Hscale*(Hul - Hll);
1996         }
1997         else {
1998                 /* same as above, but doing 5 taps, increasing quality at cost of speed */
1999                 float STc[3], STl[3], STr[3], STd[3], STu[3];
2000                 float /* Hc, */ /* UNUSED */  Hl, Hr, Hd, Hu;
2001
2002                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2003
2004                 for (c=0; c<nr_channels; c++) {
2005                         STc[c] = texvec[c];
2006                         STl[c] = texvec[c] - 0.5f*dxt[c];
2007                         STr[c] = texvec[c] + 0.5f*dxt[c];
2008                         STd[c] = texvec[c] - 0.5f*dyt[c];
2009                         STu[c] = texvec[c] + 0.5f*dyt[c];
2010                 }
2011
2012                 /* clear unused derivatives */
2013                 for (c=nr_channels; c<3; c++) {
2014                         STc[c] = 0.0f;
2015                         STl[c] = 0.0f;
2016                         STr[c] = 0.0f;
2017                         STd[c] = 0.0f;
2018                         STu[c] = 0.0f;
2019                 }
2020
2021                 /* use texres for the center sample, set rgbnor */
2022                 rgbnor = multitex_mtex(shi, mtex, STc, dxt, dyt, texres, pool, skip_load_image);
2023                 /* Hc = (fromrgb) ? rgb_to_grayscale(&texres->tr) : texres->tin; */ /* UNUSED */
2024
2025                 /* use ttexr for the other taps */
2026                 multitex_mtex(shi, mtex, STl, dxt, dyt, &ttexr, pool, skip_load_image);
2027                 Hl = (fromrgb) ? rgb_to_grayscale(&ttexr.tr) : ttexr.tin;
2028                 multitex_mtex(shi, mtex, STr, dxt, dyt, &ttexr, pool, skip_load_image);
2029                 Hr = (fromrgb) ? rgb_to_grayscale(&ttexr.tr) : ttexr.tin;
2030                 multitex_mtex(shi, mtex, STd, dxt, dyt, &ttexr, pool, skip_load_image);
2031                 Hd = (fromrgb) ? rgb_to_grayscale(&ttexr.tr) : ttexr.tin;
2032                 multitex_mtex(shi, mtex, STu, dxt, dyt, &ttexr, pool, skip_load_image);
2033                 Hu = (fromrgb) ? rgb_to_grayscale(&ttexr.tr) : ttexr.tin;
2034
2035                 dHdx = Hscale*(Hr - Hl);
2036                 dHdy = Hscale*(Hu - Hd);
2037         }
2038
2039         /* restore pointer */
2040         texres->nor = nvec;
2041
2042         /* replaced newbump with code based on listing 1 and 2 of
2043          * [Mik10] Mikkelsen M. S.: Bump Mapping Unparameterized Surfaces on the GPU.
2044          * -> http://jbit.net/~sparky/sfgrad_bump/mm_sfgrad_bump.pdf */
2045
2046         if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE )
2047                 iBumpSpace = 1;
2048         else if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE )
2049                 iBumpSpace = 2;
2050         else
2051                 iBumpSpace = 4; /* ViewSpace */
2052
2053         if ( ntap_bump->iPrevBumpSpace != iBumpSpace ) {
2054
2055                 /* initialize normal perturbation vectors */
2056                 int xyz;
2057                 float fDet, abs_fDet, fMagnitude;
2058                 /* object2view and inverted matrix */
2059                 float obj2view[3][3], view2obj[3][3], tmp[4][4];
2060                 /* local copies of derivatives and normal */
2061                 float dPdx[3], dPdy[3], vN[3];
2062                 copy_v3_v3(dPdx, shi->dxco);
2063                 copy_v3_v3(dPdy, shi->dyco);
2064                 copy_v3_v3(vN, ntap_bump->vNorg);
2065                 
2066                 if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE ) {
2067                         /* TODO: these calculations happen for every pixel!
2068                          *      -> move to shi->obi */
2069                         mul_m4_m4m4(tmp, R.viewmat, shi->obr->ob->obmat);
2070                         copy_m3_m4(obj2view, tmp); /* use only upper left 3x3 matrix */
2071                         invert_m3_m3(view2obj, obj2view);
2072
2073                         /* generate the surface derivatives in object space */
2074                         mul_m3_v3(view2obj, dPdx);
2075                         mul_m3_v3(view2obj, dPdy);
2076                         /* generate the unit normal in object space */
2077                         mul_transposed_m3_v3(obj2view, vN);
2078                         normalize_v3(vN);
2079                 }
2080                 
2081                 cross_v3_v3v3(ntap_bump->vR1, dPdy, vN);
2082                 cross_v3_v3v3(ntap_bump->vR2, vN, dPdx);
2083                 fDet = dot_v3v3(dPdx, ntap_bump->vR1);
2084                 ntap_bump->sgn_det = (fDet < 0)? -1.0f: 1.0f;
2085                 abs_fDet = ntap_bump->sgn_det * fDet;
2086
2087                 if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
2088                         if (tex->ima) {
2089                                 /* crazy hack solution that gives results similar to normal mapping - part 1 */
2090                                 normalize_v3(ntap_bump->vR1);
2091                                 normalize_v3(ntap_bump->vR2);
2092                                 abs_fDet = 1.0f;
2093                         }
2094                 }
2095                 
2096                 fMagnitude = abs_fDet;
2097                 if ( mtex->texflag & MTEX_BUMP_OBJECTSPACE ) {
2098                         /* pre do transform of texres->nor by the inverse transposed of obj2view */
2099                         mul_transposed_m3_v3(view2obj, vN);
2100                         mul_transposed_m3_v3(view2obj, ntap_bump->vR1);
2101                         mul_transposed_m3_v3(view2obj, ntap_bump->vR2);
2102                         
2103                         fMagnitude *= len_v3(vN);
2104                 }
2105                 
2106                 if (ntap_bump->fPrevMagnitude > 0.0f)
2107                         for (xyz=0; xyz<3; xyz++)
2108                                 ntap_bump->vNacc[xyz] *= fMagnitude / ntap_bump->fPrevMagnitude;
2109                 
2110                 ntap_bump->fPrevMagnitude = fMagnitude;
2111                 ntap_bump->iPrevBumpSpace = iBumpSpace;
2112         }
2113
2114         if ( mtex->texflag & MTEX_BUMP_TEXTURESPACE ) {
2115                 if (tex->ima) {
2116                         /* crazy hack solution that gives results similar to normal mapping - part 2 */
2117                         float vec[2];
2118                         const float imag_tspace_dimension_y = aspect*imag_tspace_dimension_x;
2119                         
2120                         vec[0] = imag_tspace_dimension_x*dxt[0];
2121                         vec[1] = imag_tspace_dimension_y*dxt[1];
2122                         dHdx *= 1.0f/len_v2(vec);
2123                         vec[0] = imag_tspace_dimension_x*dyt[0];
2124                         vec[1] = imag_tspace_dimension_y*dyt[1];
2125                         dHdy *= 1.0f/len_v2(vec);
2126                 }
2127         }
2128         
2129         /* subtract the surface gradient from vNacc */
2130         for (c=0; c<3; c++) {
2131                 float vSurfGrad_compi = ntap_bump->sgn_det * (dHdx * ntap_bump->vR1[c] + dHdy * ntap_bump->vR2[c]);
2132                 ntap_bump->vNacc[c] -= vSurfGrad_compi;
2133                 texres->nor[c] = ntap_bump->vNacc[c]; /* copy */
2134         }
2135
2136         rgbnor |= TEX_NOR;
2137         return rgbnor;
2138 }
2139
2140 void do_material_tex(ShadeInput *shi, Render *re)
2141 {
2142         const bool skip_load_image = (R.r.scemode & R_NO_IMAGE_LOAD) != 0;
2143         CompatibleBump compat_bump;
2144         NTapBump ntap_bump;
2145         MTex *mtex;
2146         Tex *tex;
2147         TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
2148         float *co = NULL, *dx = NULL, *dy = NULL;
2149         float fact, facm, factt, facmm, stencilTin=1.0;
2150         float texvec[3], dxt[3], dyt[3], tempvec[3], norvec[3], warpvec[3]={0.0f, 0.0f, 0.0f}, Tnor=1.0;
2151         int tex_nr, rgbnor= 0;
2152         bool warp_done = false, use_compat_bump = false, use_ntap_bump = false;
2153         bool found_nmapping = false, found_deriv_map = false;
2154         bool iFirstTimeNMap = true;
2155
2156         compatible_bump_init(&compat_bump);
2157         ntap_bump_init(&ntap_bump);
2158
2159         if (re->r.scemode & R_NO_TEX) return;
2160         /* here: test flag if there's a tex (todo) */
2161
2162         for (tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) {
2163                 
2164                 /* separate tex switching */
2165                 if (shi->mat->septex & (1<<tex_nr)) continue;
2166                 
2167                 if (shi->mat->mtex[tex_nr]) {
2168                         mtex= shi->mat->mtex[tex_nr];
2169                         
2170                         tex= mtex->tex;
2171                         if (tex == NULL) continue;
2172
2173                         found_deriv_map = (tex->type==TEX_IMAGE) && (tex->imaflag & TEX_DERIVATIVEMAP);
2174                         use_compat_bump= (mtex->texflag & MTEX_COMPAT_BUMP) != 0;
2175                         use_ntap_bump = ((mtex->texflag & (MTEX_3TAP_BUMP|MTEX_5TAP_BUMP|MTEX_BICUBIC_BUMP))!=0 || found_deriv_map!=0) ? true : false;
2176
2177                         /* XXX texture node trees don't work for this yet */
2178                         if (tex->nodetree && tex->use_nodes) {
2179                                 use_compat_bump = false;
2180                                 use_ntap_bump = false;
2181                         }
2182                         
2183                         /* case displacement mapping */
2184                         if (shi->osatex == 0 && use_ntap_bump) {
2185                                 use_ntap_bump = false;
2186                                 use_compat_bump = true;
2187                         }
2188                         
2189                         /* case ocean */
2190                         if (tex->type == TEX_OCEAN) {
2191                                 use_ntap_bump = false;
2192                                 use_compat_bump = false;
2193                         }
2194
2195                         /* which coords */
2196                         if (mtex->texco==TEXCO_ORCO) {
2197                                 if (mtex->texflag & MTEX_DUPLI_MAPTO) {
2198                                         co= shi->duplilo; dx= dxt; dy= dyt;
2199                                         dxt[0]= dxt[1]= dxt[2]= 0.0f;
2200                                         dyt[0]= dyt[1]= dyt[2]= 0.0f;
2201                                 }
2202                                 else {
2203                                         co= shi->lo; dx= shi->dxlo; dy= shi->dylo;
2204                                 }
2205                         }
2206                         else if (mtex->texco==TEXCO_OBJECT) {
2207                                 Object *ob= mtex->object;
2208                                 if (ob) {
2209                                         co= tempvec;
2210                                         dx= dxt;
2211                                         dy= dyt;
2212                                         copy_v3_v3(tempvec, shi->co);
2213                                         if (mtex->texflag & MTEX_OB_DUPLI_ORIG)
2214                                                 if (shi->obi && shi->obi->duplitexmat)
2215                                                         mul_m4_v3(shi->obi->duplitexmat, tempvec);
2216                                         mul_m4_v3(ob->imat_ren, tempvec);
2217                                         if (shi->osatex) {
2218                                                 copy_v3_v3(dxt, shi->dxco);
2219                                                 copy_v3_v3(dyt, shi->dyco);
2220                                                 mul_mat3_m4_v3(ob->imat_ren, dxt);
2221                                                 mul_mat3_m4_v3(ob->imat_ren, dyt);
2222                                         }
2223                                 }
2224                                 else {
2225                                         /* if object doesn't exist, do not use orcos (not initialized) */
2226                                         co= shi->co;
2227                                         dx= shi->dxco; dy= shi->dyco;
2228                                 }
2229                         }
2230                         else if (mtex->texco==TEXCO_REFL) {
2231                                 calc_R_ref(shi);
2232                                 co= shi->ref; dx= shi->dxref; dy= shi->dyref;
2233                         }
2234                         else if (mtex->texco==TEXCO_NORM) {
2235                                 co= shi->orn; dx= shi->dxno; dy= shi->dyno;
2236                         }
2237                         else if (mtex->texco==TEXCO_TANGENT) {
2238                                 co= shi->tang; dx= shi->dxno; dy= shi->dyno;
2239                         }
2240                         else if (mtex->texco==TEXCO_GLOB) {
2241                                 co= shi->gl; dx= shi->dxgl; dy= shi->dygl;
2242                         }
2243                         else if (mtex->texco==TEXCO_UV) {
2244                                 if (mtex->texflag & MTEX_DUPLI_MAPTO) {
2245                                         co= shi->dupliuv; dx= dxt; dy= dyt;
2246                                         dxt[0]= dxt[1]= dxt[2]= 0.0f;
2247                                         dyt[0]= dyt[1]= dyt[2]= 0.0f;
2248                                 }
2249                                 else {
2250                                         ShadeInputUV *suv= &shi->uv[shi->actuv];
2251                                         int i = shi->actuv;
2252
2253                                         if (mtex->uvname[0] != 0) {
2254                                                 for (i = 0; i < shi->totuv; i++) {
2255                                                         if (STREQ(shi->uv[i].name, mtex->uvname)) {
2256                                                                 suv= &shi->uv[i];
2257                                                                 break;
2258                                                         }
2259                                                 }
2260                                         }
2261
2262                                         co= suv->uv;
2263                                         dx= suv->dxuv;
2264                                         dy= suv->dyuv; 
2265
2266                                         compatible_bump_uv_derivs(&compat_bump, shi, mtex, i);
2267                                 }
2268                         }
2269                         else if (mtex->texco==TEXCO_WINDOW) {
2270                                 co= shi->winco; dx= shi->dxwin; dy= shi->dywin;
2271                         }
2272                         else if (mtex->texco==TEXCO_STRAND) {
2273                                 co= tempvec; dx= dxt; dy= dyt;
2274                                 co[0]= shi->strandco;
2275                                 co[1]= co[2]= 0.0f;
2276                                 dx[0]= shi->dxstrand;
2277                                 dx[1]= dx[2]= 0.0f;
2278                                 dy[0]= shi->dystrand;
2279                                 dy[1]= dy[2]= 0.0f;
2280                         }
2281                         else if (mtex->texco==TEXCO_STRESS) {
2282                                 co= tempvec; dx= dxt; dy= dyt;
2283                                 co[0]= shi->stress;
2284                                 co[1]= co[2]= 0.0f;
2285                                 dx[0]= 0.0f;
2286                                 dx[1]= dx[2]= 0.0f;
2287                                 dy[0]= 0.0f;
2288                                 dy[1]= dy[2]= 0.0f;
2289                         }
2290                         else {
2291                                 continue;  /* can happen when texco defines disappear and it renders old files */
2292                         }
2293
2294                         /* the pointer defines if bumping happens */
2295                         if (mtex->mapto & (MAP_NORM|MAP_WARP)) {
2296                                 texres.nor= norvec;
2297                                 norvec[0]= norvec[1]= norvec[2]= 0.0;
2298                         }
2299                         else texres.nor= NULL;
2300                         
2301                         if (warp_done) {
2302                                 add_v3_v3v3(tempvec, co, warpvec);
2303                                 co= tempvec;
2304                         }
2305
2306                         /* XXX texture node trees don't work for this yet */
2307                         if (texres.nor && !((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP))) {
2308                                 if (use_compat_bump) {
2309                                         rgbnor = compatible_bump_compute(&compat_bump, shi, mtex, tex,
2310                                                                          &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt,
2311                                                                          re->pool, skip_load_image);
2312                                 }
2313                                 else if (use_ntap_bump) {
2314                                         rgbnor = ntap_bump_compute(&ntap_bump, shi, mtex, tex,
2315                                                                    &texres, Tnor*stencilTin, co, dx, dy, texvec, dxt, dyt,
2316                                                                    re->pool, skip_load_image);
2317                                 }
2318                                 else {
2319                                         texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2320                                         rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, &texres, re->pool, skip_load_image);
2321                                 }
2322                         }
2323                         else {
2324                                 texco_mapping(shi, tex, mtex, co, dx, dy, texvec, dxt, dyt);
2325                                 rgbnor = multitex_mtex(shi, mtex, texvec, dxt, dyt, &texres, re->pool, skip_load_image);
2326                         }
2327
2328                         /* texture output */
2329
2330                         if ((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) {
2331                                 texres.tin = rgb_to_grayscale(&texres.tr);
2332                                 rgbnor -= TEX_RGB;
2333                         }
2334                         if (mtex->texflag & MTEX_NEGATIVE) {
2335                                 if (rgbnor & TEX_RGB) {
2336                                         texres.tr= 1.0f-texres.tr;
2337                                         texres.tg= 1.0f-texres.tg;
2338                                         texres.tb= 1.0f-texres.tb;
2339                                 }
2340                                 texres.tin= 1.0f-texres.tin;
2341                         }
2342                         if (mtex->texflag & MTEX_STENCIL) {
2343                                 if (rgbnor & TEX_RGB) {
2344                                         fact= texres.ta;
2345                                         texres.ta*= stencilTin;
2346                                         stencilTin*= fact;
2347                                 }
2348                                 else {
2349                                         fact= texres.tin;
2350                                         texres.tin*= stencilTin;
2351                                         stencilTin*= fact;
2352                                 }
2353                         }
2354                         else {
2355                                 Tnor*= stencilTin;
2356                         }
2357                         
2358                         if (texres.nor) {
2359                                 if ((rgbnor & TEX_NOR)==0) {
2360                                         /* make our own normal */
2361                                         if (rgbnor & TEX_RGB) {
2362                                                 copy_v3_v3(texres.nor, &texres.tr);
2363                                         }
2364                                         else {
2365                                                 float co_nor= 0.5f * cosf(texres.tin - 0.5f);
2366                                                 float si = 0.5f * sinf(texres.tin - 0.5f);
2367                                                 float f1, f2;
2368
2369                                                 f1= shi->vn[0];
2370                                                 f2= shi->vn[1];
2371                                                 texres.nor[0]= f1*co_nor+f2*si;
2372                                                 f1= shi->vn[1];
2373                                                 f2= shi->vn[2];
2374                                                 texres.nor[1]= f1*co_nor+f2*si;
2375                                                 texres.nor[2]= f2*co_nor-f1*si;
2376                                         }
2377                                 }
2378                                 /* warping, local space */
2379                                 if (mtex->mapto & MAP_WARP) {
2380                                         float *warpnor= texres.nor, warpnor_[3];
2381                                         
2382                                         if (use_ntap_bump) {
2383                                                 copy_v3_v3(warpnor_, texres.nor);
2384                                                 warpnor= warpnor_;
2385                                                 normalize_v3(warpnor_);
2386                                         }
2387                                         warpvec[0]= mtex->warpfac*warpnor[0];
2388                                         warpvec[1]= mtex->warpfac*warpnor[1];
2389                                         warpvec[2]= mtex->warpfac*warpnor[2];
2390                                         warp_done = true;
2391                                 }
2392 #if 0                           
2393                                 if (mtex->texflag & MTEX_VIEWSPACE) {
2394                                         /* rotate to global coords */
2395                                         if (mtex->texco==TEXCO_ORCO || mtex->texco==TEXCO_UV) {
2396                                                 if (shi->vlr && shi->obr && shi->obr->ob) {
2397                                                         float len= normalize_v3(texres.nor);
2398                                                         /* can be optimized... (ton) */
2399                                                         mul_mat3_m4_v3(shi->obr->ob->obmat, texres.nor);
2400                                                         mul_mat3_m4_v3(re->viewmat, texres.nor);
2401                                                         normalize_v3(texres.nor);
2402                                                         mul_v3_fl(texres.nor, len);
2403                                                 }
2404                                         }
2405                                 }
2406 #endif
2407                         }
2408
2409                         /* mapping */
2410                         if (mtex->mapto & (MAP_COL | MAP_COLSPEC | MAP_COLMIR)) {
2411                                 float tcol[3];
2412                                 
2413                                 /* stencil maps on the texture control slider, not texture intensity value */
2414                                 copy_v3_v3(tcol, &texres.tr);
2415
2416                                 if ((rgbnor & TEX_RGB) == 0) {
2417                                         copy_v3_v3(tcol, &mtex->r);
2418                                 }
2419                                 else if (mtex->mapto & MAP_ALPHA) {
2420                                         texres.tin = stencilTin;
2421                                 }
2422                                 else {
2423                                         texres.tin = texres.ta;
2424                                 }
2425                                 
2426                                 /* inverse gamma correction */
2427                                 if (tex->type==TEX_IMAGE) {
2428                                         Image *ima = tex->ima;
2429                                         ImBuf *ibuf = BKE_image_pool_acquire_ibuf(ima, &tex->iuser, re->pool);
2430                                         
2431                                         /* don't linearize float buffers, assumed to be linear */
2432                                         if (ibuf && !(ibuf->rect_float) && R.scene_color_manage)
2433                                                 IMB_colormanagement_colorspace_to_scene_linear_v3(tcol, ibuf->rect_colorspace);
2434
2435                                         BKE_image_pool_release_ibuf(ima, ibuf, re->pool);
2436                                 }
2437                                 
2438                                 if (mtex->mapto & MAP_COL) {
2439                                         float colfac= mtex->colfac*stencilTin;
2440                                         texture_rgb_blend(&shi->r, tcol, &shi->r, texres.tin, colfac, mtex->blendtype);
2441                                 }
2442                                 if (mtex->mapto & MAP_COLSPEC) {
2443                                         float colspecfac= mtex->colspecfac*stencilTin;
2444                                         texture_rgb_blend(&shi->specr, tcol, &shi->specr, texres.tin, colspecfac, mtex->blendtype);
2445                                 }
2446                                 if (mtex->mapto & MAP_COLMIR) {
2447                                         float mirrfac= mtex->mirrfac*stencilTin;
2448
2449                                         /* exception for envmap only */
2450                                         if (tex->type==TEX_ENVMAP && mtex->blendtype==MTEX_BLEND) {
2451                                                 fact= texres.tin*mirrfac;
2452                                                 facm= 1.0f- fact;
2453                                                 shi->refcol[0]= fact + facm*shi->refcol[0];
2454                                                 shi->refcol[1]= fact*tcol[0] + facm*shi->refcol[1];
2455                                                 shi->refcol[2]= fact*tcol[1] + facm*shi->refcol[2];
2456                                                 shi->refcol[3]= fact*tcol[2] + facm*shi->refcol[3];
2457                                         }
2458                                         else {
2459                                                 texture_rgb_blend(&shi->mirr, tcol, &shi->mirr, texres.tin, mirrfac, mtex->blendtype);
2460                                         }
2461                                 }
2462                         }
2463                         if ( (mtex->mapto & MAP_NORM) ) {
2464                                 if (texres.nor) {
2465                                         float norfac= mtex->norfac;
2466                                         
2467                                         /* we need to code blending modes for normals too once.. now 1 exception hardcoded */
2468                                         
2469                                         if ((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP)) {
2470                                                 
2471                                                 found_nmapping = 1;
2472                                                 
2473                                                 /* qdn: for normalmaps, to invert the normalmap vector,
2474                                                  * it is better to negate x & y instead of subtracting the vector as was done before */
2475                                                 if (norfac < 0.0f) {
2476                                                         texres.nor[0] = -texres.nor[0];
2477                                                         texres.nor[1] = -texres.nor[1];
2478                                                 }
2479                                                 fact = Tnor*fabsf(norfac);
2480                                                 if (fact>1.f) fact = 1.f;
2481                                                 facm = 1.f-fact;
2482                                                 if (mtex->normapspace == MTEX_NSPACE_TANGENT) {
2483                                                         /* qdn: tangent space */
2484                                                         float B[3], tv[3];
2485                                                         const float *no = iFirstTimeNMap ? shi->nmapnorm : shi->vn;
2486                                                         iFirstTimeNMap = false;
2487                                                         cross_v3_v3v3(B, no, shi->nmaptang);    /* bitangent */
2488                                                         mul_v3_fl(B, shi->nmaptang[3]);
2489                                                         /* transform norvec from tangent space to object surface in camera space */
2490                                                         tv[0] = texres.nor[0]*shi->nmaptang[0] + texres.nor[1]*B[0] + texres.nor[2]*no[0];
2491                                                         tv[1] = texres.nor[0]*shi->nmaptang[1] + texres.nor[1]*B[1] + texres.nor[2]*no[1];
2492                                                         tv[2] = texres.nor[0]*shi->nmaptang[2] + texres.nor[1]*B[2] + texres.nor[2]*no[2];
2493                                                         shi->vn[0]= facm*no[0] + fact*tv[0];
2494                                                         shi->vn[1]= facm*no[1] + fact*tv[1];
2495                                                         shi->vn[2]= facm*no[2] + fact*tv[2];
2496                                                 }
2497                                                 else {
2498                                                         float nor[3];
2499
2500                                                         copy_v3_v3(nor, texres.nor);
2501
2502                                                         if (mtex->normapspace == MTEX_NSPACE_CAMERA) {
2503                                                                 /* pass */
2504                                                         }
2505                                                         else if (mtex->normapspace == MTEX_NSPACE_WORLD) {
2506                                                                 mul_mat3_m4_v3(re->viewmat, nor);
2507                                                         }
2508                                                         else if (mtex->normapspace == MTEX_NSPACE_OBJECT) {
2509                                                                 if (shi->obr && shi->obr->ob)
2510                                                                         mul_mat3_m4_v3(shi->obr->ob->obmat, nor);
2511                                                                 mul_mat3_m4_v3(re->viewmat, nor);
2512                                                         }
2513
2514                                                         normalize_v3(nor);
2515
2516                                                         /* qdn: worldspace */
2517                                                         shi->vn[0]= facm*shi->vn[0] + fact*nor[0];
2518                                                         shi->vn[1]= facm*shi->vn[1] + fact*nor[1];
2519                                                         shi->vn[2]= facm*shi->vn[2] + fact*nor[2];
2520                                                 }
2521                                         }
2522                                         else {
2523                                                 /* XXX texture node trees don't work for this yet */
2524                                                 if (use_compat_bump || use_ntap_bump) {
2525                                                         shi->vn[0] = texres.nor[0];
2526                                                         shi->vn[1] = texres.nor[1];
2527                                                         shi->vn[2] = texres.nor[2];
2528                                                 }
2529                                                 else {
2530                                                         float nor[3], dot;
2531         
2532                                                         if (shi->mat->mode & MA_TANGENT_V) {
2533                                                                 shi->tang[0]+= Tnor*norfac*texres.nor[0];
2534                                                                 shi->tang[1]+= Tnor*norfac*texres.nor[1];
2535                                                                 shi->tang[2]+= Tnor*norfac*texres.nor[2];
2536                                                         }
2537         
2538                                                         /* prevent bump to become negative normal */
2539                                                         nor[0]= Tnor*norfac*texres.nor[0];
2540                                                         nor[1]= Tnor*norfac*texres.nor[1];
2541                                                         nor[2]= Tnor*norfac*texres.nor[2];
2542                                                         
2543                                                         dot= 0.5f + 0.5f * dot_v3v3(nor, shi->vn);
2544                                                         
2545                                                         shi->vn[0]+= dot*nor[0];
2546                                                         shi->vn[1]+= dot*nor[1];
2547                                                         shi->vn[2]+= dot*nor[2];
2548                                                 }
2549                                         }
2550                                         normalize_v3(shi->vn);
2551                                         
2552                                         /* this makes sure the bump is passed on to the next texture */
2553                                         shi->orn[0]= -shi->vn[0];
2554                                         shi->orn[1]= -shi->vn[1];
2555                                         shi->orn[2]= -shi->vn[2];
2556                                 }
2557                         }
2558
2559                         if ( mtex->mapto & MAP_DISPLACE ) {
2560                                 /* Now that most textures offer both Nor and Intensity, allow  */
2561                                 /* both to work, and let user select with slider.   */
2562                                 if (texres.nor) {
2563                                         float norfac= mtex->norfac;
2564
2565                                         shi->displace[0]+= 0.2f*Tnor*norfac*texres.nor[0];
2566                                         shi->displace[1]+= 0.2f*Tnor*norfac*texres.nor[1];
2567                                         shi->displace[2]+= 0.2f*Tnor*norfac*texres.nor[2];
2568                                 }
2569                                 
2570                                 if (rgbnor & TEX_RGB) {
2571                                         texres.tin = rgb_to_grayscale(&texres.tr);
2572                                 }
2573
2574                                 factt= (0.5f-texres.tin)*mtex->dispfac*stencilTin; facmm= 1.0f-factt;
2575
2576                                 if (mtex->blendtype==MTEX_BLEND) {
2577                                         shi->displace[0]= factt*shi->vn[0] + facmm*shi->displace[0];
2578                                         shi->displace[1]= factt*shi->vn[1] + facmm*shi->displace[1];
2579                                         shi->displace[2]= factt*shi->vn[2] + facmm*shi->displace[2];
2580                                 }
2581                                 else if (mtex->blendtype==MTEX_MUL) {
2582                                         shi->displace[0]*= factt*shi->vn[0];
2583                                         shi->displace[1]*= factt*shi->vn[1];
2584                                         shi->displace[2]*= factt*shi->vn[2];
2585                                 }
2586                                 else { /* add or sub */
2587                                         if (mtex->blendtype==MTEX_SUB) factt= -factt;
2588                                         shi->displace[0]+= factt*shi->vn[0];
2589                                         shi->displace[1]+= factt*shi->vn[1];
2590                                         shi->displace[2]+= factt*shi->vn[2];
2591                                 }
2592                         }
2593
2594                         if (mtex->mapto & MAP_VARS) {
2595                                 /* stencil maps on the texture control slider, not texture intensity value */
2596                                 
2597                                 if (rgbnor & TEX_RGB) {
2598                                         if (texres.talpha) texres.tin = texres.ta;
2599                                         else               texres.tin = rgb_to_grayscale(&texres.tr);
2600                                 }
2601
2602                                 if (mtex->mapto & MAP_REF) {
2603                                         float difffac= mtex->difffac*stencilTin;
2604
2605                                         shi->refl= texture_value_blend(mtex->def_var, shi->refl, texres.tin, difffac, mtex->blendtype);
2606                                         if (shi->refl<0.0f) shi->refl= 0.0f;
2607                                 }
2608                                 if (mtex->mapto & MAP_SPEC) {
2609                                         float specfac= mtex->specfac*stencilTin;
2610                                         
2611                                         shi->spec= texture_value_blend(mtex->def_var, shi->spec, texres.tin, specfac, mtex->blendtype);
2612                                         if (shi->spec<0.0f) shi->spec= 0.0f;
2613                                 }
2614                                 if (mtex->mapto & MAP_EMIT) {
2615                                         float emitfac= mtex->emitfac*stencilTin;
2616
2617                                         shi->emit= texture_value_blend(mtex->def_var, shi->emit, texres.tin, emitfac, mtex->blendtype);
2618                                         if (shi->emit<0.0f) shi->emit= 0.0f;
2619                                 }
2620                                 if (mtex->mapto & MAP_ALPHA) {
2621                                         float alphafac= mtex->alphafac*stencilTin;
2622
2623                                         shi->alpha= texture_value_blend(mtex->def_var, shi->alpha, texres.tin, alphafac, mtex->blendtype);
2624                                         if (shi->alpha<0.0f) shi->alpha= 0.0f;
2625                                         else if (shi->alpha>1.0f) shi->alpha= 1.0f;
2626                                 }
2627                                 if (mtex->mapto & MAP_HAR) {
2628                                         float har;  /* have to map to 0-1 */
2629                                         float hardfac= mtex->hardfac*stencilTin;
2630                                         
2631                                         har= ((float)shi->har)/128.0f;
2632                                         har= 128.0f*texture_value_blend(mtex->def_var, har, texres.tin, hardfac, mtex->blendtype);
2633                                         
2634                                         if (har<1.0f) shi->har= 1;
2635                                         else if (har>511) shi->har= 511;
2636                                         else shi->har= (int)har;
2637                                 }
2638                                 if (mtex->mapto & MAP_RAYMIRR) {
2639                                         float raymirrfac= mtex->raymirrfac*stencilTin;
2640
2641                                         shi->ray_mirror= texture_value_blend(mtex->def_var, shi->ray_mirror, texres.tin, raymirrfac, mtex->blendtype);
2642                                         if (shi->ray_mirror<0.0f) shi->ray_mirror= 0.0f;
2643                                         else if (shi->ray_mirror>1.0f) shi->ray_mirror= 1.0f;
2644                                 }
2645                                 if (mtex->mapto & MAP_TRANSLU) {
2646                                         float translfac= mtex->translfac*stencilTin;
2647
2648                                         shi->translucency= texture_value_blend(mtex->def_var, shi->translucency, texres.tin, translfac, mtex->blendtype);
2649                                         if (shi->translucency<0.0f) shi->translucency= 0.0f;
2650                                         else if (shi->translucency>1.0f) shi->translucency= 1.0f;
2651                                 }
2652                                 if (mtex->mapto & MAP_AMB) {
2653                                         float ambfac= mtex->ambfac*stencilTin;
2654
2655                                         shi->amb= texture_value_blend(mtex->def_var, shi->amb, texres.tin, ambfac, mtex->blendtype);
2656                                         if (shi->amb<0.0f) shi->amb= 0.0f;
2657                                         else if (shi->amb>1.0f) shi->amb= 1.0f;
2658                                         
2659                                         shi->ambr= shi->amb*re->wrld.ambr;
2660                                         shi->ambg= shi->amb*re->wrld.ambg;
2661                                         shi->ambb= shi->amb*re->wrld.ambb;
2662                                 }
2663                         }
2664                 }
2665         }
2666         if ((use_compat_bump || use_ntap_bump || found_nmapping) && (shi->mat->mode & MA_TANGENT_V) != 0) {
2667                 const float fnegdot = -dot_v3v3(shi->vn, shi->tang);
2668                 /* apply Gram-Schmidt projection */
2669                 madd_v3_v3fl(shi->tang,  shi->vn, fnegdot);
2670                 normalize_v3(shi->tang);
2671         }
2672 }
2673
2674
2675 void do_volume_tex(ShadeInput *shi, const float *xyz, int mapto_flag, float col_r[3], float *val, Render *re)
2676 {
2677         const bool skip_load_image = (re->r.scemode & R_NO_IMAGE_LOAD) != 0;
2678         MTex *mtex;
2679         Tex *tex;
2680         TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL};
2681         int tex_nr, rgbnor= 0;
2682         float co[3], texvec[3];
2683         float fact, stencilTin=1.0;
2684         
2685         if (re->r.scemode & R_NO_TEX) return;
2686         /* here: test flag if there's a tex (todo) */
2687         
2688         for (tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) {
2689                 /* separate tex switching */
2690                 if (shi->mat->septex & (1<<tex_nr)) continue;
2691                 
2692                 if (shi->mat->mtex[tex_nr]) {
2693                         mtex= shi->mat->mtex[tex_nr];
2694                         tex= mtex->tex;
2695                         if (tex == NULL) continue;
2696                         
2697                         /* only process if this texture is mapped 
2698                          * to one that we're interested in */
2699                         if (!(mtex->mapto & mapto_flag)) continue;
2700                         
2701                         /* which coords */
2702                         if (mtex->texco==TEXCO_OBJECT) {
2703                                 Object *ob= mtex->object;
2704                                 if (ob) {
2705                                         copy_v3_v3(co, xyz);
2706                                         if (mtex->texflag & MTEX_OB_DUPLI_ORIG) {
2707                                                 if (shi->obi && shi->obi->duplitexmat)
2708                                                         mul_m4_v3(shi->obi->duplitexmat, co);
2709                                         }
2710                                         mul_m4_v3(ob->imat_ren, co);
2711
2712                                         if (mtex->texflag & MTEX_MAPTO_BOUNDS && ob->bb) {
2713                                                 /* use bb vec[0] as min and bb vec[6] as max */
2714                                                 co[0] = (co[0] - ob->bb->vec[0][0]) / (ob->bb->vec[6][0]-ob->bb->vec[0][0]) * 2.0f - 1.0f;
2715                                                 co[1] = (co[1] - ob->bb->vec[0][1]) / (ob->bb->vec[6][1]-ob->bb->vec[0][1]) * 2.0f - 1.0f;
2716                                                 co[2] = (co[2] - ob->bb->vec[0][2]) / (ob->bb->vec[6][2]-ob->bb->vec[0][2]) * 2.0f - 1.0f;
2717                                         }
2718                                 }
2719                         }
2720                         /* not really orco, but 'local' */
2721                         else if (mtex->texco==TEXCO_ORCO) {
2722                                 
2723                                 if (mtex->texflag & MTEX_DUPLI_MAPTO) {
2724                                         copy_v3_v3(co, shi->duplilo);
2725                                 }
2726                                 else {
2727                                         Object *ob= shi->obi->ob;
2728                                         copy_v3_v3(co, xyz);
2729                  &