Blender V5.3
grease_pencil_carver.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BKE_brush.hh"
10#include "BKE_context.hh"
11#include "BKE_crazyspace.hh"
13#include "BKE_material.hh"
14#include "BKE_paint.hh"
15
17
18#include "ED_curves.hh"
19#include "ED_grease_pencil.hh"
20#include "ED_view3d.hh"
21
22#include "BLI_bounds.hh"
23
24#include "DNA_brush_types.h"
25#include "DNA_material_types.h"
27
28#include "WM_api.hh"
29
31#include "GEO_smooth_curves.hh"
32
33namespace blender {
34
35namespace ed::greasepencil {
36
40static bool execute_carver_on_drawing(const Object &ob_eval,
41 Object &obact,
42 const ARegion &region,
43 const float4x4 &projection,
44 const int layer_index,
45 const float4x4 &layer_to_world,
46 const DrawingPlacement &placement,
47 const Span<float2> mcoords,
48 const bool keep_caps,
50 bool *r_converted)
51{
52 const bke::CurvesGeometry &src = drawing.strokes();
53 const OffsetIndices<int> src_points_by_curve = src.points_by_curve();
54
55 /* Get evaluated geometry. */
58
59 const Span<float3> normals = drawing.curve_plane_normals();
60
61 Array<float4> curve_planes(src.curves_num());
62 threading::parallel_for(src.curves_range(), 4096, [&](const IndexRange src_curves) {
63 for (const int src_curve : src_curves) {
64 const float3 &normal = normals[src_curve];
65 const IndexRange points = src_points_by_curve[src_curve];
66 const float3 &point = deformation.positions[points.first()];
67 curve_planes[src_curve] = float4(normal, -math::dot(point, normal));
68 }
69 });
70
71 bke::CurvesGeometry input_curves = bke::CurvesGeometry(src);
72 input_curves.resize(src.points_num() + mcoords.size(), src.curves_num() + 1);
73 input_curves.offsets_for_write().last() = src.points_num() + mcoords.size();
74
75 bke::MutableAttributeAccessor attributes = input_curves.attributes_for_write();
76
77 placement.project(mcoords, input_curves.positions_for_write().take_back(mcoords.size()));
78
80 "fill_id", bke::AttrDomain::Curve);
81 fill_ids.span.last() = bke::greasepencil::get_next_available_fill_id(fill_ids.span.varray());
82
84 fill_ids.span.varray(), input_curves.curves_num());
85
86 fill_ids.finish();
87
88 const IndexRange clipping_points = IndexRange::from_begin_size(src.points_num(), mcoords.size());
89 const IndexRange clipping_curves = IndexRange::from_single(src.curves_num());
90
91 input_curves.fill_curve_types(clipping_curves, CURVE_TYPE_POLY);
92 input_curves.cyclic_for_write().last() = true;
93
94 /* Initialize the rest of the attributes with default values. */
98 clipping_points);
100 attributes,
102 bke::attribute_filter_from_skip_ref({"fill_id", "cyclic", "curve_type"}),
103 clipping_curves);
104
105 auto project_fn = [&](const float3 &position) {
106 return ED_view3d_project_float_v2_m4(&region, position, projection);
107 };
108
109 /* WORKAROUND. Currently only poly curves are supported. Convert any curve close to the clipping
110 * shape to poly. */
111 if (!input_curves.is_single_type(CURVE_TYPE_POLY)) {
112 const OffsetIndices<int> points_by_curve = input_curves.points_by_curve();
113 Array<float2> src_positions_2d(input_curves.points_num());
114 const Span<float3> positions = input_curves.positions();
115 for (const int i : input_curves.points_range()) {
116 src_positions_2d[i] = project_fn(positions[i]);
117 }
118
119 Array<Bounds<float2>> screen_space_bbox(input_curves.curves_num());
120 threading::parallel_for(points_by_curve.index_range(), 512, [&](const IndexRange curves_i) {
121 for (const int curve_i : curves_i) {
122 const IndexRange points_i = points_by_curve[curve_i];
123 screen_space_bbox[curve_i] = *bounds::min_max(src_positions_2d.as_span().slice(points_i));
124 }
125 });
126
127 const VArray<int8_t> curve_types = input_curves.curve_types();
128
129 const Bounds<float2> bbox_j = screen_space_bbox.last();
130
131 IndexMaskMemory memory;
132 IndexMask curves_to_convert = IndexMask::from_predicate(
133 input_curves.curves_range(), memory, [&](const int64_t curve_i) {
134 const Bounds<float2> bbox_i = screen_space_bbox[curve_i];
135
136 /* Poly curve do not need to be converted. */
137 if (curve_types[curve_i] == CURVE_TYPE_POLY) {
138 return false;
139 }
140
141 if (bounds::intersect(bbox_i, bbox_j).has_value()) {
142 return true;
143 }
144 return false;
145 });
147 curves_to_convert, input_curves, bke::AttrDomain::Curve, memory);
148
149 if (!curves_to_convert.is_empty()) {
150 input_curves = geometry::resample_to_evaluated(input_curves, curves_to_convert);
151 *r_converted = true;
152 }
153 }
154
155 boolean::CurveBooleanOpParameters op_params;
156 op_params.boolean_mode = boolean::Operation::Difference;
157 op_params.keep_caps = keep_caps;
158 op_params.skip_clipping_attributes = true;
159 op_params.separate_islands = true;
160
161 const GroupedSpan<int> shapes = shapes_data.shapes();
162 const IndexRange clipping_shapes = IndexRange::from_single(shapes.size() - 1);
163
164 IndexMaskMemory memory;
165 const IndexMask editable_strokes = ed::greasepencil::retrieve_editable_strokes(
166 obact, drawing, layer_index, memory);
167 const IndexMask editable_shapes = bke::greasepencil::curves_mask_to_shapes(
168 editable_strokes, shapes, memory);
169
170 bke::CurvesGeometry carved_strokes = boolean::curve_boolean_with_planes(op_params,
171 input_curves,
172 project_fn,
173 shapes,
174 curve_planes,
175 editable_shapes,
176 clipping_shapes,
177 layer_to_world,
178 region);
179
180 /* Set the new geometry. */
181 drawing.strokes_for_write() = std::move(carved_strokes);
182 drawing.tag_topology_changed();
183
184 return true;
185}
186
191{
192 const Array<int2> mcoords = WM_gesture_lasso_path_to_array(C, op);
193
194 if (mcoords.is_empty()) {
196 }
197
198 const Scene *scene = CTX_data_scene(C);
199 const ARegion *region = CTX_wm_region(C);
200 const RegionView3D *rv3d = CTX_wm_region_view3d(C);
201 const Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C);
204 Object *ob_eval = DEG_get_evaluated(depsgraph, obact);
205
206 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(obact->data);
207
208 Array<float2> coords(mcoords.size());
209 threading::parallel_for(mcoords.index_range(), 4096, [&](const IndexRange i_range) {
210 for (const int i : i_range) {
211 coords[i] = float2(mcoords[i]);
212 }
213 });
214
215 Array<float2> lasso_pos(coords.size());
216 const int smooth_iterations = 4;
217 const float smooth_factor = 0.8f;
218 geometry::gaussian_blur_1D(coords.as_span(),
219 smooth_iterations,
220 VArray<float>::from_single(smooth_factor, coords.size()),
221 true,
222 true,
223 false,
224 lasso_pos.as_mutable_span());
225
228 if (brush->gpencil_settings == nullptr) {
230 }
231 const bool keep_caps = (brush->gpencil_settings->flag & GP_BRUSH_ERASER_KEEP_CAPS) != 0;
232 const bool active_layer_only = (brush->gpencil_settings->flag & GP_BRUSH_ACTIVE_LAYER_ONLY) != 0;
233 std::atomic<bool> changed = false;
234 std::atomic<bool> converted = false;
235
236 bool inserted_keyframe = false;
237 if (active_layer_only) {
238 /* Apply carver on drawings of active layer. */
239 if (!grease_pencil.has_active_layer()) {
240 return OPERATOR_CANCELLED;
241 }
242 bke::greasepencil::Layer &layer = *grease_pencil.get_active_layer();
243 if (!layer.is_editable()) {
244 return OPERATOR_CANCELLED;
245 }
246
247 ensure_active_keyframe(*scene, grease_pencil, layer, true, inserted_keyframe);
248 const float4x4 layer_to_world = layer.to_world_space(*ob_eval);
249 const float4x4 projection = ED_view3d_ob_project_mat_get_from_obmat(rv3d, layer_to_world);
250 const Vector<ed::greasepencil::MutableDrawingInfo> drawings =
251 ed::greasepencil::retrieve_editable_drawings_from_layer(*scene, grease_pencil, layer);
252
253 /* Initialize helper class for projecting screen space coordinates. */
254 DrawingPlacement placement = ed::greasepencil::DrawingPlacement(
255 *scene, *region, *view3d, *ob_eval, &layer);
256
257 threading::parallel_for_each(drawings, [&](const ed::greasepencil::MutableDrawingInfo &info) {
258 bool r_converted = false;
259 if (execute_carver_on_drawing(*ob_eval,
260 *obact,
261 *region,
262 projection,
263 info.layer_index,
264 layer_to_world,
265 placement,
266 lasso_pos.as_span(),
267 keep_caps,
268 info.drawing,
269 &r_converted))
270 {
271 changed = true;
272 }
273
274 if (r_converted) {
275 converted = true;
276 }
277 });
278 }
279 else {
280 for (bke::greasepencil::Layer *layer : grease_pencil.layers_for_write()) {
281 if (layer->is_editable()) {
282 ed::greasepencil::ensure_active_keyframe(
283 *scene, grease_pencil, *layer, true, inserted_keyframe);
284 }
285 }
286
287 /* Apply carver on every editable drawing. */
288 const Vector<ed::greasepencil::MutableDrawingInfo> drawings =
289 ed::greasepencil::retrieve_editable_drawings(*scene, grease_pencil);
290 threading::parallel_for_each(drawings, [&](const ed::greasepencil::MutableDrawingInfo &info) {
291 const bke::greasepencil::Layer &layer = grease_pencil.layer(info.layer_index);
292 const float4x4 layer_to_world = layer.to_world_space(*ob_eval);
293 const float4x4 projection = ED_view3d_ob_project_mat_get_from_obmat(rv3d, layer_to_world);
294
295 /* Initialize helper class for projecting screen space coordinates. */
296 DrawingPlacement placement = ed::greasepencil::DrawingPlacement(
297 *scene, *region, *view3d, *ob_eval, &layer);
298
299 bool r_converted = false;
300 if (execute_carver_on_drawing(*ob_eval,
301 *obact,
302 *region,
303 projection,
304 info.layer_index,
305 layer_to_world,
306 placement,
307 lasso_pos,
308 keep_caps,
309 info.drawing,
310 &r_converted))
311 {
312 changed = true;
313 }
314
315 if (r_converted) {
316 converted = true;
317 }
318 });
319 }
320
321 if (converted) {
322 BKE_report(op->reports, RPT_WARNING, "Some curves were converted to Poly");
323 }
324
325 if (changed) {
326 DEG_id_tag_update(&grease_pencil.id, ID_RECALC_GEOMETRY);
328 if (inserted_keyframe) {
330 }
331 }
332
333 return OPERATOR_FINISHED;
334}
335
336} // namespace ed::greasepencil
337
339{
340 using namespace ed::greasepencil;
341
342 ot->name = "Grease Pencil Carver";
343 ot->idname = "GREASE_PENCIL_OT_stroke_carver";
344 ot->description = "Cuts stroke point in the intersect lasso";
345
348 ot->exec = grease_pencil_stroke_carver_exec;
349 ot->poll = grease_pencil_painting_poll;
351
353
355}
356
357} // namespace blender
General operations, lookup, etc. for materials.
#define C
Definition RandGen.cpp:29
#define NC_GEOM
Definition WM_types.hh:406
#define ND_DATA
Definition WM_types.hh:552
#define NA_EDITED
Definition WM_types.hh:634
#define NC_GPENCIL
Definition WM_types.hh:412
int64_t size() const
Definition BLI_array.hh:267
IndexRange index_range() const
Definition BLI_array.hh:371
bool is_empty() const
Definition BLI_array.hh:275
static IndexMask from_predicate(const IndexMask &universe, LinearAllocator<> &memory, Fn &&predicate, exec_mode::Mode mode=exec_mode::parallel)
static constexpr IndexRange from_begin_size(const int64_t begin, const int64_t size)
static constexpr IndexRange from_single(const int64_t index)
T last(const int64_t n=0) const
static VArray from_single(T value, const int64_t size)
VArray< int8_t > curve_types() const
MutableSpan< float3 > positions_for_write()
void resize(int points_num, int curves_num)
Span< float3 > positions() const
bool is_single_type(CurveType type) const
IndexRange curves_range() const
MutableSpan< int > offsets_for_write()
IndexRange points_range() const
void fill_curve_types(CurveType type)
MutableSpan< bool > cyclic_for_write()
OffsetIndices< int > points_by_curve() const
MutableAttributeAccessor attributes_for_write()
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
Span< float3 > curve_plane_normals() const
const bke::CurvesGeometry & strokes() const
#define position
#define layer
MatBase< 4, 4 > float4x4
if(state< num_states)
GeometryDeformation get_evaluated_grease_pencil_drawing_deformation(const Object *ob_eval, const Object &ob_orig, const bke::greasepencil::Drawing &drawing_orig)
IndexMask selected_mask_to_fills(const IndexMask &selected_mask, const CurvesGeometry &curves, AttrDomain selection_domain, IndexMaskMemory &memory)
int get_next_available_fill_id(Span< int > fill_ids)
ShapeData shapes_from_fill_ids(const VArray< int > &fill_ids, int curves_num)
auto attribute_filter_from_skip_ref(const Span< StringRef > skip)
void fill_attribute_range_default(MutableAttributeAccessor dst_attributes, AttrDomain domain, const AttributeFilter &attribute_filter, IndexRange range)
std::optional< Bounds< T > > intersect(const Bounds< T > &a, const Bounds< T > &b)
bool ensure_active_keyframe(const Scene &scene, GreasePencil &grease_pencil, bke::greasepencil::Layer &layer, const bool duplicate_previous_key, bool &r_inserted_keyframe)
static wmOperatorStatus grease_pencil_stroke_carver_exec(bContext *C, wmOperator *op)
static bool execute_carver_on_drawing(const Object &ob_eval, Object &obact, const ARegion &region, const float4x4 &projection, const int layer_index, const float4x4 &layer_to_world, const DrawingPlacement &placement, const Span< float2 > mcoords, const bool keep_caps, bke::greasepencil::Drawing &drawing, bool *r_converted)
CurvesGeometry resample_to_evaluated(const CurvesGeometry &src_curves, const IndexMask &selection, const ResampleCurvesOutputAttributeIDs &output_ids={})
void gaussian_blur_1D(const GSpan src, int iterations, const VArray< float > &influence_by_point, const bool smooth_ends, const bool keep_shape, const bool is_cyclic, GMutableSpan dst)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
BMesh Iterators.
__int64 int64_t
Definition BKE_text.h:90
void GREASE_PENCIL_OT_stroke_carver(wmOperatorType *ot)
Depsgraph * CTX_data_depsgraph_pointer(const bContext *C)
void WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
float2 ED_view3d_project_float_v2_m4(const ARegion *region, const float co[3], const float4x4 &mat)
void BKE_brush_init_gpencil_settings(Brush *brush)
Definition brush.cc:719
wmOperatorStatus WM_gesture_lasso_modal(bContext *C, wmOperator *op, const wmEvent *event)
MatBase< float, 4, 4 > float4x4
void DEG_id_tag_update(ID *id, unsigned int flags)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
RegionView3D * CTX_wm_region_view3d(const bContext *C)
void WM_event_add_notifier(const bContext *C, uint type, void *reference)
wmOperatorStatus WM_gesture_lasso_invoke(bContext *C, wmOperator *op, const wmEvent *event)
Paint * BKE_paint_get_active_from_context(const bContext *C)
Array< int2 > WM_gesture_lasso_path_to_array(bContext *, wmOperator *op)
float4x4 ED_view3d_ob_project_mat_get_from_obmat(const RegionView3D *rv3d, const float4x4 &obmat)
Brush * BKE_paint_brush(Paint *paint)
Scene * CTX_data_scene(const bContext *C)
@ OPTYPE_REGISTER
Definition WM_types.hh:188
@ OPTYPE_UNDO
Definition WM_types.hh:190
@ GP_BRUSH_ERASER_KEEP_CAPS
@ GP_BRUSH_ACTIVE_LAYER_ONLY
Object * CTX_data_active_object(const bContext *C)
ARegion * CTX_wm_region(const bContext *C)
View3D * CTX_wm_view3d(const bContext *C)
void WM_operator_properties_gesture_lasso(wmOperatorType *ot)
const GroupedSpan< int > shapes() const
wmOperatorStatus(*) exec(bContext *C, wmOperator *op) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1125
const char * description
Definition WM_types.hh:1115
void(*) cancel(bContext *C, wmOperator *op)
Definition WM_types.hh:1149
bool(*) poll(bContext *C) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1165
wmOperatorStatus(*) invoke(bContext *C, wmOperator *op, const wmEvent *event) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1141
wmOperatorStatus(*) modal(bContext *C, wmOperator *op, const wmEvent *event) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1157