1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2009 by Nicholas Bishop
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup bke
22  */
23 
24 #include <stdlib.h>
25 #include <string.h>
26 
27 #include "MEM_guardedalloc.h"
28 
29 #include "DNA_brush_types.h"
30 #include "DNA_gpencil_types.h"
31 #include "DNA_mesh_types.h"
32 #include "DNA_meshdata_types.h"
33 #include "DNA_modifier_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_scene_types.h"
36 #include "DNA_space_types.h"
37 #include "DNA_view3d_types.h"
38 #include "DNA_workspace_types.h"
39 
40 #include "BLI_bitmap.h"
41 #include "BLI_hash.h"
42 #include "BLI_listbase.h"
43 #include "BLI_math_vector.h"
44 #include "BLI_utildefines.h"
45 
46 #include "BLT_translation.h"
47 
48 #include "BKE_brush.h"
49 #include "BKE_ccg.h"
50 #include "BKE_colortools.h"
51 #include "BKE_context.h"
52 #include "BKE_crazyspace.h"
53 #include "BKE_deform.h"
54 #include "BKE_gpencil.h"
55 #include "BKE_idtype.h"
56 #include "BKE_image.h"
57 #include "BKE_key.h"
58 #include "BKE_lib_id.h"
59 #include "BKE_main.h"
60 #include "BKE_mesh.h"
61 #include "BKE_mesh_mapping.h"
62 #include "BKE_mesh_runtime.h"
63 #include "BKE_modifier.h"
64 #include "BKE_multires.h"
65 #include "BKE_object.h"
66 #include "BKE_paint.h"
67 #include "BKE_pbvh.h"
68 #include "BKE_subdiv_ccg.h"
69 #include "BKE_subsurf.h"
70 
71 #include "DEG_depsgraph.h"
72 #include "DEG_depsgraph_query.h"
73 
74 #include "RNA_enum_types.h"
75 
76 #include "BLO_read_write.h"
77 
78 #include "bmesh.h"
79 
palette_init_data(ID * id)80 static void palette_init_data(ID *id)
81 {
82   Palette *palette = (Palette *)id;
83 
84   BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(palette, id));
85 
86   /* Enable fake user by default. */
87   id_fake_user_set(&palette->id);
88 }
89 
palette_copy_data(Main * UNUSED (bmain),ID * id_dst,const ID * id_src,const int UNUSED (flag))90 static void palette_copy_data(Main *UNUSED(bmain),
91                               ID *id_dst,
92                               const ID *id_src,
93                               const int UNUSED(flag))
94 {
95   Palette *palette_dst = (Palette *)id_dst;
96   const Palette *palette_src = (const Palette *)id_src;
97 
98   BLI_duplicatelist(&palette_dst->colors, &palette_src->colors);
99 }
100 
palette_free_data(ID * id)101 static void palette_free_data(ID *id)
102 {
103   Palette *palette = (Palette *)id;
104 
105   BLI_freelistN(&palette->colors);
106 }
107 
palette_blend_write(BlendWriter * writer,ID * id,const void * id_address)108 static void palette_blend_write(BlendWriter *writer, ID *id, const void *id_address)
109 {
110   Palette *palette = (Palette *)id;
111   if (palette->id.us > 0 || BLO_write_is_undo(writer)) {
112     PaletteColor *color;
113     BLO_write_id_struct(writer, Palette, id_address, &palette->id);
114     BKE_id_blend_write(writer, &palette->id);
115 
116     for (color = palette->colors.first; color; color = color->next) {
117       BLO_write_struct(writer, PaletteColor, color);
118     }
119   }
120 }
121 
palette_blend_read_data(BlendDataReader * reader,ID * id)122 static void palette_blend_read_data(BlendDataReader *reader, ID *id)
123 {
124   Palette *palette = (Palette *)id;
125   BLO_read_list(reader, &palette->colors);
126 }
127 
128 IDTypeInfo IDType_ID_PAL = {
129     .id_code = ID_PAL,
130     .id_filter = FILTER_ID_PAL,
131     .main_listbase_index = INDEX_ID_PAL,
132     .struct_size = sizeof(Palette),
133     .name = "Palette",
134     .name_plural = "palettes",
135     .translation_context = BLT_I18NCONTEXT_ID_PALETTE,
136     .flags = IDTYPE_FLAGS_NO_ANIMDATA,
137 
138     .init_data = palette_init_data,
139     .copy_data = palette_copy_data,
140     .free_data = palette_free_data,
141     .make_local = NULL,
142     .foreach_id = NULL,
143     .foreach_cache = NULL,
144 
145     .blend_write = palette_blend_write,
146     .blend_read_data = palette_blend_read_data,
147     .blend_read_lib = NULL,
148     .blend_read_expand = NULL,
149 };
150 
paint_curve_copy_data(Main * UNUSED (bmain),ID * id_dst,const ID * id_src,const int UNUSED (flag))151 static void paint_curve_copy_data(Main *UNUSED(bmain),
152                                   ID *id_dst,
153                                   const ID *id_src,
154                                   const int UNUSED(flag))
155 {
156   PaintCurve *paint_curve_dst = (PaintCurve *)id_dst;
157   const PaintCurve *paint_curve_src = (const PaintCurve *)id_src;
158 
159   if (paint_curve_src->tot_points != 0) {
160     paint_curve_dst->points = MEM_dupallocN(paint_curve_src->points);
161   }
162 }
163 
paint_curve_free_data(ID * id)164 static void paint_curve_free_data(ID *id)
165 {
166   PaintCurve *paint_curve = (PaintCurve *)id;
167 
168   MEM_SAFE_FREE(paint_curve->points);
169   paint_curve->tot_points = 0;
170 }
171 
paint_curve_blend_write(BlendWriter * writer,ID * id,const void * id_address)172 static void paint_curve_blend_write(BlendWriter *writer, ID *id, const void *id_address)
173 {
174   PaintCurve *pc = (PaintCurve *)id;
175   if (pc->id.us > 0 || BLO_write_is_undo(writer)) {
176     BLO_write_id_struct(writer, PaintCurve, id_address, &pc->id);
177     BKE_id_blend_write(writer, &pc->id);
178 
179     BLO_write_struct_array(writer, PaintCurvePoint, pc->tot_points, pc->points);
180   }
181 }
182 
paint_curve_blend_read_data(BlendDataReader * reader,ID * id)183 static void paint_curve_blend_read_data(BlendDataReader *reader, ID *id)
184 {
185   PaintCurve *pc = (PaintCurve *)id;
186   BLO_read_data_address(reader, &pc->points);
187 }
188 
189 IDTypeInfo IDType_ID_PC = {
190     .id_code = ID_PC,
191     .id_filter = FILTER_ID_PC,
192     .main_listbase_index = INDEX_ID_PC,
193     .struct_size = sizeof(PaintCurve),
194     .name = "PaintCurve",
195     .name_plural = "paint_curves",
196     .translation_context = BLT_I18NCONTEXT_ID_PAINTCURVE,
197     .flags = IDTYPE_FLAGS_NO_ANIMDATA,
198 
199     .init_data = NULL,
200     .copy_data = paint_curve_copy_data,
201     .free_data = paint_curve_free_data,
202     .make_local = NULL,
203     .foreach_id = NULL,
204     .foreach_cache = NULL,
205 
206     .blend_write = paint_curve_blend_write,
207     .blend_read_data = paint_curve_blend_read_data,
208     .blend_read_lib = NULL,
209     .blend_read_expand = NULL,
210 };
211 
212 const char PAINT_CURSOR_SCULPT[3] = {255, 100, 100};
213 const char PAINT_CURSOR_VERTEX_PAINT[3] = {255, 255, 255};
214 const char PAINT_CURSOR_WEIGHT_PAINT[3] = {200, 200, 255};
215 const char PAINT_CURSOR_TEXTURE_PAINT[3] = {255, 255, 255};
216 
217 static ePaintOverlayControlFlags overlay_flags = 0;
218 
BKE_paint_invalidate_overlay_tex(Scene * scene,ViewLayer * view_layer,const Tex * tex)219 void BKE_paint_invalidate_overlay_tex(Scene *scene, ViewLayer *view_layer, const Tex *tex)
220 {
221   Paint *p = BKE_paint_get_active(scene, view_layer);
222   if (!p) {
223     return;
224   }
225 
226   Brush *br = p->brush;
227   if (!br) {
228     return;
229   }
230 
231   if (br->mtex.tex == tex) {
232     overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY;
233   }
234   if (br->mask_mtex.tex == tex) {
235     overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY;
236   }
237 }
238 
BKE_paint_invalidate_cursor_overlay(Scene * scene,ViewLayer * view_layer,CurveMapping * curve)239 void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, CurveMapping *curve)
240 {
241   Paint *p = BKE_paint_get_active(scene, view_layer);
242   if (p == NULL) {
243     return;
244   }
245 
246   Brush *br = p->brush;
247   if (br && br->curve == curve) {
248     overlay_flags |= PAINT_OVERLAY_INVALID_CURVE;
249   }
250 }
251 
BKE_paint_invalidate_overlay_all(void)252 void BKE_paint_invalidate_overlay_all(void)
253 {
254   overlay_flags |= (PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY |
255                     PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY | PAINT_OVERLAY_INVALID_CURVE);
256 }
257 
BKE_paint_get_overlay_flags(void)258 ePaintOverlayControlFlags BKE_paint_get_overlay_flags(void)
259 {
260   return overlay_flags;
261 }
262 
BKE_paint_set_overlay_override(eOverlayFlags flags)263 void BKE_paint_set_overlay_override(eOverlayFlags flags)
264 {
265   if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) {
266     if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE) {
267       overlay_flags |= PAINT_OVERLAY_OVERRIDE_CURSOR;
268     }
269     if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE) {
270       overlay_flags |= PAINT_OVERLAY_OVERRIDE_PRIMARY;
271     }
272     if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE) {
273       overlay_flags |= PAINT_OVERLAY_OVERRIDE_SECONDARY;
274     }
275   }
276   else {
277     overlay_flags &= ~(PAINT_OVERRIDE_MASK);
278   }
279 }
280 
BKE_paint_reset_overlay_invalid(ePaintOverlayControlFlags flag)281 void BKE_paint_reset_overlay_invalid(ePaintOverlayControlFlags flag)
282 {
283   overlay_flags &= ~(flag);
284 }
285 
BKE_paint_ensure_from_paintmode(Scene * sce,ePaintMode mode)286 bool BKE_paint_ensure_from_paintmode(Scene *sce, ePaintMode mode)
287 {
288   ToolSettings *ts = sce->toolsettings;
289   Paint **paint_ptr = NULL;
290   /* Some paint modes don't store paint settings as pointer, for these this can be set and
291    * referenced by paint_ptr. */
292   Paint *paint_tmp = NULL;
293 
294   switch (mode) {
295     case PAINT_MODE_SCULPT:
296       paint_ptr = (Paint **)&ts->sculpt;
297       break;
298     case PAINT_MODE_VERTEX:
299       paint_ptr = (Paint **)&ts->vpaint;
300       break;
301     case PAINT_MODE_WEIGHT:
302       paint_ptr = (Paint **)&ts->wpaint;
303       break;
304     case PAINT_MODE_TEXTURE_2D:
305     case PAINT_MODE_TEXTURE_3D:
306       paint_tmp = (Paint *)&ts->imapaint;
307       paint_ptr = &paint_tmp;
308       break;
309     case PAINT_MODE_SCULPT_UV:
310       paint_ptr = (Paint **)&ts->uvsculpt;
311       break;
312     case PAINT_MODE_GPENCIL:
313       paint_ptr = (Paint **)&ts->gp_paint;
314       break;
315     case PAINT_MODE_VERTEX_GPENCIL:
316       paint_ptr = (Paint **)&ts->gp_vertexpaint;
317       break;
318     case PAINT_MODE_SCULPT_GPENCIL:
319       paint_ptr = (Paint **)&ts->gp_sculptpaint;
320       break;
321     case PAINT_MODE_WEIGHT_GPENCIL:
322       paint_ptr = (Paint **)&ts->gp_weightpaint;
323       break;
324     case PAINT_MODE_INVALID:
325       break;
326   }
327   if (paint_ptr) {
328     BKE_paint_ensure(ts, paint_ptr);
329     return true;
330   }
331   return false;
332 }
333 
BKE_paint_get_active_from_paintmode(Scene * sce,ePaintMode mode)334 Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode)
335 {
336   if (sce) {
337     ToolSettings *ts = sce->toolsettings;
338 
339     switch (mode) {
340       case PAINT_MODE_SCULPT:
341         return &ts->sculpt->paint;
342       case PAINT_MODE_VERTEX:
343         return &ts->vpaint->paint;
344       case PAINT_MODE_WEIGHT:
345         return &ts->wpaint->paint;
346       case PAINT_MODE_TEXTURE_2D:
347       case PAINT_MODE_TEXTURE_3D:
348         return &ts->imapaint.paint;
349       case PAINT_MODE_SCULPT_UV:
350         return &ts->uvsculpt->paint;
351       case PAINT_MODE_GPENCIL:
352         return &ts->gp_paint->paint;
353       case PAINT_MODE_VERTEX_GPENCIL:
354         return &ts->gp_vertexpaint->paint;
355       case PAINT_MODE_SCULPT_GPENCIL:
356         return &ts->gp_sculptpaint->paint;
357       case PAINT_MODE_WEIGHT_GPENCIL:
358         return &ts->gp_weightpaint->paint;
359       case PAINT_MODE_INVALID:
360         return NULL;
361       default:
362         return &ts->imapaint.paint;
363     }
364   }
365 
366   return NULL;
367 }
368 
BKE_paint_get_tool_enum_from_paintmode(ePaintMode mode)369 const EnumPropertyItem *BKE_paint_get_tool_enum_from_paintmode(ePaintMode mode)
370 {
371   switch (mode) {
372     case PAINT_MODE_SCULPT:
373       return rna_enum_brush_sculpt_tool_items;
374     case PAINT_MODE_VERTEX:
375       return rna_enum_brush_vertex_tool_items;
376     case PAINT_MODE_WEIGHT:
377       return rna_enum_brush_weight_tool_items;
378     case PAINT_MODE_TEXTURE_2D:
379     case PAINT_MODE_TEXTURE_3D:
380       return rna_enum_brush_image_tool_items;
381     case PAINT_MODE_SCULPT_UV:
382       return rna_enum_brush_uv_sculpt_tool_items;
383     case PAINT_MODE_GPENCIL:
384       return rna_enum_brush_gpencil_types_items;
385     case PAINT_MODE_VERTEX_GPENCIL:
386       return rna_enum_brush_gpencil_vertex_types_items;
387     case PAINT_MODE_SCULPT_GPENCIL:
388       return rna_enum_brush_gpencil_sculpt_types_items;
389     case PAINT_MODE_WEIGHT_GPENCIL:
390       return rna_enum_brush_gpencil_weight_types_items;
391     case PAINT_MODE_INVALID:
392       break;
393   }
394   return NULL;
395 }
396 
BKE_paint_get_tool_prop_id_from_paintmode(ePaintMode mode)397 const char *BKE_paint_get_tool_prop_id_from_paintmode(ePaintMode mode)
398 {
399   switch (mode) {
400     case PAINT_MODE_SCULPT:
401       return "sculpt_tool";
402     case PAINT_MODE_VERTEX:
403       return "vertex_tool";
404     case PAINT_MODE_WEIGHT:
405       return "weight_tool";
406     case PAINT_MODE_TEXTURE_2D:
407     case PAINT_MODE_TEXTURE_3D:
408       return "image_tool";
409     case PAINT_MODE_SCULPT_UV:
410       return "uv_sculpt_tool";
411     case PAINT_MODE_GPENCIL:
412       return "gpencil_tool";
413     case PAINT_MODE_VERTEX_GPENCIL:
414       return "gpencil_vertex_tool";
415     case PAINT_MODE_SCULPT_GPENCIL:
416       return "gpencil_sculpt_tool";
417     case PAINT_MODE_WEIGHT_GPENCIL:
418       return "gpencil_weight_tool";
419     case PAINT_MODE_INVALID:
420       break;
421   }
422 
423   /* Invalid paint mode. */
424   return NULL;
425 }
426 
BKE_paint_get_active(Scene * sce,ViewLayer * view_layer)427 Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer)
428 {
429   if (sce && view_layer) {
430     ToolSettings *ts = sce->toolsettings;
431 
432     if (view_layer->basact && view_layer->basact->object) {
433       switch (view_layer->basact->object->mode) {
434         case OB_MODE_SCULPT:
435           return &ts->sculpt->paint;
436         case OB_MODE_VERTEX_PAINT:
437           return &ts->vpaint->paint;
438         case OB_MODE_WEIGHT_PAINT:
439           return &ts->wpaint->paint;
440         case OB_MODE_TEXTURE_PAINT:
441           return &ts->imapaint.paint;
442         case OB_MODE_PAINT_GPENCIL:
443           return &ts->gp_paint->paint;
444         case OB_MODE_VERTEX_GPENCIL:
445           return &ts->gp_vertexpaint->paint;
446         case OB_MODE_SCULPT_GPENCIL:
447           return &ts->gp_sculptpaint->paint;
448         case OB_MODE_WEIGHT_GPENCIL:
449           return &ts->gp_weightpaint->paint;
450         case OB_MODE_EDIT:
451           return ts->uvsculpt ? &ts->uvsculpt->paint : NULL;
452         default:
453           break;
454       }
455     }
456 
457     /* default to image paint */
458     return &ts->imapaint.paint;
459   }
460 
461   return NULL;
462 }
463 
BKE_paint_get_active_from_context(const bContext * C)464 Paint *BKE_paint_get_active_from_context(const bContext *C)
465 {
466   Scene *sce = CTX_data_scene(C);
467   ViewLayer *view_layer = CTX_data_view_layer(C);
468   SpaceImage *sima;
469 
470   if (sce && view_layer) {
471     ToolSettings *ts = sce->toolsettings;
472     Object *obact = NULL;
473 
474     if (view_layer->basact && view_layer->basact->object) {
475       obact = view_layer->basact->object;
476     }
477 
478     if ((sima = CTX_wm_space_image(C)) != NULL) {
479       if (obact && obact->mode == OB_MODE_EDIT) {
480         if (sima->mode == SI_MODE_PAINT) {
481           return &ts->imapaint.paint;
482         }
483         if (sima->mode == SI_MODE_UV) {
484           return &ts->uvsculpt->paint;
485         }
486       }
487       else {
488         return &ts->imapaint.paint;
489       }
490     }
491     else {
492       return BKE_paint_get_active(sce, view_layer);
493     }
494   }
495 
496   return NULL;
497 }
498 
BKE_paintmode_get_active_from_context(const bContext * C)499 ePaintMode BKE_paintmode_get_active_from_context(const bContext *C)
500 {
501   Scene *sce = CTX_data_scene(C);
502   ViewLayer *view_layer = CTX_data_view_layer(C);
503   SpaceImage *sima;
504 
505   if (sce && view_layer) {
506     Object *obact = NULL;
507 
508     if (view_layer->basact && view_layer->basact->object) {
509       obact = view_layer->basact->object;
510     }
511 
512     if ((sima = CTX_wm_space_image(C)) != NULL) {
513       if (obact && obact->mode == OB_MODE_EDIT) {
514         if (sima->mode == SI_MODE_PAINT) {
515           return PAINT_MODE_TEXTURE_2D;
516         }
517         if (sima->mode == SI_MODE_UV) {
518           return PAINT_MODE_SCULPT_UV;
519         }
520       }
521       else {
522         return PAINT_MODE_TEXTURE_2D;
523       }
524     }
525     else if (obact) {
526       switch (obact->mode) {
527         case OB_MODE_SCULPT:
528           return PAINT_MODE_SCULPT;
529         case OB_MODE_VERTEX_PAINT:
530           return PAINT_MODE_VERTEX;
531         case OB_MODE_WEIGHT_PAINT:
532           return PAINT_MODE_WEIGHT;
533         case OB_MODE_TEXTURE_PAINT:
534           return PAINT_MODE_TEXTURE_3D;
535         case OB_MODE_EDIT:
536           return PAINT_MODE_SCULPT_UV;
537         default:
538           return PAINT_MODE_TEXTURE_2D;
539       }
540     }
541     else {
542       /* default to image paint */
543       return PAINT_MODE_TEXTURE_2D;
544     }
545   }
546 
547   return PAINT_MODE_INVALID;
548 }
549 
BKE_paintmode_get_from_tool(const struct bToolRef * tref)550 ePaintMode BKE_paintmode_get_from_tool(const struct bToolRef *tref)
551 {
552   if (tref->space_type == SPACE_VIEW3D) {
553     switch (tref->mode) {
554       case CTX_MODE_SCULPT:
555         return PAINT_MODE_SCULPT;
556       case CTX_MODE_PAINT_VERTEX:
557         return PAINT_MODE_VERTEX;
558       case CTX_MODE_PAINT_WEIGHT:
559         return PAINT_MODE_WEIGHT;
560       case CTX_MODE_PAINT_GPENCIL:
561         return PAINT_MODE_GPENCIL;
562       case CTX_MODE_PAINT_TEXTURE:
563         return PAINT_MODE_TEXTURE_3D;
564       case CTX_MODE_VERTEX_GPENCIL:
565         return PAINT_MODE_VERTEX_GPENCIL;
566       case CTX_MODE_SCULPT_GPENCIL:
567         return PAINT_MODE_SCULPT_GPENCIL;
568       case CTX_MODE_WEIGHT_GPENCIL:
569         return PAINT_MODE_WEIGHT_GPENCIL;
570     }
571   }
572   else if (tref->space_type == SPACE_IMAGE) {
573     switch (tref->mode) {
574       case SI_MODE_PAINT:
575         return PAINT_MODE_TEXTURE_2D;
576       case SI_MODE_UV:
577         return PAINT_MODE_SCULPT_UV;
578     }
579   }
580 
581   return PAINT_MODE_INVALID;
582 }
583 
BKE_paint_brush(Paint * p)584 Brush *BKE_paint_brush(Paint *p)
585 {
586   return p ? p->brush : NULL;
587 }
588 
BKE_paint_brush_set(Paint * p,Brush * br)589 void BKE_paint_brush_set(Paint *p, Brush *br)
590 {
591   if (p) {
592     id_us_min((ID *)p->brush);
593     id_us_plus((ID *)br);
594     p->brush = br;
595 
596     BKE_paint_toolslots_brush_update(p);
597   }
598 }
599 
BKE_paint_runtime_init(const ToolSettings * ts,Paint * paint)600 void BKE_paint_runtime_init(const ToolSettings *ts, Paint *paint)
601 {
602   if (paint == &ts->imapaint.paint) {
603     paint->runtime.tool_offset = offsetof(Brush, imagepaint_tool);
604     paint->runtime.ob_mode = OB_MODE_TEXTURE_PAINT;
605   }
606   else if (ts->sculpt && paint == &ts->sculpt->paint) {
607     paint->runtime.tool_offset = offsetof(Brush, sculpt_tool);
608     paint->runtime.ob_mode = OB_MODE_SCULPT;
609   }
610   else if (ts->vpaint && paint == &ts->vpaint->paint) {
611     paint->runtime.tool_offset = offsetof(Brush, vertexpaint_tool);
612     paint->runtime.ob_mode = OB_MODE_VERTEX_PAINT;
613   }
614   else if (ts->wpaint && paint == &ts->wpaint->paint) {
615     paint->runtime.tool_offset = offsetof(Brush, weightpaint_tool);
616     paint->runtime.ob_mode = OB_MODE_WEIGHT_PAINT;
617   }
618   else if (ts->uvsculpt && paint == &ts->uvsculpt->paint) {
619     paint->runtime.tool_offset = offsetof(Brush, uv_sculpt_tool);
620     paint->runtime.ob_mode = OB_MODE_EDIT;
621   }
622   else if (ts->gp_paint && paint == &ts->gp_paint->paint) {
623     paint->runtime.tool_offset = offsetof(Brush, gpencil_tool);
624     paint->runtime.ob_mode = OB_MODE_PAINT_GPENCIL;
625   }
626   else if (ts->gp_vertexpaint && paint == &ts->gp_vertexpaint->paint) {
627     paint->runtime.tool_offset = offsetof(Brush, gpencil_vertex_tool);
628     paint->runtime.ob_mode = OB_MODE_VERTEX_GPENCIL;
629   }
630   else if (ts->gp_sculptpaint && paint == &ts->gp_sculptpaint->paint) {
631     paint->runtime.tool_offset = offsetof(Brush, gpencil_sculpt_tool);
632     paint->runtime.ob_mode = OB_MODE_SCULPT_GPENCIL;
633   }
634   else if (ts->gp_weightpaint && paint == &ts->gp_weightpaint->paint) {
635     paint->runtime.tool_offset = offsetof(Brush, gpencil_weight_tool);
636     paint->runtime.ob_mode = OB_MODE_WEIGHT_GPENCIL;
637   }
638   else {
639     BLI_assert(0);
640   }
641 }
642 
BKE_paint_get_brush_tool_offset_from_paintmode(const ePaintMode mode)643 uint BKE_paint_get_brush_tool_offset_from_paintmode(const ePaintMode mode)
644 {
645   switch (mode) {
646     case PAINT_MODE_TEXTURE_2D:
647     case PAINT_MODE_TEXTURE_3D:
648       return offsetof(Brush, imagepaint_tool);
649     case PAINT_MODE_SCULPT:
650       return offsetof(Brush, sculpt_tool);
651     case PAINT_MODE_VERTEX:
652       return offsetof(Brush, vertexpaint_tool);
653     case PAINT_MODE_WEIGHT:
654       return offsetof(Brush, weightpaint_tool);
655     case PAINT_MODE_SCULPT_UV:
656       return offsetof(Brush, uv_sculpt_tool);
657     case PAINT_MODE_GPENCIL:
658       return offsetof(Brush, gpencil_tool);
659     case PAINT_MODE_VERTEX_GPENCIL:
660       return offsetof(Brush, gpencil_vertex_tool);
661     case PAINT_MODE_SCULPT_GPENCIL:
662       return offsetof(Brush, gpencil_sculpt_tool);
663     case PAINT_MODE_WEIGHT_GPENCIL:
664       return offsetof(Brush, gpencil_weight_tool);
665     case PAINT_MODE_INVALID:
666       break; /* We don't use these yet. */
667   }
668   return 0;
669 }
670 
BKE_paint_curve_add(Main * bmain,const char * name)671 PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name)
672 {
673   PaintCurve *pc;
674 
675   pc = BKE_id_new(bmain, ID_PC, name);
676 
677   return pc;
678 }
679 
BKE_paint_palette(Paint * p)680 Palette *BKE_paint_palette(Paint *p)
681 {
682   return p ? p->palette : NULL;
683 }
684 
BKE_paint_palette_set(Paint * p,Palette * palette)685 void BKE_paint_palette_set(Paint *p, Palette *palette)
686 {
687   if (p) {
688     id_us_min((ID *)p->palette);
689     p->palette = palette;
690     id_us_plus((ID *)p->palette);
691   }
692 }
693 
BKE_paint_curve_set(Brush * br,PaintCurve * pc)694 void BKE_paint_curve_set(Brush *br, PaintCurve *pc)
695 {
696   if (br) {
697     id_us_min((ID *)br->paint_curve);
698     br->paint_curve = pc;
699     id_us_plus((ID *)br->paint_curve);
700   }
701 }
702 
BKE_paint_curve_clamp_endpoint_add_index(PaintCurve * pc,const int add_index)703 void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_index)
704 {
705   pc->add_index = (add_index || pc->tot_points == 1) ? (add_index + 1) : 0;
706 }
707 
708 /** Remove color from palette. Must be certain color is inside the palette! */
BKE_palette_color_remove(Palette * palette,PaletteColor * color)709 void BKE_palette_color_remove(Palette *palette, PaletteColor *color)
710 {
711   if (BLI_listbase_count_at_most(&palette->colors, palette->active_color) ==
712       palette->active_color) {
713     palette->active_color--;
714   }
715 
716   BLI_remlink(&palette->colors, color);
717 
718   if (palette->active_color < 0 && !BLI_listbase_is_empty(&palette->colors)) {
719     palette->active_color = 0;
720   }
721 
722   MEM_freeN(color);
723 }
724 
BKE_palette_clear(Palette * palette)725 void BKE_palette_clear(Palette *palette)
726 {
727   BLI_freelistN(&palette->colors);
728   palette->active_color = 0;
729 }
730 
BKE_palette_add(Main * bmain,const char * name)731 Palette *BKE_palette_add(Main *bmain, const char *name)
732 {
733   Palette *palette = BKE_id_new(bmain, ID_PAL, name);
734   return palette;
735 }
736 
BKE_palette_color_add(Palette * palette)737 PaletteColor *BKE_palette_color_add(Palette *palette)
738 {
739   PaletteColor *color = MEM_callocN(sizeof(*color), "Palette Color");
740   BLI_addtail(&palette->colors, color);
741   return color;
742 }
743 
BKE_palette_is_empty(const struct Palette * palette)744 bool BKE_palette_is_empty(const struct Palette *palette)
745 {
746   return BLI_listbase_is_empty(&palette->colors);
747 }
748 
749 /* helper function to sort using qsort */
palettecolor_compare_hsv(const void * a1,const void * a2)750 static int palettecolor_compare_hsv(const void *a1, const void *a2)
751 {
752   const tPaletteColorHSV *ps1 = a1, *ps2 = a2;
753 
754   /* Hue */
755   if (ps1->h > ps2->h) {
756     return 1;
757   }
758   if (ps1->h < ps2->h) {
759     return -1;
760   }
761 
762   /* Saturation. */
763   if (ps1->s > ps2->s) {
764     return 1;
765   }
766   if (ps1->s < ps2->s) {
767     return -1;
768   }
769 
770   /* Value. */
771   if (1.0f - ps1->v > 1.0f - ps2->v) {
772     return 1;
773   }
774   if (1.0f - ps1->v < 1.0f - ps2->v) {
775     return -1;
776   }
777 
778   return 0;
779 }
780 
781 /* helper function to sort using qsort */
palettecolor_compare_svh(const void * a1,const void * a2)782 static int palettecolor_compare_svh(const void *a1, const void *a2)
783 {
784   const tPaletteColorHSV *ps1 = a1, *ps2 = a2;
785 
786   /* Saturation. */
787   if (ps1->s > ps2->s) {
788     return 1;
789   }
790   if (ps1->s < ps2->s) {
791     return -1;
792   }
793 
794   /* Value. */
795   if (1.0f - ps1->v > 1.0f - ps2->v) {
796     return 1;
797   }
798   if (1.0f - ps1->v < 1.0f - ps2->v) {
799     return -1;
800   }
801 
802   /* Hue */
803   if (ps1->h > ps2->h) {
804     return 1;
805   }
806   if (ps1->h < ps2->h) {
807     return -1;
808   }
809 
810   return 0;
811 }
812 
palettecolor_compare_vhs(const void * a1,const void * a2)813 static int palettecolor_compare_vhs(const void *a1, const void *a2)
814 {
815   const tPaletteColorHSV *ps1 = a1, *ps2 = a2;
816 
817   /* Value. */
818   if (1.0f - ps1->v > 1.0f - ps2->v) {
819     return 1;
820   }
821   if (1.0f - ps1->v < 1.0f - ps2->v) {
822     return -1;
823   }
824 
825   /* Hue */
826   if (ps1->h > ps2->h) {
827     return 1;
828   }
829   if (ps1->h < ps2->h) {
830     return -1;
831   }
832 
833   /* Saturation. */
834   if (ps1->s > ps2->s) {
835     return 1;
836   }
837   if (ps1->s < ps2->s) {
838     return -1;
839   }
840 
841   return 0;
842 }
843 
palettecolor_compare_luminance(const void * a1,const void * a2)844 static int palettecolor_compare_luminance(const void *a1, const void *a2)
845 {
846   const tPaletteColorHSV *ps1 = a1, *ps2 = a2;
847 
848   float lumi1 = (ps1->rgb[0] + ps1->rgb[1] + ps1->rgb[2]) / 3.0f;
849   float lumi2 = (ps2->rgb[0] + ps2->rgb[1] + ps2->rgb[2]) / 3.0f;
850 
851   if (lumi1 > lumi2) {
852     return -1;
853   }
854   if (lumi1 < lumi2) {
855     return 1;
856   }
857 
858   return 0;
859 }
860 
BKE_palette_sort_hsv(tPaletteColorHSV * color_array,const int totcol)861 void BKE_palette_sort_hsv(tPaletteColorHSV *color_array, const int totcol)
862 {
863   /* Sort by Hue , Saturation and Value. */
864   qsort(color_array, totcol, sizeof(tPaletteColorHSV), palettecolor_compare_hsv);
865 }
866 
BKE_palette_sort_svh(tPaletteColorHSV * color_array,const int totcol)867 void BKE_palette_sort_svh(tPaletteColorHSV *color_array, const int totcol)
868 {
869   /* Sort by Saturation, Value and Hue. */
870   qsort(color_array, totcol, sizeof(tPaletteColorHSV), palettecolor_compare_svh);
871 }
872 
BKE_palette_sort_vhs(tPaletteColorHSV * color_array,const int totcol)873 void BKE_palette_sort_vhs(tPaletteColorHSV *color_array, const int totcol)
874 {
875   /* Sort by Saturation, Value and Hue. */
876   qsort(color_array, totcol, sizeof(tPaletteColorHSV), palettecolor_compare_vhs);
877 }
878 
BKE_palette_sort_luminance(tPaletteColorHSV * color_array,const int totcol)879 void BKE_palette_sort_luminance(tPaletteColorHSV *color_array, const int totcol)
880 {
881   /* Sort by Luminance (calculated with the average, enough for sorting). */
882   qsort(color_array, totcol, sizeof(tPaletteColorHSV), palettecolor_compare_luminance);
883 }
884 
BKE_palette_from_hash(Main * bmain,GHash * color_table,const char * name,const bool linear)885 bool BKE_palette_from_hash(Main *bmain, GHash *color_table, const char *name, const bool linear)
886 {
887   tPaletteColorHSV *color_array = NULL;
888   tPaletteColorHSV *col_elm = NULL;
889   bool done = false;
890 
891   const int totpal = BLI_ghash_len(color_table);
892 
893   if (totpal > 0) {
894     color_array = MEM_calloc_arrayN(totpal, sizeof(tPaletteColorHSV), __func__);
895     /* Put all colors in an array. */
896     GHashIterator gh_iter;
897     int t = 0;
898     GHASH_ITER (gh_iter, color_table) {
899       const uint col = POINTER_AS_INT(BLI_ghashIterator_getValue(&gh_iter));
900       float r, g, b;
901       float h, s, v;
902       cpack_to_rgb(col, &r, &g, &b);
903       rgb_to_hsv(r, g, b, &h, &s, &v);
904 
905       col_elm = &color_array[t];
906       col_elm->rgb[0] = r;
907       col_elm->rgb[1] = g;
908       col_elm->rgb[2] = b;
909       col_elm->h = h;
910       col_elm->s = s;
911       col_elm->v = v;
912       t++;
913     }
914   }
915 
916   /* Create the Palette. */
917   if (totpal > 0) {
918     /* Sort by Hue and saturation. */
919     BKE_palette_sort_hsv(color_array, totpal);
920 
921     Palette *palette = BKE_palette_add(bmain, name);
922     if (palette) {
923       for (int i = 0; i < totpal; i++) {
924         col_elm = &color_array[i];
925         PaletteColor *palcol = BKE_palette_color_add(palette);
926         if (palcol) {
927           copy_v3_v3(palcol->rgb, col_elm->rgb);
928           if (linear) {
929             linearrgb_to_srgb_v3_v3(palcol->rgb, palcol->rgb);
930           }
931         }
932       }
933       done = true;
934     }
935   }
936   else {
937     done = false;
938   }
939 
940   if (totpal > 0) {
941     MEM_SAFE_FREE(color_array);
942   }
943 
944   return done;
945 }
946 
947 /* are we in vertex paint or weight paint face select mode? */
BKE_paint_select_face_test(Object * ob)948 bool BKE_paint_select_face_test(Object *ob)
949 {
950   return ((ob != NULL) && (ob->type == OB_MESH) && (ob->data != NULL) &&
951           (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_FACE_SEL) &&
952           (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)));
953 }
954 
955 /* are we in weight paint vertex select mode? */
BKE_paint_select_vert_test(Object * ob)956 bool BKE_paint_select_vert_test(Object *ob)
957 {
958   return ((ob != NULL) && (ob->type == OB_MESH) && (ob->data != NULL) &&
959           (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) &&
960           (ob->mode & OB_MODE_WEIGHT_PAINT || ob->mode & OB_MODE_VERTEX_PAINT));
961 }
962 
963 /**
964  * used to check if selection is possible
965  * (when we don't care if its face or vert)
966  */
BKE_paint_select_elem_test(Object * ob)967 bool BKE_paint_select_elem_test(Object *ob)
968 {
969   return (BKE_paint_select_vert_test(ob) || BKE_paint_select_face_test(ob));
970 }
971 
BKE_paint_cavity_curve_preset(Paint * p,int preset)972 void BKE_paint_cavity_curve_preset(Paint *p, int preset)
973 {
974   CurveMapping *cumap = NULL;
975   CurveMap *cuma = NULL;
976 
977   if (!p->cavity_curve) {
978     p->cavity_curve = BKE_curvemapping_add(1, 0, 0, 1, 1);
979   }
980   cumap = p->cavity_curve;
981   cumap->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
982   cumap->preset = preset;
983 
984   cuma = cumap->cm;
985   BKE_curvemap_reset(cuma, &cumap->clipr, cumap->preset, CURVEMAP_SLOPE_POSITIVE);
986   BKE_curvemapping_changed(cumap, false);
987 }
988 
BKE_paint_object_mode_from_paintmode(ePaintMode mode)989 eObjectMode BKE_paint_object_mode_from_paintmode(ePaintMode mode)
990 {
991   switch (mode) {
992     case PAINT_MODE_SCULPT:
993       return OB_MODE_SCULPT;
994     case PAINT_MODE_VERTEX:
995       return OB_MODE_VERTEX_PAINT;
996     case PAINT_MODE_WEIGHT:
997       return OB_MODE_WEIGHT_PAINT;
998     case PAINT_MODE_TEXTURE_2D:
999     case PAINT_MODE_TEXTURE_3D:
1000       return OB_MODE_TEXTURE_PAINT;
1001     case PAINT_MODE_SCULPT_UV:
1002       return OB_MODE_EDIT;
1003     case PAINT_MODE_INVALID:
1004     default:
1005       return 0;
1006   }
1007 }
1008 
1009 /**
1010  * Call when entering each respective paint mode.
1011  */
BKE_paint_ensure(ToolSettings * ts,struct Paint ** r_paint)1012 bool BKE_paint_ensure(ToolSettings *ts, struct Paint **r_paint)
1013 {
1014   Paint *paint = NULL;
1015   if (*r_paint) {
1016     /* Tool offset should never be 0 for initialized paint settings, so it's a reliable way to
1017      * check if already initialized. */
1018     if ((*r_paint)->runtime.tool_offset == 0) {
1019       /* Currently only image painting is initialized this way, others have to be allocated. */
1020       BLI_assert(ELEM(*r_paint, (Paint *)&ts->imapaint));
1021 
1022       BKE_paint_runtime_init(ts, *r_paint);
1023     }
1024     else {
1025       BLI_assert(ELEM(*r_paint,
1026                       /* Cast is annoying, but prevent NULL-pointer access. */
1027                       (Paint *)ts->gp_paint,
1028                       (Paint *)ts->gp_vertexpaint,
1029                       (Paint *)ts->gp_sculptpaint,
1030                       (Paint *)ts->gp_weightpaint,
1031                       (Paint *)ts->sculpt,
1032                       (Paint *)ts->vpaint,
1033                       (Paint *)ts->wpaint,
1034                       (Paint *)ts->uvsculpt,
1035                       (Paint *)&ts->imapaint));
1036 #ifdef DEBUG
1037       struct Paint paint_test = **r_paint;
1038       BKE_paint_runtime_init(ts, *r_paint);
1039       /* Swap so debug doesn't hide errors when release fails. */
1040       SWAP(Paint, **r_paint, paint_test);
1041       BLI_assert(paint_test.runtime.ob_mode == (*r_paint)->runtime.ob_mode);
1042       BLI_assert(paint_test.runtime.tool_offset == (*r_paint)->runtime.tool_offset);
1043 #endif
1044     }
1045     return true;
1046   }
1047 
1048   if (((VPaint **)r_paint == &ts->vpaint) || ((VPaint **)r_paint == &ts->wpaint)) {
1049     VPaint *data = MEM_callocN(sizeof(*data), __func__);
1050     paint = &data->paint;
1051   }
1052   else if ((Sculpt **)r_paint == &ts->sculpt) {
1053     Sculpt *data = MEM_callocN(sizeof(*data), __func__);
1054     paint = &data->paint;
1055 
1056     /* Turn on X plane mirror symmetry by default */
1057     paint->symmetry_flags |= PAINT_SYMM_X;
1058 
1059     /* Make sure at least dyntopo subdivision is enabled */
1060     data->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
1061   }
1062   else if ((GpPaint **)r_paint == &ts->gp_paint) {
1063     GpPaint *data = MEM_callocN(sizeof(*data), __func__);
1064     paint = &data->paint;
1065   }
1066   else if ((GpVertexPaint **)r_paint == &ts->gp_vertexpaint) {
1067     GpVertexPaint *data = MEM_callocN(sizeof(*data), __func__);
1068     paint = &data->paint;
1069   }
1070   else if ((GpSculptPaint **)r_paint == &ts->gp_sculptpaint) {
1071     GpSculptPaint *data = MEM_callocN(sizeof(*data), __func__);
1072     paint = &data->paint;
1073   }
1074   else if ((GpWeightPaint **)r_paint == &ts->gp_weightpaint) {
1075     GpWeightPaint *data = MEM_callocN(sizeof(*data), __func__);
1076     paint = &data->paint;
1077   }
1078   else if ((UvSculpt **)r_paint == &ts->uvsculpt) {
1079     UvSculpt *data = MEM_callocN(sizeof(*data), __func__);
1080     paint = &data->paint;
1081   }
1082   else if (*r_paint == &ts->imapaint.paint) {
1083     paint = &ts->imapaint.paint;
1084   }
1085 
1086   paint->flags |= PAINT_SHOW_BRUSH;
1087 
1088   *r_paint = paint;
1089 
1090   BKE_paint_runtime_init(ts, paint);
1091 
1092   return false;
1093 }
1094 
BKE_paint_init(Main * bmain,Scene * sce,ePaintMode mode,const char col[3])1095 void BKE_paint_init(Main *bmain, Scene *sce, ePaintMode mode, const char col[3])
1096 {
1097   UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings;
1098   Paint *paint = BKE_paint_get_active_from_paintmode(sce, mode);
1099 
1100   BKE_paint_ensure_from_paintmode(sce, mode);
1101 
1102   /* If there's no brush, create one */
1103   if (PAINT_MODE_HAS_BRUSH(mode)) {
1104     Brush *brush = BKE_paint_brush(paint);
1105     if (brush == NULL) {
1106       eObjectMode ob_mode = BKE_paint_object_mode_from_paintmode(mode);
1107       brush = BKE_brush_first_search(bmain, ob_mode);
1108       if (!brush) {
1109         brush = BKE_brush_add(bmain, "Brush", ob_mode);
1110         id_us_min(&brush->id); /* fake user only */
1111       }
1112       BKE_paint_brush_set(paint, brush);
1113     }
1114   }
1115 
1116   memcpy(paint->paint_cursor_col, col, 3);
1117   paint->paint_cursor_col[3] = 128;
1118   ups->last_stroke_valid = false;
1119   zero_v3(ups->average_stroke_accum);
1120   ups->average_stroke_counter = 0;
1121   if (!paint->cavity_curve) {
1122     BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE);
1123   }
1124 }
1125 
BKE_paint_free(Paint * paint)1126 void BKE_paint_free(Paint *paint)
1127 {
1128   BKE_curvemapping_free(paint->cavity_curve);
1129   MEM_SAFE_FREE(paint->tool_slots);
1130 }
1131 
1132 /* called when copying scene settings, so even if 'src' and 'tar' are the same
1133  * still do a id_us_plus(), rather than if we were copying between 2 existing
1134  * scenes where a matching value should decrease the existing user count as
1135  * with paint_brush_set() */
BKE_paint_copy(Paint * src,Paint * tar,const int flag)1136 void BKE_paint_copy(Paint *src, Paint *tar, const int flag)
1137 {
1138   tar->brush = src->brush;
1139   tar->cavity_curve = BKE_curvemapping_copy(src->cavity_curve);
1140   tar->tool_slots = MEM_dupallocN(src->tool_slots);
1141 
1142   if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1143     id_us_plus((ID *)tar->brush);
1144     id_us_plus((ID *)tar->palette);
1145     if (src->tool_slots != NULL) {
1146       for (int i = 0; i < tar->tool_slots_len; i++) {
1147         id_us_plus((ID *)tar->tool_slots[i].brush);
1148       }
1149     }
1150   }
1151 }
1152 
BKE_paint_stroke_get_average(Scene * scene,Object * ob,float stroke[3])1153 void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3])
1154 {
1155   UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1156   if (ups->last_stroke_valid && ups->average_stroke_counter > 0) {
1157     float fac = 1.0f / ups->average_stroke_counter;
1158     mul_v3_v3fl(stroke, ups->average_stroke_accum, fac);
1159   }
1160   else {
1161     copy_v3_v3(stroke, ob->obmat[3]);
1162   }
1163 }
1164 
1165 /* returns non-zero if any of the face's vertices
1166  * are hidden, zero otherwise */
paint_is_face_hidden(const MLoopTri * lt,const MVert * mvert,const MLoop * mloop)1167 bool paint_is_face_hidden(const MLoopTri *lt, const MVert *mvert, const MLoop *mloop)
1168 {
1169   return ((mvert[mloop[lt->tri[0]].v].flag & ME_HIDE) ||
1170           (mvert[mloop[lt->tri[1]].v].flag & ME_HIDE) ||
1171           (mvert[mloop[lt->tri[2]].v].flag & ME_HIDE));
1172 }
1173 
1174 /* returns non-zero if any of the corners of the grid
1175  * face whose inner corner is at (x, y) are hidden,
1176  * zero otherwise */
paint_is_grid_face_hidden(const uint * grid_hidden,int gridsize,int x,int y)1177 bool paint_is_grid_face_hidden(const uint *grid_hidden, int gridsize, int x, int y)
1178 {
1179   /* skip face if any of its corners are hidden */
1180   return (BLI_BITMAP_TEST(grid_hidden, y * gridsize + x) ||
1181           BLI_BITMAP_TEST(grid_hidden, y * gridsize + x + 1) ||
1182           BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x + 1) ||
1183           BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x));
1184 }
1185 
1186 /* Return true if all vertices in the face are visible, false otherwise */
paint_is_bmesh_face_hidden(BMFace * f)1187 bool paint_is_bmesh_face_hidden(BMFace *f)
1188 {
1189   BMLoop *l_iter;
1190   BMLoop *l_first;
1191 
1192   l_iter = l_first = BM_FACE_FIRST_LOOP(f);
1193   do {
1194     if (BM_elem_flag_test(l_iter->v, BM_ELEM_HIDDEN)) {
1195       return true;
1196     }
1197   } while ((l_iter = l_iter->next) != l_first);
1198 
1199   return false;
1200 }
1201 
paint_grid_paint_mask(const GridPaintMask * gpm,uint level,uint x,uint y)1202 float paint_grid_paint_mask(const GridPaintMask *gpm, uint level, uint x, uint y)
1203 {
1204   int factor = BKE_ccg_factor(level, gpm->level);
1205   int gridsize = BKE_ccg_gridsize(gpm->level);
1206 
1207   return gpm->data[(y * factor) * gridsize + (x * factor)];
1208 }
1209 
1210 /* threshold to move before updating the brush rotation */
1211 #define RAKE_THRESHHOLD 20
1212 
paint_update_brush_rake_rotation(UnifiedPaintSettings * ups,Brush * brush,float rotation)1213 void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation)
1214 {
1215   if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) {
1216     ups->brush_rotation = rotation;
1217   }
1218   else {
1219     ups->brush_rotation = 0.0f;
1220   }
1221 
1222   if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE) {
1223     ups->brush_rotation_sec = rotation;
1224   }
1225   else {
1226     ups->brush_rotation_sec = 0.0f;
1227   }
1228 }
1229 
paint_calculate_rake_rotation(UnifiedPaintSettings * ups,Brush * brush,const float mouse_pos[2])1230 bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups,
1231                                    Brush *brush,
1232                                    const float mouse_pos[2])
1233 {
1234   bool ok = false;
1235   if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) ||
1236       (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
1237     const float r = RAKE_THRESHHOLD;
1238     float rotation;
1239 
1240     float dpos[2];
1241     sub_v2_v2v2(dpos, ups->last_rake, mouse_pos);
1242 
1243     if (len_squared_v2(dpos) >= r * r) {
1244       rotation = atan2f(dpos[0], dpos[1]);
1245 
1246       copy_v2_v2(ups->last_rake, mouse_pos);
1247 
1248       ups->last_rake_angle = rotation;
1249 
1250       paint_update_brush_rake_rotation(ups, brush, rotation);
1251       ok = true;
1252     }
1253     /* make sure we reset here to the last rotation to avoid accumulating
1254      * values in case a random rotation is also added */
1255     else {
1256       paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle);
1257       ok = false;
1258     }
1259   }
1260   else {
1261     ups->brush_rotation = ups->brush_rotation_sec = 0.0f;
1262     ok = true;
1263   }
1264   return ok;
1265 }
1266 
BKE_sculptsession_free_deformMats(SculptSession * ss)1267 void BKE_sculptsession_free_deformMats(SculptSession *ss)
1268 {
1269   MEM_SAFE_FREE(ss->orig_cos);
1270   MEM_SAFE_FREE(ss->deform_cos);
1271   MEM_SAFE_FREE(ss->deform_imats);
1272 }
1273 
BKE_sculptsession_free_vwpaint_data(struct SculptSession * ss)1274 void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss)
1275 {
1276   struct SculptVertexPaintGeomMap *gmap = NULL;
1277   if (ss->mode_type == OB_MODE_VERTEX_PAINT) {
1278     gmap = &ss->mode.vpaint.gmap;
1279 
1280     MEM_SAFE_FREE(ss->mode.vpaint.previous_color);
1281   }
1282   else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) {
1283     gmap = &ss->mode.wpaint.gmap;
1284 
1285     MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight);
1286     if (ss->mode.wpaint.dvert_prev) {
1287       BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert);
1288       MEM_freeN(ss->mode.wpaint.dvert_prev);
1289       ss->mode.wpaint.dvert_prev = NULL;
1290     }
1291   }
1292   else {
1293     return;
1294   }
1295   MEM_SAFE_FREE(gmap->vert_to_loop);
1296   MEM_SAFE_FREE(gmap->vert_map_mem);
1297   MEM_SAFE_FREE(gmap->vert_to_poly);
1298   MEM_SAFE_FREE(gmap->poly_map_mem);
1299 }
1300 
1301 /**
1302  * Write out the sculpt dynamic-topology #BMesh to the #Mesh.
1303  */
sculptsession_bm_to_me_update_data_only(Object * ob,bool reorder)1304 static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder)
1305 {
1306   SculptSession *ss = ob->sculpt;
1307 
1308   if (ss->bm) {
1309     if (ob->data) {
1310       BMIter iter;
1311       BMFace *efa;
1312       BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
1313         BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading);
1314       }
1315       if (reorder) {
1316         BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
1317       }
1318       BM_mesh_bm_to_me(NULL,
1319                        ss->bm,
1320                        ob->data,
1321                        (&(struct BMeshToMeshParams){
1322                            .calc_object_remap = false,
1323                        }));
1324     }
1325   }
1326 }
1327 
BKE_sculptsession_bm_to_me(Object * ob,bool reorder)1328 void BKE_sculptsession_bm_to_me(Object *ob, bool reorder)
1329 {
1330   if (ob && ob->sculpt) {
1331     sculptsession_bm_to_me_update_data_only(ob, reorder);
1332 
1333     /* Ensure the objects evaluated mesh doesn't hold onto arrays
1334      * now realloc'd in the mesh T34473. */
1335     DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1336   }
1337 }
1338 
sculptsession_free_pbvh(Object * object)1339 static void sculptsession_free_pbvh(Object *object)
1340 {
1341   SculptSession *ss = object->sculpt;
1342 
1343   if (!ss) {
1344     return;
1345   }
1346 
1347   if (ss->pbvh) {
1348     BKE_pbvh_free(ss->pbvh);
1349     ss->pbvh = NULL;
1350   }
1351 
1352   MEM_SAFE_FREE(ss->pmap);
1353   MEM_SAFE_FREE(ss->pmap_mem);
1354 
1355   MEM_SAFE_FREE(ss->persistent_base);
1356 
1357   MEM_SAFE_FREE(ss->preview_vert_index_list);
1358   ss->preview_vert_index_count = 0;
1359 
1360   MEM_SAFE_FREE(ss->preview_vert_index_list);
1361 
1362   MEM_SAFE_FREE(ss->vertex_info.connected_component);
1363   MEM_SAFE_FREE(ss->vertex_info.boundary);
1364 
1365   MEM_SAFE_FREE(ss->fake_neighbors.fake_neighbor_index);
1366 }
1367 
BKE_sculptsession_bm_to_me_for_render(Object * object)1368 void BKE_sculptsession_bm_to_me_for_render(Object *object)
1369 {
1370   if (object && object->sculpt) {
1371     if (object->sculpt->bm) {
1372       /* Ensure no points to old arrays are stored in DM
1373        *
1374        * Apparently, we could not use DEG_id_tag_update
1375        * here because this will lead to the while object
1376        * surface to disappear, so we'll release DM in place.
1377        */
1378       BKE_object_free_derived_caches(object);
1379 
1380       sculptsession_bm_to_me_update_data_only(object, false);
1381 
1382       /* In contrast with sculptsession_bm_to_me no need in
1383        * DAG tag update here - derived mesh was freed and
1384        * old pointers are nowhere stored.
1385        */
1386     }
1387   }
1388 }
1389 
BKE_sculptsession_free(Object * ob)1390 void BKE_sculptsession_free(Object *ob)
1391 {
1392   if (ob && ob->sculpt) {
1393     SculptSession *ss = ob->sculpt;
1394 
1395     if (ss->bm) {
1396       BKE_sculptsession_bm_to_me(ob, true);
1397       BM_mesh_free(ss->bm);
1398     }
1399 
1400     sculptsession_free_pbvh(ob);
1401 
1402     MEM_SAFE_FREE(ss->pmap);
1403     MEM_SAFE_FREE(ss->pmap_mem);
1404     if (ss->bm_log) {
1405       BM_log_free(ss->bm_log);
1406     }
1407 
1408     MEM_SAFE_FREE(ss->texcache);
1409 
1410     if (ss->tex_pool) {
1411       BKE_image_pool_free(ss->tex_pool);
1412     }
1413 
1414     MEM_SAFE_FREE(ss->orig_cos);
1415     MEM_SAFE_FREE(ss->deform_cos);
1416     MEM_SAFE_FREE(ss->deform_imats);
1417 
1418     if (ss->pose_ik_chain_preview) {
1419       for (int i = 0; i < ss->pose_ik_chain_preview->tot_segments; i++) {
1420         MEM_SAFE_FREE(ss->pose_ik_chain_preview->segments[i].weights);
1421       }
1422       MEM_SAFE_FREE(ss->pose_ik_chain_preview->segments);
1423       MEM_SAFE_FREE(ss->pose_ik_chain_preview);
1424     }
1425 
1426     BKE_sculptsession_free_vwpaint_data(ob->sculpt);
1427 
1428     MEM_freeN(ss);
1429 
1430     ob->sculpt = NULL;
1431   }
1432 }
1433 
1434 /* Sculpt mode handles multires differently from regular meshes, but only if
1435  * it's the last modifier on the stack and it is not on the first level */
BKE_sculpt_multires_active(Scene * scene,Object * ob)1436 MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob)
1437 {
1438   Mesh *me = (Mesh *)ob->data;
1439   ModifierData *md;
1440   VirtualModifierData virtualModifierData;
1441 
1442   if (ob->sculpt && ob->sculpt->bm) {
1443     /* can't combine multires and dynamic topology */
1444     return NULL;
1445   }
1446 
1447   if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) {
1448     /* multires can't work without displacement layer */
1449     return NULL;
1450   }
1451 
1452   /* Weight paint operates on original vertices, and needs to treat multires as regular modifier
1453    * to make it so that PBVH vertices are at the multires surface. */
1454   if ((ob->mode & OB_MODE_SCULPT) == 0) {
1455     return NULL;
1456   }
1457 
1458   for (md = BKE_modifiers_get_virtual_modifierlist(ob, &virtualModifierData); md; md = md->next) {
1459     if (md->type == eModifierType_Multires) {
1460       MultiresModifierData *mmd = (MultiresModifierData *)md;
1461 
1462       if (!BKE_modifier_is_enabled(scene, md, eModifierMode_Realtime)) {
1463         continue;
1464       }
1465 
1466       if (mmd->sculptlvl > 0 && !(mmd->flags & eMultiresModifierFlag_UseSculptBaseMesh)) {
1467         return mmd;
1468       }
1469 
1470       return NULL;
1471     }
1472   }
1473 
1474   return NULL;
1475 }
1476 
1477 /* Checks if there are any supported deformation modifiers active */
sculpt_modifiers_active(Scene * scene,Sculpt * sd,Object * ob)1478 static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob)
1479 {
1480   ModifierData *md;
1481   Mesh *me = (Mesh *)ob->data;
1482   VirtualModifierData virtualModifierData;
1483 
1484   if (ob->sculpt->bm || BKE_sculpt_multires_active(scene, ob)) {
1485     return false;
1486   }
1487 
1488   /* non-locked shape keys could be handled in the same way as deformed mesh */
1489   if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr) {
1490     return true;
1491   }
1492 
1493   md = BKE_modifiers_get_virtual_modifierlist(ob, &virtualModifierData);
1494 
1495   /* exception for shape keys because we can edit those */
1496   for (; md; md = md->next) {
1497     const ModifierTypeInfo *mti = BKE_modifier_get_info(md->type);
1498     if (!BKE_modifier_is_enabled(scene, md, eModifierMode_Realtime)) {
1499       continue;
1500     }
1501     if (md->type == eModifierType_Multires && (ob->mode & OB_MODE_SCULPT)) {
1502       MultiresModifierData *mmd = (MultiresModifierData *)md;
1503       if (!(mmd->flags & eMultiresModifierFlag_UseSculptBaseMesh)) {
1504         continue;
1505       }
1506     }
1507     if (md->type == eModifierType_ShapeKey) {
1508       continue;
1509     }
1510 
1511     if (mti->type == eModifierTypeType_OnlyDeform) {
1512       return true;
1513     }
1514     if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) {
1515       return true;
1516     }
1517   }
1518 
1519   return false;
1520 }
1521 
1522 /**
1523  * \param need_mask: So that the evaluated mesh that is returned has mask data.
1524  */
sculpt_update_object(Depsgraph * depsgraph,Object * ob,Mesh * me_eval,bool need_pmap,bool need_mask,bool UNUSED (need_colors))1525 static void sculpt_update_object(Depsgraph *depsgraph,
1526                                  Object *ob,
1527                                  Mesh *me_eval,
1528                                  bool need_pmap,
1529                                  bool need_mask,
1530                                  bool UNUSED(need_colors))
1531 {
1532   Scene *scene = DEG_get_input_scene(depsgraph);
1533   Sculpt *sd = scene->toolsettings->sculpt;
1534   SculptSession *ss = ob->sculpt;
1535   Mesh *me = BKE_object_get_original_mesh(ob);
1536   MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
1537   const bool use_face_sets = (ob->mode & OB_MODE_SCULPT) != 0;
1538 
1539   ss->depsgraph = depsgraph;
1540 
1541   ss->deform_modifiers_active = sculpt_modifiers_active(scene, sd, ob);
1542   ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0;
1543   ss->show_face_sets = (sd->flags & SCULPT_HIDE_FACE_SETS) == 0;
1544 
1545   ss->building_vp_handle = false;
1546 
1547   ss->scene = scene;
1548 
1549   if (need_mask) {
1550     if (mmd == NULL) {
1551       if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) {
1552         BKE_sculpt_mask_layers_ensure(ob, NULL);
1553       }
1554     }
1555     else {
1556       if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
1557         BKE_sculpt_mask_layers_ensure(ob, mmd);
1558       }
1559     }
1560   }
1561 
1562   /* tessfaces aren't used and will become invalid */
1563   BKE_mesh_tessface_clear(me);
1564 
1565   ss->shapekey_active = (mmd == NULL) ? BKE_keyblock_from_object(ob) : NULL;
1566 
1567   /* NOTE: Weight pPaint require mesh info for loop lookup, but it never uses multires code path,
1568    * so no extra checks is needed here. */
1569   if (mmd) {
1570     ss->multires.active = true;
1571     ss->multires.modifier = mmd;
1572     ss->multires.level = mmd->sculptlvl;
1573     ss->totvert = me_eval->totvert;
1574     ss->totpoly = me_eval->totpoly;
1575     ss->totfaces = me->totpoly;
1576 
1577     /* These are assigned to the base mesh in Multires. This is needed because Face Sets operators
1578      * and tools use the Face Sets data from the base mesh when Multires is active. */
1579     ss->mvert = me->mvert;
1580     ss->mpoly = me->mpoly;
1581     ss->mloop = me->mloop;
1582   }
1583   else {
1584     ss->totvert = me->totvert;
1585     ss->totpoly = me->totpoly;
1586     ss->totfaces = me->totpoly;
1587     ss->mvert = me->mvert;
1588     ss->mpoly = me->mpoly;
1589     ss->mloop = me->mloop;
1590     ss->multires.active = false;
1591     ss->multires.modifier = NULL;
1592     ss->multires.level = 0;
1593     ss->vmask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
1594     ss->vcol = CustomData_get_layer(&me->vdata, CD_PROP_COLOR);
1595   }
1596 
1597   /* Sculpt Face Sets. */
1598   if (use_face_sets) {
1599     if (!CustomData_has_layer(&me->pdata, CD_SCULPT_FACE_SETS)) {
1600       /* By checking here if the data-layer already exist this avoids copying the visibility from
1601        * the mesh and looping over all vertices on every sculpt editing operation, using this
1602        * function only the first time the Face Sets data-layer needs to be created. */
1603       BKE_sculpt_face_sets_ensure_from_base_mesh_visibility(me);
1604     }
1605     ss->face_sets = CustomData_get_layer(&me->pdata, CD_SCULPT_FACE_SETS);
1606   }
1607   else {
1608     ss->face_sets = NULL;
1609   }
1610 
1611   ss->subdiv_ccg = me_eval->runtime.subdiv_ccg;
1612 
1613   PBVH *pbvh = BKE_sculpt_object_pbvh_ensure(depsgraph, ob);
1614   BLI_assert(pbvh == ss->pbvh);
1615   UNUSED_VARS_NDEBUG(pbvh);
1616 
1617   BKE_pbvh_subdiv_cgg_set(ss->pbvh, ss->subdiv_ccg);
1618   BKE_pbvh_face_sets_set(ss->pbvh, ss->face_sets);
1619 
1620   BKE_pbvh_face_sets_color_set(ss->pbvh, me->face_sets_color_seed, me->face_sets_color_default);
1621 
1622   if (need_pmap && ob->type == OB_MESH && !ss->pmap) {
1623     BKE_mesh_vert_poly_map_create(
1624         &ss->pmap, &ss->pmap_mem, me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
1625   }
1626 
1627   pbvh_show_mask_set(ss->pbvh, ss->show_mask);
1628   pbvh_show_face_sets_set(ss->pbvh, ss->show_face_sets);
1629 
1630   if (ss->deform_modifiers_active) {
1631     if (!ss->orig_cos) {
1632       int a;
1633 
1634       BKE_sculptsession_free_deformMats(ss);
1635 
1636       ss->orig_cos = (ss->shapekey_active) ?
1637                          BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active) :
1638                          BKE_mesh_vert_coords_alloc(me, NULL);
1639 
1640       BKE_crazyspace_build_sculpt(depsgraph, scene, ob, &ss->deform_imats, &ss->deform_cos);
1641       BKE_pbvh_vert_coords_apply(ss->pbvh, ss->deform_cos, me->totvert);
1642 
1643       for (a = 0; a < me->totvert; a++) {
1644         invert_m3(ss->deform_imats[a]);
1645       }
1646     }
1647   }
1648   else {
1649     BKE_sculptsession_free_deformMats(ss);
1650   }
1651 
1652   if (ss->shapekey_active != NULL && ss->deform_cos == NULL) {
1653     ss->deform_cos = BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active);
1654   }
1655 
1656   /* if pbvh is deformed, key block is already applied to it */
1657   if (ss->shapekey_active) {
1658     bool pbvh_deformed = BKE_pbvh_is_deformed(ss->pbvh);
1659     if (!pbvh_deformed || ss->deform_cos == NULL) {
1660       float(*vertCos)[3] = BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active);
1661 
1662       if (vertCos) {
1663         if (!pbvh_deformed) {
1664           /* apply shape keys coordinates to PBVH */
1665           BKE_pbvh_vert_coords_apply(ss->pbvh, vertCos, me->totvert);
1666         }
1667         if (ss->deform_cos == NULL) {
1668           ss->deform_cos = vertCos;
1669         }
1670         if (vertCos != ss->deform_cos) {
1671           MEM_freeN(vertCos);
1672         }
1673       }
1674     }
1675   }
1676 }
1677 
BKE_sculpt_update_object_before_eval(Object * ob)1678 void BKE_sculpt_update_object_before_eval(Object *ob)
1679 {
1680   /* Update before mesh evaluation in the dependency graph. */
1681   SculptSession *ss = ob->sculpt;
1682 
1683   if (ss && ss->building_vp_handle == false) {
1684     if (!ss->cache && !ss->filter_cache) {
1685       /* We free pbvh on changes, except in the middle of drawing a stroke
1686        * since it can't deal with changing PVBH node organization, we hope
1687        * topology does not change in the meantime .. weak. */
1688       sculptsession_free_pbvh(ob);
1689 
1690       BKE_sculptsession_free_deformMats(ob->sculpt);
1691 
1692       /* In vertex/weight paint, force maps to be rebuilt. */
1693       BKE_sculptsession_free_vwpaint_data(ob->sculpt);
1694     }
1695     else {
1696       PBVHNode **nodes;
1697       int n, totnode;
1698 
1699       BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
1700 
1701       for (n = 0; n < totnode; n++) {
1702         BKE_pbvh_node_mark_update(nodes[n]);
1703       }
1704 
1705       MEM_freeN(nodes);
1706     }
1707   }
1708 }
1709 
BKE_sculpt_update_object_after_eval(Depsgraph * depsgraph,Object * ob_eval)1710 void BKE_sculpt_update_object_after_eval(Depsgraph *depsgraph, Object *ob_eval)
1711 {
1712   /* Update after mesh evaluation in the dependency graph, to rebuild PBVH or
1713    * other data when modifiers change the mesh. */
1714   Object *ob_orig = DEG_get_original_object(ob_eval);
1715   Mesh *me_eval = BKE_object_get_evaluated_mesh(ob_eval);
1716 
1717   BLI_assert(me_eval != NULL);
1718   sculpt_update_object(depsgraph, ob_orig, me_eval, false, false, false);
1719 }
1720 
BKE_sculpt_color_layer_create_if_needed(struct Object * object)1721 void BKE_sculpt_color_layer_create_if_needed(struct Object *object)
1722 {
1723   Mesh *orig_me = BKE_object_get_original_mesh(object);
1724   if (!U.experimental.use_sculpt_vertex_colors) {
1725     return;
1726   }
1727 
1728   if (CustomData_has_layer(&orig_me->vdata, CD_PROP_COLOR)) {
1729     return;
1730   }
1731 
1732   CustomData_add_layer(&orig_me->vdata, CD_PROP_COLOR, CD_DEFAULT, NULL, orig_me->totvert);
1733   BKE_mesh_update_customdata_pointers(orig_me, true);
1734   DEG_id_tag_update(&orig_me->id, ID_RECALC_GEOMETRY);
1735 }
1736 
BKE_sculpt_update_object_for_edit(Depsgraph * depsgraph,Object * ob_orig,bool need_pmap,bool need_mask,bool need_colors)1737 void BKE_sculpt_update_object_for_edit(
1738     Depsgraph *depsgraph, Object *ob_orig, bool need_pmap, bool need_mask, bool need_colors)
1739 {
1740   /* Update from sculpt operators and undo, to update sculpt session
1741    * and PBVH after edits. */
1742   Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
1743   Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob_orig);
1744   Mesh *me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH);
1745 
1746   BLI_assert(ob_orig == DEG_get_original_object(ob_orig));
1747 
1748   sculpt_update_object(depsgraph, ob_orig, me_eval, need_pmap, need_mask, need_colors);
1749 }
1750 
BKE_sculpt_mask_layers_ensure(Object * ob,MultiresModifierData * mmd)1751 int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
1752 {
1753   const float *paint_mask;
1754   Mesh *me = ob->data;
1755   int ret = 0;
1756 
1757   paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK);
1758 
1759   /* if multires is active, create a grid paint mask layer if there
1760    * isn't one already */
1761   if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
1762     GridPaintMask *gmask;
1763     int level = max_ii(1, mmd->sculptlvl);
1764     int gridsize = BKE_ccg_gridsize(level);
1765     int gridarea = gridsize * gridsize;
1766     int i, j;
1767 
1768     gmask = CustomData_add_layer(&me->ldata, CD_GRID_PAINT_MASK, CD_CALLOC, NULL, me->totloop);
1769 
1770     for (i = 0; i < me->totloop; i++) {
1771       GridPaintMask *gpm = &gmask[i];
1772 
1773       gpm->level = level;
1774       gpm->data = MEM_callocN(sizeof(float) * gridarea, "GridPaintMask.data");
1775     }
1776 
1777     /* if vertices already have mask, copy into multires data */
1778     if (paint_mask) {
1779       for (i = 0; i < me->totpoly; i++) {
1780         const MPoly *p = &me->mpoly[i];
1781         float avg = 0;
1782 
1783         /* mask center */
1784         for (j = 0; j < p->totloop; j++) {
1785           const MLoop *l = &me->mloop[p->loopstart + j];
1786           avg += paint_mask[l->v];
1787         }
1788         avg /= (float)p->totloop;
1789 
1790         /* fill in multires mask corner */
1791         for (j = 0; j < p->totloop; j++) {
1792           GridPaintMask *gpm = &gmask[p->loopstart + j];
1793           const MLoop *l = &me->mloop[p->loopstart + j];
1794           const MLoop *prev = ME_POLY_LOOP_PREV(me->mloop, p, j);
1795           const MLoop *next = ME_POLY_LOOP_NEXT(me->mloop, p, j);
1796 
1797           gpm->data[0] = avg;
1798           gpm->data[1] = (paint_mask[l->v] + paint_mask[next->v]) * 0.5f;
1799           gpm->data[2] = (paint_mask[l->v] + paint_mask[prev->v]) * 0.5f;
1800           gpm->data[3] = paint_mask[l->v];
1801         }
1802       }
1803     }
1804 
1805     ret |= SCULPT_MASK_LAYER_CALC_LOOP;
1806   }
1807 
1808   /* create vertex paint mask layer if there isn't one already */
1809   if (!paint_mask) {
1810     CustomData_add_layer(&me->vdata, CD_PAINT_MASK, CD_CALLOC, NULL, me->totvert);
1811     ret |= SCULPT_MASK_LAYER_CALC_VERT;
1812   }
1813 
1814   return ret;
1815 }
1816 
BKE_sculpt_toolsettings_data_ensure(struct Scene * scene)1817 void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene)
1818 {
1819   BKE_paint_ensure(scene->toolsettings, (Paint **)&scene->toolsettings->sculpt);
1820 
1821   Sculpt *sd = scene->toolsettings->sculpt;
1822   if (!sd->detail_size) {
1823     sd->detail_size = 12;
1824   }
1825   if (!sd->detail_percent) {
1826     sd->detail_percent = 25;
1827   }
1828   if (sd->constant_detail == 0.0f) {
1829     sd->constant_detail = 3.0f;
1830   }
1831 
1832   /* Set sane default tiling offsets */
1833   if (!sd->paint.tile_offset[0]) {
1834     sd->paint.tile_offset[0] = 1.0f;
1835   }
1836   if (!sd->paint.tile_offset[1]) {
1837     sd->paint.tile_offset[1] = 1.0f;
1838   }
1839   if (!sd->paint.tile_offset[2]) {
1840     sd->paint.tile_offset[2] = 1.0f;
1841   }
1842 }
1843 
check_sculpt_object_deformed(Object * object,const bool for_construction)1844 static bool check_sculpt_object_deformed(Object *object, const bool for_construction)
1845 {
1846   bool deformed = false;
1847 
1848   /* Active modifiers means extra deformation, which can't be handled correct
1849    * on birth of PBVH and sculpt "layer" levels, so use PBVH only for internal brush
1850    * stuff and show final evaluated mesh so user would see actual object shape.
1851    */
1852   deformed |= object->sculpt->deform_modifiers_active;
1853 
1854   if (for_construction) {
1855     deformed |= object->sculpt->shapekey_active != NULL;
1856   }
1857   else {
1858     /* As in case with modifiers, we can't synchronize deformation made against
1859      * PBVH and non-locked keyblock, so also use PBVH only for brushes and
1860      * final DM to give final result to user.
1861      */
1862     deformed |= object->sculpt->shapekey_active && (object->shapeflag & OB_SHAPE_LOCK) == 0;
1863   }
1864 
1865   return deformed;
1866 }
1867 
BKE_sculpt_face_sets_ensure_from_base_mesh_visibility(Mesh * mesh)1868 void BKE_sculpt_face_sets_ensure_from_base_mesh_visibility(Mesh *mesh)
1869 {
1870   const int face_sets_default_visible_id = 1;
1871   const int face_sets_default_hidden_id = -(face_sets_default_visible_id + 1);
1872 
1873   bool initialize_new_face_sets = false;
1874 
1875   if (CustomData_has_layer(&mesh->pdata, CD_SCULPT_FACE_SETS)) {
1876     /* Make everything visible. */
1877     int *current_face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS);
1878     for (int i = 0; i < mesh->totpoly; i++) {
1879       current_face_sets[i] = abs(current_face_sets[i]);
1880     }
1881   }
1882   else {
1883     initialize_new_face_sets = true;
1884     int *new_face_sets = CustomData_add_layer(
1885         &mesh->pdata, CD_SCULPT_FACE_SETS, CD_CALLOC, NULL, mesh->totpoly);
1886 
1887     /* Initialize the new Face Set data-layer with a default valid visible ID and set the default
1888      * color to render it white. */
1889     for (int i = 0; i < mesh->totpoly; i++) {
1890       new_face_sets[i] = face_sets_default_visible_id;
1891     }
1892     mesh->face_sets_color_default = face_sets_default_visible_id;
1893   }
1894 
1895   int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS);
1896 
1897   for (int i = 0; i < mesh->totpoly; i++) {
1898     if (!(mesh->mpoly[i].flag & ME_HIDE)) {
1899       continue;
1900     }
1901 
1902     if (initialize_new_face_sets) {
1903       /* When initializing a new Face Set data-layer, assign a new hidden Face Set ID to hidden
1904        * vertices. This way, we get at initial split in two Face Sets between hidden and
1905        * visible vertices based on the previous mesh visibly from other mode that can be
1906        * useful in some cases. */
1907       face_sets[i] = face_sets_default_hidden_id;
1908     }
1909     else {
1910       /* Otherwise, set the already existing Face Set ID to hidden. */
1911       face_sets[i] = -abs(face_sets[i]);
1912     }
1913   }
1914 }
1915 
BKE_sculpt_sync_face_sets_visibility_to_base_mesh(Mesh * mesh)1916 void BKE_sculpt_sync_face_sets_visibility_to_base_mesh(Mesh *mesh)
1917 {
1918   int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS);
1919   if (!face_sets) {
1920     return;
1921   }
1922 
1923   for (int i = 0; i < mesh->totpoly; i++) {
1924     const bool is_face_set_visible = face_sets[i] >= 0;
1925     SET_FLAG_FROM_TEST(mesh->mpoly[i].flag, !is_face_set_visible, ME_HIDE);
1926   }
1927 
1928   BKE_mesh_flush_hidden_from_polys(mesh);
1929 }
1930 
BKE_sculpt_sync_face_sets_visibility_to_grids(Mesh * mesh,SubdivCCG * subdiv_ccg)1931 void BKE_sculpt_sync_face_sets_visibility_to_grids(Mesh *mesh, SubdivCCG *subdiv_ccg)
1932 {
1933   int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS);
1934   if (!face_sets) {
1935     return;
1936   }
1937 
1938   if (!subdiv_ccg) {
1939     return;
1940   }
1941 
1942   CCGKey key;
1943   BKE_subdiv_ccg_key_top_level(&key, subdiv_ccg);
1944   for (int i = 0; i < mesh->totloop; i++) {
1945     const int face_index = BKE_subdiv_ccg_grid_to_face_index(subdiv_ccg, i);
1946     const bool is_hidden = (face_sets[face_index] < 0);
1947 
1948     /* Avoid creating and modifying the grid_hidden bitmap if the base mesh face is visible and
1949      * there is not bitmap for the grid. This is because missing grid_hidden implies grid is fully
1950      * visible. */
1951     if (is_hidden) {
1952       BKE_subdiv_ccg_grid_hidden_ensure(subdiv_ccg, i);
1953     }
1954 
1955     BLI_bitmap *gh = subdiv_ccg->grid_hidden[i];
1956     if (gh) {
1957       BLI_bitmap_set_all(gh, is_hidden, key.grid_area);
1958     }
1959   }
1960 }
1961 
BKE_sculpt_sync_face_set_visibility(struct Mesh * mesh,struct SubdivCCG * subdiv_ccg)1962 void BKE_sculpt_sync_face_set_visibility(struct Mesh *mesh, struct SubdivCCG *subdiv_ccg)
1963 {
1964   BKE_sculpt_face_sets_ensure_from_base_mesh_visibility(mesh);
1965   BKE_sculpt_sync_face_sets_visibility_to_base_mesh(mesh);
1966   BKE_sculpt_sync_face_sets_visibility_to_grids(mesh, subdiv_ccg);
1967 }
1968 
build_pbvh_for_dynamic_topology(Object * ob)1969 static PBVH *build_pbvh_for_dynamic_topology(Object *ob)
1970 {
1971   PBVH *pbvh = BKE_pbvh_new();
1972   BKE_pbvh_build_bmesh(pbvh,
1973                        ob->sculpt->bm,
1974                        ob->sculpt->bm_smooth_shading,
1975                        ob->sculpt->bm_log,
1976                        ob->sculpt->cd_vert_node_offset,
1977                        ob->sculpt->cd_face_node_offset);
1978   pbvh_show_mask_set(pbvh, ob->sculpt->show_mask);
1979   pbvh_show_face_sets_set(pbvh, false);
1980   return pbvh;
1981 }
1982 
build_pbvh_from_regular_mesh(Object * ob,Mesh * me_eval_deform,bool respect_hide)1983 static PBVH *build_pbvh_from_regular_mesh(Object *ob, Mesh *me_eval_deform, bool respect_hide)
1984 {
1985   Mesh *me = BKE_object_get_original_mesh(ob);
1986   const int looptris_num = poly_to_tri_count(me->totpoly, me->totloop);
1987   PBVH *pbvh = BKE_pbvh_new();
1988   BKE_pbvh_respect_hide_set(pbvh, respect_hide);
1989 
1990   MLoopTri *looptri = MEM_malloc_arrayN(looptris_num, sizeof(*looptri), __func__);
1991 
1992   BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, looptri);
1993 
1994   BKE_sculpt_sync_face_set_visibility(me, NULL);
1995 
1996   BKE_pbvh_build_mesh(pbvh,
1997                       me,
1998                       me->mpoly,
1999                       me->mloop,
2000                       me->mvert,
2001                       me->totvert,
2002                       &me->vdata,
2003                       &me->ldata,
2004                       &me->pdata,
2005                       looptri,
2006                       looptris_num);
2007 
2008   pbvh_show_mask_set(pbvh, ob->sculpt->show_mask);
2009   pbvh_show_face_sets_set(pbvh, ob->sculpt->show_face_sets);
2010 
2011   const bool is_deformed = check_sculpt_object_deformed(ob, true);
2012   if (is_deformed && me_eval_deform != NULL) {
2013     int totvert;
2014     float(*v_cos)[3] = BKE_mesh_vert_coords_alloc(me_eval_deform, &totvert);
2015     BKE_pbvh_vert_coords_apply(pbvh, v_cos, totvert);
2016     MEM_freeN(v_cos);
2017   }
2018 
2019   return pbvh;
2020 }
2021 
build_pbvh_from_ccg(Object * ob,SubdivCCG * subdiv_ccg,bool respect_hide)2022 static PBVH *build_pbvh_from_ccg(Object *ob, SubdivCCG *subdiv_ccg, bool respect_hide)
2023 {
2024   CCGKey key;
2025   BKE_subdiv_ccg_key_top_level(&key, subdiv_ccg);
2026   PBVH *pbvh = BKE_pbvh_new();
2027   BKE_pbvh_respect_hide_set(pbvh, respect_hide);
2028 
2029   Mesh *base_mesh = BKE_mesh_from_object(ob);
2030   BKE_sculpt_sync_face_set_visibility(base_mesh, subdiv_ccg);
2031 
2032   BKE_pbvh_build_grids(pbvh,
2033                        subdiv_ccg->grids,
2034                        subdiv_ccg->num_grids,
2035                        &key,
2036                        (void **)subdiv_ccg->grid_faces,
2037                        subdiv_ccg->grid_flag_mats,
2038                        subdiv_ccg->grid_hidden);
2039   pbvh_show_mask_set(pbvh, ob->sculpt->show_mask);
2040   pbvh_show_face_sets_set(pbvh, ob->sculpt->show_face_sets);
2041   return pbvh;
2042 }
2043 
BKE_sculpt_object_pbvh_ensure(Depsgraph * depsgraph,Object * ob)2044 PBVH *BKE_sculpt_object_pbvh_ensure(Depsgraph *depsgraph, Object *ob)
2045 {
2046   if (ob == NULL || ob->sculpt == NULL) {
2047     return NULL;
2048   }
2049 
2050   bool respect_hide = true;
2051   if (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
2052     if (!(BKE_paint_select_vert_test(ob) || BKE_paint_select_face_test(ob))) {
2053       respect_hide = false;
2054     }
2055   }
2056 
2057   PBVH *pbvh = ob->sculpt->pbvh;
2058   if (pbvh != NULL) {
2059     /* NOTE: It is possible that grids were re-allocated due to modifier
2060      * stack. Need to update those pointers. */
2061     if (BKE_pbvh_type(pbvh) == PBVH_GRIDS) {
2062       Object *object_eval = DEG_get_evaluated_object(depsgraph, ob);
2063       Mesh *mesh_eval = object_eval->data;
2064       SubdivCCG *subdiv_ccg = mesh_eval->runtime.subdiv_ccg;
2065       if (subdiv_ccg != NULL) {
2066         BKE_sculpt_bvh_update_from_ccg(pbvh, subdiv_ccg);
2067       }
2068     }
2069     return pbvh;
2070   }
2071 
2072   if (ob->sculpt->bm != NULL) {
2073     /* Sculpting on a BMesh (dynamic-topology) gets a special PBVH. */
2074     pbvh = build_pbvh_for_dynamic_topology(ob);
2075   }
2076   else {
2077     Object *object_eval = DEG_get_evaluated_object(depsgraph, ob);
2078     Mesh *mesh_eval = object_eval->data;
2079     if (mesh_eval->runtime.subdiv_ccg != NULL) {
2080       pbvh = build_pbvh_from_ccg(ob, mesh_eval->runtime.subdiv_ccg, respect_hide);
2081     }
2082     else if (ob->type == OB_MESH) {
2083       Mesh *me_eval_deform = object_eval->runtime.mesh_deform_eval;
2084       pbvh = build_pbvh_from_regular_mesh(ob, me_eval_deform, respect_hide);
2085     }
2086   }
2087 
2088   ob->sculpt->pbvh = pbvh;
2089   return pbvh;
2090 }
2091 
BKE_sculpt_bvh_update_from_ccg(PBVH * pbvh,SubdivCCG * subdiv_ccg)2092 void BKE_sculpt_bvh_update_from_ccg(PBVH *pbvh, SubdivCCG *subdiv_ccg)
2093 {
2094   BKE_pbvh_grids_update(pbvh,
2095                         subdiv_ccg->grids,
2096                         (void **)subdiv_ccg->grid_faces,
2097                         subdiv_ccg->grid_flag_mats,
2098                         subdiv_ccg->grid_hidden);
2099 }
2100 
2101 /* Test if PBVH can be used directly for drawing, which is faster than
2102  * drawing the mesh and all updates that come with it. */
BKE_sculptsession_use_pbvh_draw(const Object * ob,const View3D * v3d)2103 bool BKE_sculptsession_use_pbvh_draw(const Object *ob, const View3D *v3d)
2104 {
2105   SculptSession *ss = ob->sculpt;
2106   if (ss == NULL || ss->pbvh == NULL || ss->mode_type != OB_MODE_SCULPT) {
2107     return false;
2108   }
2109 
2110   if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) {
2111     /* Regular mesh only draws from PBVH without modifiers and shape keys. */
2112     const bool full_shading = (v3d && (v3d->shading.type > OB_SOLID));
2113     return !(ss->shapekey_active || ss->deform_modifiers_active || full_shading);
2114   }
2115 
2116   /* Multires and dyntopo always draw directly from the PBVH. */
2117   return true;
2118 }
2119 
2120 /* Returns the Face Set random color for rendering in the overlay given its ID and a color seed. */
2121 #define GOLDEN_RATIO_CONJUGATE 0.618033988749895f
BKE_paint_face_set_overlay_color_get(const int face_set,const int seed,uchar r_color[4])2122 void BKE_paint_face_set_overlay_color_get(const int face_set, const int seed, uchar r_color[4])
2123 {
2124   float rgba[4];
2125   float random_mod_hue = GOLDEN_RATIO_CONJUGATE * (abs(face_set) + (seed % 10));
2126   random_mod_hue = random_mod_hue - floorf(random_mod_hue);
2127   const float random_mod_sat = BLI_hash_int_01(abs(face_set) + seed + 1);
2128   const float random_mod_val = BLI_hash_int_01(abs(face_set) + seed + 2);
2129   hsv_to_rgb(random_mod_hue,
2130              0.6f + (random_mod_sat * 0.25f),
2131              1.0f - (random_mod_val * 0.35f),
2132              &rgba[0],
2133              &rgba[1],
2134              &rgba[2]);
2135   rgba_float_to_uchar(r_color, rgba);
2136 }
2137