[Bf-blender-cvs] [6f42eb245b1] blender2.8: Python IO: Initial nodal shader support for import AND export.

Bastien Montagne noreply at git.blender.org
Thu Sep 27 23:44:40 CEST 2018


Commit: 6f42eb245b1572c76c8ade0b3fb89d51c796e97c
Author: Bastien Montagne
Date:   Thu Sep 27 22:03:30 2018 +0200
Branches: blender2.8
https://developer.blender.org/rB6f42eb245b1572c76c8ade0b3fb89d51c796e97c

Python IO: Initial nodal shader support for import AND export.

That new bpy_extras' node_shader_utils module is remotely based on
existing addons' cycles_shader_compat module. It has some key
differences though:
 - It is based on Principled shader, instead of the noodle combination
   of half a dozen simpler shaders.
 - It does not do any value conversion (like e.g. clamping, which was
   only suited for FBX). Any conversion/adaptation is to be done
   by each IO add-on.
 - It extensively uses accessors to offer:
   - Easy read/write of values, hiding all the hairy noodly nodes
     (principled shader helps a lot here).
   - lazy creation of most nodes on accessing (when generating a
     material), which avoids getting unused nodes in final shader.
 - We only use Principled BSDF so far though, which means some features
   supported by previous system are not yet implemented in new one.

Note that, even though we support 'exporting' side of things, this will
only work for a very specific (and basic) kind of shader. This will have
to be clearly explained in end-user documentation.

Also, that code has had some basic testing, but most certainly needs a
lot more refinement.

As proof-of-concept, OBJ IO script will be updated to use that new
system after that commit.

===================================================================

A	release/scripts/modules/bpy_extras/node_shader_utils.py

===================================================================

