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