-
Notifications
You must be signed in to change notification settings - Fork 0
/
impvrm.py
261 lines (213 loc) · 10.7 KB
/
impvrm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# Copyright (c) 2024 Roni Raihan
# Basic script / soure code by The glTF-Blender-IO authors, see < https://github.com/KhronosGroup/glTF-Blender-IO >
# Some code functions, generated by AI ChatGPT < https://chat.openai.com/ >
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < https://www.gnu.org/licenses/ >.
#--------------------------------------------------------------------------------
# Copyright 2018-2021 The glTF-Blender-IO authors.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import bpy
import os
import sys
import time
import json
from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator
from .impread.readg2 import glTFImporter, ImportError
from .impread.imblen import BlenderGlTF
from .impread.readvrm import VRMread
from bpy.props import (StringProperty,
BoolProperty,
EnumProperty,
IntProperty,
FloatProperty,
CollectionProperty)
importer_extension_panel_unregister_functors = []
class ConvertGLTF2_Base:
"""Base class containing options that should be exposed during both import and export."""
export_import_convert_lighting_mode: EnumProperty(
name='Lighting Mode',
items=(
('SPEC', 'Standard', 'Physically-based glTF lighting units (cd, lx, nt)'),
('COMPAT', 'Unitless', 'Non-physical, unitless lighting. Useful when exposure controls are not available'),
('RAW', 'Raw (Deprecated)', 'Blender lighting strengths with no conversion'),
),
description='Optional backwards compatibility for non-standard render engines. Applies to lights',# TODO: and emissive materials',
default='SPEC'
)
class ImportVRM(Operator, ConvertGLTF2_Base, ImportHelper):
"""Load a VRM (glTF 2.0 biner) file"""
bl_idname = 'import_scene.vrm'
bl_label = 'Import VRM'
bl_options = {'REGISTER', 'UNDO'}
filter_glob: StringProperty(default="*.vrm", options={'HIDDEN'})
files: CollectionProperty(
name="File Path",
type=bpy.types.OperatorFileListElement,
)
loglevel: IntProperty(name='Log Level')
import_pack_images: BoolProperty(name='Pack Images', default=True)
merge_vertices: BoolProperty(name='Merge Vertices', default=False)
import_shading: EnumProperty(
name="Shading",
items=(("NORMALS", "Use Normal Data", ""),
("FLAT", "Flat Shading", ""),
("SMOOTH", "Smooth Shading", "")),
default="NORMALS")
bone_heuristic: EnumProperty(
name="Bone Dir",
items=(
("BLENDER", "Blender (best for import/export round trip)",
"Good for re-importing glTFs exported from Blender, "
"and re-exporting glTFs to glTFs after Blender editing. "
"Bone tips are placed on their local +Y axis (in glTF space)"),
("TEMPERANCE", "Temperance (average)",
"Decent all-around strategy. "
"A bone with one child has its tip placed on the local axis "
"closest to its child"),
("FORTUNE", "Fortune (may look better, less accurate)",
"Might look better than Temperance, but also might have errors. "
"A bone with one child has its tip placed at its child's root. "
"Non-uniform scalings may get messed up though, so beware"),
),
description="Heuristic for placing bones. Tries to make bones pretty",
default="BLENDER",
)
guess_original_bind_pose: BoolProperty(name='Guess Original Bind Pose', default=True)
import_webp_texture: BoolProperty(name='Import WebP textures', default=False)
gunakan_vrmmeta: BoolProperty(name='Use the VRM data from the model to the VRM tool', default=True)
gunakan_model: BoolProperty(name='Import model from VRM (Disable it if you only want to import VRM Meta Data)', default=True)
def draw(self, context):
layout = self.layout
layout.use_property_split = False
layout.use_property_decorate = False # No animation.
layout.label(text="Import VRM (gltf 2.0 Biner)")
box = layout.box()
kotak = box.column()
kotak.scale_y = 0.7
kotak.label(text="Remember!", icon= 'ERROR')
kotak.label(text="You must comply with the license conditions", icon= 'BLANK1')
kotak.label(text="and permission of the VRM model your import", icon= 'BLANK1')
layout.label(text="Use Meta Data", icon= 'MENU_PANEL')
layout.prop(self, "gunakan_vrmmeta", text= "Use Meta Data")
layout.label(text="Import model", icon= 'USER')
layout.prop(self, "gunakan_model", text= "Import model")
layout.label(text="Disable it if you only want to import VRM meta data")
def invoke(self, context, event):
preferences = bpy.context.preferences
for addon_name in preferences.addons.keys():
try:
if hasattr(sys.modules[addon_name], 'glTF2ImportUserExtension') or hasattr(sys.modules[addon_name], 'glTF2ImportUserExtensions'):
importer_extension_panel_unregister_functors.append(sys.modules[addon_name].register_panel())
except Exception:
pass
self.has_active_importer_extensions = len(importer_extension_panel_unregister_functors) > 0
return ImportHelper.invoke(self, context, event)
def execute(self, context):
return self.import_gltf2(context)
def import_gltf2(self, context):
bpy.ops.object.select_all(action='DESELECT')
self.set_debug_log()
import_settings = self.as_keywords()
user_extensions = []
preferences = bpy.context.preferences
for addon_name in preferences.addons.keys():
try:
module = sys.modules[addon_name]
except Exception:
continue
if hasattr(module, 'glTF2ImportUserExtension'):
extension_ctor = module.glTF2ImportUserExtension
user_extensions.append(extension_ctor())
import_settings['import_user_extensions'] = user_extensions
if self.files:
# Multiple file import
ret = {'CANCELLED'}
dirname = os.path.dirname(self.filepath)
for file in self.files:
path = os.path.join(dirname, file.name)
if self.unit_import(path, import_settings) == {'FINISHED'}:
ret = {'FINISHED'}
return ret
else:
# Single file import
return self.unit_import(self.filepath, import_settings)
def unit_import(self, filename, import_settings):
try:
if self.gunakan_vrmmeta == True:
VRMread.baca(filename)
if self.gunakan_model == True:
gltf_importer = glTFImporter(filename, import_settings)
gltf_importer.read()
gltf_importer.checks()
print("Data are loaded, start creating Blender stuff")
start_time = time.time()
BlenderGlTF.create(gltf_importer)
elapsed_s = "{:.2f}s".format(time.time() - start_time)
print("glTF import finished in " + elapsed_s)
gltf_importer.log.removeHandler(gltf_importer.log_handler)
selected_objects = bpy.context.selected_objects
rig = [obj for obj in selected_objects if obj.type == 'ARMATURE']
for obj in rig:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='POSE')
for bone in obj.pose.bones:
#pose.bones["bone_sbcierh_usrbtpb"].custom_shape = None
if bone.custom_shape == None:
continue
elif bone.name == "bone_sbcierh_usrbtpb":
bone.custom_shape = None
else:
bone.custom_shape_scale_xyz[0] = 0.1
bone.custom_shape_scale_xyz[1] = 0.1
bone.custom_shape_scale_xyz[2] = 0.1
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
return {'FINISHED'}
except ImportError as e:
self.report({'ERROR'}, e.args[0])
return {'CANCELLED'}
def set_debug_log(self):
import logging
if bpy.app.debug_value == 0:
self.loglevel = logging.CRITICAL
elif bpy.app.debug_value == 1:
self.loglevel = logging.ERROR
elif bpy.app.debug_value == 2:
self.loglevel = logging.WARNING
elif bpy.app.debug_value == 3:
self.loglevel = logging.INFO
else:
self.loglevel = logging.NOTSET
def menu_func_import(self, context):
self.layout.operator(ImportVRM.bl_idname, text="VRM using TRPHB VRM Tool (.vrm)")
def register():
bpy.utils.register_class(ImportVRM)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
def unregister():
bpy.utils.unregister_class(ImportVRM)
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
if __name__ == "__main__":
register()