text:
Keeping dimensions of a plane when twisting
I am following this youtube tutorial on making a mobius strip:
https://www.google.com/search?q=mobius+strip+blender+&sca_esv=d310bf87f451f94c&rlz=1C5CHFA_enAU853AU853&sxsrf=ACQVn09J8sx5J30lDjf4G8sQyRl0KsbYwg%3A1711673929553&ei=SRIGZrC5IfbcseMP1-W62Ag&ved=0ahUKEwjwgaukopiFAxV2bmwGHdeyDosQ4dUDCBA&uact=5&oq=mobius+strip+blender+&gs_lp=Egxnd3Mtd2l6LXNlcnAiFW1vYml1cyBzdHJpcCBibGVuZGVyIDIGEAAYFhgeMgsQABiABBiKBRiGAzILEAAYgAQYigUYhgMyCxAAGIAEGIoFGIYDMgsQABiABBiKBRiGA0jJJFCCBVjZInABeAGQAQCYAa0BoAHRC6oBAzAuObgBA8gBAPgBAZgCCqAC8AvCAgoQABhHGNYEGLADwgINEAAYgAQYigUYQxiwA8ICChAAGIAEGIoFGEPCAgUQABiABMICBRAuGIAEwgILEAAYgAQYigUYkQKYAwCIBgGQBgqSBwMxLjmgB_Uj&sclient=gws-wiz-serp#fpstate=ive&vld=cid:a36232ed,vid:deIyUny6s2A,st:0
When I get to the part where I need to use a simple deform twist on the plane, the plane does not keep its dimensions when it twists, but completely stretches as it twists:

Help Please!
Thank you

Maybe the scale of your object isn't 1 ? Then Ctrl+A > Apply Scale. Consider uploading your blend file with https://blend-exchange.com/.

the link to the tutorial in your question is actually a google search and just displays a result list.


text:
best practice for add-on generation with many functions single file or split it up?
This is quite a theoretical question.
A simple function can remain inside an add-on text file. But what if you have many functions and your text file gets very long. Would it be better to split each function into logical segments lets say one file for modifiers, one file for mesh editing and such and then have one add-on file that calls / loads the code from those text files?
Or, is it better to keep everything in one file?
Are there facts I should be aware of to help me make a choice?

Organise them when it gets too long, and scrolling and looking for specific things is tedious. There is no one good way, it all depends on how each coder likes to work ... make those rules work in your favor as you go along cause you nv know how big a code will get when you first started with a small idea.

My main curiosity was regarding performance, having to read all the files. Also the GitHub point is very valid to consider.

If your main curiosity is performance then state that in the question! :)

performance can be measured in various ways, execution speed, or 'how much time does the coder waste trying to add / fix code '

Agreed should have. Still all the replies are useful to me.

In my opinion you should always use multiple files for non-trivial addons (e.g. more than one operator).
I agree that it can be complicated in at first and I have to admit that it took me quite some time until I was able to create multi-file addons in a nice way.
BUT, a few months ago I developed an addon template for my Code Autocomplete addon that allows you to create multi-file addons very easily. Without having to care about reloading etc.
Since then I always use this template. Even as large addons as Animation Nodes and Code Autocomplete use it (and some others as well, e.g. this one).
Here is how I setup a new addon:

Create a new folder in Blenders addons directory. It's not super important but I suggest to use a name that can be a python identifier and all lower case.

Inside of this folder I create a _ init _.py file with this content.

Create a developer_utils.py file with this content.

Setup a git repository in that folder.

That's it. You can simply create more .py files in the folder now and all of them will be loaded and reloaded automatically. If you define operators, panels, ... inside of one of these files they will be registered as well (by the bpy.utils.register_module(_ name _) statement in the main file).
Ah and don't forget to create a _ init _.py file in each subdirectory. I generally keep them empty.
The Code Autocomplete addon can do the first 3 steps for you.
http://code-autocomplete-manual.readthedocs.org/en/latest/addon_development.html
So why should you use multiple files:

Much better support by version control systems like GIT.
The dependencies in your code are much clearer, because you have to import functions you want to use in a file. That makes refactoring much easier.
Easier to extend without cluttering existing code.
Better separation between parts of you addon like operators and ui.
Makes it possible to write reusable modules.
Easier to manage in modern code editors, because most of them use a folder as project (I personally use Atom atm and like it very much!).

In summary: I only see benefits in using multi-file addons and using the template I developed most of the difficulties are gone.

thanks for your sharing! But how should I install the add on? Simply by putting the directory in the Blender addons one or also have I, from Blender User preferences.../add-ons/install from file, to select a file from that directory?

regarding the example files from Jacques Lucke:
please notice that in blender 2.80 module registration procedure has changed. E.g. bpy.utils.register_module was removed.
Details here

If you can - keep it single file and only when you have reasons - go multi-file.
Benefits of single-file:

it requires less code
other people better understand it as it is less complicated
it works better inside Blender environment
there is beauty in nicely formatted single-file Blender addon. It is nicely packed together.

When to split:

When your addon is a larger project (50kb+) and when you are editing with external tools. When I know a function will be shared/reused I put it inside (for example) mesh_utils.py file, then such addons become multi-file in a folder and I link the function with:
from .mesh_utils import function

I do not split the file just because the length. Having more files over one long file is no win, both are problems to deal with. When you keep your file clean and organized, even several thousand lines long files are no problem (you can also collapse things in external editors). If the file is long I put a dictionary at the top to mark where things are (mainly their order as when you write code the lines change):
# Contents:
#  - naming utils
#  - constraints utils
#  - driver/keyframe utils
#  - opengl
#  - operators
#  - handlers
#  - ui/panels
#  - addon prefs
#  - properties
#  - register

Inside the code I mark each category with headline like this:
# =====================================================
#                       OPERATORS
# =====================================================

Inside an editor with a mini-map it can be seen and also you easily notice them when scrolling through the file helping you be oriented.
CtrlF for search in long files is your friend and a way to be fast.
CtrlSpacebar (Autocomplete inside Text editor) lists used text in an open text file - a reason to keep your functions inside one file when working inside Blender.

In the end it's you who will determine if the code structure is good or bad. You can make terrible multi-file mess and a symphony-like single-file and vice-versa. The key is good documentation/comments and format consistency. Keep all files and addons the same structure and name everything properly so it can be searched.

Clean code and Single Responsibility Principle already reasons enough to go multifile even if you have a single button. If you have only one file, you have 2 responsibilities at the very least in it: registration of the addon and the behavior of your addon. I looked at templates in the Text Editor and it didn't look very nice even in 70 line long examples. And it didn't just not look nice, it was harder to understand because I was trying to make sense which part of the file is really a different part of the addon, and how it is supposed to be divided conceptually.

I have a script with multiple functions, on buttons, that I also need to have the option to run all those functions, in a particular order, with one button press.
Is there a way to do that without having to rewrite all the functions into one operator (effectively doubling the length of the script).

single-file -- vs -- multi-file
I think if you're looking for a Blender centric answer it's a good idea to look through the scripts that come with Blender by default. The addons folder has quite a few multi-file add-ons (as directories) and only a few  long .py files -- most single-file add-ons are short.
The single file approach in general is fine for non-complicated add-ons, like a few short Operators with a Menu or Panel. Historically single file add-ons where easier to download/install by Blender newcomers. When the Install from File feature was added, which takes a zip, the single file approach lost that excuse.
Remaining reasons to use the single file approach for large add-ons are down to how comfortable someone is with Python. It's easy to write single file code, but adding a directory structure does require investing time in reading / understanding how that works. Luckily, the add-on directory  has many working examples to show how you might organize a multi-file add-on. So "it's difficult" is not an excuse either.

Text Editor
More important than single or multifile is what are you coding with, a  Text Editor equipped with features that help you code?

Does your Text Editor have plugins for checking if your code conforms to Python's "pep8" style guide?  For instance this screenshot shows what I get from SublimeText when I hit save on a file with many violations of pep-8.
Is it easy to make and trigger snippets? -- snippets are templates of reusable code which form the basis of Operators / Panels / Menus / general code patterns. Save us retyping the boilerplate.

GIT
More important still is: are you using some kind of source-code version control, (git, svn) so you can easily keep track of changes, and revert/correct with ease when code modifications cause unwanted side effects. source control systems give convenient ways to see the differences between two updates sideby side or in the form of a .diff file.

actually I do not use GIT because besides this add-on I don't think I will ever do something similar. But GIT seems to have some benefit.

GIT isn't just used for code, but also for documentation (allows you to keep clear history of changes to a single file or directory, text or binary),  I tend to give broad / general answers to benefit more potential readers.

Ah I see - I downloaded it. I assumed it was an online versioning tool but this works local. great! no more duplicates.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Confused about how to define a class
This is how I sofar define a class for a panel inside the tool shelve.
class ObjectLayer(bpy.types.Panel):
    bl_label = "ObjectLayer"
    bl_idname = "ObjectLayer"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Claas"

    def draw(self, context):
        layout = self.layout

        obj = context.object

        row = layout.row()
        row.prop(obj , "layers")

Then I got this amazing script in how to show the modifier stack in the tool bar but it uses a very different format for declaring a class
import bpy
from bpy.types import Menu, Panel, UIList
from bl_ui.properties_data_modifier import DATA_PT_modifiers as PT_MOD

@classmethod
def poll(cls, context):
    return (context.object is not None)

def make_panel(name, poll, funcs):
    overwrites = {
        "bl_space_type": "VIEW_3D",
        "bl_region_type": "TOOLS",
        "bl_label": "Test",
        "bl_context": "objectmode",
        "bl_category": "Test",
        "poll": poll,
        "draw": getattr(funcs, "draw")
    }

    for f in dir(funcs):
        if f.isupper():
            overwrites[f] = getattr(funcs, f)

    return type(name, (Panel,), overwrites)

RigPanel = make_panel("OpenStudioAddRigPanel", poll, funcs=PT_MOD)

def register(): bpy.utils.register_class(RigPanel)
def unregister(): bpy.utils.unregister_class(RigPanel)
if __name__ == "__main__": register()

This is what I tried:
import bpy
from bpy.types import Menu, Panel, UIList
from bl_ui.properties_data_modifier import DATA_PT_modifiers as PT_MOD

