code cleanup: move beauty fill calculation into its own function and some style cleanup
[blender.git] / source / blender / editors / sculpt_paint / paint_cursor.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2009 by Nicholas Bishop
19  * All rights reserved.
20  *
21  * Contributor(s): Jason Wilkins, Tom Musgrove.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  */
26
27 /** \file blender/editors/sculpt_paint/paint_cursor.c
28  *  \ingroup edsculpt
29  */
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_math.h"
34 #include "BLI_rect.h"
35 #include "BLI_utildefines.h"
36
37 #include "DNA_brush_types.h"
38 #include "DNA_color_types.h"
39 #include "DNA_object_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_screen_types.h"
42 #include "DNA_userdef_types.h"
43
44 #include "BKE_brush.h"
45 #include "BKE_context.h"
46 #include "BKE_image.h"
47 #include "BKE_paint.h"
48
49 #include "WM_api.h"
50
51 #include "BIF_gl.h"
52 #include "BIF_glutil.h"
53
54 #include "ED_view3d.h"
55
56 #include "paint_intern.h"
57 /* still needed for sculpt_stroke_get_location, should be
58  * removed eventually (TODO) */
59 #include "sculpt_intern.h"
60
61 /* TODOs:
62  *
63  * Some of the cursor drawing code is doing non-draw stuff
64  * (e.g. updating the brush rake angle). This should be cleaned up
65  * still.
66  *
67  * There is also some ugliness with sculpt-specific code.
68  */
69
70 typedef struct Snapshot {
71         float size[3];
72         float ofs[3];
73         float rot;
74         int BKE_brush_size_get;
75         int winx;
76         int winy;
77         int brush_map_mode;
78         int curve_changed_timestamp;
79 } Snapshot;
80
81 static int same_snap(Snapshot *snap, Brush *brush, ViewContext *vc)
82 {
83         MTex *mtex = &brush->mtex;
84
85         return (((mtex->tex) &&
86                  equals_v3v3(mtex->ofs, snap->ofs) &&
87                  equals_v3v3(mtex->size, snap->size) &&
88                  mtex->rot == snap->rot) &&
89
90                 /* make brush smaller shouldn't cause a resample */
91                 ((mtex->brush_map_mode == MTEX_MAP_MODE_VIEW &&
92                   (BKE_brush_size_get(vc->scene, brush) <= snap->BKE_brush_size_get)) ||
93                  (BKE_brush_size_get(vc->scene, brush) == snap->BKE_brush_size_get)) &&
94
95                 (mtex->brush_map_mode == snap->brush_map_mode) &&
96                 (vc->ar->winx == snap->winx) &&
97                 (vc->ar->winy == snap->winy));
98 }
99
100 static void make_snap(Snapshot *snap, Brush *brush, ViewContext *vc)
101 {
102         if (brush->mtex.tex) {
103                 snap->brush_map_mode = brush->mtex.brush_map_mode;
104                 copy_v3_v3(snap->ofs, brush->mtex.ofs);
105                 copy_v3_v3(snap->size, brush->mtex.size);
106                 snap->rot = brush->mtex.rot;
107         }
108         else {
109                 snap->brush_map_mode = -1;
110                 snap->ofs[0] = snap->ofs[1] = snap->ofs[2] = -1;
111                 snap->size[0] = snap->size[1] = snap->size[2] = -1;
112                 snap->rot = -1;
113         }
114
115         snap->BKE_brush_size_get = BKE_brush_size_get(vc->scene, brush);
116         snap->winx = vc->ar->winx;
117         snap->winy = vc->ar->winy;
118 }
119
120 static int load_tex(Brush *br, ViewContext *vc, float zoom)
121 {
122         static GLuint overlay_texture = 0;
123         static int init = 0;
124         static int tex_changed_timestamp = -1;
125         static int curve_changed_timestamp = -1;
126         static Snapshot snap;
127         static int old_size = -1;
128         static int old_zoom = -1;
129
130         GLubyte *buffer = NULL;
131
132         int size;
133         int j;
134         int refresh;
135         
136         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED && !br->mtex.tex) return 0;
137         
138         refresh = 
139             !overlay_texture ||
140             (br->mtex.tex &&
141              (!br->mtex.tex->preview ||
142               br->mtex.tex->preview->changed_timestamp[0] != tex_changed_timestamp)) ||
143             !br->curve ||
144             br->curve->changed_timestamp != curve_changed_timestamp ||
145             old_zoom != zoom ||
146             !same_snap(&snap, br, vc);
147
148         if (refresh) {
149                 struct ImagePool *pool = NULL;
150                 const float rotation = -br->mtex.rot;
151                 float radius = BKE_brush_size_get(vc->scene, br) * zoom;
152
153                 if (br->mtex.tex && br->mtex.tex->preview)
154                         tex_changed_timestamp = br->mtex.tex->preview->changed_timestamp[0];
155
156                 if (br->curve)
157                         curve_changed_timestamp = br->curve->changed_timestamp;
158
159                 old_zoom = zoom;
160                 make_snap(&snap, br, vc);
161
162                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
163                         int s = BKE_brush_size_get(vc->scene, br);
164                         int r = 1;
165
166                         for (s >>= 1; s > 0; s >>= 1)
167                                 r++;
168
169                         size = (1 << r);
170
171                         if (size < 256)
172                                 size = 256;
173
174                         if (size < old_size)
175                                 size = old_size;
176                 }
177                 else
178                         size = 512;
179
180                 if (old_size != size) {
181                         if (overlay_texture) {
182                                 glDeleteTextures(1, &overlay_texture);
183                                 overlay_texture = 0;
184                         }
185
186                         init = 0;
187
188                         old_size = size;
189                 }
190
191                 buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
192
193                 if (br->mtex.tex)
194                         pool = BKE_image_pool_new();
195
196                 #pragma omp parallel for schedule(static)
197                 for (j = 0; j < size; j++) {
198                         int i;
199                         float y;
200                         float len;
201
202                         for (i = 0; i < size; i++) {
203
204                                 // largely duplicated from tex_strength
205
206                                 int index = j * size + i;
207                                 float x;
208                                 float avg;
209
210                                 x = (float)i / size;
211                                 y = (float)j / size;
212
213                                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) {
214                                         x *= vc->ar->winx / radius;
215                                         y *= vc->ar->winy / radius;
216                                 }
217                                 else {
218                                         x -= 0.5f;
219                                         y -= 0.5f;
220
221                                         x *= 2;
222                                         y *= 2;
223                                 }
224
225                                 len = sqrtf(x * x + y * y);
226
227                                 if ((br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) || len <= 1) {
228                                         /* it is probably worth optimizing for those cases where 
229                                          * the texture is not rotated by skipping the calls to
230                                          * atan2, sqrtf, sin, and cos. */
231                                         if (br->mtex.tex && (rotation > 0.001f || rotation < -0.001f)) {
232                                                 const float angle    = atan2f(y, x) + rotation;
233
234                                                 x = len * cosf(angle);
235                                                 y = len * sinf(angle);
236                                         }
237
238                                         x *= br->mtex.size[0];
239                                         y *= br->mtex.size[1];
240
241                                         x += br->mtex.ofs[0];
242                                         y += br->mtex.ofs[1];
243
244                                         avg = br->mtex.tex ? paint_get_tex_pixel(br, x, y, pool) : 1;
245
246                                         avg += br->texture_sample_bias;
247
248                                         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW)
249                                                 avg *= BKE_brush_curve_strength(br, len, 1);  /* Falloff curve */
250
251                                         buffer[index] = 255 - (GLubyte)(255 * avg);
252                                 }
253                                 else {
254                                         buffer[index] = 0;
255                                 }
256                         }
257                 }
258
259                 if (pool)
260                         BKE_image_pool_free(pool);
261
262                 if (!overlay_texture)
263                         glGenTextures(1, &overlay_texture);
264         }
265         else {
266                 size = old_size;
267         }
268
269         glBindTexture(GL_TEXTURE_2D, overlay_texture);
270
271         if (refresh) {
272                 if (!init) {
273                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
274                         init = 1;
275                 }
276                 else {
277                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
278                 }
279
280                 if (buffer)
281                         MEM_freeN(buffer);
282         }
283
284         glEnable(GL_TEXTURE_2D);
285
286         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
287         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
288         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
289
290         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
291                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
292                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
293         }
294
295         return 1;
296 }
297
298 static int project_brush_radius(ViewContext *vc,
299                                 float radius,
300                                 const float location[3])
301 {
302         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
303
304         ED_view3d_global_to_vector(vc->rv3d, location, view);
305
306         /* create a vector that is not orthogonal to view */
307
308         if (fabsf(view[0]) < 0.1f) {
309                 nonortho[0] = view[0] + 1.0f;
310                 nonortho[1] = view[1];
311                 nonortho[2] = view[2];
312         }
313         else if (fabsf(view[1]) < 0.1f) {
314                 nonortho[0] = view[0];
315                 nonortho[1] = view[1] + 1.0f;
316                 nonortho[2] = view[2];
317         }
318         else {
319                 nonortho[0] = view[0];
320                 nonortho[1] = view[1];
321                 nonortho[2] = view[2] + 1.0f;
322         }
323
324         /* get a vector in the plane of the view */
325         cross_v3_v3v3(ortho, nonortho, view);
326         normalize_v3(ortho);
327
328         /* make a point on the surface of the brush tagent to the view */
329         mul_v3_fl(ortho, radius);
330         add_v3_v3v3(offset, location, ortho);
331
332         /* project the center of the brush, and the tangent point to the view onto the screen */
333         if ((ED_view3d_project_float_global(vc->ar, location, p1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
334             (ED_view3d_project_float_global(vc->ar, offset,   p2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
335         {
336                 /* the distance between these points is the size of the projected brush in pixels */
337                 return len_v2v2(p1, p2);
338         }
339         else {
340                 BLI_assert(0);  /* assert because the code that sets up the vectors should disallow this */
341                 return 0;
342         }
343 }
344
345 static int sculpt_get_brush_geometry(bContext *C, ViewContext *vc,
346                                      int x, int y, int *pixel_radius,
347                                      float location[3])
348 {
349         Scene *scene = CTX_data_scene(C);
350         Paint *paint = paint_get_active_from_context(C);
351         float mouse[2];
352         int hit;
353
354         mouse[0] = x;
355         mouse[1] = y;
356
357         if (vc->obact->sculpt && vc->obact->sculpt->pbvh &&
358             sculpt_stroke_get_location(C, location, mouse))
359         {
360                 Brush *brush = paint_brush(paint);
361                 *pixel_radius =
362                     project_brush_radius(vc,
363                                          BKE_brush_unprojected_radius_get(scene, brush),
364                                          location);
365
366                 if (*pixel_radius == 0)
367                         *pixel_radius = BKE_brush_size_get(scene, brush);
368
369                 mul_m4_v3(vc->obact->obmat, location);
370
371                 hit = 1;
372         }
373         else {
374                 Sculpt *sd    = CTX_data_tool_settings(C)->sculpt;
375                 Brush *brush = paint_brush(&sd->paint);
376
377                 *pixel_radius = BKE_brush_size_get(scene, brush);
378                 hit = 0;
379         }
380
381         return hit;
382 }
383
384 /* Draw an overlay that shows what effect the brush's texture will
385  * have on brush strength */
386 /* TODO: sculpt only for now */
387 static void paint_draw_alpha_overlay(UnifiedPaintSettings *ups, Brush *brush,
388                                      ViewContext *vc, int x, int y, float zoom)
389 {
390         rctf quad;
391
392         /* check for overlay mode */
393         if (!(brush->flag & BRUSH_TEXTURE_OVERLAY) ||
394             !(ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_VIEW, MTEX_MAP_MODE_TILED)))
395         {
396                 return;
397         }
398
399         /* save lots of GL state
400          * TODO: check on whether all of these are needed? */
401         glPushAttrib(GL_COLOR_BUFFER_BIT |
402                      GL_CURRENT_BIT |
403                      GL_DEPTH_BUFFER_BIT |
404                      GL_ENABLE_BIT |
405                      GL_LINE_BIT |
406                      GL_POLYGON_BIT |
407                      GL_STENCIL_BUFFER_BIT |
408                      GL_TRANSFORM_BIT |
409                      GL_VIEWPORT_BIT |
410                      GL_TEXTURE_BIT);
411
412         if (load_tex(brush, vc, zoom)) {
413                 glEnable(GL_BLEND);
414
415                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
416                 glDepthMask(GL_FALSE);
417                 glDepthFunc(GL_ALWAYS);
418
419                 glMatrixMode(GL_TEXTURE);
420                 glPushMatrix();
421                 glLoadIdentity();
422
423                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
424                         /* brush rotation */
425                         glTranslatef(0.5, 0.5, 0);
426                         glRotatef((double)RAD2DEGF(ups->brush_rotation),
427                                   0.0, 0.0, 1.0);
428                         glTranslatef(-0.5f, -0.5f, 0);
429
430                         /* scale based on tablet pressure */
431                         if (ups->draw_pressure && BKE_brush_use_size_pressure(vc->scene, brush)) {
432                                 glTranslatef(0.5f, 0.5f, 0);
433                                 glScalef(1.0f / ups->pressure_value, 1.0f / ups->pressure_value, 1);
434                                 glTranslatef(-0.5f, -0.5f, 0);
435                         }
436
437                         if (ups->draw_anchored) {
438                                 const float *aim = ups->anchored_initial_mouse;
439                                 quad.xmin = aim[0] - ups->anchored_size;
440                                 quad.ymin = aim[1] - ups->anchored_size;
441                                 quad.xmax = aim[0] + ups->anchored_size;
442                                 quad.ymax = aim[1] + ups->anchored_size;
443                         }
444                         else {
445                                 const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
446                                 quad.xmin = x - radius;
447                                 quad.ymin = y - radius;
448                                 quad.xmax = x + radius;
449                                 quad.ymax = y + radius;
450                         }
451                 }
452                 else {
453                         quad.xmin = 0;
454                         quad.ymin = 0;
455                         quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
456                         quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
457                 }
458
459                 /* set quad color */
460                 glColor4f(U.sculpt_paint_overlay_col[0],
461                           U.sculpt_paint_overlay_col[1],
462                           U.sculpt_paint_overlay_col[2],
463                           brush->texture_overlay_alpha / 100.0f);
464
465                 /* draw textured quad */
466                 glBegin(GL_QUADS);
467                 glTexCoord2f(0, 0);
468                 glVertex2f(quad.xmin, quad.ymin);
469                 glTexCoord2f(1, 0);
470                 glVertex2f(quad.xmax, quad.ymin);
471                 glTexCoord2f(1, 1);
472                 glVertex2f(quad.xmax, quad.ymax);
473                 glTexCoord2f(0, 1);
474                 glVertex2f(quad.xmin, quad.ymax);
475                 glEnd();
476
477                 glPopMatrix();
478         }
479
480         glPopAttrib();
481 }
482
483 /* Special actions taken when paint cursor goes over mesh */
484 /* TODO: sculpt only for now */
485 static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc,
486                                 const float location[3])
487 {
488         float unprojected_radius, projected_radius;
489
490         /* update the brush's cached 3D radius */
491         if (!BKE_brush_use_locked_size(vc->scene, brush)) {
492                 /* get 2D brush radius */
493                 if (ups->draw_anchored)
494                         projected_radius = ups->anchored_size;
495                 else {
496                         if (brush->flag & BRUSH_ANCHORED)
497                                 projected_radius = 8;
498                         else
499                                 projected_radius = BKE_brush_size_get(vc->scene, brush);
500                 }
501         
502                 /* convert brush radius from 2D to 3D */
503                 unprojected_radius = paint_calc_object_space_radius(vc, location,
504                                                                     projected_radius);
505
506                 /* scale 3D brush radius by pressure */
507                 if (ups->draw_pressure && BKE_brush_use_size_pressure(vc->scene, brush))
508                         unprojected_radius *= ups->pressure_value;
509
510                 /* set cached value in either Brush or UnifiedPaintSettings */
511                 BKE_brush_unprojected_radius_set(vc->scene, brush, unprojected_radius);
512         }
513 }
514
515 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
516 {
517         Scene *scene = CTX_data_scene(C);
518         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
519         Paint *paint = paint_get_active_from_context(C);
520         Brush *brush = paint_brush(paint);
521         ViewContext vc;
522         float final_radius;
523         float translation[2];
524         float outline_alpha, *outline_col;
525         float zoomx, zoomy;
526         
527         /* check that brush drawing is enabled */
528         if (!(paint->flags & PAINT_SHOW_BRUSH))
529                 return;
530
531         /* can't use stroke vc here because this will be called during
532          * mouse over too, not just during a stroke */
533         view3d_set_viewcontext(C, &vc);
534
535         get_imapaint_zoom(C, &zoomx, &zoomy);
536         zoomx = max_ff(zoomx, zoomy);
537
538         /* set various defaults */
539         translation[0] = x;
540         translation[1] = y;
541         outline_alpha = 0.5;
542         outline_col = brush->add_col;
543         final_radius = BKE_brush_size_get(scene, brush) * zoomx;
544
545         if (brush->flag & BRUSH_RAKE)
546                 /* here, translation contains the mouse coordinates. */
547                 paint_calculate_rake_rotation(ups, translation);
548         else if (!(brush->flag & BRUSH_ANCHORED))
549                 ups->brush_rotation = 0.0;
550
551         /* draw overlay */
552         paint_draw_alpha_overlay(ups, brush, &vc, x, y, zoomx);
553
554         /* TODO: as sculpt and other paint modes are unified, this
555          * special mode of drawing will go away */
556         if (vc.obact->sculpt) {
557                 float location[3];
558                 int pixel_radius, hit;
559
560                 /* test if brush is over the mesh */
561                 hit = sculpt_get_brush_geometry(C, &vc, x, y, &pixel_radius, location);
562
563                 if (BKE_brush_use_locked_size(scene, brush))
564                         BKE_brush_size_set(scene, brush, pixel_radius);
565
566                 /* check if brush is subtracting, use different color then */
567                 /* TODO: no way currently to know state of pen flip or
568                  * invert key modifier without starting a stroke */
569                 if ((!(brush->flag & BRUSH_INVERTED) ^
570                      !(brush->flag & BRUSH_DIR_IN)) &&
571                     ELEM5(brush->sculpt_tool, SCULPT_TOOL_DRAW,
572                           SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY,
573                           SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE))
574                 {
575                         outline_col = brush->sub_col;
576                 }
577
578                 /* only do if brush is over the mesh */
579                 if (hit)
580                         paint_cursor_on_hit(ups, brush, &vc, location);
581
582                 if (ups->draw_anchored) {
583                         final_radius = ups->anchored_size;
584                         translation[0] = ups->anchored_initial_mouse[0];
585                         translation[1] = ups->anchored_initial_mouse[1];
586                 }
587         }
588
589         /* make lines pretty */
590         glEnable(GL_BLEND);
591         glEnable(GL_LINE_SMOOTH);
592
593         /* set brush color */
594         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
595
596         /* draw brush outline */
597         glTranslatef(translation[0], translation[1], 0);
598
599         /* draw an inner brush */
600         if (ups->draw_pressure && BKE_brush_use_size_pressure(scene, brush)) {
601                 /* inner at full alpha */
602                 glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius * ups->pressure_value, 40);
603                 /* outer at half alpha */
604                 glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha * 0.5f);
605         }
606         glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius, 40);
607         glTranslatef(-translation[0], -translation[1], 0);
608
609         /* restore GL state */
610         glDisable(GL_BLEND);
611         glDisable(GL_LINE_SMOOTH);
612 }
613
614 /* Public API */
615
616 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
617 {
618         Paint *p = paint_get_active_from_context(C);
619
620         if (p && !p->paint_cursor)
621                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
622 }
623
624 void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, int (*poll)(bContext *C))
625 {
626         if (p && !p->paint_cursor)
627                 p->paint_cursor = WM_paint_cursor_activate(wm, poll, paint_draw_cursor, NULL);
628 }