Blender V5.0
stl_import_mesh.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
8
9#include "BKE_mesh.hh"
10
11#include "BLI_array_utils.hh"
12#include "BLI_span.hh"
13
14#include "DNA_mesh_types.h"
15
16#include "stl_data.hh"
17#include "stl_import_mesh.hh"
18
19#include "CLG_log.h"
20static CLG_LogRef LOG = {"io.stl"};
21
22namespace blender::io::stl {
23
24STLMeshHelper::STLMeshHelper(int tris_num, bool use_custom_normals)
25 : use_custom_normals_(use_custom_normals)
26{
27 degenerate_tris_num_ = 0;
28 duplicate_tris_num_ = 0;
29 tris_.reserve(tris_num);
30 /* Upper bound (all vertices are unique). */
31 verts_.reserve(tris_num * 3);
32 if (use_custom_normals) {
33 loop_normals_.reserve(tris_num * 3);
34 }
35}
36
38{
39 int v1_id = verts_.index_of_or_add(data.vertices[0]);
40 int v2_id = verts_.index_of_or_add(data.vertices[1]);
41 int v3_id = verts_.index_of_or_add(data.vertices[2]);
42 if ((v1_id == v2_id) || (v1_id == v3_id) || (v2_id == v3_id)) {
43 degenerate_tris_num_++;
44 return false;
45 }
46 if (!tris_.add({v1_id, v2_id, v3_id})) {
47 duplicate_tris_num_++;
48 return false;
49 }
50
51 if (use_custom_normals_) {
52 loop_normals_.append_n_times(data.normal, 3);
53 }
54 return true;
55}
56
58{
59 if (degenerate_tris_num_ > 0) {
60 CLOG_WARN(&LOG, "Removed %d degenerate triangles during import", degenerate_tris_num_);
61 }
62 if (duplicate_tris_num_ > 0) {
63 CLOG_WARN(&LOG, "Removed %d duplicate triangles during import", duplicate_tris_num_);
64 }
65
66 Mesh *mesh = BKE_mesh_new_nomain(verts_.size(), 0, tris_.size(), tris_.size() * 3);
67 mesh->vert_positions_for_write().copy_from(verts_);
68 offset_indices::fill_constant_group_size(3, 0, mesh->face_offsets_for_write());
69 array_utils::copy(tris_.as_span().cast<int>(), mesh->corner_verts_for_write());
70
71 bke::mesh_smooth_set(*mesh, false);
72
73 /* NOTE: edges must be calculated first before setting custom normals. */
74 bke::mesh_calc_edges(*mesh, false, false);
75
76 if (use_custom_normals_ && loop_normals_.size() == mesh->corners_num) {
77 bke::mesh_set_custom_normals(*mesh, loop_normals_);
78 }
79
80 return mesh;
81}
82
83} // namespace blender::io::stl
Mesh * BKE_mesh_new_nomain(int verts_num, int edges_num, int faces_num, int corners_num)
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
BMesh const char void * data
bool add_triangle(const PackedTriangle &data)
STLMeshHelper(int tris_num, bool use_custom_normals)
#define LOG(level)
Definition log.h:97
void copy(const GVArray &src, GMutableSpan dst, int64_t grain_size=4096)
void mesh_smooth_set(Mesh &mesh, bool use_smooth, bool keep_sharp_edges=false)
void mesh_calc_edges(Mesh &mesh, bool keep_existing_edges, bool select_new_edges)
void mesh_set_custom_normals(Mesh &mesh, MutableSpan< float3 > corner_normals)
void fill_constant_group_size(int size, int start_offset, MutableSpan< int > offsets)
int corners_num