class ObjectLayer(bpy.types.Panel):
bl_label = "ObjectLayer"
bl_idname = "ObjectLayer"
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Claas"

def poll(cls, context):
return (context.object is not None)

def draw(self, context):
layout = self.layout

ob = context.object

layout.operator_menu_enum("object.modifier_add", "type")

for md in ob.modifiers:
    box = layout.template_modifier(md)
    if box:
        # match enum type to our functions, avoids a lookup table.
        getattr(self, md.type)(box, ob, md)

def make_panel(name, poll, draw, funcs):
overwrites = {
    "bl_space_type": "VIEW_3D",
    "bl_region_type": "TOOLS",
    "bl_label": "Test",
    "bl_context": "objectmode",
    "bl_category": "Test",
    "poll": poll,
    "draw": draw
}

for f in dir(funcs):
    if f.isupper():
        overwrites[f] = getattr(funcs, f)

return type(name, (Panel,), overwrites)

RigPanel = make_panel("OpenStudioAddRigPanel", poll, draw, funcs=PT_MOD)

def register():
bpy.utils.register_class(ObjectLayer)

def unregister():
bpy.utils.register_class(ObjectLayer)

if __name__ == "__main__":
register()

Traceback (most recent call last):
  File "C:\Users\info\Desktop\untitled.blend\Text", line 58, in
  File "C:\Users\info\Desktop\untitled.blend\Text", line 52, in register
AttributeError: expected Panel, ObjectLayer class to have an "draw" attribute

Use the regular class definition scheme as shown in the TextEditor Python Templates -- unless you have a good reason to use a class Factory.
As Sambler shows in the new answer to the previous question: You can do this much simpler with standard class definitions -- the use of the "class Factory" was not appropriate in this scenario because it wasn't the least complicated solution.

However, to answer this question anyway; the make_panel function is what we might call a "class Factory".
Positive

It generates unique classes on the fly, requiring little code to  individualize each class. Especially useful if you need many classes which differ only in small but important ways.
This avoids explicitly writing the full class out in code for every class if you just need to change a couple of lines or functions per class.

negative

The downside to a class factory is it becomes tricky to reason about the code, especially for newcomers. If you don't know how to introspect a class it becomes a bit of a black-box.
classes generated this way must be registered with bpy.utils.register_class(...)

register_module(__name__) won't find these classes automatically.

How to use such things correctly is better discussed on a programming QA like StackOverflow. See this question / answer " How can I dynamically create derived classes from a base class " . If that question is over the top of your head, probably wait till you get more Python experience before using the code.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Why can I not edit the Mesh name in field created with row.prop(obj, "data")
With the following code I can read out the name of a mesh data block.
row.prop(obj, "data")

And with the following code I can read out the name of the object.
row.prop(obj, "name")

But I noticed that I cannot edit the mesh data name only the object name.

Here is the code from Blender that generated the mesh data block UI.
class DATA_PT_context_mesh(MeshButtonsPanel, Panel):
    bl_label = ""
    bl_options = {'HIDE_HEADER'}
    COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_GAME'}

    def draw(self, context):
        layout = self.layout

        ob = context.object
        mesh = context.mesh
        space = context.space_data

        if ob:
            layout.template_ID(ob, "data")
        elif mesh:
            layout.template_ID(space, "pin_id")

Think of Objects as containers, which can contain Curve data or Mesh data (and a few other kinds).
obj.data will refer to the Mesh or the Curve of the object. You would need to do the following to display the mesh's name
row.prop(obj.data, "name")

Or replicating what the standard panels do (with or without the icon).
    obj = context.object

    col = layout.column()
    if obj.data:
        col.prop(obj.data, "name")
        col.prop(obj.data, "name", icon="OUTLINER_DATA_" + obj.type)
    else:
        col.label('An empty selected')

Thank your very much. I learned a lot in the past days. I start to understand now how my students must feel when I teach Blender and they are new to it. There is a lot to take in.

authors: Вадим Костливцев


text:
How to iterate over selected_objects collection and ignore the active_object
I want to do something with each of the selected_objects as long as the object is not the active_object.
To put this into perspective here is a small (non working) operator that represents part of my code. I want to specify the  x location for each of the selected_objects by copying the x location from the active_object.
So I need to loop over the selected_objects and drop the object that happens to be the active_object.
#AlignXObject
class AlignXObject(bpy.types.Operator):
    bl_idname = "align.x_object"
    bl_label = "Align X Object"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self,context):

        sel_obj = bpy.context.selected_objects
        act_obj = bpy.context.active_object

        act_obj_location = bpy.data.object[act_obj].location[0]

        for obj in sel_obj:
            if obj != act_obj:
                bpy.data.object[???].location[0] = act_obj_location

bpy.context.selected_objects is a collection of references to all selected objects, and will include the active object.
bpy.context.active_object is a single reference.

There are a number of ways to get a list of selected objects that don't include the active object. The following give a list called selected of selected objects except the active object.
list Comprehension
ctx = bpy.context
active = ctx.active_object
selected = [o for o in ctx.selected_objects if not (o == active)]
# selected = [o for o in ctx.selected_objects if o != active]

# or even a generator expression.
# selected = (o for o in ctx.selected_objects if o != active)

or
set() boolean
ctx = bpy.context
active = ctx.active_object
selection = ctx.selected_objects
selected = set(selection).difference(set([active]))

then the code would be like this, see the complexity is taken out of the loop and dealt with earlier - like a pre-filter.
for obj in selected:
    obj.location[0] = act_obj_location

To use your own code it would look like this, there's nothing wrong with this approach.
for obj in sel_obj:
    if obj != act_obj:
        obj.location[0] = act_obj_location

Avoiding letting your code get too nested can help readability - it's something to keep in mind.

And I just thought I formulated the questions well ... but you are right!

You'll get the hang of it Claas. promise.


text:
How to apply a several modifiers with python (but not necessarily all modifiers)?
Apply modifier button will write this into the console:
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Box Right ")

Adding this line after "bool_mod.object = obj" does not work as expected stating that object has not attribute 'modifier'
ERROR:
  File "C:\Users\info\Desktop\Boolean.blend\ui_panel_simple.py", line 38, in execute
AttributeError: 'Object' object has no attribute 'modifier_apply'

CODE:
def execute(self, context):

    target_obj = bpy.context.active_object
    tool_objs = [obj for obj in bpy.context.selected_objects if obj != target_obj]

    for obj in tool_objs:
        bool_mod = target_obj.modifiers.new(obj.name+' ', 'BOOLEAN')
        bool_mod.operation = 'DIFFERENCE'
        bool_mod.object = obj
        target_obj.modifier_apply(modifier=bool_mod.name)

I went to blender python website to read about the modifier command and values and to my surprise found nothing that explains what options there are for operation for example.
https://www.blender.org/api/blender_python_api_2_70_5/bpy.types.Modifier.html

This will be applied to the active object , so make sure your target object is active before applying the modifier ( set it active through script  each iteration)

You should use the first line bpy.ops.object.apl......

figured it out in my answer

Objects don't have a .modifier_apply(), you can't do active_object.modifier_apply(). That's what the main Error message is saying.
modifier_apply is an operator of bpy.ops.object, which works if there's an active object. Confused? :)
# pick any object
obj = bpy.data.objects['Suzanne']

# set the object to active
bpy.context.scene.objects.active = obj

# this operator will 'work' or 'operate' on the active object we just set
bpy.ops.object.modifier_apply(modifier="my_modifier_name")

In the event that you want to apply a subset of modifiers, you have to start applying from the bottom up. You could put checks in place to skip certain modifier by type, but in your case you have only Boolean_Modifiers.
import bpy

def execute(self, context):

    target_obj = context.active_object
    tool_objs = [o for o in context.selected_objects if o != target_obj]

    BOOL = 'BOOLEAN'
    # first add them.
    for obj in tool_objs:
        bool_mod = target_obj.modifiers.new(name='diff_' + obj.name, type=BOOL)
        bool_mod.operation = 'DIFFERENCE'
        bool_mod.object = obj
        obj.hide = True

    # then apply them individually.
    for modifier in target_obj.modifiers:
        bpy.ops.object.modifier_apply(modifier=modifier.name)

execute(None, bpy.context)

This is one way to apply the modifier, there is also a direct way to apply all modifiers at once to the Mesh without such a loop. See this answer for details

bpy.context.scene.objects.active = obj doesn't work; fails with AttributeError: bpy_prop_collection: attribute "active" not found. -- Maybe it changed in 2.80?

yes, answer is correct for blender version <= 2.79

The trick to make this run is that the () after the modifier_apply() cannot be empty. The moment you define the modifier name it works.
bpy.ops.object.modifier_apply(modifier=bool_mod.name)

I assume the modifier_apply command is just in this case working like a generic apply command because we are working of a list. But you still have to call out the modifier with the name I assume.

it's not about that it is because the object doesn't have a method called modifier_apply()  so you can't do this target_obj.modifier_apply()  instead you have to make your object active and call the operator bpy.ops.object.modifier_apply()

bpy.ops.object.modifier_apply() only works when you call out the modifier to also apply!

yes but he has it like this target_obj.modifier_apply() which is not the same as this  bpy.ops.object.modifier_apply() , is it ?

True - initially I tried "bpy.ops.object.modifier_apply()" first and then exchanged parts with target_obj but still kept the () empty.

yes it shouldn't be empty


text:
How to use bpy.ops.macro - defining macro steps
I found this code and tried to understand it. As far as I understand macro allows step by step execution. But I struggle to make it work right.
As far as I understand one has to define what each macro command is
and then generate an operator that works off each macro command - right?
Sadly the Blender Python manual does not explain the use of macro well, or I did not find it.
Here is the code I have:
import bpy
from bpy.types import Operator, Macro

# Our finalizing operator, shall run after transform
class Finalize(Operator):
    bl_idname = "test.finalize"
    bl_label = "Finalize"

    def execute(self, context):
        print("DONE!")
        return {'FINISHED'}

class Make(Operator):
    bl_idname = "test.make"
    bl_label = "Make"

    def execute(self, context):
        bpy.ops.object.empty_add()
        return {'FINISHED'}

