Fixed render time regression in Blender Internal
[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)
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
129         GLubyte *buffer = NULL;
130
131         int size;
132         int j;
133         int refresh;
134         
135         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED && !br->mtex.tex) return 0;
136         
137         refresh = 
138             !overlay_texture ||
139             (br->mtex.tex &&
140              (!br->mtex.tex->preview ||
141               br->mtex.tex->preview->changed_timestamp[0] != tex_changed_timestamp)) ||
142             !br->curve ||
143             br->curve->changed_timestamp != curve_changed_timestamp ||
144             !same_snap(&snap, br, vc);
145
146         if (refresh) {
147                 struct ImagePool *pool = NULL;
148
149                 if (br->mtex.tex && br->mtex.tex->preview)
150                         tex_changed_timestamp = br->mtex.tex->preview->changed_timestamp[0];
151
152                 if (br->curve)
153                         curve_changed_timestamp = br->curve->changed_timestamp;
154
155                 make_snap(&snap, br, vc);
156
157                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
158                         int s = BKE_brush_size_get(vc->scene, br);
159                         int r = 1;
160
161                         for (s >>= 1; s > 0; s >>= 1)
162                                 r++;
163
164                         size = (1 << r);
165
166                         if (size < 256)
167                                 size = 256;
168
169                         if (size < old_size)
170                                 size = old_size;
171                 }
172                 else
173                         size = 512;
174
175                 if (old_size != size) {
176                         if (overlay_texture) {
177                                 glDeleteTextures(1, &overlay_texture);
178                                 overlay_texture = 0;
179                         }
180
181                         init = 0;
182
183                         old_size = size;
184                 }
185
186                 buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
187
188                 if (br->mtex.tex)
189                         pool = BKE_image_pool_new();
190
191                 #pragma omp parallel for schedule(static)
192                 for (j = 0; j < size; j++) {
193                         int i;
194                         float y;
195                         float len;
196
197                         for (i = 0; i < size; i++) {
198
199                                 // largely duplicated from tex_strength
200
201                                 const float rotation = -br->mtex.rot;
202                                 float radius = BKE_brush_size_get(vc->scene, br);
203                                 int index = j * size + i;
204                                 float x;
205                                 float avg;
206
207                                 x = (float)i / size;
208                                 y = (float)j / size;
209
210                                 x -= 0.5f;
211                                 y -= 0.5f;
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 *= 2;
219                                         y *= 2;
220                                 }
221
222                                 len = sqrtf(x * x + y * y);
223
224                                 if ((br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) || len <= 1) {
225                                         /* it is probably worth optimizing for those cases where 
226                                          * the texture is not rotated by skipping the calls to
227                                          * atan2, sqrtf, sin, and cos. */
228                                         if (br->mtex.tex && (rotation > 0.001f || rotation < -0.001f)) {
229                                                 const float angle    = atan2f(y, x) + rotation;
230
231                                                 x = len * cosf(angle);
232                                                 y = len * sinf(angle);
233                                         }
234
235                                         x *= br->mtex.size[0];
236                                         y *= br->mtex.size[1];
237
238                                         x += br->mtex.ofs[0];
239                                         y += br->mtex.ofs[1];
240
241                                         avg = br->mtex.tex ? paint_get_tex_pixel(br, x, y, pool) : 1;
242
243                                         avg += br->texture_sample_bias;
244
245                                         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW)
246                                                 avg *= BKE_brush_curve_strength(br, len, 1);  /* Falloff curve */
247
248                                         buffer[index] = 255 - (GLubyte)(255 * avg);
249                                 }
250                                 else {
251                                         buffer[index] = 0;
252                                 }
253                         }
254                 }
255
256                 if (pool)
257                         BKE_image_pool_free(pool);
258
259                 if (!overlay_texture)
260                         glGenTextures(1, &overlay_texture);
261         }
262         else {
263                 size = old_size;
264         }
265
266         glBindTexture(GL_TEXTURE_2D, overlay_texture);
267
268         if (refresh) {
269                 if (!init) {
270                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
271                         init = 1;
272                 }
273                 else {
274                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
275                 }
276
277                 if (buffer)
278                         MEM_freeN(buffer);
279         }
280
281         glEnable(GL_TEXTURE_2D);
282
283         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
284         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
285         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
286
287         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
288                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
289                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
290         }
291
292         return 1;
293 }
294
295 static int project_brush_radius(ViewContext *vc,
296                                 float radius,
297                                 const float location[3])
298 {
299         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
300
301         ED_view3d_global_to_vector(vc->rv3d, location, view);
302
303         /* create a vector that is not orthogonal to view */
304
305         if (fabsf(view[0]) < 0.1f) {
306                 nonortho[0] = view[0] + 1.0f;
307                 nonortho[1] = view[1];
308                 nonortho[2] = view[2];
309         }
310         else if (fabsf(view[1]) < 0.1f) {
311                 nonortho[0] = view[0];
312                 nonortho[1] = view[1] + 1.0f;
313                 nonortho[2] = view[2];
314         }
315         else {
316                 nonortho[0] = view[0];
317                 nonortho[1] = view[1];
318                 nonortho[2] = view[2] + 1.0f;
319         }
320
321         /* get a vector in the plane of the view */
322         cross_v3_v3v3(ortho, nonortho, view);
323         normalize_v3(ortho);
324
325         /* make a point on the surface of the brush tagent to the view */
326         mul_v3_fl(ortho, radius);
327         add_v3_v3v3(offset, location, ortho);
328
329         /* project the center of the brush, and the tangent point to the view onto the screen */
330         if ((ED_view3d_project_float_global(vc->ar, location, p1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
331             (ED_view3d_project_float_global(vc->ar, offset,   p2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
332         {
333                 /* the distance between these points is the size of the projected brush in pixels */
334                 return len_v2v2(p1, p2);
335         }
336         else {
337                 BLI_assert(0);  /* assert because the code that sets up the vectors should disallow this */
338                 return 0;
339         }
340 }
341
342 static int sculpt_get_brush_geometry(bContext *C, ViewContext *vc,
343                                      int x, int y, int *pixel_radius,
344                                      float location[3])
345 {
346         Scene *scene = CTX_data_scene(C);
347         Paint *paint = paint_get_active_from_context(C);
348         float window[2];
349         int hit;
350
351         window[0] = x + vc->ar->winrct.xmin;
352         window[1] = y + vc->ar->winrct.ymin;
353
354         if (vc->obact->sculpt && vc->obact->sculpt->pbvh &&
355             sculpt_stroke_get_location(C, location, window))
356         {
357                 Brush *brush = paint_brush(paint);
358                 *pixel_radius =
359                     project_brush_radius(vc,
360                                          BKE_brush_unprojected_radius_get(scene, brush),
361                                          location);
362
363                 if (*pixel_radius == 0)
364                         *pixel_radius = BKE_brush_size_get(scene, brush);
365
366                 mul_m4_v3(vc->obact->obmat, location);
367
368                 hit = 1;
369         }
370         else {
371                 Sculpt *sd    = CTX_data_tool_settings(C)->sculpt;
372                 Brush *brush = paint_brush(&sd->paint);
373
374                 *pixel_radius = BKE_brush_size_get(scene, brush);
375                 hit = 0;
376         }
377
378         return hit;
379 }
380
381 /* Draw an overlay that shows what effect the brush's texture will
382  * have on brush strength */
383 /* TODO: sculpt only for now */
384 static void paint_draw_alpha_overlay(UnifiedPaintSettings *ups, Brush *brush,
385                                      ViewContext *vc, int x, int y)
386 {
387         rctf quad;
388
389         /* check for overlay mode */
390         if (!(brush->flag & BRUSH_TEXTURE_OVERLAY) ||
391             !(ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_VIEW, MTEX_MAP_MODE_TILED)))
392         {
393                 return;
394         }
395
396         /* save lots of GL state
397          * TODO: check on whether all of these are needed? */
398         glPushAttrib(GL_COLOR_BUFFER_BIT |
399                      GL_CURRENT_BIT |
400                      GL_DEPTH_BUFFER_BIT |
401                      GL_ENABLE_BIT |
402                      GL_LINE_BIT |
403                      GL_POLYGON_BIT |
404                      GL_STENCIL_BUFFER_BIT |
405                      GL_TRANSFORM_BIT |
406                      GL_VIEWPORT_BIT |
407                      GL_TEXTURE_BIT);
408
409         if (load_tex(brush, vc)) {
410                 glEnable(GL_BLEND);
411
412                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
413                 glDepthMask(GL_FALSE);
414                 glDepthFunc(GL_ALWAYS);
415
416                 glMatrixMode(GL_TEXTURE);
417                 glPushMatrix();
418                 glLoadIdentity();
419
420                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW) {
421                         /* brush rotation */
422                         glTranslatef(0.5, 0.5, 0);
423                         glRotatef((double)RAD2DEGF((brush->flag & BRUSH_RAKE) ?
424                                                    ups->last_angle : ups->special_rotation),
425                                   0.0, 0.0, 1.0);
426                         glTranslatef(-0.5f, -0.5f, 0);
427
428                         /* scale based on tablet pressure */
429                         if (ups->draw_pressure && BKE_brush_use_size_pressure(vc->scene, brush)) {
430                                 glTranslatef(0.5f, 0.5f, 0);
431                                 glScalef(1.0f / ups->pressure_value, 1.0f / ups->pressure_value, 1);
432                                 glTranslatef(-0.5f, -0.5f, 0);
433                         }
434
435                         if (ups->draw_anchored) {
436                                 const float *aim = ups->anchored_initial_mouse;
437                                 const rcti *win = &vc->ar->winrct;
438                                 quad.xmin = aim[0] - ups->anchored_size - win->xmin;
439                                 quad.ymin = aim[1] - ups->anchored_size - win->ymin;
440                                 quad.xmax = aim[0] + ups->anchored_size - win->xmin;
441                                 quad.ymax = aim[1] + ups->anchored_size - win->ymin;
442                         }
443                         else {
444                                 const int radius = BKE_brush_size_get(vc->scene, brush);
445                                 quad.xmin = x - radius;
446                                 quad.ymin = y - radius;
447                                 quad.xmax = x + radius;
448                                 quad.ymax = y + radius;
449                         }
450                 }
451                 else {
452                         quad.xmin = 0;
453                         quad.ymin = 0;
454                         quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
455                         quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
456                 }
457
458                 /* set quad color */
459                 glColor4f(U.sculpt_paint_overlay_col[0],
460                           U.sculpt_paint_overlay_col[1],
461                           U.sculpt_paint_overlay_col[2],
462                           brush->texture_overlay_alpha / 100.0f);
463
464                 /* draw textured quad */
465                 glBegin(GL_QUADS);
466                 glTexCoord2f(0, 0);
467                 glVertex2f(quad.xmin, quad.ymin);
468                 glTexCoord2f(1, 0);
469                 glVertex2f(quad.xmax, quad.ymin);
470                 glTexCoord2f(1, 1);
471                 glVertex2f(quad.xmax, quad.ymax);
472                 glTexCoord2f(0, 1);
473                 glVertex2f(quad.xmin, quad.ymax);
474                 glEnd();
475
476                 glPopMatrix();
477         }
478
479         glPopAttrib();
480 }
481
482 /* Special actions taken when paint cursor goes over mesh */
483 /* TODO: sculpt only for now */
484 static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc,
485                                 const float location[3])
486 {
487         float unprojected_radius, projected_radius;
488
489         /* update the brush's cached 3D radius */
490         if (!BKE_brush_use_locked_size(vc->scene, brush)) {
491                 /* get 2D brush radius */
492                 if (ups->draw_anchored)
493                         projected_radius = ups->anchored_size;
494                 else {
495                         if (brush->flag & BRUSH_ANCHORED)
496                                 projected_radius = 8;
497                         else
498                                 projected_radius = BKE_brush_size_get(vc->scene, brush);
499                 }
500         
501                 /* convert brush radius from 2D to 3D */
502                 unprojected_radius = paint_calc_object_space_radius(vc, location,
503                                                                     projected_radius);
504
505                 /* scale 3D brush radius by pressure */
506                 if (ups->draw_pressure && BKE_brush_use_size_pressure(vc->scene, brush))
507                         unprojected_radius *= ups->pressure_value;
508
509                 /* set cached value in either Brush or UnifiedPaintSettings */
510                 BKE_brush_unprojected_radius_set(vc->scene, brush, unprojected_radius);
511         }
512 }
513
514 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
515 {
516         Scene *scene = CTX_data_scene(C);
517         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
518         Paint *paint = paint_get_active_from_context(C);
519         Brush *brush = paint_brush(paint);
520         ViewContext vc;
521         float final_radius;
522         float translation[2];
523         float outline_alpha, *outline_col;
524         
525         /* set various defaults */
526         translation[0] = x;
527         translation[1] = y;
528         outline_alpha = 0.5;
529         outline_col = brush->add_col;
530         final_radius = BKE_brush_size_get(scene, brush);
531
532         /* check that brush drawing is enabled */
533         if (!(paint->flags & PAINT_SHOW_BRUSH))
534                 return;
535
536         /* can't use stroke vc here because this will be called during
537          * mouse over too, not just during a stroke */
538         view3d_set_viewcontext(C, &vc);
539
540         /* TODO: as sculpt and other paint modes are unified, this
541          * special mode of drawing will go away */
542         if (vc.obact->sculpt) {
543                 float location[3];
544                 int pixel_radius, hit;
545
546                 /* this is probably here so that rake takes into
547                  * account the brush movements before the stroke
548                  * starts, but this doesn't really belong in draw code
549                  *  TODO) */
550                 {
551                         const float u = 0.5f;
552                         const float v = 1 - u;
553                         const float r = 20;
554
555                         const float dx = ups->last_x - x;
556                         const float dy = ups->last_y - y;
557
558                         if (dx * dx + dy * dy >= r * r) {
559                                 ups->last_angle = atan2(dx, dy);
560
561                                 ups->last_x = u * ups->last_x + v * x;
562                                 ups->last_y = u * ups->last_y + v * y;
563                         }
564                 }
565
566                 /* test if brush is over the mesh */
567                 hit = sculpt_get_brush_geometry(C, &vc, x, y, &pixel_radius, location);
568
569                 /* draw overlay */
570                 paint_draw_alpha_overlay(ups, brush, &vc, x, y);
571
572                 if (BKE_brush_use_locked_size(scene, brush))
573                         BKE_brush_size_set(scene, brush, pixel_radius);
574
575                 /* check if brush is subtracting, use different color then */
576                 /* TODO: no way currently to know state of pen flip or
577                  * invert key modifier without starting a stroke */
578                 if ((!(brush->flag & BRUSH_INVERTED) ^
579                      !(brush->flag & BRUSH_DIR_IN)) &&
580                     ELEM5(brush->sculpt_tool, SCULPT_TOOL_DRAW,
581                           SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY,
582                           SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE))
583                 {
584                         outline_col = brush->sub_col;
585                 }
586
587                 /* only do if brush is over the mesh */
588                 if (hit)
589                         paint_cursor_on_hit(ups, brush, &vc, location);
590
591                 if (ups->draw_anchored) {
592                         final_radius = ups->anchored_size;
593                         translation[0] = ups->anchored_initial_mouse[0] - vc.ar->winrct.xmin;
594                         translation[1] = ups->anchored_initial_mouse[1] - vc.ar->winrct.ymin;
595                 }
596         }
597
598         /* make lines pretty */
599         glEnable(GL_BLEND);
600         glEnable(GL_LINE_SMOOTH);
601
602         /* set brush color */
603         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
604
605         /* draw brush outline */
606         glTranslatef(translation[0], translation[1], 0);
607
608         /* draw an inner brush */
609         if (ups->draw_pressure && BKE_brush_use_size_pressure(scene, brush)) {
610                 /* inner at full alpha */
611                 glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius * ups->pressure_value, 40);
612                 /* outer at half alpha */
613                 glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha * 0.5f);
614         }
615         glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius, 40);
616         glTranslatef(-translation[0], -translation[1], 0);
617
618         /* restore GL state */
619         glDisable(GL_BLEND);
620         glDisable(GL_LINE_SMOOTH);
621 }
622
623 /* Public API */
624
625 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
626 {
627         Paint *p = paint_get_active_from_context(C);
628
629         if (p && !p->paint_cursor)
630                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
631 }