16#include <lagrange/Attribute.h>
17#include <lagrange/AttributeTypes.h>
18#include <lagrange/ExactPredicatesShewchuk.h>
19#include <lagrange/IndexedAttribute.h>
20#include <lagrange/Logger.h>
21#include <lagrange/SurfaceMeshTypes.h>
22#include <lagrange/cast_attribute.h>
23#include <lagrange/find_matching_attributes.h>
24#include <lagrange/map_attribute.h>
25#include <lagrange/solver/DirectSolver.h>
26#include <lagrange/triangulate_polygonal_facets.h>
27#include <lagrange/utils/Error.h>
28#include <lagrange/utils/fmt_eigen.h>
29#include <lagrange/views.h>
30#include <lagrange/weld_indexed_attribute.h>
33#include "ThreadPool.h"
34#define MULTI_THREADING_INCLUDED
35using namespace lagrange::texproc::threadpool;
38#include <lagrange/utils/warnoff.h>
39#include <Misha/RegularGrid.h>
40#include <Src/PreProcessing.h>
41#include <Src/GradientDomain.h>
42#include <lagrange/utils/warnon.h>
45#include <Eigen/Sparse>
49namespace lagrange::texproc {
53using namespace MishaK;
56template <
typename T,
unsigned N>
57using Vector = MishaK::Point<T, N>;
60static const unsigned int Dim = 3;
63static const unsigned int K = 2;
66using Solver = lagrange::solver::SolverLDLT<Eigen::SparseMatrix<double>>;
70enum class RequiresIndexedTexcoords { Yes, No };
71enum class CheckFlippedUV { Yes, No };
75template <
unsigned int NumChannels,
typename ValueType>
77 image::experimental::View3D<ValueType> texture,
80 unsigned int num_channels =
static_cast<unsigned int>(texture.extent(2));
81 if (num_channels != NumChannels)
la_debug_assert(
"Number of channels don't match");
84 grid.resize(texture.extent(0), texture.extent(1));
85 for (
unsigned int j = 0; j < grid.res(1); j++) {
86 for (
unsigned int i = 0; i < grid.res(0); i++) {
87 for (
unsigned int c = 0; c < NumChannels; c++) {
88 grid(i, j)[c] = texture(i, j, c);
94template <
unsigned int NumChannels,
typename ValueType>
97 image::experimental::View3D<ValueType> texture)
100 for (
unsigned int j = 0; j < grid.res(1); j++) {
101 for (
unsigned int i = 0; i < grid.res(0); i++) {
102 for (
unsigned int c = 0; c < NumChannels; c++) {
103 texture(i, j, c) = grid(i, j)[c];
109template <
typename ValueType>
111 const RegularGrid<K, double>& grid,
112 image::experimental::View3D<ValueType> texture)
115 for (
unsigned int j = 0; j < grid.res(1); j++) {
116 for (
unsigned int i = 0; i < grid.res(0); i++) {
117 texture(i, j, 0) = grid(i, j);
122template <
unsigned int NumChannels>
123void clamp_out_of_range(
125 const MishaK::TSP::GradientDomain<double>& gd,
126 std::pair<double, double>
range = {0.0, 1.0},
127 bool mark_out_of_range =
false)
129 size_t num_interior_out_of_range = 0;
130 size_t num_exterior_out_of_range = 0;
134 for (
unsigned int c = 0; c < NumChannels; c++) {
135 red[c] = (c == 0 ? 1.0 : 0.0);
136 green[c] = (c == 1 ? 1.0 : 0.0);
140 constexpr double eps = 1e-6;
141 for (
unsigned int c = 0; c < NumChannels; c++) {
142 if (p[c] <
range.first - eps || p[c] >
range.second + eps) {
149 for (
size_t n = 0; n < gd.numNodes(); ++n) {
150 const bool is_strictly_out = is_out_of_range(x[n]);
151 for (
unsigned int c = 0; c < NumChannels; c++) {
152 x[n][c] = std::clamp(x[n][c],
range.first,
range.second);
154 if (is_strictly_out) {
155 if (gd.isCovered(n)) {
156 num_interior_out_of_range++;
157 if (mark_out_of_range) {
161 num_exterior_out_of_range++;
162 if (mark_out_of_range) {
168 if (num_interior_out_of_range || num_exterior_out_of_range) {
170 "{} interior and {} exterior texels were out of range and have been clamped.",
171 num_interior_out_of_range,
172 num_exterior_out_of_range);
176template <
typename Scalar,
typename Index>
177void check_for_flipped_uv(
const SurfaceMesh<Scalar, Index>& mesh,
AttributeId id)
182 const auto& uv_attr = mesh.template get_indexed_attribute<Scalar>(
id);
185 return {uv_values, uv_indices};
187 const auto& uv_attr = mesh.template get_attribute<Scalar>(
id);
191 "UV attribute must be per-vertex or per-corner.");
197 : std::optional<ConstRowMatrixView<Index>>(
facet_view(mesh))};
201 auto uv_index = [&](Index f,
unsigned int k) {
202 if (uv_mesh.second.has_value()) {
203 return (*uv_mesh.second)(f, k);
209 ExactPredicatesShewchuk predicates;
211 Eigen::RowVector2d p0 = uv_mesh.first.row(uv_index(f, 0)).template
cast<double>();
212 Eigen::RowVector2d p1 = uv_mesh.first.row(uv_index(f, 1)).template
cast<double>();
213 Eigen::RowVector2d p2 = uv_mesh.first.row(uv_index(f, 2)).template
cast<double>();
214 auto r = predicates.
orient2D(p0.data(), p1.data(), p2.data());
218 "The input mesh has flipped UVs:\n p0=({:.3g})\n p1=({:.3g})\n p2=("
220 "Please fix the input mesh before proceeding.",
223 fmt::join(p2,
", ")));
251template <
typename Scalar>
256 double epsilon = 1e-4)
258 if (std::abs(epsilon) < std::numeric_limits<double>().denorm_min()) {
262 Scalar jitter_scale =
static_cast<Scalar>(epsilon / std::max<unsigned int>(width, height));
264 std::uniform_real_distribution<Scalar> dist(-jitter_scale, jitter_scale);
265 for (
auto& x : texcoords_buffer) {
271template <
typename Scalar>
272Eigen::SparseMatrix<Scalar> laplacian_regularization(Eigen::SparseMatrix<Scalar> S,
Scalar eps)
275 tbb::parallel_for(
size_t(0),
size_t(S.outerSize()), [&](
size_t c) {
277 for (typename Eigen::SparseMatrix<Scalar>::InnerIterator it(S, c); it; ++it) {
278 if (it.row() != it.col()) {
279 it.valueRef() -= eps;
283 for (
typename Eigen::SparseMatrix<Scalar>::InnerIterator it(S, c); it; ++it) {
284 if (it.row() == it.col()) {
285 it.valueRef() += eps * count;
293template <
typename Scalar,
typename Index>
300 size_t num_simplices()
const {
return static_cast<size_t>(mesh.get_num_facets()); }
301 size_t num_vertices()
const {
return static_cast<size_t>(mesh.get_num_vertices()); }
302 size_t num_texcoords()
const {
return texcoords.size() / K; }
307 for (
unsigned int d = 0; d < Dim; d++) {
308 p[d] =
static_cast<double>(vertices[i * Dim + d]);
316 for (
unsigned int k = 0; k < K; k++) {
317 q[k] =
static_cast<double>(texcoords[i * K + k]);
325 for (
unsigned int k = 0; k < K; k++) {
326 q[k] =
static_cast<double>(texcoords[i * K + k]);
332 int vertex_index(
size_t f,
unsigned int k)
const
334 return static_cast<int>(vertex_indices[f * (K + 1) + k]);
337 int texture_index(
size_t f,
unsigned int k)
const
339 switch (texture_element) {
343 default:
la_debug_assert(
"Unsupported texture element type");
return 0;
347 Simplex<double, K, K> simplex_texcoords(
size_t f)
const
349 Simplex<double, K, K> s;
350 for (
unsigned int k = 0; k <= K; k++) {
351 s[k] = texcoord(texture_index(f, k));
356 Simplex<double, K, K> vflipped_simplex_texcoords(
size_t f)
const
358 Simplex<double, K, K> s;
359 for (
unsigned int k = 0; k <= K; k++) {
360 s[k] = vflipped_texcoord(texture_index(f, k));
365 Simplex<double, Dim, K> simplex_vertices(
size_t f)
const
367 Simplex<double, Dim, K> s;
368 for (
unsigned int k = 0; k <= K; k++) {
369 s[k] = vertex(vertex_index(f, k));
374 SimplexIndex<K> facet_indices(
size_t f)
const
376 SimplexIndex<K> simplex;
377 for (
unsigned int k = 0; k <= K; ++k) {
378 simplex[k] =
static_cast<int>(vertex_indices[f * (K + 1) + k]);
391template <
typename Scalar,
typename Index>
394 RequiresIndexedTexcoords requires_indexed_texcoords,
395 CheckFlippedUV check_flipped_uv)
407 texcoord_id = res.value();
412 if (!_mesh.template is_attribute_type<Scalar>(texcoord_id)) {
414 "Input uv coordinates do not have the same scalar type as the input points. Casting "
420 if (requires_indexed_texcoords == RequiresIndexedTexcoords::Yes &&
422 logger().warn(
"UV coordinates are not indexed. Welding.");
424 weld_indexed_attribute(_mesh, texcoord_id);
430 "Numer of corners doesn't match the number of simplices");
432 if (check_flipped_uv == CheckFlippedUV::Yes) {
433 check_for_flipped_uv(_mesh, texcoord_id);
439 auto& uv_attr = _mesh.template ref_indexed_attribute<Scalar>(texcoord_id);
440 wrapper.texcoords = uv_attr.values().ref_all();
441 wrapper.texture_indices = uv_attr.indices().get_all();
444 auto& uv_attr = _mesh.template ref_attribute<Scalar>(texcoord_id);
445 wrapper.texcoords = uv_attr.ref_all();
446 wrapper.texture_indices = {};
447 wrapper.texture_element = uv_attr.get_element_type();
455template <
typename Scalar,
typename Index>
456Padding create_padding(MeshWrapper<Scalar, Index>& wrapper,
unsigned int width,
unsigned int height)
458 static_assert(
sizeof(std::array<Scalar, 2>) == 2 *
sizeof(
Scalar));
460 reinterpret_cast<std::array<Scalar, 2>*
>(wrapper.texcoords.data()),
461 wrapper.num_texcoords());
463 padding = Padding::init<Scalar>(width, height, texcoords);
464 padding.pad(width, height, texcoords);
AttributeElement get_element_type() const
Gets the attribute element type.
Definition Attribute.h:101
lagrange::span< const ValueType > get_all() const
Returns a read-only view of the buffer spanning num elements x num channels.
Definition Attribute.cpp:512
virtual short orient2D(double p1[2], double p2[2], double p3[2]) const
Exact 2D orientation test.
Definition ExactPredicatesShewchuk.cpp:37
A general purpose polygonal mesh class.
Definition SurfaceMesh.h:66
const AttributeBase & get_attribute_base(std::string_view name) const
Gets a read-only reference to the base class of attribute given its name.
Definition SurfaceMesh.cpp:1277
bool is_attribute_indexed(std::string_view name) const
Determines whether the specified attribute is indexed.
Definition SurfaceMesh.cpp:1236
const Attribute< Index > & get_corner_to_vertex() const
Gets a read-only reference to the corner -> vertex id attribute.
Definition SurfaceMesh.cpp:1400
Index get_num_facets() const
Retrieves the number of facets.
Definition SurfaceMesh.h:687
const Attribute< Scalar > & get_vertex_to_position() const
Gets a read-only reference to the vertex -> positions attribute.
Definition SurfaceMesh.cpp:1388
Index get_num_corners() const
Retrieves the number of corners.
Definition SurfaceMesh.h:694
LA_CORE_API spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:40
AttributeId map_attribute_in_place(SurfaceMesh< Scalar, Index > &mesh, AttributeId id, AttributeElement new_element)
Map attribute values to a different element type.
Definition map_attribute.cpp:270
uint32_t AttributeId
Identified to be used to access an attribute.
Definition AttributeFwd.h:73
AttributeElement
Type of element to which the attribute is attached.
Definition AttributeFwd.h:26
@ UV
Mesh attribute must have exactly 2 channels.
Definition AttributeFwd.h:62
@ Scalar
Mesh attribute must have exactly 1 channel.
Definition AttributeFwd.h:56
@ Value
Values that are not attached to a specific element.
Definition AttributeFwd.h:42
@ Indexed
Indexed mesh attributes.
Definition AttributeFwd.h:45
@ Corner
Per-corner mesh attributes.
Definition AttributeFwd.h:37
@ Vertex
Per-vertex mesh attributes.
Definition AttributeFwd.h:28
AttributeId cast_attribute_in_place(SurfaceMesh< Scalar, Index > &mesh, AttributeId attribute_id)
Cast an attribute in place to a different value type.
Definition cast_attribute.cpp:68
std::optional< AttributeId > find_matching_attribute(const SurfaceMesh< Scalar, Index > &mesh, const AttributeMatcher &options)
Finds the first attribute with the specified usage/element type/number of channels.
Definition find_matching_attributes.cpp:37
void triangulate_polygonal_facets(SurfaceMesh< Scalar, Index > &mesh, const TriangulationOptions &options={})
Triangulate polygonal facets of a mesh using a prescribed set of rules.
Definition triangulate_polygonal_facets.cpp:520
SurfaceMesh< ToScalar, ToIndex > cast(const SurfaceMesh< FromScalar, FromIndex > &source_mesh, const AttributeFilter &convertible_attributes={}, std::vector< std::string > *converted_attributes_names=nullptr)
Cast a mesh to a mesh of different scalar and/or index type.
ConstRowMatrixView< ValueType > matrix_view(const Attribute< ValueType > &attribute)
Returns a read-only view of a given attribute in the form of an Eigen matrix.
Definition views.cpp:35
Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > Vector
Type alias for one-dimensional column Eigen vectors.
Definition views.h:79
ConstRowMatrixView< ValueType > reshaped_view(const Attribute< ValueType > &attribute, size_t num_cols)
Returns a read-only view of a given single-channel attribute in the form of an Eigen matrix with a pr...
Definition views.cpp:71
ConstRowMatrixView< Index > facet_view(const SurfaceMesh< Scalar, Index > &mesh)
Returns a read-only view of a mesh facets in the form of an Eigen matrix.
Definition views.cpp:170
const Eigen::Map< const RowMatrix< Scalar >, Eigen::Unaligned > ConstRowMatrixView
Type alias for row-major const matrix view.
Definition views.h:75
#define la_runtime_assert(...)
Runtime assertion check.
Definition assert.h:174
#define la_debug_assert(...)
Debug assertion check.
Definition assert.h:194
internal::Range< Index > range(Index end)
Returns an iterable object representing the range [0, end).
Definition range.h:176
::nonstd::span< T, Extent > span
A bounds-safe view for sequences of objects.
Definition span.h:27
@ Error
Throw an error if collision is detected.
Definition MappingPolicy.h:24
Definition mesh_utils.h:295