BGE Material settings renaming Back Culling to Backface Culling and make it on by...
[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 = GEMAT_BACKCULL;
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, short 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_i, int remove_material_slot)
560 {
561         short index= (short)index_i;
562         Material *ret= NULL;
563         Material ***matar;
564         if((matar= give_matarar_id(id))) {
565                 short *totcol= give_totcolp_id(id);
566                 if(index >= 0 && index < (*totcol)) {
567                         ret= (*matar)[index];
568                         id_us_min((ID *)ret);
569
570                         if (remove_material_slot) {
571                                 if(*totcol <= 1) {
572                                         *totcol= 0;
573                                         MEM_freeN(*matar);
574                                         *matar= NULL;
575                                 }
576                                 else {
577                                         Material **mat;
578                                         if(index + 1 != (*totcol))
579                                                 memmove((*matar)+index, (*matar)+(index+1), sizeof(void *) * ((*totcol) - (index + 1)));
580
581                                         (*totcol)--;
582                                         
583                                         mat= MEM_callocN(sizeof(void *) * (*totcol), "newmatar");
584                                         memcpy(mat, *matar, sizeof(void *) * (*totcol));
585                                         MEM_freeN(*matar);
586
587                                         *matar= mat;
588                                         test_object_materials(id);
589                                 }
590
591                                 /* decrease mat_nr index */
592                                 data_delete_material_index_id(id, index);
593                         }
594
595                         /* don't remove material slot, only clear it*/
596                         else
597                                 (*matar)[index]= NULL;
598                 }
599         }
600         
601         return ret;
602 }
603
604 Material *give_current_material(Object *ob, short act)
605 {
606         Material ***matarar, *ma;
607         short *totcolp;
608         
609         if(ob==NULL) return NULL;
610         
611         /* if object cannot have material, totcolp==NULL */
612         totcolp= give_totcolp(ob);
613         if(totcolp==NULL || ob->totcol==0) return NULL;
614         
615         if(act<0) {
616                 printf("no!\n");
617         }
618         
619         if(act>ob->totcol) act= ob->totcol;
620         else if(act<=0) act= 1;
621
622         if(ob->matbits && ob->matbits[act-1]) { /* in object */
623                 ma= ob->mat[act-1];
624         }
625         else {                                                          /* in data */
626
627                 /* check for inconsistency */
628                 if(*totcolp < ob->totcol)
629                         ob->totcol= *totcolp;
630                 if(act>ob->totcol) act= ob->totcol;
631
632                 matarar= give_matarar(ob);
633                 
634                 if(matarar && *matarar) ma= (*matarar)[act-1];
635                 else ma= NULL;
636                 
637         }
638         
639         return ma;
640 }
641
642 ID *material_from(Object *ob, short act)
643 {
644
645         if(ob==NULL) return NULL;
646
647         if(ob->totcol==0) return ob->data;
648         if(act==0) act= 1;
649
650         if(ob->matbits[act-1]) return (ID *)ob;
651         else return ob->data;
652 }
653
654 Material *give_node_material(Material *ma)
655 {
656         if(ma && ma->use_nodes && ma->nodetree) {
657                 bNode *node= nodeGetActiveID(ma->nodetree, ID_MA);
658
659                 if(node)
660                         return (Material *)node->id;
661         }
662
663         return NULL;
664 }
665
666 /* GS reads the memory pointed at in a specific ordering. There are,
667  * however two definitions for it. I have jotted them down here, both,
668  * but I think the first one is actually used. The thing is that
669  * big-endian systems might read this the wrong way round. OTOH, we
670  * constructed the IDs that are read out with this macro explicitly as
671  * well. I expect we'll sort it out soon... */
672
673 /* from blendef: */
674 #define GS(a)   (*((short *)(a)))
675
676 /* from misc_util: flip the bytes from x  */
677 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
678
679 void resize_object_material(Object *ob, const short totcol)
680 {
681         Material **newmatar;
682         char *newmatbits;
683
684         if(totcol==0) {
685                 if(ob->totcol) {
686                         MEM_freeN(ob->mat);
687                         MEM_freeN(ob->matbits);
688                         ob->mat= NULL;
689                         ob->matbits= NULL;
690                 }
691         }
692         else if(ob->totcol<totcol) {
693                 newmatar= MEM_callocN(sizeof(void *)*totcol, "newmatar");
694                 newmatbits= MEM_callocN(sizeof(char)*totcol, "newmatbits");
695                 if(ob->totcol) {
696                         memcpy(newmatar, ob->mat, sizeof(void *)*ob->totcol);
697                         memcpy(newmatbits, ob->matbits, sizeof(char)*ob->totcol);
698                         MEM_freeN(ob->mat);
699                         MEM_freeN(ob->matbits);
700                 }
701                 ob->mat= newmatar;
702                 ob->matbits= newmatbits;
703         }
704         ob->totcol= totcol;
705         if(ob->totcol && ob->actcol==0) ob->actcol= 1;
706         if(ob->actcol>ob->totcol) ob->actcol= ob->totcol;
707 }
708
709 void test_object_materials(ID *id)
710 {
711         /* make the ob mat-array same size as 'ob->data' mat-array */
712         Object *ob;
713         short *totcol;
714
715         if(id==NULL || (totcol=give_totcolp_id(id))==NULL) {
716                 return;
717         }
718
719         for(ob= G.main->object.first; ob; ob= ob->id.next) {
720                 if(ob->data==id) {
721                         resize_object_material(ob, *totcol);
722                 }
723         }
724 }
725
726 void assign_material(Object *ob, Material *ma, short act)
727 {
728         Material *mao, **matar, ***matarar;
729         char *matbits;
730         short *totcolp;
731
732         if(act>MAXMAT) return;
733         if(act<1) act= 1;
734         
735         /* prevent crashing when using accidentally */
736         BLI_assert(ob->id.lib == NULL);
737         if(ob->id.lib) return;
738         
739         /* test arraylens */
740         
741         totcolp= give_totcolp(ob);
742         matarar= give_matarar(ob);
743         
744         if(totcolp==NULL || matarar==NULL) return;
745         
746         if(act > *totcolp) {
747                 matar= MEM_callocN(sizeof(void *)*act, "matarray1");
748
749                 if(*totcolp) {
750                         memcpy(matar, *matarar, sizeof(void *)*(*totcolp));
751                         MEM_freeN(*matarar);
752                 }
753
754                 *matarar= matar;
755                 *totcolp= act;
756         }
757         
758         if(act > ob->totcol) {
759                 matar= MEM_callocN(sizeof(void *)*act, "matarray2");
760                 matbits= MEM_callocN(sizeof(char)*act, "matbits1");
761                 if( ob->totcol) {
762                         memcpy(matar, ob->mat, sizeof(void *)*( ob->totcol ));
763                         memcpy(matbits, ob->matbits, sizeof(char)*(*totcolp));
764                         MEM_freeN(ob->mat);
765                         MEM_freeN(ob->matbits);
766                 }
767                 ob->mat= matar;
768                 ob->matbits= matbits;
769                 ob->totcol= act;
770
771                 /* copy object/mesh linking, or assign based on userpref */
772                 if(ob->actcol)
773                         ob->matbits[act-1]= ob->matbits[ob->actcol-1];
774                 else
775                         ob->matbits[act-1]= (U.flag & USER_MAT_ON_OB)? 1: 0;
776         }
777         
778         /* do it */
779
780         if(ob->matbits[act-1]) {        /* in object */
781                 mao= ob->mat[act-1];
782                 if(mao) mao->id.us--;
783                 ob->mat[act-1]= ma;
784         }
785         else {  /* in data */
786                 mao= (*matarar)[act-1];
787                 if(mao) mao->id.us--;
788                 (*matarar)[act-1]= ma;
789         }
790
791         if(ma)
792                 id_us_plus((ID *)ma);
793         test_object_materials(ob->data);
794 }
795
796 /* XXX - this calls many more update calls per object then are needed, could be optimized */
797 void assign_matarar(struct Object *ob, struct Material ***matar, short totcol)
798 {
799         int actcol_orig= ob->actcol;
800         short i;
801
802         while(object_remove_material_slot(ob)) {};
803
804         /* now we have the right number of slots */
805         for(i=0; i<totcol; i++)
806                 assign_material(ob, (*matar)[i], i+1);
807
808         if(actcol_orig > ob->totcol)
809                 actcol_orig= ob->totcol;
810
811         ob->actcol= actcol_orig;
812 }
813
814
815 short find_material_index(Object *ob, Material *ma)
816 {
817         Material ***matarar;
818         short a, *totcolp;
819         
820         if(ma==NULL) return 0;
821         
822         totcolp= give_totcolp(ob);
823         matarar= give_matarar(ob);
824         
825         if(totcolp==NULL || matarar==NULL) return 0;
826         
827         for(a=0; a<*totcolp; a++)
828                 if((*matarar)[a]==ma)
829                    break;
830         if(a<*totcolp)
831                 return a+1;
832         return 0;          
833 }
834
835 int object_add_material_slot(Object *ob)
836 {
837         if(ob==NULL) return FALSE;
838         if(ob->totcol>=MAXMAT) return FALSE;
839         
840         assign_material(ob, NULL, ob->totcol+1);
841         ob->actcol= ob->totcol;
842         return TRUE;
843 }
844
845 static void do_init_render_material(Material *ma, int r_mode, float *amb)
846 {
847         MTex *mtex;
848         int a, needuv=0, needtang=0;
849         
850         if(ma->flarec==0) ma->flarec= 1;
851
852         /* add all texcoflags from mtex, texco and mapto were cleared in advance */
853         for(a=0; a<MAX_MTEX; a++) {
854                 
855                 /* separate tex switching */
856                 if(ma->septex & (1<<a)) continue;
857
858                 mtex= ma->mtex[a];
859                 if(mtex && mtex->tex && (mtex->tex->type | (mtex->tex->use_nodes && mtex->tex->nodetree) )) {
860                         
861                         ma->texco |= mtex->texco;
862                         ma->mapto |= mtex->mapto;
863
864                         /* always get derivatives for these textures */
865                         if ELEM3(mtex->tex->type, TEX_IMAGE, TEX_PLUGIN, TEX_ENVMAP) ma->texco |= TEXCO_OSA;
866                         else if(mtex->texflag & (MTEX_COMPAT_BUMP|MTEX_3TAP_BUMP|MTEX_5TAP_BUMP)) ma->texco |= TEXCO_OSA;
867                         
868                         if(ma->texco & (TEXCO_ORCO|TEXCO_REFL|TEXCO_NORM|TEXCO_STRAND|TEXCO_STRESS)) needuv= 1;
869                         else if(ma->texco & (TEXCO_GLOB|TEXCO_UV|TEXCO_OBJECT|TEXCO_SPEED)) needuv= 1;
870                         else if(ma->texco & (TEXCO_LAVECTOR|TEXCO_VIEW|TEXCO_STICKY)) needuv= 1;
871
872                         if((ma->mapto & MAP_NORM) && (mtex->normapspace == MTEX_NSPACE_TANGENT))
873                                 needtang= 1;
874                 }
875         }
876
877         if(needtang) ma->mode |= MA_NORMAP_TANG;
878         else ma->mode &= ~MA_NORMAP_TANG;
879         
880         if(ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP|MA_FACETEXTURE)) {
881                 needuv= 1;
882                 if(r_mode & R_OSA) ma->texco |= TEXCO_OSA;              /* for texfaces */
883         }
884         if(needuv) ma->texco |= NEED_UV;
885         
886         /* since the raytracer doesnt recalc O structs for each ray, we have to preset them all */
887         if(r_mode & R_RAYTRACE) {
888                 if((ma->mode & (MA_RAYMIRROR|MA_SHADOW_TRA)) || ((ma->mode & MA_TRANSP) && (ma->mode & MA_RAYTRANSP))) {
889                         ma->texco |= NEED_UV|TEXCO_ORCO|TEXCO_REFL|TEXCO_NORM;
890                         if(r_mode & R_OSA) ma->texco |= TEXCO_OSA;
891                 }
892         }
893         
894         if(amb) {
895                 ma->ambr= ma->amb*amb[0];
896                 ma->ambg= ma->amb*amb[1];
897                 ma->ambb= ma->amb*amb[2];
898         }       
899         /* will become or-ed result of all node modes */
900         ma->mode_l= ma->mode;
901         ma->mode_l &= ~MA_SHLESS;
902
903         if(ma->strand_surfnor > 0.0f)
904                 ma->mode_l |= MA_STR_SURFDIFF;
905
906         /* parses the geom+tex nodes */
907         if(ma->nodetree && ma->use_nodes)
908                 ntreeShaderGetTexcoMode(ma->nodetree, r_mode, &ma->texco, &ma->mode_l);
909 }
910
911 static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode, float *amb)
912 {
913         bNode *node;
914         
915         for(node=ntree->nodes.first; node; node= node->next) {
916                 if(node->id) {
917                         if(GS(node->id->name)==ID_MA) {
918                                 Material *ma= (Material *)node->id;
919                                 if(ma!=basemat) {
920                                         do_init_render_material(ma, r_mode, amb);
921                                         basemat->texco |= ma->texco;
922                                         basemat->mode_l |= ma->mode_l & ~(MA_TRANSP|MA_ZTRANSP|MA_RAYTRANSP); 
923                                 }
924                         }
925                         else if(node->type==NODE_GROUP)
926                                 init_render_nodetree((bNodeTree *)node->id, basemat, r_mode, amb);
927                 }
928         }
929 }
930
931 void init_render_material(Material *mat, int r_mode, float *amb)
932 {
933         
934         do_init_render_material(mat, r_mode, amb);
935         
936         if(mat->nodetree && mat->use_nodes) {
937                 init_render_nodetree(mat->nodetree, mat, r_mode, amb);
938                 
939                 if (!mat->nodetree->execdata)
940                         mat->nodetree->execdata = ntreeShaderBeginExecTree(mat->nodetree, 1);
941         }
942 }
943
944 void init_render_materials(Main *bmain, int r_mode, float *amb)
945 {
946         Material *ma;
947         
948         /* clear these flags before going over materials, to make sure they
949          * are cleared only once, otherwise node materials contained in other
950          * node materials can go wrong */
951         for(ma= bmain->mat.first; ma; ma= ma->id.next) {
952                 if(ma->id.us) {
953                         ma->texco= 0;
954                         ma->mapto= 0;
955                 }
956         }
957
958         /* two steps, first initialize, then or the flags for layers */
959         for(ma= bmain->mat.first; ma; ma= ma->id.next) {
960                 /* is_used flag comes back in convertblender.c */
961                 ma->flag &= ~MA_IS_USED;
962                 if(ma->id.us) 
963                         init_render_material(ma, r_mode, amb);
964         }
965         
966         do_init_render_material(&defmaterial, r_mode, amb);
967 }
968
969 /* only needed for nodes now */
970 void end_render_material(Material *mat)
971 {
972         if(mat && mat->nodetree && mat->use_nodes) {
973                 if (mat->nodetree->execdata)
974                         ntreeShaderEndExecTree(mat->nodetree->execdata, 1);
975         }
976 }
977
978 void end_render_materials(Main *bmain)
979 {
980         Material *ma;
981         for(ma= bmain->mat.first; ma; ma= ma->id.next)
982                 if(ma->id.us) 
983                         end_render_material(ma);
984 }
985
986 static int material_in_nodetree(bNodeTree *ntree, Material *mat)
987 {
988         bNode *node;
989
990         for(node=ntree->nodes.first; node; node= node->next) {
991                 if(node->id && GS(node->id->name)==ID_MA) {
992                         if(node->id==(ID*)mat)
993                                 return 1;
994                 }
995                 else if(node->type==NODE_GROUP)
996                         if(material_in_nodetree((bNodeTree*)node->id, mat))
997                                 return 1;
998         }
999
1000         return 0;
1001 }
1002
1003 int material_in_material(Material *parmat, Material *mat)
1004 {
1005         if(parmat==mat)
1006                 return 1;
1007         else if(parmat->nodetree && parmat->use_nodes)
1008                 return material_in_nodetree(parmat->nodetree, mat);
1009         else
1010                 return 0;
1011 }
1012         
1013 /* ****************** */
1014
1015 static char colname_array[125][20]= {
1016 "Black","DarkRed","HalfRed","Red","Red",
1017 "DarkGreen","DarkOlive","Brown","Chocolate","OrangeRed",
1018 "HalfGreen","GreenOlive","DryOlive","Goldenrod","DarkOrange",
1019 "LightGreen","Chartreuse","YellowGreen","Yellow","Gold",
1020 "Green","LawnGreen","GreenYellow","LightOlive","Yellow",
1021 "DarkBlue","DarkPurple","HotPink","VioletPink","RedPink",
1022 "SlateGray","DarkGrey","PalePurple","IndianRed","Tomato",
1023 "SeaGreen","PaleGreen","GreenKhaki","LightBrown","LightSalmon",
1024 "SpringGreen","PaleGreen","MediumOlive","YellowBrown","LightGold",
1025 "LightGreen","LightGreen","LightGreen","GreenYellow","PaleYellow",
1026 "HalfBlue","DarkSky","HalfMagenta","VioletRed","DeepPink",
1027 "SteelBlue","SkyBlue","Orchid","LightHotPink","HotPink",
1028 "SeaGreen","SlateGray","MediumGrey","Burlywood","LightPink",
1029 "SpringGreen","Aquamarine","PaleGreen","Khaki","PaleOrange",
1030 "SpringGreen","SeaGreen","PaleGreen","PaleWhite","YellowWhite",
1031 "LightBlue","Purple","MediumOrchid","Magenta","Magenta",
1032 "RoyalBlue","SlateBlue","MediumOrchid","Orchid","Magenta",
1033 "DeepSkyBlue","LightSteelBlue","LightSkyBlue","Violet","LightPink",
1034 "Cyan","DarkTurquoise","SkyBlue","Grey","Snow",
1035 "Mint","Mint","Aquamarine","MintCream","Ivory",
1036 "Blue","Blue","DarkMagenta","DarkOrchid","Magenta",
1037 "SkyBlue","RoyalBlue","LightSlateBlue","MediumOrchid","Magenta",
1038 "DodgerBlue","SteelBlue","MediumPurple","PalePurple","Plum",
1039 "DeepSkyBlue","PaleBlue","LightSkyBlue","PalePurple","Thistle",
1040 "Cyan","ColdBlue","PaleTurquoise","GhostWhite","White"
1041 };
1042
1043 void automatname(Material *ma)
1044 {
1045         int nr, r, g, b;
1046         float ref;
1047         
1048         if(ma==NULL) return;
1049         if(ma->mode & MA_SHLESS) ref= 1.0;
1050         else ref= ma->ref;
1051         
1052         r= (int)(4.99f*(ref*ma->r));
1053         g= (int)(4.99f*(ref*ma->g));
1054         b= (int)(4.99f*(ref*ma->b));
1055         nr= r + 5*g + 25*b;
1056         if(nr>124) nr= 124;
1057         new_id(&G.main->mat, (ID *)ma, colname_array[nr]);
1058         
1059 }
1060
1061
1062 int object_remove_material_slot(Object *ob)
1063 {
1064         Material *mao, ***matarar;
1065         Object *obt;
1066         short *totcolp;
1067         short a, actcol;
1068         
1069         if(ob==NULL || ob->totcol==0) return FALSE;
1070         
1071         /* take a mesh/curve/mball as starting point, remove 1 index,
1072          * AND with all objects that share the ob->data
1073          * 
1074          * after that check indices in mesh/curve/mball!!!
1075          */
1076         
1077         totcolp= give_totcolp(ob);
1078         matarar= give_matarar(ob);
1079
1080         if(*matarar==NULL) return FALSE;
1081
1082         /* we delete the actcol */
1083         if(ob->totcol) {
1084                 mao= (*matarar)[ob->actcol-1];
1085                 if(mao) mao->id.us--;
1086         }
1087         
1088         for(a=ob->actcol; a<ob->totcol; a++)
1089                 (*matarar)[a-1]= (*matarar)[a];
1090         (*totcolp)--;
1091         
1092         if(*totcolp==0) {
1093                 MEM_freeN(*matarar);
1094                 *matarar= NULL;
1095         }
1096         
1097         actcol= ob->actcol;
1098         obt= G.main->object.first;
1099         while(obt) {
1100         
1101                 if(obt->data==ob->data) {
1102                         
1103                         /* WATCH IT: do not use actcol from ob or from obt (can become zero) */
1104                         mao= obt->mat[actcol-1];
1105                         if(mao) mao->id.us--;
1106                 
1107                         for(a=actcol; a<obt->totcol; a++) {
1108                                 obt->mat[a-1]= obt->mat[a];
1109                                 obt->matbits[a-1]= obt->matbits[a];
1110                         }
1111                         obt->totcol--;
1112                         if(obt->actcol > obt->totcol) obt->actcol= obt->totcol;
1113                         
1114                         if(obt->totcol==0) {
1115                                 MEM_freeN(obt->mat);
1116                                 MEM_freeN(obt->matbits);
1117                                 obt->mat= NULL;
1118                                 obt->matbits= NULL;
1119                         }
1120                 }
1121                 obt= obt->id.next;
1122         }
1123
1124         /* check indices from mesh */
1125         if (ELEM4(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT)) {
1126                 data_delete_material_index_id((ID *)ob->data, actcol-1);
1127                 freedisplist(&ob->disp);
1128         }
1129
1130         return TRUE;
1131 }
1132
1133
1134 /* r g b = current value, col = new value, fac==0 is no change */
1135 /* if g==NULL, it only does r channel */
1136 void ramp_blend(int type, float *r, float *g, float *b, float fac, const float col[3])
1137 {
1138         float tmp, facm= 1.0f-fac;
1139         
1140         switch (type) {
1141                 case MA_RAMP_BLEND:
1142                         *r = facm*(*r) + fac*col[0];
1143                         if(g) {
1144                                 *g = facm*(*g) + fac*col[1];
1145                                 *b = facm*(*b) + fac*col[2];
1146                         }
1147                                 break;
1148                 case MA_RAMP_ADD:
1149                         *r += fac*col[0];
1150                         if(g) {
1151                                 *g += fac*col[1];
1152                                 *b += fac*col[2];
1153                         }
1154                                 break;
1155                 case MA_RAMP_MULT:
1156                         *r *= (facm + fac*col[0]);
1157                         if(g) {
1158                                 *g *= (facm + fac*col[1]);
1159                                 *b *= (facm + fac*col[2]);
1160                         }
1161                                 break;
1162                 case MA_RAMP_SCREEN:
1163                         *r = 1.0f - (facm + fac*(1.0f - col[0])) * (1.0f - *r);
1164                         if(g) {
1165                                 *g = 1.0f - (facm + fac*(1.0f - col[1])) * (1.0f - *g);
1166                                 *b = 1.0f - (facm + fac*(1.0f - col[2])) * (1.0f - *b);
1167                         }
1168                                 break;
1169                 case MA_RAMP_OVERLAY:
1170                         if(*r < 0.5f)
1171                                 *r *= (facm + 2.0f*fac*col[0]);
1172                         else
1173                                 *r = 1.0f - (facm + 2.0f*fac*(1.0f - col[0])) * (1.0f - *r);
1174                         if(g) {
1175                                 if(*g < 0.5f)
1176                                         *g *= (facm + 2.0f*fac*col[1]);
1177                                 else
1178                                         *g = 1.0f - (facm + 2.0f*fac*(1.0f - col[1])) * (1.0f - *g);
1179                                 if(*b < 0.5f)
1180                                         *b *= (facm + 2.0f*fac*col[2]);
1181                                 else
1182                                         *b = 1.0f - (facm + 2.0f*fac*(1.0f - col[2])) * (1.0f - *b);
1183                         }
1184                                 break;
1185                 case MA_RAMP_SUB:
1186                         *r -= fac*col[0];
1187                         if(g) {
1188                                 *g -= fac*col[1];
1189                                 *b -= fac*col[2];
1190                         }
1191                                 break;
1192                 case MA_RAMP_DIV:
1193                         if(col[0]!=0.0f)
1194                                 *r = facm*(*r) + fac*(*r)/col[0];
1195                         if(g) {
1196                                 if(col[1]!=0.0f)
1197                                         *g = facm*(*g) + fac*(*g)/col[1];
1198                                 if(col[2]!=0.0f)
1199                                         *b = facm*(*b) + fac*(*b)/col[2];
1200                         }
1201                                 break;
1202                 case MA_RAMP_DIFF:
1203                         *r = facm*(*r) + fac*fabsf(*r-col[0]);
1204                         if(g) {
1205                                 *g = facm*(*g) + fac*fabsf(*g-col[1]);
1206                                 *b = facm*(*b) + fac*fabsf(*b-col[2]);
1207                         }
1208                                 break;
1209                 case MA_RAMP_DARK:
1210                         tmp=col[0]+((1-col[0])*facm); 
1211                         if(tmp < *r) *r= tmp; 
1212                         if(g) { 
1213                                 tmp=col[1]+((1-col[1])*facm); 
1214                                 if(tmp < *g) *g= tmp; 
1215                                 tmp=col[2]+((1-col[2])*facm); 
1216                                 if(tmp < *b) *b= tmp; 
1217                         } 
1218                                 break; 
1219                 case MA_RAMP_LIGHT:
1220                         tmp= fac*col[0];
1221                         if(tmp > *r) *r= tmp; 
1222                                 if(g) {
1223                                         tmp= fac*col[1];
1224                                         if(tmp > *g) *g= tmp; 
1225                                         tmp= fac*col[2];
1226                                         if(tmp > *b) *b= tmp; 
1227                                 }
1228                                         break;  
1229                 case MA_RAMP_DODGE:                     
1230                         
1231                                 
1232                         if(*r !=0.0f){
1233                                 tmp = 1.0f - fac*col[0];
1234                                 if(tmp <= 0.0f)
1235                                         *r = 1.0f;
1236                                 else if ((tmp = (*r) / tmp)> 1.0f)
1237                                         *r = 1.0f;
1238                                 else 
1239                                         *r = tmp;
1240                         }
1241                         if(g) {
1242                                 if(*g !=0.0f){
1243                                         tmp = 1.0f - fac*col[1];
1244                                         if(tmp <= 0.0f )
1245                                                 *g = 1.0f;
1246                                         else if ((tmp = (*g) / tmp) > 1.0f )
1247                                                 *g = 1.0f;
1248                                         else
1249                                                 *g = tmp;
1250                                 }
1251                                 if(*b !=0.0f){
1252                                         tmp = 1.0f - fac*col[2];
1253                                         if(tmp <= 0.0f)
1254                                                 *b = 1.0f;
1255                                         else if ((tmp = (*b) / tmp) > 1.0f )
1256                                                 *b = 1.0f;
1257                                         else
1258                                                 *b = tmp;
1259                                 }
1260
1261                         }
1262                                 break;  
1263                 case MA_RAMP_BURN:
1264                         
1265                         tmp = facm + fac*col[0];
1266                         
1267                         if(tmp <= 0.0f)
1268                                 *r = 0.0f;
1269                         else if (( tmp = (1.0f - (1.0f - (*r)) / tmp )) < 0.0f)
1270                                         *r = 0.0f;
1271                         else if (tmp > 1.0f)
1272                                 *r=1.0f;
1273                         else 
1274                                 *r = tmp; 
1275
1276                         if(g) {
1277                                 tmp = facm + fac*col[1];
1278                                 if(tmp <= 0.0f)
1279                                         *g = 0.0f;
1280                                 else if (( tmp = (1.0f - (1.0f - (*g)) / tmp )) < 0.0f )
1281                                                 *g = 0.0f;
1282                                 else if(tmp >1.0f)
1283                                         *g=1.0f;
1284                                 else
1285                                         *g = tmp;
1286
1287                                         tmp = facm + fac*col[2];
1288                                         if(tmp <= 0.0f)
1289                                         *b = 0.0f;
1290                                 else if (( tmp = (1.0f - (1.0f - (*b)) / tmp )) < 0.0f  )
1291                                                 *b = 0.0f;
1292                                 else if(tmp >1.0f)
1293                                         *b= 1.0f;
1294                                 else
1295                                         *b = tmp;
1296                         }
1297                                 break;
1298                 case MA_RAMP_HUE:               
1299                         if(g){
1300                                 float rH,rS,rV;
1301                                 float colH,colS,colV; 
1302                                 float tmpr,tmpg,tmpb;
1303                                 rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1304                                 if(colS!=0 ){
1305                                         rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1306                                         hsv_to_rgb( colH , rS, rV, &tmpr, &tmpg, &tmpb);
1307                                         *r = facm*(*r) + fac*tmpr;  
1308                                         *g = facm*(*g) + fac*tmpg; 
1309                                         *b = facm*(*b) + fac*tmpb;
1310                                 }
1311                         }
1312                                 break;
1313                 case MA_RAMP_SAT:               
1314                         if(g){
1315                                 float rH,rS,rV;
1316                                 float colH,colS,colV;
1317                                 rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1318                                 if(rS!=0){
1319                                         rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1320                                         hsv_to_rgb( rH, (facm*rS +fac*colS), rV, r, g, b);
1321                                 }
1322                         }
1323                                 break;
1324                 case MA_RAMP_VAL:               
1325                         if(g){
1326                                 float rH,rS,rV;
1327                                 float colH,colS,colV;
1328                                 rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1329                                 rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1330                                 hsv_to_rgb( rH, rS, (facm*rV +fac*colV), r, g, b);
1331                         }
1332                                 break;
1333                 case MA_RAMP_COLOR:             
1334                         if(g){
1335                                 float rH,rS,rV;
1336                                 float colH,colS,colV;
1337                                 float tmpr,tmpg,tmpb;
1338                                 rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV);
1339                                 if(colS!=0){
1340                                         rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV);
1341                                         hsv_to_rgb( colH, colS, rV, &tmpr, &tmpg, &tmpb);
1342                                         *r = facm*(*r) + fac*tmpr;
1343                                         *g = facm*(*g) + fac*tmpg;
1344                                         *b = facm*(*b) + fac*tmpb;
1345                                 }
1346                         }
1347                                 break;
1348                 case MA_RAMP_SOFT: 
1349                         if (g){ 
1350                                 float scr, scg, scb; 
1351
1352                                 /* first calculate non-fac based Screen mix */ 
1353                                 scr = 1.0f - (1.0f - col[0]) * (1.0f - *r); 
1354                                 scg = 1.0f - (1.0f - col[1]) * (1.0f - *g); 
1355                                 scb = 1.0f - (1.0f - col[2]) * (1.0f - *b); 
1356
1357                                 *r = facm*(*r) + fac*(((1.0f - *r) * col[0] * (*r)) + (*r * scr)); 
1358                                 *g = facm*(*g) + fac*(((1.0f - *g) * col[1] * (*g)) + (*g * scg)); 
1359                                 *b = facm*(*b) + fac*(((1.0f - *b) * col[2] * (*b)) + (*b * scb)); 
1360                         } 
1361                                 break; 
1362                 case MA_RAMP_LINEAR: 
1363                         if (col[0] > 0.5f)  
1364                                 *r = *r + fac*(2.0f*(col[0]-0.5f)); 
1365                         else  
1366                                 *r = *r + fac*(2.0f*(col[0]) - 1.0f); 
1367                         if (g){ 
1368                                 if (col[1] > 0.5f)  
1369                                         *g = *g + fac*(2.0f*(col[1]-0.5f)); 
1370                                 else  
1371                                         *g = *g + fac*(2.0f*(col[1]) -1.0f); 
1372                                 if (col[2] > 0.5f)  
1373                                         *b = *b + fac*(2.0f*(col[2]-0.5f)); 
1374                                 else  
1375                                         *b = *b + fac*(2.0f*(col[2]) - 1.0f); 
1376                         } 
1377                                 break; 
1378         }       
1379 }
1380
1381 /* copy/paste buffer, if we had a propper py api that would be better */
1382 static Material matcopybuf;
1383 static short matcopied= 0;
1384
1385 void clear_matcopybuf(void)
1386 {
1387         memset(&matcopybuf, 0, sizeof(Material));
1388         matcopied= 0;
1389 }
1390
1391 void free_matcopybuf(void)
1392 {
1393         int a;
1394
1395         for(a=0; a<MAX_MTEX; a++) {
1396                 if(matcopybuf.mtex[a]) {
1397                         MEM_freeN(matcopybuf.mtex[a]);
1398                         matcopybuf.mtex[a]= NULL;
1399                 }
1400         }
1401
1402         if(matcopybuf.ramp_col) MEM_freeN(matcopybuf.ramp_col);
1403         if(matcopybuf.ramp_spec) MEM_freeN(matcopybuf.ramp_spec);
1404
1405         matcopybuf.ramp_col= NULL;
1406         matcopybuf.ramp_spec= NULL;
1407
1408         if(matcopybuf.nodetree) {
1409                 ntreeFreeTree(matcopybuf.nodetree);
1410                 MEM_freeN(matcopybuf.nodetree);
1411                 matcopybuf.nodetree= NULL;
1412         }
1413
1414         matcopied= 0;
1415 }
1416
1417 void copy_matcopybuf(Material *ma)
1418 {
1419         int a;
1420         MTex *mtex;
1421
1422         if(matcopied)
1423                 free_matcopybuf();
1424
1425         memcpy(&matcopybuf, ma, sizeof(Material));
1426         if(matcopybuf.ramp_col) matcopybuf.ramp_col= MEM_dupallocN(matcopybuf.ramp_col);
1427         if(matcopybuf.ramp_spec) matcopybuf.ramp_spec= MEM_dupallocN(matcopybuf.ramp_spec);
1428
1429         for(a=0; a<MAX_MTEX; a++) {
1430                 mtex= matcopybuf.mtex[a];
1431                 if(mtex) {
1432                         matcopybuf.mtex[a]= MEM_dupallocN(mtex);
1433                 }
1434         }
1435         matcopybuf.nodetree= ntreeCopyTree(ma->nodetree);
1436         matcopybuf.preview= NULL;
1437         matcopybuf.gpumaterial.first= matcopybuf.gpumaterial.last= NULL;
1438         matcopied= 1;
1439 }
1440
1441 void paste_matcopybuf(Material *ma)
1442 {
1443         int a;
1444         MTex *mtex;
1445         ID id;
1446
1447         if(matcopied==0)
1448                 return;
1449         /* free current mat */
1450         if(ma->ramp_col) MEM_freeN(ma->ramp_col);
1451         if(ma->ramp_spec) MEM_freeN(ma->ramp_spec);
1452         for(a=0; a<MAX_MTEX; a++) {
1453                 mtex= ma->mtex[a];
1454                 if(mtex && mtex->tex) mtex->tex->id.us--;
1455                 if(mtex) MEM_freeN(mtex);
1456         }
1457
1458         if(ma->nodetree) {
1459                 ntreeFreeTree(ma->nodetree);
1460                 MEM_freeN(ma->nodetree);
1461         }
1462
1463         GPU_material_free(ma);
1464
1465         id= (ma->id);
1466         memcpy(ma, &matcopybuf, sizeof(Material));
1467         (ma->id)= id;
1468
1469         if(matcopybuf.ramp_col) ma->ramp_col= MEM_dupallocN(matcopybuf.ramp_col);
1470         if(matcopybuf.ramp_spec) ma->ramp_spec= MEM_dupallocN(matcopybuf.ramp_spec);
1471
1472         for(a=0; a<MAX_MTEX; a++) {
1473                 mtex= ma->mtex[a];
1474                 if(mtex) {
1475                         ma->mtex[a]= MEM_dupallocN(mtex);
1476                         if(mtex->tex) id_us_plus((ID *)mtex->tex);
1477                 }
1478         }
1479
1480         ma->nodetree= ntreeCopyTree(matcopybuf.nodetree);
1481 }
1482
1483
1484 /*********************** texface to material convert functions **********************/
1485 /* encode all the TF information into a single int */
1486 static int encode_tfaceflag(MTFace *tf, int convertall)
1487 {
1488         /* calculate the flag */
1489         int flag = tf->mode;
1490
1491         /* options that change the material offline render */   
1492         if (!convertall) {
1493                 flag &= ~TF_OBCOL;
1494         }
1495
1496         /* clean flags that are not being converted */
1497         flag &= ~TF_TEX;
1498         flag &= ~TF_SHAREDVERT;
1499         flag &= ~TF_SHAREDCOL;
1500         flag &= ~TF_CONVERTED;
1501
1502         /* light tface flag is ignored in GLSL mode */
1503         flag &= ~TF_LIGHT;
1504         
1505         /* 15 is how big the flag can be - hardcoded here and in decode_tfaceflag() */
1506         flag |= tf->transp << 15;
1507         
1508         /* increase 1 so flag 0 is different than no flag yet */
1509         return flag + 1;
1510 }
1511
1512 /* set the material options based in the tface flag */
1513 static void decode_tfaceflag(Material *ma, int flag, int convertall)
1514 {
1515         int alphablend; 
1516         GameSettings *game= &ma->game;
1517
1518         /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
1519         flag -= 1;
1520
1521         alphablend = flag >> 15; //encoded in the encode_tfaceflag function
1522         (*game).flag = 0;
1523         
1524         /* General Material Options */
1525         if ((flag & TF_DYNAMIC)==0) (*game).flag        |= GEMAT_NOPHYSICS;
1526         
1527         /* Material Offline Rendering Properties */
1528         if (convertall) {
1529                 if (flag & TF_OBCOL) ma->shade_flag |= MA_OBCOLOR;
1530         }
1531         
1532         /* Special Face Properties */
1533         if ((flag & TF_TWOSIDE)==0) (*game).flag |= GEMAT_BACKCULL;
1534         if (flag & TF_INVISIBLE)(*game).flag |= GEMAT_INVISIBLE;
1535         if (flag & TF_BMFONT) (*game).flag |= GEMAT_TEXT;
1536         
1537         /* Face Orientation */
1538         if (flag & TF_BILLBOARD) (*game).face_orientation |= GEMAT_HALO;
1539         else if (flag & TF_BILLBOARD2) (*game).face_orientation |= GEMAT_BILLBOARD;
1540         else if (flag & TF_SHADOW) (*game).face_orientation |= GEMAT_SHADOW;
1541         
1542         /* Alpha Blend */
1543         if (flag & TF_ALPHASORT && ELEM(alphablend, TF_ALPHA, TF_ADD)) (*game).alpha_blend = GEMAT_ALPHA_SORT;
1544         else if (alphablend & TF_ALPHA) (*game).alpha_blend = GEMAT_ALPHA;
1545         else if (alphablend & TF_ADD) (*game).alpha_blend = GEMAT_ADD;
1546         else if (alphablend & TF_CLIP) (*game).alpha_blend = GEMAT_CLIP;
1547 }
1548
1549 /* boolean check to see if the mesh needs a material */
1550 static int check_tfaceneedmaterial(int flag)
1551 {
1552         // check if the flags we have are not deprecated != than default material options
1553         // also if only flags are visible and collision see if all objects using this mesh have this option in physics
1554
1555         /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */
1556         flag -=1;
1557
1558         // deprecated flags
1559         flag &= ~TF_OBCOL;
1560         flag &= ~TF_SHAREDVERT;
1561         flag &= ~TF_SHAREDCOL;
1562
1563         /* light tface flag is ignored in GLSL mode */
1564         flag &= ~TF_LIGHT;
1565         
1566         // automatic detected if tex image has alpha
1567         flag &= ~(TF_ALPHA << 15);
1568         // automatic detected if using texture
1569         flag &= ~TF_TEX;
1570
1571         // settings for the default NoMaterial
1572         if (flag == TF_DYNAMIC)
1573                 return 0;
1574
1575         else
1576                 return 1;
1577 }
1578
1579 /* return number of digits of an integer */
1580 // XXX to be optmized or replaced by an equivalent blender internal function
1581 static int integer_getdigits(int number)
1582 {
1583         int i=0;
1584         if (number == 0) return 1;
1585
1586         while (number != 0){
1587                 number = (int)(number/10);
1588                 i++;
1589         }
1590         return i;
1591 }
1592
1593 static void calculate_tface_materialname(char *matname, char *newname, int flag)
1594 {
1595         // if flag has only light and collision and material matches those values
1596         // you can do strcpy(name, mat_name);
1597         // otherwise do:
1598         int digits = integer_getdigits(flag);
1599         /* clamp the old name, remove the MA prefix and add the .TF.flag suffix
1600         e.g. matname = "MALoooooooooooooongName"; newname = "Loooooooooooooon.TF.2" */
1601         sprintf(newname, "%.*s.TF.%0*d", MAX_ID_NAME-(digits+5), matname, digits, flag);
1602 }
1603
1604 /* returns -1 if no match */
1605 static short mesh_getmaterialnumber(Mesh *me, Material *ma)
1606 {
1607         short a;
1608
1609         for (a=0; a<me->totcol; a++) {
1610                 if (me->mat[a] == ma) {
1611                         return a;
1612                 }
1613         }
1614
1615         return -1;
1616 }
1617
1618 /* append material */
1619 static short mesh_addmaterial(Mesh *me, Material *ma)
1620 {
1621         material_append_id(&me->id, NULL);
1622         me->mat[me->totcol-1]= ma;
1623
1624         id_us_plus(&ma->id);
1625
1626         return me->totcol-1;
1627 }
1628
1629 static void set_facetexture_flags(Material *ma, Image *image)
1630 {
1631         if(image) {
1632                 ma->mode |= MA_FACETEXTURE;
1633                 /* we could check if the texture has alpha, but then more meshes sharing the same
1634                  * material may need it. Let's make it simple. */
1635                 if(BKE_image_has_alpha(image))
1636                         ma->mode |= MA_FACETEXTURE_ALPHA;
1637         }
1638 }
1639
1640 /* returns material number */
1641 static short convert_tfacenomaterial(Main *main, Mesh *me, MTFace *tf, int flag)
1642 {
1643         Material *ma;
1644         char idname[MAX_ID_NAME];
1645         short mat_nr= -1;
1646         
1647         /* new material, the name uses the flag*/
1648         sprintf(idname, "MAMaterial.TF.%0*d", integer_getdigits(flag), flag);
1649         
1650         if ((ma= BLI_findstring(&main->mat, idname+2, offsetof(ID, name)+2))) {
1651                 mat_nr= mesh_getmaterialnumber(me, ma);
1652                 /* assign the material to the mesh */
1653                 if(mat_nr == -1) mat_nr= mesh_addmaterial(me, ma);
1654
1655                 /* if needed set "Face Textures [Alpha]" Material options */
1656                 set_facetexture_flags(ma, tf->tpage);
1657         }
1658         /* create a new material */
1659         else {
1660                 ma= add_material(idname+2);
1661
1662                 if(ma){
1663                         printf("TexFace Convert: Material \"%s\" created.\n", idname+2);
1664                         mat_nr= mesh_addmaterial(me, ma);
1665                         
1666                         /* if needed set "Face Textures [Alpha]" Material options */
1667                         set_facetexture_flags(ma, tf->tpage);
1668
1669                         decode_tfaceflag(ma, flag, 1);
1670                         // the final decoding will happen after, outside the main loop
1671                         // for now store the flag into the material and change light/tex/collision 
1672                         // store the flag as a negative number
1673                         ma->game.flag = -flag;
1674                         id_us_min((ID *)ma);    
1675                 }
1676                 else printf("Error: Unable to create Material \"%s\" for Mesh \"%s\".", idname+2, me->id.name+2);
1677         }
1678
1679         /* set as converted, no need to go bad to this face */
1680         tf->mode |= TF_CONVERTED;       
1681         return mat_nr;
1682 }
1683
1684 /* Function to fully convert materials */
1685 static void convert_tfacematerial(Main *main, Material *ma)
1686 {
1687         Mesh *me;
1688         Material *mat_new;
1689         MFace *mf;
1690         MTFace *tf;
1691         int flag, index;
1692         int a;
1693         short mat_nr;
1694         CustomDataLayer *cdl;
1695         char idname[MAX_ID_NAME];
1696
1697         for(me=main->mesh.first; me; me=me->id.next){
1698                 /* check if this mesh uses this material */
1699                 for(a=0;a<me->totcol;a++)
1700                         if(me->mat[a] == ma) break;
1701                         
1702                 /* no material found */
1703                 if (a == me->totcol) continue;
1704
1705                 /* get the active tface layer */
1706                 index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
1707                 cdl= (index == -1)? NULL: &me->fdata.layers[index];
1708                 if (!cdl) continue;
1709
1710                 /* loop over all the faces and stop at the ones that use the material*/
1711                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1712                         if(me->mat[mf->mat_nr] != ma) continue;
1713
1714                         /* texface data for this face */
1715                         tf = ((MTFace*)cdl->data) + a;
1716                         flag = encode_tfaceflag(tf, 1);
1717
1718                         /* the name of the new material */
1719                         calculate_tface_materialname(ma->id.name, (char *)&idname, flag);
1720
1721                         if ((mat_new= BLI_findstring(&main->mat, idname+2, offsetof(ID, name)+2))) {
1722                                 /* material already existent, see if the mesh has it */
1723                                 mat_nr = mesh_getmaterialnumber(me, mat_new);
1724                                 /* material is not in the mesh, add it */
1725                                 if(mat_nr == -1) mat_nr= mesh_addmaterial(me, mat_new);
1726                         }
1727                         /* create a new material */
1728                         else {
1729                                 mat_new=copy_material(ma);
1730                                 if(mat_new){
1731                                         /* rename the material*/
1732                                         strcpy(mat_new->id.name, idname);
1733                                         id_us_min((ID *)mat_new);       
1734
1735                                         mat_nr= mesh_addmaterial(me, mat_new);
1736                                         decode_tfaceflag(mat_new, flag, 1);
1737                                 }
1738                                 else {
1739                                         printf("Error: Unable to create Material \"%s\" for Mesh \"%s.", idname+2, me->id.name+2);
1740                                         mat_nr = mf->mat_nr;
1741                                         continue;
1742                                 }
1743                         }
1744                         
1745                         /* if the material has a texture but no texture channel
1746                          * set "Face Textures [Alpha]" Material options 
1747                          * actually we need to run it always, because of old behavior
1748                          * of using face texture if any texture channel was present (multitex) */
1749                         //if((!mat_new->mtex[0]) && (!mat_new->mtex[0]->tex))
1750                         set_facetexture_flags(mat_new, tf->tpage);
1751
1752                         /* set the material number to the face*/
1753                         mf->mat_nr = mat_nr;
1754                 }
1755                 /* remove material from mesh */
1756                 for(a=0;a<me->totcol;)
1757                         if(me->mat[a] == ma) material_pop_id(&me->id, a, 1);else a++;
1758         }
1759 }
1760
1761
1762 #define MAT_BGE_DISPUTED -99999
1763
1764 int do_version_tface(Main *main, int fileload)
1765 {
1766         Mesh *me;
1767         Material *ma;
1768         MFace *mf;
1769         MTFace *tf;
1770         CustomDataLayer *cdl;
1771         int a;
1772         int flag;
1773         int index;
1774
1775         /* sometimes mesh has no materials but will need a new one. In those
1776          * cases we need to ignore the mf->mat_nr and only look at the face
1777          * mode because it can be zero as uninitialized or the 1st created material
1778          */
1779         int nomaterialslots;
1780
1781         /* alert to user to check the console */
1782         int nowarning = 1;
1783
1784         /* mark all the materials to conversion with a flag
1785          * if there is tface create a complete flag for that storing in flag
1786          * if there is tface and flag > 0: creates a new flag based on this face
1787          * if flags are different set flag to -1  
1788          */
1789         
1790         /* 1st part: marking mesh materials to update */
1791         for(me=main->mesh.first; me; me=me->id.next){
1792                 if (me->id.lib) continue;
1793
1794                 /* get the active tface layer */
1795                 index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
1796                 cdl= (index == -1)? NULL: &me->fdata.layers[index];
1797                 if (!cdl) continue;
1798
1799                 nomaterialslots = (me->totcol==0?1:0);
1800                 
1801                 /* loop over all the faces*/
1802                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1803                         /* texface data for this face */
1804                         tf = ((MTFace*)cdl->data) + a;
1805
1806                         /* conversion should happen only once */
1807                         if (fileload)
1808                                 tf->mode &= ~TF_CONVERTED;
1809                         else {
1810                                 if((tf->mode & TF_CONVERTED)) continue;
1811                                 else tf->mode |= TF_CONVERTED;
1812                         }
1813                         
1814                         /* no material slots */
1815                         if(nomaterialslots) {
1816                                 flag = encode_tfaceflag(tf, 1);
1817                                 
1818                                 /* create/find a new material and assign to the face */
1819                                 if (check_tfaceneedmaterial(flag)) {
1820                                         mf->mat_nr= convert_tfacenomaterial(main, me, tf, flag);
1821                                 }
1822                                 /* else mark them as no-material to be reverted to 0 later */
1823                                 else {
1824                                         mf->mat_nr = -1;
1825                                 }
1826                         }
1827                         else if(mf->mat_nr < me->totcol) {
1828                                 ma= me->mat[mf->mat_nr];
1829                                 
1830                                 /* no material create one if necessary */
1831                                 if(!ma) {
1832                                         /* find a new material and assign to the face */
1833                                         flag = encode_tfaceflag(tf, 1);
1834
1835                                         /* create/find a new material and assign to the face */
1836                                         if (check_tfaceneedmaterial(flag))
1837                                                 mf->mat_nr= convert_tfacenomaterial(main, me, tf, flag);
1838
1839                                         continue;
1840                                 }
1841
1842                                 /* we can't read from this if it comes from a library,
1843                                  * at doversion time: direct_link might not have happened on it,
1844                                  * so ma->mtex is not pointing to valid memory yet.
1845                                  * later we could, but it's better not */
1846                                 else if(ma->id.lib)
1847                                         continue;
1848                                 
1849                                 /* material already marked as disputed */
1850                                 else if(ma->game.flag == MAT_BGE_DISPUTED)
1851                                         continue;
1852
1853                                 /* found a material */
1854                                 else {
1855                                         flag = encode_tfaceflag(tf, ((fileload)?0:1));
1856
1857                                         /* first time changing this material */
1858                                         if (ma->game.flag == 0)
1859                                                 ma->game.flag= -flag;
1860                         
1861                                         /* mark material as disputed */
1862                                         else if (ma->game.flag != -flag) {
1863                                                 ma->game.flag = MAT_BGE_DISPUTED;
1864                                                 continue;
1865                                         }
1866                         
1867                                         /* material ok so far */
1868                                         else {
1869                                                 ma->game.flag = -flag;
1870                                                 
1871                                                 /* some people uses multitexture with TexFace by creating a texture
1872                                                  * channel which not neccessarly the tf->tpage image. But the game engine
1873                                                  * was enabling it. Now it's required to set "Face Texture [Alpha] in the
1874                                                  * material settings. */
1875                                                 if(!fileload)
1876                                                         set_facetexture_flags(ma, tf->tpage);
1877                                         }
1878                                 }
1879                         }
1880                         else
1881                                 continue;
1882                 }
1883
1884                 /* if we didn't have material slot and now we do, we need to
1885                  * make sure the materials are correct */
1886                 if(nomaterialslots) {
1887                         if (me->totcol>0) {
1888                                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1889                                         if (mf->mat_nr == -1) {
1890                                                 /* texface data for this face */
1891                                                 tf = ((MTFace*)cdl->data) + a;
1892                                                 mf->mat_nr= convert_tfacenomaterial(main, me, tf, encode_tfaceflag(tf, 1));
1893                                         }
1894                                 }
1895                         }
1896                         else {
1897                                 for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
1898                                         mf->mat_nr=0;
1899                                 }
1900                         }
1901                 }
1902
1903         }
1904         
1905         /* 2nd part - conversion */
1906         /* skip library files */
1907
1908         /* we shouldn't loop through the materials created in the loop. make the loop stop at its original length) */
1909         for (ma= main->mat.first, a=0; ma; ma= ma->id.next, a++) {
1910                 if (ma->id.lib) continue;
1911
1912                 /* disputed material */
1913                 if (ma->game.flag == MAT_BGE_DISPUTED) {
1914                         ma->game.flag = 0;
1915                         if (fileload) {
1916                                 printf("Warning: material \"%s\" skipped - to convert old game texface to material go to the Help menu.\n", ma->id.name+2);
1917                                 nowarning = 0;
1918                         }
1919                         else
1920                                 convert_tfacematerial(main, ma);
1921                         continue;       
1922                 }
1923         
1924                 /* no conflicts in this material - 90% of cases
1925                  * convert from tface system to material */
1926                 else if (ma->game.flag < 0) {
1927                         decode_tfaceflag(ma, -(ma->game.flag), 1);
1928
1929                         /* material is good make sure all faces using
1930                          * this material are set to converted */
1931                         if (fileload) {
1932                                 for(me=main->mesh.first; me; me=me->id.next){
1933                                         /* check if this mesh uses this material */
1934                                         for(a=0;a<me->totcol;a++)
1935                                                 if(me->mat[a] == ma) break;
1936                                                 
1937                                         /* no material found */
1938                                         if (a == me->totcol) continue;
1939                         
1940                                         /* get the active tface layer */
1941                                         index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
1942                                         cdl= (index == -1)? NULL: &me->fdata.layers[index];
1943                                         if (!cdl) continue;
1944                         
1945                                         /* loop over all the faces and stop at the ones that use the material*/
1946                                         for (a=0, mf=me->mface; a<me->totface; a++, mf++) {
1947                                                 if (me->mat[mf->mat_nr] == ma) {
1948                                                         /* texface data for this face */
1949                                                         tf = ((MTFace*)cdl->data) + a;
1950                                                         tf->mode |= TF_CONVERTED;
1951                                                 }
1952                                         }
1953                                 }
1954                         }
1955                 }
1956         }
1957
1958         return nowarning;
1959 }
1960