# Macro operator to concatenate transform and our finalization
class Test(Macro):
    bl_idname = "TEST_OT_Test"
    bl_label = "Test Macro"

    def execute(self, context):
        # Note that we have to register classes first before populating
        # the Macro operator
        bpy.utils.register_class(Finalize)
        bpy.utils.register_class(Make)
        bpy.utils.register_class(Test)

        # The important bit: populate the macro operator with a sequence
        # of existing other operators
        Test.define("test.make")
        Test.define("test.finalize")
        return {'FINISHED'}

# BUTTON
class ObjectData(bpy.types.Panel):
    bl_label = "Object + Mesh Data"
    bl_idname = "ObjectData"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Modeling Toolbox"

    def draw(self, context):
        layout = self.layout

        obj = context.object

        row = layout.row()
        self.layout.operator("TEST_OT_Test")

# END
def register(): bpy.utils.register_module(__name__)
def unregister(): bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()

I think it should be more like this:  https://gist.github.com/zeffii/6cff6d0f2d98ccdb97e7

I pasted the code into the text editor and executed it - it generates the button but when pressing it nothing happens.

yeah, it only works from spacebar as far as i can tell..  (as the file name suggested)

Here is a corrected version: the Test.define needed different values.
Works perfect now - even including calling the transform and waiting till that is done so you script can continue with the next command/macro!
The transformation is started via calling Test.define("TRANSFORM_OT_translate") between the first and last macro step.
import bpy
from bpy.types import Operator, Macro

#End : Snap 3D Cursor and delete empty
class Finalize(Operator):
    bl_idname = "s3dc.finalize"
    bl_label = "Finalize S3DC"

    def execute(self, context):
        bpy.ops.view3d.snap_cursor_to_selected()
        bpy.ops.object.delete();
        print("DONE!")
        return {'FINISHED'}

#Start : Create the empty
class Make(Operator):
    bl_idname = "s3dc.make"
    bl_label = "Make S3DC"

    def execute(self, context):
        bpy.ops.object.select_all(action='DESELECT')
        bpy.ops.object.empty_add()
        print('Started')
        return {'FINISHED'}

#Execute : Start the macro sequence
class S3DC(Macro):
    bl_idname = "s3dc.trigger_macro"
    bl_label = "S3DC Macro Sequence"

# UI Button in Tool Shelfe
class ObjectData(bpy.types.Panel):
    bl_label = "Object + Mesh Data"
    bl_idname = "ObjectData"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Modeling Toolbox"

    def draw(self, context):
        layout = self.layout
        row = layout.row()
        row.operator("s3dc.trigger_macro", text="Run Set 3D Cursos macro")

# END
def register():
    bpy.utils.register_module(__name__)

    S3DC.define("S3DC_OT_make")
    S3DC.define("TRANSFORM_OT_translate")  # This starts the transformation command
    S3DC.define("S3DC_OT_finalize")

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()

you have called a modal op inside non-modal, so the snapping was done before the end of the transform op ( cursor doesn't move )

Oh yes true - maybe I made a mistake because the functions where working. I noticed that sometimes you have to restart Blender to flush out some behaviors.

I cannot in the script find any command for the transformation. You added "Test.define("TRANSFORM_OT_translate")". This this line itself call the translate/grab mode?

yes it starts the transform.translate operator

How did you know that?

you mean TRANSFORM_OT_translate to transform.translate ?

Let us continue this discussion in chat.

yes in deed - I started a chat if you want to join

So, did you guys ever get this working or...
I've been having a go with this as a reference, but I'm not getting anywhere. Partly because the syntax has changed slightly since 2016, but even adjusted for 2.93 I'm not getting the macro to do what it should.
More details here: https://blender.stackexchange.com/q/277843/149985


text:
OSL and raytracing
I don't know much about the Open Shading Language, but I need to know if it can do a few things before I decide to spend the time to learn it.

Can OSL manipulate rays that hit surfaces? Such as: change ray colors, reflect, refract, delete it

Can it also get ray data? Such as: where it came from, its source, direction, and intensity.
Can it emit rays from a surface? I know that the default Cycles emission shader is written in SVM, but would it be possible make a similar shader in OSL?

If it can't do any of these things, what do you suggest I do? Is it possible to make a SVM shader?

With a little programming knowledge you will find OSL very easy to pick up (it is very close to C). The OSL spec is less than 100 pages. Even if you can't get this one scenario to work, the OSL knowledge will still be useful for other tasks. If the thought of creating a new SVM shader is an option for you then I'd expect you to be able to learn and test an OSL script within an hour. This dispersion refractive shader may be a close start to what you want.

Thanks for the info. I'm supposing that it will be easier to learn than GLSL or CG? Does that dispersion/refractive shader actually emit the dispersed rays, or does it simply color the interior of the object?

While OSL can do an emission output, the example shader generates a dispersed colour for a camera ray and a transparent colour for other rays. Going by brecht's answer it may not have the control you want. I'm not sure if you can get the incoming colour, so while you could specify the outgoing emission colour, you probably can't alter it based off the incoming colour.

There are some restrictions on what you can do in OSL, you can't create your own BSDF or trace your own shading rays currently. There is a raytrace function for things like ambient occlusion or other tricks, but the integrator and sampling is generally outside of the control of OSL shaders.
This is part of the OSL design, the shader describes the material or light behavior but does not describe how the integrator and sampling should work specifically. For example the renderer may do multiple importance sampling, bidirectional ray tracing, photon mapping, .. and all those methods should work with the same OSL shader.
The questions you ask seem to involve specific algorithms, in a physically based render engine creating rays is generally the job of the integrator which can make smarter decisions at a global level rather than each individual shader doing their own sampling.

Thanks Brecht! Two years later, today, can I use OSL to describe my own mathematical BRDF formula from scratch? Or do I have to compose from shader primitives? Thanks!

OSL still has no support for writing custom BSDFs, you can only use the builtin closures.

Thanks for the info! I need a BRDF for research, so it needs to be exact. In this case, is it possible at all to implement my own BRDF formula in Cycles? Is there any workaround?

The only way to implement a custom BSDF is to do it in the Cycles source code, if it's for research maybe the quickest way is to modify/replace an existing BSDF.

I see. Would you mind pointing me to one of the built-in shaders? I looked at https://developer.blender.org/diffusion/B/browse/master/intern/cycles/kernel/shaders/, but these are all implemented in OSL. Also, this is different from writing a shader in Shader Virtual Machine, right? Is that an option too? Thanks!!

@SibbsGambling If you look at those shaders, they'll in the end refer to builtins through stdosl.h. Then e.g. emission is implemented like this, but that'll probably be different for blender.


text:
Set the active material output node with python
Output nodes have a is_active_output property, but it doesn't seem possible to set this consistently.
I believe there's a bug where doing node.is_active_output = True does nothing unless you first click in the UI on one of the output nodes to change which one is active, then after that node.is_active_output = True will work.
However I need to stick to the current latest Blender version and cannot wait for this to be patched. Is there some other way to consistently set what the active material output node is? Preferably without deleting any nodes.

As of this patch the bug is solved. You'll either have to download the latest 3.2 alpha build or wait for the official release which will be in 3 or 4 months from now if I'm not mistaken.
Here's a snippet to toggle between 2 outputs in the world shader (inspired by developer Jacques Lucke in the bug report):
import bpy

n1 = bpy.context.scene.world.node_tree.nodes['World Output']
n2 = bpy.context.scene.world.node_tree.nodes['World Output.001']

if not n1.is_active_output:
    n1.is_active_output = True
else:
    n2.is_active_output = True

Yeah as I understand it, now (as before) just setting is_active_output = True on any node will automatically set other output nodes to False and it should work.

Thanks for this, it also works for material outputs, but somehow nobody talks about that...

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Create a new asset library and get it in a variable
How can I create a new asset library, like what bpy.ops.preferences.asset_library_add() does, but also get the new library stored in a variable?
The operator just returns {'FINISHED'}. Normally there's a separate function like D.materials.new() which returns the created datablock, but I can't find any similar .new() function for asset libraries which are stored as part of the preferences in C.preferences.filepaths.asset_libraries.
Feasibly I could store a list of asset libraries, create a new one, and then examine the libraries to see which is not present in the old list, but this seems like a silly workaround.
Edit: I guess it's maybe intentional that this can't be done easily, as you also have to handle saving the user's preferences.

OPS are designed to be used in the interface, not in the Python. I would suggest watching my minused answer here https://blender.stackexchange.com/questions/267405/why-does-script-not-add-input-to-active-modifier/267406#267406 why it is better not to use OPS.

Exactly, that's why I'm asking :)

Bpy.ops are meant to be used in Python: there are some parts of the API, like some baking, that can only be accessed through  bpy.ops. If they weren’t, then there would be no Python interface to them. At this time the asset library interface is in flux and a lot has simply not been implemented yet.

Yeah at first glance I'm inclined to believe that your "workaround" is the solution. At least for now, looking through the docs, it seems like they're working on adding to the API for asset libraries

follow up on bpy.ops:  The Blender Python fine manual Gotchas section says "Blender’s operators are tools for users to access, that can be accessed with Python too which is very useful." bpy.ops should be avoided in the case where 1) performance is critical and 2) there exists a low level alternative.  If either of these is not true, than by all means use bpy.ops but be aware of gotchas.

Asset libraries are a property collection and so there is no low level add method.  However, bpy.ops.preferences.asset_library_add() follows the common practice of adding the new library to the end of the asset library list, so you don't have to compare two versions of the list and can use this idiom:
bpy.ops.preferences.asset_library_add()
new_library = bpy.context.preferences.filepaths.asset_libraries[-1]

to retrieve a reference to the just added library.  This, of course, only works up until the next time you perform an operation that modifies the library list.

Note the things you can do with this construct is get or set new_library.name and new_library.path according to the docs https://docs.blender.org/api/current/bpy.types.UserAssetLibrary.html


text:
How to calculate the total UV area used?
I'm trying to find the total UV area used relative to the image bounds - i.e. a percentage/ratio of used space vs. available space.
I know you can use sum(f.calc_area() for f in bm.faces) for a bmesh, but I'm unsure how to do this for the UV data instead of the actual 3D mesh data.
This UV map should give an output of 1.0:

While this UV map should give an output of 0.25:

