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