diff --git a/release/scripts/modules/bpy_extras/node_shader_utils.py b/release/scripts/modules/bpy_extras/node_shader_utils.py
new file mode 100644
index 00000000000..d643295af7a
--- /dev/null
+++ b/release/scripts/modules/bpy_extras/node_shader_utils.py
@@ -0,0 +1,590 @@
+# ##### BEGIN GPL LICENSE BLOCK #####
+#
+#  This program is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License
+#  as published by the Free Software Foundation; either version 2
+#  of the License, or (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# ##### END GPL LICENSE BLOCK #####
+
+# <pep8 compliant>
+
+import bpy
+from mathutils import Vector
+
+__all__ = (
+    "PrincipledBSDFWrapper",
+    )
+
+
+def _set_check(func):
+    from functools import wraps
+    @wraps(func)
+    def wrapper(self, *args, **kwargs):
+        if self.is_readonly:
+            assert(not "Trying to set value to read-only shader!")
+            return
+        return func(self, *args, **kwargs)
+    return wrapper
+
+
+class ShaderWrapper():
+    """
+    Base class with minimal common ground for all types of shader interfaces we may want/need to implement.
+    """
+
+    # The two mandatory nodes any children class should support.
+    NODES_LIST = (
+        "node_out",
+
+        "_node_texcoords",
+        )
+
+    __slots__ = (
+        "is_readonly",
+        "material",
+        "_textures",
+        "_grid_locations",
+        ) + NODES_LIST
+
+    _col_size = 300
+    _row_size = 300
+
+    def _grid_to_location(self, x, y, dst_node=None, ref_node=None):
+        if ref_node is not None:  # x and y are relative to this node location.
+            nx = round(ref_node.location.x / self._col_size)
+            ny = round(ref_node.location.y / self._row_size)
+            x += nx
+            y += ny
+        loc = None
+        while True:
+            loc = (x * self._col_size, y * self._row_size)
+            if loc not in self._grid_locations:
+                break
+            loc = (x * self._col_size, (y - 1) * self._row_size)
+            if loc not in self._grid_locations:
+                break
+            loc = (x * self._col_size, (y - 2) * self._row_size)
+            if loc not in self._grid_locations:
+                break
+            x -= 1
+        self._grid_locations.add(loc)
+        if dst_node is not None:
+            dst_node.location = loc
+            dst_node.width = min(dst_node.width, self._col_size - 20)
+        return loc
+
+    def __init__(self, material, is_readonly=True):
+        self.is_readonly = is_readonly
+        self.material = material
+        self.update()
+
+    def update(self):  # Should be re-implemented by children classes...
+        for node in self.NODES_LIST:
+            setattr(self, node, None)
+        self._textures = {}
+        self._grid_locations = set()
+
+    def use_nodes_get(self):
+        return self.material.use_nodes
+    @_set_check
+    def use_nodes_set(self, val):
+        self.material.use_nodes = val
+        self.update()
+    use_nodes = property(use_nodes_get, use_nodes_set)
+
+    def node_texcoords_get(self):
+        if not self.use_nodes:
+            return None
+        if self._node_texcoords is None:
+            for n in self.material.node_tree.nodes:
+                if n.bl_idname == 'ShaderNodeTexCoord':
+                    self._node_texcoords = n
+                    self._grid_to_location(0, 0, ref_node=n)
+                    break
+        if self._node_texcoords is None and not self.is_readonly:
+            tree = self.material.node_tree
+            nodes = tree.nodes
+            links = tree.links
+            
+            node_texcoords = nodes.new(type='ShaderNodeTexCoord')
+            node_texcoords.label = "Texture Coords"
+            self._grid_to_location(-5, 1, dst_node=node_texcoords)
+            self._node_texcoords = node_texcoords
+        return self._node_texcoords
+    node_texcoords = property(node_texcoords_get)
+
+
+class PrincipledBSDFWrapper(ShaderWrapper):
+    """
+    Hard coded shader setup, based in Principled BSDF.
+    Should cover most common cases on import, and gives a basic nodal shaders support for export.
+    Supports basic: diffuse/spec/reflect/transparency/normal, with texturing.
+    """
+    NODES_LIST = (
+        "node_out",
+        "node_principled_bsdf",
+
+        "_node_normalmap",
+        "_node_texcoords",
+        )
+
+    __slots__ = (
+        "is_readonly",
+        "material",
+        ) + NODES_LIST
+
+    NODES_LIST = ShaderWrapper.NODES_LIST + NODES_LIST
+
+    def __init__(self, material, is_readonly=True):
+        super(PrincipledBSDFWrapper, self).__init__(material, is_readonly)
+
+    def update(self):
+        super(PrincipledBSDFWrapper, self).update()
+
+        if not self.use_nodes:
+            return
+
+        tree = self.material.node_tree
+
+        nodes = tree.nodes
+        links = tree.links
+
+        # --------------------------------------------------------------------
+        # Main output and shader.
+        node_out = None
+        node_principled = None
+        for n in nodes:
+            if n.bl_idname == 'ShaderNodeOutputMaterial' and n.inputs[0].is_linked:
+                node_out = n
+                node_principled = n.inputs[0].links[0].from_node
+            elif n.bl_idname == 'ShaderNodeBsdfPrincipled' and n.outputs[0].is_linked:
+                node_principled = n
+                for lnk in n.outputs[0].links:
+                    node_out = lnk.to_node
+                    if node_out.bl_idname == 'ShaderNodeOutputMaterial':
+                        break
+            if (node_out is not None and node_principled is not None and
+                node_out.bl_idname == 'ShaderNodeOutputMaterial' and
+                node_principled.bl_idname == 'ShaderNodeBsdfPrincipled'):
+                break
+            node_out = node_principled = None  # Could not find a valid pair, let's try again
+
+        if node_out is not None:
+            self._grid_to_location(0, 0, ref_node=node_out)
+        elif not self.is_readonly:
+            node_out = nodes.new(type='ShaderNodeOutputMaterial')
+            node_out.label = "Material Out"
+            node_out.target = 'ALL'
+            self._grid_to_location(1, 1, dst_node=node_out)
+        self.node_out = node_out
+
+        if node_principled is not None:
+            self._grid_to_location(0, 0, ref_node=node_principled)
+        elif not self.is_readonly:
+            node_principled = nodes.new(type='ShaderNodeBsdfPrincipled')
+            node_principled.label = "Principled BSDF"
+            self._grid_to_location(0, 1, dst_node=node_principled)
+            # Link
+            links.new(node_principled.outputs["BSDF"], self.node_out.inputs["Surface"])
+        self.node_principled_bsdf = node_principled
+
+        # --------------------------------------------------------------------
+        # Normal Map, lazy initialization...
+        self._node_normalmap = None
+
+        # --------------------------------------------------------------------
+        # Tex Coords, lazy initialization...
+        self._node_texcoords = None
+
+
+    def node_normalmap_get(self):
+        if not self.use_nodes:
+            return None
+        if self._node_normalmap is None and self.node_principled_bsdf is not None:
+            node_principled = self.node_principled_bsdf
+            if node_principled.inputs["Normal"].is_linked:
+                node_normalmap = node_principled.inputs["Normal"].links[0].from_node
+                if node_normalmap.bl_idname == 'ShaderNodeNormalMap':
+                    self._node_normalmap = node_normalmap
+                    self._grid_to_location(0, 0, ref_node=node_normalmap)
+            if self._node_normalmap is None and not self.is_readonly:
+                node_normalmap = nodes.new(type='ShaderNodeNormalMap')
+                node_normalmap.label = "Normal/Map"
+                self._grid_to_location(-1, -2, dst_node=node_normalmap, ref_node=node_principled)
+                # Link
+                links.new(node_normalmap.outputs["Normal"], node_principled.inputs["Normal"])
+        return self._node_normalmap
+    node_normalmap = property(node_normalmap_get)
+
+
+    # --------------------------------------------------------------------
+    # Diffuse.
+
+    def diffuse_color_get(self):
+        if not self.use_nodes or self.node_principled_bsdf is None:
+            return self.material.diffuse_color
+        return self.node_principled_bsdf.inputs["Base Color"].default_value
+    @_set_check
+    def diffuse_color_set(self, color):
+        self.material.diffuse_color = color
+        if self.use_nodes and self.node_principled_bsdf is not None:
+            self.node_principled_bsdf.inputs["Base Color"].default_value = color
+    diffuse_color = property(diffuse_color_get, diffuse_color_set)
+
+    def diffuse_texture_get(self):
+        if not self.use_nodes or self.node_principled_bsdf is None:
+            return None
+        return ShaderImageTextureWrapper(self, self.node_principled_bsdf,
+                                         self.node_principled_bsdf.inputs["Base Color"],
+                                         grid_row_diff=1)
+    diffuse_texture = property(diffuse_texture_get)
+
+
+    # --------------------------------------------------------------------
+    # Specular.
+
+    def specular_get(self):
+        if not self.use_nodes or self.node_principled_bsdf is None:
+            return self.material.specular_intensity
+        return self.node_principled_bsdf.inputs["Specular"].default_value
+    @_set_check
+    def specular_set(self, value):
+        self.m

@@ Diff output truncated at 10240 characters. @@



More information about the Bf-blender-cvs mailing list