The purpose of this question is to determine (and fix) the accuracy of image textures of known dimensions when applied to surfaces.
E.g. if we know a particular brick texture should be 2 meters wide, we should be able to use the mesh surface area in combination with the UV area utilized to calculate a multiplier to scale the texture up or down to be the correct size.
Some edge cases I'm not sure how to handle:

Overlapping UVs
UVs outside the image area

So if i understand this correctly you want a formula for the percentage of the Image used by the UV. If your overall image has a bound of 1, and your downscalled UV (1/2) uses 25% this would mean that you have a ratio of 1/4 or am i wrong?
100% = 1 (Full image bound)
1/4 = 25% so wouldn't it be possible to use this formula?
meaning if you want 20%
0.2 (20%) = 1/X
1/0.2 = 5
Meaning: if you want 20% of the Image used as a UV you have to divide by 5

Exactly, but the UV in practice is not downscaled, this is just an example. Most UVs try to fill all the available area, but there are gaps between the islands that are empty space. I need to calculate what the actual UV area used is, relative to the total area available, in any arbitrary space/mesh.

If the uv faces overlap, for example uv projection, what result do you want? Is there an exception for such cases?

It seems to me this is an XY problem: if you want consistent scale, you just want to define image dimensions, e.g. define UV dimensions as 0..1 meters. Now you don't need to calculate an area, because you still want to maintain proportions, so all you need to do is to compare an edge length with a loop length. Still, the easiest method to calculate the UV area seems to be triangulating the mesh, and summing up all UV triangles areas…

I thought I'd start with a basic solution, without the edge cases. So a script v0.1, so to say. Perhaps the brilliant minds in the community can elaborate on it, coming to a final solution together...
Since you mentioned bmesh in your question, I used it here.
This script loops over the faces of a bmesh, gets the uv coordinates of each vertex of the face and calculates the area of this uv triangle or quad.
import bpy
import bmesh
import mathutils

'''
Assumptions for script v0.1
---------------------------
1. UV map doesn't have overlapping faces
2. All UV coordinates are between 0.0 and 1.0
'''

# Force object mode, to ensure uv map is up to date
obj_mode = bpy.context.active_object.mode
if obj_mode != 'OBJECT':
    bpy.ops.object.mode_set(mode='OBJECT')

# Get active object as bmesh
bm = bmesh.new()
bm.from_mesh(bpy.context.active_object.data)

# Get active uv map
uv_layer = bm.loops.layers.uv.active

# Init uv area
uv_area = 0

# Iterate mesh faces
for face in bm.faces:
    # Get uv vertices
    uv_verts = []
    for loop in face.loops:
        uv_verts.append(loop[uv_layer].uv)

    # Calculate area between uv vertices
    if len(uv_verts) >= 3:
        # First triangle of quad
        uv_area += mathutils.geometry.area_tri(uv_verts[0], uv_verts[1], uv_verts[2])
    if len(uv_verts) == 4:
        # Second triangle of quad
        uv_area += mathutils.geometry.area_tri(uv_verts[0], uv_verts[2], uv_verts[3])

    # I suppose this can never happen...
    if len(uv_verts) > 4:
        print('N-gons in UV map not supported!')
        break

# Print uv coverage, equal to the calculated uv area sum,
# since we assume no overlaps and uv coords between 0.0 and 1.0.
print('UV coverage:', uv_area)

# Return to original mode
if obj_mode != 'OBJECT':
    bpy.ops.object.mode_set(mode=obj_mode)

I had an additional idea, for handling overlapping UV's. The approach is different, so I post it as a second answer.
The idea is: draw the faces of the UV map in an image and count the drawn pixels to calculate the coverage.

The advantage is that overlapping parts in the UV map merge together in the image, so the calculated coverage will never be greater than 100%.
Drawing the image can be done with the gpu module. In particular the offscreen rendering comes in handy here.
The code:
import bpy
import bmesh
import gpu
from gpu_extras.batch import batch_for_shader
from mathutils import Matrix, Vector
import numpy as np
from math import sqrt

'''
Calculate UV coverage for mesh - script v0.2
--------------------------------------------
UV areas outside 0.0-1.0 will be ignored.

Method: draw the UV faces in a temporary image (an offscreen gpu buffer),
similar to the image you see in the UV editor,
and count the number of drawn pixels to get the UV coverage.

This way overlapping UV will not result in a coverage > 100%.
'''

# Size of offscreen rendered UV image
UV_IMG_SIZE = 512

# Force object mode, to ensure uv map is up to date
obj_mode = bpy.context.active_object.mode
if obj_mode != 'OBJECT':
    bpy.ops.object.mode_set(mode='OBJECT')

# Get active object as bmesh
bm = bmesh.new()
bm.from_mesh(bpy.context.active_object.data)

# Get active uv map
uv_layer = bm.loops.layers.uv.active

# Init offscreen gpu image of UV map
# See: https://docs.blender.org/api/current/gpu.html#copy-offscreen-rendering-result-back-to-ram
# and: https://docs.blender.org/api/current/gpu.html#d-rectangle
offscreen = gpu.types.GPUOffScreen(UV_IMG_SIZE, UV_IMG_SIZE)
shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
shader.bind()
shader.uniform_float('color', (0.5, 0.5, 0.5, 1.0))

# Draw uv image in offscreen gpu buffer
with offscreen.bind():
    fb = gpu.state.active_framebuffer_get()
    fb.clear(color=(0.0, 0.0, 0.0, 0.0))
    with gpu.matrix.push_pop():
        # Set gpu draw matrix to [-1.0, 1.0]
        gpu.matrix.load_matrix(Matrix.Identity(4))
        gpu.matrix.load_projection_matrix(Matrix.Identity(4))
        vec_one = Vector((1, 1))

        # Iterate mesh faces
        for face in bm.faces:
            # Get uv vertices
            uv_verts = []
            for loop in face.loops:
                # Convert vector from [0.0, 1.0] to [-1.0, 1.0]
                uv_verts.append((loop[uv_layer].uv) * 2 - vec_one)

            # Draw uv triangles in offscreen image
            if len(uv_verts) >= 3:
                # First triangle
                vertices = (uv_verts[0], uv_verts[1], uv_verts[2])
                batch = batch_for_shader(shader, 'TRIS', {'pos': vertices})
                batch.draw(shader)
            if len(uv_verts) == 4:
                # Second triangle
                vertices = (uv_verts[0], uv_verts[2], uv_verts[3])
                batch = batch_for_shader(shader, 'TRIS', {'pos': vertices})
                batch.draw(shader)

            # Only triangles and quads are supported
            if len(uv_verts) > 4:
                print('N-gons in UV map not supported!')
                break

    # Get RGBA color data from offscreen buffer
    buffer = fb.read_color(0, 0, UV_IMG_SIZE, UV_IMG_SIZE, 4, 0, 'FLOAT')
    buffer.dimensions = UV_IMG_SIZE * UV_IMG_SIZE * 4

# Release offscreen render
offscreen.free()

# DEBUG: create image in Blender to inspect the result
if False:
    IMAGE_NAME = 'UV Coverage'
    if IMAGE_NAME not in bpy.data.images:
        bpy.data.images.new(IMAGE_NAME, UV_IMG_SIZE, UV_IMG_SIZE)
    image = bpy.data.images[IMAGE_NAME]
    image.scale(UV_IMG_SIZE, UV_IMG_SIZE)
    image.pixels.foreach_set(buffer)

# From RGBA color data, get the alpha channel (in numpy array)
buffer_np = np.array(buffer).reshape((UV_IMG_SIZE, UV_IMG_SIZE, 4))[:, :, 3]

# Calculate uv coverage:
# filled area (alpha is not zero) divided by total image size
uv_coverage = buffer_np[buffer_np != 0].shape[0] / (UV_IMG_SIZE * UV_IMG_SIZE)

# Print uv coverage
print('UV coverage:', uv_coverage)

# Return to original mode
if obj_mode != 'OBJECT':
    bpy.ops.object.mode_set(mode=obj_mode)

That's a really creative solution! I'm not sure yet if it's the right way to handle this edge case for me, but definitely a great idea and a useful tool for the future!

Geonodes
Just for fun, I'll understand if you downvote this, here's a geonodes solution:

You can use Python to add the geonodes modifier (and even to create the node tree from scratch), and to evaluate the object with the modifier and then read the attribute value. Perhaps it would even make sense for some dense topology, where the C++ implementation of the geonodes would prove to be more efficient than Python…
Edge Cases
In order to take care of the overlap, the complexity of the node tree explodes:

You might think dealing with UV outside of "UV area" is as easy as clamping vertex coordinate to 0..1, but that's not true:

As you move beyond 0..1 range, the shape inside keeps changing and you would expect an area to also change, however the mesh used for calculating the area doesn't change, because the vertex marked red keeps being clamped to the same spot. In order to make a proper calculation, the quad would have to be converted to an ngon, using two snapped vertices, marked with green and blue circles:

The solution is to use another boolean, to intersect with a cuboid taking all possible vertical (Z axis) space, and 0..1 on X and Y:


text:
Weights used in hook modifier affect texture created with an image
I am new to Blender, and probably my question has a very simple solution and has been done before, but I couldn't find a way to solve it (probably I didn't do the correct question in Google).
The situation is as follows:

I created a simple animation of a book opening following this tutorial

The critical part is that I used a Hook modifier that connects the pages to an empty to animate the page turn (with a SimpleDeform). The modifier uses a vertex group I created with the weights paint (see below).

I have a PNG file that I want to use to create the material. This PNG came from a real PDF that I converted to PNG for use as a texture. I include it using the texture node editor (see the 3rd picture to see the texture node editor). I use texture coordinates, mapping, and the image to use the PNG file.

The problem is (as I understand after making some proves) that the hook modifier, or the weights I used on it, affect how the image is introduced, as the following picture clearly shows:

Then, the question is: is there a way to use the weights for the hook modifier that doesn't affect the material/shader/texture?

i think, that the hook doesn't affect the image at all...but it affects the vertices. And the UV Map maps the UV "vertices" to the real vertices. And if the real vertices are stretched by the hook modifier, the image gets stretched too. So in my opinion you have to find a way, where you can bend your geometry without stretching. So i would recommend using a mathematical approach and maybe geometry nodes would be easiest to fulfill that task.

Hello, it should not affect the way the image is projected, it will just move the vertices

