-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfn.py
More file actions
1926 lines (1586 loc) · 69.9 KB
/
Copy pathfn.py
File metadata and controls
1926 lines (1586 loc) · 69.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
import json
import math
import time
import hashlib
import numpy as np
from fnmatch import fnmatch
from math import pi, cos, sin
from pathlib import Path
from bpy_extras import view3d_utils
from bpy_extras.view3d_utils import location_3d_to_region_2d
from mathutils.geometry import intersect_line_plane
from mathutils import (Matrix,
Vector,
Color,
geometry,
)
from .constants import (LAYERMAT_PREFIX,
LAYERSTROKE_PREFIX,
LAYERBRUSH_PREFIX,
DEFAULT_LAYER_STACK,
DEFAULT_MATERIAL_STACK,
DEFAULT_ACTIVE_LAYER,
)
### ---
# region mapping
## Mapping of keymap items to their id
KEYNUM_MAP = {
# Top row numbers
"ONE": "1",
"TWO": "2",
"THREE": "3",
"FOUR": "4",
"FIVE": "5",
"SIX": "6",
"SEVEN": "7",
"EIGHT": "8",
"NINE": "9",
"ZERO": "0",
# Numpad numbers
"NUMPAD_1": "1",
"NUMPAD_2": "2",
"NUMPAD_3": "3",
"NUMPAD_4": "4",
"NUMPAD_5": "5",
"NUMPAD_6": "6",
"NUMPAD_7": "7",
"NUMPAD_8": "8",
"NUMPAD_9": "9",
"NUMPAD_0": "0"
}
### ---
# region prefs
def get_addon_package():
'''Return addon package name (can be called from submodules)'''
return __package__
def get_addon_prefs():
return bpy.context.preferences.addons[__package__].preferences
def open_addon_prefs():
'''Open addon prefs windows with focus on current addon'''
bpy.ops.preferences.addon_show(module=__package__)
### ---
# region Vector
def snap_to_step(value, step):
# return (value//step)*step # Also valid
return round(value / step) * step
def location_to_region(worldcoords) -> Vector:
'''return 2d location'''
return view3d_utils.location_3d_to_region_2d(
bpy.context.region, bpy.context.space_data.region_3d, worldcoords)
def region_to_location(viewcoords, depthcoords) -> Vector:
'''return normalized 3d vector'''
return view3d_utils.region_2d_to_location_3d(
bpy.context.region, bpy.context.space_data.region_3d, viewcoords, depthcoords)
def reset_draw_settings(context=None):
'''Reset placement and orientation settings according to addon preferences'''
context = context or bpy.context
settings = context.scene.tool_settings
prefs = get_addon_prefs()
# 'ORIGIN', 'CURSOR', 'SURFACE', 'STROKE'
# settings.gpencil_stroke_placement_view3d = 'ORIGIN'
if prefs.default_placement != 'NONE':
settings.gpencil_stroke_placement_view3d = prefs.default_placement
# 'VIEW', 'AXIS_Y', 'AXIS_X', 'AXIS_Z', 'CURSOR'
# settings.gpencil_sculpt.lock_axis = 'AXIS_Y' # Front Axis
if prefs.default_orientation != 'NONE':
settings.gpencil_sculpt.lock_axis = prefs.default_orientation
def coord_distance_from_view(coord=None, context=None):
'''Get distance between view origin and plane facing view at coordinate'''
context = context or bpy.context
coord = coord or context.scene.cursor.location
rv3d = context.region_data
view_mat = rv3d.view_matrix.inverted()
view_point = view_mat @ Vector((0, 0, -1000))
co = intersect_line_plane(view_mat.translation, view_point, coord, view_point)
if co is None:
return None
return (co - view_mat.translation).length
def get_camera_view_vector():
'''return active camera view vector (normalized direction)
return None if no active camera
'''
view_vector = Vector((0,0,-1))
if not bpy.context.scene.camera:
return
view_vector.rotate(bpy.context.scene.camera.matrix_world)
return view_vector
def get_viewport_view_vector(context=None):
'''return current viewport view vector (normalized direction)'''
context = context or bpy.context
view_vector = Vector((0,0,-1))
view_vector.rotate(context.space_data.region_3d.view_rotation)
return view_vector
def coord_distance_from_cam(coord=None, context=None):
"""Get the distance between the camera and a 3D point, parallel to view vector axis"""
context = context or bpy.context
coord = coord or context.scene.cursor.location
view_mat = context.scene.camera.matrix_world
view_point = view_mat @ Vector((0, 0, -1000))
co = intersect_line_plane(view_mat.translation, view_point, coord, view_point)
if co is None:
return None
return (co - view_mat.translation).length
def get_cam_frame_world(cam, scene=None):
'''get camera frame center position in 3d space
Need scene to get resolution ratio (default to active scene)
ortho camera note: scale must be 1,1,1 (parent too)
to fit right in cam-frame rectangle
'''
scene = scene or bpy.context.scene
# Without scene passed, base on square
frame = cam.data.view_frame(scene=scene)
mat = cam.matrix_world
frame = [mat @ v for v in frame]
#-# Get center
# import numpy as np
# center = np.add.reduce(frame) / 4
# center = np.sum(frame, axis=0) / 4
return frame
def get_cam_frame_world_center(cam, scene=None):
'''get camera frame center position in 3d space
Need scene to get resolution ratio (default to active scene)
ortho camera note: scale must be 1,1,1 (parent too)
to fit right in cam-frame rectangle
'''
scene = scene or bpy.context.scene
frame = get_cam_frame_world(cam, scene=scene)
#-# Get center
# return np.sum(frame, axis=0) / 4
return np.add.reduce(frame) / 4
def calculate_dolly_zoom_position(old_position, target_position, old_focal_length, new_focal_length):
"""
Calculates a new camera position for a dolly zoom effect based on focal length change.
Designed to be used in a modal operator with a slider.
Args:
old_position: The previous/current camera position (mathutils.Vector)
target_position: The target position (mathutils.Vector)
old_focal_length: The previous/current focal length in mm
new_focal_length: The new focal length in mm
Returns:
Vector: The new camera position
"""
# Get direction vector from old camera position to target
direction = (target_position - old_position).normalized()
# Calculate current distance
current_distance = (target_position - old_position).length
# Calculate new distance to maintain same field of view for subject
# The ratio of distances should equal the ratio of focal lengths
new_distance = current_distance * (new_focal_length / old_focal_length)
# Calculate new position
return target_position - direction * new_distance
def replace_rotation_matrix(M1, M2):
'''Replace rotation component of matrix 1 with matrix 2
return a new matrix
'''
# Convert Blender matrices to numpy arrays
M1_np = np.array(M1)
M2_np = np.array(M2)
# Extract the rotation components (upper 3x3 part)
R2 = M2_np[:3, :3]
# Replace the rotation part of M1 with R2
M1_np[:3, :3] = R2
# Convert back to Blender Matrix
M1_new = Matrix(M1_np.tolist())
return M1_new
def get_scale_matrix(scale) -> Matrix:
'''Recreate a neutral mat scale'''
matscale_x = Matrix.Scale(scale[0], 4,(1,0,0))
matscale_y = Matrix.Scale(scale[1], 4,(0,1,0))
matscale_z = Matrix.Scale(scale[2], 4,(0,0,1))
matscale = matscale_x @ matscale_y @ matscale_z
return matscale
def assign_rotation_from_ref_matrix(obj, ref_mat, rot_90=True):
'''Get an object, a reference matrix and assign
:obj: Object to modify
:ref_mat: Matrix to get rotation from
:rot_90: Add and extra 90 degree negative rotation on X axis
Usefull when aligning with camera view so object keep facing front
'''
_ref_loc, ref_rot, _ref_scale = ref_mat.decompose()
if obj.parent:
mat = obj.matrix_world
else:
mat = obj.matrix_basis
o_loc, _o_rot, o_scale = mat.decompose()
loc_mat = Matrix.Translation(o_loc)
if rot_90:
mat_90 = Matrix.Rotation(-pi/2, 4, 'X')
rot_mat = ref_rot.to_matrix().to_4x4() @ mat_90
else:
rot_mat = ref_rot.to_matrix().to_4x4()
scale_mat = get_scale_matrix(o_scale)
new_mat = loc_mat @ rot_mat @ scale_mat
if obj.parent:
obj.matrix_world = new_mat
else:
obj.matrix_basis = new_mat
return new_mat
## -- used for static storyboard
def get_min_max_corner(positions, margin=0):
## Sort in place (modify list !!)
positions.sort(key=lambda vec: (vec.x, vec.z))
min_corner = positions[0]
max_corner = positions[-1]
if not margin:
return min_corner, max_corner
## Add 20% margin to get strokes in frame
diagonal = (min_corner - max_corner).length
margin = diagonal * 0.2 / 2
max_corner = max_corner + Vector((1, 0, 1)) * margin
min_corner = min_corner + Vector((-1, 0, -1)) * margin
return min_corner, max_corner
## unused - need to test performance against any_point_in_box
def any_point_in_rectangle_numpy(stroke, bottom_left, upper_right):
"""
NumPy vectorized version - fastest for large point collections.
"""
# Extract X and Z coordinates
x_coords = np.array([p.position.x for p in stroke.points])
z_coords = np.array([p.position.z for p in stroke.points])
# Check bounds
x_in_bounds = (x_coords >= bottom_left.x) & (x_coords <= upper_right.x)
z_in_bounds = (z_coords >= bottom_left.z) & (z_coords <= upper_right.z)
# Return True if any point satisfies both conditions
return np.any(x_in_bounds & z_in_bounds)
def any_point_in_box(coords, min_corner, max_corner):
''' Check if any point in coords list is within the X-Z bounding box defined by min_corner and max_corner
coords : list of Vector3 or tuple coordinates
min_corner : Vector3, lower left corner of the bounding box
max_corner : Vector3, upper right corner of the bounding box
'''
return any(min_corner.x <= co.x <= max_corner.x and min_corner.z <= co.z <= max_corner.z for co in coords)
def to_flatten_pairs(v_list, closed=True) -> list:
"""Take a sequence of item (vector, vertices), return a lists of flattened pairs.
ex: for continuous coordinate, return segments pairs, result is usable with gpu_shader 'LINES'
v_list (list): List of coordinates [a,b,c]
closed (bool):
True return [a,b,b,c,c,a] (add segment closing last to first coordinate)
False return [a,b,b,c]
"""
loop = []
for i in range(len(v_list) - 1):
loop += [v_list[i], v_list[i + 1]]
if closed:
# Add segment between last and first to close loop
loop += [v_list[-1], v_list[0]]
return loop
### ---
# region Camera/View Frustum
## User view calculation from Swann Martinez's Multi-user addon
def project_to_viewport(region: bpy.types.Region, rv3d: bpy.types.RegionView3D, coords: tuple, distance: float = 1.0) -> Vector:
""" Compute a projection from 2D to 3D viewport coordinate
:param region: target windows region
:type region: bpy.types.Region
:param rv3d: view 3D
:type rv3d: bpy.types.RegionView3D
:param coords: coordinate to project
:type coords: list
:param distance: distance offset into viewport
:type distance: float
:return: Vector() list of coordinates [x,y,z]
"""
target = [0, 0, 0]
if coords and region and rv3d:
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coords)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coords)
target = ray_origin + view_vector * distance
return Vector((target.x, target.y, target.z))
def generate_user_camera(area, region, rv3d) -> list:
""" Generate a basic camera represention of the user point of view
v1-4 first point represent the square
v5: frame center point
v6: view location (orbit point)
v7:
:return: list of 7 points
"""
# area, region, rv3d = view3d_find()
v1 = v2 = v3 = v4 = v5 = v6 = v7 = [0, 0, 0]
if area and region and rv3d:
width = region.width
height = region.height
v1 = project_to_viewport(region, rv3d, (width, height))
v2 = project_to_viewport(region, rv3d, (width, 0))
v3 = project_to_viewport(region, rv3d, (0, 0))
v4 = project_to_viewport(region, rv3d, (0, height))
v5 = project_to_viewport(region, rv3d, (width/2, height/2))
v6 = rv3d.view_location # list(rv3d.view_location)
v7 = project_to_viewport(
region, rv3d, (width/2, height/2), distance=-.8)
coords = [v1, v2, v3, v4, v5, v6, v7]
return coords
# Unused, but could be called by get_frustum_lines()
def extrapolate_points_by_length(a, b, length):
'''
Return a third point C from by continuing in AB direction
Length define BC distance. both vector2 and vector3
'''
# return b + ((b - a).normalized() * length)# one shot
ab = b - a
if not ab:
return None
return b + (ab.normalized() * length)
def circle_3d(x, y, radius, segments):
m = (1.0 / (segments - 1)) * (pi * 2)
## Detailed version
# coords = []
# for p in range(segments):
# p1 = x + cos(m * p) * radius
# p2 = y + sin(m * p) * radius
# coords.append(Vector((p1, p2, 0)))
## List comprehension for faster computation
coords = [Vector((x + cos(m * p) * radius,
y + sin(m * p) * radius,
0))
for p in range(segments)]
return coords
def get_frustum_lines(loc, left, right, orient, near_clip_point, far_clip_point, view_type):
"""return points of quad representing view frustum
sequence reresent following pairs to be used draw batch LINES
# Left and Right lines:
left near -> left far
right near -> right far
## near clip and far clip perpendicular lines:
left near -> right near
left far -> right far
"""
if view_type == 'ORTHO':
view_list = [
# Left
intersect_line_plane(left, left + orient, near_clip_point, orient),
intersect_line_plane(left, left + orient, far_clip_point, orient),
# Right
intersect_line_plane(right, right + orient, near_clip_point, orient),
intersect_line_plane(right, right + orient, far_clip_point, orient),
]
else:
### Cone Coors
## Basic view cone
# view_list = [
# loc, extrapolate_points_by_length(loc, right, 2000),
# loc, extrapolate_points_by_length(loc, left, 2000)
# ]
# View cone with clipping display
view_list = [
# Left
intersect_line_plane(loc, left, near_clip_point, orient),
intersect_line_plane(loc, left, far_clip_point, orient),
# Right
intersect_line_plane(loc, right, near_clip_point, orient),
intersect_line_plane(loc, right, far_clip_point, orient),
]
# if post_pixel:
# view_list = [fn.location_to_region(v) for v in view_list]
# Add perpenticular lines
view_list.append(view_list[0])
view_list.append(view_list[2])
view_list.append(view_list[1])
view_list.append(view_list[3])
return view_list
def get_camera_frustum(cam, context=None):
"""
Get camera frustum coordinates in 3D space
cam (Object): Camera object
context (Context, optional): Blender context for scene information
Returns:
list: 3D coordinates of camera frustum lines, or empty list if camera is invalid
"""
if not cam or cam.type != 'CAMERA':
return []
if context is None:
context = bpy.context
scene = context.scene
# Get camera frame
frame = [cam.matrix_world @ v for v in cam.data.view_frame(scene=scene)]
mat = cam.matrix_world
loc = mat.to_translation()
# Calculate midpoints for left and right sides
right = (frame[0] + frame[1]) / 2
left = (frame[2] + frame[3]) / 2
# Calculate near and far clip points
near_clip_point = mat @ Vector((0,0,-cam.data.clip_start))
far_clip_point = mat @ Vector((0,0,-cam.data.clip_end))
# Get orientation vector
orient = Vector((0,0,1))
orient.rotate(mat)
# Get frustum lines using the existing function
return get_frustum_lines(loc, left, right, orient, near_clip_point, far_clip_point, cam.data.type)
def get_viewport_frustum(area, region, rv3d, space):
"""
Get viewport frustum coordinates in 3D space
area (Area): Viewport area
region (Region): Region of the viewport
rv3d (RegionView3D): 3D region view
space (SpaceView3D): View space for clip distances
Returns:
list: 3D coordinates of viewport frustum lines
"""
## Return camrera frustum if un camera view (supposed to be the same)
# if rv3d.view_perspective == 'CAMERA':
# return get_camera_frustum(space.active.camera, context=bpy.context)
# Construct view orientation
view_mat = rv3d.view_matrix.inverted()
view_orient = Vector((0, 0, 1))
view_orient.rotate(view_mat)
# Get user camera coordinates
user_cam = generate_user_camera(area, region, rv3d)
# Extract location and view frame points
loc = user_cam[6] # View location point
left = (user_cam[2] + user_cam[3]) / 2 # Left midpoint
right = (user_cam[0] + user_cam[1]) / 2 # Right midpoint
# Calculate near and far clip points
near_clip_point = view_mat @ Vector((0, 0, -space.clip_start))
far_clip_point = view_mat @ Vector((0, 0, -space.clip_end))
# Get frustum lines using the existing function
return get_frustum_lines(loc, left, right, view_orient, near_clip_point,
far_clip_point, rv3d.view_perspective)
### ---
# region Collection management
def get_view_layer_collection(col, vl_col=None, view_layer=None):
'''return viewlayer collection from collection
col: the collection to get viewlayer collection from
view_layer (viewlayer, optional) : viewlayer to search in, if not passed, use active viewlayer
'''
if vl_col is None:
if view_layer:
vl_col = view_layer.layer_collection
else:
vl_col = bpy.context.view_layer.layer_collection
for sub in vl_col.children:
if sub.collection == col:
return sub
if len(sub.children):
c = get_view_layer_collection(col, sub)
if c is not None:
return c
### ---
# region Object
def empty_at(pos, name='Empty', type='PLAIN_AXES', size=1.0, show_name=False, link=True):
'''
Create an empty at given Vector3 position.
pos (Vector3): position
name (str, default Empty): name of the empty object
type (str, default 'PLAIN_AXES'): options in 'PLAIN_AXES','ARROWS','SINGLE_ARROW','CIRCLE','CUBE','SPHERE','CONE','IMAGE'
size (int, default 1.0): Size of the empty
link (Bool,default True): Link to active collection
i.e : empty_at((0,0,1), 'ARROWS', 2) creates "Empty" at Z+1, of type gyzmo and size 2
'''
mire = bpy.data.objects.get(name)
if not mire:
mire = bpy.data.objects.new(name, None)
if link:
bpy.context.collection.objects.link(mire)
mire.empty_display_type = type
mire.empty_display_size = size
mire.location = pos
mire.show_name = show_name
return mire
def clear_asset_metadata(id_data):
'''An appended or copied asset keeps its asset metadata and may get a fake user.
Clear both (as blender's own asset append does): this local copy is plain data.
Linked or overridden data is left untouched (not editable)'''
if id_data.library or id_data.override_library:
return
if id_data.asset_data:
id_data.asset_clear()
id_data.use_fake_user = False
def get_camera_collection(scene=None):
'''Return the collection dedicated to the cameras of the scene, create and link it if needed'''
scene = scene or bpy.context.scene
## using scene name in collection name might allow identification on multi_scene...
camera_collection_name = f'cam_{scene.name}'
cam_col = bpy.data.collections.get(camera_collection_name)
if not cam_col:
cam_col = bpy.data.collections.new(camera_collection_name)
scene.collection.children.link(cam_col)
return cam_col
def pack_images_in_object(obj, verbose=False):
'''Pack all image textures used by object into the blend file.
obj (Object): object containing materials with image textures.
'''
# Ensure the object has materials
if not obj.data.materials:
return
# print(f"Packing images for object: {obj.name}")
for mat in obj.data.materials:
if mat and mat.use_nodes:
for node in mat.node_tree.nodes:
if node.type == 'TEX_IMAGE' and node.image:
node.image.pack()
if verbose:
print(f"Packed image: {node.image.name}")
### ---
# region GP
## Unused, but has potential for later utility
def get_gp_draw_plane(context):
''' return tuple with plane coordinate and normal
of the curent drawing according to geometry'''
settings = context.scene.tool_settings
orient = settings.gpencil_sculpt.lock_axis # 'VIEW', 'AXIS_Y', 'AXIS_X', 'AXIS_Z', 'CURSOR'
loc = settings.gpencil_stroke_placement_view3d # 'ORIGIN', 'CURSOR', 'SURFACE', 'STROKE'
mat = context.object.matrix_world if context.object else None
# -> placement
if loc == "CURSOR":
plane_co = context.scene.cursor.location
else: # ORIGIN (also on origin if set to 'SURFACE', 'STROKE')
if not context.object:
plane_co = None
else:
plane_co = context.object.matrix_world.to_translation()# context.object.location
# -> orientation
if orient == 'VIEW':
plane_no = context.space_data.region_3d.view_rotation @ Vector((0,0,1))
## create vector, then rotate by view quaternion
# plane_no = Vector((0,0,1))
# plane_no.rotate(context.space_data.region_3d.view_rotation)
## only depth is important, can return None so region to location use same depth
# plane_no = None
elif orient == 'AXIS_Y': # front (X-Z)
plane_no = Vector((0,1,0))
plane_no.rotate(mat)
elif orient == 'AXIS_X': # side (Y-Z)
plane_no = Vector((1,0,0))
plane_no.rotate(mat)
elif orient == 'AXIS_Z': # top (X-Y)
plane_no = Vector((0,0,1))
plane_no.rotate(mat)
elif orient == 'CURSOR':
plane_no = Vector((0,0,1))
plane_no.rotate(context.scene.cursor.matrix)
return plane_co, plane_no
def get_gp_draw_plane_matrix(context):
'''return matrix representing the drawing plane of the grease pencil object'''
settings = context.scene.tool_settings
orient = settings.gpencil_sculpt.lock_axis # 'VIEW', 'AXIS_Y', 'AXIS_X', 'AXIS_Z', 'CURSOR'
loc = settings.gpencil_stroke_placement_view3d # 'ORIGIN', 'CURSOR', 'SURFACE', 'STROKE'
mat = context.object.matrix_world if context.object else None
draw_plane_mat = Matrix().to_3x3()
# -> placement
if loc == "CURSOR":
plane_co = context.scene.cursor.location
else: # ORIGIN (also on origin if set to 'SURFACE', 'STROKE')
if not context.object:
plane_co = None
else:
plane_co = context.object.matrix_world.to_translation() # context.object.location
if not plane_co:
return
# -> orientation
if orient == 'VIEW':
draw_plane_mat.rotate(context.space_data.region_3d.view_rotation)
# draw_plane_mat = context.space_data.region_3d.view_matrix.inverted() @ draw_plane_mat # multiply mat
elif orient == 'AXIS_Y': # front (X-Z) - Vector((0,1,0))
draw_plane_mat = Matrix.Rotation(math.radians(90), 3, 'X')
draw_plane_mat.rotate(mat)
## Can apply and nomalize matrix to reset scale ?
# draw_plane_mat = mat @ draw_plane_mat # multiply mat
elif orient == 'AXIS_X': # side (Y-Z) - Vector((1,0,0))
draw_plane_mat = Matrix.Rotation(math.radians(-90), 3, 'Y')
draw_plane_mat.rotate(mat)
# draw_plane_mat = mat @ draw_plane_mat # multiply mat
elif orient == 'AXIS_Z': # top (X-Y) - Vector((0,0,1))
draw_plane_mat.rotate(mat)
# draw_plane_mat = mat @ draw_plane_mat # multiply mat
elif orient == 'CURSOR':
draw_plane_mat.rotate(context.scene.cursor.matrix)
# draw_plane_mat = context.scene.cursor.matrix @ draw_plane_mat # multiply mat
draw_plane_mat = draw_plane_mat.to_4x4()
draw_plane_mat.translation = plane_co
return draw_plane_mat
def get_default_layer_stack_entries(prefs=None):
'''Return the default layer stack as a list of (layer_name, material_name, brush, stroke_type) tuples
Top layer first (as displayed in Blender's layer list)
Use the customized stack from addon preferences when defined, fallback to hardcoded default
'''
prefs = prefs or get_addon_prefs()
if len(prefs.layer_stack):
return [(l.name.strip(), l.material.strip(), l.brush.strip(), l.stroke_type)
for l in prefs.layer_stack if l.name.strip()]
return list(DEFAULT_LAYER_STACK)
def get_default_active_layer_name(prefs=None):
'''Return the layer name to set active on new GP objects, or None if nothing is flagged
Use the flagged entry from the customized stack in addon preferences when defined,
fallback to hardcoded default name when the stack is empty
'''
prefs = prefs or get_addon_prefs()
if len(prefs.layer_stack):
return next((l.name.strip() for l in prefs.layer_stack if l.set_active and l.name.strip()), None)
return DEFAULT_ACTIVE_LAYER
def create_default_layers(object, frame=None, use_lights=False, set_material_sync=True):
gp = object.data
if frame is None:
frame = bpy.context.scene.frame_current
# Create default layers (entries are stored top layer first, create bottom layer first)
for l_name, mat_name, brush, stroke_type in reversed(get_default_layer_stack_entries()):
layer = gp.layers.new(l_name)
layer.frames.new(frame)
layer.use_lights = use_lights
if set_material_sync:
# Set default material / brush / stroke type association (per-object custom props)
if mat_name:
set_material_association(object, layer, mat_name)
if brush:
object[LAYERBRUSH_PREFIX + layer.name] = brush_reference_from_name(brush)
if stroke_type and stroke_type != 'NONE':
object[LAYERSTROKE_PREFIX + layer.name] = stroke_type
def create_gp_object(
name="",
parented=False,
at_cursor=False,
init_dist=8.0,
face_camera=True,
track_to_cam=False,
enter_draw_mode=True,
location=None,
material_from_obj=None,
layer_from_obj=None,
context=None):
"""
Create a new grease pencil object with specified parameters.
Args:
name: Name of the Grease pencil object
parented: Whether to parent the object to the camera
at_cursor: Create at cursor location instead of facing view
init_dist: Initial distance from view
face_camera: Create facing camera instead of current view
track_to_cam: Add a track-to constraint pointing at active camera
enter_draw_mode: Whether to enter draw mode after creation
location: Explicit location to use instead of cursor or view (override other if provided)
context: Blender context, optional
Returns:
The created Grease Pencil object
"""
# Get context if not provided
if context is None:
context = bpy.context
# Get references
prefs = get_addon_prefs()
scn = context.scene
# Ensure we're in object mode
if context.object and context.object.visible_get() and context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
if context.mode == 'OBJECT':
bpy.ops.object.select_all(action='DESELECT')
# Get view matrix
r3d = context.space_data.region_3d
if r3d.view_perspective != 'CAMERA' and face_camera:
view_matrix = scn.camera.matrix_world
else:
view_matrix = r3d.view_matrix.inverted()
# Set location - prioritize explicit location if provided
if location is not None:
# Use the provided location directly
loc = location
elif at_cursor:
loc = scn.cursor.location
else:
loc = view_matrix @ Vector((0.0, 0.0, -init_dist))
# Clean name or generate default name if empty
name = name.strip()
if name == "":
# Create default numbered name
name_counter = len([o for o in bpy.data.objects if o.type == 'GREASEPENCIL']) + 1
name = f"Drawing_{name_counter:03d}"
# TODO bonus : maybe check if want to use same data as another drawing ?
# Create Grease Pencil object
gp = bpy.data.grease_pencils.new(name)
ob = bpy.data.objects.new(name, gp)
# Find appropriate collection
draw_col = next((c for c in scn.collection.children_recursive if c.name.startswith('Drawings')), None)
if not draw_col:
draw_col = next((c for c in scn.collection.children_recursive if c.name.startswith('GP')), None)
if not draw_col:
draw_col = context.collection # auto-fallback on active collection
# Link to collection
draw_col.objects.link(ob)
# Set parent if needed
if parented:
ob.parent = scn.camera
# Set transform
_ref_loc, ref_rot, _ref_scale = view_matrix.decompose()
rot_mat = ref_rot.to_matrix().to_4x4() @ Matrix.Rotation(-pi/2, 4, 'X')
## Old matrix creation method
# loc_mat = Matrix.Translation(loc)
# new_mat = loc_mat @ rot_mat @ get_scale_matrix((1, 1, 1))
## Using Blender matrix compose method
new_mat = Matrix.LocRotScale(loc, rot_mat.to_3x3(), Vector((1, 1, 1)))
ob.matrix_world = new_mat
# Make active and selected
context.view_layer.objects.active = ob
ob.select_set(True)
# Add constraint if needed
if track_to_cam:
constraint = ob.constraints.new('TRACK_TO')
constraint.target = scn.camera
constraint.track_axis = 'TRACK_Y'
constraint.up_axis = 'UP_Z'
## Configure default settings
# TODO: Set Active palette (Need a selectable loader)
if material_from_obj and len(material_from_obj.data.materials):
## load material from reference object
for mat in material_from_obj.data.materials:
gp.materials.append(mat)
else:
load_default_palette(ob=ob)
## edit_line_opacity not available anymore, kept in case feature is re-implemented in the future
## (No edit line color in GPv3, wire is displayed using curve theme)
# gp.edit_line_color[3] = prefs.default_edit_line_opacity # Bl default is 0.5
gp.use_autolock_layers = prefs.use_autolock_layers
## Create layers
if layer_from_obj and len(layer_from_obj.data.layers):
for ref_layer in layer_from_obj.data.layers:
layer = gp.layers.new(ref_layer.name)
layer.frames.new(scn.frame_current)
## get same use light and opacity settings
layer.use_lights = ref_layer.use_lights
layer.opacity = ref_layer.opacity
## Copy custom properties for layer-material and layer-brush sync
for k, v in layer_from_obj.items():
if k.startswith((LAYERMAT_PREFIX, LAYERSTROKE_PREFIX, LAYERBRUSH_PREFIX)):
ob[k] = v
else:
# Create default layers
create_default_layers(ob, use_lights=prefs.use_lights)
## Add default modifiers and effects from preferences
if prefs.use_hsv_modifier:
mod = ob.modifiers.new('HSV', 'GREASE_PENCIL_COLOR') # HSV, Hue/Saturation, Color (Default)
# mod.hue = prefs.hsv_hue
# mod.saturation = prefs.hsv_saturation
# mod.value = prefs.hsv_value
if prefs.use_blur_effect:
fx = ob.shader_effects.new('Blur', 'FX_BLUR')
fx.use_dof_mode = True # getattr(prefs, 'blur_use_dof_mode', True)
fx.samples = 32 # getattr(prefs, 'blur_samples', 32)
# Set default active layer from preferences, fallback to top layer
target_name = get_default_active_layer_name(prefs=prefs)
target_active = gp.layers.get(target_name) if target_name else None
if not target_active and len(gp.layers):
target_active = gp.layers[-1]
gp.layers.active = target_active
# Update UI
update_ui_prop_index(context)
# Enter draw mode if requested
if enter_draw_mode:
bpy.ops.object.mode_set(mode='PAINT_GREASE_PENCIL')
reset_draw_settings(context=context)
# Show canvas if first GP created on scene (or always enable at creation) ?
if len([o for o in context.scene.objects if o.type == 'GREASEPENCIL']) == 1:
context.space_data.overlay.use_gpencil_grid = True
return ob
def get_coplanar_stroke_vector(obj, s, ensure_colplanar=True, tol=0.0003):
'''Get a GP stroke object and return plane normal vector.
ensure_coplanar: return None if points in stroke are not coplanar
tol: tolerance value for coplanar points check
return normal vector, None if points are not coplanar and ensure_colplanar is True
'''
if len(s.points) < 4:
return
# obj = bpy.context.object
mat = obj.matrix_world
pct = len(s.points)
a = mat @ s.points[0].position
b = mat @ s.points[pct//3].position
c = mat @ s.points[pct//3*2].position
ab = b-a
ac = c-a
# Get normal
plane_no = ab.cross(ac)#.normalized()
if ensure_colplanar:
for p in s.points:
if abs(geometry.distance_point_to_plane(mat @ p.position, a, plane_no)) > tol:
return
return plane_no
def get_normal(obj, frame, tol=0.0003):
ct = len(frame.drawing.strokes)
if ct == 0:
return
if ct < 3:
return get_coplanar_stroke_vector(obj, frame.drawing.strokes[0], ensure_colplanar=False)
## Use first point of 3 first strokes
mat = obj.matrix_world
a = mat @ frame.drawing.strokes[0].points[0].position
b = mat @ frame.drawing.strokes[1].points[0].position
c = mat @ frame.drawing.strokes[-1].points[0].position
ab = b-a
ac = c-a
plane_no = ab.cross(ac)
## Verify coplanar ? # want to return even if it's not...
# for p in s.points:
# if abs(geometry.distance_point_to_plane(mat @ p.position, a, plane_no)) > tol:
# return
return plane_no
def get_coord(obj, frame):
coords = [p.position for s in frame.drawing.strokes for p in s.points]
mean_coord = sum(coords, Vector()) / len(coords)