Blender V5.3
editors/sculpt_paint/grease_pencil/paint.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "BKE_action.hh"
6#include "BKE_attribute.hh"
7#include "BKE_brush.hh"
8#include "BKE_colortools.hh"
9#include "BKE_context.hh"
10#include "BKE_curves.hh"
11#include "BKE_deform.hh"
12#include "BKE_geometry_set.hh"
13#include "BKE_grease_pencil.hh"
16#include "BKE_lib_id.hh"
17#include "BKE_material.hh"
18#include "BKE_paint.hh"
19#include "BKE_scene.hh"
20
21#include "BLI_bounds.hh"
22#include "BLI_color_types.hh"
24#include "BLI_listbase.hh"
25#include "BLI_math_base.hh"
26#include "BLI_math_color_c.hh"
27#include "BLI_noise.hh"
28#include "BLI_rand.hh"
29#include "BLI_rect.hh"
30#include "BLI_time.hh"
31
33
34#include "DNA_brush_types.h"
35#include "DNA_material_types.h"
36#include "DNA_modifier_types.h"
37
38#include "DNA_scene_types.h"
39#include "ED_curves.hh"
40#include "ED_grease_pencil.hh"
41#include "ED_view3d.hh"
42
43#include "GEO_fit_curves.hh"
45#include "GEO_set_curve_type.hh"
47#include "GEO_smooth_curves.hh"
49
50#include "WM_api.hh"
51#include "WM_types.hh"
52
54
55#include <numeric>
56#include <optional>
57
59
61 const Paint *paint,
62 const Brush *brush,
63 const float3 pos)
64{
65 if ((brush->flag & BRUSH_LOCK_SIZE) != 0) {
66 const float pixel_size = ED_view3d_pixel_size(rv3d, pos);
67 return (BKE_brush_unprojected_radius_get(paint, brush)) / pixel_size;
68 }
70}
71
72template<typename T>
73static inline void linear_interpolation(const T &a, const T &b, MutableSpan<T> dst)
74{
75 const float step = 1.0f / float(dst.size());
76 for (const int i : dst.index_range()) {
77 dst[i] = bke::attribute_math::mix2(float(i + 1) * step, a, b);
78 }
79}
80
82{
83 return std::accumulate(values.begin(), values.end(), float2(0)) / values.size();
84}
85
87static Array<float2> sample_curve_2d(Span<float2> positions, const int64_t resolution)
88{
89 BLI_assert(positions.size() % 3 == 0);
90 const int64_t num_handles = positions.size() / 3;
91 if (num_handles == 1) {
92 return Array<float2>(resolution, positions[1]);
93 }
94 const int64_t num_segments = num_handles - 1;
95 const int64_t num_points = num_segments * resolution;
96
97 Array<float2> points(num_points);
98 const Span<float2> curve_segments = positions.drop_front(1).drop_back(1);
99 threading::parallel_for(IndexRange(num_segments), 32 * resolution, [&](const IndexRange range) {
100 for (const int64_t segment_i : range) {
101 IndexRange segment_range(segment_i * resolution, resolution);
102 bke::curves::bezier::evaluate_segment(curve_segments[segment_i * 3 + 0],
103 curve_segments[segment_i * 3 + 1],
104 curve_segments[segment_i * 3 + 2],
105 curve_segments[segment_i * 3 + 3],
106 points.as_mutable_span().slice(segment_range));
107 }
108 });
109 return points;
110}
111
117{
118 BLI_assert(src.size() == dst.size());
119 Array<float> accumulated_lengths_src(src.size() - 1);
120 length_parameterize::accumulate_lengths<float2>(src, false, accumulated_lengths_src);
121
122 Array<float> accumulated_lengths_target(target.size() - 1);
123 length_parameterize::accumulate_lengths<float2>(target, false, accumulated_lengths_target);
124
125 Array<int> segment_indices(accumulated_lengths_src.size());
126 Array<float> segment_factors(accumulated_lengths_src.size());
128 accumulated_lengths_target, accumulated_lengths_src, segment_indices, segment_factors);
129
131 target, segment_indices, segment_factors, dst.drop_back(1));
132 dst.last() = src.last();
133}
134
137{
138 Brush *fill_guides_brush = BKE_id_new_nomain<Brush>("Draw Fill Guides");
139 fill_guides_brush->ob_mode = OB_MODE_PAINT_GREASE_PENCIL;
140
141 if (fill_guides_brush->gpencil_settings == nullptr) {
142 BKE_brush_init_gpencil_settings(fill_guides_brush);
143 }
144 BrushGpencilSettings *settings = fill_guides_brush->gpencil_settings;
145
152 BKE_curvemapping_init(fill_guides_brush->curve_rand_hue);
154 BKE_curvemapping_init(fill_guides_brush->curve_rand_value);
155
156 settings->flag2 |= GP_BRUSH_USE_STROKE;
157
158 /* Don't use unified paint settings (since we want to set own color and size). */
159 fill_guides_brush->unified_paint_flags = {};
160
161 /* Dont use pressure. */
162 fill_guides_brush->flag &= ~BRUSH_ALPHA_PRESSURE;
163 fill_guides_brush->flag &= ~BRUSH_SIZE_PRESSURE;
164 settings->flag &= ~GP_BRUSH_USE_PRESSURE;
166
167 /* Brush size relative to the view. */
168 fill_guides_brush->size = 2;
169
171 /* TODO: Use theme setting. */
172 copy_v3_fl3(fill_guides_brush->color, 0.0f, 1.0f, 1.0f);
173 settings->vertex_factor = 1.0f;
174
175 settings->active_smooth = 0.35f;
176 settings->hardness = 1.0f;
177 fill_guides_brush->spacing = 100;
178
179 settings->flag |= GP_BRUSH_GROUP_SETTINGS;
180 settings->simplify_px = 0.4f;
181
182 return fill_guides_brush;
183}
184
186 private:
187 Scene *scene_;
188 Object *object_;
190 int frame_number_;
192 float fill_opacity_sum_ = 0.0f;
193 int fill_opacity_count_ = 0;
194
196 Vector<float2> screen_space_coords_orig_;
197
202 Vector<Vector<float2>> screen_space_curve_fitted_coords_;
204 Vector<float2> screen_space_jitter_offsets_;
206 Vector<std::optional<float>> stroke_placement_depths_;
207
209 Vector<float2> screen_space_smoothed_coords_;
211 Vector<float2> screen_space_final_coords_;
212
214 int active_smooth_start_index_ = 0;
215 float4x2 texture_space_ = float4x2::identity();
216
220 std::optional<float> last_stroke_placement_depth_;
222 std::optional<int> last_stroke_placement_point_;
223
225 float2 smoothed_pen_direction_ = float2(0.0f);
226
228 float accum_distance_ = 0.0f;
229
231
232 float stroke_random_radius_factor_;
233 float stroke_random_opacity_factor_;
234 float stroke_random_rotation_factor_;
235
236 float stroke_random_hue_factor_;
237 float stroke_random_sat_factor_;
238 float stroke_random_val_factor_;
239
241 double start_time_;
243 double delta_time_;
244
246 bool do_fill_guides_;
247
249
250 Brush *saved_active_brush_;
251 Brush *fill_guides_brush_;
252
253 public:
254 void on_stroke_begin(const bContext &C, const InputSample &start_sample) override;
255 void on_stroke_extended(const bContext &C, const InputSample &extension_sample) override;
256 void on_stroke_done(const bContext &C) override;
257
258 PaintOperation(const bool do_fill_guides = false) : do_fill_guides_(do_fill_guides) {}
259
262 IndexRange interpolate_stroke_depth(std::optional<int> start_point,
263 float from_depth,
264 float to_depth);
267};
268
276
278
280 std::optional<BrushColorJitterSettings> jitter_settings_;
281
283 ColorGeometry4f fill_color_ = ColorGeometry4f(0.0f, 0.0f, 0.0f, 0.0f);
286
289
314
316 const bContext &C,
317 const InputSample &start_sample,
318 const int material_index,
319 const bool use_stroke,
320 const bool use_fill)
321 {
322 const float2 start_coords = start_sample.mouse_position;
324 const RegionView3D *rv3d = CTX_wm_region_view3d(&C);
325 const ARegion *region = CTX_wm_region(&C);
326
327 float3 start_location;
328 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
329 const std::optional<float> depth = self.placement_.get_depth(start_coords);
330 if (depth) {
331 start_location = self.placement_.place(start_coords, *depth);
332 }
333 else {
334 start_location = self.placement_.project(start_coords);
335 }
336 }
337 else {
338 start_location = self.placement_.project(start_coords);
339 }
341 rv3d,
342 region,
343 paint,
344 brush_,
345 start_sample.pressure,
346 start_location,
347 self.placement_.to_world_space(),
348 settings_);
350 *settings_, self.stroke_random_radius_factor_, 0.0f, start_radius, start_sample.pressure);
351
353 start_sample.pressure, paint, brush_, settings_);
355 self.stroke_random_opacity_factor_,
356 0.0f,
357 start_opacity,
358 start_sample.pressure);
359
360 const float start_rotation = ed::greasepencil::randomize_rotation(
361 *settings_, self.rng_, self.stroke_random_rotation_factor_, start_sample.pressure);
362 if (use_vertex_color_) {
365 self.stroke_random_hue_factor_,
366 self.stroke_random_sat_factor_,
367 self.stroke_random_val_factor_,
368 0.0f,
370 start_sample.pressure);
371 }
372
373 const bool on_back = (scene_->toolsettings->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) != 0;
374 const bool hide_fill_while_drawing = (settings_->flag & GP_BRUSH_DISSABLE_LASSO) != 0;
375 const bool cyclic_stroke = (settings_->flag & GP_BRUSH_USE_CYCLIC_STROKE) != 0;
376
377 self.screen_space_coords_orig_.append(start_coords);
378 self.screen_space_curve_fitted_coords_.append(Vector<float2>({start_coords}));
379 self.screen_space_jitter_offsets_.append(float2(0.0f));
380 self.screen_space_smoothed_coords_.append(start_coords);
381 self.screen_space_final_coords_.append(start_coords);
382
383 /* Resize the curves geometry so there is one more curve with a single point. */
384 ed::greasepencil::add_single_curve(*self.drawing_, on_back == false);
385 bke::CurvesGeometry &curves = self.drawing_->strokes_for_write();
386
387 const int active_curve = on_back ? curves.curves_range().first() :
388 curves.curves_range().last();
389 const IndexRange curve_points = curves.points_by_curve()[active_curve];
390 const int last_active_point = curve_points.last();
391
392 /* Don't smooth the first point. */
393 self.active_smooth_start_index_ = 1;
394
395 Set<std::string> point_attributes_to_skip;
396 Set<std::string> curve_attributes_to_skip;
397 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
398 curves.positions_for_write()[last_active_point] = start_location;
399 self.drawing_->radii_for_write()[last_active_point] = start_radius;
400 self.drawing_->opacities_for_write()[last_active_point] = start_opacity;
401 point_attributes_to_skip.add_multiple({"position", "radius", "opacity"});
402 if (use_vertex_color_ || attributes.contains("vertex_color")) {
403 self.drawing_->vertex_colors_for_write()[last_active_point] = vertex_color_;
404 point_attributes_to_skip.add("vertex_color");
405 }
406 if (use_fill || attributes.contains("fill_color")) {
407 self.drawing_->fill_colors_for_write()[active_curve] = fill_color_;
408 curve_attributes_to_skip.add("fill_color");
409 }
411 "delta_time", bke::AttrDomain::Point);
412 delta_times.span[last_active_point] = 0.0f;
413 point_attributes_to_skip.add("delta_time");
414 delta_times.finish();
415
417 "material_index", bke::AttrDomain::Curve);
419 "cyclic", bke::AttrDomain::Curve);
420 cyclic.span[active_curve] = cyclic_stroke;
421 materials.span[active_curve] = material_index;
422 curve_attributes_to_skip.add_multiple({"material_index", "cyclic"});
423 cyclic.finish();
424 materials.finish();
425
427 "softness", bke::AttrDomain::Curve);
428 softness.span[active_curve] = softness_;
429 curve_attributes_to_skip.add("softness");
430 softness.finish();
433 u_scale.span[active_curve] = 1.0f;
434 curve_attributes_to_skip.add("u_scale");
435 u_scale.finish();
436 bke::SpanAttributeWriter aspect_ratio = attributes.convert_or_add_for_write_span<float>(
437 "aspect_ratio", bke::AttrDomain::Curve, bke::AttributeInitValue(1.0f));
438 aspect_ratio.span[active_curve] = aspect_ratio_;
439 curve_attributes_to_skip.add("aspect_ratio");
440 aspect_ratio.finish();
441
442 if (!use_stroke) {
444 "hide_stroke", bke::AttrDomain::Curve);
445 hide_stroke.span[active_curve] = true;
446 curve_attributes_to_skip.add("hide_stroke");
447 hide_stroke.finish();
448 }
449 if (use_fill) {
451 "fill_id", bke::AttrDomain::Curve))
452 {
453 /* Set new fill id to zero, because it will have uninitialized memory otherwise.
454 * Then get the #VArray of all fill ids to compute a new one. */
455 fill_id.span[active_curve] = 0;
456 const int new_fill_id = bke::greasepencil::get_next_available_fill_id(fill_id.span);
457 fill_id.span[active_curve] = new_fill_id;
458 curve_attributes_to_skip.add("fill_id");
459 fill_id.finish();
460 }
461 }
462
463 if (settings_->uv_random > 0.0f || attributes.contains("rotation")) {
465 "rotation", bke::AttrDomain::Point);
466 rotations.span[last_active_point] = start_rotation;
467 point_attributes_to_skip.add("rotation");
468 rotations.finish();
469 }
470
471 /* Only set the attribute if the type is not the default or if it already exists. */
472 if (settings_->caps_type != GP_STROKE_CAP_TYPE_ROUND || attributes.contains("start_cap")) {
475 start_caps.span[active_curve] = settings_->caps_type;
476 curve_attributes_to_skip.add("start_cap");
477 start_caps.finish();
478 }
479
480 if (settings_->caps_type != GP_STROKE_CAP_TYPE_ROUND || attributes.contains("end_cap")) {
482 "end_cap", bke::AttrDomain::Curve);
483 end_caps.span[active_curve] = settings_->caps_type;
484 curve_attributes_to_skip.add("end_cap");
485 end_caps.finish();
486 }
487
488 self.fill_opacity_sum_ = use_fill ? start_opacity : 0.0f;
489 self.fill_opacity_count_ = use_fill ? 1 : 0;
490
491 if (attributes.contains("fill_opacity") ||
492 (use_fill && (start_opacity < 1.0f || hide_fill_while_drawing)))
493 {
494 bke::SpanAttributeWriter<float> fill_opacities =
495 attributes.convert_or_add_for_write_span<float>(
496 "fill_opacity", bke::AttrDomain::Curve, bke::AttributeInitValue(1.0f));
497 if (use_fill) {
498 /* Use 10% opacity when using the option to hide the fill while drawing
499 * (#GP_BRUSH_DISSABLE_LASSO). */
500 fill_opacities.span[active_curve] = !hide_fill_while_drawing ? start_opacity : 0.1f;
501 }
502 else {
503 fill_opacities.span[active_curve] = 1.0f;
504 }
505 curve_attributes_to_skip.add("fill_opacity");
506 fill_opacities.finish();
507 }
508
510 "init_time", bke::AttrDomain::Curve);
511 /* Truncating time in ms to uint32 then we don't lose precision in lower bits. */
512 init_times.span[active_curve] = float(uint64_t(self.start_time_ * 1e3)) / float(1e3);
513 curve_attributes_to_skip.add("init_time");
514 init_times.finish();
515
516 if (self.do_fill_guides_) {
517 bke::SpanAttributeWriter<bool> is_fill_boundary =
518 attributes.convert_or_add_for_write_span<bool>(".is_fill_guide", bke::AttrDomain::Curve);
519 is_fill_boundary.span[active_curve] = true;
520 curve_attributes_to_skip.add(".is_fill_guide");
521 is_fill_boundary.finish();
522 }
523
524 curves.curve_types_for_write()[active_curve] = CURVE_TYPE_POLY;
525 curve_attributes_to_skip.add("curve_type");
526 curves.update_curve_types();
527
528 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
529 self.stroke_placement_depths_.append(self.stroke_placement_depths_.is_empty() ?
530 std::nullopt :
531 self.stroke_placement_depths_.last());
532 /* Initialize the snap point. */
533 self.update_stroke_depth_placement(start_sample);
534 }
535
536 /* Initialize the rest of the attributes with default values. */
538 attributes,
540 bke::attribute_filter_from_skip_ref(point_attributes_to_skip),
541 IndexRange(last_active_point, 1));
543 attributes,
545 bke::attribute_filter_from_skip_ref(curve_attributes_to_skip),
546 IndexRange(active_curve, 1));
547
548 if (on_back) {
549 self.drawing_->tag_topology_changed();
550 }
551 else {
552 self.drawing_->tag_topology_changed(IndexRange::from_single(active_curve));
553 }
554 }
555
556 void active_smoothing(PaintOperation &self, const IndexRange smooth_window)
557 {
558 const Span<float2> coords_to_smooth = self.screen_space_coords_orig_.as_span().slice(
559 smooth_window);
560
561 /* Detect corners in the current slice of coordinates. */
562 const float corner_min_radius_px = 5.0f;
563 const float corner_max_radius_px = 30.0f;
564 const int64_t corner_max_samples = 64;
565 const float corner_angle_threshold = 0.6f;
566 IndexMaskMemory memory;
568 coords_to_smooth.drop_front(1).drop_back(1),
569 corner_min_radius_px,
570 corner_max_radius_px,
571 corner_max_samples,
572 corner_angle_threshold,
573 memory);
574
575 /* Pre-blur the coordinates for the curve fitting. This generally leads to a better (more
576 * stable) fit. */
577 Array<float2> coords_pre_blur(smooth_window.size());
578 const int pre_blur_iterations = 3;
580 coords_to_smooth,
581 pre_blur_iterations,
583 true,
584 true,
585 false,
586 coords_pre_blur.as_mutable_span());
587
588 /* Curve fitting. The output will be a set of handles (float2 triplets) in a flat array. */
589 const float max_error_threshold_px = 5.0f;
591 coords_pre_blur, max_error_threshold_px * settings_->active_smooth, corner_mask);
592
593 /* Sampling the curve at a fixed resolution. */
594 const int64_t sample_resolution = 32;
595 Array<float2> sampled_curve_points = sample_curve_2d(curve_points, sample_resolution);
596
597 /* Morphing the coordinates onto the curve. Result is stored in a temporary array. */
598 Array<float2> coords_smoothed(coords_to_smooth.size());
599 morph_points_to_curve(coords_to_smooth, sampled_curve_points, coords_smoothed);
600
601 MutableSpan<float2> window_coords = self.screen_space_smoothed_coords_.as_mutable_span().slice(
602 smooth_window);
603 const float converging_threshold_px = 0.1f;
604 bool stop_counting_converged = false;
605 int num_converged = 0;
606 for (const int64_t window_i : smooth_window.index_range()) {
607 /* Record the curve fitting of this point. */
608 self.screen_space_curve_fitted_coords_[window_i].append(coords_smoothed[window_i]);
609 Span<float2> fit_coords = self.screen_space_curve_fitted_coords_[window_i];
610
611 /* We compare the previous arithmetic mean to the current. Going from the back to the front,
612 * if a point hasn't moved by a minimum threshold, it counts as converged. */
613 float2 new_pos = arithmetic_mean(fit_coords);
614 if (!stop_counting_converged) {
615 float2 prev_pos = window_coords[window_i];
616 if (math::distance(new_pos, prev_pos) < converging_threshold_px) {
617 num_converged++;
618 }
619 else {
620 stop_counting_converged = true;
621 }
622 }
623
624 /* Update the positions in the current cache. */
625 window_coords[window_i] = new_pos;
626 }
627
628 /* Remove all the converged points from the active window and shrink the window accordingly. */
629 if (num_converged > 0) {
630 self.active_smooth_start_index_ += num_converged;
631 self.screen_space_curve_fitted_coords_.remove(0, num_converged);
632 }
633 }
634
636 const int new_points_num,
637 const float brush_radius_px,
638 const float pressure,
639 const IndexRange active_window,
640 MutableSpan<float3> curve_positions)
641 {
642 float jitter_factor = 1.0f;
644 jitter_factor = BKE_curvemapping_evaluateF(settings_->curve_jitter, 0, pressure);
645 }
646 const float2 tangent = math::normalize(self.smoothed_pen_direction_);
647 const float2 cotangent = float2(-tangent.y, tangent.x);
648 for ([[maybe_unused]] const int _ : IndexRange(new_points_num)) {
649 const float rand = self.rng_.get_float() * 2.0f - 1.0f;
650 const float factor = rand * settings_->draw_jitter * jitter_factor;
651 self.screen_space_jitter_offsets_.append(cotangent * factor * brush_radius_px);
652 }
653 const Span<float2> jitter_slice = self.screen_space_jitter_offsets_.as_mutable_span().slice(
654 active_window);
655 MutableSpan<float2> smoothed_coords =
656 self.screen_space_smoothed_coords_.as_mutable_span().slice(active_window);
657 MutableSpan<float2> final_coords = self.screen_space_final_coords_.as_mutable_span().slice(
658 active_window);
659 MutableSpan<float3> positions_slice = curve_positions.slice(active_window);
660 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
661 BLI_assert(self.stroke_placement_depths_.size() == self.screen_space_coords_orig_.size());
662 const Span<std::optional<float>> stroke_depths =
663 self.stroke_placement_depths_.as_span().slice(active_window);
664 for (const int64_t window_i : active_window.index_range()) {
665 final_coords[window_i] = smoothed_coords[window_i] + jitter_slice[window_i];
666 const std::optional<float> depth = stroke_depths[window_i];
667 positions_slice[window_i] = depth ? self.placement_.place(final_coords[window_i], *depth) :
668 self.placement_.project(final_coords[window_i]);
669 }
670 }
671 else {
672 for (const int64_t window_i : active_window.index_range()) {
673 final_coords[window_i] = smoothed_coords[window_i] + jitter_slice[window_i];
674 positions_slice[window_i] = self.placement_.project(final_coords[window_i]);
675 }
676 }
677 }
678
680 const bContext &C,
681 const InputSample &extension_sample)
682 {
683 const RegionView3D *rv3d = CTX_wm_region_view3d(&C);
684 const ARegion *region = CTX_wm_region(&C);
686
687 const bool on_back = (scene_->toolsettings->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) != 0;
688
689 const float2 coords = extension_sample.mouse_position;
691 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
692 const std::optional<float> depth = self.stroke_placement_depths_.is_empty() ?
693 std::nullopt :
694 self.stroke_placement_depths_.last();
695 if (depth) {
696 position = self.placement_.place(coords, *depth);
697 }
698 else {
699 position = self.placement_.project(coords);
700 }
701 }
702 else {
703 position = self.placement_.project(coords);
704 }
705
707 region,
708 paint,
709 brush_,
710 extension_sample.pressure,
711 position,
712 self.placement_.to_world_space(),
713 settings_);
715 extension_sample.pressure, paint, brush_, settings_);
716
717 const float brush_radius_px = brush_radius_to_pixel_radius(
718 rv3d, &paint, brush_, math::transform_point(self.placement_.to_world_space(), position));
719
720 bke::CurvesGeometry &curves = self.drawing_->strokes_for_write();
721 OffsetIndices<int> points_by_curve = curves.points_by_curve();
722 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
723
724 const int active_curve = on_back ? curves.curves_range().first() :
725 curves.curves_range().last();
726
727 const bool use_fill = (settings_->flag2 & GP_BRUSH_USE_FILL) != 0;
728 const bool hide_fill_while_drawing = (settings_->flag & GP_BRUSH_DISSABLE_LASSO) != 0;
729
730 if (use_fill) {
731 self.fill_opacity_sum_ += opacity;
732 self.fill_opacity_count_++;
733 if (!hide_fill_while_drawing) {
734 bke::SpanAttributeWriter<float> fill_opacities =
735 attributes.lookup_or_add_for_write_span<float>(
736 "fill_opacity", bke::AttrDomain::Curve, bke::AttributeInitValue(1.0f));
737 if (fill_opacities) {
738 fill_opacities.span[active_curve] = self.fill_opacity_sum_ / self.fill_opacity_count_;
739 fill_opacities.finish();
740 }
741 }
742 }
743
744 const IndexRange curve_points = points_by_curve[active_curve];
745 const int last_active_point = curve_points.last();
746
747 const float2 prev_coords = self.screen_space_coords_orig_.last();
748 float prev_radius = self.drawing_->radii()[last_active_point];
749 const float prev_opacity = self.drawing_->opacities()[last_active_point];
750 const ColorGeometry4f prev_vertex_color = self.drawing_->vertex_colors()[last_active_point];
751
752 const bool is_first_sample = (curve_points.size() == 1);
753
754 /* Use the vector from the previous to the next point. Set the direction based on the first two
755 * samples. For subsequent samples, interpolate with the previous direction to get a smoothed
756 * value over time. */
757 if (is_first_sample) {
758 self.smoothed_pen_direction_ = self.screen_space_coords_orig_.last() - coords;
759 }
760 else {
761 /* The smoothing rate is a factor from 0 to 1 that represents how quickly the
762 * `smoothed_pen_direction_` "reacts" to changes in direction.
763 * - 1.0f: Immediate reaction.
764 * - 0.0f: No reaction (value never changes). */
765 constexpr float smoothing_rate_factor = 0.3f;
766 self.smoothed_pen_direction_ = math::interpolate(self.smoothed_pen_direction_,
767 self.screen_space_coords_orig_.last() -
768 coords,
769 smoothing_rate_factor);
770 }
771
772 /* Approximate brush with non-circular shape by changing the radius based on the angle. */
773 float radius_factor = 1.0f;
774 if (settings_->draw_angle_factor > 0.0f) {
775 /* `angle` is the angle to the horizontal line in screen space. */
776 const float angle = settings_->draw_angle;
777 const float2 angle_vec = float2(math::cos(angle), math::sin(angle));
778
779 /* The angle factor is 1.0f when the direction is aligned with the angle vector and 0.0f when
780 * it is orthogonal to the angle vector. This is consistent with the behavior from GPv2. */
781 const float angle_factor = math::abs(
782 math::dot(angle_vec, math::normalize(self.smoothed_pen_direction_)));
783
784 /* Influence is controlled by `draw_angle_factor`. */
785 radius_factor = math::interpolate(1.0f, angle_factor, settings_->draw_angle_factor);
786 radius *= radius_factor;
787 }
788
789 /* Overwrite last point if it's very close. */
790 const float distance_px = math::distance(coords, prev_coords);
791 constexpr float point_override_threshold_px = 2.0f;
792 if (distance_px < point_override_threshold_px) {
793 self.accum_distance_ += distance_px;
794 /* Don't move the first point of the stroke. */
795 if (!is_first_sample) {
796 curves.positions_for_write()[last_active_point] = position;
797 }
800 self.stroke_random_radius_factor_,
801 self.accum_distance_,
802 radius,
803 extension_sample.pressure);
804 }
807 self.stroke_random_opacity_factor_,
808 self.accum_distance_,
809 opacity,
810 extension_sample.pressure);
811 }
812 self.drawing_->radii_for_write()[last_active_point] = math::max(radius, prev_radius);
813 self.drawing_->opacities_for_write()[last_active_point] = math::max(opacity, prev_opacity);
814 return;
815 }
816
817 /* Adjust the first points radius based on the computed angle. */
818 if (is_first_sample && settings_->draw_angle_factor > 0.0f) {
819 self.drawing_->radii_for_write()[last_active_point] *= radius_factor;
820 prev_radius = self.drawing_->radii()[last_active_point];
821 }
822
823 /* Clamp the number of points within a pixel in screen space. */
824 constexpr int max_points_per_pixel = 4;
825 /* The value `brush_->spacing` is a percentage of the brush radius in pixels. */
826 const float max_spacing_px = math::max((float(brush_->spacing) / 100.0f) *
827 float(brush_radius_px),
828 1.0f / float(max_points_per_pixel));
829 /* If the next sample is far away, we subdivide the segment to add more points. */
830 const int new_points_num = (distance_px > max_spacing_px) ?
831 int(math::floor(distance_px / max_spacing_px)) :
832 1;
833 /* Resize the curves geometry. */
835 curves, on_back == false, curve_points.size() + new_points_num);
836
837 Set<std::string> point_attributes_to_skip;
838 /* Subdivide new segment. */
839 const IndexRange new_points = curves.points_by_curve()[active_curve].take_back(new_points_num);
840 Array<float2> new_screen_space_coords(new_points_num);
841 MutableSpan<float3> positions = curves.positions_for_write();
842 MutableSpan<float3> new_positions = positions.slice(new_points);
843 MutableSpan<float> new_radii = self.drawing_->radii_for_write().slice(new_points);
844 MutableSpan<float> new_opacities = self.drawing_->opacities_for_write().slice(new_points);
845
846 /* Interpolate the screen space positions. */
847 linear_interpolation<float2>(prev_coords, coords, new_screen_space_coords);
848 linear_interpolation<float>(prev_radius, radius, new_radii);
849 linear_interpolation<float>(prev_opacity, opacity, new_opacities);
850 point_attributes_to_skip.add_multiple({"position", "radius", "opacity"});
851
852 /* Randomize radii. */
854 for (const int i : IndexRange(new_points_num)) {
856 self.stroke_random_radius_factor_,
857 self.accum_distance_ +
858 max_spacing_px * i,
859 new_radii[i],
860 extension_sample.pressure);
861 }
862 }
863
864 /* Randomize opacities. */
866 for (const int i : IndexRange(new_points_num)) {
868 self.stroke_random_opacity_factor_,
869 self.accum_distance_ +
870 max_spacing_px * i,
871 new_opacities[i],
872 extension_sample.pressure);
873 }
874 }
875
876 /* Randomize rotations. */
877 if (use_settings_random_ && (settings_->uv_random > 0.0f || attributes.contains("rotation"))) {
879 "rotation", bke::AttrDomain::Point);
880 const MutableSpan<float> new_rotations = rotations.span.slice(new_points);
881 for (const int i : IndexRange(new_points_num)) {
882 new_rotations[i] = ed::greasepencil::randomize_rotation(
883 *settings_, self.rng_, self.stroke_random_rotation_factor_, extension_sample.pressure);
884 }
885 point_attributes_to_skip.add("rotation");
886 rotations.finish();
887 }
888
889 /* Randomize vertex color. */
890 if (use_vertex_color_ || attributes.contains("vertex_color")) {
891 MutableSpan<ColorGeometry4f> new_vertex_colors =
892 self.drawing_->vertex_colors_for_write().slice(new_points);
893 linear_interpolation<ColorGeometry4f>(prev_vertex_color, vertex_color_, new_vertex_colors);
894 if (use_settings_random_ || attributes.contains("vertex_color")) {
895 for (const int i : IndexRange(new_points_num)) {
896 new_vertex_colors[i] = ed::greasepencil::randomize_color(*settings_,
898 self.stroke_random_hue_factor_,
899 self.stroke_random_sat_factor_,
900 self.stroke_random_val_factor_,
901 self.accum_distance_ +
902 max_spacing_px * i,
903 new_vertex_colors[i],
904 extension_sample.pressure);
905 }
906 }
907 point_attributes_to_skip.add("vertex_color");
908 }
909
910 const double new_delta_time = BLI_time_now_seconds() - self.start_time_;
912 "delta_time", bke::AttrDomain::Point);
914 float(self.delta_time_), float(new_delta_time), delta_times.span.slice(new_points));
915 point_attributes_to_skip.add("delta_time");
916 delta_times.finish();
917
918 /* Update the accumulated distance along the stroke in pixels. */
919 self.accum_distance_ += distance_px;
920
921 /* Update the current delta time. */
922 self.delta_time_ = new_delta_time;
923
924 /* Update screen space buffers with new points. */
925 self.screen_space_coords_orig_.extend(new_screen_space_coords);
926 self.screen_space_smoothed_coords_.extend(new_screen_space_coords);
927 self.screen_space_final_coords_.extend(new_screen_space_coords);
928 for (float2 new_position : new_screen_space_coords) {
929 self.screen_space_curve_fitted_coords_.append(Vector<float2>({new_position}));
930 }
931 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
932 const std::optional<float> last_depth = self.stroke_placement_depths_.is_empty() ?
933 std::nullopt :
934 self.stroke_placement_depths_.last();
935 self.stroke_placement_depths_.append_n_times(last_depth, new_points_num);
936 }
937
938 /* Only start smoothing if there are enough points. */
939 constexpr int64_t min_active_smoothing_points_num = 8;
940 const IndexRange smooth_window = self.screen_space_coords_orig_.index_range().drop_front(
941 self.active_smooth_start_index_);
942 if (smooth_window.size() < min_active_smoothing_points_num) {
943 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
944 const Span<std::optional<float>> new_depths =
945 self.stroke_placement_depths_.as_mutable_span().take_back(new_points_num);
946 for (const int64_t i : new_positions.index_range()) {
947 const std::optional<float> depth = new_depths[i];
948 if (depth) {
949 new_positions[i] = self.placement_.place(coords, *depth);
950 }
951 else {
952 new_positions[i] = self.placement_.project(coords);
953 }
954 }
955 }
956 else {
957 self.placement_.project(new_screen_space_coords, new_positions);
958 }
959 }
960 else {
961 /* Active smoothing is done in a window at the end of the new stroke.
962 * Final positions are written below. */
963 this->active_smoothing(self, smooth_window);
964 }
965
966 /* Jitter uses smoothed coordinates as input. In case smoothing is not applied these are the
967 * unsmoothed original coordinates. */
968 MutableSpan<float3> curve_positions = positions.slice(curves.points_by_curve()[active_curve]);
970 this->active_jitter(self,
971 new_points_num,
972 brush_radius_px,
973 extension_sample.pressure,
974 smooth_window,
975 curve_positions);
976 }
977 else {
978 MutableSpan<float2> smoothed_coords =
979 self.screen_space_smoothed_coords_.as_mutable_span().slice(smooth_window);
980 MutableSpan<float2> final_coords = self.screen_space_final_coords_.as_mutable_span().slice(
981 smooth_window);
982 /* Not jitter, so we just copy the positions over. */
983 final_coords.copy_from(smoothed_coords);
984 MutableSpan<float3> curve_positions_slice = curve_positions.slice(smooth_window);
985 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
986 BLI_assert(self.stroke_placement_depths_.size() == self.screen_space_coords_orig_.size());
987 const Span<std::optional<float>> stroke_depths =
988 self.stroke_placement_depths_.as_mutable_span().slice(smooth_window);
989 for (const int64_t window_i : smooth_window.index_range()) {
990 const std::optional<float> depth = stroke_depths[window_i];
991 curve_positions_slice[window_i] = depth ?
992 self.placement_.place(final_coords[window_i],
993 *depth) :
994 self.placement_.project(final_coords[window_i]);
995 }
996 }
997 else {
998 for (const int64_t window_i : smooth_window.index_range()) {
999 curve_positions_slice[window_i] = self.placement_.project(final_coords[window_i]);
1000 }
1001 }
1002 }
1003
1004 if (self.placement_.use_project_to_stroke() || self.placement_.use_project_to_surface()) {
1005 /* Find a new snap point and apply projection to trailing points. */
1006 self.update_stroke_depth_placement(extension_sample);
1007 }
1008
1009 /* Initialize the rest of the attributes with default values. */
1011 attributes,
1013 bke::attribute_filter_from_skip_ref(point_attributes_to_skip),
1014 curves.points_range().take_back(new_points_num));
1015
1016 self.drawing_->set_texture_matrices({self.texture_space_},
1017 IndexRange::from_single(active_curve));
1018 }
1019
1020 void execute(PaintOperation &self, const bContext &C, const InputSample &extension_sample)
1021 {
1022 const bool on_back = (scene_->toolsettings->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) != 0;
1023
1024 this->process_extension_sample(self, C, extension_sample);
1025
1026 const bke::CurvesGeometry &curves = self.drawing_->strokes();
1027 const int active_curve = on_back ? curves.curves_range().first() :
1028 curves.curves_range().last();
1029 self.drawing_->tag_topology_changed(IndexRange::from_single(active_curve));
1030 }
1031};
1032
1038
1040{
1041 /* gpencil_v3d_align is an awkward combination of multiple properties. If none of the non-zero
1042 * flags are set the AllPoints mode is the default. */
1043 const char align_flags = scene.toolsettings->gpencil_v3d_align;
1044 if (align_flags & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) {
1046 }
1047 if (align_flags & GP_PROJECT_DEPTH_STROKE_FIRST) {
1049 }
1051}
1052
1054{
1055 BLI_assert(placement_.use_project_to_stroke() || placement_.use_project_to_surface());
1056
1057 const std::optional<float> new_stroke_placement_depth = placement_.get_depth(
1058 sample.mouse_position);
1059 if (!new_stroke_placement_depth) {
1060 return false;
1061 }
1062
1063 const StrokeSnapMode snap_mode = get_snap_mode(*scene_);
1064 switch (snap_mode) {
1066 const float start_depth = last_stroke_placement_depth_ ? *last_stroke_placement_depth_ :
1067 *new_stroke_placement_depth;
1068 const float end_depth = *new_stroke_placement_depth;
1069 const IndexRange reprojected_points = this->interpolate_stroke_depth(
1070 last_stroke_placement_point_, start_depth, end_depth);
1071 /* Only reproject newly added points next time a hit point is found. */
1072 if (!reprojected_points.is_empty()) {
1073 last_stroke_placement_point_ = reprojected_points.one_after_last();
1074 }
1075
1076 last_stroke_placement_depth_ = new_stroke_placement_depth;
1077 break;
1078 }
1080 const float start_depth = last_stroke_placement_depth_ ? *last_stroke_placement_depth_ :
1081 *new_stroke_placement_depth;
1082 const float end_depth = *new_stroke_placement_depth;
1083 const IndexRange reprojected_points = this->interpolate_stroke_depth(
1084 last_stroke_placement_point_, start_depth, end_depth);
1085
1086 /* Only update depth on the first hit. */
1087 if (!last_stroke_placement_depth_) {
1088 /* Keep reprojecting all points from the first hit onward. */
1089 if (!reprojected_points.is_empty()) {
1090 last_stroke_placement_point_ = reprojected_points.one_after_last();
1091 }
1092 last_stroke_placement_depth_ = new_stroke_placement_depth;
1093 }
1094 break;
1095 }
1097 /* Only reproject once in "First Point" mode. */
1098 if (!last_stroke_placement_depth_) {
1099 const float start_depth = *new_stroke_placement_depth;
1100 const float end_depth = *new_stroke_placement_depth;
1101 this->interpolate_stroke_depth(last_stroke_placement_point_, start_depth, end_depth);
1102
1103 last_stroke_placement_depth_ = new_stroke_placement_depth;
1104 break;
1105 }
1106 }
1107 }
1108
1109 return true;
1110}
1111
1113 const float from_depth,
1114 const float to_depth)
1115{
1116 using namespace blender::bke;
1117 const bool on_back = (scene_->toolsettings->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) != 0;
1118
1119 /* Drawing should exist. */
1120 BLI_assert(drawing_);
1121 bke::greasepencil::Drawing &drawing = *drawing_;
1122 const int active_curve = on_back ? drawing.strokes().curves_range().first() :
1123 drawing.strokes().curves_range().last();
1124 const offset_indices::OffsetIndices<int> points_by_curve = drawing.strokes().points_by_curve();
1125 const IndexRange all_points = points_by_curve[active_curve];
1126 BLI_assert(screen_space_final_coords_.size() == all_points.size());
1127 if (all_points.is_empty()) {
1128 return {};
1129 }
1130
1131 IndexRange active_points = all_points;
1132 if (start_point) {
1133 active_points = IndexRange::from_begin_end_inclusive(*start_point, all_points.last());
1134 }
1135 if (active_points.is_empty()) {
1136 return {};
1137 }
1138
1139 /* Point slice relative to the curve, valid for 2D coordinate array. */
1140 const IndexRange active_curve_points = active_points.shift(-all_points.start());
1141
1142 MutableSpan<std::optional<float>> depths = stroke_placement_depths_.as_mutable_span().slice(
1143 active_curve_points);
1144 MutableSpan<float3> positions = drawing.strokes_for_write().positions_for_write().slice(
1145 active_points);
1146 const Span<float2> final_coords = screen_space_final_coords_.as_span().slice(
1147 active_curve_points);
1148 const float step_size = 1.0f / std::max(int(active_points.size()) - 1, 1);
1149 for (const int i : positions.index_range()) {
1150 /* Update the placement depth for later reprojection (active smoothing). */
1151 depths[i] = math::interpolate(from_depth, to_depth, float(i) * step_size);
1152 positions[i] = placement_.place(final_coords[i], *depths[i]);
1153 }
1154
1155 return active_points;
1156}
1157
1159{
1161 Brush *current_brush = BKE_paint_brush(paint);
1162
1163 fill_guides_brush_ = create_fill_guide_brush();
1164 BLI_assert(fill_guides_brush_ != nullptr);
1165 BKE_paint_brush_set(paint, fill_guides_brush_);
1166
1167 saved_active_brush_ = current_brush;
1168}
1169
1171{
1173 BLI_assert(saved_active_brush_ != nullptr);
1174 BKE_paint_brush_set(paint, saved_active_brush_);
1175 saved_active_brush_ = nullptr;
1176 /* Free the temporary brush. */
1177 BKE_id_free_ex(nullptr, fill_guides_brush_, LIB_ID_FREE_NO_MAIN, false);
1178 fill_guides_brush_ = nullptr;
1179}
1180
1182{
1183 Depsgraph *depsgraph = CTX_data_depsgraph_pointer(&C);
1184 ARegion *region = CTX_wm_region(&C);
1186 scene_ = CTX_data_scene(&C);
1187 object_ = CTX_data_active_object(&C);
1188 Object *eval_object = DEG_get_evaluated(depsgraph, object_);
1189 GreasePencil *grease_pencil = id_cast<GreasePencil *>(object_->data);
1190
1191 if (do_fill_guides_) {
1193 }
1194
1195 Paint *paint = &scene_->toolsettings->gp_paint->paint;
1197
1198 if (brush->gpencil_settings == nullptr) {
1200 }
1201 BrushGpencilSettings *settings = brush->gpencil_settings;
1202
1209 BKE_curvemapping_init(brush->curve_rand_hue);
1210 BKE_curvemapping_init(brush->curve_rand_saturation);
1211 BKE_curvemapping_init(brush->curve_rand_value);
1212
1213 BLI_assert(grease_pencil->has_active_layer());
1214 const bke::greasepencil::Layer &layer = *grease_pencil->get_active_layer();
1215 /* Initialize helper class for projecting screen space coordinates. */
1216 placement_ = ed::greasepencil::DrawingPlacement(*scene_, *region, *view3d, *eval_object, &layer);
1217 if (placement_.use_project_to_surface() || placement_.use_project_to_stroke()) {
1218 placement_.cache_viewport_depths(depsgraph, region, view3d);
1219 }
1220
1222 scene_, region, start_sample.mouse_position, placement_);
1223
1224 /* `View` is already stored in object space but all others are in layer space. */
1225 if (scene_->toolsettings->gp_sculpt.lock_axis != GP_LOCKAXIS_VIEW) {
1226 texture_space_ = texture_space_ * layer.to_object_space(*object_);
1227 }
1228
1230 if ((settings->flag & GP_BRUSH_GROUP_RANDOM) != 0) {
1231 /* Since we want stroke properties to randomize around set values, it's easier for us to have a
1232 * signed value in range (-1,1) in calculations downstream. */
1233 stroke_random_radius_factor_ = rng_.get_float() * 2.0f - 1.0f;
1234 stroke_random_opacity_factor_ = rng_.get_float() * 2.0f - 1.0f;
1235 stroke_random_rotation_factor_ = rng_.get_float() * 2.0f - 1.0f;
1236
1237 stroke_random_hue_factor_ = rng_.get_float() * 2.0f - 1.0f;
1238 stroke_random_sat_factor_ = rng_.get_float() * 2.0f - 1.0f;
1239 stroke_random_val_factor_ = rng_.get_float() * 2.0f - 1.0f;
1240 }
1241
1242 /* At this point it should be fine to create a new material + slot. */
1244 CTX_data_main(&C), object_, brush);
1245 const int material_index = BKE_object_material_index_get(object_, material);
1246 const bool use_stroke = (settings->flag2 & GP_BRUSH_USE_STROKE) != 0;
1247 const bool use_fill = (settings->flag2 & GP_BRUSH_USE_FILL) != 0;
1248
1249 frame_number_ = scene_->r.cfra;
1250 drawing_ = grease_pencil->get_editable_drawing_at(layer, frame_number_);
1251 multi_frame_drawings_ = ed::greasepencil::retrieve_editable_drawings(*scene_, *grease_pencil);
1252 BLI_assert(drawing_ != nullptr);
1253
1254 /* We're now starting to draw. */
1255 grease_pencil->runtime->is_drawing_stroke = true;
1256
1257 /* Initialize the start time to the current time. */
1258 start_time_ = BLI_time_now_seconds();
1259 /* Delta time starts at 0. */
1260 delta_time_ = 0.0f;
1261
1262 PaintOperationExecutor executor{*scene_};
1263 executor.process_start_sample(*this, C, start_sample, material_index, use_stroke, use_fill);
1264
1267}
1268
1269void PaintOperation::on_stroke_extended(const bContext &C, const InputSample &extension_sample)
1270{
1271 GreasePencil *grease_pencil = id_cast<GreasePencil *>(object_->data);
1272
1273 PaintOperationExecutor executor{*scene_};
1274 executor.execute(*this, C, extension_sample);
1275
1278}
1279
1281 const float influence,
1282 const int iterations,
1283 const int active_curve)
1284{
1286 const IndexRange stroke = IndexRange::from_single(active_curve);
1287 const offset_indices::OffsetIndices<int> points_by_curve = drawing.strokes().points_by_curve();
1288 const VArray<bool> cyclic = curves.cyclic();
1289 const VArray<bool> point_selection = VArray<bool>::from_single(true, curves.points_num());
1290
1291 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
1292 bke::GSpanAttributeWriter positions = attributes.lookup_for_write_span("position");
1294 points_by_curve,
1295 point_selection,
1296 cyclic,
1297 iterations,
1298 influence,
1299 false,
1300 true,
1301 positions.span);
1302 positions.finish();
1303 drawing.tag_positions_changed();
1304
1305 if (drawing.opacities().is_span()) {
1306 bke::GSpanAttributeWriter opacities = attributes.lookup_for_write_span("opacity");
1308 points_by_curve,
1309 point_selection,
1310 cyclic,
1311 iterations,
1312 influence,
1313 true,
1314 false,
1315 opacities.span);
1316 opacities.finish();
1317 }
1318 if (drawing.radii().is_span()) {
1319 bke::GSpanAttributeWriter radii = attributes.lookup_for_write_span("radius");
1321 points_by_curve,
1322 point_selection,
1323 cyclic,
1324 iterations,
1325 influence,
1326 true,
1327 false,
1328 radii.span);
1329 radii.finish();
1330 }
1331}
1332
1334 const float subdivisions,
1335 const int active_curve)
1336{
1338 const IndexRange stroke = IndexRange::from_single(active_curve);
1339 const OffsetIndices<int> points_by_curve = curves.points_by_curve();
1340
1341 Array<int> use_cuts(curves.points_num(), 0);
1342
1343 use_cuts.as_mutable_span().slice(points_by_curve[active_curve]).fill(subdivisions);
1344 const VArray<int> cuts = VArray<int>::from_span(use_cuts.as_span());
1345
1346 curves = geometry::subdivide_curves(curves, stroke, cuts);
1347}
1348
1350 const float epsilon,
1351 const int active_curve)
1352{
1353 const bke::CurvesGeometry &curves = drawing.strokes();
1354 const bke::AttributeAccessor attributes = curves.attributes();
1355 const IndexRange points = curves.points_by_curve()[active_curve];
1356 const VArray<float2> screen_space_positions_attribute = *attributes.lookup<float2>(
1357 ".draw_tool_screen_space_positions");
1358 BLI_assert(screen_space_positions_attribute.is_span());
1359
1360 const Span<float2> screen_space_positions =
1361 screen_space_positions_attribute.get_internal_span().slice(points);
1362
1363 Array<bool> points_to_delete_arr(drawing.strokes().points_num(), false);
1364 points_to_delete_arr.as_mutable_span().slice(points).fill(true);
1365 geometry::curve_simplify(curves.positions().slice(points),
1366 curves.cyclic()[active_curve],
1367 epsilon,
1368 screen_space_positions,
1369 points_to_delete_arr.as_mutable_span().slice(points));
1370
1371 IndexMaskMemory memory;
1372 const IndexMask points_to_delete = IndexMask::from_bools(points_to_delete_arr, memory);
1373 if (!points_to_delete.is_empty()) {
1374 drawing.strokes_for_write().remove_points(points_to_delete, {});
1375 drawing.tag_topology_changed();
1376 }
1377}
1378
1379static void add_strokes_to_drawing(const bool on_back,
1380 Curves *strokes,
1382{
1383 Curves *other_curves = bke::curves_new_nomain(std::move(drawing.strokes_for_write()));
1384 std::array<bke::GeometrySet, 2> geometry_sets;
1385 if (on_back) {
1386 geometry_sets = {bke::GeometrySet::from_curves(strokes),
1387 bke::GeometrySet::from_curves(other_curves)};
1388 }
1389 else {
1390 geometry_sets = {bke::GeometrySet::from_curves(other_curves),
1392 }
1393 drawing.strokes_for_write() = std::move(
1394 geometry::join_geometries(geometry_sets, {}).get_curves_for_write()->geometry.wrap());
1395 drawing.tag_topology_changed();
1396}
1397
1399 const int active_curve,
1400 const bool on_back)
1401{
1402 const bke::CurvesGeometry &curves = drawing.strokes();
1403 const IndexRange points = curves.points_by_curve()[active_curve];
1404 const bke::AttributeAccessor attributes = curves.attributes();
1405 const VArray<float2> screen_space_positions_attribute = *attributes.lookup<float2>(
1406 ".draw_tool_screen_space_positions");
1407 BLI_assert(screen_space_positions_attribute.is_span());
1408 const Span<float2> screen_space_positions =
1409 screen_space_positions_attribute.get_internal_span().slice(points);
1410 /* Extract the drawn stroke into a separate geometry, so we can trim the ends for just this
1411 * stroke. */
1413 drawing.strokes(), IndexRange::from_single(active_curve), {});
1414
1415 const IndexRange curve_mask = IndexRange::from_single(0);
1416 /* Trim the stroke ends by finding self intersections using the screen space positions. */
1418 stroke, screen_space_positions, curve_mask, curve_mask, true);
1419
1420 /* No intersection found. */
1421 if (stroke_trimmed.is_empty()) {
1422 return;
1423 }
1424
1425 /* Remove the original stroke. */
1426 drawing.strokes_for_write().remove_curves(IndexRange::from_single(active_curve), {});
1427
1428 /* Join the trimmed stroke into the drawing. */
1429 add_strokes_to_drawing(on_back, bke::curves_new_nomain(std::move(stroke_trimmed)), drawing);
1430}
1431
1433 const int active_curve,
1434 const float4x4 &viewmat,
1435 const ed::greasepencil::DrawingPlacement &placement,
1436 const float outline_radius,
1437 const int material_index,
1438 const bool on_back)
1439{
1440 /* Get the outline stroke (single curve). */
1442 drawing,
1443 IndexRange::from_single(active_curve),
1444 viewmat,
1445 3,
1446 outline_radius,
1447 0.0f,
1448 material_index);
1449
1450 /* Reproject the outline onto the drawing placement. */
1451 placement.reproject(outline.positions(), outline.positions_for_write());
1452
1453 /* Remove the original stroke. */
1454 drawing.strokes_for_write().remove_curves(IndexRange::from_single(active_curve), {});
1455
1456 /* Join the outline stroke into the drawing. */
1457 add_strokes_to_drawing(on_back, bke::curves_new_nomain(std::move(outline)), drawing);
1458}
1459
1461 const float epsilon,
1462 const bool on_back,
1463 const int active_curve)
1464{
1465 const IndexRange points = drawing.strokes().points_by_curve()[active_curve];
1467 const VArray<float> radii = drawing.radii();
1468
1469 /* Remove points at the end that have a radius close to 0. */
1470 int64_t num_points_to_remove = 0;
1471 for (int64_t index = points.last(); index >= points.first(); index--) {
1472 if (radii[index] < epsilon) {
1473 num_points_to_remove++;
1474 }
1475 else {
1476 break;
1477 }
1478 }
1479
1480 if (num_points_to_remove <= 0) {
1481 return 0;
1482 }
1483
1484 /* Don't remove the entire stroke. Leave at least one point. */
1485 if (points.size() - num_points_to_remove < 1) {
1486 num_points_to_remove = points.size() - 1;
1487 }
1488
1489 if (!on_back) {
1490 curves.resize(curves.points_num() - num_points_to_remove, curves.curves_num());
1491 curves.offsets_for_write().last() = curves.points_num();
1492 return num_points_to_remove;
1493 }
1494
1495 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
1496
1497 /* Shift the data before resizing to not delete the data at the end. */
1498 const int current_points_num = curves.points_by_curve()[0].size();
1499 const int new_points_num = current_points_num - num_points_to_remove;
1500
1501 attributes.foreach_attribute([&](const bke::AttributeIter &iter) {
1502 if (iter.domain != bke::AttrDomain::Point) {
1503 return;
1504 }
1505
1507 bke::attribute_math::shift_left(dst.span, current_points_num, dst.span.size(), new_points_num);
1508 dst.finish();
1509 });
1510
1511 curves.resize(curves.points_num() - num_points_to_remove, curves.curves_num());
1512 MutableSpan<int> offsets = curves.offsets_for_write();
1513 for (const int src_curve : curves.curves_range().drop_front(1)) {
1514 offsets[src_curve] = offsets[src_curve] - num_points_to_remove;
1515 }
1516 offsets.last() = curves.points_num();
1517
1518 return num_points_to_remove;
1519}
1520
1521static void deselect_stroke(Scene *scene,
1523 const int active_curve)
1524{
1525 const IndexRange points = drawing.strokes().points_by_curve()[active_curve];
1526
1529 scene->toolsettings);
1530
1531 for (const StringRef selection_attribute_name :
1533 {
1535 curves, selection_domain, bke::AttrType::Bool, selection_attribute_name);
1536
1537 if (selection_domain == bke::AttrDomain::Curve) {
1539 selection.span.slice(IndexRange::from_single(active_curve)));
1540 }
1541 else if (selection_domain == bke::AttrDomain::Point) {
1542 ed::curves::fill_selection_false(selection.span.slice(points));
1543 }
1544
1545 selection.finish();
1546 }
1547}
1548
1549static void process_stroke_weights(const Scene &scene,
1550 const Object &object,
1552 const int active_curve)
1553{
1555 const IndexRange points = curves.points_by_curve()[active_curve];
1556
1557 const int def_nr = BKE_object_defgroup_active_index_get(&object) - 1;
1558
1559 if (def_nr == -1) {
1560 return;
1561 }
1562
1563 const bDeformGroup *defgroup = static_cast<const bDeformGroup *>(
1564 BLI_findlink(BKE_object_defgroup_list(&object), def_nr));
1565
1566 const StringRef vertex_group_name = defgroup->name;
1567
1569 curves, IndexMask(points), vertex_group_name, scene.toolsettings->vgroup_weight);
1570
1571 if (scene.toolsettings->vgroup_weight == 0.0f) {
1572 return;
1573 }
1574
1575 /* Loop through all modifiers trying to find the pose channel for the vertex group name. */
1576 bPoseChannel *channel = nullptr;
1577 Object *ob_arm = nullptr;
1578 for (ModifierData &md : (&object)->modifiers) {
1579 if (md.type != eModifierType_GreasePencilArmature) {
1580 continue;
1581 }
1582
1583 /* Skip not visible modifiers. */
1584 if (!(md.mode & eModifierMode_Realtime)) {
1585 continue;
1586 }
1587
1589 &md);
1590 if (amd == nullptr) {
1591 continue;
1592 }
1593
1594 ob_arm = amd->object;
1595 /* Not an armature. */
1596 if (ob_arm->type != OB_ARMATURE || ob_arm->pose == nullptr) {
1597 continue;
1598 }
1599
1600 channel = BKE_pose_channel_find_name(ob_arm->pose, vertex_group_name.data());
1601 if (channel == nullptr) {
1602 continue;
1603 }
1604
1605 /* Found the channel. */
1606 break;
1607 }
1608
1609 /* Nothing valid was found. */
1610 if (channel == nullptr) {
1611 return;
1612 }
1613
1614 const float4x4 obinv = math::invert(object.object_to_world());
1615
1616 const float4x4 postmat = obinv * ob_arm->object_to_world();
1617 const float4x4 premat = math::invert(postmat);
1618
1619 const float4x4 matrix = postmat * math::invert(float4x4(channel->chan_mat)) * premat;
1620
1621 /* Update the position of the stroke to undo the movement caused by the modifier. */
1622 MutableSpan<float3> positions = curves.positions_for_write().slice(points);
1623 math::transform_points(matrix, positions);
1624}
1625
1627{
1628
1629 const IndexRange points = src.points_by_curve()[curve];
1630 bke::CurvesGeometry dst(points.size(), 1);
1631
1632 Array<int> src_offsets({points.first(), points.one_after_last()});
1633 Array<int> dst_offsets({0, int(points.size())});
1634
1638 {},
1639 src_offsets.as_span(),
1640 dst_offsets.as_span(),
1641 IndexMask{1},
1642 dst.attributes_for_write());
1643
1644 src_offsets = {curve, curve + 1};
1645 dst_offsets = {0, 1};
1646
1650 {},
1651 src_offsets.as_span(),
1652 dst_offsets.as_span(),
1653 IndexMask{1},
1654 dst.attributes_for_write());
1655 return dst;
1656}
1657
1659 const bke::CurvesGeometry &src_strokes,
1660 const int curve,
1661 const int current_frame,
1662 const bool on_back,
1664{
1665 const bke::CurvesGeometry stroke = get_single_stroke(src_strokes, curve);
1666
1667 for (const ed::greasepencil::MutableDrawingInfo &drawing_info : drawings) {
1668 if (drawing_info.frame_number == current_frame) {
1669 continue;
1670 }
1671 add_strokes_to_drawing(on_back, bke::curves_new_nomain(stroke), drawing_info.drawing);
1672 }
1673}
1674
1676 const int active_curve,
1677 const float threshold,
1678 const int8_t curve_type)
1679{
1681 const IndexMask selection = IndexRange::from_single(active_curve);
1682 const VArray<float> thresholds = VArray<float>::from_single(threshold, curves.curves_num());
1683
1684 /* TODO: Detect or manually provide corners. */
1685 const VArray<bool> corners = VArray<bool>::from_single(false, curves.points_num());
1687 curves, selection, thresholds, corners, geometry::FitMethod::Refit, {});
1688
1689 if (curve_type == CURVE_TYPE_CATMULL_ROM) {
1691 options.convert_bezier_handles_to_poly_points = false;
1692 options.convert_bezier_handles_to_catmull_rom_points = false;
1693 options.keep_bezier_shape_as_nurbs = true;
1694 options.keep_catmull_rom_shape_as_nurbs = true;
1696 }
1697 else if (curve_type == CURVE_TYPE_NURBS) {
1699 options.convert_bezier_handles_to_poly_points = false;
1700 options.convert_bezier_handles_to_catmull_rom_points = false;
1701 options.keep_bezier_shape_as_nurbs = true;
1702 options.keep_catmull_rom_shape_as_nurbs = true;
1704 }
1705}
1706
1708{
1709 using namespace blender::bke;
1711 const ARegion *region = CTX_wm_region(&C);
1712 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object_->data);
1713
1714 Paint *paint = &scene_->toolsettings->gp_paint->paint;
1716 BrushGpencilSettings *settings = brush->gpencil_settings;
1717 const bool on_back = (scene_->toolsettings->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) != 0;
1718 const bool do_post_processing = (settings->flag & GP_BRUSH_GROUP_SETTINGS) != 0;
1719 const bool do_automerge_endpoints = (scene_->toolsettings->gpencil_flags &
1721 const bool use_fill = (settings->flag2 & GP_BRUSH_USE_FILL) != 0;
1722 const bool hide_fill_while_drawing = (settings->flag & GP_BRUSH_DISSABLE_LASSO) != 0;
1723
1724 /* Grease Pencil should have an active layer. */
1725 BLI_assert(grease_pencil.has_active_layer());
1726 bke::greasepencil::Layer &active_layer = *grease_pencil.get_active_layer();
1727 /* Drawing should exist. */
1728 bke::greasepencil::Drawing &drawing = *drawing_;
1729 const int active_curve = on_back ? drawing.strokes().curves_range().first() :
1730 drawing.strokes().curves_range().last();
1731 const offset_indices::OffsetIndices<int> points_by_curve = drawing.strokes().points_by_curve();
1732 const IndexRange points = points_by_curve[active_curve];
1733
1734 /* Write the screen space positions of the new stroke as a temporary attribute, so all the
1735 * changes in topology with the operations below get propagated correctly. */
1737 bke::SpanAttributeWriter<float2> screen_space_positions =
1738 attributes.convert_or_add_for_write_only_span<float2>(".draw_tool_screen_space_positions",
1740 BLI_assert(screen_space_positions);
1741 screen_space_positions.span.slice(points).copy_from(this->screen_space_final_coords_);
1742 screen_space_positions.finish();
1743
1744 if (use_fill && hide_fill_while_drawing) {
1745 /* The opacity was set to 10% while drawing. Reset it to the actual opacity now. */
1746 bke::SpanAttributeWriter<float> fill_opacities = attributes.lookup_for_write_span<float>(
1747 "fill_opacity");
1748 BLI_assert(fill_opacities);
1749 fill_opacities.span[active_curve] = fill_opacity_sum_ / fill_opacity_count_;
1750 fill_opacities.finish();
1751 }
1752
1753 /* Remove trailing points with radii close to zero. */
1754 trim_end_points(drawing, 1e-5f, on_back, active_curve);
1755
1756 if (do_post_processing) {
1757 if (settings->draw_subdivide > 0 && settings->simplify_px == 0.0f) {
1758 subdivide_stroke(drawing, settings->draw_subdivide, active_curve);
1759 }
1760 if (settings->draw_smoothfac > 0.0f && settings->draw_smoothlvl > 0) {
1761 smooth_stroke(drawing, settings->draw_smoothfac, settings->draw_smoothlvl, active_curve);
1762 }
1763 if (settings->simplify_px > 0.0f) {
1764 simplify_stroke(drawing, settings->simplify_px, active_curve);
1765 }
1766 if ((settings->flag & GP_BRUSH_TRIM_STROKE) != 0) {
1767 trim_stroke_ends(drawing, active_curve, on_back);
1768 }
1769 if ((scene_->toolsettings->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) != 0) {
1770 process_stroke_weights(*scene_, *object_, drawing, active_curve);
1771 }
1772 if ((settings->flag & GP_BRUSH_OUTLINE_STROKE) != 0) {
1773 const float outline_radius = BKE_brush_unprojected_radius_get(paint, brush) *
1774 settings->outline_fac;
1775 const int material_index = [&]() {
1777 CTX_data_main(&C), object_, brush);
1778 return BKE_object_material_index_get(object_, material);
1779 }();
1780 outline_stroke(drawing,
1781 active_curve,
1782 float4x4(rv3d->viewmat),
1783 placement_,
1784 outline_radius,
1785 material_index,
1786 on_back);
1787 }
1788 if (settings->curve_type != CURVE_TYPE_POLY) {
1790 drawing, active_curve, settings->conversion_threshold, settings->curve_type);
1791 }
1792 }
1793
1794 /* Set the selection of the newly drawn stroke to false. */
1795 deselect_stroke(scene_, drawing, active_curve);
1796
1797 /* Remove the temporary attribute. */
1798 attributes.remove(".draw_tool_screen_space_positions");
1799
1800 drawing.set_texture_matrices({texture_space_}, IndexRange::from_single(active_curve));
1801
1802 if (do_automerge_endpoints) {
1803 constexpr float merge_distance = 20.0f;
1804 const float4x4 layer_to_world = active_layer.to_world_space(*object_);
1805 const IndexMask selection = IndexRange::from_single(active_curve);
1807 *region, drawing.strokes(), layer_to_world, merge_distance, selection, {});
1808 }
1809
1810 if (do_automerge_endpoints || on_back) {
1811 drawing.tag_topology_changed();
1812 }
1813 else {
1814 drawing.tag_topology_changed(IndexRange::from_single(active_curve));
1815 }
1816
1817 const bool use_multi_frame_editing = (scene_->toolsettings->gpencil_flags &
1819
1820 if (use_multi_frame_editing) {
1822 drawing.strokes(), active_curve, frame_number_, on_back, multi_frame_drawings_);
1823 }
1824
1825 /* Now we're done drawing. */
1826 grease_pencil.runtime->is_drawing_stroke = false;
1827
1828 if (do_fill_guides_) {
1830 }
1831
1834}
1835
1836std::unique_ptr<GreasePencilStrokeOperation> new_paint_operation(const bool do_fill_guides)
1837{
1838 return std::make_unique<PaintOperation>(do_fill_guides);
1839}
1840
1841} // namespace blender::ed::sculpt_paint::greasepencil
Blender kernel action and pose functionality.
Low-level operations for curves.
support for deformation groups and hooks.
Low-level operations for grease pencil.
Utility functions for vertex groups in grease pencil objects.
General operations, lookup, etc. for materials.
Platform independent time functions.
#define C
Definition RandGen.cpp:29
#define NC_GEOM
Definition WM_types.hh:406
#define ND_DATA
Definition WM_types.hh:552
SIMD_FORCE_INLINE btScalar angle(const btVector3 &v) const
Return the angle between this and another vector.
Definition btVector3.h:356
int64_t size() const
Definition BLI_array.hh:267
Span< T > as_span() const
Definition BLI_array.hh:254
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
Array(Allocator allocator={}) noexcept
Definition BLI_array.hh:78
ChannelStorageType a
GMutableSpan slice(const int64_t start, int64_t size) const
static IndexMask from_bools(Span< bool > bools, LinearAllocator<> &memory)
constexpr int64_t first() const
constexpr int64_t one_after_last() const
constexpr IndexRange shift(int64_t n) const
constexpr int64_t last(const int64_t n=0) const
constexpr int64_t size() const
constexpr bool is_empty() const
constexpr IndexRange()=default
constexpr int64_t start() const
static constexpr IndexRange from_single(const int64_t index)
constexpr IndexRange index_range() const
static constexpr IndexRange from_begin_end_inclusive(const int64_t begin, const int64_t last)
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr MutableSpan slice(const int64_t start, const int64_t size) const
Definition BLI_span.hh:579
constexpr MutableSpan drop_back(const int64_t n) const
Definition BLI_span.hh:624
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
constexpr void copy_from(Span< T > values) const
Definition BLI_span.hh:745
constexpr T & last(const int64_t n=0) const
Definition BLI_span.hh:695
static RandomNumberGenerator from_random_seed()
Definition rand.cc:288
bool add(const Key &key)
Definition BLI_set.hh:248
void add_multiple(Span< Key > keys)
Definition BLI_set.hh:287
constexpr Span drop_front(int64_t n) const
Definition BLI_span.hh:175
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr Span drop_back(int64_t n) const
Definition BLI_span.hh:186
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
constexpr const T * end() const
Definition BLI_span.hh:228
constexpr const T * begin() const
Definition BLI_span.hh:224
Span< T > get_internal_span() const
static VArray from_single(T value, const int64_t size)
static VArray from_span(Span< T > values)
void foreach_attribute(const FunctionRef< void(const AttributeIter &)> fn) const
bool contains(StringRef name) const
GAttributeReader lookup(const StringRef name) const
MutableSpan< float3 > positions_for_write()
void remove_points(const IndexMask &points_to_delete, const AttributeFilter &attribute_filter)
AttributeAccessor attributes() const
Span< float3 > positions() const
IndexRange curves_range() const
void remove_curves(const IndexMask &curves_to_delete, const AttributeFilter &attribute_filter)
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())
GSpanAttributeWriter convert_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter convert_or_add_for_write_only_span(StringRef name, AttrDomain domain, AttrType data_type)
GSpanAttributeWriter lookup_for_write_span(StringRef name)
VArray< ColorGeometry4f > vertex_colors() const
MutableSpan< float > opacities_for_write()
MutableSpan< float > radii_for_write()
bke::CurvesGeometry & strokes_for_write()
const bke::CurvesGeometry & strokes() const
MutableSpan< ColorGeometry4f > fill_colors_for_write()
MutableSpan< ColorGeometry4f > vertex_colors_for_write()
void set_texture_matrices(Span< float4x2 > matrices, const IndexMask &selection)
float4x4 to_world_space(const Object &object) const
constexpr const char * data() const
std::optional< float > get_depth(float2 co) const
float3 place(float2 co, float depth) const
float3 project(float2 co, bool &clipped) const
void on_stroke_extended(const bContext &C, const InputSample &extension_sample) override
void on_stroke_begin(const bContext &C, const InputSample &start_sample) override
IndexRange interpolate_stroke_depth(std::optional< int > start_point, float from_depth, float to_depth)
CCL_NAMESPACE_BEGIN struct Options options
#define position
#define layer
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
#define T
void shift_left(GMutableSpan data, int src_begin, int src_end, int dst_begin)
T mix2(float factor, const T &a, const T &b)
void evaluate_segment(const T &point_0, const T &point_1, const T &point_2, const T &point_3, MutableSpan< T > result)
int get_next_available_fill_id(Span< int > fill_ids)
void assign_to_vertex_group_from_mask(CurvesGeometry &curves, const IndexMask &mask, StringRef name, float weight)
CurvesGeometry curves_copy_curve_selection(const CurvesGeometry &curves, const IndexMask &curves_to_copy, const AttributeFilter &attribute_filter)
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)
void copy_attributes_group_to_group(AttributeAccessor src_attributes, AttrDomain src_domain, AttrDomain dst_domain, const AttributeFilter &attribute_filter, OffsetIndices< int > src_offsets, OffsetIndices< int > dst_offsets, const IndexMask &selection, MutableAttributeAccessor dst_attributes)
Curves * curves_new_nomain(int points_num, int curves_num)
void fill_selection_false(GMutableSpan selection)
Span< StringRef > get_curves_selection_attribute_names(const bke::CurvesGeometry &curves)
bke::GSpanAttributeWriter ensure_selection_attribute(bke::CurvesGeometry &curves, bke::AttrDomain selection_domain, bke::AttrType create_type, StringRef attribute_name)
bke::CurvesGeometry trim_curve_segment_ends(const bke::CurvesGeometry &src, const Span< float2 > screen_space_positions, const IndexMask &editable_curves, const IndexMask &visible_curves, const bool keep_caps)
float opacity_from_input_sample(const float pressure, const Paint &paint, const Brush *brush, const BrushGpencilSettings *settings)
float randomize_rotation(const BrushGpencilSettings &settings, const float stroke_factor, const float distance, const float pressure)
void resize_single_curve(bke::CurvesGeometry &curves, const bool at_end, const int new_points_num)
float randomize_opacity(const BrushGpencilSettings &settings, const float stroke_factor, const float distance, const float opacity, const float pressure)
ColorGeometry4f randomize_color(const BrushGpencilSettings &settings, const std::optional< BrushColorJitterSettings > &jitter, const float stroke_hue_factor, const float stroke_saturation_factor, const float stroke_value_factor, const float distance, const ColorGeometry4f color, const float pressure)
float randomize_radius(const BrushGpencilSettings &settings, const float stroke_factor, const float distance, const float radius, const float pressure)
IndexMask polyline_detect_corners(Span< float2 > points, const float radius_min, const float radius_max, const int samples_max, const float angle_threshold, IndexMaskMemory &memory)
bke::CurvesGeometry curves_merge_endpoints_by_distance(const ARegion &region, const bke::CurvesGeometry &src_curves, const float4x4 &layer_to_world, const float merge_distance, const IndexMask &selection, const bke::AttributeFilter &attribute_filter)
Array< float2 > polyline_fit_curve(Span< float2 > points, const float error_threshold, const IndexMask &corner_mask)
Vector< MutableDrawingInfo > retrieve_editable_drawings(const Scene &scene, GreasePencil &grease_pencil)
float4x2 calculate_texture_space(const Scene *scene, const ARegion *region, const float2 &mouse, const DrawingPlacement &placement)
void add_single_curve(bke::greasepencil::Drawing &drawing, const bool at_end)
bke::CurvesGeometry create_curves_outline(const bke::greasepencil::Drawing &drawing, const IndexMask &strokes, const float4x4 &transform, const int corner_subdivisions, const float outline_radius, const float outline_offset, const int material_index)
float radius_from_input_sample(const RegionView3D *rv3d, const ARegion *region, const Paint &paint, const Brush *brush, const float pressure, const float3 &location, const float4x4 &to_world, const BrushGpencilSettings *settings)
static void convert_stroke_type(bke::greasepencil::Drawing &drawing, const int active_curve, const float threshold, const int8_t curve_type)
static void append_stroke_to_multiframe_drawings(const bke::CurvesGeometry &src_strokes, const int curve, const int current_frame, const bool on_back, Span< ed::greasepencil::MutableDrawingInfo > drawings)
std::unique_ptr< GreasePencilStrokeOperation > new_paint_operation(bool do_fill_guides=false)
static void trim_stroke_ends(bke::greasepencil::Drawing &drawing, const int active_curve, const bool on_back)
static float brush_radius_to_pixel_radius(const RegionView3D *rv3d, const Paint *paint, const Brush *brush, const float3 pos)
static bke::CurvesGeometry get_single_stroke(const bke::CurvesGeometry &src, const int curve)
static int trim_end_points(bke::greasepencil::Drawing &drawing, const float epsilon, const bool on_back, const int active_curve)
bool brush_using_vertex_color(const GpPaint *gp_paint, const Brush *brush)
static void morph_points_to_curve(Span< float2 > src, Span< float2 > target, MutableSpan< float2 > dst)
static void subdivide_stroke(bke::greasepencil::Drawing &drawing, const float subdivisions, const int active_curve)
static void simplify_stroke(bke::greasepencil::Drawing &drawing, const float epsilon, const int active_curve)
static void process_stroke_weights(const Scene &scene, const Object &object, bke::greasepencil::Drawing &drawing, const int active_curve)
static void smooth_stroke(bke::greasepencil::Drawing &drawing, const float influence, const int iterations, const int active_curve)
static void deselect_stroke(Scene *scene, bke::greasepencil::Drawing &drawing, const int active_curve)
static Array< float2 > sample_curve_2d(Span< float2 > positions, const int64_t resolution)
static void outline_stroke(bke::greasepencil::Drawing &drawing, const int active_curve, const float4x4 &viewmat, const ed::greasepencil::DrawingPlacement &placement, const float outline_radius, const int material_index, const bool on_back)
static void linear_interpolation(const T &a, const T &b, MutableSpan< T > dst)
static void add_strokes_to_drawing(const bool on_back, Curves *strokes, bke::greasepencil::Drawing &drawing)
bke::GeometrySet join_geometries(Span< bke::GeometrySet > geometries, const bke::AttributeFilter &attribute_filter, const std::optional< Span< bke::GeometryComponent::Type > > &component_types_to_join=std::nullopt, bool allow_merging_instance_references=true)
void smooth_curve_attribute(const IndexMask &curves_to_smooth, const OffsetIndices< int > points_by_curve, const VArray< bool > &point_selection, const VArray< bool > &cyclic, int iterations, float influence, bool smooth_ends, bool keep_shape, GMutableSpan attribute_data)
bke::CurvesGeometry fit_poly_to_bezier_curves(const bke::CurvesGeometry &src_curves, const IndexMask &curve_selection, const VArray< float > &thresholds, const VArray< bool > &corners, FitMethod method, const bke::AttributeFilter &attribute_filter)
Definition fit_curves.cc:25
bke::CurvesGeometry subdivide_curves(const bke::CurvesGeometry &src_curves, const IndexMask &selection, const VArray< int > &cuts, const bke::AttributeFilter &attribute_filter={})
void curve_simplify(const Span< float3 > positions, const bool cyclic, const float epsilon, const GSpan attribute_data, MutableSpan< bool > points_to_delete)
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)
bke::CurvesGeometry convert_curves(const bke::CurvesGeometry &src_curves, const IndexMask &selection, CurveType dst_type, const bke::AttributeFilter &attribute_filter, const ConvertCurvesOptions &options={})
void accumulate_lengths(const Span< T > values, const bool cyclic, MutableSpan< float > lengths)
void sample_at_lengths(Span< float > accumulated_segment_lengths, Span< float > sample_lengths, MutableSpan< int > r_segment_indices, MutableSpan< float > r_factors)
void interpolate(const Span< T > src, const Span< int > indices, const Span< float > factors, MutableSpan< T > dst)
T cos(const AngleRadianBase< T > &a)
T floor(const T &a)
T distance(const T &a, const T &b)
T dot(const QuaternionBase< T > &a, const QuaternionBase< T > &b)
CartesianBasis invert(const CartesianBasis &basis)
T interpolate(const T &a, const T &b, const FactorT &t)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
T sin(const AngleRadianBase< T > &a)
T max(const T &a, const T &b)
T abs(const T &a)
void transform_points(const float4x4 &transform, MutableSpan< float3 > points, bool use_threading=true)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
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
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned __int64 uint64_t
Definition BKE_text.h:91
__int64 int64_t
Definition BKE_text.h:90
@ GP_BRUSH_MODE_VERTEXCOLOR
const ListBaseT< bDeformGroup > * BKE_object_defgroup_list(const Object *ob)
Definition deform.cc:591
MINLINE void copy_v3_v3(float r[3], const float a[3])
Depsgraph * CTX_data_depsgraph_pointer(const bContext *C)
float ED_view3d_pixel_size(const RegionView3D *rv3d, const float co[3])
float BKE_brush_radius_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1366
@ eModifierType_GreasePencilArmature
void BKE_id_free_ex(Main *bmain, void *idv, int flag_orig, bool use_flag_from_idtag)
void BKE_brush_init_gpencil_settings(Brush *brush)
Definition brush.cc:719
@ LIB_ID_FREE_NO_MAIN
MatBase< float, 4, 4 > float4x4
float BKE_brush_unprojected_radius_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1412
void BKE_curvemapping_init(CurveMapping *cumap)
void * BLI_findlink(const ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:541
@ GP_TOOL_FLAG_CREATE_WEIGHTS
@ GP_TOOL_FLAG_PAINT_ONBACK
@ GP_TOOL_FLAG_AUTOMERGE_STROKE
@ GP_USE_MULTI_FRAME_EDITING
VecBase< float, 2 > float2
void DEG_id_tag_update(ID *id, unsigned int flags)
@ OB_MODE_PAINT_GREASE_PENCIL
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
MatBase< float, 4, 2 > float4x2
bke::AttrDomain ED_grease_pencil_edit_selection_domain_get(const ToolSettings *tool_settings)
RegionView3D * CTX_wm_region_view3d(const bContext *C)
bool BKE_paint_brush_set(Paint *paint, Brush *brush)
int BKE_object_material_index_get(Object *ob, const Material *ma)
void WM_event_add_notifier(const bContext *C, uint type, void *reference)
void * BKE_id_new_nomain(short type, const char *name)
Definition lib_id.cc:1617
MINLINE void copy_v3_fl3(float v[3], float x, float y, float z)
Main * CTX_data_main(const bContext *C)
@ CURVE_TYPE_CATMULL_ROM
Paint * BKE_paint_get_active_from_context(const bContext *C)
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
std::optional< BrushColorJitterSettings > BKE_brush_color_jitter_get_settings(const Paint *paint, const Brush *brush)
Definition brush.cc:1262
Brush * BKE_paint_brush(Paint *paint)
double BLI_time_now_seconds()
Definition time.cc:30
Material * BKE_grease_pencil_object_material_ensure_from_brush(Main *bmain, Object *ob, Brush *brush)
Scene * CTX_data_scene(const bContext *C)
float3 BKE_brush_color_get(const Paint *paint, const Brush *brush)
Definition brush.cc:1253
ColorSceneLinear4f< eAlpha::Premultiplied > ColorGeometry4f
@ GP_PROJECT_DEPTH_STROKE_ENDPOINTS
@ GP_PROJECT_DEPTH_STROKE_FIRST
VecBase< float, 3 > float3
@ GP_BRUSH_USE_STROKE
@ GP_BRUSH_OUTLINE_STROKE
@ GP_BRUSH_GROUP_RANDOM
@ GP_BRUSH_USE_STRENGTH_PRESSURE
@ GP_BRUSH_TRIM_STROKE
@ GP_BRUSH_DISSABLE_LASSO
@ GP_BRUSH_USE_PRESSURE
@ GP_BRUSH_GROUP_SETTINGS
@ GP_BRUSH_USE_CYCLIC_STROKE
@ GP_BRUSH_USE_JITTER_PRESSURE
Object * CTX_data_active_object(const bContext *C)
ARegion * CTX_wm_region(const bContext *C)
float BKE_curvemapping_evaluateF(const CurveMapping *cumap, int cur, float value)
bPoseChannel * BKE_pose_channel_find_name(const bPose *pose, const char *name)
View3D * CTX_wm_view3d(const bContext *C)
signed char int8_t
Definition BKE_text.h:76
Material * BKE_grease_pencil_object_material_alt_ensure_from_brush(Main *bmain, Object *ob, Brush *brush)
int BKE_object_defgroup_active_index_get(const Object *ob)
Definition deform.cc:613
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
struct CurveMapping * curve_sensitivity
struct CurveMapping * curve_jitter
struct CurveMapping * curve_rand_strength
struct CurveMapping * curve_rand_uv
struct CurveMapping * curve_rand_pressure
struct CurveMapping * curve_strength
struct CurveMapping * curve_rand_value
struct CurveMapping * curve_rand_saturation
struct BrushGpencilSettings * gpencil_settings
struct CurveMapping * curve_rand_hue
eBrushUnifiedPaintFlags unified_paint_flags
struct bPose * pose
struct ToolSettings * toolsettings
eGPencil_Flags gpencil_flags
eGPencil_Placement_Flags gpencil_v3d_align
static GeometrySet from_curves(Curves *curves, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
void process_start_sample(PaintOperation &self, const bContext &C, const InputSample &start_sample, const int material_index, const bool use_stroke, const bool use_fill)
void active_smoothing(PaintOperation &self, const IndexRange smooth_window)
void process_extension_sample(PaintOperation &self, const bContext &C, const InputSample &extension_sample)
void active_jitter(PaintOperation &self, const int new_points_num, const float brush_radius_px, const float pressure, const IndexRange active_window, MutableSpan< float3 > curve_positions)
void execute(PaintOperation &self, const bContext &C, const InputSample &extension_sample)