-
Notifications
You must be signed in to change notification settings - Fork 10
/
cellblender_molecules.py
2483 lines (2038 loc) · 104 KB
/
cellblender_molecules.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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 #####
# <pep8 compliant>
"""
This file contains the classes for CellBlender's Molecules.
Molecules (or more properly "Molecule Species") contain two types of data:
MCell data - Name, diffusion constant, 2D/3D, etc.
Blender data - Name, glyph, size, color, position mesh
Note that some items (the name, for example) is considered as both
MCell data and Blender data.
Molecules (or parts of molecules) can be created from:
User interface (clicking buttons, and setting values)
Data Model (loading from a .blend file or an external data model file)
CellBlender API (currently the test suite, but possibly more general)
Reading a Visualization file without any molecules defined (CellBlender 0)
One of the key goals of the molecules module is to provide the proper
class structures and methods to support those different creation modes.
In general, creating the MCell data for a molecule (in CellBlender) will
also immediately create the Blender data (glyph, empty position mesh,...).
This allows the "Blender data" (glyph, size, color, mesh) to be created,
seen, and modified without running any simulations. Similarly, reading
Visualization data should probably create molecules as needed.
This leads to a "create as needed" mechanism for both MCell data and
Blender data. The "as needed" part will be based on the molecule name
as the "key". If that "key" exists in any context, then that data will
be used or updated. If that "key" does not exist in any context, then
new data will be created for that key.
"""
# blender imports
import bpy
from bpy.props import BoolProperty, CollectionProperty, EnumProperty, \
FloatProperty, FloatVectorProperty, IntProperty, \
IntVectorProperty, PointerProperty, StringProperty
from bpy.app.handlers import persistent
# These 3 imports are for the text overlays
import blf
from mathutils import Matrix, Vector
from bpy_extras.view3d_utils import location_3d_to_region_2d
import math
import mathutils
# python imports
import re
import os
import random
import cellblender
from . import data_model
# from . import cellblender_parameters
from . import parameter_system
from . import cellblender_mol_viz
from . import cellblender_utils
from . import cellblender_preferences
from . import cellblender_glyphs
class MCELL_MolLabelProps(bpy.types.PropertyGroup):
enabled: BoolProperty(default=False)
loc_x: IntProperty(name='LocX', default=0)
loc_y: IntProperty(name='LocY', default=0)
show_mol_labels: BoolProperty(name="", default=True)
print ( "Mols imported for Tom commented with " + __name__ )
def set_molecule_glyph ( context, glyph_name ):
mcell = context.scene.mcell
meshes = bpy.data.meshes
mcell.molecule_glyphs.status = ""
select_objs = context.selected_objects
if (len(select_objs) != 1):
mcell.molecule_glyphs.status = "Select One Molecule"
return
if (select_objs[0].type != 'MESH'):
mcell.molecule_glyphs.status = "Selected Object Not a Molecule"
return
mol_obj = select_objs[0]
mol_shape_name = mol_obj.name
# There may be objects in the scene with the same name as the glyphs in
# the glyph library, so we need to deal with this possibility
new_glyph_name = glyph_name
if glyph_name in meshes:
# pattern: glyph name, period, numbers. (example match: "Cube.001")
pattern = re.compile(r'%s(\.\d+)' % glyph_name)
competing_names = [m.name for m in meshes if pattern.match(m.name)]
# example: given this: ["Cube.001", "Cube.3"], make this: [1, 3]
trailing_nums = [int(n.split('.')[1]) for n in competing_names]
# remove dups & sort... better way than list->set->list?
trailing_nums = list(set(trailing_nums))
trailing_nums.sort()
i = 0
gap = False
for i in range(0, len(trailing_nums)):
if trailing_nums[i] != i+1:
gap = True
break
if not gap and trailing_nums:
i+=1
new_glyph_name = "%s.%03d" % (glyph_name, i + 1)
if (bpy.app.version[0] > 2) or ( (bpy.app.version[0]==2) and (bpy.app.version[1] > 71) ):
bpy.ops.wm.link(
directory=mcell.molecule_glyphs.glyph_lib,
files=[{"name": glyph_name}], link=False, autoselect=False)
else:
bpy.ops.wm.link_append(
directory=mcell.molecule_glyphs.glyph_lib,
files=[{"name": glyph_name}], link=False, autoselect=False)
mol_mat = mol_obj.material_slots[0].material
new_mol_mesh = meshes[new_glyph_name]
mol_obj.data = new_mol_mesh
mol_obj.hide_select = True
meshes.remove(meshes[mol_shape_name])
new_mol_mesh.name = mol_shape_name
new_mol_mesh.materials.append(mol_mat)
"""
class MCellMoleculeGlyphsPropertyGroup(bpy.types.PropertyGroup):
glyph_lib = os.path.join(
os.path.dirname(__file__), "glyph_library.blend/Mesh/")
glyph_enum = [
('Cone', "Cone", ""),
('Cube', "Cube", ""),
('Cylinder', "Cylinder", ""),
('Icosahedron', "Icosahedron", ""),
('Octahedron', "Octahedron", ""),
('Receptor', "Receptor", ""),
('Sphere_1', "Sphere_1", ""),
('Sphere_2', "Sphere_2", ""),
('Torus', "Torus", "")]
glyph: EnumProperty(items=glyph_enum, name="Molecule Shapes")
show_glyph: BoolProperty(name="Show Glyphs",description="Show Glyphs ... can cause slowness!!",default=True)
status: StringProperty(name="Status")
def remove_properties ( self, context ):
print ( "Removing all Molecule Glyph Properties... no collections to remove." )
"""
# Molecule Operators:
class MCELL_OT_molecule_add(bpy.types.Operator):
bl_idname = "mcell.molecule_add"
bl_label = "Add Molecule"
bl_description = "Add a new molecule type to an MCell model"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.mcell.molecules.add_molecule(context)
return {'FINISHED'}
class MCELL_OT_molecule_duplicate(bpy.types.Operator):
bl_idname = "mcell.molecule_duplicate"
bl_label = "Duplicate Molecule"
bl_description = "Duplicate the selected molecule type in the MCell model"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.mcell.molecules.duplicate_molecule(context)
return {'FINISHED'}
class MCELL_OT_molecule_remove(bpy.types.Operator):
bl_idname = "mcell.molecule_remove"
bl_label = "Remove Molecule"
bl_description = "Remove selected molecule type from an MCell model"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.mcell.molecules.remove_active_molecule(context)
self.report({'INFO'}, "Deleted Molecule")
return {'FINISHED'}
class MCELL_OT_mol_comp_add(bpy.types.Operator):
bl_idname = "mcell.mol_comp_add"
bl_label = "Add Component"
bl_description = "Add a new component to molecule"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.mcell.molecules.add_component(context)
self.report({'INFO'}, "Added Component")
return {'FINISHED'}
class MCELL_OT_mol_comp_remove(bpy.types.Operator):
bl_idname = "mcell.mol_comp_remove"
bl_label = "Remove Component"
bl_description = "Remove selected component from molecule"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.mcell.molecules.remove_active_component(context)
self.report({'INFO'}, "Deleted Component")
return {'FINISHED'}
class MCELL_OT_set_molecule_glyph(bpy.types.Operator):
bl_idname = "mcell.set_molecule_glyph"
bl_label = "Set Molecule Glyph"
bl_description = "Set molecule glyph to desired shape in glyph library"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
mcell = context.scene.mcell
mcell.molecule_glyphs.status = ""
select_objs = context.selected_objects
if (len(select_objs) != 1):
mcell.molecule_glyphs.status = "Select One Molecule"
return {'FINISHED'}
if (select_objs[0].type != 'MESH'):
mcell.molecule_glyphs.status = "Selected Object Not a Molecule"
return {'FINISHED'}
glyph_name = mcell.molecule_glyphs.glyph
set_molecule_glyph ( context, glyph_name )
return {'FINISHED'}
class MCELL_OT_mol_comp_stick(bpy.types.Operator):
bl_idname = "mcell.mol_comp_stick"
bl_label = "Show Stick Molecule"
bl_description = "Show a Stick Molecule"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
meshes = bpy.data.meshes
mats = bpy.data.materials
objs = bpy.data.objects
scn = bpy.context.scene
scn_objs = bpy.context.scene.collection.children[0].objects
stick_name = "mol_comp_stick_mesh"
shape_name = stick_name + "_shape"
mols = context.scene.mcell.molecules
this_mol = mols.molecule_list[mols.active_mol_index]
num_comps = len(this_mol.component_list)
comp_dist = this_mol.component_distance
# Delete the old object and mesh
if shape_name in objs:
scn_objs.unlink ( objs[shape_name] )
objs.remove ( objs[shape_name] )
if shape_name in meshes:
meshes.remove ( meshes[shape_name] )
shape_vertices = []
shape_lines = []
shape_faces = []
# Start with the origin molecule (for radial lines)
shape_vertices.append ( mathutils.Vector((0.0, 0.0, 0.0)) )
for index in range(num_comps):
loc = [0.0, 0.0, 0.0]
print ( "Mol geometry = " + this_mol.geom_type )
if this_mol.geom_type == '2DAuto':
loc = get_2D_auto_point ( num_comps, comp_dist, index )
elif this_mol.geom_type == '3DAuto':
loc = get_3D_auto_point ( num_comps, comp_dist, index )
elif this_mol.geom_type in ['XYZ','XYZRef','XYZA','XYZVA']:
loc[0] = this_mol.component_list[index].loc_x.get_value();
loc[1] = this_mol.component_list[index].loc_y.get_value();
loc[2] = this_mol.component_list[index].loc_z.get_value();
x = loc[0]
y = loc[1]
z = loc[2]
shape_vertices.append ( mathutils.Vector((x, y, z)) )
shape_lines.append ( [0,index+1] )
print ( " making a stick for " + str(x) + ", " + str(y) + ", " + str(z) )
# Create and build the new mesh
stick_shape_mesh = bpy.data.meshes.new ( shape_name )
stick_shape_mesh.from_pydata ( shape_vertices, shape_lines, shape_faces )
stick_shape_mesh.update()
# Create the new shape object from the mesh
stick_shape_obj = bpy.data.objects.new ( shape_name, stick_shape_mesh )
# Be sure the new shape is at the origin
stick_shape_obj.location.x = 0
stick_shape_obj.location.y = 0
stick_shape_obj.location.z = 0
# Allow the shape to be selected so it can be manipulated like any other object.
stick_shape_obj.hide_select = False
# Add the shape to the scene
scn_objs.link ( stick_shape_obj )
# Select to highlight it
scn_objs[shape_name].select_set(True)
self.report({'INFO'}, "Built a Stick Molecule")
return {'FINISHED'}
class MCELL_OT_mol_comp_nostick(bpy.types.Operator):
bl_idname = "mcell.mol_comp_nostick"
bl_label = "Remove Stick Molecule"
bl_description = "Remove the Stick Molecule"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
meshes = bpy.data.meshes
mats = bpy.data.materials
objs = bpy.data.objects
scn = bpy.context.scene
scn_objs = bpy.context.scene.collection.children[0].objects
stick_name = "mol_comp_stick_mesh"
shape_name = stick_name + "_shape"
# Delete the old object and mesh
if shape_name in objs:
scn_objs.unlink ( objs[shape_name] )
objs.remove ( objs[shape_name] )
if shape_name in meshes:
meshes.remove ( meshes[shape_name] )
self.report({'INFO'}, "Deleted Stick Molecule")
return {'FINISHED'}
class MCELL_OT_mol_auto_key(bpy.types.Operator):
bl_idname = "mcell.mol_auto_key"
bl_label = "Auto Key"
bl_description = "Automatically Key the Components"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
self.report({'INFO'}, "Auto keyed")
print ( "Auto keying components to first key" )
mols = context.scene.mcell.molecules
this_mol = mols.molecule_list[mols.active_mol_index]
cl = this_mol.component_list
# Create a list of ONLY the actual keys
key_only_list = [ i for i in range(len(cl)) if cl[i].is_key == True ]
if len(key_only_list) > 0:
comp_only_list = [ i for i in range(len(cl)) if cl[i].is_key == False ]
for i in comp_only_list:
if cl[i].rot_index < 0:
cl[i].rot_index = key_only_list[0]
return {'FINISHED'}
# Callbacks for all Property updates appear to require global (non-member) functions.
# This is circumvented by simply calling the associated member function passed as self:
""" Old Callbacks called corresponding from class ... new version should do this as well """
def check_callback(self, context):
self.check_callback(context)
return
def display_callback(self, context):
self.display_callback(context)
return
def name_change_callback(self, context):
# print ( "name_change_callback called with self = " + str(self) )
# print ( " old = " + self.old_name + " => new = " + self.name )
old_mol_name = "mol_" + self.old_name
new_mol_name = "mol_" + self.name
if old_mol_name + '_mat' in bpy.data.materials:
bpy.data.materials[old_mol_name + '_mat'].name = new_mol_name + '_mat'
if old_mol_name + '_shape' in bpy.data.meshes:
bpy.data.meshes[old_mol_name + '_shape'].name = new_mol_name + '_shape'
if old_mol_name + '_shape' in bpy.data.objects:
bpy.data.objects[old_mol_name + '_shape'].name = new_mol_name + '_shape'
if old_mol_name + '_pos' in bpy.data.meshes:
bpy.data.meshes[old_mol_name + '_pos'].name = new_mol_name + '_pos'
if old_mol_name in bpy.data.objects:
bpy.data.objects[old_mol_name].name = new_mol_name
self.old_name = self.name
self.check_callback(context)
return
def glyph_visibility_callback(self, context):
# print ( "Glyph vis change callback for molecule " + self.name )
ms = context.scene.mcell
show_name = "mol_" + self.name
show_shape_name = show_name + "_shape"
objs = context.scene.collection.children[0].objects
objs[show_name].hide_viewport = not self.glyph_visibility
objs[show_shape_name].hide_viewport = not self.glyph_visibility
return
def glyph_show_only_callback(self, context):
# print ( "Glyph show only callback for molecule " + self.name )
# Note the check before set to keep from infinite recursion in properties!!
if self.glyph_show_only != False:
self.glyph_show_only = False
ms = context.scene.mcell.molecules
ml = ms.molecule_list
show_only_name = "mol_" + self.name
show_only_shape_name = show_only_name + "_shape"
show_only_items = [show_only_name, show_only_shape_name]
# print ( "Only showing " + str(show_only_items) )
# Note the check before set to keep from infinite recursion in properties!!
for o in context.scene.collection.children[0].objects:
if o.name.startswith("mol_"):
if o.name in show_only_items:
if o.hide_viewport != False:
o.hide_viewport = False
else:
if o.hide_viewport != True:
o.hide_viewport = True
for o in ml:
if o.name == self.name:
if o.glyph_visibility != True:
o.glyph_visibility = True
else:
if o.glyph_visibility != False:
o.glyph_visibility = False
if self.name in ms.molecule_list:
# Select this item in the list as well
ms.active_mol_index = ms.molecule_list.find ( self.name )
return
def shape_change_callback(self, context):
# print ( "Shape change callback for molecule " + self.name )
self.create_mol_data () # ( context )
return
class MCELL_OT_mol_shade_flat(bpy.types.Operator):
bl_idname = "mcell.mol_shade_flat"
bl_label = "Shade Flat"
bl_description = "Apply flat shading to this molecule"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
mols = context.scene.mcell.molecules
if len(mols.molecule_list) > 0:
mol = mols.molecule_list[mols.active_mol_index]
if mol:
shape_name = 'mol_' + mol.name + '_shape'
obj = bpy.data.objects[shape_name]
cellblender_utils.preserve_selection_use_operator(
bpy.ops.object.shade_flat, obj)
return {'FINISHED'}
class MCELL_OT_mol_shade_smooth(bpy.types.Operator):
bl_idname = "mcell.mol_shade_smooth"
bl_label = "Shade Smooth"
bl_description = "Apply smooth shading to this molecule"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
mols = context.scene.mcell.molecules
if len(mols.molecule_list) > 0:
mol = mols.molecule_list[mols.active_mol_index]
if mol:
shape_name = 'mol_' + mol.name + '_shape'
obj = bpy.data.objects[shape_name]
cellblender_utils.preserve_selection_use_operator(
bpy.ops.object.shade_smooth, obj)
return {'FINISHED'}
def draw_labels_callback(self, context):
disp_mol_labels = context.window_manager.display_mol_labels
if disp_mol_labels.show_mol_labels:
if context.window_manager.display_mol_labels.enabled:
if context == None:
print ( "draw_labels_callback: context is None" )
return
if context.region == None:
print ( "draw_labels_callback: context.region is None" )
return
if context.space_data == None:
print ( "draw_labels_callback: context.space_data is None" )
return
if context.space_data.region_3d == None:
print ( "draw_labels_callback: context.space_data.region_3d is None" )
return
mv = context.scene.mcell.mol_viz
if 'mol_labels_index' in mv:
ml_obj_labels_index = mv['mol_labels_index']
ml_obj_labels_x = mv['mol_labels_x']
ml_obj_labels_y = mv['mol_labels_y']
ml_obj_labels_z = mv['mol_labels_z']
ml_obj_labels_bngl = mv['mol_labels_bngl']
for i in range(len(ml_obj_labels_index)):
t = ml_obj_labels_index[i]
x = ml_obj_labels_x[i]
y = ml_obj_labels_y[i]
z = ml_obj_labels_z[i]
if ml_obj_labels_bngl[t] != None:
screen_coords = location_3d_to_region_2d (context.region, context.space_data.region_3d, [x,y,z])
# Note that screen_coords can be None when an object is too close in perspective mode
if screen_coords != None:
loc_x, loc_y = screen_coords
blf.position(0, loc_x, loc_y, 0)
blf.draw(0, ml_obj_labels_bngl[t])
class MCELL_OT_mol_show_text(bpy.types.Operator):
"""Display mol labels"""
bl_idname = "mcell.mol_show_text"
bl_label = "Show Text"
bl_description = "Display a text representation of the molecule (name or BNGL string)"
bl_options = {'REGISTER'}
"""
def execute(self, context):
mols = context.scene.mcell.molecules
if len(mols.molecule_list) > 0:
mol = mols.molecule_list[mols.active_mol_index]
if mol:
shape_name = 'mol_' + mol.name + '_shape'
obj = bpy.data.objects[shape_name]
pass
return {'FINISHED'}
"""
_handle = None
def modal(self, context, event):
context.area.tag_redraw()
if not context.window_manager.display_mol_labels.enabled:
# MCELL_OT_mol_show_text.handle_remove(context)
return {'CANCELLED'}
return {'PASS_THROUGH'}
@staticmethod
def handle_add(self, context):
MCELL_OT_mol_show_text._handle = bpy.types.SpaceView3D.draw_handler_add(
draw_labels_callback,
(self, context),
'WINDOW', 'POST_PIXEL')
@staticmethod
def handle_remove(context):
_handle = MCELL_OT_mol_show_text._handle
if _handle != None:
bpy.types.SpaceView3D.draw_handler_remove(_handle, 'WINDOW')
MCELL_OT_mol_show_text._handle = None
def cancel(self, context):
if context.window_manager.display_mol_labels.enabled:
MCELL_OT_mol_show_text.handle_remove(context)
context.window_manager.display_mol_labels.enabled = False
return {'CANCELLED'}
def invoke(self, context, event):
if context.window_manager.display_mol_labels.enabled == False:
context.window_manager.display_mol_labels.enabled = True
context.window_manager.modal_handler_add(self)
MCELL_OT_mol_show_text.handle_add(self, context)
return {'RUNNING_MODAL'}
else:
context.window_manager.display_mol_labels.enabled = False
MCELL_OT_mol_show_text.handle_remove(context)
return {'CANCELLED'}
return {'CANCELLED'}
import os
def remove_mol_data_by_name ( mol_name, context ):
# print ( "Call to: \"remove_mol_data_by_name\" to remove " + mol_name )
meshes = bpy.data.meshes
mats = bpy.data.materials
objs = bpy.data.objects
scn = bpy.context.scene
scn_objs = bpy.context.scene.collection.children[0].objects
mol_obj_name = "mol_" + mol_name
mol_shape_obj_name = mol_obj_name + "_shape"
mol_shape_mesh_name = mol_obj_name + "_shape"
mol_pos_mesh_name = mol_obj_name + "_pos"
mol_material_name = mol_obj_name + "_mat"
mols_obj = objs.get("molecules")
mol_obj = objs.get(mol_obj_name)
mol_shape_obj = objs.get(mol_shape_obj_name)
mol_shape_mesh = meshes.get(mol_shape_mesh_name)
mol_pos_mesh = meshes.get(mol_pos_mesh_name)
mol_material = mats.get(mol_material_name)
if mol_obj:
try:
objs.remove ( mol_obj )
meshes.remove ( mol_pos_mesh )
except: pass
if mol_shape_obj:
try:
objs.remove ( mol_shape_obj )
meshes.remove ( mol_shape_mesh )
except: pass
if mol_material:
if mol_material.users <= 0:
try: mats.remove ( mol_material )
except: pass
class MCellMolComponentProperty(bpy.types.PropertyGroup):
contains_cellblender_parameters: BoolProperty(name="Contains CellBlender Parameters", default=True)
component_name: StringProperty(default="", description="Component name")
states_string: StringProperty(default="", description="States String")
is_key: BoolProperty(default=False, description="Indicates that this is a Rotation Key and not a true component")
loc_x: PointerProperty ( name="loc_x", type=parameter_system.Parameter_Reference )
loc_y: PointerProperty ( name="loc_y", type=parameter_system.Parameter_Reference )
loc_z: PointerProperty ( name="loc_z", type=parameter_system.Parameter_Reference )
rot_x: PointerProperty ( name="rot_x", type=parameter_system.Parameter_Reference )
rot_y: PointerProperty ( name="rot_y", type=parameter_system.Parameter_Reference )
rot_z: PointerProperty ( name="rot_z", type=parameter_system.Parameter_Reference )
rot_ang: PointerProperty ( name="rot_ang", type=parameter_system.Parameter_Reference )
rot_index: IntProperty ( name="AngleRef", default = 0, description="Index of Component/Key to use as Angle Reference (-1 defines a key)" )
def init_properties ( self, parameter_system ):
self.loc_x.init_ref ( parameter_system, user_name="Component location x", user_expr="0", user_units="microns", user_descr="loc_x" )
self.loc_y.init_ref ( parameter_system, user_name="Component location y", user_expr="0", user_units="microns", user_descr="loc_y" )
self.loc_z.init_ref ( parameter_system, user_name="Component location z", user_expr="0", user_units="microns", user_descr="loc_z" )
self.rot_x.init_ref ( parameter_system, user_name="Component rotation axis x", user_expr="0", user_units="none", user_descr="rot_x" )
self.rot_y.init_ref ( parameter_system, user_name="Component rotation axis y", user_expr="0", user_units="none", user_descr="rot_y" )
self.rot_z.init_ref ( parameter_system, user_name="Component rotation axis z", user_expr="0", user_units="none", user_descr="rot_z" )
self.rot_ang.init_ref ( parameter_system, user_name="Component rotation angle", user_expr="0", user_units="degrees", user_descr="rot_ang" )
def remove_properties ( self, context ):
print ( "Removing all Component Properties ..." )
ps = context.scene.mcell.parameter_system
self.loc_x.clear_ref ( ps )
self.loc_y.clear_ref ( ps )
self.loc_z.clear_ref ( ps )
self.rot_x.clear_ref ( ps )
self.rot_y.clear_ref ( ps )
self.rot_z.clear_ref ( ps )
self.rot_ang.clear_ref ( ps )
print ( "Done removing all Component Properties." )
class MCell_OT_molecule_recalc_comps(bpy.types.Operator):
bl_idname = "mcell.molecule_recalc_comps"
bl_label = "Recalculate"
bl_description = "Recalculate Component Geometry"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
ms = context.scene.mcell.molecules
print ( "Recalculating Component Geometry" )
for m in ms.molecule_list:
if (m.geom_type == '2DAuto') or (m.geom_type == '3DAuto'):
print ( "Updating molecule " + str(m) )
num_comps = len(m.component_list)
comp_dist = m.component_distance
index = 0
for comp in m.component_list:
loc = []
if m.geom_type == '2DAuto':
loc = get_2D_auto_point ( num_comps, comp_dist, index )
if m.geom_type == '3DAuto':
loc = get_3D_auto_point ( num_comps, comp_dist, index )
print ( "Move Mol Component \"" + comp.component_name + "\" to:" + str(loc) )
comp.loc_x.set_expr ( str(loc[0]) )
comp.loc_y.set_expr ( str(loc[1]) )
comp.loc_z.set_expr ( str(loc[2]) )
index += 1
return {'FINISHED'}
class MCell_OT_molecule_2D_Circ(bpy.types.Operator):
bl_idname = "mcell.dist_two_d_circle"
bl_label = "Recalculate 2D"
bl_description = "Recalculate 2D Component Geometry"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
# Arrange the components evenly spaced on a sphere
print ( "Recalculating Molecule Component Geometry in 3D" )
ps = context.scene.mcell.parameter_system
mols = context.scene.mcell.molecules
this_mol = mols.molecule_list[mols.active_mol_index]
# Create a list of ONLY the actual components
comp_only_list = [ c for c in this_mol.component_list if c.is_key == False ]
num_comps = len(comp_only_list)
comp_dist = this_mol.component_distance
index = 0
for comp in comp_only_list:
loc = get_2D_auto_point ( num_comps, comp_dist, index )
comp.loc_x.set_expr ( str(loc[0]) )
comp.loc_y.set_expr ( str(loc[1]) )
comp.loc_z.set_expr ( str(loc[2]) )
index += 1
return {'FINISHED'}
class MCell_OT_molecule_3D_Sp(bpy.types.Operator):
bl_idname = "mcell.dist_three_d_sphere"
bl_label = "Recalculate 3D"
bl_description = "Recalculate 3D Component Geometry"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
# Arrange the components evenly spaced on a sphere
print ( "Recalculating Molecule Component Geometry in 3D" )
ps = context.scene.mcell.parameter_system
mols = context.scene.mcell.molecules
this_mol = mols.molecule_list[mols.active_mol_index]
# Create a list of ONLY the actual components
comp_only_list = [ c for c in this_mol.component_list if c.is_key == False ]
num_comps = len(comp_only_list)
comp_dist = this_mol.component_distance
index = 0
for comp in comp_only_list:
loc = get_3D_auto_point ( num_comps, comp_dist, index )
comp.loc_x.set_expr ( str(loc[0]) )
comp.loc_y.set_expr ( str(loc[1]) )
comp.loc_z.set_expr ( str(loc[2]) )
index += 1
return {'FINISHED'}
### Using a mode change callback is one way to swap in the fields (currently disabled)
def mol_geom_type_changed_callback ( self, context ):
print ( "Geometry Type has been changed!!" )
print ( "self = " + str(self) )
# ps = context.scene.mcell.parameter_system
if self.geom_type == '2DAuto':
# Arrange the components evenly spaced on a circle in the x-y plane
this_mol = self
num_comps = len(this_mol.component_list)
comp_dist = this_mol.component_distance
index = 0
for comp in this_mol.component_list:
loc = get_2D_auto_point ( num_comps, comp_dist, index )
print ( "Move 2D Mol Component \"" + comp.component_name + "\" to:" + str(loc) )
# These created an error: AttributeError: bpy_struct: attribute "loc_x" from "MCellMolComponentProperty" is read-only
#comp.loc_x = loc[0]
#comp.loc_y = loc[1]
#comp.loc_z = loc[2]
index += 1
elif self.geom_type == '3DAuto':
# Arrange the components evenly spaced on a sphere
this_mol = self
num_comps = len(this_mol.component_list)
comp_dist = this_mol.component_distance
for index in range(num_comps):
loc = get_3D_auto_point ( num_comps, comp_dist, index )
# print ( "Move 3D Mol Component \"" + comp.component_name + "\" to:" + str(loc) )
# item.loc_x = x
class MCellMoleculeProperty(bpy.types.PropertyGroup):
contains_cellblender_parameters: BoolProperty(name="Contains CellBlender Parameters", default=True)
name: StringProperty(
name="Molecule Name", default="Molecule",
description="The molecule species name",
update=name_change_callback)
old_name: StringProperty(name="Old Mol Name", default="Molecule")
description: StringProperty(name="Description", default="")
component_list: CollectionProperty(type=MCellMolComponentProperty, name="Component List")
active_component_index: IntProperty(name="Active Component Index", default=0)
geom_type_enum = [
('None', "Coincident", ""),
('XYZRef', "XYZ,RotRef", ""),
('XYZVA', "XYZ,RotAxis", ""), # label was: "XYZ,V,A Specified"
('2DAuto', "---------------", ""), # label was: "2D Auto"
('3DAuto', "---------------", ""), # label was: "3D Auto"
('XYZ', "---------------", ""), # label was: "XYZ"
('XYZA', "---------------", "") # label was: "XYZ,A Specified"
]
geom_type: EnumProperty(
items=geom_type_enum, name="Geometry",
default='None',
description="Layout method for Complex Molecules." )
#,
#update=mol_geom_type_changed_callback)
component_distance: FloatProperty ( name="R", min=0.0, default=0.01, description="Distance of Components from Molecule" )
shape_name: StringProperty(name="ShapeName", default="")
material_name: StringProperty(name="MatName", default="")
glyph_visibility: BoolProperty ( default=True, description='Show this molecule glyph', update=glyph_visibility_callback )
glyph_show_only: BoolProperty ( default=False, description='Show only this molecule glyph', update=glyph_show_only_callback )
id: IntProperty(name="Molecule ID", default=0)
type_enum = [
('2D', "Surface Molecule", ""),
('3D', "Volume Molecule", "")]
type: EnumProperty(
items=type_enum, name="Molecule Type",
default='3D',
description="Surface molecules are constrained to surfaces/meshes. "
"Volume molecules exist in space.")
diffusion_constant: PointerProperty ( name="Molecule Diffusion Constant", type=parameter_system.Parameter_Reference )
lr_bar_trigger: BoolProperty("lr_bar_trigger", default=False)
bnglLabel: StringProperty(
name="BNGL Label", default="",
description="The molecule BNGL label",
update=check_callback)
target_only: BoolProperty(
name="Target Only",
description="If selected, molecule will not initiate reactions when "
"it runs into other molecules. Can speed up simulations.")
custom_time_step: PointerProperty ( name="Molecule Custom Time Step", type=parameter_system.Parameter_Reference )
custom_space_step: PointerProperty ( name="Molecule Custom Space Step", type=parameter_system.Parameter_Reference )
maximum_step_length: PointerProperty ( name="Maximum Step Length", type=parameter_system.Parameter_Reference )
usecolor: BoolProperty ( name="Use this Color", default=True, description='Use Molecule Color instead of Material Color', update=display_callback )
color: FloatVectorProperty ( name="", min=0.0, max=1.0, default=(0.5,0.5,0.5), subtype='COLOR', description='Molecule Color', update=display_callback )
alpha: FloatProperty ( name="Alpha", min=0.0, max=1.0, default=1.0, description="Alpha (inverse of transparency)", update=display_callback )
emit: FloatProperty ( name="Emit", min=0.0, default=1.0, description="Emits Light (brightness)", update=display_callback )
scale: FloatProperty ( name="Scale", min=0.0001, default=1.0, description="Relative size (scale) for this molecule", update=shape_change_callback )
previous_scale: FloatProperty ( name="Previous_Scale", min=0.0, default=1.0, description="Previous Scale" )
#cumulative_scale: FloatProperty ( name="Cumulative_Scale", min=0.0, default=1.0, description="Cumulative Scale" )
glyph_lib = os.path.join(os.path.dirname(__file__), "glyph_library.blend", "Mesh", "")
glyph_enum = [
('Sphere_1', "Sphere_1", ""),
('Cone', "Cone", ""),
('Cube', "Cube", ""),
('Cylinder', "Cylinder", ""),
('Icosahedron', "Icosahedron", ""),
('Octahedron', "Octahedron", ""),
('Receptor', "Receptor", ""),
('Sphere_2', "Sphere_2", ""),
('Torus', "Torus", ""),
('Tetrahedron', "Tetrahedron", ""),
('Pyramid', "Pyramid", ""),
('Letter', "Letter", "")]
glyph: EnumProperty ( items=glyph_enum, name="Molecule Shape", update=shape_change_callback )
letter_enum = [
('A', "A", ""),
('B', "B", ""),
('C', "C", ""),
('D', "D", ""),
('E', "E", ""),
('F', "F", ""),
('G', "G", ""),
('H', "H", ""),
('I', "I", ""),
('J', "J", ""),
('K', "K", ""),
('L', "L", ""),
('M', "M", ""),
('N', "N", ""),
('O', "O", ""),
('P', "P", ""),
('Q', "Q", ""),
('R', "R", ""),
('S', "S", ""),
('T', "T", ""),
('U', "U", ""),
('V', "V", ""),
('W', "W", ""),
('X', "X", ""),
('Y', "Y", ""),
('Z', "Z", "")]
letter: EnumProperty ( items=letter_enum, name="Molecule Letter", update=shape_change_callback )
export_viz: BoolProperty(
default=False, description="If selected, the molecule will be "
"included in the visualization data.")
status: StringProperty(name="Status")
name_show_help: BoolProperty ( default=False, description="Toggle more information about this parameter" )
description_show_help: BoolProperty ( default=False, description="Toggle more information about this parameter" )
bngl_label_show_help: BoolProperty ( default=False, description="Toggle more information about this parameter" )
type_show_help: BoolProperty ( default=False, description="Toggle more information about this parameter" )
target_only_show_help: BoolProperty ( default=False, description="Toggle more information about this parameter" )
def init_properties ( self, parameter_system ):
self.name = "Molecule_"+str(self.id)
self.old_name = self.name
helptext = "Molecule Diffusion Constant - \n" + \
"This molecule diffuses in space with 3D diffusion constant for volume molecules.\n" + \
"This molecule diffuses on a surface with 2D diffusion constant for surface molecules.\n" + \
"The Diffusion Constant can be zero, in which case the molecule doesn’t move."
self.diffusion_constant.init_ref ( parameter_system, user_name="Diffusion Constant", user_expr="0", user_units="cm^2/sec", user_descr=helptext )
helptext = "Molecule Custom Time Step - \n" + \
"This molecule should take timesteps of this length (in seconds).\n" + \
"Use either this or CUSTOM_SPACE_STEP, not both."
self.custom_time_step.init_ref ( parameter_system, user_name="Custom Time Step", user_expr="", user_units="seconds", user_descr=helptext )
helptext = "Molecule Custom Space Step - \n" + \
"This molecule should take steps of this average length (in microns).\n" + \
"If you use this directive, do not set CUSTOM_TIME_STEP.\n" + \
"Providing a CUSTOM_SPACE_STEP for a molecule overrides a potentially\n" + \
"present global SPACE_STEP for this particular molecule."
self.custom_space_step.init_ref ( parameter_system, user_name="Custom Space Step", user_expr="", user_units="microns", user_descr=helptext )
helptext = "Maximum Step Length - \n" + \
"This molecule should never step farther than length L (in microns) during a\n" + \
"single timestep. This can be used to speed up simulations by enforcing a certain\n" + \
"maximum step length for molecules such as molecular motors on a surface\n" + \
"without having to reduce the global timestep unnecessarily. Please use this\n" + \
"keyword with care since it may give rise to a non-equilibrium distribution of\n" + \
"the given molecule and also cause deviations from mass action kinetics."
self.maximum_step_length.init_ref ( parameter_system, user_name="Maximum Step Length", user_expr="", user_units="microns", user_descr=helptext )
self.create_mol_data() #(context)
def remove_properties ( self, context ):
print ( "Removing all Molecule Properties ..." )
ps = context.scene.mcell.parameter_system
self.diffusion_constant.clear_ref ( ps )
self.custom_time_step.clear_ref ( ps )
self.custom_space_step.clear_ref ( ps )
self.maximum_step_length.clear_ref ( ps )
self.remove_mol_data ( context )
self.component_list.clear()
self.active_component_index = 0
print ( "Done removing all Molecule Properties." )