4
$\begingroup$

How can I write this to work in blender?

if (bpy.ops.object.shade_flat() == true ):        
        bpy.ops.object.shade_smooth() = true;

if (bpy.ops.object.shade_smooth() == true):        
        bpy.ops.object.shade_flat() = True

I want to check if object is smooth shaded so I can make it flat shaded; or if object is flat shaded I can make it smooth shaded.

I want it to run when I hit the script on a selected object.

Cheers

$\endgroup$

1 Answer 1

4
$\begingroup$

The bpy.ops don't return a value and there isn't a function that will tell you if the object is smooth shaded or not; so you have to do it this way:

Smooth shading is a property of the individual polygons of a mesh. Here are two functions that let you set the shading mode or toggle it. They work by setting the use_smooth field of each polygon in the mesh. In the first function, the value is set to the OnOff argument's value. In the second, it is toggled.

There's some boiler plate error handling in each function to reduce the failure cases, if you try to run the function on an object that isn't a mesh, or properly initialized.

import bpy

def set_shading(object, OnOff=True):
    """ Set the shading mode of an object
        True means turn smooth shading on.
        False means turn smooth shading off.
    """
    if not object:
        return
    if not object.type == 'MESH':
        return
    if not object.data:
        return
    polygons = object.data.polygons
    polygons.foreach_set('use_smooth',  [OnOff] * len(polygons))
    object.data.update()

def toggle_shading(object):
    """ Toggle the shading mode of an object """
    if not object:
        return
    if not object.type == 'MESH':
        return
    if not object.data:
        return
    polygons = object.data.polygons
    for polygon in polygons:
        polygon.use_smooth = not polygon.use_smooth
    object.data.update()

If, for instance, you wanted to toggle the shading on the active object you would make a call like:

toggle_shading(C.active_object)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .