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