1 # SPDX-FileCopyrightText: 2018-2021 The glTF-Blender-IO authors
3 # SPDX-License-Identifier: Apache-2.0
7 from os
.path
import dirname
, join
, basename
9 from ...io
.com
.gltf2_io_path
import uri_to_path
10 from ...io
.imp
.gltf2_io_binary
import BinaryData
11 from ...io
.imp
.gltf2_io_user_extensions
import import_user_extensions
14 # Note that Image is not a glTF2.0 object
17 def __new__(cls
, *args
, **kwargs
):
18 raise RuntimeError("%s should not be instantiated" % cls
)
21 def create(gltf
, img_idx
):
23 img
= gltf
.data
.images
[img_idx
]
25 if img
.blender_image_name
is not None:
26 # Image is already used somewhere
29 import_user_extensions('gather_import_image_before_hook', gltf
, img
)
31 if img
.uri
is not None and not img
.uri
.startswith('data:'):
32 blender_image
= create_from_file(gltf
, img_idx
)
34 blender_image
= create_from_data(gltf
, img_idx
)
37 blender_image
.alpha_mode
= 'CHANNEL_PACKED'
38 img
.blender_image_name
= blender_image
.name
40 import_user_extensions('gather_import_image_after_hook', gltf
, img
, blender_image
)
43 def create_from_file(gltf
, img_idx
):
44 # Image stored in a file
46 num_images
= len(bpy
.data
.images
)
48 img
= gltf
.data
.images
[img_idx
]
50 path
= join(dirname(gltf
.filename
), uri_to_path(img
.uri
))
51 path
= os
.path
.abspath(path
)
52 if bpy
.data
.is_saved
and bpy
.context
.preferences
.filepaths
.use_relative_paths
:
54 path
= bpy
.path
.relpath(path
)
56 # May happen on Windows if on different drives, eg. C:\ and D:\
59 img_name
= img
.name
or basename(path
)
62 blender_image
= bpy
.data
.images
.load(
67 needs_pack
= gltf
.import_settings
['import_pack_images']
72 gltf
.log
.error("Missing image file (index %d): %s" % (img_idx
, path
))
73 blender_image
= _placeholder_image(img_name
, os
.path
.abspath(path
))
75 if len(bpy
.data
.images
) != num_images
: # If created a new image
76 blender_image
.name
= img_name
81 def create_from_data(gltf
, img_idx
):
82 # Image stored as data => pack
83 img_data
= BinaryData
.get_image_data(gltf
, img_idx
)
86 img_name
= gltf
.data
.images
[img_idx
].name
or 'Image_%d' % img_idx
88 # Create image, width and height are dummy values
89 blender_image
= bpy
.data
.images
.new(img_name
, 8, 8)
90 # Set packed file data
91 blender_image
.pack(data
=img_data
.tobytes(), data_len
=len(img_data
))
92 blender_image
.source
= 'FILE'
96 def _placeholder_image(name
, path
):
97 image
= bpy
.data
.images
.new(name
, 128, 128)
98 # allow the path to be resolved later
100 image
.source
= 'FILE'