import matplotlib.pyplot as plt
# Define the directory to save the gradient assets
os.makedirs(output_dir, exist_ok=True)
# List of Matplotlib colormaps to include
colormaps = ['viridis', 'inferno', 'plasma', 'magma', 'cividis']
# Dictionary to store the colormap data
for cmap_name in colormaps:
cmap = plt.get_cmap(cmap_name)
colors = cmap(np.linspace(0, 1, 256)) # 256 samples from the colormap
color_list = [list(color[:3]) for color in colors] # Extract RGB values
colormap_data[cmap_name] = color_list
# Template for Unity Gradient ScriptableObject
m_NumColorKeys: {num_color_keys}
m_NumAlphaKeys: {num_alpha_keys}
# Function to format color keys
def format_color_keys(colors):
for i, color in enumerate(colors):
color_str = f" key{i}: {{r: {color[0]}, g: {color[1]}, b: {color[2]}, a: 1}}\n"
color_keys.append(color_str)
ctimes.append(f" ctime{i}: {int(i * 65535 / (len(colors) - 1))}\n")
# Fill the remaining keys with default values
for i in range(len(colors), 8):
color_keys.append(f" key{i}: {{r: 0, g: 0, b: 0, a: 0}}\n")
ctimes.append(f" ctime{i}: 0\n")
return ''.join(color_keys) + ''.join(ctimes)
# Function to format alpha keys
def format_alpha_keys(colors):
for i in range(len(colors)):
alpha_keys.append(f" atime{i}: {int(i * 65535 / (len(colors) - 1))}\n")
atimes.append(f" atime{i}: {int(i * 65535 / (len(colors) - 1))}\n")
# Fill the remaining keys with default values
for i in range(len(colors), 8):
alpha_keys.append(f" atime{i}: 0\n")
atimes.append(f" atime{i}: 0\n")
return ''.join(alpha_keys) + ''.join(atimes)
# Generate Unity gradient library file
gradients_library_content = """%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Script: {fileID: 12321, guid: 0000000000000000e000000000000000, type: 0}
for cmap_name, colors in colormap_data.items():
# Reduce the number of keys to 8
reduced_colors = [colors[i] for i in np.linspace(0, len(colors) - 1, 8, dtype=int)]
color_keys = format_color_keys(reduced_colors)
alpha_keys = format_alpha_keys(reduced_colors)
gradient_asset = gradient_template.format(
num_color_keys=min(8, len(reduced_colors)),
num_alpha_keys=min(8, len(reduced_colors))
gradients_library_content += gradient_asset
gradients_library_content += " m_NumColorKeys: 2\n m_NumAlphaKeys: 2\n"
output_file = os.path.join(output_dir, "gradients_library.gradients")
with open(output_file, 'w') as f:
f.write(gradients_library_content)
print("Unity gradients library file created successfully.")