92cb346b61e98526eee721e5dbb4c2051b8e36c7
[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_customdata_types.h"
39 #include "DNA_color_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_screen_types.h"
43 #include "DNA_userdef_types.h"
44
45 #include "BKE_brush.h"
46 #include "BKE_context.h"
47 #include "BKE_curve.h"
48 #include "BKE_image.h"
49 #include "BKE_node.h"
50 #include "BKE_paint.h"
51 #include "BKE_colortools.h"
52
53 #include "WM_api.h"
54
55 #include "BIF_gl.h"
56 #include "BIF_glutil.h"
57
58 #include "IMB_imbuf_types.h"
59
60 #include "ED_view3d.h"
61
62 #include "UI_resources.h"
63
64 #include "paint_intern.h"
65 /* still needed for sculpt_stroke_get_location, should be
66  * removed eventually (TODO) */
67 #include "sculpt_intern.h"
68
69 #ifdef _OPENMP
70 #include <omp.h>
71 #endif
72
73 /* TODOs:
74  *
75  * Some of the cursor drawing code is doing non-draw stuff
76  * (e.g. updating the brush rake angle). This should be cleaned up
77  * still.
78  *
79  * There is also some ugliness with sculpt-specific code.
80  */
81
82 typedef struct TexSnapshot {
83         GLuint overlay_texture;
84         int winx;
85         int winy;
86         int old_size;
87         float old_zoom;
88         bool old_col;
89 } TexSnapshot;
90
91 typedef struct CursorSnapshot {
92         GLuint overlay_texture;
93         int size;
94         int zoom;
95 } CursorSnapshot;
96
97 static TexSnapshot primary_snap = {0};
98 static TexSnapshot secondary_snap  = {0};
99 static CursorSnapshot cursor_snap  = {0};
100
101 /* delete overlay cursor textures to preserve memory and invalidate all overlay flags */
102 void paint_cursor_delete_textures(void)
103 {
104         if (primary_snap.overlay_texture)
105                 glDeleteTextures(1, &primary_snap.overlay_texture);
106         if (secondary_snap.overlay_texture)
107                 glDeleteTextures(1, &secondary_snap.overlay_texture);
108         if (cursor_snap.overlay_texture)
109                 glDeleteTextures(1, &cursor_snap.overlay_texture);
110
111         memset(&primary_snap, 0, sizeof(TexSnapshot));
112         memset(&secondary_snap, 0, sizeof(TexSnapshot));
113         memset(&cursor_snap, 0, sizeof(CursorSnapshot));
114
115         BKE_paint_invalidate_overlay_all();
116 }
117
118 static int same_tex_snap(TexSnapshot *snap, MTex *mtex, ViewContext *vc, bool col, float zoom)
119 {
120         return (/* make brush smaller shouldn't cause a resample */
121                 //(mtex->brush_map_mode != MTEX_MAP_MODE_VIEW ||
122                 //(BKE_brush_size_get(vc->scene, brush) <= snap->BKE_brush_size_get)) &&
123
124                 (mtex->brush_map_mode != MTEX_MAP_MODE_TILED ||
125                  (vc->ar->winx == snap->winx &&
126                   vc->ar->winy == snap->winy)) &&
127                 (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL ||
128                 snap->old_zoom == zoom) &&
129                 snap->old_col == col
130                 );
131 }
132
133 static void make_tex_snap(TexSnapshot *snap, ViewContext *vc, float zoom)
134 {
135         snap->old_zoom = zoom;
136         snap->winx = vc->ar->winx;
137         snap->winy = vc->ar->winy;
138 }
139
140 static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool primary)
141 {
142         bool init;
143         TexSnapshot *target;
144
145         MTex *mtex = (primary) ? &br->mtex : &br->mask_mtex;
146         OverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
147         GLubyte *buffer = NULL;
148
149         int size;
150         int j;
151         int refresh;
152         GLenum format = col ? GL_RGBA : GL_ALPHA;
153         OverlayControlFlags invalid = (primary) ? (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) :
154                                    (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY);
155
156         target = (primary) ? &primary_snap : &secondary_snap;
157
158         refresh = 
159             !target->overlay_texture ||
160             (invalid != 0) ||
161             !same_tex_snap(target, mtex, vc, col, zoom);
162
163         init = (target->overlay_texture != 0);
164
165         if (refresh) {
166                 struct ImagePool *pool = NULL;
167                 bool convert_to_linear = false;
168                 struct ColorSpace *colorspace;
169                 /* stencil is rotated later */
170                 const float rotation = (mtex->brush_map_mode != MTEX_MAP_MODE_STENCIL) ?
171                                        -mtex->rot : 0;
172
173                 float radius = BKE_brush_size_get(vc->scene, br) * zoom;
174
175                 make_tex_snap(target, vc, zoom);
176
177                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
178                         int s = BKE_brush_size_get(vc->scene, br);
179                         int r = 1;
180
181                         for (s >>= 1; s > 0; s >>= 1)
182                                 r++;
183
184                         size = (1 << r);
185
186                         if (size < 256)
187                                 size = 256;
188
189                         if (size < target->old_size)
190                                 size = target->old_size;
191                 }
192                 else
193                         size = 512;
194
195                 if (target->old_size != size) {
196                         if (target->overlay_texture) {
197                                 glDeleteTextures(1, &target->overlay_texture);
198                                 target->overlay_texture = 0;
199                         }
200
201                         init = false;
202
203                         target->old_size = size;
204                 }
205                 if (col)
206                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size * 4, "load_tex");
207                 else
208                         buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
209
210                 pool = BKE_image_pool_new();
211
212                 if (mtex->tex && mtex->tex->nodetree)
213                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
214
215 #pragma omp parallel for schedule(static)
216                 for (j = 0; j < size; j++) {
217                         int i;
218                         float y;
219                         float len;
220                         int thread_num;
221
222 #ifdef _OPENMP
223                         thread_num = omp_get_thread_num();
224 #else
225                         thread_num = 0;
226 #endif
227
228                         if (mtex->tex->type == TEX_IMAGE && mtex->tex->ima) {
229                                 ImBuf *tex_ibuf = BKE_image_pool_acquire_ibuf(mtex->tex->ima, &mtex->tex->iuser, pool);
230                                 /* For consistency, sampling always returns color in linear space */
231                                 if (tex_ibuf && tex_ibuf->rect_float == NULL) {
232                                         convert_to_linear = true;
233                                         colorspace = tex_ibuf->rect_colorspace;
234                                 }
235                                 BKE_image_pool_release_ibuf(mtex->tex->ima, tex_ibuf, pool);
236                         }
237
238
239                         for (i = 0; i < size; i++) {
240
241                                 // largely duplicated from tex_strength
242
243                                 int index = j * size + i;
244                                 float x;
245
246                                 x = (float)i / size;
247                                 y = (float)j / size;
248
249                                 if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
250                                         x *= vc->ar->winx / radius;
251                                         y *= vc->ar->winy / radius;
252                                 }
253                                 else {
254                                         x -= 0.5f;
255                                         y -= 0.5f;
256
257                                         x *= 2;
258                                         y *= 2;
259                                 }
260
261                                 len = sqrtf(x * x + y * y);
262
263                                 if (ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL) || len <= 1) {
264                                         /* it is probably worth optimizing for those cases where 
265                                          * the texture is not rotated by skipping the calls to
266                                          * atan2, sqrtf, sin, and cos. */
267                                         if (mtex->tex && (rotation > 0.001f || rotation < -0.001f)) {
268                                                 const float angle = atan2f(y, x) + rotation;
269
270                                                 x = len * cosf(angle);
271                                                 y = len * sinf(angle);
272                                         }
273
274                                         if (col) {
275                                                 float rgba[4];
276
277                                                 paint_get_tex_pixel_col(mtex, x, y, rgba, pool, thread_num, convert_to_linear, colorspace);
278
279                                                 buffer[index * 4]     = rgba[0] * 255;
280                                                 buffer[index * 4 + 1] = rgba[1] * 255;
281                                                 buffer[index * 4 + 2] = rgba[2] * 255;
282                                                 buffer[index * 4 + 3] = rgba[3] * 255;
283                                         }
284                                         else {
285                                                 float avg = paint_get_tex_pixel(mtex, x, y, pool, thread_num);
286
287                                                 avg += br->texture_sample_bias;
288
289                                                 /* clamp to avoid precision overflow */
290                                                 CLAMP(avg, 0.0f, 1.0f);
291                                                 buffer[index] = 255 - (GLubyte)(255 * avg);
292                                         }
293                                 }
294                                 else {
295                                         if (col) {
296                                                 buffer[index * 4]     = 0;
297                                                 buffer[index * 4 + 1] = 0;
298                                                 buffer[index * 4 + 2] = 0;
299                                                 buffer[index * 4 + 3] = 0;
300                                         }
301                                         else {
302                                                 buffer[index] = 0;
303                                         }
304                                 }
305                         }
306                 }
307
308                 if (mtex->tex && mtex->tex->nodetree)
309                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
310
311                 if (pool)
312                         BKE_image_pool_free(pool);
313
314                 if (!target->overlay_texture)
315                         glGenTextures(1, &target->overlay_texture);
316         }
317         else {
318                 size = target->old_size;
319         }
320
321         glBindTexture(GL_TEXTURE_2D, target->overlay_texture);
322
323         if (refresh) {
324                 if (!init || (target->old_col != col)) {
325                         glTexImage2D(GL_TEXTURE_2D, 0, format, size, size, 0, format, GL_UNSIGNED_BYTE, buffer);
326                 }
327                 else {
328                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, format, GL_UNSIGNED_BYTE, buffer);
329                 }
330
331                 if (buffer)
332                         MEM_freeN(buffer);
333
334                 target->old_col = col;
335         }
336
337         glEnable(GL_TEXTURE_2D);
338
339         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
340         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
341         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
342
343         if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
344                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
345                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
346         }
347
348         BKE_paint_reset_overlay_invalid(invalid);
349
350         return 1;
351 }
352
353 static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom)
354 {
355         bool init;
356
357         OverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
358         GLubyte *buffer = NULL;
359
360         int size;
361         int j;
362         int refresh;
363
364         refresh =
365             !cursor_snap.overlay_texture ||
366             (overlay_flags & PAINT_INVALID_OVERLAY_CURVE) ||
367             cursor_snap.zoom != zoom;
368
369         init = (cursor_snap.overlay_texture != 0);
370
371         if (refresh) {
372                 int s, r;
373
374                 cursor_snap.zoom = zoom;
375
376                 s = BKE_brush_size_get(vc->scene, br);
377                 r = 1;
378
379                 for (s >>= 1; s > 0; s >>= 1)
380                         r++;
381
382                 size = (1 << r);
383
384                 if (size < 256)
385                         size = 256;
386
387                 if (size < cursor_snap.size)
388                         size = cursor_snap.size;
389
390                 if (cursor_snap.size != size) {
391                         if (cursor_snap.overlay_texture) {
392                                 glDeleteTextures(1, &cursor_snap.overlay_texture);
393                                 cursor_snap.overlay_texture = 0;
394                         }
395
396                         init = false;
397
398                         cursor_snap.size = size;
399                 }
400                 buffer = MEM_mallocN(sizeof(GLubyte) * size * size, "load_tex");
401
402                 curvemapping_initialize(br->curve);
403
404 #pragma omp parallel for schedule(static)
405                 for (j = 0; j < size; j++) {
406                         int i;
407                         float y;
408                         float len;
409
410                         for (i = 0; i < size; i++) {
411
412                                 // largely duplicated from tex_strength
413
414                                 int index = j * size + i;
415                                 float x;
416
417                                 x = (float)i / size;
418                                 y = (float)j / size;
419
420                                 x -= 0.5f;
421                                 y -= 0.5f;
422
423                                 x *= 2;
424                                 y *= 2;
425
426                                 len = sqrtf(x * x + y * y);
427
428                                 if (len <= 1) {
429                                         float avg = BKE_brush_curve_strength_clamp(br, len, 1.0f);  /* Falloff curve */
430
431                                         buffer[index] = 255 - (GLubyte)(255 * avg);
432
433                                 }
434                                 else {
435                                         buffer[index] = 0;
436                                 }
437                         }
438                 }
439
440                 if (!cursor_snap.overlay_texture)
441                         glGenTextures(1, &cursor_snap.overlay_texture);
442         }
443         else {
444                 size = cursor_snap.size;
445         }
446
447         glBindTexture(GL_TEXTURE_2D, cursor_snap.overlay_texture);
448
449         if (refresh) {
450                 if (!init) {
451                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
452                 }
453                 else {
454                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
455                 }
456
457                 if (buffer)
458                         MEM_freeN(buffer);
459         }
460
461         glEnable(GL_TEXTURE_2D);
462
463         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
464         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
465         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
466
467         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
468         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
469
470         BKE_paint_reset_overlay_invalid(PAINT_INVALID_OVERLAY_CURVE);
471
472         return 1;
473 }
474
475
476
477 static int project_brush_radius(ViewContext *vc,
478                                 float radius,
479                                 const float location[3])
480 {
481         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
482
483         ED_view3d_global_to_vector(vc->rv3d, location, view);
484
485         /* create a vector that is not orthogonal to view */
486
487         if (fabsf(view[0]) < 0.1f) {
488                 nonortho[0] = view[0] + 1.0f;
489                 nonortho[1] = view[1];
490                 nonortho[2] = view[2];
491         }
492         else if (fabsf(view[1]) < 0.1f) {
493                 nonortho[0] = view[0];
494                 nonortho[1] = view[1] + 1.0f;
495                 nonortho[2] = view[2];
496         }
497         else {
498                 nonortho[0] = view[0];
499                 nonortho[1] = view[1];
500                 nonortho[2] = view[2] + 1.0f;
501         }
502
503         /* get a vector in the plane of the view */
504         cross_v3_v3v3(ortho, nonortho, view);
505         normalize_v3(ortho);
506
507         /* make a point on the surface of the brush tagent to the view */
508         mul_v3_fl(ortho, radius);
509         add_v3_v3v3(offset, location, ortho);
510
511         /* project the center of the brush, and the tangent point to the view onto the screen */
512         if ((ED_view3d_project_float_global(vc->ar, location, p1, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
513             (ED_view3d_project_float_global(vc->ar, offset,   p2, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
514         {
515                 /* the distance between these points is the size of the projected brush in pixels */
516                 return len_v2v2(p1, p2);
517         }
518         else {
519                 BLI_assert(0);  /* assert because the code that sets up the vectors should disallow this */
520                 return 0;
521         }
522 }
523
524 static bool sculpt_get_brush_geometry(
525         bContext *C, ViewContext *vc,
526         int x, int y, int *pixel_radius,
527         float location[3])
528 {
529         Scene *scene = CTX_data_scene(C);
530         Paint *paint = BKE_paint_get_active_from_context(C);
531         float mouse[2];
532         bool hit;
533
534         mouse[0] = x;
535         mouse[1] = y;
536
537         if (vc->obact->sculpt && vc->obact->sculpt->pbvh &&
538             sculpt_stroke_get_location(C, location, mouse))
539         {
540                 Brush *brush = BKE_paint_brush(paint);
541                 *pixel_radius =
542                     project_brush_radius(vc,
543                                          BKE_brush_unprojected_radius_get(scene, brush),
544                                          location);
545
546                 if (*pixel_radius == 0)
547                         *pixel_radius = BKE_brush_size_get(scene, brush);
548
549                 mul_m4_v3(vc->obact->obmat, location);
550
551                 hit = 1;
552         }
553         else {
554                 Sculpt *sd    = CTX_data_tool_settings(C)->sculpt;
555                 Brush *brush = BKE_paint_brush(&sd->paint);
556
557                 *pixel_radius = BKE_brush_size_get(scene, brush);
558                 hit = 0;
559         }
560
561         return hit;
562 }
563
564 /* Draw an overlay that shows what effect the brush's texture will
565  * have on brush strength */
566 static void paint_draw_tex_overlay(UnifiedPaintSettings *ups, Brush *brush,
567                                      ViewContext *vc, int x, int y, float zoom, bool col, bool primary)
568 {
569         rctf quad;
570         /* check for overlay mode */
571
572         MTex *mtex = (primary) ? &brush->mtex : &brush->mask_mtex;
573         bool valid = (primary) ? (brush->overlay_flags & BRUSH_OVERLAY_PRIMARY) != 0 :
574                                  (brush->overlay_flags & BRUSH_OVERLAY_SECONDARY) != 0;
575         int overlay_alpha = (primary) ? brush->texture_overlay_alpha : brush->mask_overlay_alpha;
576
577         if (!(mtex->tex) || !((mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) ||
578             (valid &&
579             ELEM(mtex->brush_map_mode, MTEX_MAP_MODE_VIEW, MTEX_MAP_MODE_TILED))))
580         {
581                 return;
582         }
583
584         if (load_tex(brush, vc, zoom, col, primary)) {
585                 glEnable(GL_BLEND);
586
587                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
588                 glDepthMask(GL_FALSE);
589                 glDepthFunc(GL_ALWAYS);
590
591                 glMatrixMode(GL_TEXTURE);
592                 glPushMatrix();
593                 glLoadIdentity();
594
595                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
596                         /* brush rotation */
597                         glTranslatef(0.5, 0.5, 0);
598                         glRotatef((double)RAD2DEGF((primary) ? ups->brush_rotation : ups->brush_rotation_sec),
599                                   0.0, 0.0, 1.0);
600                         glTranslatef(-0.5f, -0.5f, 0);
601
602                         /* scale based on tablet pressure */
603                         if (primary && ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
604                                 glTranslatef(0.5f, 0.5f, 0);
605                                 glScalef(1.0f / ups->size_pressure_value, 1.0f / ups->size_pressure_value, 1);
606                                 glTranslatef(-0.5f, -0.5f, 0);
607                         }
608
609                         if (ups->draw_anchored) {
610                                 const float *aim = ups->anchored_initial_mouse;
611                                 quad.xmin = aim[0] - ups->anchored_size;
612                                 quad.ymin = aim[1] - ups->anchored_size;
613                                 quad.xmax = aim[0] + ups->anchored_size;
614                                 quad.ymax = aim[1] + ups->anchored_size;
615                         }
616                         else {
617                                 const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
618                                 quad.xmin = x - radius;
619                                 quad.ymin = y - radius;
620                                 quad.xmax = x + radius;
621                                 quad.ymax = y + radius;
622                         }
623                 }
624                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
625                         quad.xmin = 0;
626                         quad.ymin = 0;
627                         quad.xmax = BLI_rcti_size_x(&vc->ar->winrct);
628                         quad.ymax = BLI_rcti_size_y(&vc->ar->winrct);
629                 }
630                 /* Stencil code goes here */
631                 else {
632                         if (primary) {
633                                 quad.xmin = -brush->stencil_dimension[0];
634                                 quad.ymin = -brush->stencil_dimension[1];
635                                 quad.xmax = brush->stencil_dimension[0];
636                                 quad.ymax = brush->stencil_dimension[1];
637                         }
638                         else {
639                                 quad.xmin = -brush->mask_stencil_dimension[0];
640                                 quad.ymin = -brush->mask_stencil_dimension[1];
641                                 quad.xmax = brush->mask_stencil_dimension[0];
642                                 quad.ymax = brush->mask_stencil_dimension[1];
643                         }
644                         glMatrixMode(GL_MODELVIEW);
645                         glPushMatrix();
646                         if (primary)
647                                 glTranslatef(brush->stencil_pos[0], brush->stencil_pos[1], 0);
648                         else
649                                 glTranslatef(brush->mask_stencil_pos[0], brush->mask_stencil_pos[1], 0);
650                         glRotatef(RAD2DEGF(mtex->rot), 0, 0, 1);
651                         glMatrixMode(GL_TEXTURE);
652                 }
653
654                 /* set quad color. Colored overlay does not get blending */
655                 if (col)
656                         glColor4f(1.0,
657                                       1.0,
658                                       1.0,
659                                       overlay_alpha / 100.0f);
660                 else
661                         glColor4f(U.sculpt_paint_overlay_col[0],
662                                       U.sculpt_paint_overlay_col[1],
663                                       U.sculpt_paint_overlay_col[2],
664                                       overlay_alpha / 100.0f);
665
666                 /* draw textured quad */
667                 glBegin(GL_QUADS);
668                 glTexCoord2f(0, 0);
669                 glVertex2f(quad.xmin, quad.ymin);
670                 glTexCoord2f(1, 0);
671                 glVertex2f(quad.xmax, quad.ymin);
672                 glTexCoord2f(1, 1);
673                 glVertex2f(quad.xmax, quad.ymax);
674                 glTexCoord2f(0, 1);
675                 glVertex2f(quad.xmin, quad.ymax);
676                 glEnd();
677
678                 glPopMatrix();
679
680                 if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
681                         glMatrixMode(GL_MODELVIEW);
682                         glPopMatrix();
683                 }
684         }
685 }
686
687 /* Draw an overlay that shows what effect the brush's texture will
688  * have on brush strength */
689 static void paint_draw_cursor_overlay(UnifiedPaintSettings *ups, Brush *brush,
690                                       ViewContext *vc, int x, int y, float zoom)
691 {
692         rctf quad;
693         /* check for overlay mode */
694
695         if (!(brush->overlay_flags & BRUSH_OVERLAY_CURSOR)) {
696                 return;
697         }
698
699         if (load_tex_cursor(brush, vc, zoom)) {
700                 bool do_pop = false;
701                 float center[2];
702                 glEnable(GL_BLEND);
703
704                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
705                 glDepthMask(GL_FALSE);
706                 glDepthFunc(GL_ALWAYS);
707
708                 if (ups->draw_anchored) {
709                         const float *aim = ups->anchored_initial_mouse;
710                         copy_v2_v2(center, aim);
711                         quad.xmin = aim[0] - ups->anchored_size;
712                         quad.ymin = aim[1] - ups->anchored_size;
713                         quad.xmax = aim[0] + ups->anchored_size;
714                         quad.ymax = aim[1] + ups->anchored_size;
715                 }
716                 else {
717                         const int radius = BKE_brush_size_get(vc->scene, brush) * zoom;
718                         center[0] = x;
719                         center[1] = y;
720
721                         quad.xmin = x - radius;
722                         quad.ymin = y - radius;
723                         quad.xmax = x + radius;
724                         quad.ymax = y + radius;
725                 }
726
727                 /* scale based on tablet pressure */
728                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush)) {
729                         do_pop = true;
730                         glPushMatrix();
731                         glLoadIdentity();
732                         glTranslatef(center[0], center[1], 0);
733                         glScalef(ups->size_pressure_value, ups->size_pressure_value, 1);
734                         glTranslatef(-center[0], -center[1], 0);
735                 }
736
737                 glColor4f(U.sculpt_paint_overlay_col[0],
738                         U.sculpt_paint_overlay_col[1],
739                         U.sculpt_paint_overlay_col[2],
740                         brush->cursor_overlay_alpha / 100.0f);
741
742                 /* draw textured quad */
743                 glBegin(GL_QUADS);
744                 glTexCoord2f(0, 0);
745                 glVertex2f(quad.xmin, quad.ymin);
746                 glTexCoord2f(1, 0);
747                 glVertex2f(quad.xmax, quad.ymin);
748                 glTexCoord2f(1, 1);
749                 glVertex2f(quad.xmax, quad.ymax);
750                 glTexCoord2f(0, 1);
751                 glVertex2f(quad.xmin, quad.ymax);
752                 glEnd();
753
754                 if (do_pop)
755                         glPopMatrix();
756         }
757 }
758
759 static void paint_draw_alpha_overlay(UnifiedPaintSettings *ups, Brush *brush,
760                                      ViewContext *vc, int x, int y, float zoom, PaintMode mode)
761 {
762         /* color means that primary brush texture is colured and secondary is used for alpha/mask control */
763         bool col = ELEM(mode, PAINT_TEXTURE_PROJECTIVE, PAINT_TEXTURE_2D, PAINT_VERTEX) ? true : false;
764         OverlayControlFlags flags = BKE_paint_get_overlay_flags();
765         /* save lots of GL state
766          * TODO: check on whether all of these are needed? */
767         glPushAttrib(GL_COLOR_BUFFER_BIT |
768                      GL_CURRENT_BIT |
769                      GL_DEPTH_BUFFER_BIT |
770                      GL_ENABLE_BIT |
771                      GL_LINE_BIT |
772                      GL_POLYGON_BIT |
773                      GL_STENCIL_BUFFER_BIT |
774                      GL_TRANSFORM_BIT |
775                      GL_VIEWPORT_BIT |
776                      GL_TEXTURE_BIT);
777
778
779         /* coloured overlay should be drawn separately */
780         if (col) {
781                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY))
782                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, true, true);
783                 if (!(flags & PAINT_OVERLAY_OVERRIDE_SECONDARY))
784                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, false);
785                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
786                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
787         }
788         else {
789                 if (!(flags & PAINT_OVERLAY_OVERRIDE_PRIMARY))
790                         paint_draw_tex_overlay(ups, brush, vc, x, y, zoom, false, true);
791                 if (!(flags & PAINT_OVERLAY_OVERRIDE_CURSOR))
792                         paint_draw_cursor_overlay(ups, brush, vc, x, y, zoom);
793         }
794
795         glPopAttrib();
796 }
797
798
799 BLI_INLINE void draw_tri_point(float *co, float width, bool selected)
800 {
801         float w = width / 2.0f;
802         if (selected)
803                 UI_ThemeColor4(TH_VERTEX_SELECT);
804         else
805                 UI_ThemeColor4(TH_PAINT_CURVE_PIVOT);
806
807         glLineWidth(3.0);
808
809         glBegin(GL_LINE_LOOP);
810         glVertex2f(co[0], co[1] + w);
811         glVertex2f(co[0] - w, co[1] - w);
812         glVertex2f(co[0] + w, co[1] - w);
813         glEnd();
814
815         glColor4f(1.0, 1.0, 1.0, 0.5);
816         glLineWidth(1.0);
817
818         glBegin(GL_LINE_LOOP);
819         glVertex2f(co[0], co[1] + w);
820         glVertex2f(co[0] - w, co[1] - w);
821         glVertex2f(co[0] + w, co[1] - w);
822         glEnd();
823 }
824
825 BLI_INLINE void draw_rect_point(float *co, float width, bool selected)
826 {
827         float w = width / 2.0f;
828         if (selected)
829                 UI_ThemeColor4(TH_VERTEX_SELECT);
830         else
831                 UI_ThemeColor4(TH_PAINT_CURVE_HANDLE);
832         glLineWidth(3.0);
833
834         glBegin(GL_LINE_LOOP);
835         glVertex2f(co[0] + w, co[1] + w);
836         glVertex2f(co[0] - w, co[1] + w);
837         glVertex2f(co[0] - w, co[1] - w);
838         glVertex2f(co[0] + w, co[1] - w);
839         glEnd();
840
841         glColor4f(1.0, 1.0, 1.0, 0.5);
842         glLineWidth(1.0);
843
844         glBegin(GL_LINE_LOOP);
845         glVertex2f(co[0] + w, co[1] + w);
846         glVertex2f(co[0] - w, co[1] + w);
847         glVertex2f(co[0] - w, co[1] - w);
848         glVertex2f(co[0] + w, co[1] - w);
849         glEnd();
850 }
851
852
853 BLI_INLINE void draw_bezier_handle_lines(BezTriple *bez)
854 {
855         short line1[] = {0, 1};
856         short line2[] = {1, 2};
857
858         glVertexPointer(2, GL_FLOAT, 3 * sizeof(float), bez->vec);
859         glColor4f(0.0, 0.0, 0.0, 0.5);
860         glLineWidth(3.0);
861         glDrawArrays(GL_LINE_STRIP, 0, 3);
862
863         glLineWidth(1.0);
864         if (bez->f1 || bez->f2)
865                 UI_ThemeColor4(TH_VERTEX_SELECT);
866         else
867                 glColor4f(1.0, 1.0, 1.0, 0.5);
868         glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, line1);
869         if (bez->f3 || bez->f2)
870                 UI_ThemeColor4(TH_VERTEX_SELECT);
871         else
872                 glColor4f(1.0, 1.0, 1.0, 0.5);
873         glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, line2);
874 }
875
876 static void paint_draw_curve_cursor(Brush *brush)
877 {
878         if (brush->paint_curve && brush->paint_curve->points) {
879                 int i;
880                 PaintCurve *pc = brush->paint_curve;
881                 PaintCurvePoint *cp = pc->points;
882
883                 glEnable(GL_LINE_SMOOTH);
884                 glEnable(GL_BLEND);
885                 glEnableClientState(GL_VERTEX_ARRAY);
886
887                 /* draw the bezier handles and the curve segment between the current and next point */
888                 for (i = 0; i < pc->tot_points - 1; i++, cp++) {
889                         int j;
890                         PaintCurvePoint *cp_next = cp + 1;
891                         float data[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
892                         /* use color coding to distinguish handles vs curve segments  */
893                         draw_bezier_handle_lines(&cp->bez);
894                         draw_tri_point(&cp->bez.vec[1][0], 10.0, cp->bez.f2);
895                         draw_rect_point(&cp->bez.vec[0][0], 8.0, cp->bez.f1 || cp->bez.f2);
896                         draw_rect_point(&cp->bez.vec[2][0], 8.0, cp->bez.f3 || cp->bez.f2);
897
898                         for (j = 0; j < 2; j++)
899                                 BKE_curve_forward_diff_bezier(
900                                         cp->bez.vec[1][j],
901                                         cp->bez.vec[2][j],
902                                         cp_next->bez.vec[0][j],
903                                         cp_next->bez.vec[1][j],
904                                         data + j, PAINT_CURVE_NUM_SEGMENTS, sizeof(float[2]));
905
906                         glVertexPointer(2, GL_FLOAT, 0, data);
907                         glLineWidth(3.0);
908                         glColor4f(0.0, 0.0, 0.0, 0.5);
909                         glDrawArrays(GL_LINE_STRIP, 0, PAINT_CURVE_NUM_SEGMENTS + 1);
910
911                         glLineWidth(1.0);
912                         glColor4f(0.9, 0.9, 1.0, 0.5);
913                         glDrawArrays(GL_LINE_STRIP, 0, PAINT_CURVE_NUM_SEGMENTS + 1);
914                 }
915
916                 /* draw last line segment */
917                 draw_bezier_handle_lines(&cp->bez);
918                 draw_tri_point(&cp->bez.vec[1][0], 10.0, cp->bez.f2);
919                 draw_rect_point(&cp->bez.vec[0][0], 8.0, cp->bez.f1 || cp->bez.f2);
920                 draw_rect_point(&cp->bez.vec[2][0], 8.0, cp->bez.f3 || cp->bez.f2);
921
922                 glLineWidth(1.0);
923
924                 glDisable(GL_BLEND);
925                 glDisable(GL_LINE_SMOOTH);
926                 glDisableClientState(GL_VERTEX_ARRAY);
927         }
928 }
929
930 /* Special actions taken when paint cursor goes over mesh */
931 /* TODO: sculpt only for now */
932 static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewContext *vc,
933                                 const float location[3])
934 {
935         float unprojected_radius, projected_radius;
936
937         /* update the brush's cached 3D radius */
938         if (!BKE_brush_use_locked_size(vc->scene, brush)) {
939                 /* get 2D brush radius */
940                 if (ups->draw_anchored)
941                         projected_radius = ups->anchored_size;
942                 else {
943                         if (brush->flag & BRUSH_ANCHORED)
944                                 projected_radius = 8;
945                         else
946                                 projected_radius = BKE_brush_size_get(vc->scene, brush);
947                 }
948         
949                 /* convert brush radius from 2D to 3D */
950                 unprojected_radius = paint_calc_object_space_radius(vc, location,
951                                                                     projected_radius);
952
953                 /* scale 3D brush radius by pressure */
954                 if (ups->stroke_active && BKE_brush_use_size_pressure(vc->scene, brush))
955                         unprojected_radius *= ups->size_pressure_value;
956
957                 /* set cached value in either Brush or UnifiedPaintSettings */
958                 BKE_brush_unprojected_radius_set(vc->scene, brush, unprojected_radius);
959         }
960 }
961
962 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
963 {
964         Scene *scene = CTX_data_scene(C);
965         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
966         Paint *paint = BKE_paint_get_active_from_context(C);
967         Brush *brush = BKE_paint_brush(paint);
968         ViewContext vc;
969         PaintMode mode;
970         float final_radius;
971         float translation[2];
972         float outline_alpha, *outline_col;
973         float zoomx, zoomy;
974         
975         /* check that brush drawing is enabled */
976         if (!(paint->flags & PAINT_SHOW_BRUSH))
977                 return;
978
979         /* can't use stroke vc here because this will be called during
980          * mouse over too, not just during a stroke */
981         view3d_set_viewcontext(C, &vc);
982
983         get_imapaint_zoom(C, &zoomx, &zoomy);
984         zoomx = max_ff(zoomx, zoomy);
985         mode = BKE_paintmode_get_active_from_context(C);
986
987         /* skip everything and draw brush here */
988         if (brush->flag & BRUSH_CURVE) {
989                 paint_draw_curve_cursor(brush);
990                 return;
991         }
992
993         /* set various defaults */
994         translation[0] = x;
995         translation[1] = y;
996         outline_alpha = 0.5;
997         outline_col = brush->add_col;
998         final_radius = BKE_brush_size_get(scene, brush) * zoomx;
999
1000         /* don't calculate rake angles while a stroke is active because the rake variables are global and
1001          * we may get interference with the stroke itself. For line strokes, such interference is visible */
1002         if (!ups->stroke_active) {
1003                 paint_calculate_rake_rotation(ups, brush, translation);
1004         }
1005
1006         /* draw overlay */
1007         paint_draw_alpha_overlay(ups, brush, &vc, x, y, zoomx, mode);
1008
1009         /* TODO: as sculpt and other paint modes are unified, this
1010          * special mode of drawing will go away */
1011         if ((mode == PAINT_SCULPT) && vc.obact->sculpt) {
1012                 float location[3];
1013                 int pixel_radius;
1014                 bool hit;
1015
1016                 /* test if brush is over the mesh */
1017                 hit = sculpt_get_brush_geometry(C, &vc, x, y, &pixel_radius, location);
1018
1019                 if (BKE_brush_use_locked_size(scene, brush))
1020                         BKE_brush_size_set(scene, brush, pixel_radius);
1021
1022                 /* check if brush is subtracting, use different color then */
1023                 /* TODO: no way currently to know state of pen flip or
1024                  * invert key modifier without starting a stroke */
1025                 if ((!(ups->draw_inverted) ^
1026                      !(brush->flag & BRUSH_DIR_IN)) &&
1027                     ELEM(brush->sculpt_tool, SCULPT_TOOL_DRAW,
1028                           SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY,
1029                           SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE))
1030                 {
1031                         outline_col = brush->sub_col;
1032                 }
1033
1034                 /* only do if brush is over the mesh */
1035                 if (hit)
1036                         paint_cursor_on_hit(ups, brush, &vc, location);
1037         }
1038
1039         if (ups->draw_anchored) {
1040                 final_radius = ups->anchored_size;
1041                 translation[0] = ups->anchored_initial_mouse[0];
1042                 translation[1] = ups->anchored_initial_mouse[1];
1043         }
1044
1045         /* make lines pretty */
1046         glEnable(GL_BLEND);
1047         glEnable(GL_LINE_SMOOTH);
1048
1049         /* set brush color */
1050         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
1051
1052         /* draw brush outline */
1053         glTranslatef(translation[0], translation[1], 0);
1054
1055         /* draw an inner brush */
1056         if (ups->stroke_active && BKE_brush_use_size_pressure(scene, brush)) {
1057                 /* inner at full alpha */
1058                 glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius * ups->size_pressure_value, 40);
1059                 /* outer at half alpha */
1060                 glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha * 0.5f);
1061         }
1062         glutil_draw_lined_arc(0.0, M_PI * 2.0, final_radius, 40);
1063         glTranslatef(-translation[0], -translation[1], 0);
1064
1065         /* restore GL state */
1066         glDisable(GL_BLEND);
1067         glDisable(GL_LINE_SMOOTH);
1068 }
1069
1070 /* Public API */
1071
1072 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
1073 {
1074         Paint *p = BKE_paint_get_active_from_context(C);
1075
1076         if (p && !p->paint_cursor)
1077                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
1078
1079         /* invalidate the paint cursors */
1080         BKE_paint_invalidate_overlay_all();
1081 }
1082
1083 void paint_cursor_start_explicit(Paint *p, wmWindowManager *wm, int (*poll)(bContext *C))
1084 {
1085         if (p && !p->paint_cursor)
1086                 p->paint_cursor = WM_paint_cursor_activate(wm, poll, paint_draw_cursor, NULL);
1087 }