@moonboots the weighted Hook permits stretching of the geometry? My first thought is, instead of deforming the page, deform a curve in the same way, and then deform the page along it, from a fixed origin at curve-start. The page would ride the curve without stretching along it.


text:
3d viewport display rendering problem
I have this strange issue this morning... all objects seem to be half xrayish... last night all was good... as i pan or rotate is all flickers

Your Clip End (see in the top right of the 3D Viewport) is ridiculously high at 1111111125 m. Read more about it in the manual here: Depth Buffer Glitches or in one of the many answers on this topic on this site, for example: Glitchy Shadow effect, Why is my viewport glitching in orthographic view and not in perspective view

Hello and welcome. Please use a title that matches the content of the post. It should read like a question, be descriptive but succinct, unique and identifying, summarizing the problem so that anyone searching for similar issues is likely to find this. Remove anything superfluous, avoid using words like "this", "help with", "issue" or "question about", instead describe what "it" is. Remember, your title is the first thing visitors see, answers you get depend heavily on it. See What is the problem of asking “How do I do this?"

nope....
doesnt matter what values i put in.... also switching to Local view, everything disappears and trying to go back doesnt work either.... have to reopen the file to get back to here.... last night it was all good...

The values make no difference to this. Local view swapping also shows everything for a split second then the screen goes grey apart from the 3d cursor..... how do I post the file?


text:
Particle system shows on emitter mode but not on hair mode?
trying to make some grass on a plane. CtrlA done and Particle system added. On emitter it works as it should, on Hair mode, I get three straight lines flat on the XY plane... What is wrong here? Blender 3.4

Hello please share your file: https://blend-exchange.com/

weird, it works for me, see what it gives when I open your file: https://zupimages.net/up/24/37/7yuk.jpg

could it be hardware?

maybe, I can't tell

Where to go from here? hmm


text:
Aligin verticies between start and end vertices?
Just wondering how I align vertices between the active and last point in a chain? Is there a way other than scaling to an axis? for example if the surface has angled flow and I want to align/disribute vertices but on an angle between the first and actie selected points?
Thanks for any feedback

Have you tried right click > LoopTools > Gstretch (you need to activate the LoopTools addon), or right click > Set Linear?

It looks as though, here, you might be looking for good flow in hard-surface curvatures, not straightening in all dimensions? Maybe it would be worth checking out Ian McGlasham's excellent tutorial on the full use of Loop Tools > Curve, here. The operator also has a 'Linear' setting.. not covered, there, but you'll see.

I managed to find a work around as Loop tools modes all gave results I didn't want. Basicllally I wanted to pick first and last point and arrange the points in one true view axis. In this case X. I scaled to active in X, then used shear to get the angle..


text:
Procedural trail follow mesh
I'm trying to make a procedural trail in geo-nodes. But I have no idea how to make trail follow mesh position. Somehow I have to calculate movement direction and set position of points according to that but my math is terrible. Need help.

try this:
trail with icospheres:

or as curve:

result:

Hi Chris, I tried your suggestion but Instead of points follow my mesh behind, they do the opposite

Okey that worked. My mistake: I was using the same object to make trail and animate. I made two objects one for my animation and one for the trail. Thanks.

you are welcome


text:
How can I set and get the vertex color property?
I can't find a way to display RGB values (or equivalent) without using the python shell.
I would like to get and set color values numerically (ie. not painting), I can't find it for weight painting either (I expected it to appear in the "n" panel with something like "vertex" as a title).

Are you asking how to get the RGB of a color in weight paint mode?

Sorry for the late answer ! Yes, I needed a way to edit or read the color's data of a vertex, thanks for the nice answer @zeffii , but I'm looking for something in the UI, without Python. At the UI level why is it at face level ?

i'll edit my answer.

I would like to get and set color values numerically (ie. not painting),

There may be add-ons that cater to this, but at present (March 2016)

Blender doesn't have a (non-Python) way to set the Vertex Colors per selected vertex/vertices. Per face is however, as stated below, not a problem.

There is no built-in interface (yet) to get the rgb value of a selected Vertex. Each vertex can be shared by a number of faces, therefore a vertex doesn't necessarily have one color associated with it.  Behind the scenes the Vertex Colors are not stored in the data per vertex but in a Vertex Color layer, which stores vertex colors for each face of the mesh.
Possibly this explains that a bit more clear. There are 9 verts in this subdivided plane, and the middle vertex is used in 4 faces and therefore has 4 different colors associated.

Vertex Color Map
You can set a collection of faces to one colour in vertex paint mode, by selecting them and setting the colour from the colour picker, then shift+K (while the mouse cursor is inside the viewport) will fill the selection with that colour. You can  enter numericals into the Blender colour picker.
You can pick faces with face selection masking
If you want to do it by script:
import bpy
import random

# start in object mode
obj = bpy.data.objects["Cube"]
mesh = obj.data

if not mesh.vertex_colors:
    mesh.vertex_colors.new()

"""
let us assume for sake of brevity that there is now
a vertex color map called  'Col'
"""

color_layer = mesh.vertex_colors["Col"]

# or you could avoid using the color_layer name
# color_layer = mesh.vertex_colors.active

i = 0
for poly in mesh.polygons:
    for idx in poly.loop_indices:
        r, g, b = [random.random() for i in range(3)]
        color_layer.data[i].color = (r, g, b, 1.0)
        i += 1

# set to vertex paint mode to see the result
bpy.ops.object.mode_set(mode='VERTEX_PAINT')

Also a small blogpost about vertex colours here and here, if you are so inclined.
For Weight Painting, i'm not sure -- i'll let someone more familiar with that give an answer

How would you change this script to set the vertex colors equal to the value of the vertices themselves? I.e. each vertex RGB = XYZ?

How could I set the color to the value under the normal of a face or the approximate blended color if the vertices of that face are different?

@iKlsR using vertex_normals then, might be worth asking a separate question.

@iKlsR https://gist.github.com/zeffii/90399b67820dbf64628b vertex.normal

@zeffii The color under the normal or the color in the middle of a polygon. I've never used vertex paint programmatically before so not even sure the api allows this.

i don't know what you mean by 'color under the normal'.. https://gist.github.com/anonymous/6a74de7ea17a66b67c2f ?

best go for a new question, you will get some definitive answers - no doubt.

Sorry for the late answer... my question is about the GUI, not using Python. Vertex paint is vertex-based, right ? The face selection trick is almost ok, is there some way doing it per vertex as you can in Python ? I would expect it in edit mode, in some panel... but can't find it

Very helpful answer! If there is already a vertex color map that we want to keep, I figured out that we can modify the code as follows. 1. define a variable for the name: vcol_map = "Something" 2. Remove the conditional if not mesh.vertex_colors: and change the line below it to mesh.vertex_colors.new(name = vcol_map) (no indentation). 3. Define color_layer by the vcol_map variable instead of a name string: color_layer = mesh.vertex_colors.get(vcol_map) If the code is run a second time, the Something vertex color map gets renamed to Something.001 and a new Something is created.

If you happen to be working with .ply files (or can convert your model to that), I recommend using the Point Cloud Visualizer, like so:
from space_view3d_point_cloud_visualizer import PlyPointCloudReader

ply_filename = "some_file.ply"
point_cloud = PlyPointCloudReader(ply_filename).points

# get color of point at index 100
red = point_cloud['red'][100]
blue = point_cloud['blue'][100]
green = point_cloud['green'][100]

Update for 4.0 and the new Attribute API.
IN OBJECT MODE
import bpy
import random

obj = bpy.context.active_object
if obj.type == 'MESH':
    mesh = obj.data

    point_color_attribute = mesh.color_attributes.get("MyPointColors") or mesh.color_attributes.new(name="MyPointColors", type="BYTE_COLOR", domain="POINT")
    point_colors = [None] * len(mesh.vertices) * 4
    point_color_attribute.data.foreach_get("color_srgb", point_colors)  # Get Point Colors
    print(point_colors)

    for _ in range(len(mesh.vertices)):
        point_colors.extend((random.random(), random.random(), random.random(), 1))
    point_color_attribute.data.foreach_set("color_srgb", point_colors)  # Set Point Colors
    print(point_colors)

    corner_color_attribute = mesh.color_attributes.get("MyCornerColors") or mesh.color_attributes.new(name="MyCornerColors", type="BYTE_COLOR", domain="CORNER")
    corner_colors = [None] * len(mesh.loops) * 4
    point_color_attribute.data.foreach_get("color_srgb", corner_colors)  # Get Corner Colors
    print(corner_colors)

    for _ in range(len(mesh.loops)):
        corner_colors.extend((random.random(), random.random(), random.random(), 1))
    corner_color_attribute.data.foreach_set("color_srgb", corner_colors)  # Set Corner Colors
    print(corner_colors)

IN EDIT MODE
In edit mode the regular way to access attributes yields empty sequences. You have to use the bmesh construct.
import bpy
import bmesh
import random

obj = bpy.context.active_object
if obj.type == 'MESH':
    mesh = obj.data
    bm = bmesh.from_edit_mesh(mesh)

    point_color_attribute = mesh.color_attributes.get("MyPointColors") or mesh.color_attributes.new(name="MyPointColors", type="BYTE_COLOR", domain="POINT")
    point_color_layer = bm.verts.layers.color[point_color_attribute.name]
    point_colors = []
    for vert in bm.verts:
        point_colors.extend(vert[point_color_layer])  # Get Point Colors
    print(point_colors)

    point_colors = []
    for vert in bm.verts:
        vert[point_color_layer] = (random.random(), random.random(), random.random(), 1)  # Set Point Colors

    corner_color_attribute = mesh.color_attributes.get("MyCornerColors") or mesh.color_attributes.new(name="MyCornerColors", type="BYTE_COLOR", domain="CORNER")
    corner_color_layer = bm.loops.layers.color[corner_color_attribute.name]
    corner_colors = []
    for face in bm.faces:
        for loop in face.loops:
            corner_colors.extend(loop[corner_color_layer])  # Get Corner Colors
    print(corner_colors)

    for face in bm.faces:
        for loop in face.loops:
            loop[corner_color_layer] = (random.random(), random.random(), random.random(), 1)  # Set Corner Colors

    bmesh.update_edit_mesh(mesh)


