-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathshader_params_reader.py
More file actions
1536 lines (1309 loc) · 82.9 KB
/
shader_params_reader.py
File metadata and controls
1536 lines (1309 loc) · 82.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
import json
import os
import torch
import math
class ShaderParamsReader:
"""
Class for reading and applying shader parameters from JSON file
Implements the Lt=Sα(N)∘Kβ(t) pattern where shader transforms are applied to noise before sampling
"""
# Define valid parameter values for security whitelisting
VALID_SHADER_TYPES = {
"tensor_field", "cellular", "domain_warp", "fractal", "perlin",
"waves", "gaussian", "heterogeneous_fbm", "interference_patterns",
"spectral", "projection_3d", "curl_noise"
}
VALID_SHAPE_TYPES = {
"none", "circle", "square", "radial", "star", "linear",
"radial_animated", "spiral", "checkerboard", "spots", "hexgrid",
"stripes", "radial_gradient_static", "gradient", "vignette",
"cross", "triangles", "concentric", "rays", "zigzag",
"gradient_x", "gradient_y", "stars"
}
# Legacy mapping for integer shape types to string identifiers
# 1: circle/radial (old), 2: square, 3: star
LEGACY_SHAPE_MAPPING = {
1: "circle",
2: "square",
3: "star",
"1": "circle",
"2": "square",
"3": "star"
}
VALID_COLOR_SCHEMES = {
"none", "rgb", "complementary", "monochrome", "gradient",
"blue_red", "viridis", "plasma", "inferno", "magma", "turbo",
"jet", "rainbow", "cool", "hot", "parula", "hsv", "autumn",
"winter", "spring", "summer", "copper", "pink", "bone",
"ocean", "terrain", "neon", "fire", "fantasy"
}
@staticmethod
def smoothstep(edge0, edge1, x):
"""
GLSL-style smoothstep.
"""
# Ensure edges are tensors for broadcasting with x
if not isinstance(edge0, torch.Tensor):
edge0 = torch.full_like(x, float(edge0), device=x.device, dtype=x.dtype)
if not isinstance(edge1, torch.Tensor):
edge1 = torch.full_like(x, float(edge1), device=x.device, dtype=x.dtype)
# Calculate t, handling potential edge0 >= edge1 cases by clamping
delta = edge1 - edge0
# Avoid division by zero or near-zero, maintain sign for correct 1-smoothstep
safe_delta = torch.where(torch.abs(delta) < 1e-8, torch.sign(delta) * 1e-8 + 1e-8*(1-torch.abs(torch.sign(delta))), delta)
t = torch.clamp((x - edge0) / safe_delta, 0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
@staticmethod
def random_val(coords, base_seed, seed_offset):
"""
Generate a random-like value based on coordinates and seed.
Matches the random_val helper in CurlNoiseGenerator.
"""
# Use a simple hash-like function based on coordinates
# Ensuring coords are float for calculations
coords_float = coords.float()
hash_val = torch.sin(coords_float[:, :, :, 0] * (12.9898 + seed_offset) + coords_float[:, :, :, 1] * (78.233 + seed_offset)) * 43758.5453
return torch.frac(hash_val)
@staticmethod
def validate_and_sanitize_params(params):
"""
Validates and sanitizes shader parameters to prevent DoS or unexpected behavior.
Clamps values to reasonable ranges and ensures correct types.
"""
sanitized = params.copy()
# 1. Octaves: Clamp to reasonable range (e.g., 1-20) to prevent massive loops
# Check both parameter names
for key in ["octaves", "shaderOctaves"]:
if key in sanitized:
try:
# Convert to float first to handle string representations of floats
val = float(sanitized[key])
# Clamp between 1 and 20, and convert to int
sanitized[key] = int(max(1.0, min(val, 20.0)))
except (ValueError, TypeError):
print(f"Warning: Invalid octaves value '{sanitized[key]}', defaulting to 3")
sanitized[key] = 3
# 2. Scale: Ensure float and clamp to prevent numerical instability
for key in ["scale", "shaderScale"]:
if key in sanitized:
try:
val = float(sanitized[key])
if math.isnan(val) or math.isinf(val):
val = 1.0
# Clamp to avoid extremely large values
sanitized[key] = max(-1000000.0, min(val, 1000000.0))
except (ValueError, TypeError):
sanitized[key] = 1.0
# 3. Intensity/Strength: Ensure float and clamp to reasonable range
# Though some shaders might allow > 1, extremely high values can cause issues
# Check both snake_case (internal) and camelCase (frontend) key names
for key in ["intensity", "shaderColorIntensity", "shapemaskstrength", "shapeMaskStrength",
"shaderShapeStrength", "warp_strength", "shaderWarpStrength",
"phase_shift", "shaderPhaseShift"]:
if key in sanitized:
try:
val = float(sanitized[key])
if math.isnan(val) or math.isinf(val):
val = 0.0 if "strength" in key.lower() or "shift" in key.lower() else 1.0
# Clamp strictly to reasonable limits (e.g. +/- 1M) to prevent numerical instability
# This prevents DoS via numerical overflow or resource exhaustion
sanitized[key] = max(-1000000.0, min(val, 1000000.0))
except (ValueError, TypeError):
sanitized[key] = 0.0 if "strength" in key.lower() or "shift" in key.lower() else 1.0
# 4. Validate Seeds: Ensure they are within safe integer range for PyTorch
# PyTorch manual_seed expects 64-bit signed integer (approx +/- 9e18)
# Using a slightly safer range to avoid boundary issues
MAX_SEED = 9000000000000000000
MIN_SEED = -9000000000000000000
for key in ["seed", "base_seed"]:
if key in sanitized:
try:
# Check for float inputs first to catch Infinity
if isinstance(sanitized[key], float):
if math.isinf(sanitized[key]) or math.isnan(sanitized[key]):
sanitized[key] = 0
continue
val = int(sanitized[key])
# Clamp to safe range to prevent runtime crashes (DoS)
sanitized[key] = max(MIN_SEED, min(val, MAX_SEED))
except (ValueError, TypeError, OverflowError):
sanitized[key] = 0
# 5. Validate String Enums (Shader Type, Shape Type, Color Scheme)
# Prevent arbitrary strings from flowing through the system
# Check both snake_case (internal) and camelCase (frontend) key names
for key in ["shader_type", "shaderType"]:
if key in sanitized:
st = str(sanitized[key]).lower()
# Handle some common aliases before validation
if st == "tensorfield": st = "tensor_field"
if st == "heterogeneousfbm": st = "heterogeneous_fbm"
if st == "projection3d": st = "projection_3d"
if st == "curl": st = "curl_noise"
if st not in ShaderParamsReader.VALID_SHADER_TYPES:
print(f"Warning: Invalid {key} '{st}', defaulting to 'tensor_field'")
sanitized[key] = "tensor_field"
else:
sanitized[key] = st
for shape_key in ["shape_type", "shaderShapeType"]:
if shape_key in sanitized:
shape_val = sanitized[shape_key]
# Handle integer inputs for legacy shape types (1, 2, 3)
# and map them to their string equivalents if valid
is_legacy = False
if isinstance(shape_val, int) or (isinstance(shape_val, str) and shape_val.isdigit()):
# Convert to integer for lookup (handles string "1" and int 1)
try:
lookup_key = int(shape_val)
if lookup_key in ShaderParamsReader.LEGACY_SHAPE_MAPPING:
# Map to valid string name
sanitized[shape_key] = ShaderParamsReader.LEGACY_SHAPE_MAPPING[lookup_key]
is_legacy = True
else:
print(f"Warning: Invalid legacy integer {shape_key} '{shape_val}', defaulting to 'none'")
sanitized[shape_key] = "none"
is_legacy = True
except (ValueError, TypeError):
# Fallthrough to string handling if conversion fails weirdly
pass
# If not a handled legacy integer, treat as string identifier
if not is_legacy:
st = str(shape_val).lower()
if st not in ShaderParamsReader.VALID_SHAPE_TYPES:
print(f"Warning: Invalid {shape_key} '{st}', defaulting to 'none'")
sanitized[shape_key] = "none"
else:
sanitized[shape_key] = st
if "colorScheme" in sanitized:
cs = str(sanitized["colorScheme"]).lower()
if cs not in ShaderParamsReader.VALID_COLOR_SCHEMES:
print(f"Warning: Invalid colorScheme '{cs}', defaulting to 'none'")
sanitized["colorScheme"] = "none"
else:
sanitized["colorScheme"] = cs
return sanitized
@staticmethod
def get_shader_params(custom_path=None):
"""
Utility function to read shader parameters from file.
Returns a dictionary of shader parameters.
Args:
custom_path: Optional path to a custom JSON file
Returns:
Dictionary of shader parameters
"""
# Default values in case file doesn't exist or is invalid
default_params = {
"shader_type": "tensor_field",
"visualization_type": 3, # ellipses
"scale": 1.0,
"phase_shift": 0.0,
"warp_strength": 0.5,
"time": 0.0,
"octaves": 3.0,
"intensity": 0.8, # influence/strength of the shader
"shapemaskstrength": 1.0, # strength of the shape mask
"shape_type": "none" # type of shape mask
}
# Get the extension directory (where this file is located)
EXTENSION_DIR = os.path.dirname(os.path.abspath(__file__))
# Path to the shader_params.json file (default or custom)
if custom_path:
# Security check for path traversal - resolve symlinks
try:
resolved_path = os.path.realpath(custom_path)
extension_real_path = os.path.realpath(EXTENSION_DIR)
# Use realpath to ensure we are comparing canonical paths (handles symlinks and casing)
data_dir_real_path = os.path.realpath(os.path.join(extension_real_path, "data"))
default_config_real_path = os.path.realpath(os.path.join(extension_real_path, "shader_params.json"))
# 1. Strict extension check
if not resolved_path.lower().endswith('.json'):
print(f"SECURITY WARNING: Invalid file extension (must be .json): {custom_path}")
is_safe = False
else:
# 2. Strict location check: Must be in data/ OR be the root shader_params.json
# Use normcase for platform-appropriate case normalization
# (lowercases on Windows, preserves case on Linux)
resolved_norm = os.path.normcase(resolved_path)
extension_norm = os.path.normcase(extension_real_path)
data_dir_norm = os.path.normcase(data_dir_real_path)
default_config_norm = os.path.normcase(default_config_real_path)
# 2. Security Check: File must be physically inside the extension directory
# This blocks symlinks pointing outside the extension folder
is_inside_extension = os.path.commonpath([resolved_norm, extension_norm]) == extension_norm
# 3. Scope Check: File must be in data/ or be the config file
# This blocks reading source code or secrets in the extension root
is_in_data = os.path.commonpath([resolved_norm, data_dir_norm]) == data_dir_norm
is_default_config = resolved_norm == default_config_norm
is_safe = is_inside_extension and (is_in_data or is_default_config)
except (ValueError, OSError):
is_safe = False
if not is_safe:
print(f"SECURITY WARNING: Prevented access to unauthorized file: {custom_path}")
# Fallback to default path instead of opening potentially dangerous file
params_file = os.path.join(EXTENSION_DIR, "shader_params.json")
if not os.path.exists(params_file):
params_file = os.path.join(EXTENSION_DIR, "data", "shader_params.json")
else:
params_file = resolved_path
else:
# Try to find params in root directory first
params_file = os.path.join(EXTENSION_DIR, "shader_params.json")
# If not found, try the data folder
if not os.path.exists(params_file):
params_file = os.path.join(EXTENSION_DIR, "data", "shader_params.json")
# Try to read the shader parameters from the file
try:
if os.path.exists(params_file):
# print(f"Found parameters file: {params_file}")
with open(params_file, 'r') as f:
loaded_params = json.load(f)
# Map between different parameter naming conventions
param_mapping = {
"shaderType": "shader_type",
"shaderScale": "scale",
"shaderOctaves": "octaves",
"shaderWarpStrength": "warp_strength",
"shaderPhaseShift": "phase_shift",
"shapeMaskStrength": "shapemaskstrength",
"shaderShapeStrength": "shapemaskstrength",
"shaderShapeType": "shape_type"
}
# Output raw loaded params for debugging
# print(f"Raw JSON params: {loaded_params}")
# Convert parameter names if needed
params = {}
for key, value in loaded_params.items():
if key in param_mapping:
params[param_mapping[key]] = value
else:
params[key] = value
# Special handling for shaderColorIntensity to maintain both versions
if "shaderColorIntensity" in loaded_params:
# Keep the original key
params["shaderColorIntensity"] = loaded_params["shaderColorIntensity"]
# Also provide as intensity for backward compatibility
params["intensity"] = loaded_params["shaderColorIntensity"]
# Handle specific shader type mapping
if "shader_type" in params:
shader_type = params["shader_type"]
# Convert string values to standardized format
if shader_type.lower() == "tensor_field" or shader_type.lower() == "tensorfield":
params["shader_type"] = "tensor_field"
elif shader_type.lower() == "heterogeneous_fbm" or shader_type.lower() == "heterogeneousfbm":
params["shader_type"] = "heterogeneous_fbm"
elif shader_type.lower() == "projection_3d" or shader_type.lower() == "projection3d":
params["shader_type"] = "projection_3d"
elif shader_type.lower() == "cellular":
params["shader_type"] = "cellular"
elif shader_type.lower() == "fractal":
params["shader_type"] = "fractal"
elif shader_type.lower() == "perlin":
params["shader_type"] = "perlin"
elif shader_type.lower() == "waves":
params["shader_type"] = "waves"
elif shader_type.lower() == "gaussian":
params["shader_type"] = "gaussian"
elif shader_type.lower() == "domain_warp":
params["shader_type"] = "domain_warp"
elif shader_type.lower() == "interference" or shader_type.lower() == "interference_patterns":
params["shader_type"] = "interference_patterns"
print(f"Mapped shader type '{shader_type}' to 'interference_patterns'")
elif shader_type.lower() == "spectral" or shader_type.lower() == "spectral_noise":
params["shader_type"] = "spectral"
print(f"Mapped shader type '{shader_type}' to 'spectral'")
elif shader_type.lower() == "projection" or shader_type.lower() == "projection_3d" or shader_type.lower() == "3d_projection":
params["shader_type"] = "projection_3d"
print(f"Mapped shaderType '{shader_type}' to 'projection_3d'")
elif shader_type.lower() == "curl" or shader_type.lower() == "curl_noise":
params["shader_type"] = "curl_noise"
# print(f"Mapped shaderType '{shader_type}' to 'curl_noise'") # Mapped to curl_noise
# Also check if shader type is in the shaderType field (alternate field name)
if "shaderType" in loaded_params and "shader_type" not in params:
shader_type = loaded_params["shaderType"]
if isinstance(shader_type, str):
if shader_type.lower() == "tensor_field" or shader_type.lower() == "tensorfield":
params["shader_type"] = "tensor_field"
elif shader_type.lower() == "heterogeneous_fbm" or shader_type.lower() == "heterogeneousfbm":
params["shader_type"] = "heterogeneous_fbm"
elif shader_type.lower() == "projection_3d" or shader_type.lower() == "projection3d":
params["shader_type"] = "projection_3d"
elif shader_type.lower() == "cellular":
params["shader_type"] = "cellular"
elif shader_type.lower() == "fractal":
params["shader_type"] = "fractal"
elif shader_type.lower() == "perlin":
params["shader_type"] = "perlin"
elif shader_type.lower() == "waves":
params["shader_type"] = "waves"
elif shader_type.lower() == "gaussian":
params["shader_type"] = "gaussian"
elif shader_type.lower() == "domain_warp":
params["shader_type"] = "domain_warp"
elif shader_type.lower() == "interference" or shader_type.lower() == "interference_patterns":
params["shader_type"] = "interference_patterns"
print(f"Mapped shaderType '{shader_type}' to 'interference_patterns'")
elif shader_type.lower() == "spectral" or shader_type.lower() == "spectral_noise":
params["shader_type"] = "spectral"
print(f"Mapped shaderType '{shader_type}' to 'spectral'")
# Validate and sanitize loaded parameters before merging
params = ShaderParamsReader.validate_and_sanitize_params(params)
# Fill in any missing parameters with defaults
for key, value in default_params.items():
if key not in params:
params[key] = value
# print(f"Successfully loaded shader parameters: {params}")
return params
else:
print(f"Parameters file not found at: {params_file}")
except Exception as e:
print(f"Error loading shader parameters: {e}")
print(f"Using default shader parameters")
return default_params
@staticmethod
def apply_shader_to_noise(noise, shader_params=None, influence=None):
"""
Apply shader effects to the initial noise before sampling
Implements the Sα(N) part of Lt=Sα(N)∘Kβ(t)
Args:
noise: Initial noise tensor [batch, channels, height, width]
shader_params: Dictionary of shader parameters (or None to load from file)
influence: How much to blend shader noise (0.0-1.0, None uses value from params)
Returns:
Modified noise tensor with same shape as input
"""
if shader_params is None:
shader_params = ShaderParamsReader.get_shader_params()
# Extract basic parameters
batch, channels, height, width = noise.shape
device = noise.device
# Use provided influence or get from parameters
if influence is None:
influence = shader_params.get("intensity", 0.8)
# Ensure influence is a float
influence = float(influence)
# Skip if no influence
if influence <= 0.0:
return noise
# Extract shader parameters
shader_type = shader_params.get("shader_type", "tensor_field")
viz_type = shader_params.get("visualization_type", 3) # default to ellipses
scale = shader_params.get("scale", 1.0)
phase_shift = shader_params.get("phase_shift", 0.0)
warp_strength = shader_params.get("warp_strength", 0.5)
time = shader_params.get("time", 0.0)
octaves = shader_params.get("octaves", 3.0)
seed = shader_params.get("seed", 0)
# Extract shape mask parameters
shape_type = shader_params.get("shape_type", "none")
shape_mask_strength = shader_params.get("shapemaskstrength", 1.0)
# Debug print for shape mask parameters
print(f"Shape mask parameters: type={shape_type}, strength={shape_mask_strength}")
# Create coordinate grid (normalized to [-1, 1])
y, x = torch.meshgrid(torch.linspace(-1, 1, height, device=device),
torch.linspace(-1, 1, width, device=device),
indexing='ij')
# Combine into coordinate tensor
p = torch.stack([x, y], dim=-1).unsqueeze(0).repeat(batch, 1, 1, 1)
# Generate different shader patterns
if False: # Placeholder for any future shader types to be handled here
pass # Generate shader_noise for other types if needed
else:
# If the shader type was one of the removed ones or is not handled,
# print a message and return the original noise unchanged.
print(f"Shader type '{shader_type}' is not handled by apply_shader_to_noise or its simple implementation was removed. Returning original noise.")
return noise
# -- REMOVED Unreachable code: permutation, normalization, expansion, blending --
@staticmethod
def _lerp(a, b, t):
"""Helper for linear interpolation."""
return a + (b - a) * t
@staticmethod
def _hsv_to_rgb(h, s, v):
"""
Convert HSV to RGB.
h, s, v are expected in [0,1] range and shape [B, 1, H, W].
Returns R, G, B components, each as [B, 1, H, W] in [0,1] range.
"""
# Ensure inputs are correctly shaped for broadcasting if they are single values
if not isinstance(h, torch.Tensor): h = torch.full_like(s if isinstance(s, torch.Tensor) else v, float(h)) # Fallback for s or v if h is scalar
if not isinstance(s, torch.Tensor): s = torch.full_like(h, float(s))
if not isinstance(v, torch.Tensor): v = torch.full_like(h, float(v))
c = v * s
h_prime = h * 6.0 # h is [0,1]
# Ensure h_prime is a tensor for fmod
if not isinstance(h_prime, torch.Tensor):
h_prime = torch.full_like(c, float(h_prime))
x = c * (1.0 - torch.abs(torch.fmod(h_prime, 2.0) - 1.0))
m = v - c
r, g, b = torch.zeros_like(h), torch.zeros_like(h), torch.zeros_like(h)
# Masks for hue ranges
mask0 = (h_prime < 1.0)
mask1 = (h_prime >= 1.0) & (h_prime < 2.0)
mask2 = (h_prime >= 2.0) & (h_prime < 3.0)
mask3 = (h_prime >= 3.0) & (h_prime < 4.0)
mask4 = (h_prime >= 4.0) & (h_prime < 5.0)
mask5 = (h_prime >= 5.0) # covers up to 6.0
# Assign R, G, B based on hue
r[mask0], g[mask0], b[mask0] = c[mask0], x[mask0], torch.zeros_like(x)[mask0]
r[mask1], g[mask1], b[mask1] = x[mask1], c[mask1], torch.zeros_like(x)[mask1]
r[mask2], g[mask2], b[mask2] = torch.zeros_like(x)[mask2], c[mask2], x[mask2]
r[mask3], g[mask3], b[mask3] = torch.zeros_like(x)[mask3], x[mask3], c[mask3]
r[mask4], g[mask4], b[mask4] = x[mask4], torch.zeros_like(x)[mask4], c[mask4]
r[mask5], g[mask5], b[mask5] = c[mask5], torch.zeros_like(x)[mask5], x[mask5]
r, g, b = r + m, g + m, b + m
return r, g, b
@staticmethod
def _interpolate_colors(stops, t):
"""
Interpolate colors based on stops using vectorized operations.
t is a normalized value tensor [B, 1, H, W] in [0,1] range.
stops: list of [value, color_tuple_or_tensor e.g. (R,G,B) or [1,3,1,1] tensor].
Returns R, G, B components, each as [B, 1, H, W] in [0,1] range.
"""
device = t.device
dtype = t.dtype
# Prepare stops tensors
stop_vals = []
stop_colors = []
for val, color_val in stops:
stop_vals.append(float(val))
if isinstance(color_val, (list, tuple)):
c_tensor = torch.tensor(color_val, device=device, dtype=dtype).view(1, 3, 1, 1)
else: # assume it's already a tensor
c_tensor = color_val.to(device=device, dtype=dtype)
if c_tensor.numel() == 3:
c_tensor = c_tensor.view(1, 3, 1, 1)
stop_colors.append(c_tensor)
# Create tensors for bucketize/gather
stop_vals_tensor = torch.tensor(stop_vals, device=device, dtype=dtype)
# Concatenate colors to [num_stops, 3] for indexing (remove spatial dims for now)
stop_colors_stack = torch.cat([c.view(1, 3) for c in stop_colors], dim=0)
# Find indices where elements should be inserted to maintain order
# bucketize returns indices such that stop_vals[i-1] <= t < stop_vals[i]
indices = torch.bucketize(t, stop_vals_tensor)
# Clamp indices to be within [1, num_stops-1]
# This ensures we always have a valid previous stop (idx-1) and current stop (idx)
# For t < stops[0], indices=0 -> clamped to 1. Uses segment (stops[0], stops[1]).
# For t >= stops[-1], indices=num_stops -> clamped to num_stops-1. Uses segment (stops[-2], stops[-1]).
idxs = torch.clamp(indices, 1, len(stops) - 1)
# Gather start and end values/colors for each pixel's segment
# idxs is [B, 1, H, W], stop_vals_tensor is [N]
# Advanced indexing: we want result [B, 1, H, W]
# Flatten t and idxs for simpler gathering if needed, but PyTorch handles this
t0 = stop_vals_tensor[idxs - 1] # [B, 1, H, W]
t1 = stop_vals_tensor[idxs] # [B, 1, H, W]
# Gather colors
# stop_colors_stack is [N, 3]. idxs is [B, 1, H, W]
# c0 will be [B, 1, H, W, 3]
c0 = stop_colors_stack[idxs - 1]
c1 = stop_colors_stack[idxs]
# Permute to [B, 3, H, W] and squeeze singleton dimension from original idxs indexing
# Note: Indexing with [B, 1, H, W] into [N, 3] creates [B, 1, H, W, 3]
c0 = c0.permute(0, 4, 2, 3, 1).squeeze(-1) # [B, 3, H, W]
c1 = c1.permute(0, 4, 2, 3, 1).squeeze(-1) # [B, 3, H, W]
# Calculate local interpolation factor
denominator = (t1 - t0)
# Avoid division by zero
safe_denominator = torch.where(torch.abs(denominator) < 1e-8, torch.ones_like(denominator), denominator)
local_t = (t - t0) / safe_denominator
local_t = torch.clamp(local_t, 0.0, 1.0) # [B, 1, H, W]
# Interpolate
# c0, c1 are [B, 3, H, W], local_t is [B, 1, H, W] (broadcasts)
final_color = ShaderParamsReader._lerp(c0, c1, local_t)
# Handle strict out of bounds values (below first stop or above last stop)
# If t < stop[0], local_t was computed relative to stop[0] and stop[1].
# It will be negative, clamped to 0. So result = c0 = stop[0]. Correct.
# If t > stop[-1], local_t > 1, clamped to 1. Result = c1 = stop[-1]. Correct.
return final_color[:, 0:1], final_color[:, 1:2], final_color[:, 2:3]
@staticmethod
def apply_color_scheme(noise_tensor, shader_params=None):
"""
Apply color scheme to a shader noise tensor based on shader_params
Args:
noise_tensor: Input noise tensor of shape [batch, channels, height, width]
shader_params: Dictionary of shader parameters (or None to load from file)
Returns:
Modified noise tensor with color scheme applied
"""
if shader_params is None:
shader_params = ShaderParamsReader.get_shader_params()
# Get color scheme and intensity parameters
color_scheme = shader_params.get("colorScheme", "none")
# Try to get the color intensity with priority for shaderColorIntensity
color_intensity = shader_params.get("shaderColorIntensity",
shader_params.get("intensity", 0.8))
# Skip if no color scheme or zero intensity
if color_scheme == "none" or color_intensity <= 0.0:
print(f"Skipping color scheme application: scheme={color_scheme}, intensity={color_intensity}")
return noise_tensor
print(f"APPLYING COLOR SCHEME: {color_scheme} with intensity {color_intensity}")
# Extract dimensions
batch, channels, height, width = noise_tensor.shape
device = noise_tensor.device
# Create empty color tensor that we'll fill based on the scheme
color_tensor = torch.zeros_like(noise_tensor)
# Make sure to preserve the 4th channel if it exists
if channels > 3:
color_tensor[:, 3:] = noise_tensor[:, 3:]
# Helper function to normalize the noise to 0-1 range for colormaps
def normalize_to_01(tensor):
return (tensor - tensor.min()) / (tensor.max() - tensor.min() + 1e-8)
# Map base noise to 0-1 for color mapping
base_noise = normalize_to_01(noise_tensor[:, 0])
# Create a [B, 1, H, W] version of base_noise for helpers
t_color = base_noise.unsqueeze(1)
# Handle different color schemes
if color_scheme == "rgb":
# RGB color scheme: create three distinct channels
if channels >= 3:
# R channel - emphasize details in first latent dimension
color_tensor[:, 0] = noise_tensor[:, 0] * 1.5
# G channel - use second latent dimension with slight phase shift
color_tensor[:, 1] = noise_tensor[:, 1] * 1.3
# B channel - use third latent dimension with different scaling
color_tensor[:, 2] = noise_tensor[:, 2] * 0.8
elif color_scheme == "complementary":
# Complementary colors: create opposing patterns in different channels
if channels >= 3:
# First channel - original
color_tensor[:, 0] = noise_tensor[:, 0] * 1.5
# Second channel - inverted phase from channel 0
color_tensor[:, 1] = -noise_tensor[:, 0] * 0.8
# Third channel - different frequency
color_tensor[:, 2] = noise_tensor[:, 2] * 1.2
elif color_scheme == "monochrome":
# Monochrome: apply the same pattern to all channels with slight variations
if channels > 1:
base_channel = noise_tensor[:, 0:1].clone()
# Expand to all channels with slight variations in scaling
scales = torch.tensor([1.0, 0.95, 0.9, 0.85][:channels], device=device).view(1, -1, 1, 1)
color_tensor = base_channel * scales
elif color_scheme == "gradient":
# Gradient: create a position-based color gradient
if channels >= 3:
# Create coordinate grid for gradient
y_norm = torch.linspace(0, 1, height, device=device).view(1, 1, -1, 1).expand(batch, 1, -1, width)
x_norm = torch.linspace(0, 1, width, device=device).view(1, 1, 1, -1).expand(batch, 1, height, -1)
# R channel - horizontal gradient + noise
color_tensor[:, 0:1] = x_norm + noise_tensor[:, 0:1] * 0.4
# G channel - vertical gradient + noise
color_tensor[:, 1:2] = y_norm + noise_tensor[:, 1:2] * 0.4
# B channel - diagonal gradient + noise
color_tensor[:, 2:3] = (x_norm + y_norm) / 2 + noise_tensor[:, 2:3] * 0.4
elif color_scheme == "blue_red":
if channels >= 3:
# Blue to red gradient (cold to hot) using lerp
c0 = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Blue
c1 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Red
# _lerp expects t_color to be broadcastable with c0, c1.
# t_color is [B,1,H,W], c0/c1 are [1,3,1,1]. Result is [B,3,H,W]
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1] = interpolated_color[:, 0:1] # Red
color_tensor[:, 1:2] = interpolated_color[:, 1:2] # Green
color_tensor[:, 2:3] = interpolated_color[:, 2:3] # Blue
elif color_scheme == "viridis":
if channels >= 3:
stops = [
(0.0, (0.267, 0.005, 0.329)), # #440154
(0.33, (0.188, 0.407, 0.553)), # #30678D
(0.66, (0.208, 0.718, 0.471)), # #35B778
(1.0, (0.992, 0.906, 0.143)) # #FDE724
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "plasma":
if channels >= 3:
# Use robust color stops for plasma, matching curl_noise.py
stops = [
(0.0, (0.05, 0.03, 0.53)),
(0.25, (0.40, 0.00, 0.66)),
(0.5, (0.70, 0.18, 0.53)),
(0.75, (0.94, 0.46, 0.25)),
(1.0, (0.98, 0.80, 0.08))
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "inferno":
if channels >= 3:
stops = [
(0.0, (0.001, 0.001, 0.016)),
(0.25, (0.259, 0.039, 0.408)),
(0.5, (0.576, 0.149, 0.404)),
(0.75, (0.867, 0.318, 0.227)),
(0.85, (0.988, 0.647, 0.039)),
(1.0, (0.988, 1.000, 0.643))
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "magma":
if channels >= 3:
stops = [
(0.0, (0.001, 0.001, 0.016)),
(0.25, (0.231, 0.059, 0.439)),
(0.5, (0.549, 0.161, 0.506)),
(0.75, (0.871, 0.288, 0.408)),
(0.85, (0.996, 0.624, 0.427)),
(1.0, (0.988, 0.992, 0.749))
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "turbo":
if channels >= 3:
stops = [
(0.0, (0.188, 0.071, 0.235)),
(0.25, (0.275, 0.408, 0.859)),
(0.5, (0.149, 0.749, 0.549)),
(0.65, (0.831, 1.000, 0.314)),
(0.85, (0.980, 0.718, 0.298)),
(1.0, (0.729, 0.004, 0.000))
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
# Turbo often benefits from a slight boost/rescale
r, g, b = r * 1.2 - 0.1, g * 1.2 - 0.1, b * 1.2 - 0.1
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = torch.clamp(r, 0, 1), torch.clamp(g, 0, 1), torch.clamp(b, 0, 1)
elif color_scheme == "jet":
if channels >= 3:
stops = [
(0.0, (0.000, 0.000, 0.5)), # Dark Blue
(0.125, (0.000, 0.000, 1.000)),# Blue
(0.375, (0.000, 1.000, 1.000)),# Cyan
(0.625, (1.000, 1.000, 0.000)),# Yellow
(0.875, (1.000, 0.000, 0.000)),# Red
(1.0, (0.500, 0.000, 0.000)) # Dark Red
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "rainbow":
if channels >= 3:
# Use HSV to RGB for rainbow: hue from t_color, constant saturation and value
hue = t_color # base_noise is already [B,1,H,W] and [0,1]
saturation = torch.ones_like(hue) * 0.9 # High saturation
value = torch.ones_like(hue) * 0.9 # Bright value
r, g, b = ShaderParamsReader._hsv_to_rgb(hue, saturation, value)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "cool":
if channels >= 3:
c0 = torch.tensor([0.0, 1.0, 1.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Cyan
c1 = torch.tensor([1.0, 0.0, 1.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Magenta
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = interpolated_color[:,0:1], interpolated_color[:,1:2], interpolated_color[:,2:3]
elif color_scheme == "hot":
if channels >= 3:
stops = [
(0.0, (0.0, 0.0, 0.0)), # Black
(0.375, (1.0, 0.0, 0.0)), # Red
(0.75, (1.0, 1.0, 0.0)), # Yellow
(1.0, (1.0, 1.0, 1.0)) # White
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "parula":
if channels >= 3:
stops = [
(0.0, (0.208, 0.165, 0.529)), # #352a87
(0.25, (0.059, 0.361, 0.867)), # #0f5cdd
(0.5, (0.000, 0.710, 0.651)), # #00b5a6
(0.75, (1.000, 0.765, 0.216)), # #ffc337
(1.0, (0.988, 0.996, 0.643)) # #fcfea4
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "hsv":
if channels >= 3:
hue = t_color
saturation = torch.ones_like(hue) * 0.95 # Full saturation
value = torch.ones_like(hue) * 0.95 # Full value
r, g, b = ShaderParamsReader._hsv_to_rgb(hue, saturation, value)
# Original SPR HSV scaled output to [-1,1]. We keep [0,1] from _hsv_to_rgb for consistency with other interpolated.
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "autumn":
if channels >= 3:
c0 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Red
c1 = torch.tensor([1.0, 1.0, 0.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Yellow
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = interpolated_color[:,0:1], interpolated_color[:,1:2], interpolated_color[:,2:3]
elif color_scheme == "winter":
if channels >= 3:
c0 = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Blue
c1 = torch.tensor([0.0, 1.0, 0.5], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Greenish-Cyan
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = interpolated_color[:,0:1], interpolated_color[:,1:2], interpolated_color[:,2:3]
elif color_scheme == "spring":
if channels >= 3:
c0 = torch.tensor([1.0, 0.0, 1.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Magenta
c1 = torch.tensor([1.0, 1.0, 0.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Yellow
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = interpolated_color[:,0:1], interpolated_color[:,1:2], interpolated_color[:,2:3]
elif color_scheme == "summer":
if channels >= 3:
c0 = torch.tensor([0.0, 0.5, 0.4], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Dark Green
c1 = torch.tensor([1.0, 1.0, 0.4], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Yellow
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = interpolated_color[:,0:1], interpolated_color[:,1:2], interpolated_color[:,2:3]
elif color_scheme == "copper":
if channels >= 3:
c0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Black
c1 = torch.tensor([1.0, 0.6235, 0.3922], device=device, dtype=t_color.dtype).view(1, 3, 1, 1) # Copper color approx (255,159,100)
interpolated_color = ShaderParamsReader._lerp(c0, c1, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = interpolated_color[:,0:1], interpolated_color[:,1:2], interpolated_color[:,2:3]
elif color_scheme == "pink":
if channels >= 3:
stops = [
(0.0, (0.05, 0.05, 0.05)), # Dark gray
(0.5, (1.0, 0.41, 0.71)), # Hot Pink approx
(1.0, (1.0, 0.75, 0.80)) # Light Pink
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "bone":
if channels >= 3:
stops = [ # Standard bone colormap
(0.0, (0.0, 0.0, 0.0)),
(0.375, (0.3294, 0.3294, 0.4549)), # (84, 84, 116)
(0.75, (0.6275, 0.7569, 0.7569)), # (160, 193, 193)
(1.0, (1.0, 1.0, 1.0))
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
# Original shader_params_reader 'bone' scaled to [-1,1]. Let's keep [0,1] for consistency.
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "ocean":
if channels >= 3:
stops = [ # Based on matplotlib's ocean
(0.0, (0.0, 0.0, 0.0)), # Black
(0.33, (0.0, 0.0, 0.5)), # Dark Blue
(0.66, (0.0, 0.5, 1.0)), # Light Blue
(1.0, (0.7, 1.0, 1.0)) # Very Light Cyan/White
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "terrain":
if channels >= 3:
stops = [ # Standard terrain colormap
(0.0, (0.2, 0.2, 0.6)), # Deep water blue
(0.15, (0.0, 0.5, 0.0)), # Dark Green (low land)
(0.33, (0.0, 0.8, 0.4)), # Green (land)
(0.5, (0.87, 0.87, 0.4)), # Yellowish (hills)
(0.75, (0.6, 0.4, 0.2)), # Brown (mountains)
(1.0, (1.0, 1.0, 1.0)) # White (snow peaks)
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "neon":
if channels >= 3:
# Using a multi-stop lerp for vibrant neon effect
stops = [
(0.0, (1.0, 0.0, 0.5)), # Magenta
(0.33, (0.0, 1.0, 1.0)), # Cyan
(0.66, (1.0, 1.0, 0.0)), # Yellow
(1.0, (0.5, 0.0, 1.0)) # Purple
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "fire":
if channels >= 3:
stops = [ # Standard fire colormap
(0.0, (0.0, 0.0, 0.0)), # Black
(0.25, (1.0, 0.0, 0.0)), # Red
(0.6, (1.0, 1.0, 0.0)), # Yellow
(1.0, (1.0, 1.0, 1.0)) # White
]
r, g, b = ShaderParamsReader._interpolate_colors(stops, t_color)
color_tensor[:, 0:1], color_tensor[:, 1:2], color_tensor[:, 2:3] = r, g, b
elif color_scheme == "fantasy":
# Fantasy colors: magical and otherworldly - keeping original SPR logic
if channels >= 3:
# Create swirling color pattern
angle = torch.atan2(noise_tensor[:, 1], noise_tensor[:, 0])
radius = torch.sqrt(noise_tensor[:, 0]**2 + noise_tensor[:, 1]**2)
# Purple/pink base
color_tensor[:, 0] = torch.sin(angle * 2.0 + radius * 3.0) * 0.5 + 0.5
# Teal/blue variations
color_tensor[:, 1] = torch.sin(angle * 3.0 - radius * 2.0) * 0.5 + 0.5
# Golden highlights
color_tensor[:, 2] = torch.sin(radius * 5.0) * 0.5 + 0.5
# Normalize to maintain proper distribution
color_tensor = (color_tensor - 0.5) * 2.0
else:
# Default case - return original noise if color scheme not implemented or recognized
print(f"WARNING: Color scheme '{color_scheme}' not recognized, using original noise")
return noise_tensor
# Blend with original based on intensity
# Ensure color_tensor values are appropriately scaled if necessary before blending.
# For now, assuming [0,1] range from most new schemes is acceptable for blending.
result = noise_tensor * (1.0 - color_intensity) + color_tensor * color_intensity
print(f"Applied {color_scheme} color scheme - result shape: {result.shape}")
return result
@staticmethod
def apply_shape_mask(coords_normalized_01, shape_type, time=0.0, base_seed=0, use_temporal_coherence=False):
"""
Apply shape mask to coordinates.
Coordinates are expected to be in the [0, 1] range.
Args:
coords_normalized_01: Coordinate tensor [batch, height, width, 2] in [0, 1] range.
shape_type: Type of shape to apply (integer or string).
time: Animation time.
base_seed: Base seed for randomness if shapes require it.
use_temporal_coherence: Flag for temporal coherence.
Returns:
Shape mask tensor [batch, height, width, 1]
"""
batch, height, width, _ = coords_normalized_01.shape
device = coords_normalized_01.device
# For shapes that assume coordinates centered at (0,0) and range approx [-0.5, 0.5] or [-1,1]
# we create centered coordinates from the [0,1] input.
centered_coords = coords_normalized_01 - 0.5 # Now in [-0.5, 0.5] range
# Distance from center for centered_coords
center_dist = torch.sqrt(centered_coords[:, :, :, 0]**2 + centered_coords[:, :, :, 1]**2) # Max dist ~0.707
# Angle from center for centered_coords
angle = torch.atan2(centered_coords[:, :, :, 1], centered_coords[:, :, :, 0])
# Default mask
mask_output = torch.ones((batch, height, width), device=device)
# Convert string shape_type to standardized string format
if isinstance(shape_type, str):
shape_type = shape_type.lower()
# Handle both numeric and string shape types