text:
How can I reuse existing materials, objects, etc from an existing .blend?
I have created several designs for a particular project and they are related, but I don't want to have to keep recreating any similar elements, such as shared materials or textures.
How can I use the existing data in a new Blender file?

It's the other way around. Open the file you want to "import" or append the data into, then press Shift F1 or file > append. Then navigate to the file that was the data you want to "import", select the type of data you want to append, then select the datablock you want.

These answers though great for importing meshes, but don't work for importing materials with procedural elements. I have yet to find a way to do this, though I am sure there is one. There are websites full of procedural textures and shaders which you can download, but using Append to bring in the files does not bring in a working material. In other words the setup with the nodes, which forms the procedural texture does not come in with the texture or materials files via Append or link. If anyone does know how to do this I would be eternally grateful!

Go to File>Append then select the blend file you want to append from. Select Append. Then it will show you a list of folders, it is asking you what you want to append, for me I went to the Collection folder and then selected the collection I wanted to append. Select Append.

Append works for procedural textures, as of 4.0.2 (not sure if it worked for earlier versions, but does appear to work for this version at least)

You can use "File -> Link" (Ctrl+Alt+O) or "File -> Append" (Shift+F1).
Each will open a File Browser Window, from which you can then choose the file that contains the existing data you want to re-use.
Linking:
Linking will simply create an instance of the existing data, such as a material or an object. The information is not "imported" to the current file, it is always read from the original "library" file it was linked from, and never actually written into the file you are working in. This will mean that you must keep both files together, and if necessary update the path to the linked data. It is best to use relative paths for linked data.
Linked objects (note: objects in this context includes meshes, curves, cameras and lamps or collections) have a teal outline (in the default theme).

A linked cube.
You can edit linked data (such as objects, materials, etc), but you will need to edit the data in the original file.
If you need to edit your linked data, there are a number of options:*

For modern versions of Blender (2.9+) you can use the new Overrides system. Go to Object > Relations > Make Override. This allows linking an entire character for example, but modify its pose by animating its armature.
Make it a proxy object. Ctrl+Alt+P
This allows you to edit the rotation, scale, and translation of the object.
Make it local. L

Your linked object must be selected when using either option.

With materials, you have to click the  button in material properties.

An example use case for linking is when you need to reuse an existing model in a game or animation, but don't need to modify it beyond the basics of rotation, scale or translation.

Appending:
This creates a full copy of the existing data, which you can modify without issue and include in the file you are editing. You do not need to keep both files together. You are also fully able to edit the appended data (such as an object, material, or scene) without affecting the original file from which you appended.
Appended objects have an orange outline when first appended (with the default theme), but once you deselect them, then select them again, they show as normal objects do.

An appended cube.
Appending increases the size of your result blend file however, and uses more resources when editing, so it is not recommended unless you need to modify the appended data.
An example use case of appending would be when you need to create a variant of an existing model. It can save on time and effort.
For example, I created the Asiatic Black Falcon from the same original model as the Black Falcon by appending into a new file and making a few minor changes.

These two began as the same object.

Credit:

http://blenderartists.org/forum/showthread.php?225258-how-to-edit-appended-linked-objects

Further reading:

https://docs.blender.org/manual/en/dev/files/linked_libraries/index.html#linked-libraries

Hi! Thanks for this interesting answer. Do you know where appended materials go? I tried to Append a material but I looked for it in the materials tabs and it wasn't there... (I ended up appending the object, copying its material to another object, then deleting, but for future reference...) thanks!

@fabriced you have to select it from the drop down list (the sphere next to the material name at the bottom of the box).

If you just want to quickly copy a mesh from one file to the another, you can use Ctrl + C to copy the mesh to the buffer, then Ctrl + V in a new file to paste the mesh from the buffer.
Note: This feature is only available in Blender 2.66 and above.

I just tried this for the first time, and when I pasted, the object didn't appear! Then I realised that it was pasted into the same layer as on the original file, incase anyone is interested.

+1 I had some problems with appending from file. This worked flawlessly.


text:
Can Cycles renders be done from the command line?
It seems that Cycles is mainly built in the form of Python scripts (as far as I can tell). Is it still possible to use Cycles to render a .blend file from the command line?

The current tag is actually wrong.. temporarily changed it. It should be command-line with a dash, will retag when it is ok to, the old tags take a while to disappear..

update, fixed it, the old one has been deleted.

Yes you can, This will render a single frame
blender --background filename.blend --render-output //test_ --engine CYCLES --render-format PNG --use-extension 1 --render-frame 5

This will output a file named test_0005
While experimenting, I more or less substituted CYCLES with the parameters I found here. You can check the link to see what they mean and or do.

Tip - to list available rendering engines:
blender --background --engine help

The --engine switch is almost never necessary, you will have already saved the .blend file with Cycles set as render engine while editing it, and it will use that for rendering from the command line too. And this works for render engines like Luxrender or Yafaray too.

Here is an overview of (near) all command line options for Blender:
https://docs.blender.org/manual/en/2.80/advanced/command_line/render.html
blender -b file.blend -o //file -F JPEG -x 1 -f 1

source: Stack Exchange

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

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

sort: votes


text:
Face masking for texture paint in UV / Image Editor
There is "Face selection masking for painting" while in Texture painting in 3D View,
but I want to paint with a texture brush in the UV / Image Editor, so that the texture is not view angle dependent.
Is it possible to paint only on the area of specific faces, while in UV / Image Editor?

Not really at the moment.
Masks are not supported yet in the image editor though it is a feature that we will surely be implementing in the future.

well, that's disappointing but at least now i know not to look any further and go with the external application approach suggested here

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


text:
How to bind a model to an armature?
My pose mode simply does not move the body, I tried weight painting and everything but it just  does not move. It's a simple creation, just a body made simple...
I looked at some other people is works and all, all it seems to do is press CtrlP > Automatic Weights but it does not move the body still.
Something I noticed is when I use Automatic Weights it creates many Vertex Groups called Bone.XXX, but those groups are not assigned to anything. Should I find a way to assign them?

This is likely a problem specific to the particular set-up (an option incidentally disabled that turns off deformation for instance), please upload your .blend to pasteall.org and add the link to your question.

i posted it the site but i didint fin a whey to put the link to the question its posted as Bones problem

Should I find a way to assign them?

Yes. If the vertex group option is checked:

You can use the weight paint mode to change the weights of the active vertex group (current selection in the properties panel):

Assign/Remove the selected vertices to/from the active vertex group in the properties panel:

and change their weights in the viewport:


text:
poll() failed, context incorrect? - Example: bpy.ops.view3d.background_image_add()
I keep on getting context errors in the Blender Python API.
I don't understand the issue of the context in the API, how do I know which is the correct context?
Thanks!

Have a look at the Python API docs.

WiP... A comprehensive list of operator overrides

Just check if you are in edit mode somehow
Exit and code will run through

The context members available depend on the area of blender which is
currently being accessed.

See bpy.context

Many operators have a “poll” function which may check that the mouse
is a valid area or that the object is in the correct mode (Edit Mode,
Weight Paint etc). When an operator’s poll function fails within
python, an exception is raised.

See Operator.poll()
More about using Operators and why you experience poll-fails (mouse not over right screen area or wrong mode / other pre-condition). Also see the Gotchas section of the API docs about that.
You can either:

Run an operator via spacebar menu (see bottom of the section) in Blender 2.7x or using F3 as of Blender 2.8x from the proper Area (bl_options must not contain 'INTERNAL')
Specify the right execution context for the operator call (this fixes the context error only for some!)(API docs, example)
Use an override to pass the required context arguments
Change the Area.type temporarily
Use "low-level" API functions to achieve the same result without context worries

Override
Doesn't seem to work for this operator?! It adds a background but without name / texture.
Blender 3.2+
import bpy
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        override = bpy.context.copy()
        override["area"] = area
        with context.temp_override(**override):
            bpy.ops.view3d.background_image_add(name="BG", filepath=r"image.png")
        break

Blender prior to 3.2
import bpy
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        override = bpy.context.copy()
        override['area'] = area
        bpy.ops.view3d.background_image_add(override, name="BG", filepath=r"image.png")
        break

By the way:
You can pass an empty dict (like bpy.ops.example.operator({})), which usually prints warnings to the system console about the context members missing. You need to pass these members and repeat until it doesn't complain anymore. But beware of certain operators, which require scene bases - if you don't provide a reference to them, Blender will crash to desktop before you even find out they are needed.
Change Area.type
area = bpy.context.area
old_type = area.type
area.type = 'VIEW_3D'
bpy.ops.view3d.background_image_add(name="BG", filepath=r"image.png")
area.type = old_type

Low-level
Similar to the override, you need a 3D View instance, in this case its space data (because this is the place where backgrounds reside). The following code takes the first 3D View of the current screen layout (if there's one), adds a new background and sets the image to an image datablock:
import bpy

filepath = r"C:\path\to\image.png"

img = bpy.data.images.load(filepath)

for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        space_data = area.spaces.active
        bg = space_data.background_images.new()
        bg.image = img
        break

What do you mean by "scene bases"? https://docs.blender.org/api/blender_python_api_master/bpy.types.SceneBases.html? Would you mind providing an example?

@JakeD im wondering the same what does he mean by scene bases?

@HarryMcKenzie Up to v2.79, there was a layer system, and an implementation detail were "SceneBases".  A Base "is a wrapper for referencing Objects in a Scene" that references an object, stores a layer number, a selection flag, etc. (see https://github.com/blender/blender/blob/8ef39d5c882896bd75e0d4d17fb3e3d4710fc768/source/blender/makesdna/DNA_scene_types.h#L72-L79). The Python API hid this quite well but some operators required you to provide object_bases in context overrides or Blender would crash.

Here's to add to @CodeManX's answer. If you get a runtime error that looks like this:

RuntimeError: Operator bpy.ops. ... .poll() failed, context is incorrect

which is specifically in your case:

RuntimeError: Operator bpy.ops.view3d.background_image_add.poll() failed, context is incorrect

You can use the following script to override context. Make sure to use the correct Area Type which is assigned to area_type in this script and make sure this area is visible or open in your screen. For example, if you call a bpy.ops function that directly manipulates the Dope Sheet, you have to make sure this editor is actually open and set area_type = 'DOPESHEET'.
Since you are calling bpy.ops.view3d.background_image_add() which directly manipulates the 3d Viewport, you have to make sure it is actually open and set area_type = 'VIEW_3D'. It is easy to find out the enum for the area type; just switch the editor type and you will see the type in the Info Editor which is open by default in the lower left corner of the Scripting Tab

Legacy Override (version < 3.2)
Take note that in the legacy context override you have to pass the override dictionary object as first parameter to the bpy.ops function.
import bpy

area_type = 'VIEW_3D' # change this to use the correct Area Type context you want to process in
areas  = [area for area in bpy.context.window.screen.areas if area.type == area_type]

if len(areas) <= 0:
    raise Exception(f"Make sure an Area of type {area_type} is open or visible in your screen!")

override = {
    'window': bpy.context.window,
    'screen': bpy.context.window.screen,
    'area': areas[0],
    'region': [region for region in areas[0].regions if region.type == 'WINDOW'][0],
}

bpy.ops.view3d.background_image_add(override)

Temp Override (version 3.2 and beyond)
Use bpy.context.temp_override for blender 3.2 and beyond.
import bpy

area_type = 'VIEW_3D' # change this to use the correct Area Type context you want to process in
areas  = [area for area in bpy.context.window.screen.areas if area.type == area_type]

if len(areas) <= 0:
    raise Exception(f"Make sure an Area of type {area_type} is open or visible in your screen!")

with bpy.context.temp_override(
    window=bpy.context.window,
    area=areas[0],
    region=[region for region in areas[0].regions if region.type == 'WINDOW'][0],
    screen=bpy.context.window.screen
):

    bpy.ops.view3d.background_image_add()

Override for Any Blender Version
Here's a script I've prepared that I found very useful that you can utilize for any Blender version no matter if the target context area is visible or not. You simply create an instance of this ContextScriptExecuter class and pass the Area.type (area_type i.e. VIEW_3D, IMAGE_EDITOR, NODE_EDITOR, etc...) and an optional Area.ui_type (ui_type for specific NODE_EDITOR area context i.e. ShaderNodeTree, GeometryNodeTree, CompositorNodeTree, etc...) and pass your script that requires context to the script parameter.
import bpy

class ContextExecuterOverride:
    def __init__(self, window, screen, area, region):
        self.window, self.screen, self.area, self.region = window, screen, area, region
        self.legacy = not hasattr(bpy.context, "temp_override")
        if self.legacy:
            self.context = bpy.context.copy()
            self.context['window'] = window
            self.context['screen'] = screen
            self.context['area'] = area
            self.context['region'] = region
        else:
            self.context = bpy.context.temp_override(window=window, screen=screen, area=area, region=region)

    def __enter__(self):
        if not self.legacy:
            self.context.__enter__()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if not self.legacy:
            self.context.__exit__(self, exc_type, exc_value, traceback)
        return self

class ContextScriptExecuter():

    def __init__(self, area_type, ui_type=None, script=None):
        self.area_type = area_type
        self.ui_type = ui_type if ui_type else area_type
        self.script = script

    def script_content(self, override):
        self.script(override)

    def execute_script(self):
        window = bpy.context.window
        screen = window.screen
        areas = [area for area in screen.areas if area.type == self.area_type]
        area = areas[0] if len(areas) else screen.areas[0]
        prev_ui_type = area.ui_type
        area.ui_type = self.ui_type
        regions = [region for region in area.regions if region.type == 'WINDOW']
        region = regions[0] if len(regions) else None
        with ContextExecuterOverride(window=window, screen=screen, area=area, region=region) as override:
            self.script_content(override)
        area.ui_type = prev_ui_type

Here's a sample inline usage of a lambda function passed to the script parameter:
ContextScriptExecuter(
    area_type='VIEW_3D',
    script=lambda override: (
        bpy.ops.view3d.view_axis(override.context, type='TOP')
        if override.legacy
        else bpy.ops.view3d.view_axis(type='TOP')
    )
).execute_script()

And here's another example with a defined class method passed by function name to the script parameter. This script assumes you have an object already actively selected with at least one material.
class MyClass:

    def my_context_script(self, override):
        override.area.spaces.active.node_tree = bpy.context.active_object.active_material.node_tree
        if override.legacy:
            bpy.ops.node.add_node(override.context, use_transform=True, type='ShaderNodeVertexColor')
            node_tree = bpy.context.active_object.active_material.node_tree
            active_node = node_tree.nodes[-1]
        else:
            bpy.ops.node.add_node(use_transform=True, type='ShaderNodeVertexColor')
            active_node = bpy.context.active_node
        active_node.location = (0, 0)

    def exec(self):
        ContextScriptExecuter(
            area_type='NODE_EDITOR',
            ui_type='ShaderNodeTree',
            script=self.my_context_script
        ).execute_script()

MyClass().exec()

You can also create a subclass and override the script_content function and define your content there.
Warning on bpy.ops
Please note that you should always try to avoid bpy.ops functions whenever possible, that is, avoid them when there is an alternative solution because an overuse of these functions can potentially cause performance issues.

you can also switch the editor type while running your script using bpy.context.area.ui_type = area_type

FWIW think use_temp_override() can be reduced to if bpy.app.version >= (3, 2, 0): or if hasattr(bpy.context, "temp_override"):

@Gorgious hey if hasattr(bpy.context, "temp_override"): is even better as we can get rid of the hard-coded version values. thanks for sharing!

Yep. There is still a very very small chance that it would fail if someone monkeypatched this as a member of bpy.context or added it via layout.context_pointer_set but I think it's fait to assume no one would do that :)


text:
Edge Split Not In Edge Menu?
I don't know why I can't find the Edge Split option in the Edge menu!  Is that option no longer available in the new versions of Blender?  I think I'm using 2.93 or something.

Try Alt +  M > Faces by Edges. It's also on the Mesh menu.

Thanks a bunch man!

No problem. You're welcome!

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


text:
How to scale view3D area or scene to adjust the viewing area by scaling the X and Y axes independently for visualizing or manipulating geometries
I want to create feature/add-on for scaling viewport along with objects in scene. The viewport/View3D should be compressed or stretched by scaling x or y axis independently. This is called asymmetric scaling and is particularly useful for visualizing or manipulating geometries.
How it Works:
X and Y Axis Scaling: The feature enables you to scale the viewport along the X and Y axes using different scaling values. For example, you can stretch or compress the viewport more in the X direction (horizontal) than in the Y direction (vertical), or vice versa.
Asymmetric Scaling: This means you can apply a different scale factor to the X-axis compared to the Y-axis, creating an effect where the proportions of the viewport are changed independently along each axis. This is useful when you need to focus on specific parts of the model that might require more detailed analysis or adjustment in one direction but not the other.
Use Cases:
Distortion or Focus: If you are working with a surface or model that has more detail or variation in one axis (e.g., a long, narrow component), asymmetric scaling allows you to zoom in or stretch the view to focus on areas of interest without distorting the actual geometry of the model.
Object modifications: In design and modeling, you might want to adjust the vertices of the 3d object when distorted in one direction.

Hello, would you have an example of such feature being used, perhaps in another software ? I have trouble visualizing what you want to do.

Hello, thanks for response. The feature that I want to implement is similar to icem surf feature called scale with nonproportional values.
When we zoom to x axis it actually stretches the viewport vertically and compresses horizontally. vice versa for y
for example, in viewport there is object which is horizontally too long so we can't see it in viewport fully from closely. so, scaling viewport non proportionally, we can compress object horizontally in viewport to view it closely without modifying actual scaling of object

OK, I see I think. I don't think it is possible even with the python API. or you'd have to implement your own gpu shaders to draw on top of the viewport

okay, thanks...

aLternaitvrly you can scale objects in object mode and revert back the scale afterwards


text:
Which is faster: A math node tree or an OSL shader?
In terms of render times for Cycles materials, which is faster? A material node tree containing many (~20-50) math nodes or a single OSL shader script node performing the same calculation.

OSL isn't supported on the GPU, so I'd say nodes are faster if you have a GPU to render on.

Thanks, @gandalf3. I usually use large image textures so GPU isn't an option for me. But that OSL limitation is an important one.

I would still be interested in the answere.

This question has no real possible good answer.
because it depends on what you want to do in OSL or cycles
OSL scripts can be large and node systems too. so in comparing apples and pears, we cannot tell anything about weight if we don't know their size.

why not simply test it ?.

Answer is hard to give, so I will rephrase the question to will an OSL script node eventually be faster than an SVM node graph with math nodes. The answer to this question is yes. Then the next question, when will this benefit happen. this one depends on many parameters. Would I recomment to migrate to OSL script fore solely this reason? No.
I did a test on this subject. As GPU depends on many other stuff I will stick to a SVM CPU vs OSL CPU comparison.
Specs of my test machine:

Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz (8 cores)
Running on Linux
Using official Blender 2.79 release

Test scenes
I constructed 5 scenes for this test.
SVM-0: SVM without the math nodes

SVM-math: SVM with the math nodes

OSL-0: OSL without the math nodes

OSL-math: OSL with the math nodes

OSL-scipt: OSL with the script node

The scene uses around 12 math nodes. I used the emission shader as it will not scatter new rays.
SVM-0  SVM-math | OSL-0  OSL-math OSL-script
------ -------- | ------ -------- ----------
22.90  25.86    | 25.47  27.70    26.05
22.87  25.80    | 25.40  27.64    26.01
22.86  25.84    | 25.38  27.68    25.99
22.92  25.84    | 25.42  27.65    26.04
22.91  25.79    | 25.44  27.63    26.04
-----  -------- | ------ -------- ----------
22.892 25.826   | 25.422 27.660   26.026

What is important in these numbers:
 - SVM average time in the math nodes is 2.934
 - OSL average time in the math nodes is 2.238
 - OSL average time in script node is 0.604
SVM math nodes scales linear. Meaning adding more math nodes will add on average a constant performance penalty.
There is a positive effect on using script nodes. Where is the theoretically break even?
((26.026-22.892)/0.604)*12=62.2649

But different scenes will have different results. For example: the test scenes are constructed that the shader is full screen. Normally you have many different objects and materials in the scene. So let's calculate the number of samples that are needed.
1920*1080*128*62.2649 = 16526399569.92 # resolution * samples * breakeven

On my machine the benefit would happen around 16,526,399,569.92 samples that pass though a node graph where 62 mathnodes were replaced with a single script node.
Note: on different machines different things will happen and that can influence the results.
There are also other stuff to be aware off: SVM codebase is fully shared between CPU/Cuda/OpenCL. As GPU's don't have the ability to have a stack the cycles developers
came up with an idea to implement a fixed stack that could compile on all devices. This stack is limited to 256.
When node graphs get too large SVM will not become an option anymore so the artist might want to switch to OSL.
Would I still recommend it?
No. reason: other materials setup have other cost penalties in OSL. So this theoretically benefit in practice might be much higher. So for this reason I would stick to SVM.

For most use cases, OSL will be faster because it is compiled.

can you provide any examples?
the math nodes are compiled as well, so im wondering how you draw that conclusion.

Math nodes are not compiled, they are interpreted and stacked. Depending on the function you're executing, you'll get different results using SVM or OSL (both in cpu). OSL has the particularity that it optimizes calculations whenever they can be optimized, but in SVM every node is calculated even if the end result doesn't depend on the node's result.

It depends on the specific case.
Of course OSL is powerful tool for pattern generation in comparison with cycles' build in math node but you should realise that it doesn't support GPU rendering and it also increases your render time if you use non .tx format textures.
ps.
Remember that sometimes it's much faster to write a couple of lines of code instead of making a large node tree.


text:
Can I make video game clips from any game like Minecraft ones?
I'm new to Blender, but I've noticed people have Minecraft templates where you can change skins. Can you do this with any video game clip?
Can I record a clip from Call of Duty then take 10 seconds of it, or a pic (not sure which), then put it in Blender and make my own skins and whatever in it, just like the Minecraft ones?
Or do I have to actually make my own and not be able to take the models in my clip?

Hi and welcome to Blender Stackexchange. It would be helpful if you would change your headline into something more meaningful. Also try to add as many useful information in your question as possible, like links to videos or images, if necessary.

As zeffii mentioned bellow, no you cannot do that easily. If you record a video of gameplay you can't just easily change stuff and game assets from the video alone. There are many Minecraft templates because of its blocky nature and simplified graphics make it easy to recreate the content, and there are plentiful actual 3D models of the game assets to render in Blender

People can make Minecraft videos in Blender by importing characters+rigging and worlds and then animate and render them. For example this question has images that shows some of the process:
Cubic character armature deform
It's not like people are making screen captures of a game they played, then importing that video and applying a different skin/texture to the characters, that's not how it works. It would be the same as if you recorded a bit of Starwars and expected there to be an easy way to redress all the storm troopers to look like indiana jones.

Currently there are no easy ways to replace garments on recorded footage, but that doesn't mean there aren't complicated ways.
The literature
Ways are emerging to help automate the process of match making and garment replacement, but they are early proof of concept, and are not likely to be included in Blender any time soon (or indeed possibly never)

Thank you very much that really helped :) Im a sony vegas expert so I thought I would now get into blender type stuff

Minecraft is created with a design philosophy promoting user created content. If Call of Duty has the same design principles and an exporter from Blender and an importer to COD, then you might be able to do what you want. I don't play COD, an can not answer whether it's possible to do what you want in that game or not.


text:
How can I query the panels in the Tool Shelf from a script?
I would like to query the panels in the Tool Shelf, regardless of the context. Also I would like to query the tools that are in a certain panel. The idea is that my script can check if a certain panel is already there (preferably by matching the bl_label) and add certain functions to the panel if they don't already exist.

If you wanna check the appended (or prepended) draw functions of another addons, added to built-in panels, you can do for example:
draw_method = bpy.types.OBJECT_OT_relations.draw
if hasattr(draw_method, "_draw_funcs"):
    print(draw_method._draw_funcs)

As soon as a custom draw function is added, _draw_funcs will be defined and contain a list of draw functions. They are stored in a list, which means you can pop/remove/insert/append/prepend or shuffle the entries.
A really advanced possibility is to intercept all draw calls, but beware! Only a single addon may do this at a time, or you'll run into errors.
http://wiki.blender.org/index.php/User:Ideasman42/Blender_UI_Shenanigans


text:
How do I access the glTF Metallic roughness shader node with Python?
I am currently working on a little script that takes a bunch of obj, imports them into blender with their textures, plugs the textures in the right places of the GLTF Metallic Roughness shader group, and then exports everything into GLTF.
I have arrived to the part where I have to add the GLTF Metallic Roughness Node. As those who use that plugin (https://github.com/KhronosGroup/glTF-Blender-Exporter) know, to access the node and plug your textures manually, you first have to link your blender scene to the GLTF2.blend scene, and especially to the pbr node tree and the Metallic Roughness group there.
I have tried a couple of things... First I tried this:
GLTF = matnodes.new(settings =[{"value" : "byp.data.node_groups['glTF Metallic Roughness']"}], type= "ShaderNodeGroup")

Yet Blender doesn't seem to like this and says that it expects only one argument for the function "matnodes.new()"...
So I have tried this:
GLTF = matnodes.new("ShaderNodeGroup")

There it spawns a gorup shader node, but it is empty and displaying ("Missing Data-Block"... On the menu dropdown, I have tried selecting "glTF Metallic Roughness", and it turns the node into the right node, but in the info console there's no command I can use... Basically I don't know how to do that in Python.
Does anyone have an idea :/?
I haven't put the entire code because I think the rest is kind of irrelevant but don't hesitate to ask if you want to see it.
Thank you all!

Find your node group:
group = bpy.data.node_groups.get('glTF Metallic Roughness')

Assign it to the node:
GLTF = matnodes.new("ShaderNodeGroup")
GLTF.node_tree = group

Hahaha stupid me I answered you by answering my own post!

Thank you so much, it works!! It was quite simple but I'm new to Python in Blender so there's a whole lot of things I don't know very well yet :)
Thank you again!
mae_lia


text:
Where can I get the first Blender 2.8 build?
I have been testing just about every Blender 2.8 build out there to test the new EEVEE engine. I would like to compare the first build with EEVEE and the latest build in a video but I can't find the first Linux version of EEVEE. Could anyone help me get the very first Blender 2.8 version that had EEVEE in it? It would be highly appreciated!

I believe that that is impossible with the downloads from blender.org, as updates come in full iterations, the best thing to do would be to compare the dev build now to the final version when released. The dev builds are constantly updated and if existing builds need to be updated they add lettering e.g. (2.78a, 2.78b, 2.78c) which is what happened when fixes needed to be released for 2.78. So you would be hard-pressed to find a reliable source of the very very first "Blender 2.8".

https://download.blender.org/release/ the site with all versions of blender i think

the first build with EEVEE

is a rather arbitrary point in time, the blender 2.80 evee development started as a branch from the current development of blender, it was identical to the normal blender releases. There have been no tagged releases containing evee, the daily test builds have been the only available versions.
As blender is open source, you can build any variation of it that you want. The blender 2.80 development is being done in it's own branch so you just add git branch blender2.8 after you have a copy of the repo. You can list the history of the branch and checkout any commit from that list that you want and compile it as it was at that point in time.
So you can build any version that you want, but to get daily experimental pre-built binaries you have to get them the day they are available.

Go to official website of Blender
Click on Download

Scroll down and Click Latest Experimental Builds

Scroll down to find These builds are from the Blender 2.8 project. Do not use in the production nor save important file with it
Below you can find which OS or Mac or linux your using and download it.

This doesn't answer the OP's question. The question is how to get the first build of 2.8 with Eevee.


text:
How to open a .glb or .gltf file in blender?
My question is about opening .glb or .gltf files in Blender. I don't see these extensions in the Import options, although Export allows me to create files with either of those extensions.

an importer could be not yet available, but you could perhaps use this tool to read and convert to importable files https://en.wikipedia.org/wiki/Open_Asset_Import_Library

Hope someone updates this when an import is available...

glTF 2.0 import and export are shipping with Blender 2.80 Beta.

Blender comes with glTF-Blender-IO pre-installed since 2.80.
This is a refactoring of the original Khronos glTF exporter, combined with @Julien's importer.  Both of the original projects should be considered obsolete in favor of the newer, combined glTF-Blender-IO project.
The Blender Manual includes documentation on ways to use glTF.

GLTF Importer for Blender - now in progress:
https://github.com/ksons/gltf-blender-importer

A more advanced glTF importer for Blender : https://github.com/julienduroure/gltf2-blender-importer

Awesome, I had an FBX with embedded textures, but when I imported it to Blender 2.79 the textures were discarded. I was able to open the FBX in Windows 3D Paint and there textures were their. Windows 3D Paint can save to GLB. With this importer addon, I was able to get the textures.

In short, there's an exporter for the GLTF format from Blender (which I assume you have installed), but as of this moment, no one has written an importer add-on or extended the export add-on to support importing as well. This is why you can export, but have no options for importing.

Updated importer/exporter https://github.com/KhronosGroup/glTF-Blender-IO
Currently supported


text:
Cannot enable GPU
Before anything, I must mention that I've already read all similar questions and answers from this community before posting this one, so no need to close as duplicate, its not duplicate.
My render mode is Cycles. I already properly installed all necessary NVidia drivers etc (all of that were installed by default), so I navigated to File -> User Prefernces -> System -> Cycles Compute Device -> CUDA. But, the problem is because I simply cannot select it. Take a look at the .
Also, I can select it, but nothing happens. I searched on internet what to do and I didn't find what to do if the option is disabled like in my case. Also, I tried to ignore it and to just enable GPU in render menu. But, it is also disabled there too, see
.
I can select GPU, but nothing happens, it still renders using CPU. What to do in this case? Blender is not complaining about any bugs or errors and I don't see any messages why is it disabled.
Any suggestiong on how to enable it? My processor's CPU is extremelly slow while my GPU is fast, so it would be nice if I success to enable GPU because now almost any scene takes a few months to render (using just CPU). Thank you in in advance.
P.S. if you need some additional information about my OS or blender, no problem I'll provide any needed information. Thank you again.
Edit 1
As answer to ardito's questions. I just clicked all suggested tags which appeared after I finished writing the question, I dont know what a python is btw. Secondly, I cannot paste images using image editor because I need at least I think 50 rep or similar, so i must use links, I also cannot add more than 2 links per question. As answer to your last question, I can select it, (I mean I can click it and change from CPU to GPU), but it is still disabled (you can see that the option is gray, while it should be darker), but the blender still uses CPU to render instead of GPU. I tried everything, I saved it, saved settings, saved file as blend file, restarted computer, restarted blender, restarted operating system, changed computer etc, but nothing works. My version is 2.78c;
Edit 2
How I know it is still using CPU? Well, I cannot know for sure, I just suppose. The main reasong which suggest me that CPU is still being used are following:

The computation time needed for rendering is exact same, not shorter, not longer. I suppose if I change from CPU to GPU at least some scenes should be rendered differently fast (maybe slower or faster), but everything is rendering same speed as when CPU is selected
Both GPu options (in user preferences and in render menu) are disables (they are light gray while they should be color like all other buttons, so dark gray I think) which suggests that something is not normal
Thats it

I know GPU may or may not be slower than CPU on some particular scenes, but the computation time is not changed. I tried with different scenes and it renders exact same speedly. Not faster not slower.
Edit 3
As suggested in comments, I did what he said. So, I launched Blender using command line (I never did it before so sorry if I did it wrong, I had to google it to find how to do that), so then I used blender for a while, tried to do some renderings using gpu and cpu and then I screenshoted the command line window when I closed blender, so you can now see the whole log.

I noticed that blender is complaining about failed to set some frequency whatever that means. Also, I noticed in console message saying that some event has invalid window. What does it mean? Doew it maybe causes the issue? Anyway, you can see the screenshot of console (the log is very short, just few lines) and you all are experts in blender so I am sure you can easily understand what is causing issue by looking at log. Also, sorry for my bad undertsndaing of blender concepts, I am new to programming and new to blender I have no programming or animation experience before (I just bought my first PC), so sorry about it. Thanks ardito for your fast and good responses and comments, I am sure you are good programmer and you can help me solve this probably easy issue for you. Thank you in advance again.
I cannot post screenshot here not more than 2 links are allowed for newbies in this community, so I am posting link in the comments, you can see it in comment section.Thanks cegaton for importing image.

Hi, sorry, what "python" and "scripting" tags have to do with this? Also, you should add images using the editor "image tool" so that they are also visible here... Then, it's not clear if you can or cannot select the gpu setting. You say: " the problem is because I simply cannot select it." then "Also, I can select it, but nothing happens"... ? Finally, add the blender version.

@m.ardito he cannot use the editor image tool because he has 1 reputation.

@Trance-DoarCuTine python is a programming language used for scripting in blender. This question has nothing to do with scripts (so also nothing to do with python)so you should remove both the scripting and the python tags. The suggested tags are not always related to your question. After all it is not a human who suggests these tags so the failure rate is high.

@Tooniis the restriction was removed on some sites a while ago, this one including. It should be possible

@Trance - Doar Cu Tine yes, I had to try, because it's not the first time that someone says something like that... I wanted to be sure, and maybe ask a policy change to allow it...  before, I tried searching amongst BSE help system, but didn't find anything... and in that question I just expected to be able to delete it, but after posting it I couldn't.  The "someone" was Tooniis, as you see above...

@Trance - Doar Cu Tine back to topic, I cannot replicate your setup, but perhaps you could describe how you know that GPU is not used. Render times are still high?

@m.ardito. It will be good to delete all irrelevant comments, I deleted mine comments first, but I cannot delete every comment here which is not mine. I added answer to the question as edit 2

You could check in logs (expand the top "info" editor to see them, or launch blender from the command line, or activate the console (hidden by default). Also depending on specific GPU there could be some vendor tool to monitor usage. Finally, on some systems (eg Nvidia optimus)  the OS can decide/force which card enable for specific programs, so belnder could perhaps detect it but as "disabled"...?

@m.ardito. I did what you said. I added more explanation to the question. Also, here is the screenshot of blender launched from command line, here is the image: here

@Trance-DoarCuTine - In your first screenshot, it looks like the 750ti is selected.  Are you able to toggle it on and off (dark to light gray)?  Also, the frequency error is simply related to audio and it's normal.

@bertmoog. Thank you bertmoog for response. I am pretty sure I'm not colorblind so I can distinguish between selected, non-selected and disabled option. This is how it looks when it is not selected, this is how looks when selected and this is how it should look (the last screenshot is from another PC). I think the problem is more serious than it looks. Anyway thanks for trying to help, I appreciate that.

@Trance-DoarCuTine - Wow.  Wasn't saying you were color blind, I was wondering if the button was actually working because you said "I simply cannot select it."

I know im a bit late for this, but I remember in older version of blender one had to change the feature set from "Supported" to "Experimental" to get GPU rendering to work. (Render tab, above "Device")

@Trance-DoarCuTine - It looks to me too like your GPU IS in fact enabled and working. This is how it looks in my Blender. How to check: Find out how many cores your CPU has, likely more than one, probably 2 or 4 or even more. When rendering with the CPU, you will notice several corner brackets around several squares (amount of cores) rendering in parallel. Call task manager (in Windows ctrl - shift and ESC), check if your CPU usage is 100% If it is down, then GPU is working. A GPU only gives you one Square rendering at the same time with brackets on the corners, that is a sure way to tell.

Would you be able to tell me your system specifications (other than your 750 ti) as well as your version of blender? I believe I have a final answer for you but I will require this information.

Unsure but did you have the latest graphics card drivers installed? The GPU Compute is showing light gray which means the CPU is rendering it instead. Probably due to not installing the right drivers for your Graphics card it isn't getting registered.

Could try updating the graphics card driver from the manufacturers website.
Try enabling experimental mode.
Downloading and installing visual c++ 2013.

If you want faster render you can use SheepIt Free Render Farm It is really useful if you are working on an animation, where if anyone doesn't have the necessary render power to run it might take weeks to complete.

Unsure if this will help:
To know for sure if your render is using CPU or GPU you should notice a change in the number of 'tiles' that are being rendered at a time. A 'tile' is the square with little orange corners that you see being refined in your render image.
EG, if you only have 1 video card, then you will only ever render 1 tile at a time. 2 video cards (you should have SLI disabled) = 2 tiles at once. Most CPU's made in the last 5+ years are multi-threaded - so if your CPU has 4 threads, it will render 4 tiles at a time.
If you go to your render settings tab, under the PERFORMANCE section, select Áuto-Detect' and it will tell you how many threads your CPU has.
This isn't a fix, just a way of identifying if you are actually rendering on the GPU or CPU.
Otherwise, could you state the model of CPU you have and the exact brand/model of your video card? I can do some research... some older AGP cards do not support CUDA, but I can't remember if the 750 was ever made using AGP.


text:
"bpy.context.scene.object_bases" not working in 2.80?
The 2.8 documentation for the context override is found here:
https://docs.blender.org/api/blender2.8/bpy.ops.html?highlight=object_bases
override['selected_bases'] = list(bpy.context.scene.object_bases)

is even listed there, but throwing
bpy.context.scene.object_bases

into the python console throws:

Traceback (most recent call last):
   File "", line 1, in
  AttributeError: 'Scene' object has no attribute 'object_bases'

I want to merge objects as described by CodemanX here:
How to join objects with Python?
It worked in 2.79, doesnt in 2.80 and throws:

AttributeError: 'Scene' object has no attribute 'object_bases'

My code snippet:
    proxyname = "ProxyName"
    # create empty new object
    proxymesh = bpy.data.objects.new(proxyname, bpy.data.meshes.new(proxyname))
    bpy.context.collection.objects.link(proxymesh)
    proxymesh.matrix_world = bpy.context.active_object.matrix_world
    # make new, flattened object from all meshes in selection
    duplicants = []
    duplicants.append(proxymesh)
    for obj in bpy.context.selected_objects:
        if obj.type == "MESH":
            duplicant = bpy.data.objects.new("duplicant", obj.to_mesh(bpy.context.depsgraph, True, calc_undeformed=False))
            bpy.context.collection.objects.link(duplicant)
            duplicant.matrix_world = obj.matrix_world
            duplicants.append(duplicant)
    # attach flattened objects to empty object
    ctx = bpy.context.copy()
    ctx['active_object'] = proxymesh
    ctx['selected_objects'] = duplicants
    ctx['selected_editable_bases'] = [bpy.context.scene.object_bases[duplicant.name] for duplicant in duplicants]

So basically, I would like to know how to be able to iterate through the scene's object bases in 2.80?

Check the 2.80 release notes for information on how the Python API changed.

Appears no need for bases in 2.8  join operator override.
Testing this in python console. Have duped the default cube 3 times, the last dupe "Cube.003" is active and only object selected.
>>> C.object
bpy.data.objects['Cube.003']

>>> C.selected_objects
[bpy.data.objects['Cube.003']]

A list of all the mesh objects in scene to join
>>> obs = [o for o in C.scene.objects if o.type == 'MESH']
>>> obs
[bpy.data.objects['Cube'], bpy.data.objects['Cube.001'], bpy.data.objects['Cube.002'], bpy.data.objects['Cube.003']]

Make a context override dictionary, with only object, active_object, selected_objects, selected_editable_objects as members (possibly don't require "object")
>>> c = {}

>>> c["object"] = c["active_object"] = C.object
>>> c["selected_objects"] = c["selected_editable_objects"] = obs

Run the operator with this override
>>> bpy.ops.object.join(c)
{'FINISHED'}

Resulting scene after running.  All four cubes are joined as one "Cube.003"
>>> C.scene.objects[:]
[bpy.data.objects['Lamp'], bpy.data.objects['Camera'], bpy.data.objects['Cube.003']]

Risky look at obs since three of the objects no longer exist.
>>> obs
[<bpy_struct, Object invalid>, <bpy_struct, Object invalid>, <bpy_struct, Object invalid>, bpy.data.objects['Cube.003']]

Related
poll() failed, context incorrect? - Example: bpy.ops.view3d.background_image_add()
Scripting -- Can't figure out how to use correct contexts?
Reliable way to find out the required context for an operator?
How to find an operator's source code?

How did you find out which context members you have to pass to an operator?

Added some links to answer. In this case I grepped the addons folder for "bases" which gave me an inkling that it was no longer required, (commented out in print3d addon for example) confirmed by testing in console.  Would be extremely handy to have  operators required context members in the docs, but since they are generated from source would be a fair task.


text:
How do I get an icon to appear in the label of my custom python node?
Note: This was an issue in 2.79, but has been fixed in 2.83.

Custom python nodes have a bl_icon property which, when set to a valid icon name, is meant to display an icon for the node.
I presumed this icon would appear next to the node label like the compositing nodes have:

However, I have not been able to get an icon to appear for my nodes, and even the template in Text Editor> Templates> Custom Nodes doesn't seem to succeed in displaying the icon it defines.
Is there some other property that needs to be enabled to get the icon to appear or am I misunderstanding the purpose of defining a bl_icon property?

Good question. Neither works in the Compositor nor in the Shader Node Tree. I assume that this is not implemented yet,

@poor So you think it might be a mistake that it's included in the template and the api documentation?

Sorry Ray I'm not sure, but I think if that would work, it would find its way into Sverchok or Animation Nodes.

it only shows in outliner (for ex. if u look at datablocks). kinda useless.. (The icon you show in the picture is preview button and it's hardcoded. not py)

@o.g. Please add that as an answer.

I also wonder about this, I also think it is just not implemented as intended. And maybe the template is from some newer version during GSOC.

So far, the node icon only seams to appear in outliner (like datablocks).
Not very useful.
+The icon you show in the picture is preview button and it's hardcoded. not py
AFAIK you can alter, even in "real time" , the label with draw_label() and also the sockets texts. And of course, the color and size of the node. But not much more.
-
There might be an extreme workaround...
If you really need an image or something else on top of that, so much that you'd design a whole system just for that (instead of making great nodes and addons :D ), you can use OpenGl to draw something on top of the node, or header or whatever area
an example is this (note that the white rectangle could be on top of the self node! whatever the coords you need, you can work out the header area with precision)

and it's about
https://github.com/JacquesLucke/animation_nodes/tree/master/graphics


text:
Is there a better way to rotate the order of vertices of currently selected faces in edit mode?
I've been playing with duplifaces and it turns out the orientation of the copied geometry depends on the order of the vertices in the face (https://developer.blender.org/T30547).  Since I'm unhappy with the orientation of some of my duplicated geometry, clearly I need to "rotate" the vertex order of some of the faces.
I've come up with this little python snippet, but it has one drawback I can think of.
# rotate selected face

import bpy
import bmesh

mesh = bpy.context.active_object.data
bm = bmesh.from_edit_mesh(mesh)

for face in bm.faces:
    if (face.select):
        vs = face.verts[:]
        vs2 = vs[1:]+vs[:1]
        # face.verts =vs2 # fails because verts is read-only
        bm.faces.remove(face)
        f2 = bm.faces.new(vs2)
        f2.select = True

# trigger UI update
bmesh.update_edit_mesh(mesh)

The drawback is that it destroys the old face and creates a new one.  I suspect that there will be some cases where information on the old face will be lost.
Just for some flavor, here's an illustration of a situation where you might want manual control over the orientation:

JA12 put together a short video that illustrates some workflow techniques to control this if you are building new geometry:

There is a tool to help re-order mesh elements, which can be accessed in the GUI with Space > Sort Mesh elements (you must be in edit mode), or in python with bpy.ops.mesh.sort_elements(). Unfortunately it didn't seem to affect duplifaces, at least it didn't when I tried it..

Even if Sort Mesh Elements were to affect the vertex order on a face, there's only a 1/4 chance that the order of the vertices is the order you want.  I think it would require a new operator, but I'm disinclined to start work on a new patch until my other patch gets accepted, or even rejected.

Do you actually want to rotate the faces, or do you want to flip the normals (so the orientation the polygon is facing)? There are bmesh.utils.face_flip(), bmesh.ops.rotate_edges() and bmesh.utils.edge_rotate(), which might do what you want.

The UI isn't updating because the script does not call
bmesh.update_edit_mesh(mesh)

(I got this from how to use BMesh to add verts, faces, and edges to existing geometry )


text:
How to automate selection and assembly of clips defined in an input file with builtin functions or (python) scripts
I'm approaching the blender video editor and I'm wondering if there are built-in functions/available (python) scripts to automate the operation of cutting/assembling  subscenes/clips indexed in a file.
Meaning, suppose my director gives me an AVI movie and a file containing a list of times t_1_in, t_1_fin, t_2_in, t_2_fin, ... delimiting the subscenes/clips to be cut and assembled.
Is it possible in Blender to automate the cutting and selection of the clips defined by the t_i's in a file (say .dat) and their assembly in a continuos sequence?

There is an add-on to import EDLs (Edit Decision List), it is a trunk add-on that comes with Blender. As long as your list conforms to the correct source and timecode i don't see why this couldn't work.


text:
Intersection of more than 2 mesh objects
I've managed to select the intersection edges of 2 given mesh objects, using Wiltor Jaworski's plugin (http://airplanes3d.net/scripts-253_e.xml).
However, I couldn't find any reference as to how to get the (possible) intersection of more than 2 objects.
For example, if I have 3 planes A, B and C that intersect in a given point, how can I select this point?

There is a way to do this. It is not ideal, but it works and is also non-destructive. Select one of the meshes that is part of the intersection. Add a Boolean modifier to it, choose one of the other objects as the Object in the Boolean modifier. Copy that modifier and chose the other mesh as the Union Object this time. After yo do this there will be a vertex at the intersection

Select one of the meshes, any will do (A)
Add a Boolean modifier to it:

Operation: Union
Object: one of the other ones (B)

Copy the Boolean modifier

Object: the other one (C)

Optional: If you would like to use the intersection in edit mode to move around mesh components. If all you want to do is to get the intersection just add the empty

add an empty, plain axis will do fine
snap the empty to the intersection: Set the snapping type to vertex. The empty acts as a vertex in this case
in edit mode snap the geometry to the empty if you want to.

Note: You can delete the modifiers when you no longer need them.

Thank you. Using two modifiers did the job very well. However, could you elaborate on the 'Snap' method a little, starting from your point #4? How can I snap the geometry to the empty -- not sure what it means either ?

Set the snapping type to vertex. The empty acts as a vertex in this case

Indeed. Got the intersection point using an empty axis and the Magnet icon.

there are also shortcuts for the snapping. Ctrl + Tab to turn on snapping. Ctrl + Shift + Tab to set what to snap to.

@Vader It's Shift+Tab (you probably already knew that, but just in case others don't..)

@gandalf3 oops it is indeed

there are also shortcuts for the snapping. Shift + Tab to turn on snapping. Ctrl + Shift + Tab to set what to snap to

You can take advantage of Boolean modifier:

Adding a Boolean modifier to Object A, Operation: Union, Target: B;
Adding second Boolean modifier to Object A, Operation: Union, Target: C.
Apply both modifiers to find the point, or use another vertex or empty to snap on that intersection point.


text:
Problem rendering a video (Cycles / Node Editor / VSE)
I am trying to import a video to use as a background. I used cycles render but the video doesn't show up. I uploaded the video using video editor, then added the scene then added alpha over to the images. I used node editor to do the same thing and the video isn't showing up. I tried to find videos online but everyone is using blender render, the problem is the texture of the object I have only shows up in cycles and not blender render and I want to be able to see everything. Is there a way I can view the video?
the video is a .mov file but it is very big about 500MB.!
here is the rendered image

here is my VSE editor

that was all I did.

the video was quite large, is that a problem?

Nope, if you have enought RAM... It rather seems to me that you haven't turned on the "transparent" setting in 'Render' panel > 'Film' section.

it worked, I tried transparent before and it didn't work. I probably didn't wait for it to fully render.

OK, so you can answer your own question :) !

Perhaps try connecting the 'Alpha' output of the render node to the 'Fac' node of the AlphaOver node?

You first need to check the "Transparent" check box, under the subsection "Film" of the tab "Render" (the icon is a camera), on the "Properties" panel.

Then you need to connect the "Alpha" output from the RenderLayer to the "Fac" (Factor).

And, finally, where I have blue, you would connect your video.


text:
Material shading options in 3d viewport limited for Curve objects?
Render Engine set to Cycles.
For Meshes their diffuse colour is shown in 3d viewport when the Viewport Shading mode is set to Material. Curves do not do this, is there any way to turn this on for Curve objects too? For example below, the silver-grey tubes are Curves and I'd expect them to show the diffuse of the materials assigned to them (black, orange, and blue).
Viewport Shading: Materials

Renders like this, this is OK, and so is live Viewport rendering:

The problem is Curves aren't showing their colour, instead a default grey. It doesn't matter which cycles shader-type is used.

difficult to understand what you're asking. did you want to see in your viewport, what you are seeing in your render?

Works for me with cycles and BI, see: https://i.sstatic.net/WsrVM.png, maybe you overwrite the color with a viewport color?

Same thing, also for Viewport Material Shading: https://i.sstatic.net/IpHmi.png

Whenever using nodes, viewport color is independent from Diffuse Color, to preview your color in the Material Preview, copy the value in the Viewport Color slot as shown above

Thanks poor I get it now, i had never seen that Settings panel, i'm just a nodes guy :)

Glad I could help, maybe we can script a node to overwrite the color value... btw: really nice icons!

I'm voting to close this question as off-topic because This appears to be fixed in latest builds. no reason to keep the question around

@zeffii Hm.. It could still be useful, this is actually a pretty good question imo.. But if you really want it gone, then thats fine too.

OK. leave it. maybe someone with a broken build will stumble into it. I'll track views. if it's static for a long time I'll request deletion again.

EDIT
This appears to be fixed in recent builds,
original
I use Nodes for materials exclusively, and wasn't aware there was an independent Settings panel for the Viewport shading color.
1 and 2 are independent, and unlike Objects which are Meshes, the colour isn't automatic.

Here the spheres are Mesh based Objects.

here the blend

Since when has the color been automatic for mesh objects?

Not in 2.74.. Do you perhaps have some addon doing that?

Hrm.. BI will do this, but cycles never has for me..?

Let us continue this discussion in chat.


text:
How to enable View translate and Zoom widgets/gizmo for Node View
Before I attempt to write a replica widget/gizmo for NodeView. I want to know if there is a simple way to enable this glorious gizmo in a 2d view like NodeView.

I need these because the trackpad on this laptop is a bit awkward compared to a mouse. The scrollbars are also (whilst aesthetically pleasing) not ergonomic for my situation.

Node Editor don't have it, but the UV Image editor does curiously. Maybe that is easier to adapt from since it is also a 2D View

cool. i'll check it out!


text:
For Blender 2.80 API, What replaces the constraint_orientation parameter in bpy.ops.transform?
I am trying to update my plug-in from Blender 2.79 code. I am getting the following error from Blender:
TypeError: Converting py args operator properties: keyword "constraint_orientation" unrecognized.

The code relates to this call in __init__.py:
bpy.ops.transform.translate(value=(0, 1.5, 0), constraint_axis=(False, True, False), constraint_orientation='LOCAL')

What is the right way create such a constraint in Blender 2.80?

Did you check the documentation?

Also, you might want to look into using matrix_world translations instead of call bpy.ops.transform.translate. You can create a trans_local variable Vector for the translation, combine the local translation with the world matrix with obj.matrix_world.to_3x3() @ trans_local, and the translate with obj.matrix_world.translation += trans_world. Might be a little cleaner.

Replace constraint_orientation with orient_type.
Links aren't ideal because they might die. If there is a way to add this more permanently, please let me know.
https://blenderartists.org/t/2-80-cheat-sheet-for-updating-add-ons/1148974


text:
Array Modifier creates something that exports as single mesh, how to create same through group/parent/etc?
I'm using Blender for Unity3D game asset creation.  The Array Modifier does something great (see below) that I would love to be able to do for arbitrary collections of objects.  I'm hoping someone might provide instructions / pointers / plugin / ... to help achieve!  So...
An unapplied Array Modifier creates an entity that behaves like a single mesh during export but can still be modified easily (e.g. change the curve, parameters, etc).
I wish to 'group' arbitrary objects to export the same way (possibly sub-including the results of an Array Modifier).
A concrete example
A table comprises legs and top.
The legs are identical so array-ed or group instanced (depending upon layout).  (Those legs might internally use Curve Modifier which we want to tweak in the future and their spacing might also need tweaking (picture doing this with a long curving fence if you're thinking manual answers!)).
On export, the arrayed legs appear as a single mesh (which appears in Unity3D as a single GameObject).  Perfect!
The table top needs including (otherwise its separation degrades performance due to requiring an extra draw call).

Group-ing in Blender does nothing (that I can tell?).
Parent-ing them merely produces same parenting in Unity = same performance issue.
Join-ing them will make the single object but prevent easy future modification.

Potentials
My research found is-it-possible-to-group-several-objects-and-then-manipulate-them-scale-rotate which suggests both parenting and grouping but otherwise nothing.
The only potentials I see involves temporarily joining before / during export.  This seems annoying overhead.  'Before' requires keeping the blend files outside Unity losing the lovely auto-update.  IIUC Unity imports blend files through some magic Blender-invoking that does an FBX export.  'During' might involve some programming hooks that might join things during that export but not modify the original file?
All thoughts welcome! Thanks in advance!

Welcome to blender.SE! Unfortunately this question appears to be off-topic because Blender exports object grouping information in the FBX file, so the issue is on Unity3D's end.

@Aldrik I don't think this requires closing, the question is not about an issue with Unity or fbx, but about finding a possible solution in blender to efficiently group objects before export while keeping the objects editable.

@RayMairlot The standard object grouping does this. This issue is that Unity is apparently not doing anything with this information.

@Aldrik You are right, despite reading the q several times it appears I was completely distracted by the mention of 'fbx' and 'export'.

Does Unity import all layers?

It seems that joining (CtrlJ) is exactly what you are looking for.
Joining shouldn't prevent future modification.
Within the joined mesh, there will still be two disjoint islands (or five, if each leg is disjoint): the table top and the rest of the mesh.
If you want to separate it again to work with, you can use P → By Selection. You can even, immediately after joining, save the table top as a vertex group so you don't have to worry about selecting it again later, although the Select Linked function (L or Ctrl L) should work for that anyway.
Are there any other concerns for joining? If so, perhaps there's a workaround.

The only answer I could offer would be to write a python script that will take your selected objects (the objects you are hoping to export as 1 game object), duplicate them, join them into one object, call the fbx export operator and then delete the duplicated object.
This has the benefit of automating the task for you, while leaving your original objects intact, but the disadvantage of not allowing unity to manage your files directly as you currently have.

It's my understanding that Unity manages assets directly via blender, so this would break the workflow.


text:
Rendered image coming out black for compositing
Issue: I'm a beginner, trying donut tutorial ("Blender guru"). For compositing, when I render the image, there appears a black screen with many dots (from the start of render till the end), shown below.

Facts: I've connected the nodes in compositing workspace as shown in image. (I've restarted the app. a few times as well).

Observation:
When I render the image (by F12 key) from Layout or Shading workspace, it renders correctly. But in any other workspace, like Compositing, Modelling, etc. it comes out black (shown earlier).
Below is the rendered img. (which is how I want), when I render it from layout workspace.

I want to find out, what might be the reason, for the image rendering to not occur when I'm at compositing workspace.
Please suggest any possible solutions which you might believe.

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

Ya sure, the file was around 200mb with packing, so I used google drive: https://drive.google.com/file/d/1kbgPCRogG27e-46a9F0JmyR9drCaBNZZ/view?usp=sharing

In the Scene panel, you have selected an object as camera, you need to select your camera instead:

Thanks, that solved it. I was just assigning local camera instead of Scene>>camera.


text:
Stretch a UV Map In Sync WIth A Shape Key?
I have a Minecraft rig set up so that the arm/leg will keep a 90 degree angle so that the leg doesn't deform at the joint.  I did this using a shape key with a drive.
The problem with this is that it causes the texture to deform when the shape key is used.
Is there a way I can make the UV Map stretch in sync with the shape key drive so that it does not deform the texture?  Am I approaching this wrong?
Thanks!

Could you illustrate a little further? You would expect a UV texture to stick to the skin of a deforming object.. it's unclear what is happening, that you don't want.

I'm going to rewrite the question.

Normally a UV map would stretch with the mesh.
If you want some block based (alike non deforming lego) character.
Then you create it as separate blocks,
ea : upper leg is a cube and lower leg is a seperate cube.
For each cube part you set the bone weight 100% it will not deform, and from start to end move with the bone, as such the UV (now per block) does not get deformed.
Its a bit hard to tell if you want such movement, i took a little bit of imagination with your problem description, trying to follow what you want.
Its quite common here to put in the blend file in your question, its not required but just a sugestion.


text:
Bevel Clipping/Stopping Point?
Sometimes I bevel two edge loops right next to each other that will end up touching each other.  This means that when I bevel them they will eventually meet, and they will have the potential to overlap each other.  Is there like a bevel clipping option or something that will keep these from overlapping, but will allow the last bevel loops to come to the same position so I can simply click merge to remove the doubles?  Hope this makes sense.
Think similar to the clipping effect for the mirror modifier.

a simple bevel option that would keep a an edge loop from beveling too far would be nice too.

Alternatively you can press C during the bevel operation to toggle between clipping or not clipping to prevent overlaps. I use this with Ctrl +  B shortcut for the bevel tool for a speedy workflow.

Thanks, man!  I didn't know this existed!  Works perfectly!

This functionality is built into the Bevel Modifier, which can be used to bevel only some parts of a model using vertex groups.

Thx, that'll do it for me!

@RBlong2us I'd go with Ian's answer, because when I read your question it sounded like you were talking of using the Bevel tool in Edit mode and not the Bevel modifier.

You are correct.  However this is a good tip.

How to specify a vertex group for a modifier?

Many modifiers (expecially deformers) have a Vertex group field in which you can specify wheter to apply the effect or not. In the case of Bevel modifier, you have to select Vertex Group as Limit Method.


text:
How does Blender calculate path normals?
In Blender, paths may be used to animate objects or to sweep surfaces. Both of these actions require that every point on the path has a normal. If this requirement were not fulfilled, the orientation of the object following the path would be ambiguous and the operations could not be completed.
Curves only have tangents and do not have intrinsic normals. Since normals are required, there must be an algorithm in Blender to generate them somehow. I only know of the following ways to generate normals for a curve:

Use the normal of the plane formed by the tangent and a fixed global axis. Fails when the curve runs parallel to this axis.
Use the normal of the average plane of the curve. Fails when the curve is a straight line.
Use a rail curve. This requires the user to define a second independent curve which never meets the first, and the normal is the line between the two curves.

Blender's path object does not fail when parallel to a global axis or when it's control vertices form a straight line. It also does not require a rail curve. How does it work?
I found this: http://wiki.blender.org/index.php/Dev:Ref/Requests/Incremental_curve_normals_proposal which present another possible solution, but it seems incomplete and may not reflect what Blender actually does at all. It does explain the problem in detail though.

They might be using the derivates of the curve to calculate the darboux frame. I'm not sure, though. Have you tried looking at the source?

Curve control points have also a tilt value, which you can adjust both with the shortcut shift-T and from the properties panel while editing curves. Perhaps this is what you refer as normal?

@axrwkr CV = control vertex = control points.

@saharm I was hoping to avoid looking at the source but I suppose it would work as a last resort. I'll read about this darboux frame, thanks.

@hjaarnio tilt has to be relative to something. By "normal" I mean the up vector when tilt is 0.

In the Shape panel for Curve objects there are 3 twisting options:

Z-Up: uses Z axis to determine the twist.
Tangent: uses Frenet / Darboux frame tangent.
Minimum: step along the curve points, for each point computing a normal that is orthogonal to the curve direction and rotated as little as possible compared to the normal of the previous point.

Minimum is the default, and it behaves well in most cases. The downside is that it's non-local, any control point can influence the twist in the rest of the curve, but that's unavoidable, there is no other way to get minimal twisting.
The implementation in the Blender source code is in make_bevel_list_3D_minimum_twist.


text:
Accessing the object mode preview mesh, or reproducing it?
When in object mode with wireframe display, Blender only draws edges between non-coplanar faces, or edges which only belong to one face. For example this image shows switching between object and edit mode:

Using the python API, is there a way to access the object mode preview mesh, or some other way to tell if an edge would be rendered in object mode? i.e., without having build a list of faces for each edge and then check whether every pair of faces is coplanar?
I don't want to display all edges in object mode, so option "Draw all edges" is of no use. In fact that is the exact opposite of what I want. I want to export only the edges which are shown in object mode, using a python script.

Do you want to have a real mesh only consisting of the shown edges, or just a render? PS good call flagging this.

A real mesh, to export to another format.

I don't think a way exists. What you are seeing is the result of culling the opengl draw commands, not any actual mesh generation. The draw all edges option bypasses the culling.

For mostly flat meshes like your example, this script makes a simplified wireframe mesh, the more curves, the more edges are included. Is that something like what you are after?

@sambler yes, that's what I am after. I wondered if there was a way to do it without recalculating the angle between every pair of faces.


text:
Can I Have 2 Different Rest Poses For My Rig?
I am making a Minecraft character, and I want it to have an option to have 2 different size options for the eyes.  This means that the rig would have to change its rest pose to accommodate for the changes.
Is there a way I can have 2 different rest poses so I can change the settings for the eye size, without having to make 2 separate rigs?

No, but you can have 1) a pose library, now a pose Asset in blender 3.x, where one rig is an adjustment from the rest.  Or 2) you have two different armatures, and you choose which armature is applied to your (common) mesh in a scene -- to save on file size.

thx, I'll look into that


text:
Where is the Vector math add node?
I want to have one material for a bunch of objects and have them generate a different UV for each. This question has been answered here,
but I can't find the "Add" node that accepts vectors.
My Add > Converter > Math > Add node only has grey dots, where I need purple ones.

You want ShiftA> Add > Converter > Vector math instead:

It's worth noting that the node label will changing depending on what operation you select; as you can see, it's not actually called an "Add" node.

You can also simply use a Color Mix node, since vectors (XYZ) are basically the same as textures (RGB) if you stretch your brain a bit. There's nothing stopping you from plugging purple dots into yellow ones almost anywhere. The same goes for the grey dot (values), the only exception is the green one for shaders.
UVs are two dimensional, so they only have X and Y, or R and G (Though other texture coordinates have a Z/B component). Plug the UVs into a shader's color input and you'll see what I mean. This allows us to manipulate UVs just like textures before plugging them into the Vector of the image (or any texture).

The top images are the standard UVs and an image mapped with them, and the bottom ones are the same UVs mixed with another texture, then used to map the same brick image.
Read more about it here: http://adaptivesamples.com/2013/07/31/cif-4-uvs-are-colours/
This is the node setup for the bottom images:


text:
Rotation around the cursor with low-level python (no bpy.ops)
In order to optimize my script, I would need some help to perform a rotation around the cursor
(see Rotate object around cursor with Python)
With low-level python, that means, without bpy.ops.* operations.
I have to admit that I didn't find a good overview on how to make rotation with python without bpy.ops. Do I have to perform matrix operations for a simple rotation around an axis Z located at the cursor position?

I think you are better of using the bpy.ops. The functions in the module call on compiled C commands. This is a lot faster than doing it with python. Also optimizing a script by not using the built-ins blender provides is rather silly. This is just my opinion though

The low level python api will call c-functions as well. See this post and this post for reasons to not use operators.

Rotate a vector
import bpy
from math import pi
from mathutils import Vector, Euler, Matrix, Quaternion

v = Vector((1.0, 1.0, 1.0))
#point which will be rotated around the cursor

cursor_loc = bpy.context.scene.cursor_location

rot_mat = Matrix.Rotation(pi / 2.0, 3, 'Z')
v_new = rot_mat * (v - cursor_loc) + cursor_loc

There are further options available (see api docs):
You can construct a matrix, this is most efficient if you want to apply the same transformation on many points.
mat = (Matrix.Translation(cursor_loc) *
       Matrix.Rotation(pi / 2.0, 4, 'Z') *
       Matrix.Translation(-cursor_loc))
v_new = mat * v

You can use quaternions:
# using (axis, angle) constructor
q = Quaternion((0.0, 0.0, 1.0), pi / 2.0)
v_new = q * (v - cursor_loc) + cursor_loc

or eulers:
eu = Euler((0.0, 0.0, pi / 2.0), 'XYZ')
v_new = v - cursor_loc
v_new.rotate(eu)  # works for quat's and matrix types too
v_new += cursor_loc

Rotate an object
mat = (Matrix.Translation(cursor_loc) *
       Matrix.Rotation(pi / 2.0, 4, 'Z') *
       Matrix.Translation(-cursor_loc))

obj.matrix_world = mat * obj.matrix_world

Euler and Quaternion both offer a method to convert them to a matrix:
q  = Quaternion()
eu = Euler()

mat =  q.to_matrix().to_4x4()
mat = eu.to_matrix().to_4x4()

You can also do from math import radians and specify the rotation in degrees like radians(90) (equal to pi/2)

Thanks pink vertex for the answer. I have difficulties to adapt your proposal for a single point (the vector v) to a whole object obj; could you adapt your script to make it run for an object obj that is a plan or a cube? Thanks.

Added a section.

great, it helped me a lot! I used the matrix_basis and not matrix_world but your answer provided me the information I needed to move ahead. Thanks!

Rotate object(s) around cursor with cursor rotation
I did a function. you can run it on selected objects in a loop.
for ob in context.selected.objects
    rot_around_curs(context, ob)

I convert cursor rotation to a matrix, then modify obj matrix to get a rotation around the cursor with the cursor rotation value
    def rot_around_curs(self, context, obj):
        curs = context.scene.cursor
        mat = curs.matrix
        loc = curs.location
        R = mat.to_quaternion().to_matrix().to_4x4() #cursor rotation
        T = Matrix.Translation(loc) #cursor location
        M = T @ R @ T.inverted() #we just involve the rotation
        obj.matrix_world = M @ obj.matrix_world #update obj matrix

the advantage of converting matrix in quaternion is to not use for instance curs.rotation_euler depending in what rotation mode you are

Hi, thanks for the post. This site is not a regular forum, answers should be substantial and thoroughly explain the solution and required workflow. One liners and short tips rarely make for a good answer. If you can [edit] your post and provide some more details about the code. Perhaps add a few images illustrating the workflow and final results. See How do I write a good answer?


text:
Can threading.event be used as an event in an modal operator?
I am trying to use the event from a thread as an event in a modal operator, is this possible using the bpy.types.Event somehow?
Or do I have to set a timer and check if the event is true?

No, there's no way to pass it to the operator's modal method, so you can't mix both event types. Using a Timer is a better option.


text:
How to get an armature by name in Python and get access to its bones?
I want to retrieve an armature by name and access its bones. However, this doesn't work:
armature = bpy.data.objects["rig"]
bones = armature.bones

It gives the error

'Object' object has no attribute 'bones'`

The "rig" object is found, and the armature variable holds a bpy_struct after the first line executes.
So how do I access the bone data?

"rig" is an Object datablock, bone data however is part of an Armature datablock.
What you are looking for is bpy.data.objects["rig"].data, which is the armature:
# Active object
ob = bpy.context.object

if ob.type == 'ARMATURE':
    armature = ob.data

    for bone in armature.bones:
        print(bone.name)

An armature has two bone collections:

.bones
.edit_bones

Note that .edit_bones are only accessible if the armature is in Edit Mode.
See EditBones, PoseBones, Bone... Bones
There is a third kind of bone data structure for pose bones, which is referenced by the object and not the armature:
bpy.data.objects["rig"].pose.bones


text:
Abort script that renders frames
My script runs through a for loop, each time rendering a frame. How can I abort the script?
Normally, I'd use CTL+C in the terminal Blender was launched from, but this doesn't work.  It just waits until the current frame is done and then raises a KeyboardInterrupt exception in some file called .../2.69/scripts/addons/cycles/engine.py, but continues on to the next frame.
Here is a simplified version of my script:
import bpy

framesToRender = (1, 3, 4, 6, 7)

for frame in framesToRender:
    bpy.context.scene.frame_set(frame)
    bpy.context.scene.render.filepath = "/home/garrett/Desktop/" + str(frame).zfill(4)
    bpy.ops.render.render(write_still=True)

EDIT:
The only way I've figured out to stop it is by killing Blender from the System Monitor (for Ubuntu), or close the terminal Blender was launched from. Using xkill on Blender kills the user interface, but doesn't stop the script.

I am not sure in what part of the script you want to abort, but you can try raiseing and Exception manually in your code.

The tiny x button in the info header during a rendering process is hardcoded, it's unfortunately not an operator you could call from python :(

@Vader, thanks, but I'm trying to stop the script running using a command entered into the terminal Blender was called from (since the script can take many hours to finish), not from a command coded into the script.

The reason why Ctrl+C doesn't work is because it sends SIGINT, which is used to stop renders (hence the cycles reference). If you don't mind killing blender too, either killall blender or kill $(pgrep blender) should stop the script as well.

Couldn't you add a simple if stop to your render loop and set it to true on KeyboardInterrupt?

The exception does not reach the executing for loop. It is consumed before and not raised again. Seems like the render operator always returns 'FINISHED'. So you can not check for that, neither.

I wonder where it's consumed, looks like a bug or misconcepted operator if it's impossible to catch.

@CoDEmanX, good point.  I can't even seem to intercept the console output by changing sys.stdout.  If I could, then I could search through it for KeyboardInterrupt before printing it to the console.

To stop the loop you can install your own handler for the SIGINT signal which is executed by the main thread. (see signal module)
The rendering of the current frame will not abort.
import bpy
import signal

abort = None

def hndl(signum, frame):
    global abort
    abort = True
    print("\nAbort")
    #uncomment to call the default handler
    #raising the KeyboardInterruption exception
    #signal.default_int_handler(signum, frame)

def run():
    global abort
    signal.signal(signal.SIGINT, hndl)
    count = 0
    abort = False
    while not abort and count < 10:
        count += 1
        print(count, abort)
        bpy.ops.render.render()

def reset():
    signal.signal(
        signal.SIGINT,
        signal.default_int_handler
        )

if __name__== "__main__":
    run()
    reset()

Could you explain the code a bit? How does this stop the render mid-frame?

That seems to work.  I've tested it on Linux and Windows.


text:
Are features from Blender daily builds typically in next release?
I have a script which is not working on Blender 2.69, but it works fine on the latest build from builder.blender.org/download. Perhaps they tweaked something in how rigid body simulations are baked to keyframes.
Should I expect my script to work with the next Blender release?
In other words, do the daily builds have experimental features which will be removed or is it typically just features that are planned to be included with the next release?

As for your question about rigid bodies, yes they did change something.

Yes they will typically be in the next release.
There's a Variation column on the builder download page, if it's Official, then it's build straight from current master branch.
Features available in these official builds will typically be in the stable releases, although there are rare exceptions when a feature may be disabled (if its not ready) or removed.
It's a new feature, but still under heavy development. It is supposed to be initially released in 2.70. But the current release cycle has been streched a lot already, and people may eagerly wait for other things to be available in a stable release. So the developers may decide to do a release soon. They post-pone the tabs for 2.71, to let them mature, and not throw them in an unfinished state at the users.
If you rely on certain features in an addon for example, and want to ensure compatibility with the next stable release, I would wait for the first Release Candidate (expect 2.70 RC1 at the end of February). If nobody finds bugs in the RC, it will become the stable release. Otherwise there will be another or even a third RC, until all show-stopper problems are solved. Hence, all features of the RC will be in the stable release (functional changes are not allowed in this phase).


text:
Error in addon: "wm_operator_invoke: invalid operator call"
In this simple addon example, a button is added to the Render tab of the Properties window

but when I click on it, I get the error message:

wm_operator_invoke: invalid operator call 'OBJECT_OT_my_operator'

What am I doing wrong?  Here's my code:
import bpy

class OBJECT_OT_my_operator(bpy.types.Operator):
    bl_idname='object.my_operator'
    bl_label="My Operator"

    def exec(self, context):
        print("hello")
        return {'FINISHED'}

def draw(self, context):
    self.layout.operator('object.my_operator', text="Operator 1")

def register():
    bpy.utils.register_module(__name__)
    bpy.types.RENDER_PT_render.append(draw)

if __name__ == "__main__":
    register()

exec should be execute

Just mark CoDemans answer since he already gave an extended explanation.

As pink vertex pointed out, the method needs to called execute.
What happens here?
An operator added to a panel shows as button, and if you click it, Blender will try to invoke it by default (which means it looks for an invoke() method in the operator).
Since your operator has no invoke(), it will try to execute it instead (thus try to call execute()). Your operator doesn't have it, and Blender gives up with the error mesasge:

wm_operator_invoke: invalid operator call 'OBJECT_OT_my_operator'

So it means it couldn't find a method for the operator context (invoke for a button in a panel by default), nor an alternative (execute).
You can override the operator context in layouts if you need to. If your operator defines invoke() and execute() alongside, you might want a button in a panel that executes the operator, and not invoke it. Create a layout sub-element (column, row, ...) and set its operator_context attribute to the context you want to run it in (see API docs):
import bpy

class OBJECT_OT_my_operator(bpy.types.Operator):
    bl_idname = "object.my_operator"
    bl_label = "My Operator"

    def invoke(self, context, event):
        print("hello invoke")
        return {'FINISHED'}

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

def draw(self, context):
    layout = self.layout
    layout.operator(OBJECT_OT_my_operator.bl_idname, text="Operator 1 - invoke (default)")

    col = layout.column()
    col.operator_context = 'EXEC_DEFAULT'
    col.operator(OBJECT_OT_my_operator.bl_idname, text="Operator 1 - execute")

def register():
    bpy.utils.register_class(OBJECT_OT_my_operator)
    bpy.types.RENDER_PT_render.append(draw)

def unregister():
    bpy.utils.unregister_class(OBJECT_OT_my_operator)
    bpy.types.RENDER_PT_render.remove(draw)

if __name__ == "__main__":
    register()


text:
Can I perform an action when a file is saved or loaded?
If I create a Blender file with a single plane that has 10 000 particles of hair, the resulting file size is 9.9 MB.
If, before saving, I reduce the "Number" (RNA ParticleSettings.count) to 1, the resulting file size is only 435 KB.
Because the hair is randomly generated with a specified seed (ParticleSystem.seed), I can open the 435 KB-file and set the number back to 10 000 and get the exact same hair system generated.
In scenes where I have a lot of hair (especially grass, which can require millions of particles), I've seen differences as high as 50 MB. Taking into account the two backup files, that's 150 MB of disk (and, for me, cloud) space saved, which is a clear advantage. The downsides of this method, however, include:

It's cumbersome. I don't want to have to remember to disable something before saving and re-enable it when I load.
It's error-prone. I find myself adding README.txt files to my directories indicating the desired number of particles for each object, because otherwise I forget and my renders are inconsistent (all of a sudden the grass doubles).
It's forgettable. I've lost days of render time due to rendering a scene with a single grass particle because I've forgotten to reset the number. Obviously this is a human error problem, but it's not helped by Blender.

Is there a way I can attach a "save hook" and "open hook" to a file to do this automatically for me? I could easily write a Python script with custom settings for each particle system:
import bpy

def hair_reduce():
    for ps in bpy.data.particles:
        if ps.type == 'HAIR' and not 'actual_hair_count' in ps:
            ps['actual_hair_count'] = ps.count
            ps.count = 1

def hair_apply():
    for ps in bpy.data.particles:
        if ps.type == 'HAIR' and 'actual_hair_count' in ps:
            ps.count = int(ps['actual_hair_count'])
            del ps['actual_hair_count']

The trick, however, is to have these functions called when the file is saved or loaded.
Can I attach a save/load hook to Blender, or otherwise perform an action when the file is saved or loaded?

Sounds like a bug, should probably be reported on the tracker.

We can register handlers that will be executed before, or after, specific operations. The handler lists are all in bpy.app.handlers, and looking at your requirement, the handler list to use is save_pre (executed before saving) and load_post (executed after loading).
The function needs to be persistent, so they won't disappear every time a new file is loaded. Here's an example of how to register it, edited from my own addon needing such feature:
import bpy
from bpy.app.handlers import persistent

@persistent
def hair_reduce(dummy):
    print('hair_reduce')

@persistent
def hair_apply(dummy):
    print('hair_apply')

def register():
    if not hair_apply in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.append(hair_apply)
    if not hair_reduce in bpy.app.handlers.save_pre:
        bpy.app.handlers.save_pre.append(hair_reduce)

def unregister():
    if hair_apply in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.remove(hair_apply)
    if hair_reduce in bpy.app.handlers.save_pre:
        bpy.app.handlers.save_pre.remove(hair_reduce)

Thanks for your answer. What does the dummy parameter do? Also, shouldn't it be save_pre.append(hair_reduce)?

Also, can I add hair_apply to save_post as well?

Whoops, forgot to replace that one. In several handler lists I've used, the argument's value is always None. So I simply name it the way the example code do.

What, so the hair settings are applied back after saving? I think you can. This is edited from my addon saving and restoring some other settings, originally using both save_pre and save_post, and they worked.

Okay, thanks. One more thing: could you please advise me as to why I can't enable my addon after installing it from file? The code is here.

I added import code for persistent decorator, and remove register_module, from my example code. Should now work in your addon.