hero props
[convexer.git] / __init__.py
1 # Copyright (C) 2022 Harry Godden (hgn)
2
3 bl_info = {
4 "name":"Convexer",
5 "author": "Harry Godden (hgn)",
6 "version": (0,1),
7 "blender":(3,1,0),
8 "location":"Export",
9 "descriptin":"",
10 "warning":"",
11 "wiki_url":"",
12 "category":"Import/Export",
13 }
14
15 print( "Convexer reload" )
16
17 #from mathutils import *
18 import bpy, gpu, math, os, time, mathutils, blf, subprocess, shutil, hashlib
19 from ctypes import *
20 from gpu_extras.batch import batch_for_shader
21 from bpy.app.handlers import persistent
22
23 # GPU and viewport drawing
24 # ------------------------------------------------------------------------------
25
26 # Handlers
27 cxr_view_draw_handler = None
28 cxr_ui_draw_handler = None
29
30 # Batches
31 cxr_view_lines = None
32 cxr_view_mesh = None
33 cxr_jobs_batch = None
34 cxr_jobs_inf = []
35
36 # Shaders
37 cxr_view_shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
38 cxr_ui_shader = gpu.types.GPUShader("""
39 uniform mat4 ModelViewProjectionMatrix;
40 uniform float scale;
41
42 in vec2 aPos;
43 in vec4 aColour;
44
45 out vec4 colour;
46
47 void main()
48 {
49 gl_Position = ModelViewProjectionMatrix * vec4(aPos.x*scale,aPos.y, 0.0, 1.0);
50 colour = aColour;
51 }
52 ""","""
53 in vec4 colour;
54 out vec4 FragColor;
55
56 void main()
57 {
58 FragColor = colour;
59 }
60 """)
61
62 # Render functions
63 #
64 def cxr_ui(_,context):
65 global cxr_jobs_batch, cxr_ui_shader, cxr_jobs_inf
66
67 w = gpu.state.viewport_get()[2]
68 cxr_ui_shader.bind()
69 cxr_ui_shader.uniform_float( "scale", w )
70
71 if cxr_jobs_batch != None:
72 gpu.state.blend_set('ALPHA')
73 cxr_jobs_batch.draw(cxr_ui_shader)
74
75 blf.position(0,2,50,0)
76 blf.size(0,50,48)
77 blf.color(0,1.0,1.0,1.0,1.0)
78 blf.draw(0,"Compiling")
79
80 for ji in cxr_jobs_inf:
81 blf.position(0,ji[0]*w,35,0)
82 blf.size(0,50,20)
83 blf.draw(0,ji[1])
84
85 py = 80
86 blf.size(0,50,16)
87 for ln in reversed(CXR_COMPILER_CHAIN.LOG[-25:]):
88 blf.position(0,2,py,0)
89 blf.draw(0,ln[:-1])
90 py += 16
91
92 if CXR_PREVIEW_OPERATOR.LASTERR != None:
93 blf.position(0,2,80,0)
94 blf.size(0,50,48)
95 blf.color(0,1.0,0.2,0.2,0.9)
96 blf.draw(0,"This is a stoopid error\nWIthiuawdnaw")
97
98 # Something is off with TIMER,
99 # this forces the viewport to redraw before we can continue with our
100 # compilation stuff.
101
102 CXR_COMPILER_CHAIN.WAIT_REDRAW = False
103
104 def cxr_draw():
105 global cxr_view_shader, cxr_view_mesh, cxr_view_lines
106
107 cxr_view_shader.bind()
108
109 gpu.state.depth_mask_set(False)
110 gpu.state.line_width_set(1.5)
111 gpu.state.face_culling_set('BACK')
112 gpu.state.depth_test_set('NONE')
113 gpu.state.blend_set('ALPHA')
114
115 if cxr_view_lines != None:
116 cxr_view_lines.draw( cxr_view_shader )
117
118 gpu.state.depth_test_set('LESS_EQUAL')
119 gpu.state.blend_set('ADDITIVE')
120 if cxr_view_mesh != None:
121 cxr_view_mesh.draw( cxr_view_shader )
122
123 def cxr_jobs_update_graph(jobs):
124 global cxr_jobs_batch, cxr_ui_shader, cxr_jobs_inf
125
126 cxr_jobs_inf = []
127
128 total_width = 0
129 verts = []
130 colours = []
131 indices = []
132
133 for sys in jobs:
134 total_width += sys['w']
135
136 sf = 1.0/total_width
137 cur = 0.0
138 ci = 0
139
140 for sys in jobs:
141 w = sys['w']
142 h = 30.0
143 colour = sys['colour']
144 colourwait = (colour[0],colour[1],colour[2],0.4)
145 colourrun = (colour[0]*1.5,colour[1]*1.5,colour[2]*1.5,0.5)
146 colourdone = (colour[0],colour[1],colour[2],1.0)
147
148 jobs = sys['jobs']
149 sfsub = (1.0/(len(jobs)))*w
150 i = 0
151
152 for j in jobs:
153 if j == None: colour = colourdone
154 else: colour = colourwait
155
156 px = (cur + (i)*sfsub) * sf
157 px1 = (cur + (i+1.0)*sfsub) * sf - 0.003
158 i += 1
159
160 verts += [(px,0), (px, h), (px1, 0.0), (px1,h)]
161 colours += [colour,colour,colour,colour]
162 indices += [(ci+0,ci+2,ci+3),(ci+0,ci+3,ci+1)]
163 ci += 4
164
165 cxr_jobs_inf += [((sf*cur), sys['title'])]
166 cur += w
167
168 cxr_jobs_batch = batch_for_shader(
169 cxr_ui_shader, 'TRIS',
170 { "aPos": verts, "aColour": colours },
171 indices = indices
172 )
173
174 # view_layer.update() doesnt seem to work,
175 # tag_redraw() seems to have broken
176 # therefore, change a property
177 def scene_redraw():
178 ob = bpy.context.scene.objects[0]
179 ob.hide_render = ob.hide_render
180
181 # the 'real' way to refresh the scene
182 for area in bpy.context.window.screen.areas:
183 if area.type == 'view_3d':
184 area.tag_redraw()
185
186 # Shared libraries
187 # ------------------------------------------------------------------------------
188
189 # dlclose for reloading modules manually
190 libc_dlclose = None
191 libc_dlclose = cdll.LoadLibrary(None).dlclose
192 libc_dlclose.argtypes = [c_void_p]
193
194 # wrapper for ctypes binding
195 class extern():
196 def __init__(_,name,argtypes,restype):
197 _.name = name
198 _.argtypes = argtypes
199 _.restype = restype
200 _.call = None
201
202 def loadfrom(_,so):
203 _.call = getattr(so,_.name)
204 _.call.argtypes = _.argtypes
205
206 if _.restype != None:
207 _.call.restype = _.restype
208
209 # libcxr (convexer)
210 # ------------------------------------------------------------------------------
211
212 libcxr = None
213
214 # Structure definitions
215 #
216 class cxr_edge(Structure):
217 _fields_ = [("i0",c_int32),
218 ("i1",c_int32),
219 ("freestyle",c_int32)]
220
221 class cxr_static_loop(Structure):
222 _fields_ = [("index",c_int32),
223 ("edge_index",c_int32),
224 ("uv",c_double * 2)]
225
226 class cxr_polygon(Structure):
227 _fields_ = [("loop_start",c_int32),
228 ("loop_total",c_int32),
229 ("normal",c_double * 3),
230 ("center",c_double * 3),
231 ("material_id",c_int32)]
232
233 class cxr_material(Structure):
234 _fields_ = [("res",c_int32 * 2),
235 ("name",c_char_p)]
236
237 class cxr_static_mesh(Structure):
238 _fields_ = [("vertices",POINTER(c_double * 3)),
239 ("edges",POINTER(cxr_edge)),
240 ("loops",POINTER(cxr_static_loop)),
241 ("polys",POINTER(cxr_polygon)),
242 ("materials",POINTER(cxr_material)),
243
244 ("poly_count",c_int32),
245 ("vertex_count",c_int32),
246 ("edge_count",c_int32),
247 ("loop_count",c_int32),
248 ("material_count",c_int32)]
249
250 class cxr_tri_mesh(Structure):
251 _fields_ = [("vertices",POINTER(c_double *3)),
252 ("colours",POINTER(c_double *4)),
253 ("indices",POINTER(c_int32)),
254 ("indices_count",c_int32),
255 ("vertex_count",c_int32)]
256
257 class cxr_vmf_context(Structure):
258 _fields_ = [("mapversion",c_int32),
259 ("skyname",c_char_p),
260 ("detailvbsp",c_char_p),
261 ("detailmaterial",c_char_p),
262 ("scale",c_double),
263 ("offset",c_double *3),
264 ("lightmap_scale",c_int32),
265 ("brush_count",c_int32),
266 ("entity_count",c_int32),
267 ("face_count",c_int32)]
268
269 # Convert blenders mesh format into CXR's static format (they are very similar)
270 #
271 def mesh_cxr_format(obj):
272 orig_state = None
273
274 if bpy.context.active_object != None:
275 orig_state = obj.mode
276 if orig_state != 'OBJECT':
277 bpy.ops.object.mode_set(mode='OBJECT')
278
279 dgraph = bpy.context.evaluated_depsgraph_get()
280 data = obj.evaluated_get(dgraph).data
281
282 _,mtx_rot,_ = obj.matrix_world.decompose()
283
284 mesh = cxr_static_mesh()
285
286 vertex_data = ((c_double*3)*len(data.vertices))()
287 for i, vert in enumerate(data.vertices):
288 v = obj.matrix_world @ vert.co
289 vertex_data[i][0] = c_double(v[0])
290 vertex_data[i][1] = c_double(v[1])
291 vertex_data[i][2] = c_double(v[2])
292
293 loop_data = (cxr_static_loop*len(data.loops))()
294 polygon_data = (cxr_polygon*len(data.polygons))()
295
296 for i, poly in enumerate(data.polygons):
297 loop_start = poly.loop_start
298 loop_end = poly.loop_start + poly.loop_total
299 for loop_index in range(loop_start, loop_end):
300 loop = data.loops[loop_index]
301 loop_data[loop_index].index = loop.vertex_index
302 loop_data[loop_index].edge_index = loop.edge_index
303
304 if data.uv_layers:
305 uv = data.uv_layers.active.data[loop_index].uv
306 loop_data[loop_index].uv[0] = c_double(uv[0])
307 loop_data[loop_index].uv[1] = c_double(uv[1])
308 else:
309 loop_data[loop_index].uv[0] = c_double(0.0)
310 loop_data[loop_index].uv[1] = c_double(0.0)
311 center = obj.matrix_world @ poly.center
312 normal = mtx_rot @ poly.normal
313
314 polygon_data[i].loop_start = poly.loop_start
315 polygon_data[i].loop_total = poly.loop_total
316 polygon_data[i].normal[0] = normal[0]
317 polygon_data[i].normal[1] = normal[1]
318 polygon_data[i].normal[2] = normal[2]
319 polygon_data[i].center[0] = center[0]
320 polygon_data[i].center[1] = center[1]
321 polygon_data[i].center[2] = center[2]
322 polygon_data[i].material_id = poly.material_index
323
324 edge_data = (cxr_edge*len(data.edges))()
325
326 for i, edge in enumerate(data.edges):
327 edge_data[i].i0 = edge.vertices[0]
328 edge_data[i].i1 = edge.vertices[1]
329 edge_data[i].freestyle = edge.use_freestyle_mark
330
331 material_data = (cxr_material*len(obj.material_slots))()
332
333 for i, ms in enumerate(obj.material_slots):
334 inf = material_info(ms.material)
335 material_data[i].res[0] = inf['res'][0]
336 material_data[i].res[1] = inf['res'][1]
337 material_data[i].name = inf['name'].encode('utf-8')
338
339 mesh.edges = cast(edge_data, POINTER(cxr_edge))
340 mesh.vertices = cast(vertex_data, POINTER(c_double*3))
341 mesh.loops = cast(loop_data,POINTER(cxr_static_loop))
342 mesh.polys = cast(polygon_data, POINTER(cxr_polygon))
343 mesh.materials = cast(material_data, POINTER(cxr_material))
344
345 mesh.poly_count = len(data.polygons)
346 mesh.vertex_count = len(data.vertices)
347 mesh.edge_count = len(data.edges)
348 mesh.loop_count = len(data.loops)
349 mesh.material_count = len(obj.material_slots)
350
351 if orig_state != None:
352 bpy.ops.object.mode_set(mode=orig_state)
353
354 return mesh
355
356 # Callback ctypes indirection things.. not really sure.
357 c_libcxr_log_callback = None
358 c_libcxr_line_callback = None
359
360 # Public API
361 # -------------------------------------------------------------
362 libcxr_decompose = extern( "cxr_decompose",
363 [POINTER(cxr_static_mesh), POINTER(c_int32)],
364 c_void_p
365 )
366 libcxr_free_world = extern( "cxr_free_world",
367 [c_void_p],
368 None
369 )
370 libcxr_write_test_data = extern( "cxr_write_test_data",
371 [POINTER(cxr_static_mesh)],
372 None
373 )
374 libcxr_world_preview = extern( "cxr_world_preview",
375 [c_void_p],
376 POINTER(cxr_tri_mesh)
377 )
378 libcxr_free_tri_mesh = extern( "cxr_free_tri_mesh",
379 [c_void_p],
380 None
381 )
382 libcxr_begin_vmf = extern( "cxr_begin_vmf",
383 [POINTER(cxr_vmf_context), c_void_p],
384 None
385 )
386 libcxr_vmf_begin_entities = extern( "cxr_vmf_begin_entities",
387 [POINTER(cxr_vmf_context), c_void_p],
388 None
389 )
390 libcxr_push_world_vmf = extern("cxr_push_world_vmf",
391 [c_void_p,POINTER(cxr_vmf_context),c_void_p],
392 None
393 )
394 libcxr_end_vmf = extern( "cxr_end_vmf",
395 [POINTER(cxr_vmf_context),c_void_p],
396 None
397 )
398
399 # VDF + with open wrapper
400 libcxr_vdf_open = extern( "cxr_vdf_open", [c_char_p], c_void_p )
401 libcxr_vdf_close = extern( "cxr_vdf_close", [c_void_p], None )
402 libcxr_vdf_put = extern( "cxr_vdf_put", [c_void_p,c_char_p], None )
403 libcxr_vdf_node = extern( "cxr_vdf_node", [c_void_p,c_char_p], None )
404 libcxr_vdf_edon = extern( "cxr_vdf_edon", [c_void_p], None )
405 libcxr_vdf_kv = extern( "cxr_vdf_kv", [c_void_p,c_char_p,c_char_p], None )
406
407 class vdf_structure():
408 def __init__(_,path):
409 _.path = path
410 def __enter__(_):
411 _.fp = libcxr_vdf_open.call( _.path.encode('utf-8') )
412 if _.fp == None:
413 print( F"Could not open file {_.path}" )
414 return None
415 return _
416 def __exit__(_,type,value,traceback):
417 if _.fp != None:
418 libcxr_vdf_close.call(_.fp)
419 def put(_,s):
420 libcxr_vdf_put.call(_.fp, s.encode('utf-8') )
421 def node(_,name):
422 libcxr_vdf_node.call(_.fp, name.encode('utf-8') )
423 def edon(_):
424 libcxr_vdf_edon.call(_.fp)
425 def kv(_,k,v):
426 libcxr_vdf_kv.call(_.fp, k.encode('utf-8'), v.encode('utf-8'))
427
428 # Other
429 libcxr_lightpatch_bsp = extern( "cxr_lightpatch_bsp", [c_char_p], None )
430
431 libcxr_funcs = [ libcxr_decompose, libcxr_free_world, libcxr_begin_vmf, \
432 libcxr_vmf_begin_entities, libcxr_push_world_vmf, \
433 libcxr_end_vmf, libcxr_vdf_open, libcxr_vdf_close, \
434 libcxr_vdf_put, libcxr_vdf_node, libcxr_vdf_edon,
435 libcxr_vdf_kv, libcxr_lightpatch_bsp, libcxr_write_test_data,\
436 libcxr_world_preview, libcxr_free_tri_mesh ]
437
438 # Callbacks
439
440 def libcxr_log_callback(logStr):
441 print( F"{logStr.decode('utf-8')}",end='' )
442
443 cxr_line_positions = None
444 cxr_line_colours = None
445
446 def cxr_reset_lines():
447 global cxr_line_positions, cxr_line_colours
448
449 cxr_line_positions = []
450 cxr_line_colours = []
451
452 def cxr_batch_lines():
453 global cxr_line_positions, cxr_line_colours, cxr_view_shader, cxr_view_lines
454
455 cxr_view_lines = batch_for_shader(\
456 cxr_view_shader, 'LINES',\
457 { "pos": cxr_line_positions, "color": cxr_line_colours })
458
459 def libcxr_line_callback( p0,p1,colour ):
460 global cxr_line_colours, cxr_line_positions
461
462 cxr_line_positions += [(p0[0],p0[1],p0[2])]
463 cxr_line_positions += [(p1[0],p1[1],p1[2])]
464 cxr_line_colours += [(colour[0],colour[1],colour[2],colour[3])]
465 cxr_line_colours += [(colour[0],colour[1],colour[2],colour[3])]
466
467 # libnbvtf
468 # ------------------------------------------------------------------------------
469
470 libnbvtf = None
471
472 # Constants
473 NBVTF_IMAGE_FORMAT_RGBA8888 = 0
474 NBVTF_IMAGE_FORMAT_RGB888 = 2
475 NBVTF_IMAGE_FORMAT_DXT1 = 13
476 NBVTF_IMAGE_FORMAT_DXT5 = 15
477 NBVTF_TEXTUREFLAGS_CLAMPS = 0x00000004
478 NBVTF_TEXTUREFLAGS_CLAMPT = 0x00000008
479 NBVTF_TEXTUREFLAGS_NORMAL = 0x00000080
480 NBVTF_TEXTUREFLAGS_NOMIP = 0x00000100
481 NBVTF_TEXTUREFLAGS_NOLOD = 0x00000200
482
483 libnbvtf_convert = extern( "nbvtf_convert", \
484 [c_char_p,c_int32,c_int32,c_int32,c_int32,c_int32,c_uint32,c_char_p], \
485 c_int32 )
486
487 libnbvtf_init = extern( "nbvtf_init", [], None )
488 libnbvtf_funcs = [ libnbvtf_convert, libnbvtf_init ]
489
490 # Loading
491 # --------------------------
492
493 def shared_reload():
494 global libcxr, libnbvtf, libcxr_funcs, libnbvtf_funcs
495
496 # Unload libraries if existing
497 def _reload( lib, path ):
498 if lib != None:
499 _handle = lib._handle
500 for i in range(10): libc_dlclose( _handle )
501 lib = None
502 del lib
503 return cdll.LoadLibrary( F'{os.path.dirname(__file__)}/{path}.so' )
504
505 libnbvtf = _reload( libnbvtf, "libnbvtf" )
506 libcxr = _reload( libcxr, "libcxr" )
507
508 for fd in libnbvtf_funcs:
509 fd.loadfrom( libnbvtf )
510 libnbvtf_init.call()
511
512 for fd in libcxr_funcs:
513 fd.loadfrom( libcxr )
514
515 # Callbacks
516 global c_libcxr_log_callback, c_libcxr_line_callback
517
518 LOG_FUNCTION_TYPE = CFUNCTYPE(None,c_char_p)
519 c_libcxr_log_callback = LOG_FUNCTION_TYPE(libcxr_log_callback)
520
521 LINE_FUNCTION_TYPE = CFUNCTYPE(None,\
522 POINTER(c_double), POINTER(c_double), POINTER(c_double))
523 c_libcxr_line_callback = LINE_FUNCTION_TYPE(libcxr_line_callback)
524
525 libcxr.cxr_set_log_function(cast(c_libcxr_log_callback,c_void_p))
526 libcxr.cxr_set_line_function(cast(c_libcxr_line_callback,c_void_p))
527
528 build_time = c_char_p.in_dll(libcxr,'cxr_build_time')
529 print( F"libcxr build time: {build_time.value}" )
530
531 shared_reload()
532
533 # Configuration
534 # ------------------------------------------------------------------------------
535
536 # Standard entity functions, think of like base.fgd
537 #
538 def cxr_get_origin(context):
539 return context['object'].location * context['transform']['scale'] + \
540 mathutils.Vector(context['transform']['offset'])
541
542 def cxr_get_angles(context):
543 obj = context['object']
544 euler = [ a*57.295779513 for a in obj.rotation_euler ]
545 angle = [0,0,0]
546 angle[0] = euler[1]
547 angle[1] = euler[2]
548 angle[2] = euler[0]
549 return angle
550
551 def cxr_baseclass(classes, other):
552 base = other.copy()
553 for x in classes:
554 base.update(x.copy())
555 return base
556
557 # EEVEE Light component converter -> Source 1
558 #
559 def ent_lights(context):
560 obj = context['object']
561 kvs = cxr_baseclass([ent_origin],\
562 {
563 "_distance": (0.0 if obj.data.cxr_data.realtime else -1.0),
564 "_light": [int(pow(obj.data.color[i],1.0/2.2)*255.0) for i in range(3)] +\
565 [int(obj.data.energy * bpy.context.scene.cxr_data.light_scale)],
566 "_lightHDR": '-1 -1 -1 1',
567 "_lightscaleHDR": 1
568 })
569
570 if obj.data.type == 'SPOT':
571 kvs['_cone'] = obj.data.spot_size*(57.295779513/2.0)
572 kvs['_inner_cone'] = (1.0-obj.data.spot_blend)*kvs['_cone']
573
574 # Blenders spotlights are -z forward
575 # Source is +x, however, it seems to use a completely different system.
576 # Since we dont care about roll for spotlights, we just take the
577 # pitch and yaw via trig
578
579 _,mtx_rot,_ = obj.matrix_world.decompose()
580 fwd = mtx_rot @ mathutils.Vector((0,0,-1))
581
582 kvs['pitch'] = math.asin(fwd[2]) * 57.295779513
583 kvs['angles'] = [ 0.0, math.atan2(fwd[1],fwd[0]) * 57.295779513, 0.0 ]
584 kvs['_quadratic_attn'] = 0.0 # Source spotlights + quadratic falloff look
585 # Really bad...
586 #
587 # Blender's default has a much more 'nice'
588 # look.
589 kvs['_linear_attn'] = 1.0
590
591 elif obj.data.type == 'POINT':
592 kvs['_quadratic_attn'] = 1.0
593 kvs['_linear_attn'] = 0.0
594
595 elif obj.data.type == 'SUN':
596 pass # TODO
597
598 return kvs
599
600 def ent_prop(context):
601 kvs = {}
602 if isinstance( context['object'], bpy.types.Collection ):
603 kvs['angles'] = [0,180,0]
604 kvs['enablelightbounce'] = 1
605 kvs['disableshadows'] = 0
606 kvs['fademindist'] = -1
607 kvs['fadescale'] = 1
608 kvs['model'] = F"{asset_path('models',context['object'])}.mdl".lower()
609 kvs['renderamt'] = 255
610 kvs['rendercolor'] = [255, 255, 255]
611 kvs['skin'] = 0
612 kvs['solid'] = 6
613 kvs['uniformscale'] = 1.0
614
615 pos = mathutils.Vector(context['origin'])
616 pos += mathutils.Vector(context['transform']['offset'])
617
618 kvs['origin'] = [pos[1],-pos[0],pos[2]]
619
620 return kvs
621
622 def ent_cubemap(context):
623 obj = context['object']
624 return cxr_baseclass([ent_origin], {"cubemapsize": obj.data.cxr_data.size})
625
626 ent_origin = { "origin": cxr_get_origin }
627 ent_angles = { "angles": cxr_get_angles }
628 ent_transform = cxr_baseclass( [ent_origin], ent_angles )
629
630 #include the user config
631 exec(open(F'{os.path.dirname(__file__)}/config.py').read())
632
633 # Blender state callbacks
634 # ------------------------------------------------------------------------------
635
636 @persistent
637 def cxr_on_load(dummy):
638 global cxr_view_lines, cxr_view_mesh
639
640 cxr_view_lines = None
641 cxr_view_mesh = None
642
643 @persistent
644 def cxr_dgraph_update(scene,dgraph):
645 return
646 print( F"Hallo {time.time()}" )
647
648 # Convexer compilation functions
649 # ------------------------------------------------------------------------------
650
651 # Asset path management
652
653 def asset_uid(asset):
654 if isinstance(asset,str):
655 return asset
656
657 # Create a unique ID string
658 base = "bopshei"
659 v = asset.cxr_data.asset_id
660 name = ""
661
662 if v == 0:
663 name = "A"
664 else:
665 dig = []
666
667 while v:
668 dig.append( int( v % len(base) ) )
669 v //= len(base)
670
671 for d in dig[::-1]:
672 name += base[d]
673
674 if bpy.context.scene.cxr_data.include_names:
675 name += asset.name.replace('.','_')
676
677 return name
678
679 # -> <project_name>/<asset_name>
680 def asset_name(asset):
681 return F"{bpy.context.scene.cxr_data.project_name}/{asset_uid(asset)}"
682
683 # -> <subdir>/<project_name>/<asset_name>
684 def asset_path(subdir, asset):
685 return F"{subdir}/{asset_name(asset_uid(asset))}"
686
687 # -> <csgo>/<subdir>/<project_name>/<asset_name>
688 def asset_full_path(sdir,asset):
689 return F"{bpy.context.scene.cxr_data.subdir}/"+\
690 F"{asset_path(sdir,asset_uid(asset))}"
691
692 # Entity functions / infos
693 # ------------------------
694
695 def cxr_intrinsic_classname(obj):
696 if obj.type == 'LIGHT':
697 return {
698 'SPOT': "light_spot",
699 'POINT': "light",
700 'SUN': "light_directional" }[ obj.data.type ]
701
702 elif obj.type == 'LIGHT_PROBE':
703 return "env_cubemap"
704 elif obj.type == 'EMPTY':
705 if obj.is_instancer:
706 return "prop_static"
707
708 return None
709
710 def cxr_custom_class(obj):
711 if obj.type == 'MESH': custom_class = obj.cxr_data.brushclass
712 else: custom_class = obj.cxr_data.classname
713
714 return custom_class
715
716 def cxr_classname(obj):
717 intr = cxr_intrinsic_classname(obj)
718 if intr != None: return intr
719
720 custom_class = cxr_custom_class(obj)
721 if custom_class != 'NONE':
722 return custom_class
723
724 return None
725
726 # Returns array of:
727 # intinsic: (k, False, value)
728 # property: (k, True, value or default)
729 #
730 # Error: None
731 #
732 def cxr_entity_keyvalues(context):
733 classname = context['classname']
734 obj = context['object']
735 if classname not in cxr_entities: return None
736
737 result = []
738
739 entdef = cxr_entities[classname]
740 kvs = entdef['keyvalues']
741
742 if callable(kvs): kvs = kvs(context)
743
744 for k in kvs:
745 kv = kvs[k]
746 value = kv
747 isprop = False
748
749 if isinstance(kv,dict):
750 isprop = True
751 value = obj[ F"cxrkv_{k}" ]
752 else:
753 if callable(kv):
754 value = kv(context)
755
756 if isinstance(value,mathutils.Vector):
757 value = [_ for _ in value]
758
759 result += [(k, isprop, value)]
760
761 return result
762
763 # Extract material information from shader graph data
764 #
765 def material_info(mat):
766 info = {}
767 info['res'] = (512,512)
768 info['name'] = 'tools/toolsnodraw'
769
770 if mat == None or mat.use_nodes == False:
771 return info
772
773 # Builtin shader
774 if mat.cxr_data.shader == 'Builtin':
775 info['name'] = mat.name
776 return info
777
778 # Custom materials
779 info['name'] = asset_name(mat)
780
781 # Using the cxr_graph_mapping as a reference, go through the shader
782 # graph and gather all $props from it.
783 #
784 def _graph_read( node_def, node=None, depth=0 ):
785 nonlocal mat
786 nonlocal info
787
788 def _variant_apply( val ):
789 nonlocal mat
790
791 if isinstance( val, str ):
792 return val
793 else:
794 for shader_variant in val:
795 if shader_variant[0] == mat.cxr_data.shader:
796 return shader_variant[1]
797
798 # Find rootnodes
799 if node == None:
800 _graph_read.extracted = []
801
802 for node_idname in node_def:
803 for n in mat.node_tree.nodes:
804 if n.bl_idname == node_idname:
805 node_def = node_def[node_idname]
806 node = n
807 break
808
809 for link in node_def:
810 if isinstance( node_def[link], dict ):
811 inputt = node.inputs[link]
812 inputt_def = node_def[link]
813
814 if inputt.is_linked:
815
816 # look for definitions for the connected node type
817 con = inputt.links[0].from_node
818
819 for node_idname in inputt_def:
820 if con.bl_idname == node_idname:
821 con_def = inputt_def[ node_idname ]
822 _graph_read( con_def, con, depth+1 )
823
824 # No definition found! :(
825 # TODO: Make a warning for this?
826
827 else:
828 if "default" in inputt_def:
829 prop = _variant_apply( inputt_def['default'] )
830 info[prop] = inputt.default_value
831 else:
832 prop = _variant_apply( node_def[link] )
833 info[prop] = getattr(node,link)
834
835 _graph_read(cxr_graph_mapping)
836
837 if "$basetexture" in info:
838 export_res = info['$basetexture'].cxr_data.export_res
839 info['res'] = (export_res[0], export_res[1])
840
841 return info
842
843 def vec3_min( a, b ):
844 return mathutils.Vector((min(a[0],b[0]),min(a[1],b[1]),min(a[2],b[2])))
845 def vec3_max( a, b ):
846 return mathutils.Vector((max(a[0],b[0]),max(a[1],b[1]),max(a[2],b[2])))
847
848 def cxr_collection_center(collection, transform):
849 BIG=999999999
850 bounds_min = mathutils.Vector((BIG,BIG,BIG))
851 bounds_max = mathutils.Vector((-BIG,-BIG,-BIG))
852
853 for obj in collection.objects:
854 if obj.type == 'MESH':
855 corners = [ mathutils.Vector(c) for c in obj.bound_box ]
856
857 for corner in [ obj.matrix_world@c for c in corners ]:
858 bounds_min = vec3_min( bounds_min, corner )
859 bounds_max = vec3_max( bounds_max, corner )
860
861 center = (bounds_min + bounds_max) / 2.0
862
863 origin = mathutils.Vector((-center[1],center[0],center[2]))
864 origin *= transform['scale']
865
866 return origin
867
868 # Prepares Scene into dictionary format
869 #
870 def cxr_scene_collect():
871 context = bpy.context
872
873 # Make sure all of our asset types have a unique ID
874 def _uid_prepare(objtype):
875 used_ids = [0]
876 to_generate = []
877 id_max = 0
878 for o in objtype:
879 vs = o.cxr_data
880 if vs.asset_id in used_ids:
881 to_generate+=[vs]
882 else:
883 id_max = max(id_max,vs.asset_id)
884 used_ids+=[vs.asset_id]
885 for vs in to_generate:
886 id_max += 1
887 vs.asset_id = id_max
888 _uid_prepare(bpy.data.materials)
889 _uid_prepare(bpy.data.images)
890 _uid_prepare(bpy.data.collections)
891
892 sceneinfo = {
893 "entities": [], # Everything with a classname
894 "geo": [], # All meshes without a classname
895 "heros": [] # Collections prefixed with mdl_
896 }
897
898 def _collect(collection,transform):
899 nonlocal sceneinfo
900
901 if collection.name.startswith('.'): return
902 if collection.hide_render: return
903
904 if collection.name.startswith('mdl_'):
905 sceneinfo['entities'] += [{
906 "object": collection,
907 "classname": "prop_static",
908 "transform": transform,
909 "origin": cxr_collection_center( collection, transform )
910 }]
911
912 sceneinfo['heros'] += [{
913 "collection": collection,
914 "transform": transform,
915 "origin": cxr_collection_center( collection, transform )
916 }]
917 return
918
919 for obj in collection.objects:
920 if obj.hide_get(): continue
921
922 classname = cxr_classname( obj )
923
924 if classname != None:
925 sceneinfo['entities'] += [{
926 "object": obj,
927 "classname": classname,
928 "transform": transform
929 }]
930 elif obj.type == 'MESH':
931 sceneinfo['geo'] += [{
932 "object": obj,
933 "transform": transform
934 }]
935
936 for c in collection.children:
937 _collect( c, transform )
938
939 transform_main = {
940 "scale": context.scene.cxr_data.scale_factor,
941 "offset": (0,0,0)
942 }
943
944 transform_sky = {
945 "scale": context.scene.cxr_data.skybox_scale_factor,
946 "offset": (0,0,context.scene.cxr_data.skybox_offset )
947 }
948
949 if 'main' in bpy.data.collections:
950 _collect( bpy.data.collections['main'], transform_main )
951
952 if 'skybox' in bpy.data.collections:
953 _collect( bpy.data.collections['skybox'], transform_sky )
954
955 return sceneinfo
956
957 # Write VMF out to file (JOB HANDLER)
958 #
959 def cxr_export_vmf(sceneinfo, output_vmf):
960 cxr_reset_lines()
961
962 with vdf_structure(output_vmf) as m:
963 print( F"Write: {output_vmf}" )
964
965 vmfinfo = cxr_vmf_context()
966 vmfinfo.mapversion = 4
967
968 #TODO: These need to be in options...
969 vmfinfo.skyname = b"sky_csgo_night02b"
970 vmfinfo.detailvbsp = b"detail.vbsp"
971 vmfinfo.detailmaterial = b"detail/detailsprites"
972 vmfinfo.lightmap_scale = 12
973
974 vmfinfo.brush_count = 0
975 vmfinfo.entity_count = 0
976 vmfinfo.face_count = 0
977
978 libcxr_begin_vmf.call( pointer(vmfinfo), m.fp )
979
980 def _buildsolid( cmd ):
981 nonlocal m
982
983 baked = mesh_cxr_format( cmd['object'] )
984 world = libcxr_decompose.call( baked, None )
985
986 if world == None:
987 return False
988
989 vmfinfo.scale = cmd['transform']['scale']
990
991 offset = cmd['transform']['offset']
992 vmfinfo.offset[0] = offset[0]
993 vmfinfo.offset[1] = offset[1]
994 vmfinfo.offset[2] = offset[2]
995
996 libcxr_push_world_vmf.call( world, pointer(vmfinfo), m.fp )
997 libcxr_free_world.call( world )
998
999 return True
1000
1001 # World geometry
1002 for brush in sceneinfo['geo']:
1003 if not _buildsolid( brush ):
1004 cxr_batch_lines()
1005 scene_redraw()
1006 return False
1007
1008 libcxr_vmf_begin_entities.call(pointer(vmfinfo), m.fp)
1009
1010 # Entities
1011 for ent in sceneinfo['entities']:
1012 obj = ent['object']
1013 ctx = ent['transform']
1014 cls = ent['classname']
1015
1016 m.node( 'entity' )
1017 m.kv( 'classname', cls )
1018
1019 kvs = cxr_entity_keyvalues( ent )
1020
1021 for kv in kvs:
1022 if isinstance(kv[2], list):
1023 m.kv( kv[0], ' '.join([str(_) for _ in kv[2]]) )
1024 else: m.kv( kv[0], str(kv[2]) )
1025
1026 if not isinstance( obj, bpy.types.Collection ):
1027 if obj.type == 'MESH':
1028 if not _buildsolid( ent ):
1029 cxr_batch_lines()
1030 scene_redraw()
1031 return False
1032
1033 m.edon()
1034
1035 print( "Done" )
1036 return True
1037
1038 # COmpile image using NBVTF and hash it (JOB HANDLER)
1039 #
1040 def compile_image(img):
1041 if img==None:
1042 return None
1043
1044 name = asset_name(img)
1045 src_path = bpy.path.abspath(img.filepath)
1046
1047 dims = img.cxr_data.export_res
1048 fmt = {
1049 'RGBA': NBVTF_IMAGE_FORMAT_RGBA8888,
1050 'DXT1': NBVTF_IMAGE_FORMAT_DXT1,
1051 'DXT5': NBVTF_IMAGE_FORMAT_DXT5,
1052 'RGB': NBVTF_IMAGE_FORMAT_RGB888
1053 }[ img.cxr_data.fmt ]
1054
1055 mipmap = img.cxr_data.mipmap
1056 lod = img.cxr_data.lod
1057 clamp = img.cxr_data.clamp
1058 flags = img.cxr_data.flags
1059
1060 q=bpy.context.scene.cxr_data.image_quality
1061
1062 userflag_hash = F"{mipmap}.{lod}.{clamp}.{flags}"
1063 file_hash = F"{name}.{os.path.getmtime(src_path)}"
1064 comphash = F"{file_hash}.{dims[0]}.{dims[1]}.{fmt}.{userflag_hash}.{q}"
1065
1066 if img.cxr_data.last_hash != comphash:
1067 print( F"Texture update: {img.filepath}" )
1068
1069 src = src_path.encode('utf-8')
1070 dst = (asset_full_path('materials',img)+'.vtf').encode('utf-8')
1071
1072 flags_full = flags
1073
1074 # texture setting flags
1075 if not lod: flags_full |= NBVTF_TEXTUREFLAGS_NOLOD
1076 if clamp:
1077 flags_full |= NBVTF_TEXTUREFLAGS_CLAMPS
1078 flags_full |= NBVTF_TEXTUREFLAGS_CLAMPT
1079
1080 if libnbvtf_convert.call(src,dims[0],dims[1],mipmap,fmt,q,flags_full,dst):
1081 img.cxr_data.last_hash = comphash
1082
1083 return name
1084
1085 #
1086 # Compile a material to VMT format. This is quick to run, doesnt need to be a
1087 # job handler.
1088 #
1089 def compile_material(mat):
1090 info = material_info(mat)
1091 properties = mat.cxr_data
1092
1093 print( F"Compile {asset_full_path('materials',mat)}.vmt" )
1094 if properties.shader == 'Builtin':
1095 return []
1096
1097 props = []
1098
1099 # Walk the property tree
1100 def _mlayer( layer ):
1101 nonlocal properties, props
1102
1103 for decl in layer:
1104 if isinstance(layer[decl],dict): # $property definition
1105 pdef = layer[decl]
1106 ptype = pdef['type']
1107
1108 subdefines = False
1109 default = None
1110 prop = None
1111
1112 if 'shaders' in pdef and properties.shader not in pdef['shaders']:
1113 continue
1114
1115 # Group expansion (does it have subdefinitions?)
1116 for ch in pdef:
1117 if isinstance(pdef[ch],dict):
1118 subdefines = True
1119 break
1120
1121 expandview = False
1122
1123 if ptype == 'ui':
1124 expandview = True
1125 else:
1126 if ptype == 'intrinsic':
1127 if decl in info:
1128 prop = info[decl]
1129 else:
1130 prop = getattr(properties,decl)
1131 default = pdef['default']
1132
1133 if not isinstance(prop,str) and \
1134 not isinstance(prop,bpy.types.Image) and \
1135 hasattr(prop,'__getitem__'):
1136 prop = tuple([p for p in prop])
1137
1138 if prop != default:
1139 # write prop
1140 props += [(decl,pdef,prop)]
1141
1142 if subdefines:
1143 expandview = True
1144
1145 if expandview: _mlayer(pdef)
1146
1147 _mlayer( cxr_shader_params )
1148
1149 # Write the vmt
1150 with vdf_structure( F"{asset_full_path('materials',mat)}.vmt" ) as vmt:
1151 vmt.node( properties.shader )
1152 vmt.put( "// Convexer export\n" )
1153
1154 for pair in props:
1155 decl = pair[0]
1156 pdef = pair[1]
1157 prop = pair[2]
1158
1159 def _numeric(v):
1160 nonlocal pdef
1161 if 'exponent' in pdef: return str(pow( v, pdef['exponent'] ))
1162 else: return str(v)
1163
1164 if isinstance(prop,bpy.types.Image):
1165 vmt.kv( decl, asset_name(prop))
1166 elif isinstance(prop,bool):
1167 vmt.kv( decl, '1' if prop else '0' )
1168 elif isinstance(prop,str):
1169 vmt.kv( decl, prop )
1170 elif isinstance(prop,float) or isinstance(prop,int):
1171 vmt.kv( decl, _numeric(prop) )
1172 elif isinstance(prop,tuple):
1173 vmt.kv( decl, F"[{' '.join([_numeric(_) for _ in prop])}]" )
1174 else:
1175 vmt.put( F"// (cxr) unkown shader value type'{type(prop)}'" )
1176
1177 vmt.edon()
1178 return props
1179
1180 def cxr_export_modelsrc( mdl, origin, asset_dir, project_name, transform ):
1181 dgraph = bpy.context.evaluated_depsgraph_get()
1182
1183 # Compute hash value
1184 chash = asset_uid(mdl)+str(origin)+str(transform)
1185
1186 #for obj in mdl.objects:
1187 # if obj.type != 'MESH':
1188 # continue
1189
1190 # ev = obj.evaluated_get(dgraph).data
1191 # srcverts=[(v.co[0],v.co[1],v.co[2]) for v in ev.vertices]
1192 # srcloops=[(l.normal[0],l.normal[1],l.normal[2]) for l in ev.loops]
1193
1194 # chash=hashlib.sha224((str(srcverts)+chash).encode()).hexdigest()
1195 # chash=hashlib.sha224((str(srcloops)+chash).encode()).hexdigest()
1196
1197 # if ev.uv_layers.active != None:
1198 # uv_layer = ev.uv_layers.active.data
1199 # srcuv=[(uv.uv[0],uv.uv[1]) for uv in uv_layer]
1200 # else:
1201 # srcuv=['none']
1202
1203 # chash=hashlib.sha224((str(srcuv)+chash).encode()).hexdigest()
1204 # srcmats=[ ms.material.name for ms in obj.material_slots ]
1205 # chash=hashlib.sha224((str(srcmats)+chash).encode()).hexdigest()
1206 # transforms=[ obj.location, obj.rotation_euler, obj.scale ]
1207 # srctr=[(v[0],v[1],v[2]) for v in transforms]
1208 # chash=hashlib.sha224((str(srctr)+chash).encode()).hexdigest()
1209
1210 #if chash != mdl.cxr_data.last_hash:
1211 # mdl.cxr_data.last_hash = chash
1212 # print( F"Compile: {mdl.name}" )
1213 #else:
1214 # return True
1215
1216 bpy.ops.object.select_all(action='DESELECT')
1217
1218 # Get viewlayer
1219 def _get_layer(col,name):
1220 for c in col.children:
1221 if c.name == name:
1222 return c
1223 sub = _get_layer(c,name)
1224 if sub != None:
1225 return sub
1226 return None
1227 layer = _get_layer(bpy.context.view_layer.layer_collection,mdl.name)
1228
1229 prev_state = layer.hide_viewport
1230 layer.hide_viewport=False
1231
1232 # Collect materials to be compiled, and temp rename for export
1233 mat_dict = {}
1234
1235 for obj in mdl.objects:
1236 obj.select_set(state=True)
1237 for ms in obj.material_slots:
1238 if ms.material != None:
1239 if ms.material not in mat_dict:
1240 mat_dict[ms.material] = ms.material.name
1241 ms.material.name = asset_uid(ms.material)
1242 ms.material.use_nodes = False
1243
1244 uid=asset_uid(mdl)
1245 bpy.ops.export_scene.fbx( filepath=F'{asset_dir}/{uid}_ref.fbx',\
1246 check_existing=False,
1247 use_selection=True,
1248 apply_unit_scale=False,
1249 bake_space_transform=False
1250 )
1251
1252 # Fix material names back to original
1253 for mat in mat_dict:
1254 mat.name = mat_dict[mat]
1255 mat.use_nodes = True
1256
1257 layer.hide_viewport=prev_state
1258
1259 # Write out QC file
1260 with open(F'{asset_dir}/{uid}.qc','w') as o:
1261 o.write(F'$modelname "{project_name}/{uid}"\n')
1262 #o.write(F'$scale .32\n')
1263 o.write(F'$scale {transform["scale"]/100.0}\n')
1264 o.write(F'$body _ "{uid}_ref.fbx"\n')
1265 o.write(F'$staticprop\n')
1266 o.write(F'$origin {origin[0]} {origin[1]} {origin[2]}\n')
1267
1268 #TODO: vphys
1269 o.write(F'$cdmaterials {project_name}\n')
1270 o.write(F'$sequence idle {uid}_ref.fbx\n')
1271
1272 return True
1273 #
1274 # Copy bsp file (and also lightpatch it)
1275 #
1276 def cxr_patchmap( src, dst ):
1277 libcxr_lightpatch_bsp.call( src.encode('utf-8') )
1278 shutil.copyfile( src, dst )
1279 return True
1280
1281 # Convexer operators
1282 # ------------------------------------------------------------------------------
1283
1284 # Force reload of shared libraries
1285 #
1286 class CXR_RELOAD(bpy.types.Operator):
1287 bl_idname="convexer.reload"
1288 bl_label="Reload"
1289 def execute(_,context):
1290 shared_reload()
1291 return {'FINISHED'}
1292
1293 # Used for exporting data to use with ASAN builds
1294 #
1295 class CXR_DEV_OPERATOR(bpy.types.Operator):
1296 bl_idname="convexer.dev_test"
1297 bl_label="Export development data"
1298
1299 def execute(_,context):
1300 # Prepare input data
1301 mesh_src = mesh_cxr_format(context.active_object)
1302 libcxr_write_test_data.call( pointer(mesh_src) )
1303 return {'FINISHED'}
1304
1305 # UI: Preview how the brushes will looks in 3D view
1306 #
1307 class CXR_PREVIEW_OPERATOR(bpy.types.Operator):
1308 bl_idname="convexer.preview"
1309 bl_label="Preview Brushes"
1310
1311 LASTERR = None
1312 RUNNING = False
1313
1314 def execute(_,context):
1315 return {'FINISHED'}
1316
1317 def modal(_,context,event):
1318 global cxr_view_mesh
1319 static = _.__class__
1320
1321 if event.type == 'ESC':
1322 cxr_reset_lines()
1323 cxr_batch_lines()
1324 cxr_view_mesh = None
1325 static.RUNNING = False
1326
1327 scene_redraw()
1328 return {'FINISHED'}
1329
1330 return {'PASS_THROUGH'}
1331
1332 def invoke(_,context,event):
1333 global cxr_view_shader, cxr_view_mesh
1334 static = _.__class__
1335 static.LASTERR = None
1336
1337 cxr_reset_lines()
1338
1339 mesh_src = mesh_cxr_format(context.active_object)
1340
1341 err = c_int32(0)
1342 world = libcxr_decompose.call( mesh_src, pointer(err) )
1343
1344 if world == None:
1345 cxr_view_mesh = None
1346 cxr_batch_lines()
1347 scene_redraw()
1348
1349 static.LASTERR = ["There is no error", \
1350 "Non-Manifold",\
1351 "Bad-Manifold",\
1352 "No-Candidate",\
1353 "Internal-Fail",\
1354 "Non-Coplanar",\
1355 "Non-Convex Polygon"]\
1356 [err.value]
1357
1358 if static.RUNNING:
1359 return {'CANCELLED'}
1360 else:
1361 context.window_manager.modal_handler_add(_)
1362 return {'RUNNING_MODAL'}
1363
1364 # Generate preview using cxr
1365 #
1366 ptrpreview = libcxr_world_preview.call( world )
1367 preview = ptrpreview[0]
1368
1369 vertices = preview.vertices[:preview.vertex_count]
1370 vertices = [(_[0],_[1],_[2]) for _ in vertices]
1371
1372 colours = preview.colours[:preview.vertex_count]
1373 colours = [(_[0],_[1],_[2],_[3]) for _ in colours]
1374
1375 indices = preview.indices[:preview.indices_count]
1376 indices = [ (indices[i*3+0],indices[i*3+1],indices[i*3+2]) \
1377 for i in range(int(preview.indices_count/3)) ]
1378
1379 cxr_view_mesh = batch_for_shader(
1380 cxr_view_shader, 'TRIS',
1381 { "pos": vertices, "color": colours },
1382 indices = indices,
1383 )
1384
1385 libcxr_free_tri_mesh.call( ptrpreview )
1386 libcxr_free_world.call( world )
1387 cxr_batch_lines()
1388 scene_redraw()
1389
1390 # Allow user to spam the operator
1391 if static.RUNNING:
1392 return {'CANCELLED'}
1393
1394 if not static.RUNNING:
1395 static.RUNNING = True
1396 context.window_manager.modal_handler_add(_)
1397 return {'RUNNING_MODAL'}
1398
1399 # Search for VMF compiler executables in subdirectory
1400 #
1401 class CXR_DETECT_COMPILERS(bpy.types.Operator):
1402 bl_idname="convexer.detect_compilers"
1403 bl_label="Find compilers"
1404
1405 def execute(self,context):
1406 scene = context.scene
1407 settings = scene.cxr_data
1408 subdir = settings.subdir
1409
1410 for exename in ['studiomdl','vbsp','vvis','vrad']:
1411 searchpath = os.path.normpath(F'{subdir}/../bin/{exename}.exe')
1412 if os.path.exists(searchpath):
1413 settings[F'exe_{exename}'] = searchpath
1414
1415 return {'FINISHED'}
1416
1417 # Main compile function
1418 #
1419 class CXR_COMPILER_CHAIN(bpy.types.Operator):
1420 bl_idname="convexer.chain"
1421 bl_label="Compile Chain"
1422
1423 # 'static'
1424 USER_EXIT = False
1425 SUBPROC = None
1426 TIMER = None
1427 TIMER_LAST = 0.0
1428 WAIT_REDRAW = False
1429 FILE = None
1430 LOG = []
1431
1432 JOBINFO = None
1433 JOBID = 0
1434 JOBSYS = None
1435
1436 def cancel(_,context):
1437 global cxr_jobs_batch
1438 static = _.__class__
1439 wm = context.window_manager
1440
1441 if static.SUBPROC != None:
1442 static.SUBPROC.terminate()
1443 static.SUBPROC = None
1444
1445 if static.TIMER != None:
1446 wm.event_timer_remove( static.TIMER )
1447 static.TIMER = None
1448
1449 static.FILE.close()
1450
1451 cxr_jobs_batch = None
1452 scene_redraw()
1453 return {'FINISHED'}
1454
1455 def modal(_,context,ev):
1456 static = _.__class__
1457
1458 if ev.type == 'TIMER':
1459 global cxr_jobs_batch
1460
1461 if static.WAIT_REDRAW:
1462 scene_redraw()
1463 return {'PASS_THROUGH'}
1464 static.WAIT_REDRAW = True
1465
1466 if static.USER_EXIT:
1467 print( "Chain USER_EXIT" )
1468 return _.cancel(context)
1469
1470 if static.SUBPROC != None:
1471 # Deal with async modes
1472 status = static.SUBPROC.poll()
1473 if status == None:
1474
1475 # Cannot redirect STDOUT through here without causing
1476 # undefined behaviour due to the Blender Python specification.
1477 #
1478 # Have to write it out to a file and read it back in.
1479 #
1480 with open("/tmp/convexer_compile_log.txt","r") as log:
1481 static.LOG = log.readlines()
1482 return {'PASS_THROUGH'}
1483 else:
1484 #for l in static.SUBPROC.stdout:
1485 # print( F'-> {l.decode("utf-8")}',end='' )
1486 static.SUBPROC = None
1487
1488 if status != 0:
1489 print(F'Compiler () error: {status}')
1490 return _.cancel(context)
1491
1492 static.JOBSYS['jobs'][static.JOBID] = None
1493 cxr_jobs_update_graph( static.JOBINFO )
1494 scene_redraw()
1495 return {'PASS_THROUGH'}
1496
1497 # Compile syncronous thing
1498 for sys in static.JOBINFO:
1499 for i,target in enumerate(sys['jobs']):
1500 if target != None:
1501
1502 if callable(sys['exec']):
1503 print( F"Run (sync): {static.JOBID} @{time.time()}" )
1504
1505 if not sys['exec'](*target):
1506 print( "Job failed" )
1507 return _.cancel(context)
1508
1509 sys['jobs'][i] = None
1510 static.JOBID += 1
1511 else:
1512 # Run external executable (wine)
1513 static.SUBPROC = subprocess.Popen( target,
1514 stdout=static.FILE,\
1515 stderr=subprocess.PIPE,\
1516 cwd=sys['cwd'])
1517 static.JOBSYS = sys
1518 static.JOBID = i
1519
1520 cxr_jobs_update_graph( static.JOBINFO )
1521 scene_redraw()
1522 return {'PASS_THROUGH'}
1523
1524 # All completed
1525 print( "All jobs completed!" )
1526 cxr_jobs_batch = None
1527
1528 scene_redraw()
1529 return _.cancel(context)
1530
1531 return {'PASS_THROUGH'}
1532
1533 def invoke(_,context,event):
1534 static = _.__class__
1535 wm = context.window_manager
1536
1537 if static.TIMER == None:
1538 print("Launching compiler toolchain")
1539
1540 # Run static compilation units now (collect, vmt..)
1541 filepath = bpy.data.filepath
1542 directory = os.path.dirname(filepath)
1543 settings = bpy.context.scene.cxr_data
1544
1545 asset_dir = F"{directory}/modelsrc"
1546 material_dir = F"{settings.subdir}/materials/{settings.project_name}"
1547 model_dir = F"{settings.subdir}/models/{settings.project_name}"
1548 output_vmf = F"{directory}/{settings.project_name}.vmf"
1549
1550 os.makedirs( asset_dir, exist_ok=True )
1551 os.makedirs( material_dir, exist_ok=True )
1552 os.makedirs( model_dir, exist_ok=True )
1553
1554 static.FILE = open(F"/tmp/convexer_compile_log.txt","w")
1555 static.LOG = []
1556
1557 sceneinfo = cxr_scene_collect()
1558 image_jobs = []
1559 qc_jobs = []
1560
1561 # Collect materials
1562 a_materials = set()
1563 for brush in sceneinfo['geo']:
1564 for ms in brush['object'].material_slots:
1565 a_materials.add( ms.material )
1566
1567 for ent in sceneinfo['entities']:
1568 if isinstance(ent['object'],bpy.types.Collection): continue
1569
1570 if ent['object'].type == 'MESH':
1571 for ms in ent['object'].material_slots:
1572 a_materials.add( ms.material )
1573
1574 # TODO.. this should just be in the entity loop
1575 for hero in sceneinfo['heros']:
1576 uid = asset_uid(hero['collection'])
1577 qc_jobs += [F'{uid}.qc']
1578 for obj in hero['collection'].objects:
1579 for ms in obj.material_slots:
1580 a_materials.add( ms.material )
1581
1582 # Collect images
1583 for mat in a_materials:
1584 for pair in compile_material(mat):
1585 decl = pair[0]
1586 pdef = pair[1]
1587 prop = pair[2]
1588
1589 if isinstance(prop,bpy.types.Image):
1590 flags = 0
1591 if 'flags' in pdef: flags = pdef['flags']
1592 if prop not in image_jobs:
1593 image_jobs += [(prop,)]
1594 prop.cxr_data.flags = flags
1595
1596 # Convexer jobs
1597 static.JOBID = 0
1598 static.JOBINFO = []
1599
1600 static.JOBINFO += [{
1601 "title": "Convexer",
1602 "w": 20,
1603 "colour": (1.0,0.3,0.1,1.0),
1604 "exec": cxr_export_vmf,
1605 "jobs": [(sceneinfo,output_vmf)]
1606 }]
1607
1608 if len(image_jobs) > 0:
1609 static.JOBINFO += [{
1610 "title": "Textures",
1611 "w": 40,
1612 "colour": (0.1,1.0,0.3,1.0),
1613 "exec": compile_image,
1614 "jobs": image_jobs
1615 }]
1616
1617 # FBX stage
1618
1619 if len(sceneinfo['heros']) > 0:
1620 static.JOBINFO += [{
1621 "title": "Batches",
1622 "w": 25,
1623 "colour": (0.5,0.5,1.0,1.0),
1624 "exec": cxr_export_modelsrc,
1625 "jobs": [(h['collection'], h['origin'], asset_dir, \
1626 settings.project_name, h['transform']) for h in \
1627 sceneinfo['heros']]
1628 }]
1629
1630 # VBSP stage
1631 game = 'z:'+settings.subdir.replace('/','\\')
1632 args = [ \
1633 '-game', game, settings.project_name
1634 ]
1635
1636 if len(qc_jobs) > 0:
1637 static.JOBINFO += [{
1638 "title": "StudioMDL",
1639 "w": 20,
1640 "colour": (0.8,0.1,0.1,1.0),
1641 "exec": "studiomdl",
1642 "jobs": [[settings[F'exe_studiomdl']] + [\
1643 '-nop4', '-game', game, qc] for qc in qc_jobs],
1644 "cwd": asset_dir
1645 }]
1646
1647 static.JOBINFO += [{
1648 "title": "VBSP",
1649 "w": 25,
1650 "colour": (0.1,0.2,1.0,1.0),
1651 "exec": "vbsp",
1652 "jobs": [[settings[F'exe_vbsp']] + args],
1653 "cwd": directory
1654 }]
1655
1656 static.JOBINFO += [{
1657 "title": "VVIS",
1658 "w": 25,
1659 "colour": (0.9,0.5,0.5,1.0),
1660 "exec": "vvis",
1661 "jobs": [[settings[F'exe_vvis']] + args],
1662 "cwd": directory
1663 }]
1664
1665 static.JOBINFO += [{
1666 "title": "VRAD",
1667 "w": 25,
1668 "colour": (0.9,0.2,0.3,1.0),
1669 "exec": "vrad",
1670 "jobs": [[settings[F'exe_vrad']] + args],
1671 "cwd": directory
1672 }]
1673
1674 static.JOBINFO += [{
1675 "title": "CXR",
1676 "w": 5,
1677 "colour": (0.0,1.0,0.4,1.0),
1678 "exec": cxr_patchmap,
1679 "jobs": [(F"{directory}/{settings.project_name}.bsp",\
1680 F"{settings.subdir}/maps/{settings.project_name}.bsp")]
1681 }]
1682
1683 static.USER_EXIT=False
1684 static.TIMER=wm.event_timer_add(0.1,window=context.window)
1685 wm.modal_handler_add(_)
1686
1687 cxr_jobs_update_graph( static.JOBINFO )
1688 scene_redraw()
1689 return {'RUNNING_MODAL'}
1690
1691 print("Chain exiting...")
1692 static.USER_EXIT=True
1693 return {'RUNNING_MODAL'}
1694
1695 class CXR_RESET_HASHES(bpy.types.Operator):
1696 bl_idname="convexer.hash_reset"
1697 bl_label="Reset asset hashes"
1698
1699 def execute(_,context):
1700 for c in bpy.data.collections:
1701 c.cxr_data.last_hash = F"<RESET>{time.time()}"
1702 c.cxr_data.asset_id=0
1703
1704 for t in bpy.data.images:
1705 t.cxr_data.last_hash = F"<RESET>{time.time()}"
1706 t.cxr_data.asset_id=0
1707
1708 return {'FINISHED'}
1709
1710 # Convexer panels
1711 # ------------------------------------------------------------------------------
1712
1713 # Helper buttons for 3d toolbox view
1714 #
1715 class CXR_VIEW3D( bpy.types.Panel ):
1716 bl_idname = "VIEW3D_PT_convexer"
1717 bl_label = "Convexer"
1718 bl_space_type = 'VIEW_3D'
1719 bl_region_type = 'UI'
1720 bl_category = "Convexer"
1721
1722 @classmethod
1723 def poll(cls, context):
1724 return (context.object is not None)
1725
1726 def draw(_, context):
1727 layout = _.layout
1728 row = layout.row()
1729 row.scale_y = 2
1730 row.operator("convexer.preview")
1731
1732 if CXR_PREVIEW_OPERATOR.LASTERR != None:
1733 box = layout.box()
1734 box.label(text=CXR_PREVIEW_OPERATOR.LASTERR, icon='ERROR')
1735
1736 # Main scene properties interface, where all the settings go
1737 #
1738 class CXR_INTERFACE(bpy.types.Panel):
1739 bl_label="Convexer"
1740 bl_idname="SCENE_PT_convexer"
1741 bl_space_type='PROPERTIES'
1742 bl_region_type='WINDOW'
1743 bl_context="scene"
1744
1745 def draw(_,context):
1746 _.layout.operator("convexer.reload")
1747 _.layout.operator("convexer.dev_test")
1748 _.layout.operator("convexer.preview")
1749 _.layout.operator("convexer.hash_reset")
1750
1751 settings = context.scene.cxr_data
1752
1753 _.layout.prop(settings, "debug")
1754 _.layout.prop(settings, "scale_factor")
1755 _.layout.prop(settings, "lightmap_scale")
1756 _.layout.prop(settings, "light_scale" )
1757 _.layout.prop(settings, "image_quality" )
1758
1759 box = _.layout.box()
1760
1761 box.prop(settings, "project_name")
1762 box.prop(settings, "subdir")
1763
1764 box = _.layout.box()
1765 box.operator("convexer.detect_compilers")
1766 box.prop(settings, "exe_studiomdl")
1767 box.prop(settings, "exe_vbsp")
1768 box.prop(settings, "exe_vvis")
1769 box.prop(settings, "exe_vrad")
1770
1771 text = "Compile" if CXR_COMPILER_CHAIN.TIMER == None else "Cancel"
1772 row = box.row()
1773 row.scale_y = 3
1774 row.operator("convexer.chain", text=text)
1775
1776
1777 class CXR_MATERIAL_PANEL(bpy.types.Panel):
1778 bl_label="VMT Properties"
1779 bl_idname="SCENE_PT_convexer_vmt"
1780 bl_space_type='PROPERTIES'
1781 bl_region_type='WINDOW'
1782 bl_context="material"
1783
1784 def draw(_,context):
1785 active_object = bpy.context.active_object
1786 if active_object == None: return
1787
1788 active_material = active_object.active_material
1789 if active_material == None: return
1790
1791 properties = active_material.cxr_data
1792 info = material_info( active_material )
1793
1794 _.layout.label(text=F"{info['name']} @{info['res'][0]}x{info['res'][1]}")
1795 _.layout.prop( properties, "shader" )
1796
1797 for xk in info:
1798 _.layout.label(text=F"{xk}:={info[xk]}")
1799
1800 def _mtex( name, img, uiParent ):
1801 nonlocal properties
1802
1803 box = uiParent.box()
1804 box.label( text=F'{name} "{img.filepath}"' )
1805 def _p2( x ):
1806 if ((x & (x - 1)) == 0):
1807 return x
1808 closest = 0
1809 closest_diff = 10000000
1810 for i in range(16):
1811 dist = abs((1 << i)-x)
1812 if dist < closest_diff:
1813 closest_diff = dist
1814 closest = i
1815 real = 1 << closest
1816 if x > real:
1817 return 1 << (closest+1)
1818 if x < real:
1819 return 1 << (closest-1)
1820 return x
1821
1822 if img is not None:
1823 row = box.row()
1824 row.prop( img.cxr_data, "export_res" )
1825 row.prop( img.cxr_data, "fmt" )
1826
1827 row = box.row()
1828 row.prop( img.cxr_data, "mipmap" )
1829 row.prop( img.cxr_data, "lod" )
1830 row.prop( img.cxr_data, "clamp" )
1831
1832 img.cxr_data.export_res[0] = _p2( img.cxr_data.export_res[0] )
1833 img.cxr_data.export_res[1] = _p2( img.cxr_data.export_res[1] )
1834
1835 def _mview( layer, uiParent ):
1836 nonlocal properties
1837
1838 for decl in layer:
1839 if isinstance(layer[decl],dict): # $property definition
1840 pdef = layer[decl]
1841 ptype = pdef['type']
1842
1843 thisnode = uiParent
1844 expandview = True
1845 drawthis = True
1846
1847 if ('shaders' in pdef) and \
1848 (properties.shader not in pdef['shaders']):
1849 continue
1850
1851 if ptype == 'intrinsic':
1852 if decl not in info:
1853 drawthis = False
1854
1855 if drawthis:
1856 for ch in pdef:
1857 if isinstance(pdef[ch],dict):
1858 if ptype == 'ui' or ptype == 'intrinsic':
1859 pass
1860 elif getattr(properties,decl) == pdef['default']:
1861 expandview = False
1862
1863 thisnode = uiParent.box()
1864 break
1865
1866 if ptype == 'ui':
1867 thisnode.label( text=decl )
1868 elif ptype == 'intrinsic':
1869 if isinstance(info[decl], bpy.types.Image):
1870 _mtex( decl, info[decl], thisnode )
1871 else:
1872 # hidden intrinsic value.
1873 # Means its a float array or something not an image
1874 thisnode.label(text=F"-- hidden intrinsic '{decl}' --")
1875 else:
1876 thisnode.prop(properties,decl)
1877 if expandview: _mview(pdef,thisnode)
1878
1879 _mview( cxr_shader_params, _.layout )
1880
1881 def cxr_entity_changeclass(_,context):
1882 active_object = context.active_object
1883
1884 # Create ID properties
1885 entdef = None
1886 classname = cxr_custom_class(active_object)
1887
1888 if classname in cxr_entities:
1889 entdef = cxr_entities[classname]
1890
1891 kvs = entdef['keyvalues']
1892 if callable(kvs): kvs = kvs(active_object)
1893
1894 for k in kvs:
1895 kv = kvs[k]
1896 key = F'cxrkv_{k}'
1897
1898 if callable(kv) or not isinstance(kv,dict): continue
1899
1900 if key not in active_object:
1901 active_object[key] = kv['default']
1902 id_prop = active_object.id_properties_ui(key)
1903 id_prop.update(default=kv['default'])
1904
1905 class CXR_ENTITY_PANEL(bpy.types.Panel):
1906 bl_label="Entity Config"
1907 bl_idname="SCENE_PT_convexer_entity"
1908 bl_space_type='PROPERTIES'
1909 bl_region_type='WINDOW'
1910 bl_context="object"
1911
1912 def draw(_,context):
1913 active_object = bpy.context.active_object
1914
1915 if active_object == None: return
1916
1917 default_context = {
1918 "scale": bpy.context.scene.cxr_data.scale_factor,
1919 "offset": (0,0,0)
1920 }
1921
1922 ecn = cxr_intrinsic_classname( active_object )
1923 classname = cxr_custom_class( active_object )
1924
1925 if ecn == None:
1926 if active_object.type == 'MESH':
1927 _.layout.prop( active_object.cxr_data, 'brushclass' )
1928 else: _.layout.prop( active_object.cxr_data, 'classname' )
1929
1930 if classname == 'NONE':
1931 return
1932 else:
1933 _.layout.label(text=F"<implementation defined ({ecn})>")
1934 _.layout.enabled=False
1935 classname = ecn
1936
1937 kvs = cxr_entity_keyvalues( {
1938 "object": active_object,
1939 "transform": default_context,
1940 "classname": classname
1941 })
1942
1943 if kvs != None:
1944 for kv in kvs:
1945 if kv[1]:
1946 _.layout.prop( active_object, F'["cxrkv_{kv[0]}"]', text=kv[0])
1947 else:
1948 row = _.layout.row()
1949 row.enabled = False
1950 row.label( text=F'{kv[0]}: {repr(kv[2])}' )
1951 else:
1952 _.layout.label( text=F"ERROR: NO CLASS DEFINITION" )
1953
1954 class CXR_LIGHT_PANEL(bpy.types.Panel):
1955 bl_label = "Source Settings"
1956 bl_idname = "LIGHT_PT_cxr"
1957 bl_space_type = 'PROPERTIES'
1958 bl_region_type = 'WINDOW'
1959 bl_context = "data"
1960
1961 def draw(self, context):
1962 layout = self.layout
1963 scene = context.scene
1964
1965 active_object = bpy.context.active_object
1966 if active_object == None: return
1967
1968 if active_object.type == 'LIGHT' or \
1969 active_object.type == 'LIGHT_PROBE':
1970
1971 properties = active_object.data.cxr_data
1972
1973 if active_object.type == 'LIGHT':
1974 layout.prop( properties, "realtime" )
1975 elif active_object.type == 'LIGHT_PROBE':
1976 layout.prop( properties, "size" )
1977
1978 # Settings groups
1979 # ------------------------------------------------------------------------------
1980
1981 class CXR_IMAGE_SETTINGS(bpy.types.PropertyGroup):
1982 export_res: bpy.props.IntVectorProperty(
1983 name="",
1984 description="Texture Export Resolution",
1985 default=(512,512),
1986 min=1,
1987 max=4096,
1988 size=2)
1989
1990 fmt: bpy.props.EnumProperty(
1991 name="Format",
1992 items = [
1993 ('DXT1', "DXT1", "BC1 compressed", '', 0),
1994 ('DXT5', "DXT5", "BC3 compressed", '', 1),
1995 ('RGB', "RGB", "Uncompressed", '', 2),
1996 ('RGBA', "RGBA", "Uncompressed (with alpha)", '', 3)
1997 ],
1998 description="Image format",
1999 default=0)
2000
2001 last_hash: bpy.props.StringProperty( name="" )
2002 asset_id: bpy.props.IntProperty(name="intl_assetid",default=0)
2003
2004 mipmap: bpy.props.BoolProperty(name="MIP",default=True)
2005 lod: bpy.props.BoolProperty(name="LOD",default=True)
2006 clamp: bpy.props.BoolProperty(name="CLAMP",default=False)
2007 flags: bpy.props.IntProperty(name="flags",default=0)
2008
2009 class CXR_LIGHT_SETTINGS(bpy.types.PropertyGroup):
2010 realtime: bpy.props.BoolProperty(name="Realtime Light", default=True)
2011
2012 class CXR_CUBEMAP_SETTINGS(bpy.types.PropertyGroup):
2013 size: bpy.props.EnumProperty(
2014 name="Resolution",
2015 items = [
2016 ('1',"1x1",'','',0),
2017 ('2',"2x2",'','',1),
2018 ('3',"4x4",'','',2),
2019 ('4',"8x8",'','',3),
2020 ('5',"16x16",'','',4),
2021 ('6',"32x32",'','',5),
2022 ('7',"64x64",'','',6),
2023 ('8',"128x128",'','',7),
2024 ('9',"256x256",'','',8)
2025 ],
2026 description="Texture resolution",
2027 default=7)
2028
2029 class CXR_ENTITY_SETTINGS(bpy.types.PropertyGroup):
2030 entity: bpy.props.BoolProperty(name="")
2031
2032 enum_pointents = [('NONE',"None","")]
2033 enum_brushents = [('NONE',"None","")]
2034
2035 for classname in cxr_entities:
2036 entdef = cxr_entities[classname]
2037 if 'allow' in entdef:
2038 itm = [(classname, classname, "")]
2039 if 'EMPTY' in entdef['allow']: enum_pointents += itm
2040 else: enum_brushents += itm
2041
2042 classname: bpy.props.EnumProperty(items=enum_pointents, name="Class", \
2043 update=cxr_entity_changeclass, default='NONE' )
2044
2045 brushclass: bpy.props.EnumProperty(items=enum_brushents, name="Class", \
2046 update=cxr_entity_changeclass, default='NONE' )
2047
2048 class CXR_MODEL_SETTINGS(bpy.types.PropertyGroup):
2049 last_hash: bpy.props.StringProperty( name="" )
2050 asset_id: bpy.props.IntProperty(name="vmf_settings",default=0)
2051
2052 class CXR_SCENE_SETTINGS(bpy.types.PropertyGroup):
2053 project_name: bpy.props.StringProperty( name="Project Name" )
2054 subdir: bpy.props.StringProperty( name="Subdirectory" )
2055
2056 exe_studiomdl: bpy.props.StringProperty( name="studiomdl" )
2057 exe_vbsp: bpy.props.StringProperty( name="vbsp" )
2058 opt_vbsp: bpy.props.StringProperty( name="args" )
2059 exe_vvis: bpy.props.StringProperty( name="vvis" )
2060 opt_vvis: bpy.props.StringProperty( name="args" )
2061 exe_vrad: bpy.props.StringProperty( name="vrad" )
2062 opt_vrad: bpy.props.StringProperty( name="args" )
2063
2064 debug: bpy.props.BoolProperty(name="Debug",default=False)
2065 scale_factor: bpy.props.FloatProperty( name="VMF Scale factor", \
2066 default=32.0,min=1.0)
2067 skybox_scale_factor: bpy.props.FloatProperty( name="Sky Scale factor", \
2068 default=1.0,min=0.01)
2069
2070 skybox_offset: bpy.props.FloatProperty(name="Sky offset",default=-4096.0)
2071 light_scale: bpy.props.FloatProperty(name="Light Scale",default=1.0/5.0)
2072 include_names: bpy.props.BoolProperty(name="Append original file names",\
2073 default=True)
2074 lightmap_scale: bpy.props.IntProperty(name="Global Lightmap Scale",\
2075 default=12)
2076 image_quality: bpy.props.IntProperty(name="Texture Quality (0-18)",\
2077 default=8, min=0, max=18 )
2078
2079
2080 classes = [ CXR_RELOAD, CXR_DEV_OPERATOR, CXR_INTERFACE, \
2081 CXR_MATERIAL_PANEL, CXR_IMAGE_SETTINGS,\
2082 CXR_MODEL_SETTINGS, CXR_ENTITY_SETTINGS, CXR_CUBEMAP_SETTINGS,\
2083 CXR_LIGHT_SETTINGS, CXR_SCENE_SETTINGS, CXR_DETECT_COMPILERS,\
2084 CXR_ENTITY_PANEL, CXR_LIGHT_PANEL, CXR_PREVIEW_OPERATOR,\
2085 CXR_VIEW3D, CXR_COMPILER_CHAIN, CXR_RESET_HASHES ]
2086
2087 vmt_param_dynamic_class = None
2088
2089 def register():
2090 global cxr_view_draw_handler, vmt_param_dynamic_class, cxr_ui_handler
2091
2092 for c in classes:
2093 bpy.utils.register_class(c)
2094
2095 # Build dynamic VMT properties class defined by cxr_shader_params
2096 annotations_dict = {}
2097
2098 def _dvmt_propogate(layer):
2099 nonlocal annotations_dict
2100
2101 for decl in layer:
2102 if isinstance(layer[decl],dict): # $property definition
2103 pdef = layer[decl]
2104
2105 prop = None
2106 if pdef['type'] == 'bool':
2107 prop = bpy.props.BoolProperty(\
2108 name = pdef['name'],\
2109 default = pdef['default'])
2110
2111 elif pdef['type'] == 'float':
2112 prop = bpy.props.FloatProperty(\
2113 name = pdef['name'],\
2114 default = pdef['default'])
2115
2116 elif pdef['type'] == 'vector':
2117 if 'subtype' in pdef:
2118 prop = bpy.props.FloatVectorProperty(\
2119 name = pdef['name'],\
2120 subtype = pdef['subtype'],\
2121 default = pdef['default'],\
2122 size = len(pdef['default']))
2123 else:
2124 prop = bpy.props.FloatVectorProperty(\
2125 name = pdef['name'],\
2126 default = pdef['default'],\
2127 size = len(pdef['default']))
2128
2129 elif pdef['type'] == 'string':
2130 prop = bpy.props.StringProperty(\
2131 name = pdef['name'],\
2132 default = pdef['default'])
2133
2134 elif pdef['type'] == 'enum':
2135 prop = bpy.props.EnumProperty(\
2136 name = pdef['name'],\
2137 items = pdef['items'],\
2138 default = pdef['default'])
2139
2140 if prop != None:
2141 annotations_dict[decl] = prop
2142
2143 # Recurse into sub-definitions
2144 _dvmt_propogate(pdef)
2145
2146 annotations_dict["shader"] = bpy.props.EnumProperty(\
2147 name = "Shader",\
2148 items = [( _,\
2149 cxr_shaders[_]["name"],\
2150 '') for _ in cxr_shaders],\
2151 default = next(iter(cxr_shaders)))
2152
2153 annotations_dict["asset_id"] = bpy.props.IntProperty(name="intl_assetid",\
2154 default=0)
2155
2156 _dvmt_propogate( cxr_shader_params )
2157 vmt_param_dynamic_class = type(
2158 "CXR_VMT_DYNAMIC",
2159 (bpy.types.PropertyGroup,),{
2160 "__annotations__": annotations_dict
2161 },
2162 )
2163
2164 bpy.utils.register_class( vmt_param_dynamic_class )
2165
2166 # Pointer types
2167 bpy.types.Material.cxr_data = \
2168 bpy.props.PointerProperty(type=vmt_param_dynamic_class)
2169 bpy.types.Image.cxr_data = \
2170 bpy.props.PointerProperty(type=CXR_IMAGE_SETTINGS)
2171 bpy.types.Object.cxr_data = \
2172 bpy.props.PointerProperty(type=CXR_ENTITY_SETTINGS)
2173 bpy.types.Collection.cxr_data = \
2174 bpy.props.PointerProperty(type=CXR_MODEL_SETTINGS)
2175 bpy.types.Light.cxr_data = \
2176 bpy.props.PointerProperty(type=CXR_LIGHT_SETTINGS)
2177 bpy.types.LightProbe.cxr_data = \
2178 bpy.props.PointerProperty(type=CXR_CUBEMAP_SETTINGS)
2179 bpy.types.Scene.cxr_data = \
2180 bpy.props.PointerProperty(type=CXR_SCENE_SETTINGS)
2181
2182 # CXR Scene settings
2183
2184 # GPU / callbacks
2185 cxr_view_draw_handler = bpy.types.SpaceView3D.draw_handler_add(\
2186 cxr_draw,(),'WINDOW','POST_VIEW')
2187
2188 cxr_ui_handler = bpy.types.SpaceView3D.draw_handler_add(\
2189 cxr_ui,(None,None),'WINDOW','POST_PIXEL')
2190
2191 bpy.app.handlers.load_post.append(cxr_on_load)
2192 bpy.app.handlers.depsgraph_update_post.append(cxr_dgraph_update)
2193
2194 def unregister():
2195 global cxr_view_draw_handler, vmt_param_dynamic_class, cxr_ui_handler
2196
2197 bpy.utils.unregister_class( vmt_param_dynamic_class )
2198 for c in classes:
2199 bpy.utils.unregister_class(c)
2200
2201 bpy.app.handlers.depsgraph_update_post.remove(cxr_dgraph_update)
2202 bpy.app.handlers.load_post.remove(cxr_on_load)
2203
2204 bpy.types.SpaceView3D.draw_handler_remove(cxr_view_draw_handler,'WINDOW')
2205 bpy.types.SpaceView3D.draw_handler_remove(cxr_ui_handler,'WINDOW')