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