text:
How to call a function on change in Enum dropdown list?
I have created enum dropdown list to change masking of an object by changing vertex group assigned
# On Enum change i want to trigger this function
def maskIt (self, context):
    #Do some thing here like bellow
    #bpy.data.objects["Suzanne"].modifiers["Mask"].vertex_group = "Group 2"

Creating Enum dropdown list here
def initSceneProperties(scn):
    bpy.types.Scene.MyEnum = EnumProperty(
        items = [('Group 1', 'Group 1', 'Group 1',1),
                 ('Group 2', 'Group 2', 'Group 2',2),
                 ('Group 3', 'Group 3', 'Group 3',3)],
        name = "Mask the MESH")
    scn['MyEnum'] = 2

Calling the function
initSceneProperties(bpy.context.scene)

Use the update argument of the EnumProperty.
import bpy

def maskIt(self, context):
    print('called and changed to,', context.scene.MyEnum)

class LayoutDemoPanel(bpy.types.Panel):
    """Creates a Panel in the scene context of the properties editor"""
    bl_label = "Layout Demo"
    bl_idname = "SCENE_PT_layout"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "scene"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        layout.prop(scene, "MyEnum")

def register():
    bpy.types.Scene.MyEnum = bpy.props.EnumProperty(
        items = [('Group 1', 'Group 1', 'Group 1',1),
                 ('Group 2', 'Group 2', 'Group 2',2),
                 ('Group 3', 'Group 3', 'Group 3',3)],
        name = "Mask the MESH",
        default = 'Group 1',
        update = maskIt)

    bpy.utils.register_class(LayoutDemoPanel)

def unregister():
    bpy.utils.unregister_class(LayoutDemoPanel)
    del bpy.types.Scene.MyEnum

if __name__ == "__main__":
    register()


text:
Getting the list of points that describe a Curve without converting to mesh
I've used mathutils.geometry.interpolate_bezier() in the past to create points for a curve using the bezier handle and knot coordinates.
from the docs:

interpolate_bezier(knot1, handle1, handle2, knot2, resolution)

My question is; given an existing curve in the scene, is there a neat way to get at the points that describe the curve without converting it to a mesh, or figuring out which handle (left or right) to use for each spline point.
curve = bpy.data.curves[0].splines[0]
curve.bezier_points[0].co
curve.bezier_points[0].handle_left
curve.bezier_points[0].handle_right

Note that there is/was a bug in the interpolation utility function that made it return 2D coordinates, even if the curve is 3D: https://developer.blender.org/T43473

The parameters can be found by taking the coordinate and right handle of a point, and the coordinate and left handle of the next point in the bezier points array.
For cyclic curves the last point and the first point in the array form an extra segment.
spline = bpy.data.curves[0].splines[0]

if len(spline.bezier_points) >= 2:
    r = spline.resolution_u + 1
    segments = len(spline.bezier_points)
    if not spline.use_cyclic_u:
        segments -= 1

    points = []
    for i in range(segments):
        inext = (i + 1) % len(spline.bezier_points)

        knot1 = spline.bezier_points[i].co
        handle1 = spline.bezier_points[i].handle_right
        handle2 = spline.bezier_points[inext].handle_left
        knot2 = spline.bezier_points[inext].co

        _points = mathutils.geometry.interpolate_bezier(knot1, handle1, handle2, knot2, r)
        points.extend(_points)

That's exactly what I'm looking for, thank you brecht!

I rolled this snippet into a function that takes a spline and a clean boolean (to remove consecutive doubles) : https://gist.github.com/zeffii/5724956


text:
Is it possible to create a compositor node with PyNodes that outputs camera clip_start and clip_end?
Im not looking for a how to, but some of you may know if this is possible or not. An example of a dummy node added to compositor would be much appreciated, i can't find any (or i'm looking in all the wrong places)
The PyNodes documentation is here, The TextEditor template Custom Node creates a custom node tree, but what am I supposed to do with that?

PyNodes do not make it possible to extend Blender Internal, Cycles or the compositor with new nodes.
They are designed to make user interfaces for new node systems. For example developers of external render engines can use them to make their own shader node systems, or an addon could make a new geometry node system.
It would of course be very useful if they did, but that would be a much bigger project, as it requires each node system to expose an API with access to its inner workings.

Thanks @brecht, i'm watching the Geometry Nodes addon like a hawk.

I don't know if there is actually a geometry nodes addon in development, it's just an example of something this could be used for.

there is / was http://wiki.blender.org/uploads/b/b9/Blender2.67_pynodes_geometry_nodes_addon.png https://www.gitorious.org/blender-trunk/addons/trees/geometry_nodes/py/scripts/addons/geometry_nodes

Not sure if this is possible with PyNodes, Seems like the sort of thing you'd use Drivers for.
You can use node settings to drive these values too,
Add a driver to the cameras clipping, and set the driver to point to a scene property, eg: node_tree.nodes["Mix"].inputs[0].default_value

And the other way around you can do too, of course. Add a driver to a value node, and set the driver to point to the camera property like clip_sta and clip_end.

using drivers is indeed a solution, but I have to accept the definitive answer by brecht on whether or not PyNodes could do it


text:
Run additional code after user has executed and finished an operator
The script https://gist.github.com/zeffii/5671824 creates a polysphere, but allows the user to set how spherical it is and how many subdivisions it has and its radius as parameters.
The problem is the sphere has doubles along all sides as a result of the way the geometry is created. Doubles are no good for sculpting -- and sculpting is the reason for the polysphere.
I would like to know if there is a way to automatically run remove_doubles(threshold=1.0e-5) just once, on the newly created object when the script is finished. (by finished i mean you can no longer adjust parameters)
edit:
I guess my alternative will be to construct the mesh without doubles in the first place, which is going to be a bit of a mind-bender or delete the mesh on each parameter adjustment and remove doubles too on each adjustment.
edit2
I reluctantly went for the delete / create / remove doubles combo, the script does work as desired from the point of view of the user. Script is here

at each setting change or when the user is happy with the overall thing?

Can you describe the workflow you intend in more detail? I assume you want quick updates but call remove doubles as a final step only once.

@zeffii it's tricky since as far as I know, there isn't a method from bpy.types.Op that cleans up like a destructor and nothing can execute after return.

@zeffii how about calling it at every modification at the panel?

@iKlsR, I tried this before posting, it didn't seem to be in the right context to apply the remove_doubles.

@zeffii ah true, to toggle back and forth would be awful.

when the user is happy with the settings. Is confusing, this makes it sound like its a user interaction to remove doubles as a part of the tool. Please try be clearer next time.

i'm certainly no Feynman, this was the best i could do.

No, at least operators don't have the notion of a final state.
I can see in some cases you may want to setup a tools options, then perform some action once the options are set.
You could use a pop-up dialog 1 (as image-new does), but then you dont get feedback when changing values.
Some script writers add toggles to their operators that perform some extra calculation, so the user can choose to quickly setup options then press this last, while this isn't in keeping with our intended workflow, it makes some sense if the operator can't give interactive feedback because they're so slow.
There is one way you might be able to do what you want, and that is to create a Modal Operator, see the example in the text editor templates.
This way you start a tool which has its own mode (like grab or rotate), you can choose to handle events to adjust the settings, then a key such as Enter can finalize the operation.
So this may work in some cases - but modal operators assume a fairly different workflow so it depends a lot on what you do.

I could try the modal form (I have coded a few of them previously) with a final button to accept. Will report back if I go this way.

I've accepted this, not because it solved my question immediately, but because it offers useful terminology for further investigation. Thanks!

In fact I misunderstood the question, I thought you wanted to run the tool, edit settings (using operator redo), then only remove doubles once at the end.

it would have been more optimal if i could remove doubles just once, instead of on every update. so at the time of asking the question, knowing what I did shaped how i formulated it.

The solution I arrived at goes like this, not sure if this is a hack or reasonable practice:
def execute(self, context):

    # this removes the existing mesh data, when user adjusts slider
    if context.object:
        bpy.ops.mesh.delete()

    # this deals with mesh repopulation
    verts, faces = make_polysphere(self)
    base = create_mesh_object(context, verts, [], faces, "PolySphere")
    context.object.show_wire = True

    # perform the final operations on the object.
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.remove_doubles(threshold=1.0e-5)
    return {'FINISHED'}

Therefore, perhaps the original question wasn't stated as accurately as possible.
edit:  this is buggy, I don't use it. Still trying to figure out a reasonable solution to the remove doubles problem.


text:
how to use BMesh to add verts, faces, and edges to existing geometry
I've puzzled about this for a while, but haven't found an answer I understood. This snippet below does add geometry (3 verts and a face) but it also generates an error, Does going to object mode make the data reference in bm be cleared? if so, how does data.vertices still get updated?
ReferenceError: BMesh data of type BMesh has been removed
Error: Python script fail, look in the console for now...

any ideas, this is the cut down script ( run it with a cube in edit mode)
import bpy, bmesh

obj = bpy.context.object
bm = bmesh.from_edit_mesh(obj.data)

bm.verts.new((2.0, 2.0, 2.0))
bm.verts.new((-2.0, 2.0, 2.0))
bm.verts.new((-2.0, -2.0, 2.0))

set_of_verts = set(bm.verts[i] for i in range(-3,0))
bm.faces.new(set_of_verts)

bpy.ops.object.mode_set(mode='OBJECT')
bm.to_mesh(obj.data)

I have a few scripts that might benefit using the BMesh module for adding geometry, I know how to do it in the pre BMesh way.
Edit, using answer: here's how to add tris and quads while staying in edit mode https://gist.github.com/zeffii/5668669

Instead of set_of_verts you could also use the return-value of the bm.verts.new(...) which is exactly the vertex you want.

you should make a proper answer then, show the neatest way.

Alternatively, if you want to keep your current approach, you can replace it by the simpler bm.verts[-3:].

The issue with this script is when you exit editmode, the editmesh you were editing becomes invalid (thats good, but not what you want).
So instead, just exit editmode and blender will handle converting the modified bmesh into the object mode mesh data.
import bpy, bmesh

obj = bpy.context.object
me = obj.data
bm = bmesh.from_edit_mesh(me)

