Depsgraph: remove EvaluationContext, pass Depsgraph instead.
[blender.git] / source / blender / blenkernel / intern / paint.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  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/paint.c
29  *  \ingroup bke
30  */
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_object_types.h"
38 #include "DNA_mesh_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_brush_types.h"
43 #include "DNA_space_types.h"
44 #include "DNA_workspace_types.h"
45
46 #include "BLI_bitmap.h"
47 #include "BLI_utildefines.h"
48 #include "BLI_math_vector.h"
49 #include "BLI_listbase.h"
50
51 #include "BKE_brush.h"
52 #include "BKE_colortools.h"
53 #include "BKE_deform.h"
54 #include "BKE_main.h"
55 #include "BKE_context.h"
56 #include "BKE_crazyspace.h"
57 #include "BKE_global.h"
58 #include "BKE_image.h"
59 #include "BKE_key.h"
60 #include "BKE_library.h"
61 #include "BKE_mesh.h"
62 #include "BKE_modifier.h"
63 #include "BKE_object.h"
64 #include "BKE_paint.h"
65 #include "BKE_pbvh.h"
66 #include "BKE_subsurf.h"
67
68 #include "DEG_depsgraph.h"
69
70 #include "bmesh.h"
71
72 const char PAINT_CURSOR_SCULPT[3] = {255, 100, 100};
73 const char PAINT_CURSOR_VERTEX_PAINT[3] = {255, 255, 255};
74 const char PAINT_CURSOR_WEIGHT_PAINT[3] = {200, 200, 255};
75 const char PAINT_CURSOR_TEXTURE_PAINT[3] = {255, 255, 255};
76
77 static eOverlayControlFlags overlay_flags = 0;
78
79 void BKE_paint_invalidate_overlay_tex(Scene *scene, ViewLayer *view_layer, const Tex *tex)
80 {
81         Paint *p = BKE_paint_get_active(scene, view_layer);
82         Brush *br = p->brush;
83
84         if (!br)
85                 return;
86
87         if (br->mtex.tex == tex)
88                 overlay_flags |= PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY;
89         if (br->mask_mtex.tex == tex)
90                 overlay_flags |= PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY;
91 }
92
93 void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, CurveMapping *curve)
94 {
95         Paint *p = BKE_paint_get_active(scene, view_layer);
96         Brush *br = p->brush;
97
98         if (br && br->curve == curve)
99                 overlay_flags |= PAINT_INVALID_OVERLAY_CURVE;
100 }
101
102 void BKE_paint_invalidate_overlay_all(void)
103 {
104         overlay_flags |= (PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY |
105                           PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY |
106                           PAINT_INVALID_OVERLAY_CURVE);
107 }
108
109 eOverlayControlFlags BKE_paint_get_overlay_flags(void)
110 {
111         return overlay_flags;
112 }
113
114 void BKE_paint_set_overlay_override(eOverlayFlags flags)
115 {
116         if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) {
117                 if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE)
118                         overlay_flags |= PAINT_OVERLAY_OVERRIDE_CURSOR;
119                 if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE)
120                         overlay_flags |= PAINT_OVERLAY_OVERRIDE_PRIMARY;
121                 if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE)
122                         overlay_flags |= PAINT_OVERLAY_OVERRIDE_SECONDARY;
123         }
124         else {
125                 overlay_flags &= ~(PAINT_OVERRIDE_MASK);
126         }
127 }
128
129 void BKE_paint_reset_overlay_invalid(eOverlayControlFlags flag)
130 {
131         overlay_flags &= ~(flag);
132 }
133
134 Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode)
135 {
136         if (sce) {
137                 ToolSettings *ts = sce->toolsettings;
138
139                 switch (mode) {
140                         case ePaintSculpt:
141                                 return &ts->sculpt->paint;
142                         case ePaintVertex:
143                                 return &ts->vpaint->paint;
144                         case ePaintWeight:
145                                 return &ts->wpaint->paint;
146                         case ePaintTexture2D:
147                         case ePaintTextureProjective:
148                                 return &ts->imapaint.paint;
149                         case ePaintSculptUV:
150                                 return &ts->uvsculpt->paint;
151                         case ePaintInvalid:
152                                 return NULL;
153                         default:
154                                 return &ts->imapaint.paint;
155                 }
156         }
157
158         return NULL;
159 }
160
161 Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer)
162 {
163         if (sce && view_layer) {
164                 ToolSettings *ts = sce->toolsettings;
165                 
166                 if (view_layer->basact && view_layer->basact->object) {
167                         switch (view_layer->basact->object->mode) {
168                                 case OB_MODE_SCULPT:
169                                         return &ts->sculpt->paint;
170                                 case OB_MODE_VERTEX_PAINT:
171                                         return &ts->vpaint->paint;
172                                 case OB_MODE_WEIGHT_PAINT:
173                                         return &ts->wpaint->paint;
174                                 case OB_MODE_TEXTURE_PAINT:
175                                         return &ts->imapaint.paint;
176                                 case OB_MODE_EDIT:
177                                         if (ts->use_uv_sculpt)
178                                                 return &ts->uvsculpt->paint;
179                                         return &ts->imapaint.paint;
180                                 default:
181                                         break;
182                         }
183                 }
184
185                 /* default to image paint */
186                 return &ts->imapaint.paint;
187         }
188
189         return NULL;
190 }
191
192 Paint *BKE_paint_get_active_from_context(const bContext *C)
193 {
194         Scene *sce = CTX_data_scene(C);
195         ViewLayer *view_layer = CTX_data_view_layer(C);
196         SpaceImage *sima;
197
198         if (sce && view_layer) {
199                 ToolSettings *ts = sce->toolsettings;
200                 Object *obact = NULL;
201
202                 if (view_layer->basact && view_layer->basact->object)
203                         obact = view_layer->basact->object;
204
205                 if ((sima = CTX_wm_space_image(C)) != NULL) {
206                         if (obact && obact->mode == OB_MODE_EDIT) {
207                                 if (sima->mode == SI_MODE_PAINT)
208                                         return &ts->imapaint.paint;
209                                 else if (ts->use_uv_sculpt)
210                                         return &ts->uvsculpt->paint;
211                         }
212                         else {
213                                 return &ts->imapaint.paint;
214                         }
215                 }
216                 else if (obact) {
217                         switch (obact->mode) {
218                                 case OB_MODE_SCULPT:
219                                         return &ts->sculpt->paint;
220                                 case OB_MODE_VERTEX_PAINT:
221                                         return &ts->vpaint->paint;
222                                 case OB_MODE_WEIGHT_PAINT:
223                                         return &ts->wpaint->paint;
224                                 case OB_MODE_TEXTURE_PAINT:
225                                         return &ts->imapaint.paint;
226                                 case OB_MODE_EDIT:
227                                         if (ts->use_uv_sculpt)
228                                                 return &ts->uvsculpt->paint;
229                                         return &ts->imapaint.paint;
230                                 default:
231                                         return &ts->imapaint.paint;
232                         }
233                 }
234                 else {
235                         /* default to image paint */
236                         return &ts->imapaint.paint;
237                 }
238         }
239
240         return NULL;
241 }
242
243 ePaintMode BKE_paintmode_get_active_from_context(const bContext *C)
244 {
245         Scene *sce = CTX_data_scene(C);
246         ViewLayer *view_layer = CTX_data_view_layer(C);
247         SpaceImage *sima;
248
249         if (sce && view_layer) {
250                 ToolSettings *ts = sce->toolsettings;
251                 Object *obact = NULL;
252
253                 if (view_layer->basact && view_layer->basact->object)
254                         obact = view_layer->basact->object;
255
256                 if ((sima = CTX_wm_space_image(C)) != NULL) {
257                         if (obact && obact->mode == OB_MODE_EDIT) {
258                                 if (sima->mode == SI_MODE_PAINT)
259                                         return ePaintTexture2D;
260                                 else if (ts->use_uv_sculpt)
261                                         return ePaintSculptUV;
262                         }
263                         else {
264                                 return ePaintTexture2D;
265                         }
266                 }
267                 else if (obact) {
268                         switch (obact->mode) {
269                                 case OB_MODE_SCULPT:
270                                         return ePaintSculpt;
271                                 case OB_MODE_VERTEX_PAINT:
272                                         return ePaintVertex;
273                                 case OB_MODE_WEIGHT_PAINT:
274                                         return ePaintWeight;
275                                 case OB_MODE_TEXTURE_PAINT:
276                                         return ePaintTextureProjective;
277                                 case OB_MODE_EDIT:
278                                         if (ts->use_uv_sculpt)
279                                                 return ePaintSculptUV;
280                                         return ePaintTexture2D;
281                                 default:
282                                         return ePaintTexture2D;
283                         }
284                 }
285                 else {
286                         /* default to image paint */
287                         return ePaintTexture2D;
288                 }
289         }
290
291         return ePaintInvalid;
292 }
293
294 Brush *BKE_paint_brush(Paint *p)
295 {
296         return p ? p->brush : NULL;
297 }
298
299 void BKE_paint_brush_set(Paint *p, Brush *br)
300 {
301         if (p) {
302                 id_us_min((ID *)p->brush);
303                 id_us_plus((ID *)br);
304                 p->brush = br;
305         }
306 }
307
308 /** Free (or release) any data used by this paint curve (does not free the pcurve itself). */
309 void BKE_paint_curve_free(PaintCurve *pc)
310 {
311         MEM_SAFE_FREE(pc->points);
312         pc->tot_points = 0;
313 }
314
315 PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name)
316 {
317         PaintCurve *pc;
318
319         pc = BKE_libblock_alloc(bmain, ID_PC, name, 0);
320
321         return pc;
322 }
323
324 /**
325  * Only copy internal data of PaintCurve ID from source to already allocated/initialized destination.
326  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
327  *
328  * WARNING! This function will not handle ID user count!
329  *
330  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
331  */
332 void BKE_paint_curve_copy_data(Main *UNUSED(bmain), PaintCurve *pc_dst, const PaintCurve *pc_src, const int UNUSED(flag))
333 {
334         if (pc_src->tot_points != 0) {
335                 pc_dst->points = MEM_dupallocN(pc_src->points);
336         }
337 }
338
339 PaintCurve *BKE_paint_curve_copy(Main *bmain, const PaintCurve *pc)
340 {
341         PaintCurve *pc_copy;
342         BKE_id_copy_ex(bmain, &pc->id, (ID **)&pc_copy, 0, false);
343         return pc_copy;
344 }
345
346 void BKE_paint_curve_make_local(Main *bmain, PaintCurve *pc, const bool lib_local)
347 {
348         BKE_id_make_local_generic(bmain, &pc->id, true, lib_local);
349 }
350
351 Palette *BKE_paint_palette(Paint *p)
352 {
353         return p ? p->palette : NULL;
354 }
355
356 void BKE_paint_palette_set(Paint *p, Palette *palette)
357 {
358         if (p) {
359                 id_us_min((ID *)p->palette);
360                 id_us_plus((ID *)palette);
361                 p->palette = palette;
362         }
363 }
364
365 void BKE_paint_curve_set(Brush *br, PaintCurve *pc)
366 {
367         if (br) {
368                 id_us_min((ID *)br->paint_curve);
369                 id_us_plus((ID *)pc);
370                 br->paint_curve = pc;
371         }
372 }
373
374 void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_index)
375 {
376         pc->add_index = (add_index || pc->tot_points == 1) ? (add_index + 1) : 0;
377 }
378
379 /* remove colour from palette. Must be certain color is inside the palette! */
380 void BKE_palette_color_remove(Palette *palette, PaletteColor *color)
381 {
382         if (BLI_listbase_count_at_most(&palette->colors, palette->active_color) == palette->active_color) {
383                 palette->active_color--;
384         }
385
386         BLI_remlink(&palette->colors, color);
387
388         if (palette->active_color < 0 && !BLI_listbase_is_empty(&palette->colors)) {
389                 palette->active_color = 0;
390         }
391
392         MEM_freeN(color);
393 }
394
395 void BKE_palette_clear(Palette *palette)
396 {
397         BLI_freelistN(&palette->colors);
398         palette->active_color = 0;
399 }
400
401 Palette *BKE_palette_add(Main *bmain, const char *name)
402 {
403         Palette *palette;
404
405         palette = BKE_libblock_alloc(bmain, ID_PAL, name, 0);
406
407         /* enable fake user by default */
408         id_fake_user_set(&palette->id);
409
410         return palette;
411 }
412
413 /**
414  * Only copy internal data of Palette ID from source to already allocated/initialized destination.
415  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
416  *
417  * WARNING! This function will not handle ID user count!
418  *
419  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
420  */
421 void BKE_palette_copy_data(Main *UNUSED(bmain), Palette *palette_dst, const Palette *palette_src, const int UNUSED(flag))
422 {
423         BLI_duplicatelist(&palette_dst->colors, &palette_src->colors);
424 }
425
426 Palette *BKE_palette_copy(Main *bmain, const Palette *palette)
427 {
428         Palette *palette_copy;
429         BKE_id_copy_ex(bmain, &palette->id, (ID **)&palette_copy, 0, false);
430         return palette_copy;
431 }
432
433 void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local)
434 {
435         BKE_id_make_local_generic(bmain, &palette->id, true, lib_local);
436 }
437
438 /** Free (or release) any data used by this palette (does not free the palette itself). */
439 void BKE_palette_free(Palette *palette)
440 {
441         BLI_freelistN(&palette->colors);
442 }
443
444 PaletteColor *BKE_palette_color_add(Palette *palette)
445 {
446         PaletteColor *color = MEM_callocN(sizeof(*color), "Pallete Color");
447         BLI_addtail(&palette->colors, color);
448         return color;
449 }
450
451
452 bool BKE_palette_is_empty(const struct Palette *palette)
453 {
454         return BLI_listbase_is_empty(&palette->colors);
455 }
456
457
458 /* are we in vertex paint or weight pain face select mode? */
459 bool BKE_paint_select_face_test(Object *ob)
460 {
461         return ( (ob != NULL) &&
462                  (ob->type == OB_MESH) &&
463                  (ob->data != NULL) &&
464                  (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_FACE_SEL) &&
465                  (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))
466                  );
467 }
468
469 /* are we in weight paint vertex select mode? */
470 bool BKE_paint_select_vert_test(Object *ob)
471 {
472         return ( (ob != NULL) &&
473                  (ob->type == OB_MESH) &&
474                  (ob->data != NULL) &&
475                  (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) &&
476                  (ob->mode & OB_MODE_WEIGHT_PAINT || ob->mode & OB_MODE_VERTEX_PAINT)
477                  );
478 }
479
480 /**
481  * used to check if selection is possible
482  * (when we don't care if its face or vert)
483  */
484 bool BKE_paint_select_elem_test(Object *ob)
485 {
486         return (BKE_paint_select_vert_test(ob) ||
487                 BKE_paint_select_face_test(ob));
488 }
489
490 void BKE_paint_cavity_curve_preset(Paint *p, int preset)
491 {
492         CurveMap *cm = NULL;
493
494         if (!p->cavity_curve)
495                 p->cavity_curve = curvemapping_add(1, 0, 0, 1, 1);
496
497         cm = p->cavity_curve->cm;
498         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
499
500         p->cavity_curve->preset = preset;
501         curvemap_reset(cm, &p->cavity_curve->clipr, p->cavity_curve->preset, CURVEMAP_SLOPE_POSITIVE);
502         curvemapping_changed(p->cavity_curve, false);
503 }
504
505 eObjectMode BKE_paint_object_mode_from_paint_mode(ePaintMode mode)
506 {
507         switch (mode) {
508                 case ePaintSculpt:
509                         return OB_MODE_SCULPT;
510                 case ePaintVertex:
511                         return OB_MODE_VERTEX_PAINT;
512                 case ePaintWeight:
513                         return OB_MODE_WEIGHT_PAINT;
514                 case ePaintTextureProjective:
515                         return OB_MODE_TEXTURE_PAINT;
516                 case ePaintTexture2D:
517                         return OB_MODE_TEXTURE_PAINT;
518                 case ePaintSculptUV:
519                         return OB_MODE_EDIT;
520                 case ePaintInvalid:
521                 default:
522                         return 0;
523         }
524 }
525
526 void BKE_paint_init(Scene *sce, ePaintMode mode, const char col[3])
527 {
528         UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings;
529         Brush *brush;
530         Paint *paint = BKE_paint_get_active_from_paintmode(sce, mode);
531
532         /* If there's no brush, create one */
533         brush = BKE_paint_brush(paint);
534         if (brush == NULL) {
535                 eObjectMode ob_mode = BKE_paint_object_mode_from_paint_mode(mode);
536                 brush = BKE_brush_first_search(G.main, ob_mode);
537
538                 if (!brush) {
539                         brush = BKE_brush_add(G.main, "Brush", ob_mode);
540                         id_us_min(&brush->id);  /* fake user only */
541                 }
542                 BKE_paint_brush_set(paint, brush);
543         }
544
545         memcpy(paint->paint_cursor_col, col, 3);
546         paint->paint_cursor_col[3] = 128;
547         ups->last_stroke_valid = false;
548         zero_v3(ups->average_stroke_accum);
549         ups->average_stroke_counter = 0;
550         if (!paint->cavity_curve)
551                 BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE);
552 }
553
554 void BKE_paint_free(Paint *paint)
555 {
556         curvemapping_free(paint->cavity_curve);
557 }
558
559 /* called when copying scene settings, so even if 'src' and 'tar' are the same
560  * still do a id_us_plus(), rather then if we were copying between 2 existing
561  * scenes where a matching value should decrease the existing user count as
562  * with paint_brush_set() */
563 void BKE_paint_copy(Paint *src, Paint *tar, const int flag)
564 {
565         tar->brush = src->brush;
566         tar->cavity_curve = curvemapping_copy(src->cavity_curve);
567
568         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
569                 id_us_plus((ID *)tar->brush);
570                 id_us_plus((ID *)tar->palette);
571         }
572 }
573
574 void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3])
575 {
576         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
577         if (ups->last_stroke_valid && ups->average_stroke_counter > 0) {
578                 float fac = 1.0f / ups->average_stroke_counter;
579                 mul_v3_v3fl(stroke, ups->average_stroke_accum, fac);
580         }
581         else {
582                 copy_v3_v3(stroke, ob->obmat[3]);
583         }
584 }
585
586 /* returns non-zero if any of the face's vertices
587  * are hidden, zero otherwise */
588 bool paint_is_face_hidden(const MLoopTri *lt, const MVert *mvert, const MLoop *mloop)
589 {
590         return ((mvert[mloop[lt->tri[0]].v].flag & ME_HIDE) ||
591                 (mvert[mloop[lt->tri[1]].v].flag & ME_HIDE) ||
592                 (mvert[mloop[lt->tri[2]].v].flag & ME_HIDE));
593 }
594
595 /* returns non-zero if any of the corners of the grid
596  * face whose inner corner is at (x, y) are hidden,
597  * zero otherwise */
598 bool paint_is_grid_face_hidden(const unsigned int *grid_hidden,
599                               int gridsize, int x, int y)
600 {
601         /* skip face if any of its corners are hidden */
602         return (BLI_BITMAP_TEST(grid_hidden, y * gridsize + x) ||
603                 BLI_BITMAP_TEST(grid_hidden, y * gridsize + x + 1) ||
604                 BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x + 1) ||
605                 BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x));
606 }
607
608 /* Return true if all vertices in the face are visible, false otherwise */
609 bool paint_is_bmesh_face_hidden(BMFace *f)
610 {
611         BMLoop *l_iter;
612         BMLoop *l_first;
613
614         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
615         do {
616                 if (BM_elem_flag_test(l_iter->v, BM_ELEM_HIDDEN)) {
617                         return true;
618                 }
619         } while ((l_iter = l_iter->next) != l_first);
620
621         return false;
622 }
623
624 float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level,
625                             unsigned x, unsigned y)
626 {
627         int factor = BKE_ccg_factor(level, gpm->level);
628         int gridsize = BKE_ccg_gridsize(gpm->level);
629         
630         return gpm->data[(y * factor) * gridsize + (x * factor)];
631 }
632
633 /* threshold to move before updating the brush rotation */
634 #define RAKE_THRESHHOLD 20
635
636 void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation)
637 {
638         if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE)
639                 ups->brush_rotation = rotation;
640         else
641                 ups->brush_rotation = 0.0f;
642
643         if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)
644                 ups->brush_rotation_sec = rotation;
645         else
646                 ups->brush_rotation_sec = 0.0f;
647 }
648
649 bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, const float mouse_pos[2])
650 {
651         bool ok = false;
652         if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) || (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
653                 const float r = RAKE_THRESHHOLD;
654                 float rotation;
655
656                 float dpos[2];
657                 sub_v2_v2v2(dpos, ups->last_rake, mouse_pos);
658
659                 if (len_squared_v2(dpos) >= r * r) {
660                         rotation = atan2f(dpos[0], dpos[1]);
661
662                         copy_v2_v2(ups->last_rake, mouse_pos);
663
664                         ups->last_rake_angle = rotation;
665
666                         paint_update_brush_rake_rotation(ups, brush, rotation);
667                         ok = true;
668                 }
669                 /* make sure we reset here to the last rotation to avoid accumulating
670                  * values in case a random rotation is also added */
671                 else {
672                         paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle);
673                         ok = false;
674                 }
675         }
676         else {
677                 ups->brush_rotation = ups->brush_rotation_sec = 0.0f;
678                 ok = true;
679         }
680         return ok;
681 }
682
683 void BKE_sculptsession_free_deformMats(SculptSession *ss)
684 {
685         MEM_SAFE_FREE(ss->orig_cos);
686         MEM_SAFE_FREE(ss->deform_cos);
687         MEM_SAFE_FREE(ss->deform_imats);
688 }
689
690 void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss)
691 {
692         struct SculptVertexPaintGeomMap *gmap = NULL;
693         if (ss->mode_type == OB_MODE_VERTEX_PAINT) {
694                 gmap = &ss->mode.vpaint.gmap;
695
696                 MEM_SAFE_FREE(ss->mode.vpaint.previous_color);
697         }
698         else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) {
699                 gmap = &ss->mode.wpaint.gmap;
700
701                 MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight);
702                 if (ss->mode.wpaint.dvert_prev) {
703                         BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert);
704                         MEM_freeN(ss->mode.wpaint.dvert_prev);
705                         ss->mode.wpaint.dvert_prev = NULL;
706                 }
707         }
708         else {
709                 return;
710         }
711         MEM_SAFE_FREE(gmap->vert_to_loop);
712         MEM_SAFE_FREE(gmap->vert_map_mem);
713         MEM_SAFE_FREE(gmap->vert_to_poly);
714         MEM_SAFE_FREE(gmap->poly_map_mem);
715 }
716
717 /* Write out the sculpt dynamic-topology BMesh to the Mesh */
718 static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder)
719 {
720         SculptSession *ss = ob->sculpt;
721
722         if (ss->bm) {
723                 if (ob->data) {
724                         BMIter iter;
725                         BMFace *efa;
726                         BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
727                                 BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading);
728                         }
729                         if (reorder)
730                                 BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
731                         BM_mesh_bm_to_me(ss->bm, ob->data, (&(struct BMeshToMeshParams){0}));
732                 }
733         }
734 }
735
736 void BKE_sculptsession_bm_to_me(Object *ob, bool reorder)
737 {
738         if (ob && ob->sculpt) {
739                 sculptsession_bm_to_me_update_data_only(ob, reorder);
740
741                 /* ensure the objects DerivedMesh mesh doesn't hold onto arrays now realloc'd in the mesh [#34473] */
742                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
743         }
744 }
745
746 void BKE_sculptsession_bm_to_me_for_render(Object *object)
747 {
748         if (object && object->sculpt) {
749                 if (object->sculpt->bm) {
750                         /* Ensure no points to old arrays are stored in DM
751                          *
752                          * Apparently, we could not use DEG_id_tag_update
753                          * here because this will lead to the while object
754                          * surface to disappear, so we'll release DM in place.
755                          */
756                         BKE_object_free_derived_caches(object);
757
758                         if (object->sculpt->pbvh) {
759                                 BKE_pbvh_free(object->sculpt->pbvh);
760                                 object->sculpt->pbvh = NULL;
761                         }
762
763                         sculptsession_bm_to_me_update_data_only(object, false);
764
765                         /* In contrast with sculptsession_bm_to_me no need in
766                          * DAG tag update here - derived mesh was freed and
767                          * old pointers are nowhere stored.
768                          */
769                 }
770         }
771 }
772
773 void BKE_sculptsession_free(Object *ob)
774 {
775         if (ob && ob->sculpt) {
776                 SculptSession *ss = ob->sculpt;
777                 DerivedMesh *dm = ob->derivedFinal;
778
779                 if (ss->bm) {
780                         BKE_sculptsession_bm_to_me(ob, true);
781                         BM_mesh_free(ss->bm);
782                 }
783
784                 if (ss->pbvh)
785                         BKE_pbvh_free(ss->pbvh);
786                 if (ss->bm_log)
787                         BM_log_free(ss->bm_log);
788
789                 if (dm && dm->getPBVH)
790                         dm->getPBVH(NULL, dm);  /* signal to clear */
791
792                 if (ss->texcache)
793                         MEM_freeN(ss->texcache);
794
795                 if (ss->tex_pool)
796                         BKE_image_pool_free(ss->tex_pool);
797
798                 if (ss->layer_co)
799                         MEM_freeN(ss->layer_co);
800
801                 if (ss->orig_cos)
802                         MEM_freeN(ss->orig_cos);
803                 if (ss->deform_cos)
804                         MEM_freeN(ss->deform_cos);
805                 if (ss->deform_imats)
806                         MEM_freeN(ss->deform_imats);
807
808                 BKE_sculptsession_free_vwpaint_data(ob->sculpt);
809
810                 MEM_freeN(ss);
811
812                 ob->sculpt = NULL;
813         }
814 }
815
816 /* Sculpt mode handles multires differently from regular meshes, but only if
817  * it's the last modifier on the stack and it is not on the first level */
818 MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob)
819 {
820         Mesh *me = (Mesh *)ob->data;
821         ModifierData *md;
822         VirtualModifierData virtualModifierData;
823
824         if (ob->sculpt && ob->sculpt->bm) {
825                 /* can't combine multires and dynamic topology */
826                 return NULL;
827         }
828
829         if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) {
830                 /* multires can't work without displacement layer */
831                 return NULL;
832         }
833
834         for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) {
835                 if (md->type == eModifierType_Multires) {
836                         MultiresModifierData *mmd = (MultiresModifierData *)md;
837
838                         if (!modifier_isEnabled(scene, md, eModifierMode_Realtime))
839                                 continue;
840
841                         if (mmd->sculptlvl > 0) return mmd;
842                         else return NULL;
843                 }
844         }
845
846         return NULL;
847 }
848
849
850 /* Checks if there are any supported deformation modifiers active */
851 static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob)
852 {
853         ModifierData *md;
854         Mesh *me = (Mesh *)ob->data;
855         MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
856         VirtualModifierData virtualModifierData;
857
858         if (mmd || ob->sculpt->bm)
859                 return false;
860
861         /* non-locked shape keys could be handled in the same way as deformed mesh */
862         if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr)
863                 return true;
864
865         md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
866
867         /* exception for shape keys because we can edit those */
868         for (; md; md = md->next) {
869                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
870                 if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) continue;
871                 if (ELEM(md->type, eModifierType_ShapeKey, eModifierType_Multires)) continue;
872
873                 if (mti->type == eModifierTypeType_OnlyDeform) return true;
874                 else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) return true;
875         }
876
877         return false;
878 }
879
880 /**
881  * \param need_mask So the DerivedMesh thats returned has mask data
882  */
883 void BKE_sculpt_update_mesh_elements(
884         Depsgraph *depsgraph, Scene *scene, Sculpt *sd, Object *ob,
885         bool need_pmap, bool need_mask)
886 {
887         DerivedMesh *dm;
888         SculptSession *ss = ob->sculpt;
889         Mesh *me = ob->data;
890         MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
891
892         ss->modifiers_active = sculpt_modifiers_active(scene, sd, ob);
893         ss->show_diffuse_color = (sd->flags & SCULPT_SHOW_DIFFUSE) != 0;
894         ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0;
895
896         ss->building_vp_handle = false;
897
898         if (need_mask) {
899                 if (mmd == NULL) {
900                         if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) {
901                                 BKE_sculpt_mask_layers_ensure(ob, NULL);
902                         }
903                 }
904                 else {
905                         if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
906 #if 1
907                                 BKE_sculpt_mask_layers_ensure(ob, mmd);
908 #else                   /* if we wanted to support adding mask data while multi-res painting, we would need to do this */
909                                 if ((ED_sculpt_mask_layers_ensure(ob, mmd) & ED_SCULPT_MASK_LAYER_CALC_LOOP)) {
910                                         /* remake the derived mesh */
911                                         ob->recalc |= OB_RECALC_DATA;
912                                         BKE_object_handle_update(scene, ob);
913                                 }
914 #endif
915                         }
916                 }
917         }
918
919         /* tessfaces aren't used and will become invalid */
920         BKE_mesh_tessface_clear(me);
921
922         ss->kb = (mmd == NULL) ? BKE_keyblock_from_object(ob) : NULL;
923
924         dm = mesh_get_derived_final(depsgraph, scene, ob, CD_MASK_BAREMESH);
925
926         /* VWPaint require mesh info for loop lookup, so require sculpt mode here */
927         if (mmd && ob->mode & OB_MODE_SCULPT) {
928                 ss->multires = mmd;
929                 ss->totvert = dm->getNumVerts(dm);
930                 ss->totpoly = dm->getNumPolys(dm);
931                 ss->mvert = NULL;
932                 ss->mpoly = NULL;
933                 ss->mloop = NULL;
934         }
935         else {
936                 ss->totvert = me->totvert;
937                 ss->totpoly = me->totpoly;
938                 ss->mvert = me->mvert;
939                 ss->mpoly = me->mpoly;
940                 ss->mloop = me->mloop;
941                 ss->multires = NULL;
942                 ss->vmask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
943         }
944
945         ss->pbvh = dm->getPBVH(ob, dm);
946         ss->pmap = (need_pmap && dm->getPolyMap) ? dm->getPolyMap(ob, dm) : NULL;
947
948         pbvh_show_diffuse_color_set(ss->pbvh, ss->show_diffuse_color);
949         pbvh_show_mask_set(ss->pbvh, ss->show_mask);
950
951         if (ss->modifiers_active) {
952                 if (!ss->orig_cos) {
953                         int a;
954
955                         BKE_sculptsession_free_deformMats(ss);
956
957                         ss->orig_cos = (ss->kb) ? BKE_keyblock_convert_to_vertcos(ob, ss->kb) : BKE_mesh_vertexCos_get(me, NULL);
958
959                         BKE_crazyspace_build_sculpt(depsgraph, scene, ob, &ss->deform_imats, &ss->deform_cos);
960                         BKE_pbvh_apply_vertCos(ss->pbvh, ss->deform_cos);
961
962                         for (a = 0; a < me->totvert; ++a) {
963                                 invert_m3(ss->deform_imats[a]);
964                         }
965                 }
966         }
967         else {
968                 BKE_sculptsession_free_deformMats(ss);
969         }
970
971         if (ss->kb != NULL && ss->deform_cos == NULL) {
972                 ss->deform_cos = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
973         }
974
975         /* if pbvh is deformed, key block is already applied to it */
976         if (ss->kb) {
977                 bool pbvh_deformd = BKE_pbvh_isDeformed(ss->pbvh);
978                 if (!pbvh_deformd || ss->deform_cos == NULL) {
979                         float (*vertCos)[3] = BKE_keyblock_convert_to_vertcos(ob, ss->kb);
980
981                         if (vertCos) {
982                                 if (!pbvh_deformd) {
983                                         /* apply shape keys coordinates to PBVH */
984                                         BKE_pbvh_apply_vertCos(ss->pbvh, vertCos);
985                                 }
986                                 if (ss->deform_cos == NULL) {
987                                         ss->deform_cos = vertCos;
988                                 }
989                                 if (vertCos != ss->deform_cos) {
990                                         MEM_freeN(vertCos);
991                                 }
992                         }
993                 }
994         }
995
996         /* 2.8x - avoid full mesh update! */
997         BKE_mesh_batch_cache_dirty(me, BKE_MESH_BATCH_DIRTY_SCULPT_COORDS);
998 }
999
1000 int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
1001 {
1002         const float *paint_mask;
1003         Mesh *me = ob->data;
1004         int ret = 0;
1005
1006         paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
1007
1008         /* if multires is active, create a grid paint mask layer if there
1009          * isn't one already */
1010         if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
1011                 GridPaintMask *gmask;
1012                 int level = max_ii(1, mmd->sculptlvl);
1013                 int gridsize = BKE_ccg_gridsize(level);
1014                 int gridarea = gridsize * gridsize;
1015                 int i, j;
1016
1017                 gmask = CustomData_add_layer(&me->ldata, CD_GRID_PAINT_MASK,
1018                                              CD_CALLOC, NULL, me->totloop);
1019
1020                 for (i = 0; i < me->totloop; i++) {
1021                         GridPaintMask *gpm = &gmask[i];
1022
1023                         gpm->level = level;
1024                         gpm->data = MEM_callocN(sizeof(float) * gridarea,
1025                                                 "GridPaintMask.data");
1026                 }
1027
1028                 /* if vertices already have mask, copy into multires data */
1029                 if (paint_mask) {
1030                         for (i = 0; i < me->totpoly; i++) {
1031                                 const MPoly *p = &me->mpoly[i];
1032                                 float avg = 0;
1033
1034                                 /* mask center */
1035                                 for (j = 0; j < p->totloop; j++) {
1036                                         const MLoop *l = &me->mloop[p->loopstart + j];
1037                                         avg += paint_mask[l->v];
1038                                 }
1039                                 avg /= (float)p->totloop;
1040
1041                                 /* fill in multires mask corner */
1042                                 for (j = 0; j < p->totloop; j++) {
1043                                         GridPaintMask *gpm = &gmask[p->loopstart + j];
1044                                         const MLoop *l = &me->mloop[p->loopstart + j];
1045                                         const MLoop *prev = ME_POLY_LOOP_PREV(me->mloop, p, j);
1046                                         const MLoop *next = ME_POLY_LOOP_NEXT(me->mloop, p, j);
1047
1048                                         gpm->data[0] = avg;
1049                                         gpm->data[1] = (paint_mask[l->v] +
1050                                                         paint_mask[next->v]) * 0.5f;
1051                                         gpm->data[2] = (paint_mask[l->v] +
1052                                                         paint_mask[prev->v]) * 0.5f;
1053                                         gpm->data[3] = paint_mask[l->v];
1054                                 }
1055                         }
1056                 }
1057
1058                 ret |= SCULPT_MASK_LAYER_CALC_LOOP;
1059         }
1060
1061         /* create vertex paint mask layer if there isn't one already */
1062         if (!paint_mask) {
1063                 CustomData_add_layer(&me->vdata, CD_PAINT_MASK,
1064                                      CD_CALLOC, NULL, me->totvert);
1065                 ret |= SCULPT_MASK_LAYER_CALC_VERT;
1066         }
1067
1068         return ret;
1069 }
1070
1071 void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene)
1072 {
1073         Sculpt *sd = scene->toolsettings->sculpt;
1074         if (sd == NULL) {
1075                 sd = scene->toolsettings->sculpt = MEM_callocN(sizeof(Sculpt), __func__);
1076
1077                 /* Turn on X plane mirror symmetry by default */
1078                 sd->paint.symmetry_flags |= PAINT_SYMM_X;
1079                 sd->paint.flags |= PAINT_SHOW_BRUSH;
1080
1081                 /* Make sure at least dyntopo subdivision is enabled */
1082                 sd->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
1083         }
1084
1085         if (!sd->detail_size) {
1086                 sd->detail_size = 12;
1087         }
1088         if (!sd->detail_percent) {
1089                 sd->detail_percent = 25;
1090         }
1091         if (sd->constant_detail == 0.0f) {
1092                 sd->constant_detail = 3.0f;
1093         }
1094
1095         /* Set sane default tiling offsets */
1096         if (!sd->paint.tile_offset[0]) {
1097                 sd->paint.tile_offset[0] = 1.0f;
1098         }
1099         if (!sd->paint.tile_offset[1]) {
1100                 sd->paint.tile_offset[1] = 1.0f;
1101         }
1102         if (!sd->paint.tile_offset[2]) {
1103                 sd->paint.tile_offset[2] = 1.0f;
1104         }
1105 }