Blender V5.3
obj_import_mtl.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_image.hh"
10#include "BKE_main.hh"
11#include "BKE_node.hh"
13
14#include "BLI_math_vector_c.hh"
15#include "BLI_path_utils.hh"
16#include "BLI_string.hh"
17
18#include "DNA_material_types.h"
19#include "DNA_node_types.h"
20
21#include "NOD_shader.h"
22
23#include "obj_export_mtl.hh"
24#include "obj_import_mtl.hh"
25
26#include "CLG_log.h"
27
28namespace blender {
29
30static CLG_LogRef LOG = {"io.obj"};
31
32namespace io::obj {
33
39 const char *socket_id,
40 Span<float> value,
41 bNode *r_node)
42{
43 BLI_assert(r_node);
44 bNodeSocket *socket{bke::node_find_socket(*r_node, SOCK_IN, UString(socket_id))};
45 BLI_assert(socket && socket->type == property_type);
46 switch (property_type) {
47 case SOCK_FLOAT: {
48 BLI_assert(value.size() == 1);
49 static_cast<bNodeSocketValueFloat *>(socket->default_value)->value = value[0];
50 break;
51 }
52 case SOCK_RGBA: {
53 /* Alpha will be added manually. It is not read from the MTL file either. */
54 BLI_assert(value.size() == 3);
55 copy_v3_v3(static_cast<bNodeSocketValueRGBA *>(socket->default_value)->value, value.data());
56 static_cast<bNodeSocketValueRGBA *>(socket->default_value)->value[3] = 1.0f;
57 break;
58 }
59 case SOCK_VECTOR: {
60 BLI_assert(value.size() == 3);
62 value.data());
63 break;
64 }
65 default: {
66 BLI_assert(0);
67 break;
68 }
69 }
70}
71
72static Image *load_image_at_path(Main *bmain, const std::string &path, bool relative_paths)
73{
74 Image *image = BKE_image_load_exists(bmain, path.c_str());
75 if (!image) {
76 CLOG_WARN(&LOG, "Cannot load image file: '%s'", path.c_str());
77 return nullptr;
78 }
79 CLOG_INFO(&LOG, "Loaded image from: '%s'", path.c_str());
80 if (relative_paths) {
82 BLI_path_normalize(image->filepath);
83 }
84 return image;
85}
86
87static Image *create_placeholder_image(Main *bmain, const std::string &path)
88{
89 /* Create image without checking if it can be opened. */
90 return BKE_image_load_exists(bmain, path.c_str(), false);
91}
92
93static Image *load_texture_image(Main *bmain, const MTLTexMap &tex_map, bool relative_paths)
94{
95 Image *image = nullptr;
96
97 /* Remove quotes. */
98 std::string image_path{tex_map.image_path};
99 auto end_pos = std::remove(image_path.begin(), image_path.end(), '"');
100 image_path.erase(end_pos, image_path.end());
101
102 /* First try treating texture path as relative. */
103 std::string tex_path{tex_map.mtl_dir_path + image_path};
104 image = load_image_at_path(bmain, tex_path, relative_paths);
105 if (image != nullptr) {
106 return image;
107 }
108 /* Then try using it directly as absolute path. */
109 image = load_image_at_path(bmain, image_path, relative_paths);
110 if (image != nullptr) {
111 return image;
112 }
113 /* Try replacing underscores with spaces. */
114 std::string no_underscore_path{image_path};
115 std::replace(no_underscore_path.begin(), no_underscore_path.end(), '_', ' ');
116 if (!ELEM(no_underscore_path, image_path, tex_path)) {
117 image = load_image_at_path(bmain, no_underscore_path, relative_paths);
118 if (image != nullptr) {
119 return image;
120 }
121 }
122 /* Try taking just the basename from input path. */
123 std::string base_path{tex_map.mtl_dir_path + BLI_path_basename(image_path.c_str())};
124 if (base_path != tex_path) {
125 image = load_image_at_path(bmain, base_path, relative_paths);
126 if (image != nullptr) {
127 return image;
128 }
129 }
130
131 image = create_placeholder_image(bmain, tex_path);
132 return image;
133}
134
135/* Nodes are arranged in columns by type, with manually placed x coordinates
136 * based on node widths. */
137const float node_locx_texcoord = -880.0f;
138const float node_locx_mapping = -680.0f;
139const float node_locx_image = -480.0f;
140const float node_locx_normalmap = -200.0f;
141const float node_locx_bsdf = 0.0f;
142const float node_locx_output = 280.0f;
143
144/* Nodes are arranged in rows; one row for each image being used. */
145const float node_locy_top = 300.0f;
146const float node_locy_step = 300.0f;
147
148/* Add a node of the given type at the given location. */
149static bNode *add_node(bNodeTree *ntree, int type, float x, float y)
150{
151 bNode *node = bke::node_add_static_node(nullptr, *ntree, type);
152 node->location[0] = x;
153 node->location[1] = y;
154 return node;
155}
156
157static void link_sockets(bNodeTree *ntree,
158 bNode *from_node,
159 const char *from_node_id,
160 bNode *to_node,
161 const char *to_node_id)
162{
163 bNodeSocket *from_sock{bke::node_find_socket(*from_node, SOCK_OUT, UString(from_node_id))};
164 bNodeSocket *to_sock{bke::node_find_socket(*to_node, SOCK_IN, UString(to_node_id))};
165 BLI_assert(from_sock && to_sock);
166 bke::node_add_link(*ntree, *from_node, *from_sock, *to_node, *to_sock);
167}
168
169static void set_bsdf_socket_values(bNode *bsdf, Material *mat, const MTLMaterial &mtl_mat)
170{
171 const int illum = mtl_mat.illum_mode;
172 bool do_highlight = false;
173 bool do_tranparency = false;
174 bool do_reflection = false;
175 bool do_glass = false;
176 /* See https://wikipedia.org/wiki/Wavefront_.obj_file for possible values of illum. */
177 switch (illum) {
178 case -1:
179 case 1:
180 /* Base color on, ambient on. */
181 break;
182 case 2: {
183 /* Highlight on. */
184 do_highlight = true;
185 break;
186 }
187 case 3: {
188 /* Reflection on and Ray trace on. */
189 do_reflection = true;
190 break;
191 }
192 case 4: {
193 /* Transparency: Glass on, Reflection: Ray trace on. */
194 do_glass = true;
195 do_reflection = true;
196 do_tranparency = true;
197 break;
198 }
199 case 5: {
200 /* Reflection: Fresnel on and Ray trace on. */
201 do_reflection = true;
202 break;
203 }
204 case 6: {
205 /* Transparency: Refraction on, Reflection: Fresnel off and Ray trace on. */
206 do_reflection = true;
207 do_tranparency = true;
208 break;
209 }
210 case 7: {
211 /* Transparency: Refraction on, Reflection: Fresnel on and Ray trace on. */
212 do_reflection = true;
213 do_tranparency = true;
214 break;
215 }
216 case 8: {
217 /* Reflection on and Ray trace off. */
218 do_reflection = true;
219 break;
220 }
221 case 9: {
222 /* Transparency: Glass on, Reflection: Ray trace off. */
223 do_glass = true;
224 do_reflection = false;
225 do_tranparency = true;
226 break;
227 }
228 default: {
229 CLOG_WARN(&LOG,
230 "Material illum value '%d' is not supported by the Principled BSDF shader.",
231 illum);
232 break;
233 }
234 }
235 /* Approximations for trying to map obj/mtl material model into
236 * Principled BSDF: */
237 /* Specular: average of Ks components. */
238 float specular = (mtl_mat.spec_color[0] + mtl_mat.spec_color[1] + mtl_mat.spec_color[2]) / 3;
239 if (specular < 0.0f) {
240 specular = do_highlight ? 1.0f : 0.0f;
241 }
242 /* Roughness: map 0..1000 range to 1..0 and apply non-linearity. */
243 float roughness;
244 if (mtl_mat.spec_exponent < 0.0f) {
245 roughness = do_highlight ? 0.0f : 1.0f;
246 }
247 else {
248 float clamped_ns = std::max(0.0f, std::min(1000.0f, mtl_mat.spec_exponent));
249 roughness = 1.0f - sqrt(clamped_ns / 1000.0f);
250 }
251 /* Metallic: average of `Ka` components. */
252 float metallic = (mtl_mat.ambient_color[0] + mtl_mat.ambient_color[1] +
253 mtl_mat.ambient_color[2]) /
254 3;
255 if (do_reflection) {
256 if (metallic < 0.0f) {
257 metallic = 1.0f;
258 }
259 }
260 else {
261 metallic = 0.0f;
262 }
263
264 float ior = mtl_mat.ior;
265 if (ior < 0) {
266 if (do_tranparency) {
267 ior = 1.0f;
268 }
269 if (do_glass) {
270 ior = 1.5f;
271 }
272 }
273 float alpha = mtl_mat.alpha;
274 if (do_tranparency && alpha < 0) {
275 alpha = 1.0f;
276 }
277
278 /* PBR values, when present, override the ones calculated above. */
279 if (mtl_mat.roughness >= 0) {
280 roughness = mtl_mat.roughness;
281 }
282 if (mtl_mat.metallic >= 0) {
283 metallic = mtl_mat.metallic;
284 }
285
286 float3 base_color = mtl_mat.color;
287 if (base_color.x >= 0 && base_color.y >= 0 && base_color.z >= 0) {
288 set_property_of_socket(SOCK_RGBA, "Base Color", {base_color, 3}, bsdf);
289 /* Viewport shading uses legacy r,g,b base color. */
290 mat->r = base_color.x;
291 mat->g = base_color.y;
292 mat->b = base_color.z;
293 }
294
296 set_property_of_socket(SOCK_FLOAT, "Emission Strength", {1.0f}, bsdf);
297 }
298
299 float3 emission_color = mtl_mat.emission_color;
300 if (emission_color.x >= 0 && emission_color.y >= 0 && emission_color.z >= 0) {
301 float emission_strength = fmax(emission_color.x, fmax(emission_color.y, emission_color.z));
302 if (emission_strength > 1.0f) {
303 /* For colors brighter than 1.0, change color to be in 0..1 range, and set emission
304 * strength accordingly. */
306 SOCK_RGBA, "Emission Color", {emission_color / emission_strength, 3}, bsdf);
307 set_property_of_socket(SOCK_FLOAT, "Emission Strength", {emission_strength}, bsdf);
308 }
309 else {
310 set_property_of_socket(SOCK_RGBA, "Emission Color", {emission_color, 3}, bsdf);
311 set_property_of_socket(SOCK_FLOAT, "Emission Strength", {1.0f}, bsdf);
312 }
313 }
314
315 set_property_of_socket(SOCK_FLOAT, "Specular IOR Level", {specular}, bsdf);
316 set_property_of_socket(SOCK_FLOAT, "Roughness", {roughness}, bsdf);
317 mat->roughness = roughness;
318 set_property_of_socket(SOCK_FLOAT, "Metallic", {metallic}, bsdf);
319 mat->metallic = metallic;
320 /* Some files have `Ni 0`, ignore those values. */
321 if (ior > 0.0f) {
322 set_property_of_socket(SOCK_FLOAT, "IOR", {ior}, bsdf);
323 }
324 if (alpha != -1) {
325 set_property_of_socket(SOCK_FLOAT, "Alpha", {alpha}, bsdf);
326 }
327 if (do_tranparency || (alpha >= 0.0f && alpha < 1.0f)) {
328 mat->blend_method = MA_BM_BLEND;
329 mat->blend_flag |= MA_BL_HIDE_BACKFACE;
330 }
331
332 if (mtl_mat.sheen >= 0) {
333 set_property_of_socket(SOCK_FLOAT, "Sheen Weight", {mtl_mat.sheen}, bsdf);
334 }
335 if (mtl_mat.cc_thickness >= 0) {
336 /* Clearcoat used to include an implicit 0.25 factor, so stay compatible to old versions. */
337 set_property_of_socket(SOCK_FLOAT, "Coat Weight", {0.25f * mtl_mat.cc_thickness}, bsdf);
338 }
339 if (mtl_mat.cc_roughness >= 0) {
340 set_property_of_socket(SOCK_FLOAT, "Coat Roughness", {mtl_mat.cc_roughness}, bsdf);
341 }
342 if (mtl_mat.aniso >= 0) {
343 set_property_of_socket(SOCK_FLOAT, "Anisotropic", {mtl_mat.aniso}, bsdf);
344 }
345 if (mtl_mat.aniso_rot >= 0) {
346 set_property_of_socket(SOCK_FLOAT, "Anisotropic Rotation", {mtl_mat.aniso_rot}, bsdf);
347 }
348
349 /* Transmission: average of transmission color. */
350 float transmission = (mtl_mat.transmit_color[0] + mtl_mat.transmit_color[1] +
351 mtl_mat.transmit_color[2]) /
352 3;
353 if (transmission >= 0) {
354 set_property_of_socket(SOCK_FLOAT, "Transmission Weight", {transmission}, bsdf);
355 }
356}
357
358static void add_image_textures(Main *bmain,
359 bNodeTree *ntree,
360 bNode *bsdf,
361 Material *mat,
362 const MTLMaterial &mtl_mat,
363 bool relative_paths)
364{
365 float node_locy = node_locy_top;
366 for (int key = 0; key < int(MTLTexMapType::Count); ++key) {
367 const MTLTexMap &value = mtl_mat.texture_maps[key];
368 if (!value.is_valid()) {
369 /* No Image texture node of this map type can be added to this material. */
370 continue;
371 }
372
373 Image *image = load_texture_image(bmain, value, relative_paths);
374 if (image == nullptr) {
375 continue;
376 }
377
378 bNode *image_node = add_node(ntree, SH_NODE_TEX_IMAGE, node_locx_image, node_locy);
379 BLI_assert(image_node);
380 image_node->id = &image->id;
381 static_cast<NodeTexImage *>(image_node->storage)->projection = value.projection_type;
382
383 /* Add normal map node if needed. */
384 bNode *normal_map = nullptr;
385 if (key == int(MTLTexMapType::Normal)) {
386 normal_map = add_node(ntree, SH_NODE_NORMAL_MAP, node_locx_normalmap, node_locy);
387 const float bump = std::max(0.0f, mtl_mat.normal_strength);
388 set_property_of_socket(SOCK_FLOAT, "Strength", {bump}, normal_map);
389 }
390
391 /* Add UV mapping & coordinate nodes only if needed. */
392 if (value.translation != float3(0, 0, 0) || value.scale != float3(1, 1, 1)) {
393 bNode *texcoord = add_node(ntree, SH_NODE_TEX_COORD, node_locx_texcoord, node_locy);
394 bNode *mapping = add_node(ntree, SH_NODE_MAPPING, node_locx_mapping, node_locy);
395 set_property_of_socket(SOCK_VECTOR, "Location", {value.translation, 3}, mapping);
396 set_property_of_socket(SOCK_VECTOR, "Scale", {value.scale, 3}, mapping);
397
398 link_sockets(ntree, texcoord, "UV", mapping, "Vector");
399 link_sockets(ntree, mapping, "Vector", image_node, "Vector");
400 }
401
402 if (normal_map) {
403 link_sockets(ntree, image_node, "Color", normal_map, "Color");
404 link_sockets(ntree, normal_map, "Normal", bsdf, "Normal");
405 }
406 else if (key == int(MTLTexMapType::Alpha)) {
407 link_sockets(ntree, image_node, "Alpha", bsdf, tex_map_type_to_socket_id[key]);
408 mat->blend_method = MA_BM_BLEND;
409 mat->blend_flag |= MA_BL_HIDE_BACKFACE;
410 }
411 else {
412 link_sockets(ntree, image_node, "Color", bsdf, tex_map_type_to_socket_id[key]);
413 }
414
415 /* Next layout row: goes downwards on the screen. */
416 node_locy -= node_locy_step;
417 }
418}
419
421 const MTLMaterial &mtl_mat,
422 Material *mat,
423 bool relative_paths)
424{
425 bNodeTree *ntree = mat->nodetree;
426 BLI_assert(mat->nodetree);
427
430
431 set_bsdf_socket_values(bsdf, mat, mtl_mat);
432 add_image_textures(bmain, ntree, bsdf, mat, mtl_mat, relative_paths);
433 link_sockets(ntree, bsdf, "BSDF", output, "Surface");
435
436 return ntree;
437}
438
439} // namespace io::obj
440} // namespace blender
#define SH_NODE_TEX_IMAGE
#define SH_NODE_BSDF_PRINCIPLED
#define SH_NODE_TEX_COORD
#define SH_NODE_NORMAL_MAP
#define SH_NODE_OUTPUT_MATERIAL
#define SH_NODE_MAPPING
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
#define ELEM(...)
#define output
constexpr const T * data() const
Definition BLI_span.hh:219
constexpr int64_t size() const
Definition BLI_span.hh:256
UString()=default
bNode * node_add_static_node(const bContext *C, bNodeTree &ntree, int type)
Definition node.cc:4283
bNodeLink & node_add_link(bNodeTree &ntree, bNode &fromnode, bNodeSocket &fromsock, bNode &tonode, bNodeSocket &tosock)
Definition node.cc:4638
bNodeSocket * node_find_socket(bNode &node, eNodeSocketInOut in_out, UString identifier)
Definition node.cc:3036
void node_set_active(bNodeTree &ntree, bNode &node)
Definition node.cc:5484
const char * tex_map_type_to_socket_id[]
const float node_locy_step
const float node_locx_normalmap
static void add_image_textures(Main *bmain, bNodeTree *ntree, bNode *bsdf, Material *mat, const MTLMaterial &mtl_mat, bool relative_paths)
const float node_locx_image
static bNode * add_node(bNodeTree *ntree, int type, float x, float y)
const float node_locx_mapping
const float node_locx_bsdf
static void set_bsdf_socket_values(bNode *bsdf, Material *mat, const MTLMaterial &mtl_mat)
static Image * create_placeholder_image(Main *bmain, const std::string &path)
bNodeTree * create_mtl_node_tree(Main *bmain, const MTLMaterial &mtl_mat, Material *mat, bool relative_paths)
const float node_locx_texcoord
static void set_property_of_socket(eNodeSocketDatatype property_type, const char *socket_id, Span< float > value, bNode *r_node)
const float node_locx_output
const float node_locy_top
static void link_sockets(bNodeTree *ntree, bNode *from_node, const char *from_node_id, bNode *to_node, const char *to_node_id)
static Image * load_image_at_path(Main *bmain, const std::string &path, bool relative_paths)
static Image * load_texture_image(Main *bmain, const MTLTexMap &tex_map, bool relative_paths)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
MINLINE void copy_v3_v3(float r[3], const float a[3])
const char * BKE_main_blendfile_path(const Main *bmain) ATTR_NONNULL()
Definition main.cc:1058
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
Image * BKE_image_load_exists(Main *bmain, const char *filepath, bool check_open=true, bool *r_exists=nullptr)
bool void BLI_path_rel(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1)
sqrt(x)+1/max(0
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
static CLG_LogRef LOG
Definition logging.cpp:12
MINLINE void copy_v4_v4(float r[4], const float a[4])
VecBase< float, 3 > float3
eNodeSocketDatatype type
const MTLTexMap & tex_map_of_type(MTLTexMapType key) const
MTLTexMap texture_maps[int(MTLTexMapType::Count)]