v1 = bm.verts.new((2.0, 2.0, 2.0))
v2 = bm.verts.new((-2.0, 2.0, 2.0))
v3 = bm.verts.new((-2.0, -2.0, 2.0))

bm.faces.new((v1, v2, v3))

bmesh.update_edit_mesh(obj.data)

# This is optional, you could also stay in editmode.
bpy.ops.object.mode_set(mode='OBJECT')

Note, if you want to stay in editmode, call bmesh.update_edit_mesh(me) at the end of the script to ensure ngons are re-triangulated for display.

OP can also see http://www.blender.org/documentation/blender_python_api_2_69_release/info_gotcha.html#edit-mode-memory-access for more details

Thanks @ideasman42 : bmesh.update_edit_mesh(obj.data) directly fixes my problem. This wasn't clear from docs,  which in this case I didn't find very useful (even the current docs).

The issue is clearly the one already mentioned in other answers, the editmesh becomes invalid when you exit Edit Mode. But there is a "simplification" for your script.

Note: Every variable t_* will become invalid once you exit Edit Mode

So here is the simplified script:
import bpy, bmesh

obj = bpy.context.object
me = obj.data
t_bm = bmesh.from_edit_mesh(me)

t_v1 = t_bm.verts.new((2.0, 2.0, 2.0)) # the created vertex
t_v2 = t_bm.verts.new((-2.0, 2.0, 2.0))
t_v3 = t_bm.verts.new((-2.0, -2.0, 2.0))

t_face = t_bm.faces.new([t_v1, t_v2, t_v3]) # .new() always returns the produced (bmesh-)object
# Saving the vertices/edges/faces for backreference.

# Once you run this command you cannot access the bmesh anymore
bpy.ops.object.mode_set(mode='OBJECT')

Almost every .new() on any list will return the newly added data.


text:
Is it possible to print to the Report window in the Info view?
I wonder if it is currently possible to print or send messages to the Report window in the Info view? this would be quite useful sometimes.

We can always use an operator's report method. Running the following operator:
class RENDER_OT_test(bpy.types.Operator):
    bl_idname = 'render.oha_test'
    bl_label = 'Test'
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        self.report({'INFO'}, 'Printing report to Info window.')
        return {'FINISHED'}

prints this in the Info window:

The color depends on the type enum: INFO gets green, WARNING light red, and ERROR dark red. I don't see reference to any direct output to Info window, other than this method.

