Blender V5.3
trace_util.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "BKE_attribute.hh"
6#include "BLI_color_types.hh"
7#include "BLI_math_matrix.hh"
8
9#include "BKE_curves.hh"
10
11#include "IMB_imbuf.hh"
12
13#include "MEM_guardedalloc.h"
14
15#ifdef WITH_POTRACE
16# include "potracelib.h"
17#endif
18
19#include "trace_util.hh"
20
22
23#ifdef WITH_POTRACE
24
25using PathSegment = potrace_dpoint_t[3];
26
27static int to_potrace(const TurnPolicy turn_policy)
28{
29 switch (turn_policy) {
30 case TurnPolicy ::Foreground:
31 return POTRACE_TURNPOLICY_BLACK;
32 case TurnPolicy ::Background:
33 return POTRACE_TURNPOLICY_WHITE;
34 case TurnPolicy ::Left:
35 return POTRACE_TURNPOLICY_LEFT;
36 case TurnPolicy ::Right:
37 return POTRACE_TURNPOLICY_RIGHT;
38 case TurnPolicy ::Minority:
39 return POTRACE_TURNPOLICY_MINORITY;
40 case TurnPolicy ::Majority:
41 return POTRACE_TURNPOLICY_MAJORITY;
42 case TurnPolicy ::Random:
43 return POTRACE_TURNPOLICY_RANDOM;
44 }
46 return POTRACE_TURNPOLICY_MINORITY;
47}
48
49Bitmap *create_bitmap(const int2 &size)
50{
51 constexpr int BM_WORDSIZE = int(sizeof(potrace_word));
52 constexpr int BM_WORDBITS = 8 * BM_WORDSIZE;
53
54 /* Number of words per scanline. */
55 const int32_t dy = (size.x + BM_WORDBITS - 1) / BM_WORDBITS;
56
57 potrace_bitmap_t *bm = MEM_new_uninitialized<potrace_bitmap_t>(__func__);
58 if (!bm) {
59 return nullptr;
60 }
61 bm->w = size.x;
62 bm->h = size.y;
63 bm->dy = dy;
64 bm->map = MEM_new_array_uninitialized<potrace_word>(size.y * dy, __func__);
65
66 return bm;
67}
68
69void free_bitmap(Bitmap *bm)
70{
71 if (bm != nullptr) {
72 MEM_delete(bm->map);
73 }
74 MEM_SAFE_DELETE(bm);
75}
76
77ImBuf *bitmap_to_image(const Bitmap &bm)
78{
79 constexpr int BM_WORDSIZE = int(sizeof(potrace_word));
80 constexpr int BM_WORDBITS = 8 * BM_WORDSIZE;
81 constexpr potrace_word BM_HIBIT = potrace_word(1) << (BM_WORDBITS - 1);
82
83 const int2 size = {bm.w, bm.h};
84 ImBuf *ibuf = IMB_allocImBuf(size.x, size.y, ImBufFlags::ByteData);
85 BLI_assert(ibuf->byte_data() != nullptr);
86
87 const int num_words = bm.dy * bm.h;
88 const int words_per_scanline = bm.dy;
89 const Span<potrace_word> words = {bm.map, num_words};
91 reinterpret_cast<ColorGeometry4b *>(ibuf->byte_data_for_write()),
93 threading::parallel_for(IndexRange(ibuf->y), 4096, [&](const IndexRange range) {
94 for (const int y : range) {
95 Span<potrace_word> scanline_words = words.slice(
96 IndexRange(words_per_scanline * y, words_per_scanline));
97 const MutableSpan<ColorGeometry4b> scanline_colors = colors.slice(
98 IndexRange(y * ibuf->x, ibuf->x));
99 for (uint32_t x = 0; x < ibuf->x; x++) {
100 const potrace_word &word = scanline_words[x / BM_WORDBITS];
101 const potrace_word mask = BM_HIBIT >> (x & (BM_WORDBITS - 1));
102 scanline_colors[x] = ((word & mask) != 0 ? ColorGeometry4b(255, 0, 0, 255) :
103 ColorGeometry4b(0, 0, 255, 255));
104 }
105 }
106 });
107
108 return ibuf;
109}
110
111Trace *trace_bitmap(const TraceParams &params, Bitmap &bm)
112{
113 potrace_param_t *po_params = potrace_param_default();
114 if (!po_params) {
115 return nullptr;
116 }
117 po_params->turdsize = params.size_threshold;
118 po_params->turnpolicy = to_potrace(params.turn_policy);
119 po_params->alphamax = params.alpha_max;
120 po_params->opticurve = params.optimize_curves;
121 po_params->opttolerance = params.optimize_tolerance;
122
123 potrace_state_t *st = potrace_trace(po_params, &bm);
124 potrace_param_free(po_params);
125
126 if (!st || st->status != POTRACE_STATUS_OK) {
127 if (st) {
128 potrace_state_free(st);
129 }
130 return nullptr;
131 }
132 return st;
133}
134
135void free_trace(Trace *trace)
136{
137 potrace_state_free(trace);
138}
139bke::CurvesGeometry trace_to_curves(const Trace &trace, const float4x4 &transform)
140{
141 return trace_to_curves(trace, [=](const int2 &pixel) {
142 return math::transform_point(transform, float3(pixel.x, pixel.y, 0));
143 });
144}
145
146bke::CurvesGeometry trace_to_curves(const Trace &trace,
147 FunctionRef<float3(const int2 &)> pixel_to_position)
148{
149 auto project_pixel = [&](const potrace_dpoint_t &point) -> float3 {
150 return pixel_to_position(int2(point.x, point.y));
151 };
152
153 /* Count paths and points. */
154 Vector<int> offsets;
155 for (const potrace_path_t *path = trace.plist; path != nullptr; path = path->next) {
156 const Span<int> path_tags = {path->curve.tag, path->curve.n};
157 const Span<PathSegment> path_segments = {path->curve.c, path->curve.n};
158
159 int point_num = 0;
160 for (const int segment_i : path_segments.index_range()) {
161 switch (path_tags[segment_i]) {
162 case POTRACE_CORNER:
163 point_num += 2;
164 break;
165 case POTRACE_CURVETO:
166 point_num += 1;
167 break;
168 default:
170 break;
171 }
172 }
173 offsets.append(point_num);
174 }
175 /* Last element stores total size. */
176 offsets.append(0);
177 const OffsetIndices points_by_curve = offset_indices::accumulate_counts_to_offsets(offsets);
178 if (points_by_curve.is_empty()) {
179 return {};
180 }
181
182 bke::CurvesGeometry curves(points_by_curve.total_size(), points_by_curve.size());
183 curves.offsets_for_write().copy_from(offsets);
184
185 /* Construct all curves as Bezier curves. */
186 curves.fill_curve_types(CURVE_TYPE_BEZIER);
187 /* All trace curves are cyclic. */
188 curves.attributes_for_write().add<bool>(
189 "cyclic", bke::AttrDomain::Curve, bke::AttributeInitValue(true));
190
191 MutableSpan<int8_t> handle_types_left = curves.handle_types_left_for_write();
192 MutableSpan<int8_t> handle_types_right = curves.handle_types_right_for_write();
193 MutableSpan<float3> handle_positions_left = curves.handle_positions_left_for_write();
194 MutableSpan<float3> handle_positions_right = curves.handle_positions_right_for_write();
195 MutableSpan<float3> positions = curves.positions_for_write();
196
197 /* Draw each curve. */
198 int curve_i = 0;
199 for (const potrace_path_t *path = trace.plist; path != nullptr; path = path->next, ++curve_i) {
200 const Span<int> path_tags = {path->curve.tag, path->curve.n};
201 const Span<PathSegment> path_segments = {path->curve.c, path->curve.n};
202
203 const IndexRange points = points_by_curve[curve_i];
204 if (points.is_empty()) {
205 continue;
206 }
207
208 /* POTRACE stores the last 3 points of a bezier segment.
209 * The start point is the last segment's end point. */
210 int point_i = points.last();
211 auto next_point = [&]() {
212 point_i = (point_i == points.last() ? points.first() : point_i + 1);
213 };
214
215 for (const int segment_i : path_segments.index_range()) {
216 const PathSegment &segment = path_segments[segment_i];
217 switch (path_tags[segment_i]) {
218 case POTRACE_CORNER:
219 /* POTRACE corners are formed by straight lines from the previous/next point.
220 * segment[0] is unused, segment[1] is the corner position, segment[2] is the next point.
221 */
222 handle_types_right[point_i] = BEZIER_HANDLE_VECTOR;
223
224 next_point();
225 positions[point_i] = project_pixel(segment[1]);
226 handle_types_left[point_i] = BEZIER_HANDLE_VECTOR;
227 handle_types_right[point_i] = BEZIER_HANDLE_VECTOR;
228
229 next_point();
230 positions[point_i] = project_pixel(segment[2]);
231 handle_types_left[point_i] = BEZIER_HANDLE_VECTOR;
232 break;
233 case POTRACE_CURVETO:
234 /* segment[0] is the previous point's right-side handle, segment[1] is the next point's
235 * left-side handle, segment[2] is the next point. */
236 handle_types_right[point_i] = BEZIER_HANDLE_FREE;
237 handle_positions_right[point_i] = project_pixel(segment[0]);
238
239 next_point();
240 positions[point_i] = project_pixel(segment[2]);
241 handle_types_left[point_i] = BEZIER_HANDLE_FREE;
242 handle_positions_left[point_i] = project_pixel(segment[1]);
243 break;
244 default:
246 break;
247 }
248 }
249 }
250
251 curves.tag_topology_changed();
252 curves.tag_positions_changed();
253 curves.tag_radii_changed();
254
255 /* Calculate handles for all corner points (vector handle type). */
256 curves.calculate_bezier_auto_handles();
257
258 return curves;
259}
260
261#endif
262
263} // namespace blender::ed::image_trace
Low-level operations for curves.
Read Blender memory allocation and freeing.
#define BLI_assert_unreachable()
SIMD_FORCE_INLINE btVector3 transform(const btVector3 &point) const
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr IndexRange()=default
MatBase< 4, 4 > float4x4
Segment< FEdge *, Vec3r > segment
void free_bitmap(Bitmap *bm)
bke::CurvesGeometry trace_to_curves(const Trace &trace, const float4x4 &transform)
Bitmap * create_bitmap(const int2 &size)
void free_trace(Trace *trace)
ImBuf * bitmap_to_image(const Bitmap &bm)
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
void * MEM_new_uninitialized(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
size_t IMB_get_pixel_count(const ImBuf *ibuf)
Get the length of the data of the given image buffer in pixels.
VecBase< int32_t, 2 > int2
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
signed int int32_t
Definition BKE_text.h:78
ColorSceneLinearByteEncoded4b< eAlpha::Premultiplied > ColorGeometry4b
void trace(Resources &srt, const LightprobeRenderData &lightprobes, const Uniform &uni, const draw::View &views, const Sampling &sampling, const gbuffer::Reader &reader, const uint3 group_id, const uint3 local_id)
const uint8_t * byte_data() const
uint8_t * byte_data_for_write()
Definition allocimbuf.cc:60