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