i made this snippet to demo a problem i've experienced: https://gist.github.com/zeffii/5734884  , say I try to call this operator from a place in a script using bpy.ops.render.oha_test() i get `Undefined Type: Printing report to Info window.
{'FINISHED'}` and there is no printing to the report window..

When the enumeration type is only INFO, WARNING or ERROR, the message is prefixed accordingly (e.g. "Info: ..."). But if we add DEBUG, the prefix turns to "Undefined Type: ...". Maybe we're dealing with a little quirk (bug?) in the C function related to flag-reading. Gotta read the source to make sure, but I don't think it's an error. (and report doesn't output to report area if executed on a Python interpreter area)

I don't think multiple values were intended to work, just use one value. They are more like importance levels where DEBUG is the lowest and ERROR is the highest.

@brecht I don't know how it's supposed to be used, as there's no documentation. Just trying combination and it just works. And only specifying DEBUG outputs nothing, either in shell, Info's report area or header.

I don't know if combinations should be allowed, but they were not really intended in the design, so maybe something should be fixed in Blender. That's why I suggest to change the example to use only 1 value.

Oh, the code in blenkernel/intern/report.c uses switch instead of bitwise ops. That explains...

OK, thanks guys. The takeaway here is once the script is running it is reasonably easy to send messages to the info window. example: https://gist.github.com/zeffii/5735019

@brecht Ah yes, it does nothing. Combining DEBUG and other type suppresses output to Info area's header, though, which led me to think it has some use :) I concede that it's probably unintended.

I tried the sample but I cant get message in the info view..
`import bpy
class RENDER_OT_test(bpy.types.Operator): bl_idname = 'render.oha1_test' bl_label = 'Test' bl_options = {'REGISTER', 'UNDO'} def execute(self, context): self.report({'INFO'}, 'Printing report to Info window.') return {'FINISHED'} bpy.utils.register_class(RENDER_OT_test)`
test call to the newly defined operator
bpy.ops.render.oha1_test()

After running the script, execute the operator as bpy.ops.render.oha1_test in Python console or as Test in spacebar-menu. Works for me.

I needed to display a notification message when running a script in the Text Editor by hitting the 'Run Script' button. For exactly this purpose I have found a hack that works, even if this is not the preferred way :)
import bpy

def oops(self, context):
    self.layout.label(text="You have done something you shouldn't do!")

bpy.context.window_manager.popup_menu(oops, title="Error", icon='ERROR')

with newer version of blender 2.9x use self.layout.label(text="You have done something you shouldn't do!")

This should be the code: to get popup in mouse event use ERROR instead INFO.
see report
-'INFO' is lower and 'ERROR_OUT_OF_MEMORY' is highest level of error type.
def yourfunction(context):
    whatever the function

class RENDER_OT_test(bpy.types.Operator):
    bl_idname = 'render.oha_test'
    bl_label = 'Test'
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        try:
            yourfunction(context)
            return {'FINISHED'}
        except:
            self.report({'INFO'}, 'Printing report to Info window.')
            return {'CANCELLED'}

basically is the already accepted solution of 4 years ago...

The accepted answer doesn't work without try condition in Blender 2.79 and the return statement and code blocks are clarified here.


text:
Scripting Grease Pencil and choosing data layer to be linked
I like how gpencil lets me draw shapes and link the data to specific objects or the scene. I have a trigonometry script which generates shapes, but I can't seem to select which 'Data to be linked' from a script.

The following script is a reduced version of what i'm doing, but it shows that the layer and data creation is easy enough.
import math
import bpy

def get_layer(gdata_owner, layer_name):

    grease_data = bpy.data.grease_pencil
    if gdata_owner not in grease_data:
        gp = grease_data.new(gdata_owner)
    else:
        gp = grease_data[gdata_owner]

    # get grease pencil layer
    if not (layer_name in gp.layers):
        layer = gp.layers.new(layer_name)
        layer.frames.new(1)
        layer.line_width = 1
    else:
        layer = gp.layers[layer_name]
        layer.frames[0].clear()

    return layer

def generate_gp3d_stroke(layer):
    layer.show_points = True
    layer.color = (0.2, 0.90, .2)
    s = layer.frames[0].strokes.new()
    s.draw_mode = '3DSPACE'

    chain = []
    num_verts = 10
    r = 2.2
    gamma = 2 * math.pi / num_verts
    for i in range(num_verts+1):
        theta = gamma * i
        world_point = (math.sin(theta) * r, math.cos(theta) * r, 1.2)
        chain.append(world_point)

    s.points.add(len(chain))
    for idx, p in enumerate(chain):
        s.points[idx].co = p

class TrigGenerator(bpy.types.Operator):

    bl_idname = 'mesh.trig_generator'
    bl_label = 'generated trig with gpencil'
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        obj = bpy.context.object
        data_name = 'stack_data'
        layer_name = "stack layer"
        layer = get_layer(data_name, layer_name)
        generate_gp3d_stroke(layer)
        return {'FINISHED'}

def register():
    bpy.utils.register_class(TrigGenerator)

def unregister():
    bpy.utils.unregister_class(TrigGenerator)

if __name__ == '__main__':
    register()

it's probably simple, but it eludes me.

update:
the one line fix is the last line of execute:
def execute(self, context):
    obj = bpy.context.object
    data_name = 'stack_data'
    layer_name = "stack layer"
    layer = get_layer(data_name, layer_name)
    generate_gp3d_stroke(layer)
    context.scene.grease_pencil = bpy.data.grease_pencil[data_name]
    return {'FINISHED'}

I'm not sure if this is what you are looking for but:
bpy.context.scene.grease_pencil = bpy.data.grease_pencil['GPencil']

will set the scene's active grease pencil datablock to be 'GPencil'.
I found this by using autocomplete in the Python Console to see properties of the Scene.
As with other datablocks in blender you can also set scene.grease_pencil to be None to have no active grease pencil datablock.

yep, that's the one. bpy.context.scene.grease_pencil = bpy.data.grease_pencil['stack_data']

woah, I didn't thank you. Thanks! I must be very dim sometimes.

@zeffii No problem, everyone needs help sometimes.

Grease pencil can be attached either scene or object.
Change grease pencil source from scene to object.
bpy.context.object.grease_pencil = bpy.context.scene.grease_pencil

Then you can select grease pencil setting.
The code below set parent for the first layer.
bpy.context.object.grease_pencil.layers[0].parent = bpy.object.context


text:
Fixing intersecting mesh due to sculpting?
I am sculpting a mesh using dynamic topology. I accidentally got an intersection between two parts of the mesh. This happened because I used the clay brush, and I "extruded" the bottom part into the top part. The problem is that it happened too long ago to be able to undo it, or revert to saved. How can I do this without losing my work?

I was able to fix it by applying the smooth brush with a high strength to the intersected area.


text:
Render just part of a final image from Cycles?
I'm using an older Nvidia chip that hates running viewport renders, and I need to check if changes to the materials on a few objects not far from the center of my scene are (I'm rendering a floorplan with an orthographic camera from above, so I'm looking down on objects and want to check if the displacement materials are working correctly).
Is there any way to select a bit of the image and have it render first or without having to render the rest of the image? I'm aware that you can tell the image to render from an edge, but my stuff's about equidistant from either side of the scene.

classically this is called 'border rendering' or 'region rendering'.

Ctrl + B in the 3D Viewport or the Camera View will allow you to drag while holding  LMB select the area of the image you want to render. If you want to clear the border, press Ctrl + Alt + B.
Shift + B also still works in Camera View but is only there for compatibility and will be replaced entirely by Ctrl + B in future versions.
For "Render->Render Image" (F12 ) to render only part of the image you also need to have Render->Dimensions->Border enabled.

You know, I was working yesterday and bumped into that on accident, without realizing what I was doing, outside of the camera view mode (so it did nothing), and totally proceeded to completely disregard it. Great answer!

"outside of the camera view mode (so it did nothing)" if you're in Viewport Render Mode, it will only render that segment, so long as you keep the view facing that way.

In the render tab I expanded the Dimensions section and checked "Bord", then I selected an area with ctrl-B in the 3d view. F12 still renders the whole image.

You have to select the region (Ctrl +B) on the main view, not on the secondary view, if you have split the view. I had split the screen so that the left showed little "Rendered" and the right showed big "Solid". I selected the region on the left "Rendered" view so pressing F12 rendered the whole scene. I selected the region on the right view and it worked.

Is there a way to get the selected render region to move with an animation?

If one would like to re- render an object in an animation
(without rendering the whole frame), i would highly recommend this addon :
https://blendermarket.com/products/animated-render-border/
It tracks an object trough your animation and renders it with a border around it,  so in Blenders video Editor, you could overlay your fixed object partial image over the wrong frames.

You can create another camera, and place it so that you zoom closer in on the scene (use the techniques outlined in this post What's the quickest, easiest way to point the camera somewhere in blender?). You can set the scene to render using that camera instead of your main one by selecting that camera in the Outliner.

Also a good answer, but a little bit liable to cause issues; reflections are often based off of camera perspective, so while top-down orthographic views like I'm using are fine with this, you'd be better off doing Charles' method for this, especially if working with a camera that has fisheying going on.

@KyleWilley You should also be able to zoom the camera in place by selecting local coordinates, then scaling it in its axis of view like any ordinary object.

But the issue I'm referring to is unique to perspective cameras; with orthographic ones this method is fine, because there is no distortion built into the renderer; you're getting the pixel directly in front of the camera. With a perspective camera you're not doing this.
For instance, to get a perspective "floorplan" to show stuff pushed up against the walls of a room from directly above, you'd have to pull the stuff out from the walls a good deal, because you're getting stuff based off of the aperture of the simulated lenses.

Yes, but the field of view affects distortion, does it not? Aperture is not necessarily the correct term here, but I'm not great with real life cameras.
If my FOV is 70, I see a lot less "fisheye" on the edge versus if it's 170 (Ah, Quake).

@KyleWilley I figured out how to zoom in place, and added a second answer describing that technique.

One option is to change the focal length of the camera. This has the advantage of working in all views, not just orthographic. It keeps the perspective of the camera the same, so it doesn't affect lighting or distortion, but instead works much like zooming on a real-life camera.
Select the camera in the 3D View or Outliner, then go to the Camera tab in the Properties menu. Under lens, you can change the 'focal length' (in perspective or panoramic view) or 'orthographic scale' (in orthographic view).
Original render:

Zoomed render:

Notice that the lighting levels on each of the panels of the sphere remain unchanged between renders.

A small caution to add here is that it doesn't necessarily work for off-center things, nor does it necessarily reduce render times.


text:
I baked a normal map on this mesh, but now it reflects light in a weird way. What can i do to fix this?

I baked a normal map on this mesh, but now it reflects light in a weird way. the upper part turns dark!

Normal map

Wire frame

And nodes.
My intintions are to have the light bounce off the plain as if it were flat, like this ...

Can you show wires/the normal map/nodes etc and explain how you expect it to display? At the moment there isn't enough info.

Please use your OS' screenshot functionality (e.g. the 'print screen' key)

Photos of your monitor are very hard to read and not helpful at all in diagnosing shading or graphic issues, please use the OS screenshot feature

@Sazerac blender has its own built-in screenshot.

don't know if this would fix it but you should have the "normal map" node between the image texture and bsdf diffuse nodes

I believe you have to use a "Normal map" node before you plug your texture into the normal node of the diffuse shader.
Shift+A -> Vector -> Normal map.


text:
Boolean modifier not working, tried solutions suggested in similar articles
I have recently tried to make vice and when using the boolean modifier to create holes for screws, it didn't work. I selected the main body, added modifier and chose my cylinder that was supposed to make the screw hole. Since I needed the "difference" setting, I selected it and all that happened was that the cylinder just stayed there and didn't create the hole I needed. I have checked youtube tutorials, questions and answers on this topic on this website and tried the solutions people suggested, yet nothing worked. Could someone help me solve this problem and tell me what I'm doing wrong?
Thank you in advance
Notes: I'm using blender 2.79b

Maybe the same Problem as here: https://blender.stackexchange.com/questions/144532/boolean-modifier-issues-engraving-text-on-to-a-face/144538#144538

could you please share your file? https://blend-exchange.giantcowfilms.com/

SOLVED
As Robert suggested, it was the same problem that was described in the article he linked, so big thanks to him for helping me out.


text:
how to create fluid simulation in glass?

how to create fluid simulation in glass?

what exactly is the problem you're having? have you tried searching for a tutorial or other questions here?

There is a video you should be able to figure out the minor  changes but other wise there.
https://m.youtube.com/watch?v=YgwKPP2ZEjI


text:
2.8 Weight painting mirror issue
I've rigged a model and applied automatic weights. I went into weight painting mode to touch up and refine the bendy parts, I selected the left thigh bone and applied mirror with topographical mirror.

This streak across the auto-weighted area stays in the same spot when I select the right thigh as shown here:

It seems like mirroring does not work, it pastes changes from one side to the other after the options become enabled. I've been fiddling a little bit with the options to find out how to edit the pre-existing weights and have the operations applied for the bone's siblings as well. I also note that when topographical mirror is not enabled, the changes are not even applied in any form to the other bone. I appreciate any help and information to help with this problem, or if I'm misconstruing some options and coming to bad conclusions.

I tried the same thing and had the same problem.  I will mention that this is supposed to work.  side note: are your bones named correctly?

I believe so, unless blender is case sensitive. The name of the bone mapped to the vertex area I was painting on is named thigh.l and it's sibling bone was thigh.r .

That should probably work, but if you want you can try renaming those two bones to thigh.L and thigh.R, but I don't think it will make a difference.   This is annoying, because this is supposed to work, but doesn't for some reason.

I believe there is a way to mirror the weights after you have already made the adjustments on one side, but I'm not sure where that option is found.


text:
Motion Tracking: When will "Prepass" enhance Motion Tracking quality?
I tried to figure out, when Prepass should be used in the Motion Tracking Settings. I understand from the wiki that...

Prepass
Enables a two pass tracking, where the first pass is a brute force tracking of location only, and the second pass will use tracking of the full motion model refining the first pass.

However, I don't yet know if enabling it if I want to track a marker in a video with fixed lighting and a fixed camera will improve my tracking quality.
Under which circumstances is Prepass advantageous and when should it not be used?


text:
My character is incomplete when I render with the gpu in cycles
I'm trying to render my animation, but when I do, the character appears incomplete. For some reason, if I render with the CPU this doesn't happen.

Hello and welcome to BSE. Impossible to know without more information. Can you perhaps share your blend file https://blend-exchange.com


text:
Modify frames of a non-visible object
I want to extend an animation that has already been created. Originally, it has 550 frames, but I want to lengthen it to 750.
To do this, I want to move all the frames from 250 onwards.
I tried to disable "only show selected" option on the timeline to see all keyframes, but it only works for objects that are visible. Is there a way to see the keyframes of absolutely all objects, including non-visible ones? or maybe another way to achieve what I want?

In the Dopesheet window, there's a button that enables the "Show Hidden" function, next to the "Only selected" one.

Good to note that, because Blender makes hidden objects non-selectable, you need to enable "show hidden" AND disable "only selected"


text:
Distribute instances along a curve equidistance on cuve projection on a plane
complete beginner here, so bear with me please!
I would like to create a palisade fence with the help of the geometry nodes. At first sight it seems simple: Curve --> Resample --> instance on points.
Now, my problem is that the fence goes steeply up at one point, and I want the instances to be equidistant on the projection on the horizontal plane to prevent the poles from overlapping each other.
I tried creating a linked object of the curve and shrinkwrapped it on the horizontal plane, but then I'm stuck. I now have the choice of creating a fully horizontal fence with nicely spaced poles (taking the shrink-wrapped linked object as base) or one that goes up and down, but with unevenly spaced poles (taking the original curve as base).
Is it somehow possible to tell Blender to either transpose each instance on the projected curve up to the projection's originator, or to resample the curve with projected equidistance in the first place, or get the required result in yet another way?

if you save the z-position of your original curve, then just set z of your curve to 0, resample by length, then restore old z position and instance your poles:

Wow.... just.... wow..... I cannot express how amazed I am about the versatility of these geometry nodes, and how incredibly fast I got such a great answer to my question, perfectly explaining me how I can solve my problem! THANKS A LOT!!

you are welcome


text:
viewport overlays for grease pencil are not visible
I am new to blender and currently running blender version 4.2,
I tried to enable canvas for my grease pencil object but I couldn't find the canvas option in viewport overlays,
I also checked the documentation, it says grease pencil object needs to be selected to enable grease pencil options but I am not able to enable it even after selecting grease pencil object.
Please tell me if there is anything I am doing wrong

When you have a Grease Pencil object selected, a Grease Pencil menu appears next to the Viewport Overlays drop-down. The icon is two squares connected by a looping line. The Canvas option has been moved into this menu.


text:
Import camera animation from Maya 2014
There's a bunch of import/export formats common to both Blender and Maya, but which of them support animation? FBX is supposed to, but for now our addon doesn't support that yet.
Specifically, I need to get animated cameras from a Maya scene into Blender.
One way would be to export a file for each frame (which would need markers and attaching cameras to them to make each frame's camera the active one for that frame) but that wouldn't work with motion blur.

The DAE_FBX exporter works, just select the cameras and use File > Export Selection > (channel box) DAE_FBX Export. The usual y-up versus z-up happen, but otherwise it's fine:

OpenCOLLADA supports animated cameras and the SDK includes a Maya plug-in. Setting the active camera might need to be redone manually.

It seems to be only compatible with Maya 2008 to 2010, I'm using 2014

The separate plug-in for OpenCollada format works with Maya versions 2013 and below. Maya 2014 and forward comes with OpenCollada built into the .fbx exporter. Make sure to turn on fbxmaya on in your plug-in manager and choose the dae_fbx export option PeterT mentioned above.

This method works for cameras but doesn't work for animation on objects or characters. For that you'll need to use a .mmd and a saved .obj of your object to transfer to Blender. You can download the script here: http://www.creativecrash.com/maya/script/maya-to-houdini-particles-mdd-obj-exporter