6b8d486ae56e5636e78d3d8299b63bc1fbd05981
[blender.git] / source / blender / blenkernel / intern / material.c
1
2 /*  material.c
3  *
4  * 
5  * $Id$
6  *
7  * ***** BEGIN GPL LICENSE BLOCK *****
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL LICENSE BLOCK *****
31  */
32
33 /** \file blender/blenkernel/intern/material.c
34  *  \ingroup bke
35  */
36
37
38 #include <string.h>
39 #include <math.h>
40 #include <stddef.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_curve_types.h"
45 #include "DNA_material_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_customdata_types.h"
49 #include "DNA_ID.h"
50 #include "DNA_meta_types.h"
51 #include "DNA_node_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_scene_types.h"
54
55 #include "BLI_math.h"           
56 #include "BLI_listbase.h"               
57 #include "BLI_utildefines.h"
58
59 #include "BKE_animsys.h"
60 #include "BKE_displist.h"
61 #include "BKE_global.h"
62 #include "BKE_icons.h"
63 #include "BKE_image.h"
64 #include "BKE_library.h"
65 #include "BKE_main.h"
66 #include "BKE_material.h"
67 #include "BKE_mesh.h"
68 #include "BKE_node.h"
69 #include "BKE_curve.h"
70
71 #include "GPU_material.h"
72
73 /* used in UI and render */
74 Material defmaterial;
75
76 /* called on startup, creator.c */
77 void init_def_material(void)
78 {
79         init_material(&defmaterial);
80 }
81
82 /* not material itself */
83 void free_material(Material *ma)
84 {
85         MTex *mtex;
86         int a;
87         
88         for(a=0; a<MAX_MTEX; a++) {
89                 mtex= ma->mtex[a];
90                 if(mtex && mtex->tex) mtex->tex->id.us--;
91                 if(mtex) MEM_freeN(mtex);
92         }
93         
94         if(ma->ramp_col) MEM_freeN(ma->ramp_col);
95         if(ma->ramp_spec) MEM_freeN(ma->ramp_spec);
96         
97         BKE_free_animdata((ID *)ma);
98         
99         if(ma->preview)
100                 BKE_previewimg_free(&ma->preview);
101         BKE_icon_delete((struct ID*)ma);
102         ma->id.icon_id = 0;
103         
104         /* is no lib link block, but material extension */
105         if(ma->nodetree) {
106                 ntreeFreeTree(ma->nodetree);
107                 MEM_freeN(ma->nodetree);
108         }
109
110         if(ma->gpumaterial.first)
111                 GPU_material_free(ma);
112 }
113
114 void init_material(Material *ma)
115 {
116         ma->r= ma->g= ma->b= ma->ref= 0.8;
117         ma->specr= ma->specg= ma->specb= 1.0;
118         ma->mirr= ma->mirg= ma->mirb= 1.0;
119         ma->spectra= 1.0;
120         ma->amb= 1.0;
121         ma->alpha= 1.0;
122         ma->spec= ma->hasize= 0.5;
123         ma->har= 50;
124         ma->starc= ma->ringc= 4;
125         ma->linec= 12;
126         ma->flarec= 1;
127         ma->flaresize= ma->subsize= 1.0;
128         ma->flareboost= 1;
129         ma->seed2= 6;
130         ma->friction= 0.5;
131         ma->refrac= 4.0;
132         ma->roughness= 0.5;
133         ma->param[0]= 0.5;
134         ma->param[1]= 0.1;
135         ma->param[2]= 0.5;
136         ma->param[3]= 0.1;
137         ma->rms= 0.1;
138         ma->darkness= 1.0;      
139         
140         ma->strand_sta= ma->strand_end= 1.0f;
141         
142         ma->ang= 1.0;
143         ma->ray_depth= 2;
144         ma->ray_depth_tra= 2;
145         ma->fresnel_mir= 0.0;
146         ma->fresnel_tra= 0.0;
147         ma->fresnel_tra_i= 1.25;
148         ma->fresnel_mir_i= 1.25;
149         ma->tx_limit= 0.0;
150         ma->tx_falloff= 1.0;
151         ma->shad_alpha= 1.0f;
152         
153         ma->gloss_mir = ma->gloss_tra= 1.0;
154         ma->samp_gloss_mir = ma->samp_gloss_tra= 18;
155         ma->adapt_thresh_mir = ma->adapt_thresh_tra = 0.005;
156         ma->dist_mir = 0.0;
157         ma->fadeto_mir = MA_RAYMIR_FADETOSKY;
158         
159         ma->rampfac_col= 1.0;
160         ma->rampfac_spec= 1.0;
161         ma->pr_lamp= 3;                 /* two lamps, is bits */
162         ma->pr_type= MA_SPHERE;
163
164         ma->sss_radius[0]= 1.0f;
165         ma->sss_radius[1]= 1.0f;
166         ma->sss_radius[2]= 1.0f;
167         ma->sss_col[0]= 1.0f;
168         ma->sss_col[1]= 1.0f;
169         ma->sss_col[2]= 1.0f;
170         ma->sss_error= 0.05f;
171         ma->sss_scale= 0.1f;
172         ma->sss_ior= 1.3f;
173         ma->sss_colfac= 1.0f;
174         ma->sss_texfac= 0.0f;
175         ma->sss_front= 1.0f;
176         ma->sss_back= 1.0f;
177
178         ma->vol.density = 1.0f;
179         ma->vol.emission = 0.0f;
180         ma->vol.scattering = 1.0f;
181         ma->vol.reflection = 1.0f;
182         ma->vol.transmission_col[0] = ma->vol.transmission_col[1] = ma->vol.transmission_col[2] = 1.0f;
183         ma->vol.reflection_col[0] = ma->vol.reflection_col[1] = ma->vol.reflection_col[2] = 1.0f;
184         ma->vol.emission_col[0] = ma->vol.emission_col[1] = ma->vol.emission_col[2] = 1.0f;
185         ma->vol.density_scale = 1.0f;
186         ma->vol.depth_cutoff = 0.01f;
187         ma->vol.stepsize_type = MA_VOL_STEP_RANDOMIZED;
188         ma->vol.stepsize = 0.2f;
189         ma->vol.shade_type = MA_VOL_SHADE_SHADED;
190         ma->vol.shadeflag |= MA_VOL_PRECACHESHADING;
191         ma->vol.precache_resolution = 50;
192         ma->vol.ms_spread = 0.2f;
193         ma->vol.ms_diff = 1.f;
194         ma->vol.ms_intensity = 1.f;
195         
196         ma->game.flag=0;
197         ma->game.alpha_blend=0;
198         ma->game.face_orientation=0;
199         
200         ma->mode= MA_TRACEBLE|MA_SHADBUF|MA_SHADOW|MA_RAYBIAS|MA_TANGENT_STR|MA_ZTRANSP;
201         ma->shade_flag= MA_APPROX_OCCLUSION;
202         ma->preview = NULL;
203 }
204
205 Material *add_material(const char *name)
206 {
207         Material *ma;
208
209         ma= alloc_libblock(&G.main->mat, ID_MA, name);
210         
211         init_material(ma);
212         
213         return ma;      
214 }
215
216 /* XXX keep synced with next function */
217 Material *copy_material(Material *ma)
218 {
219         Material *man;
220         int a;
221         
222         man= copy_libblock(ma);
223         
224         id_lib_extern((ID *)man->group);
225         
226         for(a=0; a<MAX_MTEX; a++) {
227                 if(ma->mtex[a]) {
228                         man->mtex[a]= MEM_mallocN(sizeof(MTex), "copymaterial");
229                         memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex));
230                         id_us_plus((ID *)man->mtex[a]->tex);
231                 }
232         }
233         
234         if(ma->ramp_col) man->ramp_col= MEM_dupallocN(ma->ramp_col);
235         if(ma->ramp_spec) man->ramp_spec= MEM_dupallocN(ma->ramp_spec);
236         
237         if (ma->preview) man->preview = BKE_previewimg_copy(ma->preview);
238
239         if(ma->nodetree) {
240                 man->nodetree= ntreeCopyTree(ma->nodetree);     /* 0 == full new tree */
241         }
242
243         man->gpumaterial.first= man->gpumaterial.last= NULL;
244         
245         return man;
246 }
247
248 /* XXX (see above) material copy without adding to main dbase */
249 Material *localize_material(Material *ma)
250 {
251         Material *man;
252         int a;
253         
254         man= copy_libblock(ma);
255         BLI_remlink(&G.main->mat, man);
256
257         /* no increment for texture ID users, in previewrender.c it prevents decrement */
258         for(a=0; a<MAX_MTEX; a++) {
259                 if(ma->mtex[a]) {
260                         man->mtex[a]= MEM_mallocN(sizeof(MTex), "copymaterial");
261                         memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex));
262                 }
263         }
264         
265         if(ma->ramp_col) man->ramp_col= MEM_dupallocN(ma->ramp_col);
266         if(ma->ramp_spec) man->ramp_spec= MEM_dupallocN(ma->ramp_spec);
267         
268         man->preview = NULL;
269         
270         if(ma->nodetree)
271                 man->nodetree= ntreeLocalize(ma->nodetree);
272         
273         man->gpumaterial.first= man->gpumaterial.last= NULL;
274         
275         return man;
276 }
277
278 static void extern_local_material(Material *ma)
279 {
280         int i;
281         for(i=0; i < MAX_MTEX; i++) {
282                 if(ma->mtex[i]) id_lib_extern((ID *)ma->mtex[i]->tex);
283         }
284 }
285
286 void make_local_material(Material *ma)
287 {
288         Main *bmain= G.main;
289         Object *ob;
290         Mesh *me;
291         Curve *cu;
292         MetaBall *mb;
293         Material *man;
294         int a, local=0, lib=0;
295
296         /* - only lib users: do nothing
297                 * - only local users: set flag
298                 * - mixed: make copy
299                 */
300         
301         if(ma->id.lib==NULL) return;
302         if(ma->id.us==1) {
303                 ma->id.lib= NULL;
304                 ma->id.flag= LIB_LOCAL;
305
306                 new_id(&bmain->mat, (ID *)ma, NULL);
307                 extern_local_material(ma);
308                 return;
309         }
310         
311         /* test objects */
312         ob= bmain->object.first;
313         while(ob) {
314                 if(ob->mat) {
315                         for(a=0; a<ob->totcol; a++) {
316                                 if(ob->mat[a]==ma) {
317                                         if(ob->id.lib) lib= 1;
318                                         else local= 1;
319                                 }
320                         }
321                 }
322                 ob= ob->id.next;
323         }
324         /* test meshes */
325         me= bmain->mesh.first;
326         while(me) {
327                 if(me->mat) {
328                         for(a=0; a<me->totcol; a++) {
329                                 if(me->mat[a]==ma) {
330                                         if(me->id.lib) lib= 1;
331                                         else local= 1;
332                                 }
333                         }
334                 }
335                 me= me->id.next;
336         }
337         /* test curves */
338         cu= bmain->curve.first;
339         while(cu) {
340                 if(cu->mat) {
341                         for(a=0; a<cu->totcol; a++) {
342                                 if(cu->mat[a]==ma) {
343                                         if(cu->id.lib) lib= 1;
344                                         else local= 1;
345                                 }
346                         }
347                 }
348                 cu= cu->id.next;
349         }
350         /* test mballs */
351         mb= bmain->mball.first;
352         while(mb) {
353                 if(mb->mat) {
354                         for(a=0; a<mb->totcol; a++) {
355                                 if(mb->mat[a]==ma) {
356                                         if(mb->id.lib) lib= 1;
357                                         else local= 1;
358                                 }
359                         }
360                 }
361                 mb= mb->id.next;
362         }
363         
364         if(local && lib==0) {
365                 ma->id.lib= NULL;
366                 ma->id.flag= LIB_LOCAL;
367
368                 new_id(&bmain->mat, (ID *)ma, NULL);
369                 extern_local_material(ma);
370         }
371         else if(local && lib) {
372                 
373                 man= copy_material(ma);
374                 man->id.us= 0;
375                 
376                 /* do objects */
377                 ob= bmain->object.first;
378                 while(ob) {
379                         if(ob->mat) {
380                                 for(a=0; a<ob->totcol; a++) {
381                                         if(ob->mat[a]==ma) {
382                                                 if(ob->id.lib==NULL) {
383                                                         ob->mat[a]= man;
384                                                         man->id.us++;
385                                                         ma->id.us--;
386                                                 }
387                                         }
388                                 }
389                         }
390                         ob= ob->id.next;
391                 }
392                 /* do meshes */
393                 me= bmain->mesh.first;
394                 while(me) {
395                         if(me->mat) {
396                                 for(a=0; a<me->totcol; a++) {
397                                         if(me->mat[a]==ma) {
398                                                 if(me->id.lib==NULL) {
399                                                         me->mat[a]= man;
400                                                         man->id.us++;
401                                                         ma->id.us--;
402                                                 }
403                                         }
404                                 }
405                         }
406                         me= me->id.next;
407                 }
408                 /* do curves */
409                 cu= bmain->curve.first;
410                 while(cu) {
411                         if(cu->mat) {
412                                 for(a=0; a<cu->totcol; a++) {
413                                         if(cu->mat[a]==ma) {
414                                                 if(cu->id.lib==NULL) {
415                                                         cu->mat[a]= man;
416                                                         man->id.us++;
417                                                         ma->id.us--;
418                                                 }
419                                         }
420                                 }
421                         }
422                         cu= cu->id.next;
423                 }
424                 /* do mballs */
425                 mb= bmain->mball.first;
426                 while(mb) {
427                         if(mb->mat) {
428                                 for(a=0; a<mb->totcol; a++) {
429                                         if(mb->mat[a]==ma) {
430                                                 if(mb->id.lib==NULL) {
431                                                         mb->mat[a]= man;
432                                                         man->id.us++;
433                                                         ma->id.us--;
434                                                 }
435                                         }
436                                 }
437                         }
438                         mb= mb->id.next;
439                 }
440         }
441 }
442
443 /* for curve, mball, mesh types */
444 void extern_local_matarar(struct Material **matar, short totcol)
445 {
446         short i;
447         for(i= 0; i < totcol; i++) {
448                 id_lib_extern((ID *)matar[i]);
449         }
450 }
451
452 Material ***give_matarar(Object *ob)
453 {
454         Mesh *me;
455         Curve *cu;
456         MetaBall *mb;
457         
458         if(ob->type==OB_MESH) {
459                 me= ob->data;
460                 return &(me->mat);
461         }
462         else if ELEM3(ob->type, OB_CURVE, OB_FONT, OB_SURF) {
463                 cu= ob->data;
464                 return &(cu->mat);
465         }
466         else if(ob->type==OB_MBALL) {
467                 mb= ob->data;
468                 return &(mb->mat);
469         }
470         return NULL;
471 }
472
473 short *give_totcolp(Object *ob)
474 {
475         Mesh *me;
476         Curve *cu;
477         MetaBall *mb;
478         
479         if(ob->type==OB_MESH) {
480                 me= ob->data;
481                 return &(me->totcol);
482         }
483         else if ELEM3(ob->type, OB_CURVE, OB_FONT, OB_SURF) {
484                 cu= ob->data;
485                 return &(cu->totcol);
486         }
487         else if(ob->type==OB_MBALL) {
488                 mb= ob->data;
489                 return &(mb->totcol);
490         }
491         return NULL;
492 }
493
494 /* same as above but for ID's */
495 Material ***give_matarar_id(ID *id)
496 {
497         switch(GS(id->name)) {
498         case ID_ME:
499                 return &(((Mesh *)id)->mat);
500                 break;
501         case ID_CU:
502                 return &(((Curve *)id)->mat);
503                 break;
504         case ID_MB:
505                 return &(((MetaBall *)id)->mat);
506                 break;
507         }
508         return NULL;
509 }
510
511 short *give_totcolp_id(ID *id)
512 {
513         switch(GS(id->name)) {
514         case ID_ME:
515                 return &(((Mesh *)id)->totcol);
516                 break;
517         case ID_CU:
518                 return &(((Curve *)id)->totcol);
519                 break;
520         case ID_MB:
521                 return &(((MetaBall *)id)->totcol);
522                 break;
523         }
524         return NULL;
525 }
526
527 static void data_delete_material_index_id(ID *id, int index)
528 {
529         switch(GS(id->name)) {
530         case ID_ME:
531                 mesh_delete_material_index((Mesh *)id, index);
532                 break;
533         case ID_CU:
534                 curve_delete_material_index((Curve *)id, index);
535                 break;
536         case ID_MB:
537                 /* meta-elems dont have materials atm */
538                 break;
539         }
540 }
541
542 void material_append_id(ID *id, Material *ma)
543 {
544         Material ***matar;
545         if((matar= give_matarar_id(id))) {
546                 short *totcol= give_totcolp_id(id);
547                 Material **mat= MEM_callocN(sizeof(void *) * ((*totcol) + 1), "newmatar");
548                 if(*totcol) memcpy(mat, *matar, sizeof(void *) * (*totcol));
549                 if(*matar) MEM_freeN(*matar);
550
551                 *matar= mat;
552                 (*matar)[(*totcol)++]= ma;
553
554                 id_us_plus((ID *)ma);
555                 test_object_materials(id);
556         }
557 }
558
559 Material *material_pop_id(ID *id, int index, int remove_material_slot)
560 {
561         Material *ret= NULL;
562         Material ***matar;
563         if((matar= give_matarar_id(id))) {
564                 short *totcol= give_totcolp_id(id);
565                 if(index >= 0 && index < (*totcol)) {
566                         ret= (*matar)[index];
567                         id_us_min((ID *)ret);
568
569                         if (remove_material_slot) {
570                                 if(*totcol <= 1) {
571                                         *totcol= 0;
572                                         MEM_freeN(*matar);
573                                         *matar= NULL;
574                                 }
575                                 else {
576                                         Material **mat;
577                                         if(index + 1 != (*totcol))
578                                                 memmove((*matar)+index, (*matar)+(index+1), sizeof(void *) * ((*totcol) - (index + 1)));
579
580                                         (*totcol)--;
581                                         
582                                         mat= MEM_callocN(sizeof(void *) * (*totcol), "newmatar");
583                                         memcpy(mat, *matar, sizeof(void *) * (*totcol));
584                                         MEM_freeN(*matar);
585
586                                         *matar= mat;
587                                         test_object_materials(id);
588                                 }
589
590                                 /* decrease mat_nr index */
591                                 data_delete_material_index_id(id, index);
592                         }
593
594                         /* don't remove material slot, only clear it*/
595                         else
596                                 (*matar)[index]= NULL;
597                 }
598         }
599         
600         return ret;
601 }
602
603 Material *give_current_material(Object *ob, int act)
604 {
605         Material ***matarar, *ma;
606         short *totcolp;
607         
608         if(ob==NULL) return NULL;
609         
610         /* if object cannot have material, totcolp==NULL */
611         totcolp= give_totcolp(ob);
612         if(totcolp==NULL || ob->totcol==0) return NULL;
613         
614         if(act<0) {
615                 printf("no!\n");
616         }
617         
618         if(act>ob->totcol) act= ob->totcol;
619         else if(act<=0) act= 1;
620
621         if(ob->matbits && ob->matbits[act-1]) { /* in object */
622                 ma= ob->mat[act-1];
623         }
624         else {                                                          /* in data */
625
626                 /* check for inconsistency */
627                 if(*totcolp < ob->totcol)
628                         ob->totcol= *totcolp;
629                 if(act>ob->totcol) act= ob->totcol;
630
631                 matarar= give_matarar(ob);
632                 
633                 if(matarar && *matarar) ma= (*matarar)[act-1];
634                 else ma= NULL;
635                 
636         }
637         
638         return ma;
639 }
640
641 ID *material_from(Object *ob, int act)
642 {
643
644         if(ob==NULL) return NULL;
645
646         if(ob->totcol==0) return ob->data;
647         if(act==0) act= 1;
648
649         if(ob->matbits[act-1]) return (ID *)ob;
650         else return ob->data;
651 }
652
653 Material *give_node_material(Material *ma)
654 {
655         if(ma && ma->use_nodes && ma->nodetree) {
656                 bNode *node= nodeGetActiveID(ma->nodetree, ID_MA);
657
658                 if(node)
659                         return (Material *)node->id;
660         }
661
662         return NULL;
663 }
664
665 /* GS reads the memory pointed at in a specific ordering. There are,
666  * however two definitions for it. I have jotted them down here, both,
667  * but I think the first one is actually used. The thing is that
668  * big-endian systems might read this the wrong way round. OTOH, we
669  * constructed the IDs that are read out with this macro explicitly as
670  * well. I expect we'll sort it out soon... */
671
672 /* from blendef: */
673 #define GS(a)   (*((short *)(a)))
674
675 /* from misc_util: flip the bytes from x  */
676 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
677
678 void resize_object_material(Object *ob, const short totcol)
679 {
680         Material **newmatar;
681         char *newmatbits;
682
683         if(totcol==0) {
684                 if(ob->totcol) {
685                         MEM_freeN(ob->mat);
686                         MEM_freeN(ob->matbits);
687                         ob->mat= NULL;
688                         ob->matbits= NULL;
689                 }
690         }
691         else if(ob->totcol<totcol) {
692                 newmatar= MEM_callocN(sizeof(void *)*totcol, "newmatar");
693                 newmatbits= MEM_callocN(sizeof(char)*totcol, "newmatbits");
694                 if(ob->totcol) {
695                         memcpy(newmatar, ob->mat, sizeof(void *)*ob->totcol);
696                         memcpy(newmatbits, ob->matbits, sizeof(char)*ob->totcol);
697                         MEM_freeN(ob->mat);
698                         MEM_freeN(ob->matbits);
699                 }
700                 ob->mat= newmatar;
701                 ob->matbits= newmatbits;
702         }
703         ob->totcol= totcol;
704         if(ob->totcol && ob->actcol==0) ob->actcol= 1;
705         if(ob->actcol>ob->totcol) ob->actcol= ob->totcol;
706 }
707
708 void test_object_materials(ID *id)
709 {
710         /* make the ob mat-array same size as 'ob->data' mat-array */
711         Object *ob;
712         short *totcol;
713
714         if(id==NULL || (totcol=give_totcolp_id(id))==NULL) {
715                 return;
716         }
717
718         for(ob= G.main->object.first; ob; ob= ob->id.next) {
719                 if(ob->data==id) {
720                         resize_object_material(ob, *totcol);
721                 }
722         }
723 }
724
725 void assign_material(Object *ob, Material *ma, int act)
726 {
727         Material *mao, **matar, ***matarar;
728         char *matbits;
729         short *totcolp;
730
731         if(act>MAXMAT) return;
732         if(act<1) act= 1;
733         
734         /* prevent crashing when using accidentally */
735         BLI_assert(ob->id.lib == NULL);
736         if(ob->id.lib) return;
737         
738         /* test arraylens */
739         
740         totcolp= give_totcolp(ob);
741         matarar= give_matarar(ob);
742         
743         if(totcolp==NULL || matarar==NULL) return;
744         
745         if(act > *totcolp) {
746                 matar= MEM_callocN(sizeof(void *)*act, "matarray1");
747
748                 if(*totcolp) {
749                         memcpy(matar, *matarar, sizeof(void *)*(*totcolp));
750                         MEM_freeN(*matarar);
751                 }
752
753                 *matarar= matar;
754                 *totcolp= act;
755         }
756         
757         if(act > ob->totcol) {
758                 matar= MEM_callocN(sizeof(void *)*act, "matarray2");
759                 matbits= MEM_callocN(sizeof(char)*act, "matbits1");
760                 if( ob->totcol) {
761                         memcpy(matar, ob->mat, sizeof(void *)*( ob->totcol ));
762                         memcpy(matbits, ob->matbits, sizeof(char)*(*totcolp));
763                         MEM_freeN(ob->mat);
764                         MEM_freeN(ob->matbits);
765                 }
766                 ob->mat= matar;
767                 ob->matbits= matbits;
768                 ob->totcol= act;
769
770                 /* copy object/mesh linking, or assign based on userpref */
771                 if(ob->actcol)
772                         ob->matbits[act-1]= ob->matbits[ob->actcol-1];
773                 else
774                         ob->matbits[act-1]= (U.flag & USER_MAT_ON_OB)? 1: 0;
775         }
776         
777         /* do it */
778
779         if(ob->matbits[act-1]) {        /* in object */
780                 mao= ob->mat[act-1];
781                 if(mao) mao->id.us--;
782                 ob->mat[act-1]= ma;
783         }
784         else {  /* in data */
785                 mao= (*matarar)[act-1];
786                 if(mao) mao->id.us--;
787                 (*matarar)[act-1]= ma;
788         }
789
790         if(ma)
791                 id_us_plus((ID *)ma);
792         test_object_materials(ob->data);
793 }
794
795 /* XXX - this calls many more update calls per object then are needed, could be optimized */
796 void assign_matarar(struct Object *ob, struct Material ***matar, int totcol)
797 {
798         int i, actcol_orig= ob->actcol;
799
800         while(object_remove_material_slot(ob)) {};
801
802         /* now we have the right number of slots */
803         for(i=0; i<totcol; i++)
804                 assign_material(ob, (*matar)[i], i+1);
805
806         if(actcol_orig > ob->totcol)
807                 actcol_orig= ob->totcol;
808
809         ob->actcol= actcol_orig;
810 }
811
812
813 int find_material_index(Object *ob, Material *ma)
814 {
815         Material ***matarar;
816         short a, *totcolp;
817         
818         if(ma==NULL) return 0;
819         
820         totcolp= give_totcolp(ob);
821         matarar= give_matarar(ob);
822         
823         if(totcolp==NULL || matarar==NULL) return 0;
824         
825         for(a=0; a<*totcolp; a++)
826                 if((*matarar)[a]==ma)
827                    break;
828         if(a<*totcolp)
829                 return a+1;
830         return 0;          
831 }
832
833 int object_add_material_slot(Object *ob)
834 {
835         if(ob==NULL) return FALSE;
836         if(ob->totcol>=MAXMAT) return FALSE;
837         
838         assign_material(ob, NULL, ob->totcol+1);
839         ob->actcol= ob->totcol;
840         return TRUE;
841 }
842
843 static void do_init_render_material(Material *ma, int r_mode, float *amb)
844 {
845         MTex *mtex;
846         int a, needuv=0, needtang=0;
847         
848         if(ma->flarec==0) ma->flarec= 1;
849
850         /* add all texcoflags from mtex, texco and mapto were cleared in advance */
851         for(a=0; a<MAX_MTEX; a++) {
852                 
853                 /* separate tex switching */
854                 if(ma->septex & (1<<a)) continue;
855
856                 mtex= ma->mtex[a];
857                 if(mtex && mtex->tex && (mtex->tex->type | (mtex->tex->use_nodes && mtex->tex->nodetree) )) {
858                         
859                         ma->texco |= mtex->texco;
860                         ma->mapto |= mtex->mapto;
861
862                         /* always get derivatives for these textures */
863                         if ELEM3(mtex->tex->type, TEX_IMAGE, TEX_PLUGIN, TEX_ENVMAP) ma->texco |= TEXCO_OSA;
864                         else if(mtex->texflag & (MTEX_COMPAT_BUMP|MTEX_3TAP_BUMP|MTEX_5TAP_BUMP)) ma->texco |= TEXCO_OSA;
865                         
866                         if(ma->texco & (TEXCO_ORCO|TEXCO_REFL|TEXCO_NORM|TEXCO_STRAND|TEXCO_STRESS)) needuv= 1;
867                         else if(ma->texco & (TEXCO_GLOB|TEXCO_UV|TEXCO_OBJECT|TEXCO_SPEED)) needuv= 1;
868                         else if(ma->texco & (TEXCO_LAVECTOR|TEXCO_VIEW|TEXCO_STICKY)) needuv= 1;
869
870                         if((ma->mapto & MAP_NORM) && (mtex->normapspace == MTEX_NSPACE_TANGENT))
871                                 needtang= 1;
872                 }
873         }
874
875         if(needtang) ma->mode |= MA_NORMAP_TANG;
876         else ma->mode &= ~MA_NORMAP_TANG;
877         
878         if(ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP|MA_FACETEXTURE)) {
879                 needuv= 1;
880                 if(r_mode & R_OSA) ma->texco |= TEXCO_OSA;              /* for texfaces */
881         }
882         if(needuv) ma->texco |= NEED_UV;
883         
884         /* since the raytracer doesnt recalc O structs for each ray, we have to preset them all */
885         if(r_mode & R_RAYTRACE) {
886                 if((ma->mode & (MA_RAYMIRROR|MA_SHADOW_TRA)) || ((ma->mode & MA_TRANSP) && (ma->mode & MA_RAYTRANSP))) {
887                         ma->texco |= NEED_UV|TEXCO_ORCO|TEXCO_REFL|TEXCO_NORM;
888                         if(r_mode & R_OSA) ma->texco |= TEXCO_OSA;
889                 }
890         }
891         
892         if(amb) {
893                 ma->ambr= ma->amb*amb[0];
894                 ma->ambg= ma->amb*amb[1];
895                 ma->ambb= ma->amb*amb[2];
896         }       
897         /* will become or-ed result of all node modes */
898         ma->mode_l= ma->mode;
899         ma->mode_l &= ~MA_SHLESS;
900
901         if(ma->strand_surfnor > 0.0f)
902                 ma->mode_l |= MA_STR_SURFDIFF;
903
904         /* parses the geom+tex nodes */
905         if(ma->nodetree && ma->use_nodes)
906                 ntreeShaderGetTexcoMode(ma->nodetree, r_mode, &ma->texco, &ma->mode_l);
907 }
908
909 static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode, float *amb)
910 {
911         bNode *node;
912         
913         for(node=ntree->nodes.first; node; node= node->next) {
914                 if(node->id) {
915                         if(GS(node->id->name)==ID_MA) {
916                                 Material *ma= (Material *)node->id;
917                                 if(ma!=basemat) {
918                                         do_init_render_material(ma, r_mode, amb);
919                                         basemat->texco |= ma->texco;
920                                         basemat->mode_l |= ma->mode_l & ~(MA_TRANSP|MA_ZTRANSP|MA_RAYTRANSP); 
921                                 }
922                         }
923                         else if(node->type==NODE_GROUP)
924                                 init_render_nodetree((bNodeTree *)node->id, basemat, r_mode, amb);
925                 }
926         }
927 }
928
929 void init_render_material(Material *mat, int r_mode, float *amb)
930 {
931         
932         do_init_render_material(mat, r_mode, amb);
933         
934         if(mat->nodetree && mat->use_nodes) {
935                 init_render_nodetree(mat->nodetree, mat, r_mode, amb);
936                 
937                 if (!mat->nodetree->execdata)
938                         mat->nodetree->execdata = ntreeShaderBeginExecTree(mat->nodetree, 1);
939         }
940 }
941
942 void init_render_materials(Main *bmain, int r_mode, float *amb)
943 {
944         Material *ma;
945         
946         /* clear these flags before going over materials, to make sure they
947          * are cleared only once, otherwise node materials contained in other
948          * node materials can go wrong */
949         for(ma= bmain->mat.first; ma; ma= ma->id.next) {
950                 if(ma->id.us) {
951                         ma->texco= 0;
952                         ma->mapto= 0;
953                 }
954         }
955
956         /* two steps, first initialize, then or the flags for layers */
957         for(ma= bmain->mat.first; ma; ma= ma->id.next) {
958                 /* is_used flag comes back in convertblender.c */
959                 ma->flag &= ~MA_IS_USED;
960                 if(ma->id.us) 
961                         init_render_material(ma, r_mode, amb);
962         }
963         
964         do_init_render_material(&defmaterial, r_mode, amb);
965 }
966
967 /* only needed for nodes now */
968 void end_render_material(Material *mat)
969 {
970         if(mat && mat->nodetree && mat->use_nodes) {
971                 if (mat->nodetree->execdata)
972                         ntreeShaderEndExecTree(mat->nodetree->execdata, 1);
973         }
974 }
975
976 void end_render_materials(Main *bmain)
977 {
978         Material *ma;
979         for(ma= bmain->mat.first; ma; ma= ma->id.next)
980                 if(ma->id.us) 
981                         end_render_material(ma);
982 }
983
984 static int material_in_nodetree(bNodeTree *ntree, Material *mat)
985 {
986         bNode *node;
987
988         for(node=ntree->nodes.first; node; node= node->next) {
989                 if(node->id && GS(node->id->name)==ID_MA) {
990                         if(node->id==(ID*)mat)
991                                 return 1;
992                 }
993                 else if(node->type==NODE_GROUP)
994                         if(material_in_nodetree((bNodeTree*)node->id, mat))
995                                 return 1;
996         }
997
998         return 0;
999 }
1000
1001 int material_in_material(Material *parmat, Material *mat)
1002 {
1003         if(parmat==mat)
1004                 return 1;
1005         else if(parmat->nodetree && parmat->use_nodes)
1006                 return material_in_nodetree(parmat->nodetree, mat);
1007         else
1008                 return 0;
1009 }
1010         
1011 /* ****************** */
1012
1013 static char colname_array[125][20]= {
1014 "Black","DarkRed","HalfRed","Red","Red",
1015 "DarkGreen","DarkOlive","Brown","Chocolate","OrangeRed",
1016 "HalfGreen","GreenOlive","DryOlive","Goldenrod","DarkOrange",
1017 "LightGreen","Chartreuse","YellowGreen","Yellow","Gold",
1018 "Green","LawnGreen","GreenYellow","LightOlive","Yellow",
1019 "DarkBlue","DarkPurple","HotPink","VioletPink","RedPink",
1020 "SlateGray","DarkGrey","PalePurple","IndianRed","Tomato",
1021 "SeaGreen","PaleGreen","GreenKhaki","LightBrown","LightSalmon",
1022 "SpringGreen","PaleGreen","MediumOlive","YellowBrown","LightGold",
1023 "LightGreen","LightGreen","LightGreen","GreenYellow","PaleYellow",
1024 "HalfBlue","DarkSky","HalfMagenta","VioletRed","DeepPink",
1025 "SteelBlue","SkyBlue","Orchid","LightHotPink","HotPink",
1026 "SeaGreen","SlateGray","MediumGrey","Burlywood","LightPink",
1027 "SpringGreen","Aquamarine","PaleGreen","Khaki","PaleOrange",
1028 "SpringGreen","SeaGreen","PaleGreen","PaleWhite","YellowWhite",
1029 "LightBlue","Purple","MediumOrchid","Magenta","Magenta",
1030 "RoyalBlue","SlateBlue","MediumOrchid","Orchid","Magenta",
1031 "DeepSkyBlue","LightSteelBlue","LightSkyBlue","Violet","LightPink",
1032 "Cyan","DarkTurquoise","SkyBlue","Grey","Snow",
1033 "Mint","Mint","Aquamarine","MintCream","Ivory",
1034 "Blue","Blue","DarkMagenta","DarkOrchid","Magenta",
1035 "SkyBlue","RoyalBlue","LightSlateBlue","MediumOrchid","Magenta",
1036 "DodgerBlue","SteelBlue","MediumPurple","PalePurple","Plum",
1037 "DeepSkyBlue","PaleBlue","LightSkyBlue","PalePurple","Thistle",
1038 "Cyan","ColdBlue","PaleTurquoise","GhostWhite","White"
1039 };
1040
1041 void automatname(Material *ma)
1042 {
1043         int nr, r, g, b;
1044         float ref;
1045         
1046         if(ma==NULL) return;
1047         if(ma->mode & MA_SHLESS) ref= 1.0;
1048         else ref= ma->ref;
1049         
1050         r= (int)(4.99f*(ref*ma->r));
1051         g= (int)(4.99f*(ref*ma->g));
1052         b= (int)(4.99f*(ref*ma->b));
1053         nr= r + 5*g + 25*b;
1054         if(nr>124) nr= 124;
1055         new_id(&G.main->mat, (ID *)ma, colname_array[nr]);
1056         
1057 }
1058
1059
1060 int object_remove_material_slot(Object *ob)
1061 {
1062         Material *mao, ***matarar;
1063         Object *obt;
1064         short *totcolp;
1065         int a, actcol;
1066         
1067         if(ob==NULL || ob->totcol==0) return FALSE;
1068         
1069         /* take a mesh/curve/mball as starting point, remove 1 index,
1070          * AND with all objects that share the ob->data
1071          * 
1072          * after that check indices in mesh/curve/mball!!!
1073          */
1074         
1075         totcolp= give_totcolp(ob);
1076         matarar= give_matarar(ob);
1077
1078         if(*matarar==NULL) return FALSE;
1079
1080         /* we delete the actcol */
1081         if(ob->totcol) {
1082                 mao= (*matarar)[ob->actcol-1];
1083                 if(mao) mao->id.us--;
1084         }
1085         
1086         for(a=ob->actcol; a<ob->totcol; a++)
1087                 (*matarar)[a-1]= (*matarar)[a];
1088         (*totcolp)--;
1089         
1090         if(*totcolp==0) {
1091                 MEM_freeN(*matarar);
1092                 *matarar= NULL;
1093         }
1094         
1095         actcol= ob->actcol;
1096         obt= G.main->object.first;
1097         while(obt) {
1098         
1099                 if(obt->data==ob->data) {
1100                         
1101                         /* WATCH IT: do not use actcol from ob or from obt (can become zero) */
1102                         mao= obt->mat[actcol-1];
1103                         if(mao) mao->id.us--;
1104                 
1105                         for(a=actcol; a<obt->totcol; a++) {
1106                                 obt->mat[a-1]= obt->mat[a];
1107                                 obt->matbits[a-1]= obt->matbits[a];
1108                         }
1109                         obt->totcol--;
1110                         if(obt->actcol > obt->totcol) obt->actcol= obt->totcol;
1111                         
1112                         if(obt->totcol==0) {
1113                                 MEM_freeN(obt->mat);
1114                                 MEM_freeN(obt->matbits);
1115                                 obt->mat= NULL;
1116                                 obt->matbits= NULL;
1117                         }
1118                 }
1119                 obt= obt->id.next;
1120         }
1121
1122         /* check indices from mesh */
1123         if (ELEM4(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT)) {
1124                 data_delete_material_index_id((ID *)ob->data, actcol-1);
1125                 freedisplist(&ob->disp);
1126         }
1127
1128         return TRUE;
1129 }
1130
1131
1132 /* r g b = current value, col = new value, fac==0 is no change */
1133 /* if g==NULL, it only does r channel */
1134 void ramp_blend(int type, float *r, float *g, float *b, float fac, const float col[3])
1135 {
1136         float tmp, facm= 1.0f-fac;
1137         
1138         switch (type) {
1139                 case MA_RAMP_BLEND:
1140                         *r = facm*(*r) + fac*col[0];
1141                         if(g) {
1142                                 *g = facm*(*g) + fac*col[1];
1143                                 *b = facm*(*b) + fac*col[2];
1144                         }
1145                                 break;
1146                 case MA_RAMP_ADD:
1147                         *r += fac*col[0];
1148                         if(g) {
1149                                 *g += fac*col[1];
1150                                 *b += fac*col[2];
1151                         }
1152                                 break;
1153                 case MA_RAMP_MULT:
1154                         *r *= (facm + fac*col[0]);
1155                         if(g) {
1156                                 *g *= (facm + fac*col[1]);
1157                                 *b *= (facm + fac*col[2]);
1158                         }
1159                                 break;
1160                 case MA_RAMP_SCREEN:
1161                         *r = 1.0f - (facm + fac*(1.0f - col[0])) * (1.0f - *r);
1162                         if(g) {
1163                                 *g = 1.0f - (facm + fac*(1.0f - col[1])) * (1.0f - *g);
1164                                 *b = 1.0f - (facm + fac*(1.0f - col[2])) * (1.0f - *b);
1165                         }
1166                                 break;
1167                 case MA_RAMP_OVERLAY:
1168                         if(*r < 0.5f)
1169                                 *r *= (facm + 2.0f*fac*col[0]);
1170                         else
1171                                 *r = 1.0f - (facm + 2.0f*fac*(1.0f - col[0])) * (1.0f - *r);
1172                         if(g) {
1173                                 if(*g < 0.5f)
1174                                         *g *= (facm + 2.0f*fac*col[1]);
1175                                 else
1176                                         *g = 1.0f - (facm + 2.0f*fac*(1.0f - col[1])) * (1.0f - *g);
1177                                 if(*b < 0.5f)
1178                                         *b *= (facm + 2.0f*fac*col[2]);
1179                                 else
1180                                         *b = 1.0f - (facm + 2.0f*fac*(1.0f - col[2])) * (1.0f - *b);
1181                         }
1182                                 break;
1183                 case MA_RAMP_SUB:
1184                         *r -= fac*col[0];
1185                         if(g) {
1186                                 *g -= fac*col[1];
1187                                 *b -= fac*col[2];
1188                         }
1189                                 break;
1190                 case MA_RAMP_DIV:
1191                         if(col[0]!=0.0f)
1192                                 *r = facm*(*r) + fac*(*r)/col[0];
1193                         if(g) {
1194                                 if(col[1]!=0.0f)
1195                                         *g = facm*(*g) + fac*(*g)/col[1];
1196                                 if(col[2]!=0.0f)
1197                                         *b = facm*(*b) + fac*(*b)/col[2];
1198                         }
1199                                 break;
1200                 case MA_RAMP_DIFF:
1201                         *r = facm*(*r) + fac*fabsf(*r-col[0]);
1202                         if(g) {
1203                                 *g = facm*(*g) + fac*fabsf(*g-col[1]);
1204                                 *b = facm*(*b) + fac*fabsf(*b-col[2]);
1205                         }
1206                                 break;
1207                 case MA_RAMP_DARK:
1208                         tmp=col[0]+((1-col[0])*facm); 
1209                         if(tmp < *r) *r= tmp; 
1210                         if(g) { 
1211                                 tmp=col[1]+((1-col[1])*facm); 
1212                                 if(tmp < *g) *g= tmp; 
1213                                 tmp=col[2]+((1-col[2])*facm); 
1214                                 if(tmp < *b) *b= tmp; 
1215                         } 
1216                                 break; 
1217                 case MA_RAMP_LIGHT:
1218                         tmp= fac*col[0];
1219                         if(tmp > *r) *r= tmp; 
1220                                 if(g) {
1221                                         tmp= fac*col[1];
1222                                         if(tmp > *g) *g= tmp; 
1223                                         tmp= fac*col[2];
1224                                         if(tmp > *b) *b= tmp; 
1225                                 }
1226                                         break;  
1227                 case MA_RAMP_DODGE:                     
1228                         
1229                                 
1230                         if(*r !=0.0f){
1231                                 tmp = 1.0f - fac*col[0];
1232                                 if(tmp <= 0.0f)
1233                                         *r = 1.0f;
1234                                 else if ((tmp = (*r) / tmp)> 1.0f)
1235                                         *r = 1.0f;
1236                                 else 
1237                                         *r = tmp;
1238                         }
1239                         if(g) {
1240                                 if(*g !=0.0f){
1241                                         tmp = 1.0f - fac*col[1];
1242                                         if(tmp <= 0.0f )
1243                                                 *g = 1.0f;
1244                                         else if ((tmp = (*g) / tmp) > 1.0f )
1245                                                 *g = 1.0f;
1246                                         else
1247                                                 *g = tmp;
1248                                 }
1249                                 if(*b !=0.0f){
1250                                         tmp = 1.0f - fac*col[2];
1251                                         if(tmp <= 0.0f)
1252                                                 *b = 1.0f;
1253                                         else if ((tmp = (*b) / tmp) > 1.0f )
1254                                                 *b = 1.0f;
1255                                         else
1256                                                 *b = tmp;
1257                                 }
1258
1259                         }
1260                                 break;  
1261                 case MA_RAMP_BURN:
1262                         
1263                         tmp = facm + fac*col[0];
1264                         
1265                         if(tmp <= 0.0f)
1266                                 *r = 0.0f;
1267                         else if (( tmp = (1.0f - (1.0f - (*r)) / tmp )) < 0.0f)
1268                                         *r = 0.0f;
1269                         else if (tmp > 1.0f)
1270                                 *r=1.0f;
1271                         else 
1272                                 *r = tmp; 
1273
1274                         if(g) {
1275                                 tmp = facm + fac*col[1];
1276                                 if(tmp <= 0.0f)
1277                                         *g = 0.0f;
1278                                 else if (( tmp = (1.0f - (1.0f - (*g)) / tmp )) < 0.0f )
1279                                                 *g = 0.0f;
1280                                 else if(tmp >1.0f)
1281                                         *g=1.0f;
1282                                 else
1283                                         *g = tmp;
1284                                         
1285                                         tmp = facm + fac*col[2];
1286                                         if(tmp <= 0.0f)
1287                                         *b = 0.0f;
1288                                 else if (( tmp = (1.0f - (1.0f - (*b)) / tmp )) < 0.0f  )
1289                                                 *b = 0.0f;
1290                                 else if(tmp >1.0f)
1291                                         *b= 1.0f;
1292                                 else
1293                                         *b = tmp;
1294                         }
1295                                 break;
1296                 case MA_RAMP_HUE:               
1297                         if(g){
1298                                 float rH,rS,rV;
1299                                 float colH,colS,colV; 
1300                                 float tmpr,tmpg,tmpb;
1301                                 rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1302                                 if(colS!=0 ){
1303                                         rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1304                                         hsv_to_rgb( colH , rS, rV, &tmpr, &tmpg, &tmpb);
1305                                         *r = facm*(*r) + fac*tmpr;  
1306                                         *g = facm*(*g) + fac*tmpg; 
1307                                         *b = facm*(*b) + fac*tmpb;
1308                                 }
1309                         }
1310                                 break;
1311                 case MA_RAMP_SAT:               
1312                         if(g){
1313                                 float rH,rS,rV;
1314                                 float colH,colS,colV;
1315                                 rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1316                                 if(rS!=0){
1317                                         rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1318                                         hsv_to_rgb( rH, (facm*rS +fac*colS), rV, r, g, b);
1319                                 }
1320                         }
1321                                 break;
1322                 case MA_RAMP_VAL:               
1323                         if(g){
1324                                 float rH,rS,rV;
1325                                 float colH,colS,colV;
1326                                 rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1327                                 rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1328                                 hsv_to_rgb( rH, rS, (facm*rV +fac*colV), r, g, b);
1329                         }
1330                                 break;
1331                 case MA_RAMP_COLOR:             
1332                         if(g){
1333                                 float rH,rS,rV;
1334                                 float colH,colS,colV;
1335                                 float tmpr,tmpg,tmpb;
1336                                 rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1337                                 if(colS!=0){
1338                                         rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1339                                         hsv_to_rgb( colH, colS, rV, &tmpr, &tmpg, &tmpb);
1340                                         *r = facm*(*r) + fac*tmpr;
1341                                         *g = facm*(*g) + fac*tmpg;
1342                                         *b = facm*(*b) + fac*tmpb;
1343                                 }
1344                         }
1345                                 break;
1346                 case MA_RAMP_SOFT: 
1347                         if (g){ 
1348                                 float scr, scg, scb; 
1349
1350                                 /* first calculate non-fac based Screen mix */ 
1351                                 scr = 1.0f - (1.0f - col[0]) * (1.0f - *r); 
1352                                 scg = 1.0f - (1.0f - col[1]) * (1.0f - *g); 
1353                                 scb = 1.0f - (1.0f - col[2]) * (1.0f - *b); 
1354
1355                                 *r = facm*(*r) + fac*(((1.0f - *r) * col[0] * (*r)) + (*r * scr)); 
1356                                 *g = facm*(*g) + fac*(((1.0f - *g) * col[1] * (*g)) + (*g * scg)); 
1357                                 *b = facm*(*b) + fac*(((1.0f - *b) * col[2] * (*b)) + (*b * scb)); 
1358                         } 
1359                                 break; 
1360                 case MA_RAMP_LINEAR: 
1361                         if (col[0] > 0.5f)  
1362                                 *r = *r + fac*(2.0f*(col[0]-0.5f)); 
1363                         else  
1364                                 *r = *r + fac*(2.0f*(col[0]) - 1.0f); 
1365                         if (g){ 
1366                                 if (col[1] > 0.5f)  
1367                                         *g = *g + fac*(2.0f*(col[1]-0.5f)); 
1368                                 else  
1369                                         *g = *g + fac*(2.0f*(col[1]) -1.0f); 
1370                                 if (col[2] > 0.5f)  
1371                                         *b = *b + fac*(2.0f*(col[2]-0.5f)); 
1372                                 else  
1373                                         *b = *b + fac*(2.0f*(col[2]) - 1.0f); 
1374                         } 
1375                                 break; 
1376         }       
1377 }
1378
1379 /* copy/paste buffer, if we had a propper py api that would be better */
1380 static Material matcopybuf;
1381 static short matcopied= 0;
1382
1383 void clear_matcopybuf(void)
1384 {
1385         memset(&matcopybuf, 0, sizeof(Material));
1386         matcopied= 0;
1387 }
1388
1389 void free_matcopybuf(void)
1390 {
1391         int a;
1392
1393         for(a=0; a<MAX_MTEX; a++) {
1394                 if(matcopybuf.mtex[a]) {
1395                         MEM_freeN(matcopybuf.mtex[a]);
1396                         matcopybuf.mtex[a]= NULL;
1397                 }
1398         }
1399
1400         if(matcopybuf.ramp_col) MEM_freeN(matcopybuf.ramp_col);
1401         if(matcopybuf.ramp_spec) MEM_freeN(matcopybuf.ramp_spec);
1402
1403         matcopybuf.ramp_col= NULL;
1404         matcopybuf.ramp_spec= NULL;
1405
1406         if(matcopybuf.nodetree) {
1407                 ntreeFreeTree(matcopybuf.nodetree);
1408                 MEM_freeN(matcopybuf.nodetree);
1409                 matcopybuf.nodetree= NULL;
1410         }
1411
1412         matcopied= 0;
1413 }
1414
1415 void copy_matcopybuf(Material *ma)
1416 {
1417         int a;
1418         MTex *mtex;
1419
1420         if(matcopied)
1421                 free_matcopybuf();
1422
1423         memcpy(&matcopybuf, ma, sizeof(Material));
1424         if(matcopybuf.ramp_col) matcopybuf.ramp_col= MEM_dupallocN(matcopybuf.ramp_col);
1425         if(matcopybuf.ramp_spec) matcopybuf.ramp_spec= MEM_dupallocN(matcopybuf.ramp_spec);
1426
1427         for(a=0; a<MAX_MTEX; a++) {
1428                 mtex= matcopybuf.mtex[a];
1429                 if(mtex) {
1430                         matcopybuf.mtex[a]= MEM_dupallocN(mtex);
1431                 }
1432         }
1433         matcopybuf.nodetree= ntreeCopyTree(ma->nodetree);
1434         matcopybuf.preview= NULL;
1435         matcopybuf.gpumaterial.first= matcopybuf.gpumaterial.last= NULL;
1436         matcopied= 1;
1437 }
1438
1439 void paste_matcopybuf(Material *ma)
1440 {
1441         int a;
1442         MTex *mtex;
1443         ID id;
1444
1445         if(matcopied==0)
1446                 return;
1447         /* free current mat */
1448         if(ma->ramp_col) MEM_freeN(ma->ramp_col);
1449         if(ma->ramp_spec) MEM_freeN(ma->ramp_spec);
1450         for(a=0; a<MAX_MTEX; a++) {
1451                 mtex= ma->mtex[a];
1452                 if(mtex && mtex->tex) mtex->tex->id.us--;
1453                 if(mtex) MEM_freeN(mtex);
1454         }
1455
1456         if(ma->nodetree) {
1457                 ntreeFreeTree(ma->nodetree);
1458                 MEM_freeN(ma->nodetree);
1459         }
1460
1461         GPU_material_free(ma);
1462
1463         id= (ma->id);
1464         memcpy(ma, &matcopybuf, sizeof(Material));
1465         (ma->id)= id;
1466
1467         if(matcopybuf.ramp_col) ma->ramp_col= MEM_dupallocN(matcopybuf.ramp_col);
1468         if(matcopybuf.ramp_spec) ma->ramp_spec= MEM_dupallocN(matcopybuf.ramp_spec);
1469
1470         for(a=0; a<MAX_MTEX; a++) {
1471                 mtex= ma->mtex[a];
1472                 if(mtex) {
1473                         ma->mtex[a]= MEM_dupallocN(mtex);
1474                         if(mtex->tex) id_us_plus((ID *)mtex->tex);
1475                 }
1476         }
1477
1478         ma->nodetree= ntreeCopyTree(matcopybuf.nodetree);
1479 }
1480
1481
1482 /*********************** texface to material convert functions **********************/
1483 /* encode all the TF information into a single int */
1484 static int encode_tfaceflag(MTFace *tf, int convertall)
1485 {
1486         /* calculate the flag */
1487         int flag = tf->mode;
1488
1489         /* options that change the material offline render */   
1490         if (!convertall) {
1491                 flag &= ~TF_OBCOL;
1492         }
1493
1494         /* clean flags that are not being converted */
1495         flag &= ~TF_TEX;
1496         flag &= ~TF_SHAREDVERT;
1497         flag &= ~TF_SHAREDCOL;
1498         flag &= ~TF_CONVERTED;
1499
1500         /* light tface flag is ignored in GLSL mode */
1501         flag &= ~TF_LIGHT;
1502         
1503         /* 15 is how big the flag can be - hardcoded here and in decode_tfaceflag() */
1504         flag |= tf->transp << 15;
1505         
1506         /* increase 1 so flag 0 is different than no flag yet */
1507         return flag + 1;
1508 }
1509
1510 /* set the material options based in the tface flag */
1511 static void decode_tfaceflag(Material *ma, int flag, int convertall)
1512 {
1513         int alphablend; 
1514         GameSettings *game= &ma->game;
1515
1516         /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
1517         flag -= 1;
1518
1519         alphablend = flag >> 15; //encoded in the encode_tfaceflag function
1520         (*game).flag = 0;
1521         
1522         /* General Material Options */
1523         if ((flag & TF_DYNAMIC)==0) (*game).flag        |= GEMAT_NOPHYSICS;
1524         
1525         /* Material Offline Rendering Properties */
1526         if (convertall) {
1527                 if (flag & TF_OBCOL) ma->shade_flag |= MA_OBCOLOR;
1528         }
1529         
1530         /* Special Face Properties */
1531         if ((flag & TF_TWOSIDE)==0) (*game).flag |= GEMAT_BACKCULL;
1532         if (flag & TF_INVISIBLE)(*game).flag |= GEMAT_INVISIBLE;
1533         if (flag & TF_BMFONT) (*game).flag |= GEMAT_TEXT;
1534         
1535         /* Face Orientation */
1536         if (flag & TF_BILLBOARD) (*game).face_orientation |= GEMAT_HALO;
1537         else if (flag & TF_BILLBOARD2) (*game).face_orientation |= GEMAT_BILLBOARD;
1538         else if (flag & TF_SHADOW) (*game).face_orientation |= GEMAT_SHADOW;
1539         
1540         /* Alpha Blend */
1541         if (flag & TF_ALPHASORT && ELEM(alphablend, TF_ALPHA, TF_ADD)) (*game).alpha_blend = GEMAT_ALPHA_SORT;
1542         else if (alphablend & TF_ALPHA) (*game).alpha_blend = GEMAT_ALPHA;
1543         else if (alphablend & TF_ADD) (*game).alpha_blend = GEMAT_ADD;
1544         else if (alphablend & TF_CLIP) (*game).alpha_blend = GEMAT_CLIP;
1545 }
1546
1547 /* boolean check to see if the mesh needs a material */
1548 static int check_tfaceneedmaterial(int flag)
1549 {
1550         // check if the flags we have are not deprecated != than default material options
1551         // also if only flags are visible and collision see if all objects using this mesh have this option in physics
1552
1553         /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
1554         flag -=1;
1555
1556         // deprecated flags
1557         flag &= ~TF_OBCOL;
1558         flag &= ~TF_SHAREDVERT;
1559         flag &= ~TF_SHAREDCOL;
1560
1561         /* light tface flag is ignored in GLSL mode */
1562         flag &= ~TF_LIGHT;
1563         
1564         // automatic detected if tex image has alpha
1565         flag &= ~(TF_ALPHA << 15);
1566         // automatic detected if using texture
1567         flag &= ~TF_TEX;
1568
1569         // settings for the default NoMaterial
1570         if (flag == TF_DYNAMIC)
1571                 return 0;
1572
1573         else
1574                 return 1;
1575 }
1576
1577 /* return number of digits of an integer */
1578 // XXX to be optmized or replaced by an equivalent blender internal function
1579 static int integer_getdigits(int number)
1580 {
1581         int i=0;
1582         if (number == 0) return 1;
1583
1584         while (number != 0){
1585                 number = (int)(number/10);
1586                 i++;
1587         }
1588         return i;
1589 }
1590
1591 static void calculate_tface_materialname(char *matname, char *newname, int flag)
1592 {
1593         // if flag has only light and collision and material matches those values
1594         // you can do strcpy(name, mat_name);
1595         // otherwise do:
1596         int digits = integer_getdigits(flag);
1597         /* clamp the old name, remove the MA prefix and add the .TF.flag suffix
1598         e.g. matname = "MALoooooooooooooongName"; newname = "Loooooooooooooon.TF.2" */
1599         sprintf(newname, "%.*s.TF.%0*d", MAX_ID_NAME-(digits+5), matname, digits, flag);
1600 }
1601
1602 /* returns -1 if no match */
1603 static int mesh_getmaterialnumber(Mesh *me, Material *ma) {
1604         int a;
1605
1606         for (a=0; a<me->totcol; a++)
1607                 if (me->mat[a] == ma)
1608                         return a;
1609
1610         return -1;
1611 }
1612
1613 /* append material */
1614 static int mesh_addmaterial(Mesh *me, Material *ma)
1615 {
1616         material_append_id(&me->id, NULL);
1617         me->mat[me->totcol-1]= ma;
1618
1619         id_us_plus(&ma->id);
1620
1621         return me->totcol-1;
1622 }
1623
1624 static void set_facetexture_flags(Material *ma, Image *image)
1625 {
1626         if(image) {
1627                 ma->mode |= MA_FACETEXTURE;
1628                 /* we could check if the texture has alpha, but then more meshes sharing the same
1629                  * material may need it. Let's make it simple. */
1630                 if(BKE_image_has_alpha(image))
1631                         ma->mode |= MA_FACETEXTURE_ALPHA;
1632         }
1633 }
1634
1635 /* returns material number */
1636 static int convert_tfacenomaterial(Main *main, Mesh *me, MTFace *tf, int flag)
1637 {
1638         Material *ma;
1639         char idname[MAX_ID_NAME];
1640         int mat_nr= -1;
1641         
1642         /* new material, the name uses the flag*/
1643         sprintf(idname, "MAMaterial.TF.%0*d", integer_getdigits(flag), flag);
1644         
1645         if ((ma= BLI_findstring(&main->mat, idname+2, offsetof(ID, name)+2))) {
1646                 mat_nr= mesh_getmaterialnumber(me, ma);
1647                 /* assign the material to the mesh */
1648                 if(mat_nr == -1) mat_nr= mesh_addmaterial(me, ma);
1649
1650                 /* if needed set "Face Textures [Alpha]" Material options */
1651                 set_facetexture_flags(ma, tf->tpage);
1652         }
1653         /* create a new material */
1654         else {
1655                 ma= add_material(idname+2);
1656
1657                 if(ma){
1658                         printf("TexFace Convert: Material \"%s\" created.\n", idname+2);
1659                         mat_nr= mesh_addmaterial(me, ma);
1660                         
1661                         /* if needed set "Face Textures [Alpha]" Material options */
1662                         set_facetexture_flags(ma, tf->tpage);
1663
1664                         decode_tfaceflag(ma, flag, 1);
1665                         // the final decoding will happen after, outside the main loop
1666                         // for now store the flag into the material and change light/tex/collision 
1667                         // store the flag as a negative number
1668                         ma->game.flag = -flag;
1669                         id_us_min((ID *)ma);    
1670                 }
1671                 else printf("Error: Unable to create Material \"%s\" for Mesh \"%s\".", idname+2, me->id.name+2);
1672         }
1673
1674         /* set as converted, no need to go bad to this face */
1675         tf->mode |= TF_CONVERTED;       
1676         return mat_nr;
1677 }
1678
1679 /* Function to fully convert materials */
1680 static void convert_tfacematerial(Main *main, Material *ma)
1681 {
1682         Mesh *me;
1683         Material *mat_new;
1684         MFace *mf;
1685         MTFace *tf;
1686         int flag, index;
1687         int a, mat_nr;
1688         CustomDataLayer *cdl;
1689         char idname[MAX_ID_NAME];
1690
1691         for(me=main->mesh.first; me; me=me->id.next){
1692                 /* check if this mesh uses this material */
1693                 for(a=0;a<me->totcol;a++)
1694                         if(me->mat[a] == ma) break;
1695                         
1696                 /* no material found */
1697                 if (a == me->totcol) continue;
1698
1699                 /* get the active tface layer */
1700                 index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
1701                 cdl= (index == -1)? NULL: &me->fdata.layers[index];
1702                 if (!cdl) continue;
1703
1704                 /* loop over all the faces and stop at the ones that use the material*/
1705                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1706                         if(me->mat[(int)mf->mat_nr] != ma) continue;
1707
1708                         /* texface data for this face */
1709                         tf = ((MTFace*)cdl->data) + a;
1710                         flag = encode_tfaceflag(tf, 1);
1711
1712                         /* the name of the new material */
1713                         calculate_tface_materialname(ma->id.name, (char *)&idname, flag);
1714
1715                         if ((mat_new= BLI_findstring(&main->mat, idname+2, offsetof(ID, name)+2))) {
1716                                 /* material already existent, see if the mesh has it */
1717                                 mat_nr = mesh_getmaterialnumber(me, mat_new);
1718                                 /* material is not in the mesh, add it */
1719                                 if(mat_nr == -1) mat_nr= mesh_addmaterial(me, mat_new);
1720                         }
1721                         /* create a new material */
1722                         else {
1723                                 mat_new=copy_material(ma);
1724                                 if(mat_new){
1725                                         /* rename the material*/
1726                                         strcpy(mat_new->id.name, idname);
1727                                         id_us_min((ID *)mat_new);       
1728
1729                                         mat_nr= mesh_addmaterial(me, mat_new);
1730                                         decode_tfaceflag(mat_new, flag, 1);
1731                                 }
1732                                 else {
1733                                         printf("Error: Unable to create Material \"%s\" for Mesh \"%s.", idname+2, me->id.name+2);
1734                                         mat_nr = mf->mat_nr;
1735                                         continue;
1736                                 }
1737                         }
1738                         
1739                         /* if the material has a texture but no texture channel
1740                          * set "Face Textures [Alpha]" Material options 
1741                          * actually we need to run it always, because of old behavior
1742                          * of using face texture if any texture channel was present (multitex) */
1743                         //if((!mat_new->mtex[0]) && (!mat_new->mtex[0]->tex))
1744                         set_facetexture_flags(mat_new, tf->tpage);
1745
1746                         /* set the material number to the face*/
1747                         mf->mat_nr = mat_nr;
1748                 }
1749                 /* remove material from mesh */
1750                 for(a=0;a<me->totcol;)
1751                         if(me->mat[a] == ma) material_pop_id(&me->id, a, 1);else a++;
1752         }
1753 }
1754
1755 int do_version_tface(Main *main, int fileload)
1756 {
1757         Mesh *me;
1758         Material *ma;
1759         MFace *mf;
1760         MTFace *tf;
1761         CustomDataLayer *cdl;
1762         int a;
1763         int flag;
1764         int index;
1765
1766         /* sometimes mesh has no materials but will need a new one. In those
1767          * cases we need to ignore the mf->mat_nr and only look at the face
1768          * mode because it can be zero as uninitialized or the 1st created material
1769          */
1770         int nomaterialslots;
1771
1772         /* alert to user to check the console */
1773         int nowarning = 1;
1774
1775         /* mark all the materials to conversion with a flag
1776          * if there is tface create a complete flag for that storing in flag
1777          * if there is tface and flag > 0: creates a new flag based on this face
1778          * if flags are different set flag to -1  
1779          */
1780         
1781         /* 1st part: marking mesh materials to update */
1782         for(me=main->mesh.first; me; me=me->id.next){
1783                 if (me->id.lib) continue;
1784
1785                 /* get the active tface layer */
1786                 index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
1787                 cdl= (index == -1)? NULL: &me->fdata.layers[index];
1788                 if (!cdl) continue;
1789
1790                 nomaterialslots = (me->totcol==0?1:0);
1791                 
1792                 /* loop over all the faces*/
1793                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1794                         /* texface data for this face */
1795                         tf = ((MTFace*)cdl->data) + a;
1796
1797                         /* conversion should happen only once */
1798                         if (fileload)
1799                                 tf->mode &= ~TF_CONVERTED;
1800                         else {
1801                                 if((tf->mode & TF_CONVERTED)) continue;
1802                                 else tf->mode |= TF_CONVERTED;
1803                         }
1804                         
1805                         /* no material slots */
1806                         if(nomaterialslots) {
1807                                 flag = encode_tfaceflag(tf, 1);
1808                                 
1809                                 /* create/find a new material and assign to the face */
1810                                 if (check_tfaceneedmaterial(flag))
1811                                         mf->mat_nr= convert_tfacenomaterial(main, me, tf, flag);
1812                                         
1813                         /* else mark them as no-material to be reverted to 0 later */
1814                                 else
1815                                         mf->mat_nr = -1;
1816                         }
1817                         else if(mf->mat_nr < me->totcol) {
1818                                 ma= me->mat[(int)mf->mat_nr];
1819                                 
1820                                 /* no material create one if necessary */
1821                                 if(!ma) {
1822                                         /* find a new material and assign to the face */
1823                                         flag = encode_tfaceflag(tf, 1);
1824
1825                                         /* create/find a new material and assign to the face */
1826                                         if (check_tfaceneedmaterial(flag))
1827                                                 mf->mat_nr= convert_tfacenomaterial(main, me, tf, flag);
1828
1829                                         continue;
1830                                 }
1831
1832                                 /* we can't read from this if it comes from a library,
1833                                  * at doversion time: direct_link might not have happened on it,
1834                                  * so ma->mtex is not pointing to valid memory yet.
1835                                  * later we could, but it's better not */
1836                                 else if(ma->id.lib)
1837                                         continue;
1838                                 
1839                                 /* material already marked as disputed */
1840                                 else if(ma->game.flag == -99999)
1841                                         continue;
1842
1843                                 /* found a material */
1844                                 else {
1845                                         flag = encode_tfaceflag(tf, ((fileload)?0:1));
1846
1847                                         /* first time changing this material */
1848                                         if (ma->game.flag == 0)
1849                                                 ma->game.flag= -flag;
1850                         
1851                                         /* mark material as disputed */
1852                                         else if (ma->game.flag != -flag) {
1853                                                 ma->game.flag = -99999;
1854                                                 continue;
1855                                         }
1856                         
1857                                         /* material ok so far */
1858                                         else {
1859                                                 ma->game.flag = -flag;
1860                                                 
1861                                                 /* some people uses multitexture with TexFace by creating a texture
1862                                                  * channel which not neccessarly the tf->tpage image. But the game engine
1863                                                  * was enabling it. Now it's required to set "Face Texture [Alpha] in the
1864                                                  * material settings. */
1865                                                 if(!fileload)
1866                                                         set_facetexture_flags(ma, tf->tpage);
1867                                         }
1868                                 }
1869                         }
1870                         else
1871                                 continue;
1872                 }
1873
1874                 /* if we didn't have material slot and now we do, we need to
1875                  * make sure the materials are correct */
1876                 if(nomaterialslots) {
1877                         if (me->totcol>0) {
1878                                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1879                                         if (mf->mat_nr == -1) {
1880                                                 /* texface data for this face */
1881                                                 tf = ((MTFace*)cdl->data) + a;
1882                                                 mf->mat_nr= convert_tfacenomaterial(main, me, tf, encode_tfaceflag(tf, 1));
1883                                         }
1884                                 }
1885                         } else {
1886                                 for(a=0, mf=me->mface; a<me->totface; a++, mf++)
1887                                         mf->mat_nr=0;
1888                         }
1889                 }
1890
1891         }
1892         
1893         /* 2nd part - conversion */
1894         /* skip library files */
1895
1896         /* we shouldn't loop through the materials created in the loop. make the loop stop at its original length) */
1897         for (ma= main->mat.first, a=0; ma; ma= ma->id.next, a++) {
1898                 if (ma->id.lib) continue;
1899
1900                 /* disputed material */
1901                 if (ma->game.flag == -99999) {
1902                         ma->game.flag = 0;
1903                         if (fileload) {
1904                                 printf("Warning: material \"%s\" skipped - to convert old game texface to material go to the Help menu.\n", ma->id.name+2);
1905                                 nowarning = 0;
1906                         }
1907                         else
1908                                 convert_tfacematerial(main, ma);
1909                         continue;       
1910                 }
1911         
1912                 /* no conflicts in this material - 90% of cases
1913                  * convert from tface system to material */
1914                 else if (ma->game.flag < 0){
1915                         decode_tfaceflag(ma, -(ma->game.flag), 1);
1916
1917                         /* material is good make sure all faces using
1918                          * this material are set to converted */
1919                         if (fileload) {
1920                                 for(me=main->mesh.first; me; me=me->id.next){
1921                                         /* check if this mesh uses this material */
1922                                         for(a=0;a<me->totcol;a++)
1923                                                 if(me->mat[a] == ma) break;
1924                                                 
1925                                         /* no material found */
1926                                         if (a == me->totcol) continue;
1927                         
1928                                         /* get the active tface layer */
1929                                         index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
1930                                         cdl= (index == -1)? NULL: &me->fdata.layers[index];
1931                                         if (!cdl) continue;
1932                         
1933                                         /* loop over all the faces and stop at the ones that use the material*/
1934                                         for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1935                                                 if(me->mat[(int)mf->mat_nr] != ma) continue;
1936                                                 else tf->mode |= TF_CONVERTED;
1937                                         }
1938                                 }
1939                         }
1940                 }
1941         }
1942
1943         return nowarning;
1944 }
1945