Commit 91d5c210 authored by Campbell Barton's avatar Campbell Barton
Browse files

Cleanup: tabs -> spaces

parent 5c755ab5
# Copyright 2015 Théo Friberg under GNU GPL 3
if "bpy" in locals():
import importlib
importlib.reload(JSONOps)
import importlib
importlib.reload(JSONOps)
else:
from . import JSONOps
from . import JSONOps
import bpy
import os
......
# Copyright 2015 Théo Friberg under GNU GPL 3
if "bpy" in locals():
import importlib
importlib.reload(JSONOps)
import importlib
importlib.reload(JSONOps)
else:
from . import JSONOps
from . import JSONOps
import bpy
import os
......@@ -12,184 +12,184 @@ import glob
class AutomatOperatorFromTexture(bpy.types.Operator):
"""This operator generates automatic materials from textures in Cycles."""
"""This operator generates automatic materials from textures in Cycles."""
# Metadata of the operator
# Metadata of the operator
bl_idname = "com.new_automat"
bl_label = "Automatic Material from Image"
bl_options = {"UNDO"}
bl_idname = "com.new_automat"
bl_label = "Automatic Material from Image"
bl_options = {"UNDO"}
# Variables used for storing the filepath given by blender's file manager
# Variables used for storing the filepath given by blender's file manager
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
filename: bpy.props.StringProperty()
directory: bpy.props.StringProperty(subtype="FILE_PATH")
filepath: bpy.props.StringProperty(subtype="FILE_PATH")
filename: bpy.props.StringProperty()
directory: bpy.props.StringProperty(subtype="FILE_PATH")
make_seamless: bpy.props.BoolProperty(name="Make Seamless", description="Make tileable (removes visible borders of the image).")
make_seamless: bpy.props.BoolProperty(name="Make Seamless", description="Make tileable (removes visible borders of the image).")
def execute(self, context):
def execute(self, context):
"""This is the main runnable method of the operator.
"""This is the main runnable method of the operator.
This creates all the node setup."""
# Create the material
# Create the material
mat = bpy.data.materials.new(self.filename)
mat = bpy.data.materials.new(self.filename)
mat.use_nodes = True
nodes = mat.node_tree.nodes
mat.use_nodes = True
nodes = mat.node_tree.nodes
# Empty whatever nodes we allready had.
# Empty whatever nodes we allready had.
for node in nodes.keys():
nodes.remove(nodes[node])
for node in nodes.keys():
nodes.remove(nodes[node])
nodes_dict = {}
nodes_dict = {}
# Create the main part of the material
# Create the main part of the material
nodes_dict = JSONOps.inflateFile(mat, os.path.dirname(
os.path.realpath(__file__))+os.sep+
"automatic_material.json")
nodes_dict = JSONOps.inflateFile(mat, os.path.dirname(
os.path.realpath(__file__))+os.sep+
"automatic_material.json")
# We load the images
# We load the images
image_data = bpy.data.images.load(self.filepath)
nodes_dict["Color Image"].image = image_data
image_data = bpy.data.images.load(self.filepath)
nodes_dict["Color Image"].image = image_data
# We check if the texture must be made seamless
# We check if the texture must be made seamless
if self.make_seamless:
seamless_vector = JSONOps.inflateFile(mat, os.path.dirname(os.path.realpath(__file__))+os.sep+"seamless_vector.json", -3000, 0)
links = mat.node_tree.links
links.new(seamless_vector["Pick Vector"].outputs["Color"], nodes_dict["Color Image"].inputs["Vector"])
if self.make_seamless:
seamless_vector = JSONOps.inflateFile(mat, os.path.dirname(os.path.realpath(__file__))+os.sep+"seamless_vector.json", -3000, 0)
links = mat.node_tree.links
links.new(seamless_vector["Pick Vector"].outputs["Color"], nodes_dict["Color Image"].inputs["Vector"])
# Below we check potential maps
# Below we check potential maps
modified_fname = self.filename.split(".")
modified_fname = self.filename.split(".")
# Check if we are dealing with maps generated with CrazyBump.
# If so is the case, the color map is by default suffixed with _COLOR
# Check if we are dealing with maps generated with CrazyBump.
# If so is the case, the color map is by default suffixed with _COLOR
known_scheme = False
known_scheme = False
if modified_fname[0][-6:] == "_COLOR":
if modified_fname[0][-6:] == "_COLOR":
# We are dealing with CrazyBump and we remove the suffix
# We are dealing with CrazyBump and we remove the suffix
modified_fname[0] = modified_fname[0][:-6]
known_scheme = True
modified_fname[0] = modified_fname[0][:-6]
known_scheme = True
other_files = []
folder = os.path.split(self.filepath)[0]+os.path.sep+"*"
pattern = folder + ".".join(modified_fname[:-1])+"*."+modified_fname[-1]
other_files = glob.glob(pattern)
other_files = []
folder = os.path.split(self.filepath)[0]+os.path.sep+"*"
pattern = folder + ".".join(modified_fname[:-1])+"*."+modified_fname[-1]
other_files = glob.glob(pattern)
# We check if we can find a Specularity Map
# We check if we can find a Specularity Map
specmap = ""
specmap = ""
for file in other_files:
if "spec" in os.path.split(file)[-1].lower():
specmap = file
break
for file in other_files:
if "spec" in os.path.split(file)[-1].lower():
specmap = file
break
if len(specmap) > 0:
if len(specmap) > 0:
spec_map = nodes.new("ShaderNodeTexImage")
spec_map.location = [nodes_dict["Adjust reflectivity"].location[0],
nodes_dict["Adjust reflectivity"].location[1]+50]
spec_map.label = "Specularity Map"
nodes.remove(nodes_dict["Adjust reflectivity"])
spec_map.image = bpy.data.images.load(specmap)
links = mat.node_tree.links
spec_map = nodes.new("ShaderNodeTexImage")
spec_map.location = [nodes_dict["Adjust reflectivity"].location[0],
nodes_dict["Adjust reflectivity"].location[1]+50]
spec_map.label = "Specularity Map"
nodes.remove(nodes_dict["Adjust reflectivity"])
spec_map.image = bpy.data.images.load(specmap)
links = mat.node_tree.links
links.new(spec_map.outputs["Color"],
nodes_dict["Mix Shaders"].inputs[0])
if self.make_seamless:
links.new(seamless_vector["Pick Vector"].outputs["Color"], spec_map.inputs["Vector"])
links.new(spec_map.outputs["Color"],
nodes_dict["Mix Shaders"].inputs[0])
if self.make_seamless:
links.new(seamless_vector["Pick Vector"].outputs["Color"], spec_map.inputs["Vector"])
# We check if we can find a Normal Map
# We check if we can find a Normal Map
normalmap = ""
normalmap = ""
for file in other_files:
if "normal" in os.path.split(file)[-1].lower() or ".".join(os.path.split(file)[1].split(".") [:-1])[-4:] == "_NRM":
normalmap = file
break
for file in other_files:
if "normal" in os.path.split(file)[-1].lower() or ".".join(os.path.split(file)[1].split(".") [:-1])[-4:] == "_NRM":
normalmap = file
break
if len(normalmap) > 0 and ((not "normal" in self.filename.lower()) or known_scheme):
if len(normalmap) > 0 and ((not "normal" in self.filename.lower()) or known_scheme):
normal_map = nodes.new("ShaderNodeTexImage")
normal_map.location = [nodes_dict["Color Image"].location[0],
nodes_dict["Color Image"].location[1]-240]
normal_map.label = "Normal Map"
normal_map.image = bpy.data.images.load(normalmap)
links = mat.node_tree.links
normal_map = nodes.new("ShaderNodeTexImage")
normal_map.location = [nodes_dict["Color Image"].location[0],
nodes_dict["Color Image"].location[1]-240]
normal_map.label = "Normal Map"
normal_map.image = bpy.data.images.load(normalmap)
links = mat.node_tree.links
normal = nodes.new("ShaderNodeNormalMap")
normal.location = [nodes_dict["Convert to Bump Map"].location[0],
nodes_dict["Convert to Bump Map"].location[1]]
nodes.remove(nodes_dict["Convert to Bump Map"])
links.new(normal_map.outputs["Color"],
normal.inputs[1])
links.new(normal.outputs["Normal"],
nodes_dict["Diffuse Component"].inputs[2])
links.new(normal.outputs["Normal"],
nodes_dict["Glossy Component"].inputs[2])
if self.make_seamless:
links.new(seamless_vector["Pick Vector"].outputs["Color"], normal_map.inputs["Vector"])
normal = nodes.new("ShaderNodeNormalMap")
normal.location = [nodes_dict["Convert to Bump Map"].location[0],
nodes_dict["Convert to Bump Map"].location[1]]
nodes.remove(nodes_dict["Convert to Bump Map"])
links.new(normal_map.outputs["Color"],
normal.inputs[1])
links.new(normal.outputs["Normal"],
nodes_dict["Diffuse Component"].inputs[2])
links.new(normal.outputs["Normal"],
nodes_dict["Glossy Component"].inputs[2])
if self.make_seamless:
links.new(seamless_vector["Pick Vector"].outputs["Color"], normal_map.inputs["Vector"])
# We check if we can find a Bump Map
# We check if we can find a Bump Map
bumpmap = ""
bumpmap = ""
for file in other_files:
if "bump" in os.path.split(file.lower())[-1]:
bumpmap = file
break
for file in other_files:
if "bump" in os.path.split(file.lower())[-1]:
bumpmap = file
break
if len(bumpmap) > 0 and not "bump" in self.filename.lower() and not len(normalmap) > 0:
if len(bumpmap) > 0 and not "bump" in self.filename.lower() and not len(normalmap) > 0:
bump_map = nodes.new("ShaderNodeTexImage")
bump_map.location = [nodes_dict["Color Image"].location[0],
nodes_dict["Color Image"].location[1]-240]
bump_map.label = "Bump Map"
bump_map.image = bpy.data.images.load(bumpmap)
links = mat.node_tree.links
links.new(bump_map.outputs["Color"], nodes_dict["Convert to Bump Map"].inputs[2])
if self.make_seamless:
links.new(seamless_vector["Pick Vector"].outputs["Color"], bump_map.inputs["Vector"])
bump_map = nodes.new("ShaderNodeTexImage")
bump_map.location = [nodes_dict["Color Image"].location[0],
nodes_dict["Color Image"].location[1]-240]
bump_map.label = "Bump Map"
bump_map.image = bpy.data.images.load(bumpmap)
links = mat.node_tree.links
links.new(bump_map.outputs["Color"], nodes_dict["Convert to Bump Map"].inputs[2])
if self.make_seamless:
links.new(seamless_vector["Pick Vector"].outputs["Color"], bump_map.inputs["Vector"])
# Try to add the material to the selected object
try:
bpy.context.object.data.materials.append(mat)
except AttributeError:
# Try to add the material to the selected object
try:
bpy.context.object.data.materials.append(mat)
except AttributeError:
# If there is no object with materials selected,
# don't add the material to anythinng.
# If there is no object with materials selected,
# don't add the material to anythinng.
pass
pass
# Tell that all went well
# Tell that all went well
return {"FINISHED"}
return {"FINISHED"}
def invoke(self, context, event):
def invoke(self, context, event):
"""This method opens the file browser. After that, the
"""This method opens the file browser. After that, the
execute(...) method gets ran, creating the node setup.
It also checks that the render engine is Cycles. """
if bpy.context.scene.render.engine == 'CYCLES':
self.filename = ""
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
else:
self.report({'ERROR'}, "Can't generate Cycles material with Blender"
"internal as active renderer.")
return {"FINISHED"}
if bpy.context.scene.render.engine == 'CYCLES':
self.filename = ""
context.window_manager.fileselect_add(self)
return {"RUNNING_MODAL"}
else:
self.report({'ERROR'}, "Can't generate Cycles material with Blender"
"internal as active renderer.")
return {"FINISHED"}
# Copyright 2015 Théo Friberg under GNU GPL 3
bl_info = {
"name": "Cycles Automatic Materials",
"author": "Théo Friberg",
"blender": (2, 80, 0),
"version": (0, 39),
"location": "Space > Automatic / Adjustable Material from Image",
"description": "One-click material setup from texture for Cycles. Blur from b°wide node pack.",
"warning": "Still a work in progress",
"doc_url": "",
"tracker_url": "mailto:theo.friberg@gmail.com?subject="
"Bug report for Cycles Automatic Materials addon&body="
"I have come across the following error while using the Cycles automatic"
" materials addon (Please explain both the symptoms of the error and"
" what you were doing when the error occured. If you think a specific"
" action of yours is related to the error, please include a description"
" of it too.):",
"support": "COMMUNITY",
"category": "Render"
"name": "Cycles Automatic Materials",
"author": "Théo Friberg",
"blender": (2, 80, 0),
"version": (0, 39),
"location": "Space > Automatic / Adjustable Material from Image",
"description": "One-click material setup from texture for Cycles. Blur from b°wide node pack.",
"warning": "Still a work in progress",
"doc_url": "",
"tracker_url": "mailto:theo.friberg@gmail.com?subject="
"Bug report for Cycles Automatic Materials addon&body="
"I have come across the following error while using the Cycles automatic"
" materials addon (Please explain both the symptoms of the error and"
" what you were doing when the error occured. If you think a specific"
" action of yours is related to the error, please include a description"
" of it too.):",
"support": "COMMUNITY",
"category": "Render"
}
if "bpy" in locals():
import importlib
importlib.reload(JSONOps)
importlib.reload(AutoOp)
importlib.reload(AdjOp)
import importlib
importlib.reload(JSONOps)
importlib.reload(AutoOp)
importlib.reload(AdjOp)
else:
from . import JSONOps
from . import AutoOp
from . import AdjOp
from . import JSONOps
from . import AutoOp
from . import AdjOp
import bpy
......@@ -42,23 +42,23 @@ def menu_draw(self, context):
def register():
"""This method registers the AutomatOperatorFromTexture
"""This method registers the AutomatOperatorFromTexture
operator and the AdjustableOperatorFromTexture operator. """
bpy.utils.register_class(AutoOp.AutomatOperatorFromTexture)
bpy.utils.register_class(AdjOp.AdjustableOperatorFromTexture)
bpy.types.TOPBAR_MT_file_import.append(menu_draw)
bpy.utils.register_class(AutoOp.AutomatOperatorFromTexture)
bpy.utils.register_class(AdjOp.AdjustableOperatorFromTexture)
bpy.types.TOPBAR_MT_file_import.append(menu_draw)
def unregister():
"""This method unregisters the AutomatOperatorFromTexture
"""This method unregisters the AutomatOperatorFromTexture
operator and the AdjustableOperatorFromTexture operator. """
bpy.types.TOPBAR_MT_file_import.remove(menu_draw)
bpy.utils.unregister_class(AutoOp.AutomatOperatorFromTexture)
bpy.utils.unregister_class(AdjOp.AdjustableOperatorFromTexture)
bpy.types.TOPBAR_MT_file_import.remove(menu_draw)
bpy.utils.unregister_class(AutoOp.AutomatOperatorFromTexture)
bpy.utils.unregister_class(AdjOp.AdjustableOperatorFromTexture)
# Run register if the file is ran from blenders text editor
if __name__ == "__main__":
register()
register()
......@@ -279,7 +279,7 @@ def process_next_chunk(context, file, previous_chunk, importedObjects, IMAGE_SEA
TEXTURE_DICT = {}
MATDICT = {}
# TEXMODE = Mesh.FaceModes['TEX']
# TEXMODE = Mesh.FaceModes['TEX']
# Localspace variable names, faster.
STRUCT_SIZE_FLOAT = struct.calcsize('f')
......@@ -497,7 +497,7 @@ def process_next_chunk(context, file, previous_chunk, importedObjects, IMAGE_SEA
#is it a material chunk?
elif new_chunk.ID == MATERIAL:
# print("read material")
# print("read material")
#print 'elif new_chunk.ID == MATERIAL:'
contextMaterial = bpy.data.materials.new('Material')
......@@ -507,7 +507,7 @@ def process_next_chunk(context, file, previous_chunk, importedObjects, IMAGE_SEA
#print 'elif new_chunk.ID == MAT_NAME:'
material_name, read_str_len = read_string(file)
# print("material name", material_name)
# print("material name", material_name)
#plus one for the null character that ended the string
new_chunk.bytes_read += read_str_len
......@@ -521,14 +521,14 @@ def process_next_chunk(context, file, previous_chunk, importedObjects, IMAGE_SEA
# TODO: consider ambient term somehow. maybe add to color
# if temp_chunk.ID == MAT_FLOAT_COLOR:
# contextMaterial.mirror_color = read_float_color(temp_chunk)
# temp_data = file.read(struct.calcsize('3f'))
# temp_chunk.bytes_read += 12
# contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
# temp_data = file.read(struct.calcsize('3f'))
# temp_chunk.bytes_read += 12
# contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
# elif temp_chunk.ID == MAT_24BIT_COLOR:
# contextMaterial.mirror_color = read_byte_color(temp_chunk)
# temp_data = file.read(struct.calcsize('3B'))
# temp_chunk.bytes_read += 3
# contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
# temp_data = file.read(struct.calcsize('3B'))
# temp_chunk.bytes_read += 3
# contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
# else:
skip_to_end(file, temp_chunk)
new_chunk.bytes_read += temp_chunk.bytes_read
......@@ -538,35 +538,35 @@ def process_next_chunk(context, file, previous_chunk, importedObjects, IMAGE_SEA
read_chunk(file, temp_chunk)
if temp_chunk.ID == MAT_FLOAT_COLOR:
contextMaterialWrapper.base_color = read_float_color(temp_chunk)
# temp_data = file.read(struct.calcsize('3f'))
# temp_chunk.bytes_read += 12
# contextMaterial.rgbCol = [float(col) for col in struct.unpack('<3f', temp_data)]
# temp_data = file.read(struct.calcsize('3f'))
# temp_chunk.bytes_read += 12
# contextMaterial.rgbCol = [float(col) for col in struct.unpack('<3f', temp_data)]
elif temp_chunk.ID == MAT_24BIT_COLOR:
contextMaterialWrapper.base_color = read_byte_color(temp_chunk)
# temp_data = file.read(struct.calcsize('3B'))
# temp_chunk.bytes_read += 3
# contextMaterial.rgbCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
# temp_data = file.read(struct.calcsize('3B'))
# temp_chunk.bytes_read += 3
# contextMaterial.rgbCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
else:
skip_to_end(file, temp_chunk)
# print("read material diffuse color", contextMaterial.diffuse_color)
# print("read material diffuse color", contextMaterial.diffuse_color)
new_chunk.bytes_read += temp_chunk.bytes_read
elif new_chunk.ID == MAT_SPECULAR:
#print 'elif new_chunk.ID == MAT_SPECULAR:'
read_chunk(file, temp_chunk)
# TODO: consider using specular term somehow
# TODO: consider using specular term somehow
# if temp_chunk.ID == MAT_FLOAT_COLOR:
# contextMaterial.specular_color = read_float_color(temp_chunk)
# temp_data = file.read(struct.calcsize('3f'))
# temp_chunk.bytes_read += 12
# contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
# temp_data = file.read(struct.calcsize('3f'))
# temp_chunk.bytes_read += 12
# contextMaterial.mirCol = [float(col) for col in struct.unpack('<3f', temp_data)]
# elif temp_chunk.ID == MAT_24BIT_COLOR:
# contextMaterial.specular_color = read_byte_color(temp_chunk)
# temp_data = file.read(struct.calcsize('3B'))
# temp_chunk.bytes_read += 3
# contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
# temp_data = file.read(struct.calcsize('3B'))
# temp_chunk.bytes_read += 3
# contextMaterial.mirCol = [float(col)/255 for col in struct.unpack('<3B', temp_data)] # data [0,1,2] == rgb
# else:
skip_to_end(file, temp_chunk)
new_chunk.bytes_read += temp_chunk.bytes_read
......@@ -856,8 +856,8 @@ def load_3ds(filepath,
# global SCN
# XXX
# if BPyMessages.Error_NoFile(filepath):
# return
# if BPyMessages.Error_NoFile(filepath):
# return
print("importing 3DS: %r..." % (filepath), end="")
......@@ -865,7 +865,7 @@ def load_3ds(filepath,
bpy.ops.object.select_all(action='DESELECT')
time1 = time.clock()
# time1 = Blender.sys.time()
# time1 = Blender.sys.time()
current_chunk = Chunk()
......@@ -891,10 +891,10 @@ def load_3ds(filepath,
object_matrix.clear()
scn = context.scene
# scn = bpy.data.scenes.active
# scn = bpy.data.scenes.active
# SCN = scn
# SCN_OBJECTS = scn.objects
# SCN_OBJECTS.selected = [] # de select all
# SCN_OBJECTS = scn.objects
# SCN_OBJECTS.selected = [] # de select all
importedObjects = [] # Fill this list with objects
process_next_chunk(context, file, current_chunk, importedObjects, IMAGE_SEARCH)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment