text:
Add-on Dev: Extract int value from Blender's enum flag set?
Is there any way to extract an int value from one of Blender's ENUM_FLAG properties? Here are the definitions I have:
# binary flag values
class OpFlag:
    GA = 1<<0 # activator for asset mode
    LP = 1<<1 # activator for low poly mode
    HP = 1<<2 # activator for high poly mode
    CU = 1<<3 # activator for custom mode

# string based flag values for Blender controls
opflags=[
            ('GA', "Asset", "desc", OpFlag.GA ),
            ('LP', "Low", "desc", OpFlag.LP ),
            ('HP', "High", "desc", OpFlag.HP ),
            ('CU', "Custom", "desc", OpFlag.CU )
        ]

# property using flags
modes : EnumProperty(
    name = "Modes",
    options = {'ENUM_FLAG'},
    items = opflags,
    default={'GA','LP','HP','CU'}
    )

This is what I would like to be able to do, if possible:
control_op_flags = int( 0 ) # just to make it obvious this is an int
control_op_flags |= int( modes )

I read somewhere online that you can cast a Blender string-based enum value to int, but it doesn't seem to work with an enum-flags set. This is the error I get:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'

Does anyone know how to convert an enum-flags set into a single int? I didn't consider it until just now, but is it possible to iterate the set and convert/OR all of the values together myself? Would that be the proper way to handle this? I've never iterated a set before, so going to investigate that now.
Edit Update: When I try to iterate the set and OR in one entry from it, I get the error ValueError: invalid literal for int() with base 10: 'GA'.. Sounds like it is dealing with it purely as a string. I'm not sure how to associate it with my opflags list.
Thanks for any advice

You can access the value through the RNA properties. Assuming that you have stored modes in a PointerProperty and assigned to bpy.types.Scene.demo_tool (just an example), you can access it in the following way:
The first step is to get access to the RNA properties of demo_tool or in general the object that contains your EnumProperty. This will give us access to the underlying data structure of modes which contains the mapping to the integer values.
demo_tool = bpy.context.scene.demo_tool
items = demo_tool.bl_rna.properties["modes"].enum_items

The enum_items give you access to a collection (bpy_prop_collection) of EnumProperties which represent the valid (single) flags you can use. It allows a look-up with a key. For example the following code gives you the integer value for your 'LP' flag, by accessing the EnumPropertyItem.
items['LP'].value

Since you have a set of strings stored in modes when using options={'ENUM_FLAG'} you must iterate through it to get the integer value for each flag.
for flag in demo_tool.modes:
    print(f"{items[flag].value}")

Once you have the integers you can perform the boolean logic operations to create a single value.

import bpy

class DemoSettings(bpy.types.PropertyGroup):
    GA = 1 << 0  # activator for asset mode
    LP = 1 << 1  # activator for low poly mode
    HP = 1 << 2  # activator for high poly mode
    CU = 1 << 3  # activator for custom mode

    # string based flag values for Blender controls
    opflags = [
        ('GA', "Asset", "desc", GA),
        ('LP', "Low", "desc", LP),
        ('HP', "High", "desc", HP),
        ('CU', "Custom", "desc", CU)
    ]

    # property using flags
    modes: bpy.props.EnumProperty(
        name="Modes",
        options={'ENUM_FLAG'},
        items=opflags,
        default={'GA', 'LP', 'HP', 'CU'}
    )

class DEMO_PT_panel(bpy.types.Panel):
    """Creates a Panel in the scene context of the properties editor"""
    bl_label = "My own addon"
    bl_category = "Name of your tab"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"

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

        row = layout.row()
        row.prop(demo_tool, "modes")

        items = demo_tool.bl_rna.properties["modes"].enum_items

        flag_value = 0

        for flag in demo_tool.modes:
            flag_value |= items[flag].value

        row.label(text=str(flag_value))

classes = (DemoSettings,
           DEMO_PT_panel)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)
    bpy.types.Scene.demo_tool = bpy.props.PointerProperty(type=DemoSettings)

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)

if __name__ == "__main__":
    register()

Your knowledge (and/or ability to find information) is really impressive. Thanks for this detailed answer. For some reason, I keep getting the error bpy_prop_collection[key]: key "modes" not found. Would this be because I'm storing "modes" inside of an operator class? Using properties inside of operators is very new for me, so I may be doing something else wrong. I am able to access modes normally, but self.bl_rna.properties["modes"] throws this error. Would there be an obvious reason?

@Robert Thank you! I'd have to look into that.


text:
The lambda problem - how to send a constant value through it
Is it possible to send a constant value to a (function-pointer-like) variable that makes use of lambda? Here is a very simplified version of what I want to do:
for p in range(property):
    property[p].update = lambda s, c: DoUpdate( s, c, p )

I would like the third arg p to be converted into a constant value. Or to send the value rather than the variable. Is this possible? To have p evaluated immediately?
I've seen answers that show to do it this way:
for p in range(property):
    property[p].update = lambda s, c, arg=p: DoUpdate( s, c, arg )

But I'm getting TypeError: update keyword: expected a function taking 2 arguments, not 3
Does this solution not work for Blender specifically? Or maybe I am doing it wrong? Does anyone know of a trick to convince lambda to record the value instead of the variable?

This works properly in Blender, since it uses a regular Python underneath. The following example uses a lambda with a default argument in order to evaluate the argument during declaration:
def test(a, b, c):
    print(f'a = {a}\nb = {b}\nc = {c}')

a = [1, 2, 3]
b = 2

x = lambda a, b, c=len(a): test(a, b, c)
a = [1, 2, 3, 4]
x(a, b)

The lambda uses a default argument for the third parameter, which is evaluated right away. The output is therefore:
a = [1, 2, 3, 4]
b = 2
c = 3

c still has the original length of a which was changed after declaring the lambda.

The issue that you're having is unrelated to the lambda though. The update callback is expected to take exactly two arguments. This is checked in the properties (bpy_props.c) through:
if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
  return NULL;
}

If you can supply a function that takes two arguments it will work properly.

Have you tried using this setup as a property update function? For some reason, my properties will not register when I do this.

As the updater for properties of a dynamic class, but a setter would also be ok: property[p].update = lambda s, c, arg=p: DoUpdate( s, c, arg ) ..It appears that Blender is specifically counting the number of parameters, rather than just trying to call it. Any idea how to solve this situation? I'm still trying to learn Python, but I'm guessing the reason lambda works with variables that fall out of scope is because it increases their reference count. Any variable data used in it will remain alive until the lambda dies. Is that right? If so, I may be able to take advantage of it.

Ran out of space. The problem I'm facing is forcing lambda to generate a new variable for each property, rather than using the same one each time. If all of the properties use the same temporary variable, they will all end up using the same value (the last one). So I'm hoping there is some way to force a new one to be generated each time.

I'll investigate this.

Really appreciate your efforts. I'm also playing around with it, but it feels like chasing my tail - or trying to fix the logic of a time travel device. Even if you can think of a way to use global variables in the lambda (a different one per property), that would be helpful. I may end up having to manually assign each lambda outside of a loop. I wonder if its possible to edit a lambda after creating it..

@Robert unless I'm mistaken, your approach doesn't work because the update function is required to have only self and context as arguments. Using a function with three or more parameters even if they are optional ones, doesn't work. This has nothing to do with lambdas though.

Like I said, it looks like Blender is counting the number of parameters rather than just trying to call it. I doubt there is anything that can be done with the outside parameters of the lambda, but it may be possible to convince the inside execution code to send unique data for each property. I will continue looking.

Correct. When you declare a property and pass a update callback function, it will call bpy_prop_callback_check(update_cb, "update", 2)(bpy_props.c). It checks if you have exactly two arguments.

Apparently, its as simple as defining the lambda in another function (see other answer)

With some help from the main board, it looks like defining another scope for the lambda will force it to generate a new instance for each use:
def MakeUpdateLambda(func,parm):
    return lambda s, c: func( s, c, parm )

for p in range(property):
    property[p].update = MakeUpdateLambda( DoUpdate, p )

source: Stack Exchange

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

sort: votes


text:
3D View not showing ortho view even when it says it is?
New here, about 6 mos on Blender, mostly in 2.78 and 2.79... so I'm sure I'm overlooking something.
I don't know how to describe this... but Blender's lying to me. I'm trying to go to top orthographic view for a model, but even though I'm hitting 9 on the numpad, and it's showing the right thing in the upper left corner of 3d view, but this ISN'T orthogonal view.
I'm COMPLETELY confused at this point and don't know how to begin troubleshooting except a reinstall... Running 2.79, nothing that SHOULD affect this as far as addons (that I know of).
http://i1160.photobucket.com/albums/q486/BeyondNERVA/Ortho%20problem_zpslfi8azsd.jpg1
[]1

For clarification, that's IMMEDIATELY after hitting 9 on the numpad... repeated pressing of 9 doesn't change the issue, but if an object isn't selevted it shifts the grid outside the viewport so I can't see the model or the origin. shift+cmb to re-center leaves it at apparently the same angle,but a few grid dimensions away from being seen. That may help...

Well I don't know what numpad 9 does, but for the 3 main views there is numpad 1,3 and 7 (or ctrl 1,3 and 7) for the reverse direction. Numpad 9 does not forcibly align the view to one of the global main axis.
Another possibility would have been, if you had changed the "Global" option in the transform orientation pane, but it looks fine on your screenshot.

Wow... I typoed twice. That's a way to make a good impression. ;P
It would show side orthos, but not top, even when I hit the correct button (7). I'm booting it up again today after having the computer shut down. Maybe the 4th time is a charm.

could you upload your blendfile at https://blend-exchange.giantcowfilms.com/

I realized that there was an update for Blender that I didn't have during my searches, so just installed the new version and it's now behaving normally. No clue WHAT the problem was, but it's gone now!

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


text:
UV mapping problem - separated triangles instead of one surface
I'm new to blender so this is certainty a simple question but i have searched for a solution and can't find any.
I am trying to UV map an imported CAD model which is a simple beam (se picture below). The problem is that what is one single surface gets divided into several separated triangles in the UV mapping. How do I merge the triangles into one surface?

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

Hello :). Please choose an answer to mark as accepted, or write your own solution. (it keeps popping up as unanswered). Big thanks.

Just answering this, so it can be removed from unanswered :).
You need to

Apply scale (its at 0,001)
Merge double vertices (122 overall)
Then UV unwrap

first of all, your edges may not be conected,example: Try going to the vertex selection mode and merge all vertex that overlap(if you are with difficulty to select them go to the wireframe mode [press Z] and use box selection [press B] to get all of them ).

if you are willing to remake all the mesh properly, make everything from a cube or a plane extruding it faces, i dont know how you got to the triangles.
Now that your mesh is fixed, you need to mark the seams in order to get a proper uvmap.

NOTE: only mark seams were you want to get cut in your UV map.
if you want to know more about uv maps or modeling i recommend to watch tutorial before, it really helps.
hope this helps.

Here You have a short video: https://www.youtube.com/watch?v=V6OXSR5Ynyc. Everything needed is there with seam marks for sure. As Diogo said next time please try to model object Yo-self cause imported thing could cause troubles especially when made from triangles.

Thank you for the answers. Unfortunately I still don't get it to work. I have watched all tutorial I can find about UV mapping but in all the tutorials the model is very simple and the goal is often to "cut" the model to make the UV map better. But in my case I want to do the opposite, to join parts in the UV map.

The background to why I am imported the model instead of creating it myself is that in my work as a production engineer I am importing a CAD model of our factory into a VR model using Unity. The picture i attached in my question is only a very small part of a much more complex model. So to re-create all the parts would take too long.

I would much appreciate if you can take a look at my model that i attached in the comment of my question and see if there is something that can be done to make a better UV mapping. If it is not possible I will remake the parts like you suggest but only the parts that is most important and live with that most of the parts don't have any texture.

I think that a good part of the problem is caused because its an imported file, try finding better ways to convert the cad file to blend or simply start everything from scratch in blender because maybe fixing this problem in every model would take longer then fixing what is causing


text:
Weird Texture stretching

I have this weird texture stretching on the top of the barrel, how can I fix it. I tried box projection, didn't change anything. I have subdivision modifier active. Thanks

please share the UV map screenshot of the object

This is actually without making any seams,default UV I think, I tried adding some, it showed different results but none of them was actually correct. So I assume I am not doing something right. Thanks!

In UV editor try "Average Island Scale" and then "Pack Islands".

@MarkusvonBroady didn't help, tried but same problem still ocurs. Thanks anyway

overlapping edges made that error.

Try selecting it and scale it down.
you can use the uv sync selection as your help in selection.

also try to change your seam to a better suited position.

It is, but actualy there is three overlapping edges, and even some more vertices.I don't know how I managed to do it but I can't fix it right. Even if I scale them all, of 2 of them or just one. Maybe going over again this top part is best idea.

if it's too complex just add a seam in the problematic area and unwrap it again

That helped, still no 100% accurate but it will not be seen from very close distance so it will manage. Thanks!

np. updated the answer for a suggestion on uv seam.

When you are modeling a 3d object you need to study it.
How a wooden barrel built?
check this out:

A wooden barrel is made from a set of wooden boards (with a concave shape) disposed in a circular way to create the external structure.
The head is just a cylinder put on the top of the barrel. It's another material and another piece.

So I suggest to rethink your object starting from different 3d shapes. The textures will follow easily when you'll have better parts. Check this shapes:

Very nice suggestion for future 3d models and workflow, seems complicated, but probably worth a try. Thanks for advices!

While a nice overview this in no way addresses the actual problem at hand ergo not an answer.

Try selecting the center vert/loop on top and use Ctrl + Numpad + to Select More until you've grabbed the necessary loops and then try adjusting your UVs.


text:
Volume Absorption density of whiskey
In fluid in a glass it mentions using a volume absorption node. Below are the settings suggested for red wine in the answer from @gandalf.

Any clues re  what settings, particularly  density, to use  for whiskey?

are you talking about bubbles within the liquid?

https://blender.stackexchange.com/a/35731/15543


text:
I'm not have shortcut about Selection to Cursor
I have blender v2.79. But i don't have shortcut "Selection to Cursor (shift+ctrl+Y)". Have anyone know how to Assign a shortcut?
https://youtu.be/W5Qp2pUMeQE?t=4m56s

It is Shift + Ctrl+ S, not Y

@DuarteFarrajotaRamos Nope, that's Save As.

Ah damn, you are right, meant Shift + S

There isn't any shortcut for that command specifically in default Blender. You can create one by just Right clicking on menu item and choosing Add Shortcut

There is a custom shortcut defined in the blender version he is using.
You can do this by opening the menu, right clicking on the item, hovering over the box and putting in a shortcut.


text:
Add-On Dev: Per-File Initialization (Issues Enabling Add-on After File Load)
I've noticed a lot of add-on code using the load_post handler to serve as a sort of startup event. This makes a lot of sense, because many elements do not exist before that moment, and most add-ons need to associate with them.
But what about when an add-on is activated after the blend file is loaded? The normal startup sequence seems to be load_pre, addon.register, load_post, which allows us to sync with the file contents. But how do we detect when load_post happens before our add-on is registered?
I've tried accessing bpy.data.* and bpy.context.*, to try to detect any differences, but they are both restricted at normal startup. Is there a safe way to ask the environment if any scenes exist?
Edit: Just want to sum my problem up as a really simple question: How do I initialize add-on states that need to look at scene elements?

Hi. If you can explain the specific situation that makes you think you need to do this, it might help.

Just any situation where you need to look at the scene at startup would encounter the issue. For example, if an add-on actively manipulates lights, I'm assuming it would need to detect the existence of lights before it starts manipulating them. I may have explained it poorly, but I'm just trying to detect weather or not a scene already exists when my add-on starts. In my specific situation, I'm wanting to build a hierarchy table. I also have certain routines that shouldn't run unless certain scene elements are present.

After reading about it, it looks like they limited access to the scene during registration to help protect developers from themselves. But any add-on that makes use of load_post is likely to break when activated after loading a file. Whatever it does in that function will fail to happen until a new file is loaded.

You're having a hard time working around the restriction, because you're not supposed to do that. See: https://blender.stackexchange.com/questions/24415/accessing-bpy-context-gives-a-restrictcontext-warning-how-to-fix-this

I actually mixed myself up on the restriction thing. My problem is wanting to initialize add-on states that rely on scene objects. I was trying to solve it by checking for a valid scene on startup. But I didn't realize I was doing that check inside of register. So I confused the restriction error with an invalid scene. If anyone has the add-on io_scene_valvesource, that is an example of an add-on that used a hack to fix this problem. They register their post-loading event function as load_post and depsgraph_update_post, then delete the depsgraph version after it gets called.

It's currently in the middle of the night so I can't the add-on you're referring to. The issue with this approach is that you are checking a state that may not be valid anymore once you actually execute an operator later on. Which is precisely the reason why the restriction were imposed in the first place. Say you want to check if scene had a certain property and your test when loading the add-on is positive. Now before any operator is executed the user switches the scene. Now your check was made on the wrong scene and your state is invalid.

All the use cases you've described should not be handled when loading the add-on. Either calculate the state on the fly when the operator is executed or use something like a handler for depsgraph_update_post to continuously update the state whenever something relevant in the project changes.

I understand your point. You're saying the add-on the should update on the fly to make sure scene-specific information is still accurate. But even those add-ons would want to start up with accurate information. They have no reliable constructor-like event where scene data is available. And there are a lot of situations where a continuous update would not make sense. What if an add-on adds something to each project exactly one time? Like a global object, hidden global states, or a singleton into bpy.data.scenes[0], etc. Changing scenes would not cause any issues with these.

Sorry, I shouldn't be trying to argue any points with my limited experience with this. My purpose was to find a safe way to initialize scene-related states at startup, but I think that question has been answered. It doesn't look like its possible without some type event hack. Either way, I appreciate the advice.

No problem, having a discussion about these things is good because it allows everybody to learn. We can be wrong too, sometimes.

BTW make sure you tag people with e.g. @rjg otherwise they don't get notified that you left a comment.

Add-ons can do per-file initialisation, if the add-on has some kind of panel in the UI somewhere.
You may notice various panels in Blender's UI have checkboxes next to the panel title. This is can be because they don't want to be active unless specifically turned on, but it can also be because they want to do some setup before being used:

This can be achieved in your own add-on by adding a draw_header function into the class that defines your panel:
def draw_header(self, context):

    self.layout.prop(context.scene, "addon_panel_enabled", text="")

The draw_header displays a boolean which I created and registered in the register function of the add-on:
bpy.types.Scene.addon_panel_enabled = bpy.props.BoolProperty(default=False, update=initialiseAddon)

The property has an update function called initialiseAddon which runs when the boolean is changed. It is in initialiseAddon that you can run your setup code.
Be aware, however, that this will run when the header checkbox is enabled and disabled. You could of course include code to make sure it only runs once by checking if the header boolean is true (the update function seems to be run after the value has been set):
def initialiseAddon(self, context):
    if context.scene.addon_panel_enabled:
        print("Only runs when enabling the checkbox")

Or just make another property which stores whether initialisation has been done or inspect your own data.
If you don't have a panel, then you should do initialisation in your operator when it first runs and again, have a scene property that stores whether setup has been done or not.
Full code (based on the UI Panel Simple template that comes with Blender):
import bpy

class HelloWorldPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

    def draw_header(self, context):

        self.layout.prop(context.scene, "addon_panel_enabled", text="")

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

        obj = context.object

        row = layout.row()
        row.label(text="Hello world!", icon='WORLD_DATA')

        row = layout.row()
        row.label(text="Active object is: " + obj.name)
        row = layout.row()
        row.prop(obj, "name")

        row = layout.row()
        row.operator("mesh.primitive_cube_add")

def initialiseAddon(self, context):
    #Per file initialisation code here
    if context.scene.addon_panel_enabled == True:
        print("Only runs when enabling the checkbox")

def register():
    bpy.types.Scene.addon_panel_enabled = bpy.props.BoolProperty(default=False, update=initialiseAddon)
    bpy.utils.register_class(HelloWorldPanel)

def unregister():
    bpy.utils.unregister_class(HelloWorldPanel)
    del bpy.types.Scene.addon_panel_enabled

if __name__ == "__main__":
    register()

That is one of the right ways to accomplish the goal.

Yeah, any type of user event that indicates the user wants to use the add-on would be a good place to initialize. The best place for a panel add-on would be when the user expands the panel itself, but there's unfortunately no event for that.


text:
Add-On Dev: Button that simply calls a Function?
I apologize for the volume of questions. I tried searching for this, but came up with nothing related.
When building an operator window (or panel for that matter), is there any way to setup a simple button -> function relationship? Say, for example, if I had 6 buttons that I wanted to have call 6 separate functions?
If this is not possible, would there be a clever way to create a single operator class that allows its caller to specify a custom function to call when it is executed? Something like this?
op = layout.operator( "wm.function_caller", text="Write Data")
op.function = self.WriteData

I hadn't considered this until writing this question, so I think I will go try some variations on this. If it works, the down-side would be the inability to specify a custom description tool-tip for the buttons, right?
Thanks - any advice is appreciated.
Edit: Just wanted to provide a simple example of where something like this might make sense. If you define an operator window that allows the user to manipulate multiple sets of the same data, you may provide buttons at the top of it to "add" a set, to "subtract" a set, to "move forward" a set in order, to "move back" a set in order, etc. I find it strange that Blender provides a simple callback mechanism for data changes, but doesn't provide one for buttons.

Why don't you create 6 operator classes each with their specific function? I'm not entirely sure what problem you're trying to solve.

Condensed this into one comment: For one, I wasn't sure if it was possible to execute operators from within another operator. Since my buttons exist in an operator window, it seemed reasonable to map its buttons to its functions. But my primary reason for wanting to call functions was because the buttons were supposed to execute actions for the window operator and use/manipulate its data/properties. Some of that data cannot exist as properties, so I wasn't sure how to transmit the data back and forth between operators.

The following example shows how to create multiple operators each with their specific function. It only shows three buttons, but the concept remains the same for an arbitrary number of buttons and their underlying operators. The panel is created in the sidebar of the 3D View which can be opened with N.
I hope I haven't misunderstood what you're trying to accomplish. In case I did, feel free to leave a comment.
bl_info = {
    "name": "Multiple operator example",
    "author": "Robert Guetzkow",
    "version": (1, 0),
    "blender": (2, 80, 0),
    "location": "View3D > Sidebar > My own addon",
    "description": "Example with multiple operators",
    "warning": "",
    "wiki_url": "",
    "category": "3D View"}

import bpy

class EXAMPLE_OT_func_1(bpy.types.Operator):
    bl_idname = "example.func_1"
    bl_label = "Function 1"

    def execute(self, context):
        # Implement your first function here
        self.report({'INFO'}, f"This is {self.bl_idname}")
        return {'FINISHED'}

class EXAMPLE_OT_func_2(bpy.types.Operator):
    bl_idname = "example.func_2"
    bl_label = "Function 2"

    def execute(self, context):
        # Implement your second function here
        self.report({'INFO'}, f"This is {self.bl_idname}")
        return {'FINISHED'}

class EXAMPLE_OT_func_3(bpy.types.Operator):
    bl_idname = "example.func_3"
    bl_label = "Function 3"

    def execute(self, context):
        # Implement your third function here
        self.report({'INFO'}, f"This is {self.bl_idname}")
        return {'FINISHED'}

class EXAMPLE_PT_panel(bpy.types.Panel):
    bl_label = "My own addon"
    bl_category = "Name of your tab"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"

    def draw(self, context):
        layout = self.layout
        layout.operator(EXAMPLE_OT_func_1.bl_idname)
        layout.operator(EXAMPLE_OT_func_2.bl_idname)
        layout.operator(EXAMPLE_OT_func_3.bl_idname)

classes = (EXAMPLE_OT_func_1, EXAMPLE_OT_func_2, EXAMPLE_OT_func_3, EXAMPLE_PT_panel)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)

if __name__ == "__main__":
    register()

Thanks man, I appreciate the detailed example. I was thinking of situations where you would have a lot of simple actions associated with a single operator. Your example highlights the fact that defining an operator is just as simple as defining a function. In my situation, I need the secondary operators to some how communicate with my primary operator. This is why I wanted to call its functions with the buttons. But there are probably other ways to do it.

In general you would use some class that stores that for that purpose. Since you've added a clarification after I've written my answer, it could be that you're looking for a way to implement a UIList similar to how the UI for the material slots works with the add, subtract, move up and down?

In my specific case, it's a list of override pages, where the user can add, remove, and switch between pages (left, right). It's not complex. I just hoped I could keep all of the functionality inside the single operator. Have the buttons call event functions that change/add/remove pages. I'm still trying to plan it out. Thanks a bunch for the advice.

You can use a property, which is set differently for each function in the panel.

Add a property to your operator.
custom_prop = bpy.props.StringProperty(default="Default Value.")
Add the operator to your UI layout
op = layout.operator(OPERATOR_OT_name.bl_idname)
Modify the property of the operators call.
op.custom_prop = "Other Value."

Modifying Robert Gützkow's answer's code:
import bpy

class EXAMPLE_OT_multi_purpose(bpy.types.Operator):
    bl_idname = "example.multi_purpose"
    bl_label = "Function using variables."

    custom_prop = bpy.props.StringProperty(default="Default Value.")

    def execute(self, context):
        v = self.custom_prop
        self.report({'INFO'}, f"Prop is '{v}'")
        return {'FINISHED'}

class EXAMPLE_PT_panel(bpy.types.Panel):
    bl_label = "My own addon"
    bl_category = "Name of your tab"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"

    def draw(self, context):
        layout = self.layout
        op = layout.operator(EXAMPLE_OT_multi_purpose.bl_idname, text="Function")
        op.custom_prop = "Default Value"

        op = layout.operator(EXAMPLE_OT_multi_purpose.bl_idname,
            text="Same Function, but different.")
        op.custom_prop = "Not default value, causing other behaviour."

classes = (EXAMPLE_OT_multi_purpose, EXAMPLE_PT_panel)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)

if __name__ == "__main__":
    register()

Thank you, I appreciate the information. My pain stems from the fact that my properties exist in my primary operator, which invokes a window. My scene elements have simple binary data, which gets converted into Blender properties when this operator window opens. I want to create page buttons in this window, which need to communicate back to the primary operator window (to sync the property data to the element's data page). I think my best option is to remove the properties from the operator window altogether, and place them somewhere else, like user preferences.


text:
Identify root collection?
I'm not sure if this type of question belongs here, but I'm trying to write a simple add-on that exports game assets to FBX files based on collections. Each collection becomes a separate file. But an issue is that I don't want to process the root collection.
Now I am very new to python (started yesterday), and have not yet figured out how to iterate Blender's collections, so this may not be necessary. But I have a feeling the iteration will be linear (not hierarchy based). So I'm wondering if there is a way to identify the primary scene root collection of a scene? Would I just compare its name to "Scene Collection"? This seems like a bad way of handling it, but that's the best I have at the moment. On the other hand, if the very first collection of Blender's collection list is always the root, that might make it easier.
In case I find any Blender python developers willing to help, I had a couple other questions regarding Blender and python in general. FYI, I come from a decently strong C++ background with absolutely no python experience..

Does python use spacing, tabs, and end of lines as part of its syntax? Really strange how this works. So for example, how does the python interpreter know where a for loop body starts and ends? Just based on spacing and indentation?
Several add-ons appear to be assigning their own made-up variables to blender object types. Such as bpy.types.Scene.myVariable = make_pointer(MyObject) or bpy.types.Object.myBool = BoolProperty(..).. Does a simple line such as this create a new variable in the class type that the addon can use as custom data? If so, how do they not conflict with each other?
scene = bpy.context.scene - I'm assuming this type of code does not copy the entire scene to a new instance, but rather copies the variable that represents a reference to the scene? Something like that?
if obj.name in scene.objects: - Really curious as to what this is doing exactly. It almost looks like it is using the name property of the object to search in the scene list of objects for that specific name string. Is that the case? If so, wow.

Thanks for any assistance. I know I should be learning to use python correctly before I start diving into building a Blender add-on. Hoping I can get away with knowing just enough to pull this off.
Thanks!

The master collection of the current scene can be accessed using bpy.context.scene.collection. You can access all scenes regardless of the one currently active through bpy.data.scenes. For example if you want to access a scene by name and get its master collection, you could use bpy.data.scenes["Scene"].collection. Alternatively you can also access them by index.
Once you have the master collection of the scene you can get all objects regardless of the sub-collections within, using all_objects. So for example bpy.context.scene.collection.all_objects would give you all objects in the current scene. You can iterate through them like this (which prints the name of the objects):
for obj in bpy.context.scene.collection.all_objects:
    print(obj.name)

Regarding your other questions:

Yes Python requires indentation to determine what part of the code is within a specific scope. I recommend using an editor that helps you write syntactically correct code.
Add-on can add their own variables using code similar to the one you described and it's precisely so that they can store custom data. They can conflict each other if the have the same name, which is why their name is usually based on the add-on and often bundle their configuration in a PointerProperty which points to an object that contains the actual variables/settings/properties that the add-on uses. This avoids adding several variables.
Correct, the scene variable just holds a references to the scene object.
Correct. I think this works (might be slightly wrong) because SceneObjects, which is the type of bpy.context.scene.objects, implements a custom __eq__ method, that allows to determine equality by their unique name. If their names are equal they are the same object.

You can actually test of lot of these interactively in Blender's scripting workspace where you have a console that let's you run these commands in Blender without having to write an add-on right away.

Please note that storing variables for add-ons and other aspects that rely on bpy are exclusive to Blender's API and you won't encounter them when programming in Python outside of Blender.


text:
Combine and duplicate meshes before exporting them?
I'm writing an add-on that exports objects to FBX file format.
One of its features will be the ability to merge another object for export. So the user selects object A, clicks the "choose merge object" button, then clicks object B. During export, the objects are combined as per Ctrl+J type operation, exported as a single object, then everything is restored to normal (back to 2 objects).
This is my idea:

Duplicate both objects - remaining steps deal with copies
Set B as selected and A as active
Use bpy.ops.object.join()
Export A (active_object)
Delete A

I have a couple questions regarding this if anyone might know something about it..
X. Is there an alternative to avoid the need to create temporaries and delete them afterward? The objects could be any complexity imaginable, so any way to use the inputs as read-only would be better. Some alternate merger? A+B=C instead of A+=delete(B)?
Edit: I later found out that you can duplicate an object as a link (which doesn't copy mesh data), then use that linked duplicate as an input object for join(). This is very similar to not needing to create temporaries because the mesh data is never duplicated.
Y. In the scenario above using join(), would the temporary copy of B be deleted automatically? Not sure how join() works under the hood. And a little worried about messing around with a deleted object reference in code.
Edit: Yes, all input objects except the active one get deleted by join().
I really appreciate any advice. I'm very new to python and add-on development,  so details are also appreciated.

Sounds like a job for our good old friend: Undo. I know it sounds stupid, but... you know.

Does undo work efficiently in these situations? Also, I'm not knowledgeable (at all) about how Blender's undo system works. I've noticed that it sometimes seems to be restoring the entire scene/file when I undo certain changes. Some things that changed before the undo action are undone as a side effect. I would be worried that with my limited knowledge of it, I may cause more damage than good.

Hi @Robert, what solution did you finally go for? I want to do something similar. With Undo I am affraid that accidently corrupts the scene (especially when something crashes in the process - locked file? no idea). With the Save option I would have the same fear as you - that you quickly want to test an idea out and now your file is saved and you would never know.

Sounds like a job for our good old friend: Undo. You can make it complicated for sure, but since the operation is in memory anyway, it should make it pretty fast.
import bpy

from bpy.props import (BoolProperty, FloatProperty, StringProperty)
from bpy.types import (Operator)
from bpy_extras.io_utils import ExportHelper

# ExportHelper is a helper class, defines filename and
# invoke() function which calls the file selector.
class EXPORT_OT_customFBX(Operator, ExportHelper):
    """Export the scene to FBX"""
    bl_idname = "export_scene.custom_fbx"
    bl_label = "Export FBX"

    # ExportHelper mixin class uses this
    filename_ext = ".fbx"

    filter_glob: StringProperty(
        default="*.fbx",
        options={'HIDDEN'},
        maxlen=255,  # Max internal buffer length, longer would be clamped.
    )

    # List of operator properties, the attributes will be assigned
    # to the class instance from the operator settings before calling.
    global_scale: FloatProperty(
        name="Scale",
        description="Scale",
        default=1.0,
    )

    use_subsurf: BoolProperty(
        name="Use Subsurf",
        description="Use Subsurf",
        default=False,
    )

    apply_unit_scale: BoolProperty(
        name="Apply Unit Scale",
        description="Use Subsurf",
        default=True,
    )

    def execute(self, context):

        viewport_selection = [o for o in context.selected_objects if o.type == 'MESH']

        if len(viewport_selection) == 2:
            if context.active_object in viewport_selection:
                # Join!
                # https://blender.stackexchange.com/q/13986
                # https://blender.stackexchange.com/q/50160
                bpy.ops.object.join()
            else:
                print ("Can not call join operator")
        else:
            print ("Nothing to join.")

        # Export
        bpy.ops.export_scene.fbx(
                filepath=self.filepath,
                global_scale=self.global_scale,
                apply_unit_scale=self.apply_unit_scale,
                use_subsurf=self.use_subsurf,
                use_metadata=True,
                axis_forward='-Z',
                axis_up='Y'
            )

        # Undo!
        bpy.ops.ed.undo()
        return {'FINISHED'}

# Only needed if you want to add into a dynamic menu
def draw_export_fbx(self, context):
    self.layout.operator(EXPORT_OT_customFBX.bl_idname, text="Custom FBX (.fbx)", icon="MESH_MONKEY")

# Registration
classes = (
    EXPORT_OT_customFBX,
)

def register():
    from bpy.utils import register_class
    for cls in classes:
        register_class(cls)

    bpy.types.TOPBAR_MT_file_export.prepend(draw_export_fbx)

def unregister():
    from bpy.utils import unregister_class
    for cls in reversed(classes):
        unregister_class(cls)

    bpy.types.TOPBAR_MT_file_export.remove(draw_export_fbx)

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.export_scene.custom_fbx('INVOKE_DEFAULT')

Operator is based on Templates > Python > Operator File Export

Another quite boring approach is saving the file before exporting to fbx and then reload the blend:
def execute(self, context):

    # Save!
    if bpy.data.is_dirty:
        bpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)

    viewport_selection = [o for o in context.selected_objects if o.type == 'MESH']

    if len(viewport_selection) == 2:
        if context.active_object in viewport_selection:
            # Join! # https://blender.stackexchange.com/q/13986
            bpy.ops.object.join()
        else:
            print ("Can not call join operator")
    else:
        print ("Nothing to join.")

    # Export
    bpy.ops.export_scene.fbx(
            filepath=self.filepath,
            global_scale=self.global_scale,
            apply_unit_scale=self.apply_unit_scale,
            use_subsurf=self.use_subsurf,
            use_metadata=True,
            axis_forward='-Z',
            axis_up='Y'
        )

    # Reload
    bpy.ops.wm.open_mainfile(filepath=bpy.data.filepath)
    return {'FINISHED'}

Might be nice doing some tests to measure execution time of both... in memory.

Thanks for the detailed information! Does the undo system work based off of operations? In the sense that one operation = one undo? The file saving concept is also a clever idea and simple way to handle it. I would just be worried that many developers probably make temporary edits to their models right before export (part of the reason I'm trying to make this add-on). Maybe if I saved to a temporary folder, it could work. But if the undo system works this easily, that seems like a good way to handle it.  Thanks again!

Everything is an operation @Robert. Not sure what you mean by developers make temporary edits? Do you mean artists? What developers or artists can do with the models exactly? To be on the save side, you can increment the version of the blend as well as using the second approach to save before exporting it and even report that the file is not ready for export in case it's not saved by using the report method of the operator: self.report({'ERROR'}, "Save!")

I mean models inside of Blender are rarely in the correct state for a game engine. Sometimes they need to be optimized or reconfigured in a way that makes destructive changes to the model. So the artist would make these changes, export, then undo, reload, or close without saving. The more changes needed, the more likely they would close or reload instead of using undo. So if I save their scene during export, I would make their temporary change permanent. It could probably be avoided by saving to an alternate file.

Ok get it. Should I implement the report method I mentioned? @Robert

I don't see the need to join the objects at all inside Blender. Since you are? writing the fbx export code, just merge the triangle/texture/animation data for the two meshes yourself and write it out to the fbx format as a single object.

I'm not writing the entire exporter. Mearly executing the built in FBX exporter with extended options like different batch modes and prefix/suffix options. Primarily intended for game development (assets, low poly,  high poly). For example,  the user can mark a specific collection or object as "high poly", then that gets exported to a specific directory and/or with different prefix. Merging objects is another feature. But I would not want to try recoding the file parsers.

I see. Sorry for the confusion.
I would say that your approach is good. Doing some practice runs on my setup seems to show that B no longer exists after merging with A.

Thanks for checking that out. I'm surprised Blender doesn't have some type of advanced mesh joining function. I figured Join() was probably calling something else behind the scenes. Maybe I can try to actually find that function to find out when I get back to a computer


text:
Add-On Dev: Access Property Details
This question has likely been asked before. I tried to search, but I honestly don't know how to phrase the question specifically enough to find anything.
If I define a property inside of a class like this:
class Type(bpy.types.PropertyGroup):

    stuff : bpy.props.BoolProperty(
        name="Property Name",
        description="Property Info",
        default=False,
        )

Is it possible to access the name, description, default, and other fields, later at execution time? Say, for example, during a panel draw function?
Edit:
After posting, I starting playing around and found that class_instance.__annotations__.values() seems to include all of this data. But I'm not sure how to sort it out or access the data. I'm still pretty unskilled with Python concepts like tuples and dictionaries, but it looks like the wanted data may be in a dictionary? I'm thinking it may be possible to access it with something like var.__annotations__.values()[1]['description'].
But even if something like this is possible, would it be the correct way to do it? Is there a better way?

annotations is a new stuff in Python3. Which Blender 2.80 adapt the feature to make those properties as annotations. And you can use __annotations__ to access those data for sure. If the value is not modified since the Group created, those properties can only be access in annotations AFAIK. But maybe I am wrong.

You can access them through RNA without using annotations. Assuming you have registered your PropertyGroup you can access them like in the following example.
For instance the code below gives you access to the description of Eevee's render samples property.
bpy.context.scene.eevee.bl_rna.properties["taa_render_samples"].description

Thanks! Are bl_rna.properties and __annotations__ similar features? I don't entirely understand what sets these apart. One thing I noticed was that __annotations__ only seems to include "properties", where bl_rna.properties seems to include all members? Is that true? Are there any other differences?

After looking a little deeper, __annotations__ looks to primarily be groupings of strings, where bl_rna.properties looks more like a class instance with many property details, some of which are also strings. I think I'm starting to get it.

The __annotations__ are relevant for the declaration of the properties using the : syntax. It allows you to access the class variables like a dictionary. It usually becomes relevant  when you want to create properties dynamically (which you don't do in your example). I haven't checked Blender's source code for this, but I'm fairly certain that bl_rna.properties uses these annotations under the hood. If the properties are registered I find the approach through the Blender API a bit nicer.


text:
Properties, the Defaults for Property keys, and when to use get()
First, I've encountered a confusing situation regarding property defaults and the use of getters. When I use a getter, I end up having to supply the default of the property a second time, even though the property has a default specified. Is this normal? Does a property's default attribute become obsolete once you define a getter for it?
Here is a simple situation to illustrate. The relevant lines are the getter() return value and the property default assignment:
flag_list=[
            ('A', "A", "Info", global_flag_a ),
            ('B', "B", "Info", global_flag_b ),
            ('C', "C", "Info", global_flag_c ),
            ('D', "D", "Info", global_flag_d ),
            ]

class PropsPrefs(bpy.types.AddonPreferences):

    # getter
    def getter(self):

        # must supply defaults a second time here?
        return self.get( "enum_flag_var", global_flag_a | global_flag_b | global_flag_c )

    # setter
    def setter(self,value):

        # assign new value if not none
        if value != 0:
            self["enum_flag_var"] = value

    # enum flag variable
    enum_flag_var : EnumProperty(
        name="flags",
        options={'ENUM_FLAG'},
        items=flag_list,
        description="info",
        default={'A', 'B', 'C'}, # never gets used?
        get=getter,
        set=setter
        )

My second area of confusion is why we need to use self.get("property") instead of self.property (as well as self["property"]) in certain situations? I'm assuming it is because these properties are generated at run-time as they are written to for the first time?
Would anyone be able to elaborate on how this works, and when to use one syntax over the other? Any documentation about this behavior? My current (limited) strategy is to use self.property until it throws an error, then switch to self.get("property"). But because of my lack of understanding, I have no way of knowing which of these situations might throw an error under different circumstances.

It seem that the dictionary doesn't get the default values inserted when getter and setter are implemented (for any property type). The .get() is necessary because the dictionary doesn't (yet) contain the key, accessing it directly would result in a KeyError.

Thanks @rjg. Okay, that's what I was assuming. One reason I'm confused is because I typically only seem to have to use .get() in the class functions. I haven't needed it in other modules (yet). Is this because Blender does something to initialize the key at some point? Or does the key only get generated when it is written to? If anyone can help me understand which types of events generate the key, that would be extremely helpful. Thanks again

The key is in the dictionary once the setter is executed. That would happen once the user interacts with the property in the UI or when you assign it in your script. In case it wasn't clear get() is commonly used with dictionaries because of they may not contain the key you searching for. It's not a special function that only exists in Blender.

That makes sense. So if you were writing an operator or function that made use of many user inputs, you would use .get() for all of them, just in case the user didn't modify them? If that's the case, it seems like .get() should pretty much always be used. Or at least at the top of functions/operators. That also means the default attribute for all properties just became obsolete.

Yes that's probably a good idea. BTW the reason why self.property in the getter doesn't work is because accessing it like that also triggers the getter, which results in an infinite recursion.

Thanks for all of your help. You should copy and paste all of this into an answer so I can accept.

The default value will not be automatically applied when declaring a property with a getter and setter.
In Python you can use the .get() function when accessing a key in a dictionary that may not exist. It allows you to specify a second argument which will be used as default value in case the key cannot be found. This is necessary for your use case, because the key "enum_flag_var" may not yet exists in the bpy_struct dictionary. Accessing it using self["enum_flag_var"] will result in a KeyError.
KeyError: 'bpy_struct[key]: key "enum_flag_var" not found'

The key will exist once you've assigned a value to the property in your script or when the user sets a value in the UI. You cannot use self.property in the getter, because that would in turn also call the getter and therefore cause an infinite recursion. That's why the value is accessed through the dictionary.

Thanks rjg. I wasn't able to find this information anywhere else. Maybe because I assumed it was a Blender concept when it was actually a Python concept. But I'm still assuming it will help a lot of new Blender developers.


text:
How to change graph interpolation type in headless mode
I'm writing a script for Blender that needs to be run from the terminal. I would like to change the interpolation type of f-curves in my script. When using Blender's normal UI, the sequence of commands for what I want to accomplish is:
bpy.context.area.ui_type = 'FCURVES'
bpy.ops.graph.select_all(action='SELECT')
bpy.ops.graph.interpolation_type(type='BACK')

This works great when I run the code within Blender, however when I try to execute this from the terminal, I receive the following error:
bpy.context.area.ui_type = 'FCURVES'
AttributeError: 'NoneType' object has no attribute 'ui_type'

This is understandable, because in headless mode, apparently there is no area or UI. How can I achieve the same results in headless mode?
Thanks!

No UI in headless mode.
There are a number of similar questions.
Change extrapolation type from Python running in the background
Look for lower level API calls.  In the UI the interpolation is set from the Keys Menu indicating that it is a property of an fcurve's  keyframe point.
>>> action = D.actions['CubeAction']
>>> fcurve = action.fcurves[0]
>>> fcurve.keyframe_points[0].interpolation
'BEZIER'

>>> fcurve.keyframe_points[0].interpolation = 'BACK'
>>>

Consult the docs on bpy.types.Keyframe for options, or to get valid enums from error message feedback
>>> fcurve.keyframe_points[0].interpolation = 'FOO'
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
TypeError: bpy_struct: item.attr = val: enum "FOO" not found in ('CONSTANT', 'LINEAR', 'BEZIER', 'SINE', 'QUAD', 'CUBIC', 'QUART', 'QUINT', 'EXPO', 'CIRC', 'BACK', 'BOUNCE', 'ELASTIC')


text:
Is there any way to override UILayout.prop tooltip?
I have a collection on boolean properties I want to display in a node. BoolVectorProperty isn't really applicable because I want to be able to change the size of the array dynamically.
My issue is that when displaying a compact grid, there's no way to tell the user the index of a button. That is, I would like to override the tooltip of a UILayout.prop widget. If I set the text-kwarg to something nonempty, icon_only seems to be ignored.
My current code:
class SequencerPosition(bpy.types.PropertyGroup):
    value: bpy.props.BoolProperty(name="Value")

class TriggerSequencer(Node):
    bl_idname = 'TriggerSequencerNode'
    bl_label = 'Trigger Sequencer'
    bl_width_min = 70.0

    sequence: bpy.props.CollectionProperty(type=SequencerPosition, name="Sequence")

    def init(self, context):
        for i in range(16):
            self.sequence.add()

    def draw_buttons(self, context, layout):
        grid = layout.grid_flow(row_major=True)
        for i, pg in enumerate(self.sequence):
            grid.prop(pg, 'value', icon_only=True)

results in this node:

The tooltips are rather unhelpful, just saying "Value."

Dynamically re-annotate a pointer property

I forgot to select one
Example below.  Note I've used Scene properties to illustrate the concept, as it's simpler to put together using simple panel template code and column flow to layout, than making custom nodes.  Pretty sure the same concepts apply.
The Scene.foo_int property unregisters re-annotates and re registers the propertygroup class.  The init call is emulated by calling the rereg update method.
import bpy
from bpy.props import BoolProperty, PointerProperty, IntProperty

class SequencerPosition(bpy.types.PropertyGroup):
    __annotations__ = {}
    pass

def rereg(self, context):
    if getattr(SequencerPosition, "is_registered", False):
        bpy.utils.unregister_class(SequencerPosition)
    SequencerPosition.__annotations__.clear()
    for i in range(self.foo_int):

        SequencerPosition.__annotations__[f"value{i}"] = BoolProperty(
            name=f"Value{i}",
            description=f"Do something with value {i}")

    bpy.utils.register_class(SequencerPosition)
    bpy.types.Scene.foo = PointerProperty(type=SequencerPosition)

class HelloWorldPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        layout.prop(scene, "foo_int")
        grid = layout.column_flow(columns=8)
        for anno in SequencerPosition.__annotations__.keys():
            grid.prop(scene.foo, anno, icon_only=True)

def register():
    bpy.utils.register_class(HelloWorldPanel)
    bpy.types.Scene.foo_int = IntProperty(min=0, max=32, update=rereg)

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

if __name__ == "__main__":
    rereg(bpy.context.scene, bpy.context)
    register()

Oh, and this won't really work if I have multiple instances of the
  node, right?

Yes that's a catch on the dynamic registering, however can annotate the node with a maximum number, and only display so many based on a node int property
to demonstrate:

I've annotated the CustomNode with a max of 32 and used the int to set the layout
def draw_buttons(self, context, layout):
    layout.label(text="Node settings")
    layout.prop(self, "my_int_prop")
    grid = layout.grid_flow(row_major=True, columns=4)
    for i in range(self.my_int_prop):
        grid.prop(self, f'value{i}', icon_only=True)

Appreciated. At least it's less complicated to do it like this than I thought, but I'm not sure if I'd rather just not have tooltips.

Oh, and this won't really work if I have multiple instances of the node, right?

Oops, yep.  Instead could register propertygroup class with max number of annotations, and only display based on length int.

I now have something like __annotations__ = {f"step{i}": bpy.props.BoolProperty(name=f"Step {i}") for i in range(MAX_STEPS)}. I still don't like the string indexing (I tried having integers as keys and Blender did a royal segfault), but this is a lot cleaner.

What string indexing?

The fact that I have to do getattr(sequence, f"step{i}") to address the steps programmatically, i.e. index them with strings "step0", "step1", ...

Would have segfaulted because the string is the name of the prop, which cannot be an integer... can learn some facts the hard way.  Could link to a collection such that it displays the step annotation (ie does the string indexing in the bg)  but hardly seems worth the hassle.  Been a pleasure helping.

Yeah, thanks! I'd like for the code for registering the annotations be incorporated in your answer before accepting it.


text:
How to set a fixed background image as reference for sculpting?
The background should be fixed and not change with the orientation of the model:

All the information I can find is about using background images for modelling reference, by using empties, planes etc... But they all stay fixed to the model and rotate along with it depending on the viewing angle. I just want the grey viewport background to be like a kind of wallpaper with all my reference images.
Is it possible to do this?
Example: Joe Menna uses this all the time in Zbrush, like in this movie (starting at 10:30).

It is possible!
A few steps needed for it though.

You have to use a camera for this to work, the camera can be set up so the boundaries are at the edges of the screen, activating "lock camera to view" (function is in my favorites menu) makes it then possible to look around and rotate the view while staying in the camera.
After setting up the camera view, we need to add a background image or images to the camera, each image can be placed on the screen and scaled to our liking, allowing us to make a collage like in the mentioned video. If you made a collage of all the references already, fine, less images to load and position.
Under the camera object in the "Background Images" header we have the "Add Image" button. Clicking on that gives us a new entry "Not Set" under which we can Open/Select an image either from disk or use an already loaded one in the scene by using the little image icon with the arrow down, left to the "Open" button.
Once the image is loaded/selected, we have options like color space, alpha, depth (here we chose back) as well as frame method, where i would go with crop, to keep the image in ratio rather then stretching it. Further there is the X and Y offset which allows us to position the image(s) where we want them. Lastly rotation and scale for the fine tuning as well as options for vertical and horizontal flipping.
Once a picture is set up we can set up more by repeating the 3rd and 4th step, til we have all the screen estate used up. It is even possible to pack in more images that would lay on top of each other and show or hide them depending on their need.

Don't forget to save the file and eventually pack the images in the .blend file to open the file and realize the images are gone.
With all that said, here a little visual demonstration:

Excuse the small size, the 2MB upload limit forced me to cut down on size. Hope it still shows the essential part, that is, it works.

Thank you so much for this great explanation!


text:
How can I import materials from another blender file with python?
I have many files containing different parts of my blender internal material collection. How can I make a script which imports all of them into another blend file?

This is easily possible without python. Do you need to use python? (I'm pretty sure it's possible with python too) Or is a gui solution acceptable?

I would need to do it many times and on many files, and it would go nicely with the script i have already made. i know that you can press Shift+F1 to import from other blend files.
It would need to be a python script.

There is some archaic way you could do this with bpy.ops.wm.append() but a better way is to work with the api available via bpy.types.BlendDataLibraries.
import bpy

# using a relative path
path = "//file_name.blend"

with bpy.data.libraries.load(path) as (data_from, data_to):
    data_to.materials = data_from.materials

As a sanity check or for logging purposes, you can loop through what was appended and see if everything is there as it should be
for mat in data_to.materials:
    if mat is not None:
        print(mat.name)

As it relates to many files, it should be simple enough to extend the script to also loop through a list of filenames to append materials from. A final note, the materials appended have no users so make sure to stick them somewhere before closing your file.

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


text:
Mesh with mirror modifier shaded differently on the other half
Does anyone know on what occasion is mesh with mirror modifier shaded differently on the other half? Normal is fine. Thanks in advance.

Check if there is no duplicated object.

@LeoNas No duplicated object.

If you want it, you can send the file using this link: https://blend-exchange.giantcowfilms.com/

@LeoNas Thanks.

Seems that Custom Split Normals are causing the issue.
In the Data panel, under Geometry Data, click the Clear Custom Split Normals Data button to fix it.

Nice it works! Thanks!


text:
Draw a perfect circle on texture
I want to draw two perfect circles on a sphere that would function as the sphere's eyes.
When I go to to the Texture Paint and try to draw two circles they are hardly perfect:

How can I draw two perfect circles in Texture Paint?
Is there an option to choose a geometrical shape and just adjust its size instead of drawing it from scratch?

It doesn't seem that there is any inner tool to easily draw a circle or a square in Texture Paint mode, that said you can use the trick explained here by Nwytg:

Choose Stroke Method > Anchored:

Create this kind of Falloff that will make the circle empty:

Left click at the center of the circle and drag:

Or keep the same Falloff but choose Stroke Method > Dots, press F to set the circle radius, and left click to create the circle:

Interesting use of the custom brush falloff. Smart !

If you have an iPhone or iPad you can stroke the circles in Tintaur app with two linked arcs and then export ready-to-use spherical textures. Here's a short video explaining the process.

This looks like a smartphone app ad.

I don't think so

you're wrong then.

You could make the brush very large and sharp to match the outer diameter of the eye and then erase or paint with base color the inner diameter of the eye.


text:
How to revert this action?
I had made a face and tried to bevel one of the edges.
I must have clicked something that is similar to control+B but isn't because afterwards the computer was stuck loading and then I got this weird geometry:

Control+Z won't revert my geometry.
What have I done and how do I revert it?
Edit:
If it helps to figure out the problem, I noticed that when moving my point of view the only parts of the original mesh that are visible are always within this long face that suddenly appeared.

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?"

You probably clicked Alt + B by accident, which clips your viewport to only show a selected part of the scene. Simply click Alt + B again to reverse the viewport clipping.
You can also see that you have your viewport clipped by the "(clipped)" at the top left of your screenshot.


text:
Mesh looks darker when subdivision is disabled
It seems whenever I am disabling the subdivision the whole mesh become darker.
The File:

Subdivision enabled:

Subdivision disabled:

Why is that?

Hello, maybe it is overlapping with a copy? could you please share your file (at least a part of your object)?

I edited the original post and added the file

Hello, please show the entire node graph of the material used for the model

The split normals (the normals that determine the shading) are messed up for some reason, just Clear Custom Split Normals Data:


text:
How to get Smoke into Z-Depth Pass?
Is it possible to render smoke into the Z-Dpth pass? I did a setup following the advices found here but it renders only the domain as geometry no smoke.

You cannot get a Z-depth of a volumetric shader. You would have to somehow turn the volume into a mesh - and get a depth of those polygons.
An idea would be to give the smoke a color based on distance from camera - you can shade the volume almost solid with high density scatter shader - but that relies on external lighting. With emission shader the volume behaves additively resulting in incorrect depth-values (it's brighter than mesh at same depth). So there's no way to get the smoke's Z-depth other than meshifying it.

You can easily mix shaders for them to behave +/- correctly for Z. That is add_shader{Absorption(black,1), Emission(ray_length)};
And mix_shader that with nothing depending on density of volume needed.
That way it doesn't get additive and any mostly opaque cloud should work that way just fine.
The real problem is that ray length doesn't work for volumes.

@kivig It get's additive. Did you tried the setup? It cannot work because of reasons explained in the answer.

Yey! It seems I did it.
You don't get precise z-depth, but at least you get depth gradient, which can be mapped to needed values after.
I did it for a camera being inside volume. Otherwise you probably need to create additional outside volume to act as depth attenuation mist.

Emission+absorbtion create a non-additive "white".
Mix inputs original volume density (clouds smoke etc.)
Add absorption (this should probably be assigned to an external
volume that includes everything visible), density adjusts depth of
"z".
If you wish to keep it all in one scene, the last node is switch between original shader/z.

This of course is a workaround, so it might seem complicated for some, in which case I won't be able to guide step by step for every possible scenario. However it worked for me.

Can you share the .blend? I would like to test your use case and what it outputs.

In theory, but I'll probably forget. Atm I'm busy on a project which I can't post directly (nda). However the setup is not that complicated if you create a procedural cloud for instance and just add what's in the screenshot.

I did that and it doesn't work even remotely, that's why I am asking if I didn't miss anything.

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


text:
Why are these rendered surfaces reflecting two different colors?
Why are these rendered surfaces reflecting two different colors? I'm using Cycles and an HDRi for illumination. I've applied scale, UV unwrapped and checked that the normals are facing outward. Thanks for any help.

In your node setup for the Chrome material, you need to change the Normal Map node type from Tangent to Object. Then you will get the same response on both objects.

Brilliant! If you have a moment could you explain the reason why so I can understand Cycles better? Thank you.

Honestly, I spent about an hour trying to track that down. It seems that Tangent normal maps should work fine, but there is definitely something different about the 2 meshes that make their surfaced give different results. I tried a number of things, including combining them into 1 mesh but the surfaces still acted differently. Had to give up.

Yes, I agree it's probably something to do with the mesh. I started out with it combined and separated it as part of trouble shooting to no avail. Thank you for your time I can move on now...


text:
Rotating Array Modifier applied to a rotated object issue
So initially I've learned using the Array modifier from this video but actually it is decribed in short in this Q&A. When I used it to create a spiral ladder, I got a problem, though: when I used an empty for object offset, the copy ladder step was scaled by more than 10 along Z and by 2 along X which I fixed by scaling the empty.
Now I'm trying to use the Array modifier to create a cylinder with a code of thinner cylinders emerging from it. Here's what I have before applying the modifier:

Note that:

the thin cylinder's facets were moved so that its origin is on its bottom
it was then rotated around the X axis
then it was moved along Y and its origin was moved back to the (0,0,0)
now cursor is also at (0,0,0) and I created an empty also there, at (0,0,0)

So what I'm expecting is when I set an Array modifier with the Object offset of the Empty (the Arrows one), the copies are on the same place as the original cylinder and then I rotate the Empty and get my nice cone. However, even without any rotations, just when I set Object offset to the Empty, I get this:

Man, I'm definitely missing something. I've seen this question but the origin of my thin cylinder is in the same place as the Empty. Any ideas?
Here's my .blend file:

PS and here's an idea of what I'm trying to get (I've made this one by simple creating duplicates and rotating them around Z, but I'd like to have multiple of them placed in a regular manner):

See http://blender.stackexchange.com/questions/7298/why-is-it-important-to-apply-transformation-to-an-objects-data


text:
Why are my textures appearing correctly on material view, but not on soild?
I'm trying to put together some assets to make a vrchat model for myself. Everything appeared to be great on the model, but when I checked the solid view, I noticed that the front of my model's shoes were transparent. I thought maybe it would be okay because the shoes looked fine in material and rendered view. I loaded the model into unity and it shows the shoes' front transparent like it did in the solid mode. This is my second day of using blender and I can't seem to find the solution. Any tips?

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

I would, but I don't think I can because the assets I'm using are purchased and they have DMCA stuff, so I'm not sure how that would work with sharing the file

have you checked for overlapping geometry, normals orientation?

The Solid mode uses the Workbench render engine which uses not the Material Properties > Surface colors but the settings under Material Properties > Viewport Display. Also, check the options for the viewport shading (dropdown menu right next to the shading icons). https://docs.blender.org/manual/en/latest/editors/3dview/display/shading.html#solid

I fixed it by recalculating the normals to face the outside.


text:
How do I get a selection of points, which don't have another point above them in a certain Z distance?
I'm doing some mesh to voxel geo nodes and want to transform a given mesh into a blocky shape. Then I only want to colorize the top layer of the blocks. That's where the problem begins:
How can I get (index independent) a selection of points, which don't have another point right above them? A certain Z distance should be the deciding factor here (if possible).
Or is there a way to do it with texture coordinates, which look for the top most face and color the mesh from it's given Z coordinate and downwards?
I have been searching it for the past hour and been trying some things by myself, but no solution found so far.
Is this even possible?
Appreciate any help

Rather than first spawning cubes, then coloring them, I'm first spawning triangles, then spawning colored cubes based on the topology.
The topology here means the logic between cubes, and more specifically, how much space is above any given cube - raycasting is used for that; here at least 4 empty cube-spaces are required for the grass to grow:

Now this is insanity. Absolutely love this solution. Thank you so much <3

you can try it with this node setup:

The "trick" is here to instance curve lines. And with endpoint selection you can identify the start and end points.
result:

video tutorial: https://youtu.be/ZleGuOP3Rpk


text:
I bake normal maps and get a gray thing
Why when I try to bake a normal map in blender 3.3.1 I get a gray weird thing. Whatever I do, instead of a normal map, I get a gray thing. I tried to flip the normals, I tried to select the heads in different order, I tried to change the size of the head and I tried to change the settings in the bake section, changed the max ray distance and extrusion, nothing helps. I even tried to find a solution to a similar problem in Google, but it did not help either. The only thing that helped was to download the old version of blender 2.8 and the normal map is baked well in it. In the new version, nothing works for me, what could be the problem?
Blender File

I find baking normal map from a multires modifier much easier, you could try it

Thanks for the answer, yes, I forgot to write about multires, with it my normal map is baked well. But I'm wondering why I can't bake the old way with two models. Maybe somewhere you can change one parameter and everything will work or something like that. It haunts me and I constantly think about it...

Not sure why it doesn't work for you. I've disconnected the Image Texture node, lowered the sample count to 10, and it baked fine in Blender 3.3.0

I downloaded version 3.3.0 in it doesn't work for me either, but I tried version 3.0.0 and baking still works in it. Is it possible that my computer is just outdated for baking normals in the new blender? I have a powerful GT 440 and an incredible AMD Phenom II x6 1035t. What do you think?

I don't know.  An old GPU should not matter if you bake with the CPU. I have a "powerful" onboard graphic chip and only can use the CPU for Cycles.

I know this is several months old but I realized my normals were flipped. If you're getting gray colors on your baked normal maps, check if your model has normals oriented the right way. Check the overlay "Face Orientation" and make sure outside faces are blue

✅ Correct / ⛔ Wrong:

Second issue: Source object had a NORMAL MAP attached. Remove any normal maps from the source geometry


text:
unwanted grid appeared in render viewport

Does anyone know how to get rid of it? Thanks a lot!

I recommend taking screenshots of your screen instead of photographs Taking photographs of your own screen looks really unprofessional and even silly in pretty much all contexts and sometimes makes it a lot harder for people who attempt to help because it's not always possible to see essential information in low quality incomplete images with reflections.

This "grid" is here to tell you the background will be transparent when rendering. You can set the background not to be transparent in the Render Properties like below :

This will remove the grid you have in your viewport with shading set to "Rendered"

Thank you so much!!!


text:
How to add a text object?
I want to change a text dynamically using the game engine, that is, the bge module. I want to do it through a text box and I found a question about it. The problem is that in a part of it says to add a text object. I do not know how to do it, because I can not find the option "text object" in the "add" button of the "Logic Editor" bar.
The code I´m using is this:
# import game engine modules
from bge import render, logic
# import stand alone modules
import bgl, blf

# create a new font object, use external ttf file
font_path = logic.expandPath('C://Documents and Settings//Guillermo//Mis documentos//Google Drive//Gproyectos//Proyectos con Blender//Zeyada.ttf')
# store the font indice - to use later
font_id = blf.load(font_path)
chain = 'this is the message'

def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF drawing routine
    blf.position(font_id, (width * 0.2), (height * 0.3), 0)
    blf.size(font_id, 50, 72)
    bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
    blf.draw(font_id,chain)

def update(cont):
    own = cont.owner
    chain = own['msg']

# set the font drawing routine to run every frame
scene = logic.getCurrentScene()
scene.post_draw = [write]

I call to this piece of code, drawtext.py.
In the scripting window this is the code I have written:
import drawtext
drawtext.chain = 'Hello Mind Maps!'

But I suspect that drawtext.chain must be linked to a text box from which you can enter text in real time.

you can edit written text via string game property but you need to assign it to your drawing property in this method, here is the code.
# import game engine modules
from bge import render, logic
# import stand alone modules
import bgl, blf

# create a new font object, use external ttf file
font_path = logic.expandPath('//C://Documents and Settings//Guillermo//Mis
documentos//Google Drive//Gproyectos//Proyectos con Blender//Zeyada.ttf')
# store the font indice - to use later
font_id = blf.load(font_path)
# we get the game property and assign it before drawing so we can change it always
cont = logic.getCurrentController()
chain = cont.owner['msg']

def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF drawing routine
    blf.position(font_id, (width * 0.2), (height * 0.3), 0)
    blf.size(font_id, 50, 72)
    bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
    blf.draw(font_id,chain)

# set the font drawing routine to run every frame
scene = logic.getCurrentScene()
scene.post_draw = [write]

all you have to do is changing the owner property "msg" it will be drawn, you can also put a keyboard sensor and set the "msg" string as keystrokes log property so it will receive the keystrokes and display, them you don't need to connect it to the python controller but make sure that the code is always running, the code should be with the object that has the property "msg".


text:
Mesh is invisible and only shows in edit mode
I'm pretty new to blender and I've been trying to put a Mesh onto a skeleton with animations (keyframes) but I've ran into the issue of my Mesh disappearing after adding it to the skeleton with animations.
I can see the mesh perfectly fine in edit mode but I can't play the animation with the mesh attached. I've tried a couple of solutions but none have worked (Auto run python scripts is on,Went into pose mode and applied pose as rest shape,and a couple of other things).
Sorry if the terms I'm using are wrong I'm still very new to blender and anything related to it.  Here's the file   Stalker Animation and Mesh (The model and skeleton are .nif files I took from falloutnv and the animation i'm trying to use is a .kf file,I've used the other version of blender with the nif attachment to send them over to the most current version of blender)
If someone can give me instructions on how to fix this issue I would be grateful,I want to import other animations but I want to make sure I'm doing it right.


text:
Changing frame start in smoke domain
I wanted to add a quick smoke effect to my animation that starts at some point in the middle of the animation.
When running the default configuration for the smoke, it seems to render fine.
But the moment I have tried to set the Frame Start value in the Physics Properties for the smoke domain, it suddenly becomes all blurry:

I have tried deleting the cache folder, but it did not seem to work.
When looking frame by frame, the frames inside the range given seem fine, it is the ones out of the scope that look like this instead of no showing smoke at all.
Furthermore, when running the entire animation, then all of the animation sequence looks the same as in the picture.
What is the source of the problem here?


text:
Instancing not working in blender 2.8
(EDIT to reply to duplicate thread suggestion: The reason I think that this thread is not answered in https://blender.stackexchange.com/questions/68923/torus-object-stretched-in-array-curve-modifier
is because none of the solutions seem to talk about this feature which is very simple and different to the method used in the thread indicated. The problem is also addressed in How can I duplicate a mesh along a curve?, which does not work for me in 2.8. It seems such a fundamental and simple feature, it deserves to work in 2.8. I suspect I am missing a simple step that you don't need to do in 2.79)
(EDIT on problem: Progress: I do seem to get one duplication of the object on top of the instancer, because if I change the evaluation time on the path animation setting, I can see another object on the curve. But just one.)
My objective is to duplicate an object many times along a curved path without that object distorting. (With array and curve modifiers the object distorts around curves).
I found this video tutorial how to do it in 2.79, and it works fine: https://www.youtube.com/watch?v=Rp88ckdLwVQ
(Basically it says:
Click on object you want to repeat then click on the path;
Ctrl+p > follow path;
With the object selected, go to the object properties;
In the duplication section, select frames then unselect speed;
Play with adjustments
When I try to do the same in 2.8 (although the section is called "instancing" instead of "duplication" it looks like it does the same) I get no joy.
Any ideas?
Many thanks.

Possible duplicate of Torus object stretched in array curve modifier


text:
Motion Tracking Data into Animation Nodes Editor?
I've created a simple motion track from video in the movie clip editor.  I can see the motion data in the graph view:

I've also created an empty from the motion data and when I hit playback I can see the empty moving in the 3D view.
The problem is that when I add the empty as an object to the Node Animation area and wire it to any other node, I never see the X/Y values change over time during playback.  Here's my current node layout:

(EDIT: I'm using the text node to view the value of the X coordinate in real time during the animation playback).
I know that the motion data can be used in the Compositor layout using the Track Position Node, but I want to use the tracking data to animate an object in the 3d space and am assuming the Animation Node editor would be more appropriate.
Is there any way of getting the empty's location data into the Animation Node editor or barring that, passing the Track Position output from the Compositor Node editor into the Animation Node editor?
UPTDATE:  As recommended by SergeL, here's is how to retrieve the tracker empty location data using Animation Nodes:

Try to use Matrix input + Matrix Decompose instead of Transforms Input

Use the Word matrix to retrieve the location.

An easier way to investigate the value of a certain data is to user a viewer node, see documentation.

@SergeL - That worked!  I've updated my question with the details.

According to the documentation:

Matrices from Matrix Input node are more reliable than transforms from Transforms Input node because of their different forms and because they are always up to date even during physics simulations or when constraints are used.

For instance, if one uses a Copy Location constraint to adjust the object's location, the transforms will report the original location while the matrix inputs will report the final location.


text:
Optimize cycles background rendering
Is there any trick to increase performance in background-only tiles in cycles. As you can see in the pictures, an empty render takes more than one minute. When you render motion graphics animations, there are a lot of these empty tiles in every frame, so it would decrease reder times quite a bit.
Thanks.

As of 2.74 RC, if the background is entirely black, it will be ignored, making it faster.

mmm, it doesn't seem to be the case in my master build.

Are you using the release candidate, or any build after it? The release notes clearly states this http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/2.74#Cycles_Rendering

I've tried rc2, up to date master, and 2.73. Yes, maybe there is a little improvement, not much.

I guess, it is just that all the samples are calculated even for background, maybe something like adaptive sampling is necesary to speed-up background.

@someonewithpc Black backgrounds have been optimized but still take time to render. rendering 100% black will not result in realtime rendering. So they have not been ignored. Just optimized.

I've used this adaptive sampling patch to pretty good effect in optimizing renders like this.

What are your machine specs, and also what is the frame size? Also, can you state CPU/GPU and tile size please. I'm just trying to understand why it's taking a full minute to render a blank frame. Thanks.

As of Blender 2.83 (currently in alpha at the time of this post), this can be solved by using the "Adaptive Sampling" option in Cycles. Adaptive sampling will automatically stop sampling in areas of the frame that are no longer noisy. To enable it, check the "Adaptive Sampling" box in Render Settings > Sampling

Once adaptive sampling is enabled, the render and viewport samples settings become the maximum number of samples that a pixel can have. How many samples a pixel actually gets will be adjusted automatically based on how noisy it is. Once Cycles sees a pixel as no longer being noisy, it will stop sampling it.
Under Sampling > Advanced, there are 2 additional options, Adaptive Min Samples, and Adaptive Threshold. Both are set to 0 (automatic) by default.

Adaptive Min Samples dictates how many samples Cycles will take before beginning to check if a region is noise-free. Checking for completion adds some overhead, so you don't want to do it when the image is still hopelessly noisy. The default setting of 0 puts this in automatic mode, which will set it to the square root of the maximum samples setting. This is good enough in most cases, although if you're using a high number of samples (such as several thousand) and have blank areas in your frame, manually setting it to a value such as 32 may give some performance improvement.
Adaptive Threshold sets a metric that defines when a pixel is "no longer noisy". The default of 0 puts this in automatic mode, which is usually fine if you're using denoising. If you need to adjust it manually, smaller values correspond to less noise. For final renders, values such as 0.001 are common.
In this example image, adaptive sampling allows the render to finish twice as fast (10sec instead of 20sec) at 1024 samples while producing the same final image.

By enabling the "sample count" pass, you can see a "heatmap" of where Cycles needed to use more samples. Darker values show fewer samples, with the darkest being areas that stopped right away at the minimum number of samples. Brighter values show more samples, with white being areas that went all the way to the maximum number of samples.

It really depends on what type of motion graphics you are trying to render. I would question whether you need the full 576 samples to achieve the renders you want.
Decrease AA Samples - If you switch to Branched Path Tracing, keeping square samples on, I would try reducing the effective AA samples to 20 or under (try 4 or 5 in square sample mode). You can increase the other sample rates to get multiples that equal 576 (although you may not need it for Transmission, Volume or Subsurface, depends on your scene). Decreasing the AA samples will speed up background tile rendering significantly. As long as you have enough AA quality for the edges of your rendered objects, you should be fine.
Turn Off Sample All Indirect Lights - Also I'd turn off "Sample All Indirect Lights" if it doesn't affect your scene quality noticeably. It will make quite a difference.
Optimize Tile Size - Small tile sizes (16-32 for CPU) seem to be more efficient around the edges of objects where there is a transition area between object and background. However, once the tiles are rendering 100% background it seems a little larger tile size (64-128) is more efficient in Cycles. You need to find the optimum balance between the 2 sizes depending on how much background is being rendered in the frame.

If these suggestions do not help, perhaps you could share a sample frame render so we can see the type of scenes you are trying to render.


text:
The constraint_orientation setting does not work in script
The function I wrote below:
def dc(period,mvtype,axis,mval,boolx,booly,boolz):

    v3d = [x for x in bpy.context.screen.areas if x.type == 'VIEW_3D']
    v3d[0].spaces[0].transform_orientation = 'axes-'+ bpy.context.active_object.name
    ob = bpy.context.active_object

    mtx = bpy.context.scene.objects['axes-'+bpy.context.active_object.name].matrix_world
    if axis == 'x':
        vec = mathutils.Vector((mtx[0][0], mtx[1][0], mtx[2][0]))
    elif axis == 'y':
        vec = mathutils.Vector((mtx[0][1], mtx[1][1], mtx[2][1]))
    elif axis == 'z':
        vec = mathutils.Vector((mtx[0][2], mtx[1][2], mtx[2][2]))
    else:
         return

    inv = ob.matrix_world.copy()
    inv.invert()
    # align to custom axis
    mv = vec * inv * mval
    ob.select=True

    bpy.ops.transform.translate(value=mv,constraint_axis=(boolx, booly, boolz),constraint_orientation='axes-1')

    bpy.ops.object.select_all(action='DESELECT')
    ob.select=True
    bpy.context.scene.objects.active = ob
    return

# call the function by
dc(0,8,'y',1,  False, True, False)

But in the info panel:
bpy.ops.transform.translate(value=(XXXXX, XXXXX, 0), constraint_axis=(False, True, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
The constraint_orientation is "global" rather than "axes-1" as i set.
Any reason of that ?


text:
Selecting all objects that have been specified in Modifiers
Could anyone help in making a script for selecting all objects that are specified in the different modifiers that an object has stacked? For example if my object has a Boolean modifier and an Array modifier, which both refer to an empty or another object (in the Array modifier there is for example an Object offset you can specify). Would it be possible to select all those object with one click? Thanks.

What have you tried so far, could you post what you have achieved and show us were exactly you are stuck? As it stands now it sounds like you want someone to do it for you, which is not really the spirit of this site.

Fair enough. I will do it myself and share it.

Using the bl_rna.properties collection.  This gives the name, type and other properties of the properties of the modifier. If the property is an object it is most likely, both a PointerProperty (prop.type == 'POINTER') and points to a prop.fixed_type of bpy.types.Object.  If so getattr(modifier, propertyname) will be either the object if set, or None if not.
import bpy
context = bpy.context
obj = context.object
for m in obj.modifiers:
    print("modifier (%s): %s" % (m.type, m.name))
    for k, v in m.bl_rna.properties.items():
        if v.type == 'POINTER' and v.fixed_type.name == "Object":
            print("\t", k, getattr(m, k))
            # select mod obj if not None
            ob = getattr(m, k, None)
            if ob is not None:
                ob.select_set(True)

It is a little brute-force, but here is my attempt : http://web.purplefrog.com/~thoth/blender/python-cookbook/select-objects-in-modifiers.html
import bpy
import inspect

def select_objects_in_modifiers(obj):
    rna = obj.bl_rna

    refs = set()
    for mod in obj.modifiers:
        for key,val in inspect.getmembers(mod):
            if val is None:
                continue
            if hasattr(val, "bl_rna") and val.bl_rna == rna:
                refs.add(val)

    for o2 in refs:
        o2.select = True
        #print(o2)

select_objects_in_modifiers(bpy.context.active_object)

We use inspect.getmembers to scan all the fields of a modifier and check to see if the .bl_rna matches the bl_rna for an object.  If so, that must be an object referenced by a modifier.


text:
How to get user input for a function?
I have created a function that requires a file path input, I found a way to have the user input a file location but I am not sure how to access it. I thought it was assigned to the bpy.types.Scene.conf_path but I do not get the directory when its printed.  Here is my code.
import bpy
class HelloWorldPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

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

        obj = context.object
        col = layout.column()
        col.prop(context.scene, 'conf_path')

def register():
    bpy.utils.register_class(HelloWorldPanel)
    bpy.utils.register_module(__name__)
    bpy.types.Scene.conf_path = bpy.props.StringProperty \
      (
      name = "XML Location",
      default = "",
      description = "Define the root path of the project",
      subtype = 'DIR_PATH'
      )

def unregister():
    bpy.utils.unregister_class(HelloWorldPanel)
    bpy.utils.unregister_module(__name__)
    del bpy.types.Scene.conf_path

if __name__ == "__main__":
    register()

I appreciate any help or direction. Thanks

Can you elaborate on the print statement?  After setting should be reflected via py console:  C.scene.conf_path   Note this is an instance not the class.   Don't use register class and register module together.  Registering registerable classes with register_class is what register_module is doing for you..  (register_module has been ditched for 2.8) seriously consider starting from 2.8 at this point in time. Finally, On formatting, open braces  are also considered a line continuation by python

You are right I was not printing the right thing. When I printed C.scene.conf_path. it worked. Thank you sooo much this saves me so much time.

I was not calling the information properly. It is not under bpy.types.Scene.conf_path but rather C.scene.conf_path.