svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r20849:20855
[blender.git] / source / blender / blenkernel / intern / brush.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <math.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_brush_types.h"
36 #include "DNA_color_types.h"
37 #include "DNA_image_types.h"
38 #include "DNA_texture_types.h"
39 #include "DNA_scene_types.h"
40 #include "DNA_windowmanager_types.h"
41
42 #include "RNA_access.h"
43
44 #include "BLI_arithb.h"
45 #include "BLI_blenlib.h"
46
47 #include "BKE_brush.h"
48 #include "BKE_colortools.h"
49 #include "BKE_global.h"
50 #include "BKE_image.h"
51 #include "BKE_library.h"
52 #include "BKE_main.h"
53 #include "BKE_texture.h"
54 #include "BKE_utildefines.h"
55
56 #include "IMB_imbuf.h"
57 #include "IMB_imbuf_types.h"
58
59 #include "RE_render_ext.h" /* externtex */
60 #include "RE_shader_ext.h"
61
62 /* Datablock add/copy/free/make_local */
63
64 Brush *add_brush(char *name)
65 {
66         Brush *brush;
67
68         brush= alloc_libblock(&G.main->brush, ID_BR, name);
69
70         brush->rgb[0]= 1.0f;
71         brush->rgb[1]= 1.0f;
72         brush->rgb[2]= 1.0f;
73         brush->alpha= 0.2f;
74         brush->size= 25;
75         brush->spacing= 10.0f;
76         brush->rate= 0.1f;
77         brush->innerradius= 0.5f;
78         brush->clone.alpha= 0.5;
79         brush->sculpt_tool = SCULPT_TOOL_DRAW;
80
81         brush_curve_preset(brush, BRUSH_PRESET_SHARP);
82
83         /* enable fake user by default */
84         brush->id.flag |= LIB_FAKEUSER;
85         brush_toggled_fake_user(brush);
86         
87         return brush;   
88 }
89
90 Brush *copy_brush(Brush *brush)
91 {
92         Brush *brushn;
93         MTex *mtex;
94         int a;
95         
96         brushn= copy_libblock(brush);
97
98         for(a=0; a<MAX_MTEX; a++) {
99                 mtex= brush->mtex[a];
100                 if(mtex) {
101                         brushn->mtex[a]= MEM_dupallocN(mtex);
102                         if(mtex->tex) id_us_plus((ID*)mtex->tex);
103                 }
104         }
105
106         brushn->curve= curvemapping_copy(brush->curve);
107
108         /* enable fake user by default */
109         if (!(brushn->id.flag & LIB_FAKEUSER)) {
110                 brushn->id.flag |= LIB_FAKEUSER;
111                 brush_toggled_fake_user(brushn);
112         }
113         
114         return brushn;
115 }
116
117 /* not brush itself */
118 void free_brush(Brush *brush)
119 {
120         MTex *mtex;
121         int a;
122
123         for(a=0; a<MAX_MTEX; a++) {
124                 mtex= brush->mtex[a];
125                 if(mtex) {
126                         if(mtex->tex) mtex->tex->id.us--;
127                         MEM_freeN(mtex);
128                 }
129         }
130
131         curvemapping_free(brush->curve);
132 }
133
134 void make_local_brush(Brush *brush)
135 {
136         /* - only lib users: do nothing
137                 * - only local users: set flag
138                 * - mixed: make copy
139                 */
140         
141         Brush *brushn;
142         Scene *scene;
143         int local= 0, lib= 0;
144
145         if(brush->id.lib==0) return;
146
147         if(brush->clone.image) {
148                 /* special case: ima always local immediately */
149                 brush->clone.image->id.lib= 0;
150                 brush->clone.image->id.flag= LIB_LOCAL;
151                 new_id(0, (ID *)brush->clone.image, 0);
152         }
153
154         for(scene= G.main->scene.first; scene; scene=scene->id.next)
155                 if(scene->toolsettings->imapaint.brush==brush) {
156                         if(scene->id.lib) lib= 1;
157                         else local= 1;
158                 }
159         
160         if(local && lib==0) {
161                 brush->id.lib= 0;
162                 brush->id.flag= LIB_LOCAL;
163                 new_id(0, (ID *)brush, 0);
164
165                 /* enable fake user by default */
166                 if (!(brush->id.flag & LIB_FAKEUSER)) {
167                         brush->id.flag |= LIB_FAKEUSER;
168                         brush_toggled_fake_user(brush);
169                 }
170         }
171         else if(local && lib) {
172                 brushn= copy_brush(brush);
173                 brushn->id.us= 1; /* only keep fake user */
174                 brushn->id.flag |= LIB_FAKEUSER;
175                 
176                 for(scene= G.main->scene.first; scene; scene=scene->id.next)
177                         if(scene->toolsettings->imapaint.brush==brush)
178                                 if(scene->id.lib==0) {
179                                         scene->toolsettings->imapaint.brush= brushn;
180                                         brushn->id.us++;
181                                         brush->id.us--;
182                                 }
183         }
184 }
185
186 /* Library Operations */
187
188 Brush **current_brush_source(Scene *sce)
189 {
190         if(G.f & G_SCULPTMODE)
191                 return &sce->toolsettings->sculpt->brush;
192         else if(G.f & G_VERTEXPAINT)
193                 return &sce->toolsettings->vpaint->brush;
194         else if(G.f & G_WEIGHTPAINT)
195                 return &sce->toolsettings->wpaint->brush;
196         else if(G.f & G_TEXTUREPAINT)
197                 return &sce->toolsettings->imapaint.brush;
198         return NULL;
199 }
200
201 int brush_set_nr(Brush **current_brush, int nr)
202 {
203         ID *idtest, *id;
204         
205         id= (ID*)(*current_brush);
206         idtest= (ID*)BLI_findlink(&G.main->brush, nr-1);
207         
208         if(idtest==0) { /* new brush */
209                 if(id) idtest= (ID *)copy_brush((Brush *)id);
210                 else idtest= (ID *)add_brush("Brush");
211                 idtest->us--;
212         }
213         if(idtest!=id) {
214                 brush_delete(current_brush);
215                 *current_brush= (Brush *)idtest;
216                 id_us_plus(idtest);
217
218                 return 1;
219         }
220
221         return 0;
222 }
223
224 int brush_delete(Brush **current_brush)
225 {
226         if (*current_brush) {
227                 (*current_brush)->id.us--;
228                 *current_brush= NULL;
229
230                 return 1;
231         }
232
233         return 0;
234 }
235
236 void brush_toggled_fake_user(Brush *brush)
237 {
238         ID *id= (ID*)brush;
239         if(id) {
240                 if(id->flag & LIB_FAKEUSER) {
241                         id_us_plus(id);
242                 } else {
243                         id->us--;
244                 }
245         }
246 }
247
248 void brush_curve_preset(Brush *b, BrushCurvePreset preset)
249 {
250         CurveMap *cm = NULL;
251
252         if(!b->curve)
253                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
254
255         cm = b->curve->cm;
256
257         if(cm->curve)
258                 MEM_freeN(cm->curve);
259
260         if(preset == BRUSH_PRESET_SHARP)
261                 cm->totpoint= 3;
262         if(preset == BRUSH_PRESET_SMOOTH)
263                 cm->totpoint= 6;
264         if(preset == BRUSH_PRESET_MAX)
265                 cm->totpoint= 2;
266
267
268         cm->curve= MEM_callocN(cm->totpoint*sizeof(CurveMapPoint), "curve points");
269         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
270
271         if(preset == BRUSH_PRESET_SHARP) {
272                 cm->curve[0].x= 0;
273                 cm->curve[0].y= 1;
274                 cm->curve[1].x= 0.33;
275                 cm->curve[1].y= 0.33;
276                 cm->curve[2].x= 1;
277                 cm->curve[2].y= 0;
278         }
279         else if(preset == BRUSH_PRESET_SMOOTH) {
280                 cm->curve[0].x= 0;
281                 cm->curve[0].y= 1;
282                 cm->curve[1].x= 0.1;
283                 cm->curve[1].y= 0.97553;
284                 cm->curve[2].x= 0.3;
285                 cm->curve[2].y= 0.79389;
286                 cm->curve[3].x= 0.9;
287                 cm->curve[3].y= 0.02447;
288                 cm->curve[4].x= 0.7;
289                 cm->curve[4].y= 0.20611;
290                 cm->curve[5].x= 1;
291                 cm->curve[5].y= 0;
292         }
293         else if(preset == BRUSH_PRESET_MAX) {
294                 cm->curve[0].x= 0;
295                 cm->curve[0].y= 1;
296                 cm->curve[1].x= 1;
297                 cm->curve[1].y= 1;
298         }
299
300         curvemapping_changed(b->curve, 0);
301 }
302
303 int brush_texture_set_nr(Brush *brush, int nr)
304 {
305         ID *idtest, *id=NULL;
306
307         if(brush->mtex[brush->texact])
308                 id= (ID *)brush->mtex[brush->texact]->tex;
309
310         idtest= (ID*)BLI_findlink(&G.main->tex, nr-1);
311         if(idtest==0) { /* new tex */
312                 if(id) idtest= (ID *)copy_texture((Tex *)id);
313                 else idtest= (ID *)add_texture("Tex");
314                 idtest->us--;
315         }
316         if(idtest!=id) {
317                 brush_texture_delete(brush);
318
319                 if(brush->mtex[brush->texact]==NULL) {
320                         brush->mtex[brush->texact]= add_mtex();
321                         brush->mtex[brush->texact]->r = 1.0f;
322                         brush->mtex[brush->texact]->g = 1.0f;
323                         brush->mtex[brush->texact]->b = 1.0f;
324                 }
325                 brush->mtex[brush->texact]->tex= (Tex*)idtest;
326                 id_us_plus(idtest);
327
328                 return 1;
329         }
330
331         return 0;
332 }
333
334 int brush_texture_delete(Brush *brush)
335 {
336         if(brush->mtex[brush->texact]) {
337                 if(brush->mtex[brush->texact]->tex)
338                         brush->mtex[brush->texact]->tex->id.us--;
339                 MEM_freeN(brush->mtex[brush->texact]);
340                 brush->mtex[brush->texact]= NULL;
341
342                 return 1;
343         }
344
345         return 0;
346 }
347
348 int brush_clone_image_set_nr(Brush *brush, int nr)
349 {
350         if(brush && nr > 0) {
351                 Image *ima= (Image*)BLI_findlink(&G.main->image, nr-1);
352
353                 if(ima) {
354                         brush_clone_image_delete(brush);
355                         brush->clone.image= ima;
356                         id_us_plus(&ima->id);
357                         brush->clone.offset[0]= brush->clone.offset[1]= 0.0f;
358
359                         return 1;
360                 }
361         }
362
363         return 0;
364 }
365
366 int brush_clone_image_delete(Brush *brush)
367 {
368         if (brush && brush->clone.image) {
369                 brush->clone.image->id.us--;
370                 brush->clone.image= NULL;
371                 return 1;
372         }
373
374         return 0;
375 }
376
377 void brush_check_exists(Brush **brush)
378 {
379         if(*brush==NULL)
380                 brush_set_nr(brush, 1);
381 }
382
383 /* Brush Sampling */
384
385 /*static float taylor_approx_cos(float f)
386 {
387         f = f*f;
388         f = 1.0f - f/2.0f + f*f/24.0f;
389         return f;
390 }*/
391
392 float brush_sample_falloff(Brush *brush, float dist)
393 {
394         float a, outer, inner;
395
396         outer = brush->size >> 1;
397         inner = outer*brush->innerradius;
398
399         if (dist <= inner) {
400                 return brush->alpha;
401         }
402         else if ((dist < outer) && (inner < outer)) {
403                 a = sqrt((dist - inner)/(outer - inner));
404                 return (1 - a)*brush->alpha;
405
406                 /* formula used by sculpt, with taylor approx 
407                 a = 0.5f*(taylor_approx_cos(3.0f*(dist - inner)/(outer - inner)) + 1.0f);
408                 return a*brush->alpha; */
409         }
410         else 
411                 return 0.0f;
412 }
413
414 float brush_sample_falloff_noalpha(Brush *brush, float dist)
415 {
416         float outer, inner;
417
418         outer = brush->size >> 1;
419         inner = outer*brush->innerradius;
420
421         if (dist <= inner) {
422                 return 1.0f;
423         }
424         else if ((dist < outer) && (inner < outer)) {
425                 return 1.0f - sqrt((dist - inner)/(outer - inner));
426         }
427         else 
428                 return 0.0f;
429 }
430
431 void brush_sample_tex(Brush *brush, float *xy, float *rgba)
432 {
433         MTex *mtex= brush->mtex[brush->texact];
434
435         if (mtex && mtex->tex) {
436                 float co[3], tin, tr, tg, tb, ta;
437                 int hasrgb;
438                 
439                 co[0]= xy[0]/(brush->size >> 1);
440                 co[1]= xy[1]/(brush->size >> 1);
441                 co[2]= 0.0f;
442
443                 hasrgb= externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
444
445                 if (hasrgb) {
446                         rgba[0]= tr;
447                         rgba[1]= tg;
448                         rgba[2]= tb;
449                         rgba[3]= ta;
450                 }
451                 else {
452                         rgba[0]= tin;
453                         rgba[1]= tin;
454                         rgba[2]= tin;
455                         rgba[3]= 1.0f;
456                 }
457         }
458         else if (rgba)
459                 rgba[0]= rgba[1]= rgba[2]= rgba[3]= 1.0f;
460 }
461
462
463 void brush_imbuf_new(Brush *brush, short flt, short texfall, int size, ImBuf **outbuf)
464 {
465         ImBuf *ibuf;
466         float xy[2], dist, rgba[4], *dstf;
467         int x, y, rowbytes, xoff, yoff, imbflag;
468         char *dst, crgb[3];
469
470         imbflag= (flt)? IB_rectfloat: IB_rect;
471         xoff = -size/2.0f + 0.5f;
472         yoff = -size/2.0f + 0.5f;
473         rowbytes= size*4;
474
475         if (*outbuf)
476                 ibuf= *outbuf;
477         else
478                 ibuf= IMB_allocImBuf(size, size, 32, imbflag, 0);
479
480         if (flt) {
481                 for (y=0; y < ibuf->y; y++) {
482                         dstf = ibuf->rect_float + y*rowbytes;
483
484                         for (x=0; x < ibuf->x; x++, dstf+=4) {
485                                 xy[0] = x + xoff;
486                                 xy[1] = y + yoff;
487
488                                 if (texfall == 0) {
489                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
490
491                                         VECCOPY(dstf, brush->rgb);
492                                         dstf[3]= brush_sample_falloff(brush, dist);
493                                 }
494                                 else if (texfall == 1) {
495                                         brush_sample_tex(brush, xy, dstf);
496                                 }
497                                 else {
498                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
499
500                                         brush_sample_tex(brush, xy, rgba);
501
502                                         dstf[0] = rgba[0]*brush->rgb[0];
503                                         dstf[1] = rgba[1]*brush->rgb[1];
504                                         dstf[2] = rgba[2]*brush->rgb[2];
505                                         dstf[3] = rgba[3]*brush_sample_falloff(brush, dist);
506                                 }
507                         }
508                 }
509         }
510         else {
511                 crgb[0]= FTOCHAR(brush->rgb[0]);
512                 crgb[1]= FTOCHAR(brush->rgb[1]);
513                 crgb[2]= FTOCHAR(brush->rgb[2]);
514
515                 for (y=0; y < ibuf->y; y++) {
516                         dst = (char*)ibuf->rect + y*rowbytes;
517
518                         for (x=0; x < ibuf->x; x++, dst+=4) {
519                                 xy[0] = x + xoff;
520                                 xy[1] = y + yoff;
521
522                                 if (texfall == 0) {
523                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
524
525                                         dst[0]= crgb[0];
526                                         dst[1]= crgb[1];
527                                         dst[2]= crgb[2];
528                                         dst[3]= FTOCHAR(brush_sample_falloff(brush, dist));
529                                 }
530                                 else if (texfall == 1) {
531                                         brush_sample_tex(brush, xy, rgba);
532                                         dst[0]= FTOCHAR(rgba[0]);
533                                         dst[1]= FTOCHAR(rgba[1]);
534                                         dst[2]= FTOCHAR(rgba[2]);
535                                         dst[3]= FTOCHAR(rgba[3]);
536                                 }
537                                 else {
538                                         dist = sqrt(xy[0]*xy[0] + xy[1]*xy[1]);
539
540                                         brush_sample_tex(brush, xy, rgba);
541                                         dst[0] = FTOCHAR(rgba[0]*brush->rgb[0]);
542                                         dst[1] = FTOCHAR(rgba[1]*brush->rgb[1]);
543                                         dst[2] = FTOCHAR(rgba[2]*brush->rgb[2]);
544                                         dst[3] = FTOCHAR(rgba[3]*brush_sample_falloff(brush, dist));
545                                 }
546                         }
547                 }
548         }
549
550         *outbuf= ibuf;
551 }
552
553 /* Brush Painting */
554
555 typedef struct BrushPainterCache {
556         short enabled;
557
558         int size;                       /* size override, if 0 uses brush->size */
559         short flt;                      /* need float imbuf? */
560         short texonly;          /* no alpha, color or fallof, only texture in imbuf */
561
562         int lastsize;
563         float lastalpha;
564         float lastinnerradius;
565
566         ImBuf *ibuf;
567         ImBuf *texibuf;
568         ImBuf *maskibuf;
569 } BrushPainterCache;
570
571 struct BrushPainter {
572         Brush *brush;
573
574         float lastmousepos[2];  /* mouse position of last paint call */
575
576         float accumdistance;    /* accumulated distance of brush since last paint op */
577         float lastpaintpos[2];  /* position of last paint op */
578         float startpaintpos[2]; /* position of first paint */
579
580         double accumtime;               /* accumulated time since last paint op (airbrush) */
581         double lasttime;                /* time of last update */
582
583         float lastpressure;
584
585         short firsttouch;               /* first paint op */
586
587         float startsize;
588         float startalpha;
589         float startinnerradius;
590         float startspacing;
591
592         BrushPainterCache cache;
593 };
594
595 BrushPainter *brush_painter_new(Brush *brush)
596 {
597         BrushPainter *painter= MEM_callocN(sizeof(BrushPainter), "BrushPainter");
598
599         painter->brush= brush;
600         painter->firsttouch= 1;
601         painter->cache.lastsize= -1; /* force ibuf create in refresh */
602
603         painter->startsize = brush->size;
604         painter->startalpha = brush->alpha;
605         painter->startinnerradius = brush->innerradius;
606         painter->startspacing = brush->spacing;
607
608         return painter;
609 }
610
611 void brush_painter_require_imbuf(BrushPainter *painter, short flt, short texonly, int size)
612 {
613         if ((painter->cache.flt != flt) || (painter->cache.size != size) ||
614                 ((painter->cache.texonly != texonly) && texonly)) {
615                 if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
616                 if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
617                 painter->cache.ibuf= painter->cache.maskibuf= NULL;
618                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
619         }
620
621         if (painter->cache.flt != flt) {
622                 if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
623                 painter->cache.texibuf= NULL;
624                 painter->cache.lastsize= -1; /* force ibuf create in refresh */
625         }
626
627         painter->cache.size= size;
628         painter->cache.flt= flt;
629         painter->cache.texonly= texonly;
630         painter->cache.enabled= 1;
631 }
632
633 void brush_painter_free(BrushPainter *painter)
634 {
635         Brush *brush = painter->brush;
636
637         brush->size = painter->startsize;
638         brush->alpha = painter->startalpha;
639         brush->innerradius = painter->startinnerradius;
640         brush->spacing = painter->startspacing;
641
642         if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
643         if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
644         if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
645         MEM_freeN(painter);
646 }
647
648 static void brush_painter_do_partial(BrushPainter *painter, ImBuf *oldtexibuf, int x, int y, int w, int h, int xt, int yt, float *pos)
649 {
650         Brush *brush= painter->brush;
651         ImBuf *ibuf, *maskibuf, *texibuf;
652         float *bf, *mf, *tf, *otf=NULL, xoff, yoff, xy[2], rgba[4];
653         char *b, *m, *t, *ot= NULL;
654         int dotexold, origx= x, origy= y;
655
656         xoff = -brush->size/2.0f + 0.5f;
657         yoff = -brush->size/2.0f + 0.5f;
658         xoff += (int)pos[0] - (int)painter->startpaintpos[0];
659         yoff += (int)pos[1] - (int)painter->startpaintpos[1];
660
661         ibuf = painter->cache.ibuf;
662         texibuf = painter->cache.texibuf;
663         maskibuf = painter->cache.maskibuf;
664
665         dotexold = (oldtexibuf != NULL);
666
667         if (painter->cache.flt) {
668                 for (; y < h; y++) {
669                         bf = ibuf->rect_float + (y*ibuf->x + origx)*4;
670                         tf = texibuf->rect_float + (y*texibuf->x + origx)*4;
671                         mf = maskibuf->rect_float + (y*maskibuf->x + origx)*4;
672
673                         if (dotexold)
674                                 otf = oldtexibuf->rect_float + ((y - origy + yt)*oldtexibuf->x + xt)*4;
675
676                         for (x=origx; x < w; x++, bf+=4, mf+=4, tf+=4) {
677                                 if (dotexold) {
678                                         VECCOPY(tf, otf);
679                                         tf[3] = otf[3];
680                                         otf += 4;
681                                 }
682                                 else {
683                                         xy[0] = x + xoff;
684                                         xy[1] = y + yoff;
685
686                                         brush_sample_tex(brush, xy, tf);
687                                 }
688
689                                 bf[0] = tf[0]*mf[0];
690                                 bf[1] = tf[1]*mf[1];
691                                 bf[2] = tf[2]*mf[2];
692                                 bf[3] = tf[3]*mf[3];
693                         }
694                 }
695         }
696         else {
697                 for (; y < h; y++) {
698                         b = (char*)ibuf->rect + (y*ibuf->x + origx)*4;
699                         t = (char*)texibuf->rect + (y*texibuf->x + origx)*4;
700                         m = (char*)maskibuf->rect + (y*maskibuf->x + origx)*4;
701
702                         if (dotexold)
703                                 ot = (char*)oldtexibuf->rect + ((y - origy + yt)*oldtexibuf->x + xt)*4;
704
705                         for (x=origx; x < w; x++, b+=4, m+=4, t+=4) {
706                                 if (dotexold) {
707                                         t[0] = ot[0];
708                                         t[1] = ot[1];
709                                         t[2] = ot[2];
710                                         t[3] = ot[3];
711                                         ot += 4;
712                                 }
713                                 else {
714                                         xy[0] = x + xoff;
715                                         xy[1] = y + yoff;
716
717                                         brush_sample_tex(brush, xy, rgba);
718                                         t[0]= FTOCHAR(rgba[0]);
719                                         t[1]= FTOCHAR(rgba[1]);
720                                         t[2]= FTOCHAR(rgba[2]);
721                                         t[3]= FTOCHAR(rgba[3]);
722                                 }
723
724                                 b[0] = t[0]*m[0]/255;
725                                 b[1] = t[1]*m[1]/255;
726                                 b[2] = t[2]*m[2]/255;
727                                 b[3] = t[3]*m[3]/255;
728                         }
729                 }
730         }
731 }
732
733 void brush_painter_fixed_tex_partial_update(BrushPainter *painter, float *pos)
734 {
735         Brush *brush= painter->brush;
736         BrushPainterCache *cache= &painter->cache;
737         ImBuf *oldtexibuf, *ibuf;
738         int imbflag, destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
739
740         imbflag= (cache->flt)? IB_rectfloat: IB_rect;
741         if (!cache->ibuf)
742                 cache->ibuf= IMB_allocImBuf(brush->size, brush->size, 32, imbflag, 0);
743         ibuf= cache->ibuf;
744
745         oldtexibuf= cache->texibuf;
746         cache->texibuf= IMB_allocImBuf(brush->size, brush->size, 32, imbflag, 0);
747
748         if (oldtexibuf) {
749                 srcx= srcy= 0;
750                 destx= (int)painter->lastpaintpos[0] - (int)pos[0];
751                 desty= (int)painter->lastpaintpos[1] - (int)pos[1];
752                 w= oldtexibuf->x;
753                 h= oldtexibuf->y;
754
755                 IMB_rectclip(cache->texibuf, oldtexibuf, &destx, &desty, &srcx, &srcy, &w, &h);
756         }
757         else {
758                 srcx= srcy= 0;
759                 destx= desty= 0;
760                 w= h= 0;
761         }
762         
763         x1= destx;
764         y1= desty;
765         x2= destx+w;
766         y2= desty+h;
767
768         /* blend existing texture in new position */
769         if ((x1 < x2) && (y1 < y2))
770                 brush_painter_do_partial(painter, oldtexibuf, x1, y1, x2, y2, srcx, srcy, pos);
771
772         if (oldtexibuf)
773                 IMB_freeImBuf(oldtexibuf);
774
775         /* sample texture in new areas */
776         if ((0 < x1) && (0 < ibuf->y))
777                 brush_painter_do_partial(painter, NULL, 0, 0, x1, ibuf->y, 0, 0, pos);
778         if ((x2 < ibuf->x) && (0 < ibuf->y))
779                 brush_painter_do_partial(painter, NULL, x2, 0, ibuf->x, ibuf->y, 0, 0, pos);
780         if ((x1 < x2) && (0 < y1))
781                 brush_painter_do_partial(painter, NULL, x1, 0, x2, y1, 0, 0, pos);
782         if ((x1 < x2) && (y2 < ibuf->y))
783                 brush_painter_do_partial(painter, NULL, x1, y2, x2, ibuf->y, 0, 0, pos);
784 }
785
786 static void brush_painter_refresh_cache(BrushPainter *painter, float *pos)
787 {
788         Brush *brush= painter->brush;
789         BrushPainterCache *cache= &painter->cache;
790         MTex *mtex= brush->mtex[brush->texact];
791         int size;
792         short flt;
793
794         if ((brush->size != cache->lastsize) || (brush->alpha != cache->lastalpha)
795             || (brush->innerradius != cache->lastinnerradius)) {
796                 if (cache->ibuf) {
797                         IMB_freeImBuf(cache->ibuf);
798                         cache->ibuf= NULL;
799                 }
800                 if (cache->maskibuf) {
801                         IMB_freeImBuf(cache->maskibuf);
802                         cache->maskibuf= NULL;
803                 }
804
805                 flt= cache->flt;
806                 size= (cache->size)? cache->size: brush->size;
807
808                 if (!(mtex && mtex->tex) || (mtex->tex->type==0)) {
809                         brush_imbuf_new(brush, flt, 0, size, &cache->ibuf);
810                 }
811                 else if (brush->flag & BRUSH_FIXED_TEX) {
812                         brush_imbuf_new(brush, flt, 0, size, &cache->maskibuf);
813                         brush_painter_fixed_tex_partial_update(painter, pos);
814                 }
815                 else
816                         brush_imbuf_new(brush, flt, 2, size, &cache->ibuf);
817
818                 cache->lastsize= brush->size;
819                 cache->lastalpha= brush->alpha;
820                 cache->lastinnerradius= brush->innerradius;
821         }
822         else if ((brush->flag & BRUSH_FIXED_TEX) && mtex && mtex->tex) {
823                 int dx = (int)painter->lastpaintpos[0] - (int)pos[0];
824                 int dy = (int)painter->lastpaintpos[1] - (int)pos[1];
825
826                 if ((dx != 0) || (dy != 0))
827                         brush_painter_fixed_tex_partial_update(painter, pos);
828         }
829 }
830
831 void brush_painter_break_stroke(BrushPainter *painter)
832 {
833         painter->firsttouch= 1;
834 }
835
836 static void brush_apply_pressure(BrushPainter *painter, Brush *brush, float pressure)
837 {
838         if (brush->flag & BRUSH_ALPHA_PRESSURE) 
839                 brush->alpha = MAX2(0.0, painter->startalpha*pressure);
840         if (brush->flag & BRUSH_SIZE_PRESSURE)
841                 brush->size = MAX2(1.0, painter->startsize*pressure);
842         if (brush->flag & BRUSH_RAD_PRESSURE)
843                 brush->innerradius = MAX2(0.0, painter->startinnerradius*pressure);
844         if (brush->flag & BRUSH_SPACING_PRESSURE)
845                 brush->spacing = MAX2(1.0, painter->startspacing*(1.5f-pressure));
846 }
847
848 int brush_painter_paint(BrushPainter *painter, BrushFunc func, float *pos, double time, float pressure, void *user)
849 {
850         Brush *brush= painter->brush;
851         int totpaintops= 0;
852
853         if (pressure == 0.0f)
854                 pressure = 1.0f;        /* zero pressure == not using tablet */
855
856         if (painter->firsttouch) {
857                 /* paint exactly once on first touch */
858                 painter->startpaintpos[0]= pos[0];
859                 painter->startpaintpos[1]= pos[1];
860
861                 brush_apply_pressure(painter, brush, pressure);
862                 if (painter->cache.enabled)
863                         brush_painter_refresh_cache(painter, pos);
864                 totpaintops += func(user, painter->cache.ibuf, pos, pos);
865                 
866                 painter->lasttime= time;
867                 painter->firsttouch= 0;
868                 painter->lastpaintpos[0]= pos[0];
869                 painter->lastpaintpos[1]= pos[1];
870         }
871 #if 0
872         else if (painter->brush->flag & BRUSH_AIRBRUSH) {
873                 float spacing, step, paintpos[2], dmousepos[2], len;
874                 double starttime, curtime= time;
875
876                 /* compute brush spacing adapted to brush size */
877                 spacing= brush->rate; //brush->size*brush->spacing*0.01f;
878
879                 /* setup starting time, direction vector and accumulated time */
880                 starttime= painter->accumtime;
881                 Vec2Subf(dmousepos, pos, painter->lastmousepos);
882                 len= Normalize2(dmousepos);
883                 painter->accumtime += curtime - painter->lasttime;
884
885                 /* do paint op over unpainted time distance */
886                 while (painter->accumtime >= spacing) {
887                         step= (spacing - starttime)*len;
888                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
889                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
890
891                         if (painter->cache.enabled)
892                                 brush_painter_refresh_cache(painter);
893                         totpaintops += func(user, painter->cache.ibuf,
894                                 painter->lastpaintpos, paintpos);
895
896                         painter->lastpaintpos[0]= paintpos[0];
897                         painter->lastpaintpos[1]= paintpos[1];
898                         painter->accumtime -= spacing;
899                         starttime -= spacing;
900                 }
901                 
902                 painter->lasttime= curtime;
903         }
904 #endif
905         else {
906                 float startdistance, spacing, step, paintpos[2], dmousepos[2];
907                 float t, len, press;
908
909                 /* compute brush spacing adapted to brush size, spacing may depend
910                    on pressure, so update it */
911                 brush_apply_pressure(painter, brush, painter->lastpressure);
912                 spacing= MAX2(1.0f, brush->size)*brush->spacing*0.01f;
913
914                 /* setup starting distance, direction vector and accumulated distance */
915                 startdistance= painter->accumdistance;
916                 Vec2Subf(dmousepos, pos, painter->lastmousepos);
917                 len= Normalize2(dmousepos);
918                 painter->accumdistance += len;
919
920                 /* do paint op over unpainted distance */
921                 while ((len > 0.0f) && (painter->accumdistance >= spacing)) {
922                         step= spacing - startdistance;
923                         paintpos[0]= painter->lastmousepos[0] + dmousepos[0]*step;
924                         paintpos[1]= painter->lastmousepos[1] + dmousepos[1]*step;
925
926                         t = step/len;
927                         press= (1.0f-t)*painter->lastpressure + t*pressure;
928                         brush_apply_pressure(painter, brush, press);
929                         spacing= MAX2(1.0f, brush->size)*brush->spacing*0.01f;
930
931                         if (painter->cache.enabled)
932                                 brush_painter_refresh_cache(painter, paintpos);
933
934                         totpaintops +=
935                                 func(user, painter->cache.ibuf, painter->lastpaintpos, paintpos);
936
937                         painter->lastpaintpos[0]= paintpos[0];
938                         painter->lastpaintpos[1]= paintpos[1];
939                         painter->accumdistance -= spacing;
940                         startdistance -= spacing;
941                 }
942
943                 /* do airbrush paint ops, based on the number of paint ops left over
944                    from regular painting. this is a temporary solution until we have
945                    accurate time stamps for mouse move events */
946                 if (brush->flag & BRUSH_AIRBRUSH) {
947                         double curtime= time;
948                         double painttime= brush->rate*totpaintops;
949
950                         painter->accumtime += curtime - painter->lasttime;
951                         if (painter->accumtime <= painttime)
952                                 painter->accumtime= 0.0;
953                         else
954                                 painter->accumtime -= painttime;
955
956                         while (painter->accumtime >= brush->rate) {
957                                 brush_apply_pressure(painter, brush, pressure);
958                                 if (painter->cache.enabled)
959                                         brush_painter_refresh_cache(painter, paintpos);
960                                 totpaintops +=
961                                         func(user, painter->cache.ibuf, painter->lastmousepos, pos);
962                                 painter->accumtime -= brush->rate;
963                         }
964
965                         painter->lasttime= curtime;
966                 }
967         }
968
969         painter->lastmousepos[0]= pos[0];
970         painter->lastmousepos[1]= pos[1];
971         painter->lastpressure= pressure;
972
973         brush->alpha = painter->startalpha;
974         brush->size = painter->startsize;
975         brush->innerradius = painter->startinnerradius;
976         brush->spacing = painter->startspacing;
977
978         return totpaintops;
979 }
980
981 /* Uses the brush curve control to find a strength value between 0 and 1 */
982 float brush_curve_strength(Brush *br, float p, const float len)
983 {
984         if(p > len) p= len;
985         return curvemapping_evaluateF(br->curve, 0, p/len);
986 }
987
988 /* TODO: should probably be unified with BrushPainter stuff? */
989 unsigned int *brush_gen_texture_cache(Brush *br, int half_side)
990 {
991         unsigned int *texcache = NULL;
992         MTex *mtex = br->mtex[br->texact];
993         TexResult texres;
994         int hasrgb, ix, iy;
995         int side = half_side * 2;
996
997         memset(&texres, 0, sizeof(TexResult));
998         
999         if(mtex && mtex->tex) {
1000                 float x, y, step = 2.0 / side, co[3];
1001
1002                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
1003
1004                 BKE_image_get_ibuf(mtex->tex->ima, NULL);
1005                 
1006                 /*do normalized cannonical view coords for texture*/
1007                 for (y=-1.0, iy=0; iy<side; iy++, y += step) {
1008                         for (x=-1.0, ix=0; ix<side; ix++, x += step) {
1009                                 co[0]= x;
1010                                 co[1]= y;
1011                                 co[2]= 0.0f;
1012                                 
1013                                 /* This is copied from displace modifier code */
1014                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 1, &texres);
1015                         
1016                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1017                                  * intensity, so calculate one (formula from do_material_tex).
1018                                  * if the texture didn't give an RGB value, copy the intensity across
1019                                  */
1020                                 if(hasrgb & TEX_RGB)
1021                                         texres.tin = (0.35 * texres.tr + 0.45 *
1022                                                       texres.tg + 0.2 * texres.tb);
1023
1024                                 texres.tin = texres.tin * 255.0;
1025                                 ((char*)texcache)[(iy*side+ix)*4] = (char)texres.tin;
1026                                 ((char*)texcache)[(iy*side+ix)*4+1] = (char)texres.tin;
1027                                 ((char*)texcache)[(iy*side+ix)*4+2] = (char)texres.tin;
1028                                 ((char*)texcache)[(iy*side+ix)*4+3] = (char)texres.tin;
1029                         }
1030                 }
1031         }
1032
1033         return texcache;
1034 }
1035
1036 /**** Radial Control ****/
1037 static struct ImBuf *brush_gen_radial_control_imbuf(Brush *br)
1038 {
1039         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1040         unsigned int *texcache;
1041         int side = 128;
1042         int half = side / 2;
1043         int i, j;
1044
1045         texcache = brush_gen_texture_cache(br, half);
1046         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1047         im->x = im->y = side;
1048
1049         for(i=0; i<side; ++i) {
1050                 for(j=0; j<side; ++j) {
1051                         float magn= sqrt(pow(i - half, 2) + pow(j - half, 2));
1052                         im->rect_float[i*side + j]= brush_curve_strength(br, magn, half);
1053                 }
1054         }
1055
1056         /* Modulate curve with texture */
1057         if(texcache) {
1058                 for(i=0; i<side; ++i) {
1059                         for(j=0; j<side; ++j) {
1060                                 const int col= texcache[i*side+j];
1061                                 im->rect_float[i*side+j]*= (((char*)&col)[0]+((char*)&col)[1]+((char*)&col)[2])/3.0f/255.0f;
1062                         }
1063                 }
1064
1065                 MEM_freeN(texcache);
1066         }
1067
1068         return im;
1069 }
1070
1071 void brush_radial_control_invoke(wmOperator *op, Brush *br, float size_weight)
1072 {
1073         int mode = RNA_int_get(op->ptr, "mode");
1074         float original_value= 0;
1075
1076         if(mode == WM_RADIALCONTROL_SIZE)
1077                 original_value = br->size * size_weight;
1078         else if(mode == WM_RADIALCONTROL_STRENGTH)
1079                 original_value = br->alpha;
1080         else if(mode == WM_RADIALCONTROL_ANGLE)
1081                 original_value = br->rot;
1082
1083         RNA_float_set(op->ptr, "initial_value", original_value);
1084         op->customdata = brush_gen_radial_control_imbuf(br);
1085 }
1086
1087 int brush_radial_control_exec(wmOperator *op, Brush *br, float size_weight)
1088 {
1089         int mode = RNA_int_get(op->ptr, "mode");
1090         float new_value = RNA_float_get(op->ptr, "new_value");
1091         const float conv = 0.017453293;
1092
1093         if(mode == WM_RADIALCONTROL_SIZE)
1094                 br->size = new_value * size_weight;
1095         else if(mode == WM_RADIALCONTROL_STRENGTH)
1096                 br->alpha = new_value;
1097         else if(mode == WM_RADIALCONTROL_ANGLE)
1098                 br->rot = new_value * conv;
1099
1100         return OPERATOR_FINISHED;
1101 }