forked from BlenderKit/Blendkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.py
More file actions
2134 lines (1828 loc) · 79.5 KB
/
Copy pathupload.py
File metadata and controls
2134 lines (1828 loc) · 79.5 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import json
import logging
import os
import re
import subprocess
import sys
import requests
import tempfile
from pathlib import Path
from typing import Optional, Any
import bpy
from bpy.props import ( # TODO only keep the ones actually used when cleaning
IntProperty,
BoolProperty,
EnumProperty,
StringProperty,
)
from bpy.types import Operator
from .asset_bar import asset_bar_op
from . import (
asset_inspector,
autothumb,
categories,
client_lib,
client_tasks,
global_vars,
image_utils,
overrides,
paths,
reports,
ui_panels,
utils,
search,
)
NAME_MINIMUM = 3
NAME_MAXIMUM = 40
TAGS_MINIMUM = 3
TAGS_MAXIMUM = 10
DESCRIPTION_MINIMUM = 20
BLENDKIT_EXPORT_DATA_FILE = "data.json"
bk_logger = logging.getLogger(__name__)
licenses = (
("royalty_free", "Royalty Free", "royalty free commercial license"),
("cc_zero", "Creative Commons Zero", "Creative Commons Zero"),
)
def wire_thumbnail_upload_enabled() -> bool:
"""Feature gate for experimental wireframe thumbnail uploads."""
addon = bpy.context.preferences.addons.get(__package__)
if addon is None:
return False
preferences = addon.preferences
return getattr(preferences, "enable_wire_thumbnail_upload", False)
def add_version(data):
data["sourceAppName"] = "blender"
data["sourceAppVersion"] = utils.get_blender_version()
data["addonVersion"] = utils.get_addon_version()
def write_to_report(props, text):
props.report = props.report + " - " + text + "\n\n"
def refresh_upload_status_ui():
"""Request a UI redraw so synchronous preparation messages become visible."""
window_manager = getattr(bpy.context, "window_manager", None)
if window_manager is None:
return
for window in window_manager.windows:
screen = getattr(window, "screen", None)
if screen is None:
continue
for area in screen.areas:
area.tag_redraw()
def set_upload_status(props, text):
"""Update upload status and force a redraw for long synchronous steps."""
props.upload_state = text
refresh_upload_status_ui()
def prevalidate_model(props):
"""Check model for possible problems:
- check if all objects does not have asymmetrical scaling. Asymmetrical scaling is a big problem.
Anything scaled away from (1,1,1) is a smaller problem. We do not check for that.
- round minor drifts from 1.0
"""
TOLERANCE = 1e-5
ob = utils.get_active_model()
obs = utils.get_hierarchy(ob)
for ob in obs:
if ob.scale[0] == ob.scale[1] == ob.scale[2]:
continue # all totally good
if all(abs(scalar - 1.0) <= TOLERANCE for scalar in ob.scale):
bk_logger.info(
f"Snapped minor float drift on '{ob}': "
+ f"{ob.scale[0], ob.scale[1], ob.scale[2]} → (1.0, 1.0, 1.0)"
)
ob.scale = (1.0, 1.0, 1.0)
if ob.scale[0] != ob.scale[1] or ob.scale[1] != ob.scale[2]:
write_to_report(
props,
f"Asymmetrical scaling in the object {ob.name} - please apply scale on all models",
)
def get_model_materials():
"""get all materials in the asset hierarchy, will be used to validate materials in future"""
ob = utils.get_active_model()
obs = utils.get_hierarchy(ob)
materials = []
for ob in obs:
if ob.type in ("MESH", "CURVE"):
for mat in ob.data.materials:
if mat not in materials:
materials.append(mat)
return materials
def prevalidate_scene(props):
"""Check scene for possible problems:
- check if user is author of all assets in scene"""
problematic_assets = []
for ob in bpy.context.scene.objects:
if not ob.get("asset_data"):
continue
if utils.user_is_owner(ob["asset_data"]):
continue
asset_name = ob["asset_data"].get("name")
author_name = ob["asset_data"].get("author", {}).get("fullName")
problematic_assets.append(f" - {asset_name} by {author_name}\n")
if len(problematic_assets) == 0:
return # No problematic assets found
oa_string = "".join(problematic_assets)
write_to_report(
props,
f"Other author's assets are present in scene \n"
f" Remove assets by these authors before uploading the scene:\n"
f"{oa_string}",
)
def check_missing_data_model(props):
autothumb.update_upload_model_preview(None, None)
if props.engine == "NONE":
write_to_report(props, "Set at least one rendering/output engine")
# if not any(props.dimensions):
# write_to_report(props, 'Run autotags operator or fill in dimensions manually')
def check_missing_data_scene(props):
autothumb.update_upload_model_preview(None, None)
if props.engine == "NONE":
write_to_report(props, "Set at least one rendering/output engine")
def check_missing_data_material(props):
autothumb.update_upload_material_preview(None, None)
if props.engine == "NONE":
write_to_report(props, "Set rendering/output engine")
def check_missing_data_brush(props):
autothumb.update_upload_brush_preview(None, None)
def check_missing_data(asset_type, props, upload_set):
"""Check if all required data is present and fills in the upload props with error messages."""
props.report = ""
if props.name == "":
write_to_report(
props,
"A name is required.\n" " Please provide a name for your asset.",
)
elif len(props.name) < NAME_MINIMUM:
write_to_report(
props,
f"Name is too short.\n"
f" Please provide a name with at least {NAME_MINIMUM} characters.",
)
elif len(props.name) > NAME_MAXIMUM:
write_to_report(
props,
f"Name is too long.\n"
f" Please provide a name with at most {NAME_MAXIMUM} characters.",
)
if props.is_private == "PUBLIC":
category_ok = props.category == "NONE"
subcategory_ok = props.subcategory != "EMPTY" and props.subcategory == "NONE"
subcategory1_ok = props.subcategory1 != "EMPTY" and props.subcategory1 == "NONE"
if category_ok or subcategory_ok or subcategory1_ok:
write_to_report(
props,
"Category, subcategory, or sub-subcategory has not been selected.\n"
" Please ensure you select appropriate values; 'None' is not a valid selection.\n"
" Proper categorization significantly improves your asset's discoverability.",
)
if "THUMBNAIL" in upload_set:
if asset_type in ("MODEL", "SCENE", "MATERIAL", "PRINTABLE", "BRUSH"):
thumb_path = bpy.path.abspath(props.thumbnail)
if props.thumbnail == "":
write_to_report(
props,
"A thumbnail image has not been provided.\n"
" Please add a thumbnail in JPG or PNG format, ensuring at least 1024x1024 pixels.",
)
elif not os.path.exists(Path(thumb_path)):
write_to_report(
props,
"Thumbnail filepath does not exist on the disk.\n"
" Please check the filepath and try again.",
)
if "PHOTO_THUMBNAIL" in upload_set: # for printable assets
# Add validation for the photo thumbnail for printable assets
# only if it's in the upload set
if props.photo_thumbnail_will_upload_on_website:
pass
else:
foto_thumb_path = bpy.path.abspath(props.photo_thumbnail)
if props.photo_thumbnail == "":
write_to_report(
props,
"A photo thumbnail image has not been provided.\n"
" Please add a photo of the 3D printed object in JPG or PNG format, ensuring at least 1024x1024 pixels.",
)
elif not os.path.exists(Path(foto_thumb_path)):
write_to_report(
props,
"Photo thumbnail filepath does not exist on the disk.\n"
" Please check the filepath and try again.",
)
if wire_thumbnail_upload_enabled() and "WIRE_THUMBNAIL" in upload_set:
if props.wire_thumbnail_will_upload_on_website:
pass
else:
wire_thumb_path = bpy.path.abspath(props.wire_thumbnail)
if props.wire_thumbnail == "":
write_to_report(
props,
"A wireframe thumbnail image has not been provided.\n"
" Please add a wireframe thumbnail in JPG or PNG format, ensuring at least 1024x1024 pixels.",
)
elif not os.path.exists(Path(wire_thumb_path)):
write_to_report(
props,
"Wireframe thumbnail filepath does not exist on the disk.\n"
" Please check the filepath and try again.",
)
if props.is_private == "PUBLIC":
check_public_requirements(props)
if asset_type in ("MODEL", "PRINTABLE"):
prevalidate_model(props)
check_missing_data_model(props)
elif asset_type == "SCENE":
prevalidate_scene(props)
check_missing_data_scene(props)
elif asset_type == "MATERIAL":
check_missing_data_material(props)
elif asset_type == "BRUSH":
check_missing_data_brush(props)
if props.report != "":
props.report = (
f"Before {props.is_private.lower()} upload, please fix:\n\n" + props.report
)
def check_public_requirements(props):
"""Check requirements for public upload. Add error message into props.report if needed."""
if props.description == "":
write_to_report(
props,
"No asset description has been provided.\n"
f" Please write a description of at least {DESCRIPTION_MINIMUM} characters.\n"
" A comprehensive description enhances your asset's visibility\n"
" in relevant search results.",
)
elif len(props.description) < DESCRIPTION_MINIMUM:
write_to_report(
props,
"The asset description provided is too brief.\n"
f" Please ensure your description is at least {DESCRIPTION_MINIMUM} characters long.\n"
" A comprehensive description enhances your asset's visibility\n"
" in relevant search results.",
)
if props.tags == "":
write_to_report(
props,
"No tags have been provided for your asset.\n"
f" Please add at least {TAGS_MINIMUM} tags to improve its discoverability.\n"
" Tags enhance your asset's visibility in relevant search results.",
)
elif len(props.tags.split(",")) < TAGS_MINIMUM:
write_to_report(
props,
"Not enough tags have been provided for your asset.\n"
f" Please ensure you have at least {TAGS_MINIMUM} tags to improve its discoverability.\n"
" Tags enhance your asset's visibility in relevant search results.",
)
def check_tags_format(tags_string: str):
"""Check if tags string is a comma-separated list of tags consisting of only alphanumeric characters and underscores.
Returns a bool and list of tags that do not meet the format requirement.
"""
tags_string = tags_string.strip()
if tags_string == "":
return True, []
tags = tags_string.split(",")
problematic_tags = []
for tag in tags:
tag = tag.strip()
if tag == "" or not re.match("^[0-9a-zA-Z_]+$", tag):
problematic_tags.append(tag)
if len(problematic_tags) > 0:
return False, problematic_tags
return True, problematic_tags
def sub_to_camel(content):
replaced = re.sub(r"_.", lambda m: m.group(0)[1].upper(), content)
return replaced
def get_upload_data(caller=None, context=None, asset_type=None):
"""
works though metadata from addon props and prepares it for upload to dicts.
Parameters
----------
caller - upload operator or none
context - context
asset_type - asset type in capitals (blender enum)
Returns
-------
export_data- all extra data that the process needs to upload and communicate with UI from a thread.
- eval_path_computing - string path to UI prop that denotes if upload is still running
- eval_path_state - string path to UI prop that delivers messages about upload to ui
- eval_path - path to object holding upload data to be able to access it with various further commands
- models - in case of model upload, list of objects
- thumbnail_path - path to thumbnail file
upload_data - asset_data generated from the ui properties
"""
user_preferences = bpy.context.preferences.addons[__package__].preferences
export_data: dict[str, Any] = {
# "type": asset_type,
}
upload_params: dict[str, Any] = {}
# initialize here to prevent unbound
upload_data: dict[str, Any] = {}
if asset_type in ("MODEL", "PRINTABLE"):
# Prepare to save the file
mainmodel = utils.get_active_model()
props = mainmodel.blenderkit
obs = utils.get_hierarchy(mainmodel)
obnames = []
for ob in obs:
obnames.append(ob.name)
export_data["models"] = obnames
export_data["thumbnail_path"] = bpy.path.abspath(props.thumbnail)
# Add photo thumbnail path to export_data for printable assets
if asset_type == "PRINTABLE" and props.photo_thumbnail:
export_data["photo_thumbnail_path"] = bpy.path.abspath(
props.photo_thumbnail
)
# Add wire thumbnail path to export_data for models and printable assets
if (
wire_thumbnail_upload_enabled()
and asset_type in ("MODEL", "SCENE", "PRINTABLE")
and props.wire_thumbnail
):
export_data["wire_thumbnail_path"] = bpy.path.abspath(props.wire_thumbnail)
eval_path_computing = (
"bpy.data.objects['%s'].blenderkit.uploading" % mainmodel.name
)
eval_path_state = (
"bpy.data.objects['%s'].blenderkit.upload_state" % mainmodel.name
)
eval_path = "bpy.data.objects['%s']" % mainmodel.name
upload_data = {
"assetType": asset_type.lower(),
}
# Common parameters for both MODEL and PRINTABLE
upload_params = {
"faceCount": props.face_count,
"modifiers": utils.string2list(props.modifiers),
"dimensionX": round(props.dimensions[0], 4),
"dimensionY": round(props.dimensions[1], 4),
"dimensionZ": round(props.dimensions[2], 4),
"boundBoxMinX": round(props.bbox_min[0], 4),
"boundBoxMinY": round(props.bbox_min[1], 4),
"boundBoxMinZ": round(props.bbox_min[2], 4),
"boundBoxMaxX": round(props.bbox_max[0], 4),
"boundBoxMaxY": round(props.bbox_max[1], 4),
"boundBoxMaxZ": round(props.bbox_max[2], 4),
}
# Additional parameters only for MODEL type
if asset_type == "MODEL":
engines = [props.engine.lower()]
if props.engine1 != "NONE":
engines.append(props.engine1.lower())
if props.engine2 != "NONE":
engines.append(props.engine2.lower())
if props.engine3 != "NONE":
engines.append(props.engine3.lower())
if props.engine == "OTHER":
engines.append(props.engine_other.lower())
style = props.style.lower()
upload_params.update(
{
"productionLevel": props.production_level.lower(),
"modelStyle": style,
"engines": engines,
"materials": utils.string2list(props.materials),
"shaders": utils.string2list(props.shaders),
"uv": props.uv,
"animated": props.animated,
"rig": props.rig,
"simulation": props.simulation,
"purePbr": props.pbr,
"faceCountRender": props.face_count_render,
"manifold": props.manifold,
"objectCount": props.object_count,
"procedural": props.is_procedural,
"nodeCount": props.node_count,
"textureCount": props.texture_count,
"megapixels": props.total_megapixels,
}
)
if props.use_design_year:
upload_params["designYear"] = props.design_year
if props.condition != "UNSPECIFIED":
upload_params["condition"] = props.condition.lower()
if props.pbr:
pt = props.pbr_type
pt = pt.lower()
upload_params["pbrType"] = pt
if props.texture_resolution_max > 0:
upload_params["textureResolutionMax"] = props.texture_resolution_max
upload_params["textureResolutionMin"] = props.texture_resolution_min
if props.mesh_poly_type != "OTHER":
upload_params["meshPolyType"] = props.mesh_poly_type.lower()
# Common optional parameters for both MODEL and PRINTABLE
optional_params = [
"manufacturer",
"designer",
"design_collection",
"design_variant",
]
for p in optional_params:
if eval("props.%s" % p) != "":
upload_params[sub_to_camel(p)] = eval("props.%s" % p)
if props.use_design_year:
upload_params["designYear"] = props.design_year
if props.sexualized_content:
upload_params["sexualizedContent"] = props.sexualized_content
elif asset_type == "SCENE":
# Prepare to save the file
s = bpy.context.scene
props = s.blenderkit
export_data["scene"] = s.name
export_data["thumbnail_path"] = bpy.path.abspath(props.thumbnail)
eval_path_computing = "bpy.data.scenes['%s'].blenderkit.uploading" % s.name
eval_path_state = "bpy.data.scenes['%s'].blenderkit.upload_state" % s.name
eval_path = "bpy.data.scenes['%s']" % s.name
engines = [props.engine.lower()]
if props.engine1 != "NONE":
engines.append(props.engine1.lower())
if props.engine2 != "NONE":
engines.append(props.engine2.lower())
if props.engine3 != "NONE":
engines.append(props.engine3.lower())
if props.engine == "OTHER":
engines.append(props.engine_other.lower())
style = props.style.lower()
# if style == 'OTHER':
# style = props.style_other.lower()
upload_data = {
"assetType": "scene",
}
upload_params = {
"productionLevel": props.production_level.lower(),
"modelStyle": style,
"engines": engines,
"modifiers": utils.string2list(props.modifiers),
"materials": utils.string2list(props.materials),
"shaders": utils.string2list(props.shaders),
"uv": props.uv,
"animated": props.animated,
# "simulation": props.simulation,
"purePbr": props.pbr,
"faceCount": max(0, props.face_count),
"faceCountRender": max(0, props.face_count_render),
"objectCount": max(0, props.object_count),
# "scene": props.is_scene,
}
if props.use_design_year:
upload_params["designYear"] = props.design_year
if props.condition != "UNSPECIFIED":
upload_params["condition"] = props.condition.lower()
if props.pbr:
pt = props.pbr_type
pt = pt.lower()
upload_params["pbrType"] = pt
if props.texture_resolution_max > 0:
upload_params["textureResolutionMax"] = props.texture_resolution_max
upload_params["textureResolutionMin"] = props.texture_resolution_min
if props.mesh_poly_type != "OTHER":
upload_params["meshPolyType"] = (
props.mesh_poly_type.lower()
) # .replace('_',' ')
elif asset_type == "MATERIAL":
mat = bpy.context.active_object.active_material
props = mat.blenderkit
# props.name = mat.name
export_data["material"] = str(mat.name)
export_data["thumbnail_path"] = bpy.path.abspath(props.thumbnail)
# mat analytics happen here, since they don't take up any time...
asset_inspector.check_material(props, mat)
eval_path_computing = "bpy.data.materials['%s'].blenderkit.uploading" % mat.name
eval_path_state = "bpy.data.materials['%s'].blenderkit.upload_state" % mat.name
eval_path = "bpy.data.materials['%s']" % mat.name
engine = props.engine
if engine == "OTHER":
engine = props.engine_other
engine = engine.lower()
style = props.style.lower()
# if style == 'OTHER':
# style = props.style_other.lower()
upload_data = {
"assetType": "material",
}
upload_params = {
"materialStyle": style,
"engine": engine,
"shaders": utils.string2list(props.shaders),
"uv": props.uv,
"animated": props.animated,
"purePbr": props.pbr,
"textureSizeMeters": props.texture_size_meters,
"procedural": props.is_procedural,
"nodeCount": props.node_count,
"textureCount": props.texture_count,
"megapixels": props.total_megapixels,
}
if props.pbr:
upload_params["pbrType"] = props.pbr_type.lower()
if props.texture_resolution_max > 0:
upload_params["textureResolutionMax"] = props.texture_resolution_max
upload_params["textureResolutionMin"] = props.texture_resolution_min
elif asset_type == "BRUSH":
brush = utils.get_active_brush()
props = brush.blenderkit
# props.name = brush.name
export_data["brush"] = str(brush.name)
export_data["thumbnail_path"] = bpy.path.abspath(props.thumbnail)
eval_path_computing = "bpy.data.brushes['%s'].blenderkit.uploading" % brush.name
eval_path_state = "bpy.data.brushes['%s'].blenderkit.upload_state" % brush.name
eval_path = "bpy.data.brushes['%s']" % brush.name
# mat analytics happen here, since they don't take up any time...
brush_type = ""
if bpy.context.sculpt_object is not None:
brush_type = "sculpt"
elif bpy.context.image_paint_object: # could be just else, but for future p
brush_type = "texture_paint"
upload_params = {
"mode": brush_type,
}
upload_data = {
"assetType": "brush",
}
elif asset_type == "HDR":
ui_props = bpy.context.window_manager.blenderkitUI
# imagename = ui_props.hdr_upload_image
image = ui_props.hdr_upload_image # bpy.data.images.get(imagename)
if not image:
return None, None
props = image.blenderkit
image_utils.analyze_image_is_true_hdr(image)
# props.name = brush.name
base, ext = os.path.splitext(image.filepath)
thumb_path = base + ".jpg"
export_data["thumbnail_path"] = bpy.path.abspath(thumb_path)
export_data["hdr"] = str(image.name)
export_data["hdr_filepath"] = str(bpy.path.abspath(image.filepath))
# export_data["thumbnail_path"] = bpy.path.abspath(brush.icon_filepath)
eval_path_computing = "bpy.data.images['%s'].blenderkit.uploading" % image.name
eval_path_state = "bpy.data.images['%s'].blenderkit.upload_state" % image.name
eval_path = "bpy.data.images['%s']" % image.name
# mat analytics happen here, since they don't take up any time...
upload_params = {
"textureResolutionMax": props.texture_resolution_max,
"trueHDR": props.true_hdr,
}
upload_data = {
"assetType": "hdr",
}
elif asset_type == "TEXTURE":
style = props.style
# if style == 'OTHER':
# style = props.style_other
upload_data = {
"assetType": "texture",
}
upload_params = {
"style": style,
"animated": props.animated,
"purePbr": props.pbr,
"resolution": props.resolution,
}
if props.pbr:
pt = props.pbr_type
pt = pt.lower()
upload_data["pbrType"] = pt
elif asset_type == "NODEGROUP":
ui_props = bpy.context.window_manager.blenderkitUI
bk_logger.info("preparing nodegroup upload")
asset = ui_props.nodegroup_upload
bk_logger.info("asset:" + str(asset))
if not asset:
return None, None
props = asset.blenderkit
export_data["nodegroup"] = str(asset.name)
export_data["thumbnail_path"] = bpy.path.abspath(props.thumbnail)
eval_path_computing = (
f"bpy.data.node_groups['{asset.name}'].blenderkit.uploading"
)
eval_path_state = (
f"bpy.data.node_groups['{asset.name}'].blenderkit.upload_state"
)
eval_path = f"bpy.data.node_groups['{asset.name}']"
# mat analytics happen here, since they don't take up any time...
upload_params = {"nodeType": asset.type.lower()}
upload_data = {
"assetType": "nodegroup",
}
add_version(upload_data)
# caller can be upload operator, but also asset bar called from tooltip generator
if caller and caller.properties.main_file is True:
upload_data["name"] = props.name
upload_data["displayName"] = props.name
else:
upload_data["displayName"] = props.name
upload_data["description"] = props.description
upload_data["tags"] = utils.string2list(props.tags)
# category is always only one value by a slug, that's why we go down to the lowest level and overwrite.
if props.category == "" or props.category == "NONE":
upload_data["category"] = asset_type.lower()
else:
upload_data["category"] = props.category
if props.subcategory not in (
"NONE",
"EMPTY",
"OTHER",
): # if OTHER category is selected, parent category will be used
upload_data["category"] = props.subcategory
if props.subcategory1 not in (
"NONE",
"EMPTY",
"OTHER",
): # if OTHER category is selected, parent category will be used
upload_data["category"] = props.subcategory1
upload_data["license"] = props.license
upload_data["isFree"] = props.is_free == "FREE"
upload_data["isPrivate"] = props.is_private == "PRIVATE"
upload_data["token"] = user_preferences.api_key
# author name (server fills in the real author from the API key, but the
# background packing process needs it to write asset_data.author into the
# saved .blend so the validator sees the correct author in the asset browser)
profile = global_vars.BKIT_PROFILE
upload_data["author"] = getattr(profile, "fullName", "") or getattr(
profile, "username", ""
)
upload_data["parameters"] = upload_params
# if props.asset_base_id != '':
export_data["assetBaseId"] = props.asset_base_id
export_data["id"] = props.id
export_data["eval_path_computing"] = eval_path_computing
export_data["eval_path_state"] = eval_path_state
export_data["eval_path"] = eval_path
bk_logger.info("export_data:" + str(export_data))
return export_data, upload_data
def update_free_full(self, context):
if self.asset_type == "material":
if self.free_full == "FULL":
self.free_full = "FREE"
ui_panels.ui_message(
title="All Blendkit materials are free",
message="Any material uploaded to Blendkit is free."
" However, it can still earn money for the author,"
" based on our fair share system. "
"Part of subscription is sent to authors based on usage by paying users.",
)
def can_edit_asset(active_index: int = -1, asset_data: Optional[dict] = None):
if active_index < 0 and not asset_data:
return False
profile = global_vars.BKIT_PROFILE
if profile is None:
return False
if utils.profile_is_validator():
return True
if not asset_data:
sr = search.get_search_results()
asset_data = dict(sr[active_index])
if int(asset_data["author"]["id"]) == profile.id:
return True
return False
class FastMetadata(bpy.types.Operator):
"""Edit metadata of the asset"""
bl_idname = "wm.blenderkit_fast_metadata"
bl_label = "Update metadata"
bl_options = {"REGISTER", "UNDO", "INTERNAL"}
asset_id: StringProperty( # type: ignore[valid-type]
name="Asset Base Id",
description="Unique name of the asset (hidden)",
default="",
)
asset_type: StringProperty(name="Asset Type", description="Asset Type", default="") # type: ignore[valid-type]
name: StringProperty( # type: ignore[valid-type]
name="Name",
description="Provide name of your asset, choose a few descriptive English words that clearly identify and distinguish your asset. Good naming helps your asset to be found on the search engine. Follow these tips:\n\n"
"Use Descriptive Terms:\nInclude specific details such as the brand, material, or distinct features of the asset.\n\n"
"Avoid Generic or Vague Terms:\nNames like 'Sky 01' or 'Big Tree' are too general and not helpful for search optimization. Instead, use names that provide meaningful information about the asset.\n\n"
"Highlight Key Attributes:\nIncorporate important attributes that are likely to be used in search queries, such as the model in vehicles or the designer in furniture.\n\n"
"Bad names: Chair 01, Nice Car, Statue\n"
"Good names: Knoll Steel Chair, Skoda Kodiaq, Statue of Liberty",
default="",
)
description: StringProperty( # type: ignore[valid-type]
name="Description",
description="Provide a clear and concise description of your asset in English. To enhance searchability and discoverability of your asset, follow these tips:\n\n"
"Be Specific:\nUse precise terms that accurately reflect the asset. Include key characteristics such as material, color, function, or designer/brand.\n\n"
"Use Recognizable Keywords:\nIncorporate well-known and relevant keywords that users are likely to search for. This includes brand names, designer names, common usage, and industry-specific terms.\n\n"
"Avoid Jargon:\nUnless industry-specific terms are widely understood by your target audience, use simple language that is easy to understand.\n\n"
"Highlight Unique Features:\nMention any distinctive features that set the asset apart from others, such as a unique design, special function, or notable collaboration.\n\n"
"Keep it Brief:\nAim for a short description that captures the essence of the asset without unnecessary details. A concise description makes it easier for Elasticsearch to process and for users to scan",
default="",
)
tags: StringProperty( # type: ignore[valid-type]
name="Tags",
description="Enter up to 10 tags, separated by commas. Tags may include alphanumeric characters and underscores only. For better discoverability, follow these tips:\n\n"
"Choose Relevant Keywords:\nSelect tags that closely relate to the asset's features, usage, or industry terms. This increases the chances that your asset appears in relevant searches.\n\n"
"Include Synonyms:\nAdd variations or synonyms to cover different ways users might search for similar items. Especially consider synonyms for terms used in the asset's name or description to broaden search relevancy.\n\n"
"Prioritize Common Terms:\nUse commonly searched terms within your target audience. This helps connect your assets to the most likely queries.\n\n"
"Enhance with Specificity: While common terms are essential, adding specific tags can help in uniquely identifying and categorizing the asset. This is particularly useful for users looking for particular features or attributes.",
default="",
)
category: EnumProperty( # type: ignore[valid-type]
name="Category",
description="Select the main category for the uploaded asset. "
"Choose the most accurate category to enhance visibility and download rates. "
"Proper categorization ensures your asset reaches people actively searching for assets like yours",
items=categories.get_category_enums,
update=categories.update_category_enums,
)
subcategory: EnumProperty( # type: ignore[valid-type]
name="Subcategory",
description="Select a subcategory within the chosen main category",
items=categories.get_subcategory_enums,
update=categories.update_subcategory_enums,
)
subcategory1: EnumProperty( # type: ignore[valid-type]
name="Sub-subcategory",
description="Select a further subcategory within the chosen subcategory",
items=categories.get_subcategory1_enums,
)
license: EnumProperty( # type: ignore[valid-type]
items=licenses,
default="royalty_free",
description="License. Please read our help for choosing the right licenses",
)
is_private: EnumProperty( # type: ignore[valid-type]
name="Thumbnail Style",
items=(
(
"PRIVATE",
"Private",
"You asset will be hidden to public. The private assets are limited by a quota.",
),
(
"PUBLIC",
"Public",
'"Your asset will go into the validation process automatically',
),
),
description="If not marked private, your asset will go into the validation process automatically\n"
"Private assets are limited by quota",
default="PUBLIC",
)
sexualized_content: BoolProperty( # type: ignore[valid-type]
name="Sexualized content",
description=(
"Flag this asset if it includes explicit content, suggestive poses, or overemphasized secondary sexual characteristics. "
"This helps users filter content according to their preferences, creating a safe and inclusive browsing experience for all.\n\n"
"Flag not required:\n"
"- naked base mesh model,\n"
"- figure in underwear/swimwear in neutral position.\n\n"
"Flag required:\n"
"- figure in sexually suggestive pose,\n"
"- figure with over overemphasized sexual characteristics,\n"
"- objects related to sexual act."
),
default=False,
)
free_full: EnumProperty( # type: ignore[valid-type]
name="Free or Full Plan",
items=(
(
"FREE",
"Free",
"You consent you want to release this asset as free for everyone",
),
("FULL", "Full", "Your asset will be in the full plan"),
),
description="Choose whether the asset should be free or in the Full Plan",
default="FULL",
update=update_free_full,
)
# Design metadata
manufacturer: StringProperty( # type: ignore[valid-type]
name="Manufacturer",
description="Manufacturer, company making a design piece or product.",
default="",
)
designer: StringProperty( # type: ignore[valid-type]
name="Designer",
description="Author of the original design piece depicted.",
default="",
)
design_collection: StringProperty( # type: ignore[valid-type]
name="Design Collection",
description="Name of the collection this design belongs to.",
default="",
)
design_variant: StringProperty( # type: ignore[valid-type]
name="Design Variant",
description="Colour or material variant of the product.",
default="",
)
use_design_year: BoolProperty( # type: ignore[valid-type]
name="Use Design Year",
description="Whether to include the design year in the metadata. If enabled, the design year will be included as a parameter in the asset metadata.",
default=False,
)
design_year: IntProperty( # type: ignore[valid-type]
name="Design Year",
description="When this item was designed.",
default=1960,
)
####################
@classmethod
def poll(cls, context):
return True
def draw(self, context):
# this timer is there to not let double clicks through the popups down to the asset bar.
ui_panels.set_overlay_panel_active()
layout = self.layout
# col = layout.column()
layout.label(text=self.message)
layout.prop(self, "category")
if self.category != "NONE" and self.subcategory != "EMPTY":
layout.prop(self, "subcategory")
if self.subcategory != "NONE" and self.subcategory1 != "EMPTY":
layout.prop(self, "subcategory1")
layout.prop(self, "name")
layout.prop(self, "description")
layout.prop(self, "tags")
layout.prop(self, "is_private", expand=True)
layout.prop(self, "free_full", expand=True)
if self.is_private == "PUBLIC":
layout.prop(self, "license")
layout.prop(self, "manufacturer")
layout.prop(self, "designer")
layout.prop(self, "design_collection")
layout.prop(self, "design_variant")
layout.prop(self, "use_design_year")
if self.use_design_year:
layout.prop(self, "design_year")
# layout.label(text="Content Flags:")