text:
Object displaces once parented to bone
i just ran in the next issue when parenting an object to a bone. It displaces by 57m and rotates it. Frustrating as hell.
And yes, before i did anything i applied scale, rotation, etc.

What am i doing wrong?
Thanks for your help.

What do you mean by "ran in the next issue" and what exactly are you trying to do? Have you watched any rigging tutorials?

Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.


text:
How can I map the same part of a texture to different parts of the model?
I am trying to model a simple hose-arm thing for a robot character, and am drawing all of the textures. These 3 sections on the model could be the same, though. They are modeled the same, and could have the same textures, so is there any easy way to just have all of them mapped to the same part of the uv texture so that I don't have to draw that part 3 times?

You should be able to hover over each UV island in turn, hit 'L' to select it, then Grab it and move it over one of the other islands  then paint all the islands at once. You may have to scale each one so that they fit over each other.

Thanks, although they don't quite line up just moving them over. I wanted to know if there was a good way to make sure the individual vertices lined up so the texture ends up the same on all three segments. Or if maybe there's a way to select them so that they all map to the same spot on the UV.

I'm not sure to be honest. I've never done much work on aligning UV areas. Not sure why the UV areas from your object aren't symmetrical. The object itself seems to be symmetrical. How did you UV unwrap it and have you added any seams to it to help the unwrap?

Because all 3 UV islands have exactly the same geometry you could use the Copy and paste tools in the UV editor to stack all 3 islands one atop the other.

In the UV editor, select the UV island that you want to copy (and transfer to the other two).
Open the UV menu and choose the Copy UV's option.
Select the other two UV islands.(select one then Shift select the other).
Open the UV menu and choose the Paste UV's option.

Now all 3 UV islands should be perfectly stacked.

That worked perfectly, thank you!

source: Stack Exchange

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

sort: votes


text:
Instances Random Rotation messes up Rotate Instances toward Object
I have this geo node, in which I can rotate instances toward object. What I want to do is add some randomization, rotation offset, or any fancy things before the Rotate Toward Object, but after all it must respect the final Rotate Toward Object as the main result, controlled by the Factor value. For example, if the Factor moving toward 1, then all other rotation modifications other than the Rotate Toward Object will have lesser effect.

But if I plug the random rotation in,I can see that the random rotation still takes effect, even though Rotate Toward Object now having Factor at 1. This suggests that the Instance Rotation I'm using for the calculation is not correct, how can I fix this behavior?

Have you tried the Rotate Rotation node?

Subtracting two rotation vectors does not make much sense unless both rotations are around the same axis X, Y or Z. The reason is that ONE rotation is in fact THREE rotations, by default in GN, first around X, then around Y, eventually around Z. Consequently, applying one full rotation after the other is very different from applying one rotation around X with the delta X angle, then around Y with the delta Y angle, and eventually around Z with the delta Z angle. You can have a look here e.g. about inverting a rotation: https://blender.stackexchange.com/a/280487/177431

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


text:
Smooth merging in curve to mesh
I generate a bunch of curves in geometry nodes that are then supposed to be converted to mesh with curve circle as the fill curve. I want the mesh to be merged smoothly at points of contact. something like the result of the skin modifier. voxel remesh generates too many verticies and results in some quality issues. Converting to volume and then back to mesh has the same problem while being very slow on top.

Can you please show the desired result with images? It is not clear from the text alone what exactly the goal of this question is. In the best case, you also share your Blend file with us to avoid misunderstandings: https://blend-exchange.com/

I don't think anyone has reproduced the skin modifier in geonodes.


text:
Picking instances from realized instances
I have some instances that have been realized and modified after realization. Using these as a collection I want to do an instance on points with pick instance. I have tried various things but none seem to work.

Use "Split to Instances" to create a dynamic "collection". Of course you need to somehow tell Blender what geometry belongs to which element: one way would be to connect "Mesh Island: Island Index" to the "group ID".

(Using Blender 4.2.1)
The instance Index can be captured before the Realize Instances node, then used as Group ID input in the Split to Instances node to recover each original instance.

(NB: the Switch node and the Rotate Instances node are for demonstration purpose only, to show that the instances order is not modified)
Resources:
(Blender 4.2.1+)

just wondering for this case, when there is boolean operation applied after the realization, I am using sample nearest surface or nearest index to get the captured instance ID for the booleaned edges, is there some more elegant/better way?


text:
join two coils together
i have this probem where i want two coils to collide, but i cant figure out a way to do it neatly

https://blender.stackexchange.com/questions/57284/is-it-possible-to-extrude-a-curve-in-two-directions/

Did you try joining the meshes and editing the geometry? As long as they are separate meshes, you won't be able to properly connect them.


text:
Reliable path for add-on data storage
How can I use the python API to find the most reliable location that an add-on can use to store data like images, assets, etc. automatically?
It's important that this location:

doesn't change for different versions of blender
doesn't get deleted on system reboot like some temp folders
is available on every OS

One option I've found is to use bpy.utils.resource_path('USER') which ends in the version number (on windows C:\Users\blah\AppData\Roaming\Blender Foundation\Blender\2.78), but then do a relative jump to the folder above it. Is there a better way?

Wrote an answer, but then realized it's not automatic as the user has to set a folder in the addon prefs.  This is a one time thing if the user enables addon and saves user prefs.

Maybe we should add a new key 'DATA' to that function? I've already made a suggestion for CACHE. I might get around to implementing it some day ;-)

Set it once in the addons User Preferences.
Suggest using a property in  addon preferences  The user chooses the folder.  I had deleted this answer, as it is not "automatic", however setting a storage location once,  is IMO, not a huge overhead.
Modify the script in link with a folder property
class ExampleAddonPreferences(AddonPreferences):
    # this must match the addon name, use '__package__'
    # when defining this in a submodule of a python package.
    bl_idname = __name__

    assets_folder = StringProperty(
            name="Assets Folder",
            subtype='DIR_PATH',
            )

    def draw(self, context):
        layout = self.layout
        layout.label(text="This is a preferences view for our addon")
        layout.prop(self, "assets_folder")

And then when you need to access it
    preferences = context.preferences
    addon_prefs = preferences.addons[__name__].preferences

    assets_folder = addon_prefs.assets_folder

What about os.path.expanduser('~')?
From what i read on https://docs.python.org/2/library/os.path.html it should work for all UNIX system and Windows. Moreover it is assured that the user have write permission in it.

That does seem like quite a good solution, the only slight disadvantage being it's not in a blender-specific location. For reference, on windows this resolves to C:\Users\you, on linux I assume it's just the home directory.

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


text:
Keyframes in the dope sheet are uneditable, is this a bug?
I am very new to blender and im unsure if this is a bug or not
The selected frames on the dope sheet are permanently seletced and i can't move and edit them in anyway
Whenever i move the keyframes in the layout timeline it doesn't actually change the animation until the original 35 frames are over, and then it plays the animation again but only for some parts
im clueless

hello, could you please share your file with the animated object only? Maybe you have locked the bones?

I did manage to find the issue and fix it, your comment was very helpful tysm!

oh ok great!!!!


text:
Offset Lineart to display true silhouette?
Is there a setting or a way to offset line art silhouettes, so that it is only on the outside of an object? Like it is possible with the Outwards Solidify Method. Line art will be always displayed on the "edge" of an object, reaching slightly inwards, as outwards.
I already tried the offset-modifier, but the scaling options there are clearly not what I'm looking for.

Hello and welcome! Could you please provide some screenshots to clarify what you're trying to do? I'm having trouble understanding your goal, and visual examples would help a lot.


text:
Smooth displaced mesh
Whenever I use a Displace Modifier, it looks like it does no interpolation of my height map.

Green is how it should be, Red how it is. Notice how the mesh is dense. The texture I use as height-map is extremely smooth, it should produce a really nice mesh instead of this "aliasing effect".
I tried to set the number of vertices to the resolution of the height-map (Loop-cut x time on x-axis and y time on y-axis for a x*y height-map) but it produces the same strange mesh.
How can I get a good looking and precise displacement, independently of the mesh resolution ?
Solutions without the displacement modifier are accepted if they exist, but I must use the full resolution of my height-map as I must produce a precise work.
To clarify more what I'm looking for, here, nearly how it should looks like (not all the height-map points are used):

I made some further testing. Here a picture with 2 lines. Top left to down right is "anti-aliased" the other is not.

I tested it on a 512*512 vertices plane (510 Loop-cuts on x and 510 on y) Here is the result :

Strange enough, the line which is anti-aliased has more aliasing with the displacement modifier. Problem is, LIDAR datas are "antialiased" (data from real world, like a photo). Setting the colour space to linear improves the quality. In texture panel, a filter size above 2 creates nice but wrong geometry.

Edited with some drawing :)

Since the displacement modifier uses textures, you can make use of texture sampling options which apply with the example you give.
In the texture's Image Sampling panel, make sure Interpolation is enabled, and increase the filter size (values between [1.5 ... 2.0] give quite smooth result, 3.0 and above are smooth but you loose definition).
You may also want to change the color-space of the image between linear/srgb.

It seems to be the solution, however, after many tries with different bit depths, different paint programs and 3D Packages to produces meshes out of the heigh-maps, etc... I wasn't able to get a result that I'm sure is right. For example, img2stl gives a very different result. So I have at the moment nothing to compare Blender's result. Problem is I get that aliasing effect until I set the filter size to 7-8, which I'm not sure keeps all the information intact. They all do correct mapping from grey value to height value, but the artifacts are different in each package. Still investigating...

I Have a GIS Programm at school that creates TIN (3D Meshes) out of geotiffs. I'll try to compare results with it as it should give the most exact results.

@matali, I think the nature of this problem is that you notice pixelation when the surface makes a 3D shape more then your do as an image. also added note about color space.

Setting to "Linear" improves the quality, thanks. I added an example image in the question for testing. I hope it doesn't get a lossy compression. My tests gives : a filter size under 4 still show aliasing effects. But above 2, the line starts to get too large (so the 3D Model is not exact anymore).

@matali, quite sure the artifacts are correct, at least in that - if the resolution is too low and there is a sharp variation you are going to get artifacts. So unless you can find evidence otherwise (in that case it could be a bug), I would suggest to avoid by using higher resolution images.

Yes I think the artifacts are correct too. I had a look at how QuantumGIS solves this. It first draws the height lines as curves, then calculates the triangulated mesh. I think this step of finding the height lines is what produces those smooth curves and removes the raster artifacts.

In that case you would need a specialized tool for creating geometry, then tessellating & displacing height maps, which would be great but out of the scope of the displacement modifier.

Tried today with some other proprietary GIS tools. I can confirm the smoothness comes from the first step of searching contours = height curves. So your answer is the best one for Blender Ideasman. For those wanting a really good looking TIN/DEM, use a GIS program.

It looks like part of the problem is that you're using both a subsurf and a displace modifier.
If you're going for accuracy, make sure your subsurf is ABOVE the displace. This will give you more polygons to work with (and can be handy for controlling the number of polys you have to render in the viewport, without affecting the final render), but it will not smooth the polygons at all.
If you're looking for "nice" (smooth) results, make sure that your subsurf is BELOW the displace modifier. Just be aware that the subsurf will smooth things without regard to accuracy. Any high-frequency data (sharp peaks, deep troughs, saddles, cliffs, etc.) will be essentially lost (smoothed over).
Last caveat, as you've apparently discovered, if your mesh has enough polygons, then your polys will eventually be more dense than the pixels of your texture, in which case you're going to get a VERY accurate recreation of the texture... down to every aliased pixel.
I've done some of this kind of terrain work before and the unfortunate reality is that the most accurate results often don't look as pretty as we want.
Good luck!

Hi Matt, thanks for your answer, my subsurf is above the displace already. Problem are flat areas, they prevent the interpolation algorithm to work properly. On a line with height 1; 0.9; 0.8;...;0.1;0 interpolation will give 1;0.95;0.9;0.85;...;0.15;0.10;0.05;0. But if the bit depth is not precise enough, it will be stored in heightmap as 1; 1; 1;...;0;0;0 and then interpolated to 1;1;1;0,5;0;0;0 giving that aliasing. I tried to draw heightcurves for every level the bitdepth allow and then interpolate from there. But for many kms long areas with cm precision, it's just too much data.

Smooth shading
For a smooth transition between faces you need to enable smooth shading:

The easiest way is to set an entire object as smooth or faceted by selecting a mesh object, and in Object mode, click Smooth in the Tool Shelf. This button does not stay pressed; it forces the assignment of the “smoothing” attribute to each face in the mesh, including when you add or delete geometry.

Mesh smoothing
To smooth the mesh use the Smooth modifier:

This modifier smooths a mesh by flattening the angles between adjacent faces in it, just like Smooth in the Editing context. So it smooths without subdividing the mesh – the number of vertices remains the same.

Tried it with different parameters, factors superior to 2 gives a chaos of wires (bug ?), but even with factor at 2 and repeat at 40, I still have traces of aliasing/pixels. Can I attach a file for people to try and see the problem ?

@matali yes, add it to the question but make it as small as possible.

Using the smooth modifier is a work-around and not solving the real problem, though It seems to me this question may be better as a bug report.

@ideasman42, your assuming the mesh is displaced by an image. This modifier also provides much more control than just the Image Sampling setting.

@Aldrik, right, however the questioner specifically asks about pixel interpolation.

@Aldrik, thanks for the answer, it helps producing a "nice looking mesh". However, in my case, it produces sometime too big height differences (between reality and 3D model). For those not looking for fidelity, it's a good answer :)

Not sure how I should change the wording of the question's title to include the fact that it should be exact. "Smooth and exact/precise displaced mesh" ?

In my experience, displacement accuracy is usually related to one of two things: mesh resolution, and the bit depth of the texture image.
Can you add a multires modifier before the displacement modifier to up the mesh resolution?
Can you bring in the texture with a higher bit depth (16/32) so there is a finer gradation between the height levels? A 32 exr file will obviously give you more height detail for displacement, but it all depends on your source file for the texture.
Barring that, it might be a bug as Campbell has suggested.

I tried with a 16 bit/channel texture, it doesn't help. The problem comes actually when the mesh resolution is near or superior to the texture resolution.

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


text:
How to find the right keymap to change on addon registration?
I tried to redefine a shortcut in my addon registration step, but I can't find which one to change. In the user one (bpy.context.window_manager.keyconfigs.user.keymaps['3D View'].keymap_items) there are 3 transform.translate keymaps.
How can my registration code recognise the one in transform modal map and rebind it to a custom key ? How to restore it in the unregister function ?

See the api reference

That's exactly what I followed, but there is nothing about modal map there or am I blind ?

Are you after one of these, e.g. rotate?
>>> C.window_manager.keyconfigs.user.keymaps['Transform Modal Map'].keymap_items[5].propvalue
'ROTATE'

I'm pretty sure there's only one modal map for all transform operators (and not changable with python).
import bpy
wm = bpy.context.window_manager
keymap = [k for k in wm.keyconfigs.user.keymaps['Transform Modal Map'].keymap_items if k.type == 'G'] #k.propvalue=="TRANSLATE"]
modal_translate = keymap[0] if len(keymap) > 0 else None
print("\n", modal_translate)
for attr in dir(modal_translate):
    if not attr.startswith("_"):
        val = getattr(modal_translate, attr)
        if type(val) in {int, float, str, bool}:
            print("\t", attr, "=", val)

"""
 <bpy_struct, KeyMapItem("")>
         active = True
         alt = False
         any = False
         ctrl = False
         id = 5
         idname =
         is_user_defined = False
         is_user_modified = False
         key_modifier = NONE
         map_type = KEYBOARD
         name =
         oskey = False
         propvalue = TRANSLATE
         shift = False
         show_expanded = False
         type = G
         value = PRESS
"""

But note that you can't provide an operator name in modal maps. Only the predefined modal operations can be set (propvalue).

When I change the shortcut for translate in modal mode under the user preferences, one of the 3 above-mentionned transform.translate go away. So I'm sure I could do it with python by rebinding one of them. problem is which one and how to ensure it works by all users (even those with non-default config).

Not sure how to safely restore a user binding, since blender doesn't call unregister() on quit nor are save_pre / save_post app handlers called (although blender saves to quit.blend). Probably safer to just deactivate an existing keymap and search for it on unregister() to activate again. This way, you don't have to store anything.

Entering the code above, i get : >>> modal_translate.type
'WHEELUPMOUSE'. I try to configure G in translate modal mode to cancel blender's translate in my register addon function (to automatically make a GG shortcut)

Updated code to look for 'G' keybinding and print info. Condition can easily be changed. You should probably look for all map_type == KEYBOARD keymap items with propvalue == 'TRANSLATE' and set active=False. Then add your own new keymap item with propvalue='CANCEL'.


text:
Can I save blend files with lzma instead of gzip?
I compiled blender with Lzma on, but when I check "compress file" while saving, it currently compresses with gzip (zlib).
Is there a special compile option to change it? Or can I do a save script in python that compress/decompress to/from lzma (without writing to the HDD).
I'm working on very big files and Lzma2 (tested by compressing to .xz with linux) is between 2x and 3x smaller and not much slower because multi threaded.

The GZIP compression is currently the only compression format considered when writing or reading a .blend file. A single reference to LZMA in Blender's code is for compressing point-cache files, with accompanying caveat:
"Effective but slow compression"

... something we wouldn't consider as primary choice, for dealing with potentially large .blend files.
I think your best bet is to write export/import operators, utilizing external LZMA (de)compressor.

Some kind of operator would only work for single blend files, you couldn't library link to them for example. so it can work but it would be limited.

The official doc of Python says 3.3 includes lzma2. But yes, it wouldn't work for linking.

@ideasman42 With the new improvements made to the sculpt system, it's not hard to have 600MB uncompressed files. One of my scultp was compressed down to 90MB from 750MB with LZMA against 250MB with Gzip and LZMA was faster with 8 threads than gzip (monothread). 4cores with HT are not that rare either amongst the community I think. LZMA is already in Blender's code, so maybe let the user decide in the options ?

@matali, Of course other options can always be added, good to know it can be threaded, but currently its not supported (which is the answer to your question).

@Ideasman42 Thanks for your answer, it was not a feature request, more a feedback on today's new use cases and the problems they bring.

No, blend file compression is currently limited to gzip.
LZMA support is only for pointcache compression. If this is needed, I'd suggest looking into using a file-system that supports compression (such as Btrfs).

Good solution in some time maybe, but today, it seems to be pretty unstable. I use it mainly for Hires sculpt which take lot of time. It would be rather annoying to loose many hours/days of work.

I've had no problems using Btrfs, if you want a less actively developed file-system see the list on wikipedia. Of course for important information making backups is a must.


text:
How are oslexec.lib and oslexec_d.lib compiled?
I'm currently trying to change a method in the oslexec library so I can add extra math for closure types (it's a long story). So I was needing to compile oslexec.lib and possibly oslexec_d.lib, from the Open Shading Language (OSL) repository. I was wondering if anyone knew if Blender uses the standard oslexec library or if there were additional changes added to it for use in Blender? The reason is when I do compile the oslexec library folder (in the osl repo specifically), and then paste it into blender's repo before compiling, I get link errors 2019/2001 relating to OpenImageIO. I didn't know if the reason for this was because additional code is added to oslexec when it is compiled into oslexec.lib?
Or the other possibility which is also likely, I originally was trying to compile all of osl, however I got stuck adding/installing the various dependencies for it through CMAKE. So after persistent trial and error I ended up realizing I could compile oslexec individually and it at least built fine. Though now I'm thinking by not making all of osl with the dependencies it needs, that's why the oslexec.lib file displays link errors when compiling blender.
So in summary: Is the oslexec library code changed at all from it's OSL source code for blender? Also does all of OSL need to be compiled with it's dependencies for oslexec library folder to build correctly into oslexec.lib?
Thanks,
Nate

for questions about the source code of Blender and such, you'd probably get more answers by asking on the official Blender chat with the devs. See Community — blender.org


text:
Partial glowing transparent grid on logo
I want to create a partial glowing grid on a logo as in this video: https://youtu.be/ril9RQmegR0
Can anyone help me?
thank you!

Hello and welcome. While files, images, and external videos or links may be helpful additions they should not be the only way to obtain information about your issue. Don't make understanding your question rely on downloading a file, watching a video or visiting an external site. Use the builtin tools to upload images or gifs, along with thoroughly explaining the problem in written form so it can be indexed and searched for thus helping future visitors with similar issues.

Maybe give a Wireframe modifier to your object, and enable the Bloom option if you are in Eevee until Blender 3. Since Blender 4 Bloom doesn't exist anymore and you need to use a Filter > Glare node in the Compositor:


text:
Miscalculating midpoint of 3 objects?
I have a problem with a script which is calculating the middle point of 3 objects A, B and D.
When I move B in between D and A, the C object should be in location of B, but it is a fair amount on opposite side from which the B object moved from.
Below are the lines which i'm using.
a = scene.objects["a"]
b = scene.objects["b"]
d = scene.objects["d"]
c = scene.objects["c"]

aPos = a.position.xyz
bPos = b.position.xyz
dPos = d.position.xyz

mid = (aPos + bPos + dPos) * 0.5

c.worldPosition.xyz = mid

Feels like it is not calculating this precisely, and even if i move the mesh of object B to where it supposed to look like, visually B aligns with C between A and D. But when B moves for a fair amount to opposite side again, it no longer feels like it is the middle of A, B and D.
Just wanted to ask if anyone has been facing or noticed this "glitch" I would say, or maybe a more precise way of getting this done exists?
Thanks in advance!

Three points, divide by 3, not two.
mid = (aPos + bPos + dPos) / 3.0

This night the Daniel saved my life with this soooong!
I could be dieing here for years trying to figure this out...
Thank You so much!


text:
How to get Python multiprocessing module working on windows?
I am trying to run a script within Blender that utilizes multiprocessing module.
According to documentation it is possible to use it ( see note at the end of "Strange errors using ‘threading’ module" ).

Pythons threads only allow co-currency and won’t speed up your scripts on multi-processor systems, the subprocess and multiprocess modules can be used with Blender and make use of multiple CPU’s too..

So I tried running below script within Blender:
from multiprocessing import Pool

def test( v ):
    print(v)
    return v

p = Pool(2)

print( p.map(test, range(5) ) )

This however spawns as many new Blender instances (with separate windows) as there are workers in p (in my case 2).
Also it spews in System Console :
Can't read file: "C:\Program Files\Blender Foundation\Blender\-c", Unable to open the file.
Can't read file: "C:\Program Files\Blender Foundation\Blender\from multiprocessing.forking import main; main()", Unable to open the file.
Can't read file: "C:\Program Files\Blender Foundation\Blender\--multiprocessing-fork", Unable to open the file.
Can't read file: "C:\Program Files\Blender Foundation\Blender\2888", Unable to open the file.

I also thought about using os.fork() to do the same thing, but sadly Windows does not support that.
I've been looking all over Internet, but so far I was not able to find even one example proving that documentation is correct.
The only thing I found was thread on blenderartists.org, but it is locked and with no responses.

Update: This is a windows spesific limitation in the multiprocessing module. ~ideasman42.

You can find and chat with many devs by locating the following channel using an IRC application.
#blendercoders freenode - Chat Room on IRC
http://irc.netsplit.de/channels/details.php?room=%23blendercoders&net=freenode
There is also a blenderpython channel but I forget the exact name.  Someone at #blendercoders will know it.

I believe this has to do with running it in Windows. The multiprocessing module has several restrictions there, because it cannot fork, but instead spawns a new interpreter to import the module. In this case, it would seem that the arguments that would cause Python to do this don't work on Blender; the multiprocessing module must be told where to find a compatible Python interpreter instead.

few years ago there was a master-class in autodesk area that was about python multi thread I do not know if it is useful for blender but I think the concept is same.

Your code works in 2.73 . Guess they've fixed something

@Highstaker thanks for update. I will check it when I get home.

@elmo Works in 2.74 as well. But I've just noticed that you're using Windows here, and I used it in Ubuntu. I doubt that this code is affected by OS used, but who knows...

I am using Windows 8.1 and it spawns new blender instances. So it's not working (on Windows). Meh.

Maybe you'd like to file a bug report to get more considered answer? Errors from such a small amount of code tend to mean the problem isn't with the code..

I entirely forgot I asked that question, but since then I've worked out a workaround for the issue.
I use Blender as video editor (even though it is not its primary purpose it works really well for my needs while still being free).
I ended up creating and add-on script that will launch multiple instances of Blender to render separate sections of my video thus utilising multiple cores in my CPU.
Full solution and actual add-on with that functionality can be seen here:
https://github.com/elmopl/ktba/blob/master/scripts/addons/parallel_render.py
It's not perfect in how it is coded, but it works fine.
I simply save my current project's state into temporary .blend file and then launch multiple headless Blender instances (using subprocess module) that load that temporary project and launch into main() of my add-on.
That main() is responsible for handling communication with main instance and performing render operation of headless instances.
It seems to work quite well.
Usage of addon documented here: https://github.com/elmopl/ktba/wiki/Addons#parallel-render
That solution could be split and wrapped up into separate module that does purely subprocess call + handles communication layer. Then it could be reused by others.

Alternatively, you can use Flamenco, which is what we use & develop at the Blender Institute.

Edit, this workaround is no longer needed as of 2.91.

This looks like a kind of ms-windows specific problem... at least a conflict with having an embedded Python interpreter and the environment which multiprocessing expects.
(its not exactly a bug, in that its not like Blender devs can fix some mistake to get this working).
Currently multiprocessing makes the assumption that its running in python and not running inside an application.

I managed to get multi-processing working on ms-windows, doing some workarounds.

sys.executable needs to point to Python executable.
The scripts __file__ needs to point to a file on-disk(not always the case - when executing a text block for example).

Heres an example of a workaround:
import sys
# are we running inside Blender?
bpy = sys.modules.get("bpy")
if bpy is not None:
    sys.executable = bpy.app.binary_path_python
    # get the text-block's filepath
    __file__ = bpy.data.texts[__file__[1:]].filepath
del bpy, sys

# end workaround!
# --------------------------------------------------

# Example from
# https://docs.python.org/3/library/multiprocessing.html
from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    if hasattr(os, 'getppid'):  # only available on Unix
        print('parent process:', os.getppid())
    print('process id:', os.getpid())

def f(name):
    info('function f')
    print('hello', name)

def main():
    info('main line')
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

if __name__ == '__main__':
    main()

I have a feeling this will not allow me to access blender specific things, so not overly useful.
What I want to do is to run in parallel multiple renders of different parts of sequence/scene.
I have 8 cores and Blender does not utilise all of them when rendering VSE result. Currently my solution is to open 4-6 Blender instances, change start/end frames by hand and render. Which is annoying. I would like to achieve this with one click.

Right, You can't access anything which is Blender specific (unless you compile Blender as  Python module, and even then... you wont be able to pass Blender data as arguments).

@elmo, From the sounds of it, you don't actually want to use Python's multiprocessing module at all. Please ask a new question ~ Blender+Python can do this, but not using multiprocessing.

Looks like this trick does not work in this days. The example on my computer launching new Blender instances.

I think this statement in the same docs says a lot:

"So far, no work has gone into making Blender’s python integration thread safe, so until its properly supported, best not make use of this. "

The statement that subprocess and multiprocess can be used with Blender isn't false, just may be interpreted in reverse with regards to multiprocess module.

subprocess can call external apps fine with .call or .Popen, non-blocking or blocking. Works as expected, threaded or non threaded.
multiprocess probably doesn't work (right now) as you might expect, how I interpreted this statement originally was, "you can call several instances of Blender from a python program using multiprocessing, that way you have control over what ends when and can use multiple CPU's.

In the end the warning is reasonable clear (I think?) that we aren't to expect threaded execution of calls to Blender functions within the one Blender executable. (for instance function calls that take a lot of time, like baking.. it is possible to write scripts to do all that and finally when all blender processes have ended , merge the result in an additional script. The work (scripting wise) may be a little bit more, but that seems to be where it's at at the moment.
Ubuntu 14.04
On Ubuntu that code leaves headless processes behind, which only finish when the main Blender executable is terminated. If there's a problem it's not entirely localized to windows.

Question is not about Linux. It mentions Windows explicitly (I've updated title to make it more obvious).

If you stopped reading just because I mentioned Linux then you are missing the point, the answer is pretty OS agnostic.

Being "thread safe" has nothing to do with multiprocessing. So that part is not really relevant to question. I am looking for a solution that will allow me to write a plug-in for blender so I can just press one button to execute things in parallel (render video sequence).
Quite likely I can write a script to a file and then launch it somehow in different instances of Blender, but that's not really point of that question.
Answer will quite likely be very OS specific as it seems there is an issue with multiprocessing specifically on Windows.

... I used python 3.9.4(64 bits) in Windows 10 the following code:
from multiprocessing import Pool
def test( v ):
    print(v)
    return v
if __name__ == '__main__':
    with Pool(2) as p:
        print(p.map(test, range(5)))

.... and at run-time obtain this output results:
0
1
2
3
4
[0, 1, 2, 3, 4]

authors: Сергей Солуянов


text:
Setting render options from the command line
I was hoping to render blender using the command line mode on linux. However, I do not no how to set the output resolution and H.264 as the encoding. Both these options work in the GUI mode but I wish to use them from the command line

You can't set the dimensions from the command line. I'm also certain variations of this have been asked before.. please have a look through the commandline tag.. or specifically Can Cycles renders be done from the command line? and Is there a way to batch render multiple scenes?. Have a look at the parameters in the second link and I believe you can pass H.264 to -F.

Modified the question title, since theres nothing specific to H264 about your question (for any other format the answer would be the same).

pretty neat one: bpy.context.scene.render.image_settings.file_format = 'PNG'

Yes, you can set the dimensions from the command line. The render-batch script in this repo does exactly that.

I prefer to render to separate PNG frames (or alternatively OpenEXR). Then I encode the frames separately using FFmpeg. This way I can tweak the quality settings etc without having to re-render.

Command line
One way is to set the properties from the gui, save the file, then render. The settings will be preserved for rendering from the command line.
Note that (as already mentioned by iKlsR) you can set the render output format from the command line with -F:
Format Options:
-F or --render-format <format>
Set the render format, Valid options are...
    TGA IRIS JPEG MOVIE IRIZ RAWTGA
    AVIRAW AVIJPEG PNG BMP FRAMESERVER
(formats that can be compiled into blender, not available on all systems)
    HDR TIFF EXR MULTILAYER MPEG AVICODEC QUICKTIME CINEON DPX DDS

However, it seems H264 is not a valid setting for this argument.
Further reading: https://docs.blender.org/manual/en/latest/advanced/command_line/arguments.html#python-options
Python
Another way is to use blender's python API, and run a python script in blender from the command line (see this post), e.g.:
blender --background /path/to/file.blend --python /path/to/script.py --render-anim

or
blender -b /path/to/file.blend -P /path/to/script.py -a

The render resolution can be set with bpy.context.scene.render.resolution_x and bpy.context.scene.render.resolution_y.
The output format can be set to H.264 with
bpy.context.scene.render.image_settings.file_format = 'H264'.
Note on scene values:
You may want to assign the settings for all scenes to avoid confusion with complex setups which use multiple scenes.
for scene in bpy.data.scenes:
    scene.render.resolution_x = 1920
    scene.render.resolution_y = 1080
    scene.render.image_settings.file_format = 'H264'

Note invoking render:
When using a Python script to render you have the choice to...

Pass the --render-anim argument.
Call bpy.ops.render.render(animation=True) directly from the Python script.

Both do the same thing however calling the operator from Python means if the script fails to run, render won't execute, This may be good/bad depending on your use-case.
Calling from Python also gives some flexibility - for example you could call render multiple times with different frame ranges.

Note: to avoid creating a script file just for this, a python expression can be passed directly at the command line (the \n should be replaced with actual newlines): blender -b path/to/file.blend --python-expr "import bpy\n for scene in bpy.data.scenes:\n     scene.render.resolution_x = 1920\n     scene.render.resolution_y = 1080\n     scene.render.image_settings.file_format = 'H264'" -a

instead of /n you can use semicolons ;


text:
Is it possible to reset the render view zoom level to 1:1?
After I have rendered an image I often want to zoom in and out to get a good look at it and check for problems etc. However, I don't know how to reset the zoom level back to 1:1 (1 image pixel = 1 display pixel). I know I can just save the render and look at it in an image viewing application, but I was wondering if there is a shortcut or toolbar button somewhere that will reset the zoom?

You use Numpad 1 to get a 1:1 zoom ratio in the Image editor. If you go to View in the header, you can see all the options there.

Thanks. I guess I need to get into the habit of looking through the menus. Seems obvious now :)

in 2.8 it's in menu VIEW > FRACTIONAL ZOOM > ZOOM 1:1

The relevant keyboard shortcuts are 1 for 1:1 zoom, 2 for 1:2, and 4 for 1:4.

Numbers on the numpad, not regular numbers.

these shortcuts can also be customized in  User Preferences > Input > 3D View > 3D View (Global) > View Numpad . So they can be anything you want. Useful for if you don't have a numpad or find laptop fn keys cumbersome.

Also compound with Ctrl for inverse.


text:
What does “Use the pinned node tree” do?
In the Node Editor (Blender 2.67) there is pin icon in the menubar below, which is described as “Use the pinned node tree”.
What is it used for?

The pinned node tree feature enables you to stick a node tree (pin it) to one instance of the node editor, so that you can open another node editor displaying another node tree.
This feature is really useful when you need to simultaneously compare and edit Node Trees belonging to different data blocks (materials for instance).
Reference: http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/2.67/Node_Editor


text:
Can I export a PDF from Blender?
I would like to have a way of getting the design sheets(aka blueprints) like you can in CAD software.
Is there a plugin or addon or some form of python script that can export a PDF(vector screenshot) of the GUI(primarily the 3D view)?

I don't really understand your question. Do you want the geometric data with dimensioned drawing or just the wireframe of your object? E.g. http://wiki.blender.org/uploads/e/e1/Manual-2.6-Render-Freestyle-Demo-BluePrint.png

This isn't currently possible out of the box with Blender or with any addons atm, I could however suggest looking at MeshLab.. it can export to .u3d which can be converted to pdf. http://meshlab.sourceforge.net/

Could you link to an image (or a PDF file) which shows an example of what you would like to achieve? - PDF can contain lots of different kinds of data so its hard to guess at what you want. Are you expecting this to be wireframe or shaded for example?

SVGWriter for Blender/Freestyle

The SVGWriter package provides a set of Python script files for authoring SVG documents with Blender and Freestyle.

Nowadays, SVGs are more portable than PDF, with support in all major browsers. There are also many free tools that can convert them to PDF if that's required. One such program is PDFAid.

The main link is broken, better replace with https://docs.blender.org/manual/en/latest/addons/render_freestyle_svg.html

@MarcosSaito  Your link has become broken too.

To your question:
- Not directly but they are an addon to export the viewport in svg:
"Export SVG" by Liero ->
http://blenderartists.org/forum/showthread.php?282824-SVG-output-script
and in Inkscape, you can export in pdf normally! And voilà!

With an svg python library like this one, it's easy enough to generate pdf from svg too!

The accepted answer suggested the Freestyle SVG plugin; the current URL at time of writing is:
https://docs.blender.org/manual/en/dev/addons/render/render_freestyle_svg.html
The key bit of advice from that URL is:

This add-on can be enabled via Preferences ‣ Add-ons ‣ Render ‣
  Freestyle SVG Exporter. The GUI for the exporter should now be visible
  in the render tab of the Properties editor. The exported .svg file is
  written to the default output path Properties ‣ Output ‣ Output.

The SVG is exported upon rendering the view to the specified output folder, in addition to the regular output.
Another stack exchange post describes some useful settings for exporting the wireframe view appearance: in Blender 2.8 in Layout view, if you open up the 'View Layer Properties' pane, change visibility to 'QI range'.

At present, there is no such addon/plugin that I'm aware of. You can see which addons are currently available publicly on the blender wiki
If all you want to do is convert a collection of images to pdf then there are several python pdf libraries to choose from, i've used reportlab to generate a pdf from a directory of images. But this might be considered off topic.

It seems like your question has two parts:
1) can I export to pdf?
and 2) can I generate blueprints with blender?
The answer to both are no, not with some extra steps (i.e. no script or addons, you'd have to do it manually using Orthographic view.)

To actually make the image, you might want to render in wireframe, (or do screencapture) then Export an image and make your pdf with that. (For screencapture on Windows, press "PrntScn" and then "Ctrl-V" in Paint or Photoshop to capture the GUI, before you last edit you were asking for a GUI capture.)
addendum: You might want to get in contact with these people: Blueprints Collection

Hi and welcome to Stack Exchange! This is a fine answer, but he is asking for a way to make a vector screenshot/blueprint. Please try to answer questions that will solve original posters problem.

the words blueprint and vector screenshot were added by people other than the OP, it's difficult to tell exactly what the OP wants without his response.

what about ANSI sheets. like in autocad? i'm autocad-autolisp certified either if a "blueprint" likes it or not.


text:
Console vs scripting python constants
Using 2.67b for python scripting I get this:
while importing math, numpy on the scripting console, internal variables seem to be fine
but when running scripts need to manually define numbers likely to be enabled when importing math, numpy like PI, E, C and several others I think.
Could that be a version problem or do you have to manually define each variables and constants over the scripting editor?

The python console has various convenience imports, from math import *  being one of them.
Text from the console:
PYTHON INTERACTIVE CONSOLE 3.3.2 (default, May 21 2013, 15:40:45)  [GCC 4.8.0 20130502 (prerelease)]

Command History:     Up/Down Arrow
Cursor:              Left/Right Home/End
Remove:              Backspace/Delete
Execute:             Enter
Autocomplete:        Ctrl-Space
Zoom:                Ctrl +/-, Ctrl-Wheel
Builtin Modules:     bpy, bpy.data, bpy.ops, bpy.props, bpy.types, bpy.context, bpy.utils, bgl, blf, mathutils
Convenience Imports: from mathutils import *; from math import *
Convenience Variables: C = bpy.context, D = bpy.data

>>> pi
3.141592653589793

Importing the entirety of a module using * when not experimenting in the console is generally seen as bad practice / not pythonic, and explained in part here.

Remember, you can never know for sure what names a module exports, so
  either take what you need — from module import name1, name2, or keep
  them in the module and access on a per-need basis

For scripting outside of the console use explicit imports. Create a template with all your frequently used imports, similar to this, and place it in the ../scripts/templates_py/ folder:
import bpy
import mathutils
from mathutils import Vector, Matrix
from math import pi, sin, cos, tan

this article goes into great detail about code structure and includes a short section on imports, definitely food for thought if the topic isn't well understood.

the alternative would be import math and then access math.pi, math.sin etc. For maths this would be overkill, but for more complex modules you should consider that. It also becomes important if you use both math and cmath. And it's noteworthy that you can do things like from math import sin as sine in order to give you more freedom with your own variables' names


text:
Camera to user view?
Let's suppose we have a medium-poly mesh, and we want to snapshot several different closeups by just flying in the camera or using the user's perspective to flyover.
Is there a keyboard shortcut for adding a camera to the user's current view without all having to moving the camera all over the scene to fit a desired position? The switching back and forth from user perspectives to camera view is annoying.

You can see http://blender.stackexchange.com/questions/43/whats-the-quickest-easiest-way-to-point-the-camera-somewhere-in-blender

To make your active camera match up with the viewport, use Ctrl + Alt + 0 (Numpad 0, the other zero won't work).
Also, you can track the camera to an empty with the Track To constraint. This will force your camera to point to the empty, which you can place in the center of your medium complexity face mesh.
To set up the Track To constraint:

Select your empty first, then camera.

Ctrl + Shift + C key, and choose Track To from the menu.

Then, go to the Properties panel > Object Constraints tab. The Target: should say Empty. Change the To: axis to -Z and the Up: axis to Y.

Now your camera will always point to the empty, making things easier for you to position.

Thanks, I got my rep score up, so I was able to add the screen shots.

yep but my original question was retrieved and altered and now it doesn't fit the original purpose. what you think?

can this be done with menus? Ubuntu will close the window if i press those keys

@cammil System Settings -> Keyboard -> Minimize Key -> Set it to 'CTRL ALT 0'. Not the Numpad-0 of course. I'm pretty happy I found this shortcut in Ubuntu! +2 if I could. I used a similar shortcut in MacOSX for the longest time and never new it existed in Ubuntu.

Or accessible through the (space key) menu : "align camera to view".

For @cammil and also my future self: it's found in the menus at View > Align View > Align Active Camera To View.

CtrlAltNumpad 0 will snap the active camera to your viewport position :)

How do you do this with menus or the Python api? I am on ubuntu and ctrl+alt+0 will close the active window.

It works under windows

Its because in windows CTRL+ALT+Numpad 0 is not associated to any system functionality, in UBUNTU it is used to minimize window. There is simple solution, just change shortcut in blender to CTRL+ALT+SHIFT+Numpad 0. Here https://askubuntu.com/a/618581/69037 is described ho to do that.


text:
Orthographic camera mirrored in viewport?
I'm trying to render a building using an orthographic camera. The first side of the building works fine, but when I mirror the camera to the other side of the building the camera is in the right position but the view through the camera is mirrored on the Y axis.
I tried different things:

Mirror the camera again and rotate it around 180°. Doesn't work, the viewport is still mirrored on one axis.
Apply Rotation, Location and Scale (doesn't work either)

My question is, how do I fix this behavior?
PS: I fixed it with new camera - but the question, or the answer is still interesting.

Why do you use mirror ? You should use the 3D cursor (placing it at the building center) to rotate the camera along Z axis, 180°...

This sounds like it could be a bug. If it is, you could consider filing a bug report

Related? http://blender.stackexchange.com/questions/1093/mirror-reflection-invertion

This is because the Object mode Mirror tool works by scaling -1. (the same thing will happen if you manually scale the camera by -1.) You will also notice that in addition to the viewport being mirrored, Object Normals appear reversed.
from the wiki about Edit mode mirror:

The mirror tool in Edit mode is similar to Mirroring in Object mode.
  It is exactly equivalent to scaling by -1 vertices, edges or faces
  around one chosen pivot point and in the direction of one chosen axis,
  only it is faster/handier.

note that using an Orthographic or Perspective camera does not change this behavior. It is the same on both.
(as already mentioned by Polosson),
The solution is to Rotate the camera instead of mirroring it.
Also as already mentioned by Polosson, one way to do this would be to

Select the building, and press Shift+S > Cursor to selection
Press . to change the Pivot point to Cursor
Select the Camera and rotate around the Z axis by 180 degrees. (R+Z+180)


text:
Connect two overlapping planes in Editmode GIS-Tool
I'm still very new to Blender and unfortunately I'm failing at something that is actually quite easy.
I want to connect two overlapping planes so that only four vertices are created. I'm not allowed to move the planes, as there is map material mapped onto them. I can connect them via Join, but in editmode they are still two separate planes (8 vertices).
Background: I use the GIS tool and would like to embed a fairly large area with the highest zoom level in Blender. Unfortunately, I have not yet managed to load the maps in loggt mode as a single plane in Blender. So I want to select the area individually with e at level 17/18 and then select the next monitor section (etc.). This works wonderfully, you can generate large areas at a very good zoom level, but the giz-toll overlaps the planes. When I load the height data and confirm the modifiers, I get a lot of faces at the overlaps. I would therefore like to connect them cleanly beforehand.
Do you know of a way to do this? Remesh and Boolen did not work.
Thank you!
LG
Adrian

If you have overlapping vertices you should be able to merge them by selecting them and then hitting M > Merge by Distance.

yes, I tried that. Unfortunately I can only set the value to 50m . But the plane is several kilometers long. Unfortunately nothing happens.

Merge by distance is really only intended to merge vertices right on top of or very close to each other. The other options on that menu are for groups or pairs of vertices and do what the menu says! This is the Blender manual section on merging.


text:
Follow Path Constraint not working
I am trying to make a the default cube follow a simple path. But no matter how many times I reset the position of the cube to the origin, the cube just follows it's own path in a straight line (a dotted blue line). I'm only adjusting the influence value. It does not follow the path at all. Can anyone please help me with this? How do I use the follow path constraint properly?
All I've done is create a cube, create a path, edited it so that it looks like a curve and then added the path constraint on the cube, nothing else.

Hello select the cube and press Alt G to make it begin at the beginning of the curve, also make sure that the good axis is selected in the constraint, if it still doesnt work please share the file

Have you clicked 'Animate Path' and then run the timeline?

I've tried Alt G and changing the axis, but it doesn't seem to work, here's the file
https://drive.google.com/file/d/1yn5Nr_MY-YB2PsaR5Ce5dWf90xwS1jsi/view?usp=sharing @moonboots

Yes, that seems to work. But, there are no keyframes and I want to be able to control the influence factor for animation. @JohnEason

Don't click on Animate Path otherwise it assigns a Generator modifier to the curve and make the objet move automatically, to cancel that, select the curve, go into the Data panel > Path Animation > right click on Evaluation Time and Clear Keyframes (or remove the Generator modifier of the curve in the Graph Editor). Now you can keyframe the Evaluation Time the way you want.

Thanks a lot @moonboots this worked perfectly. I will use this technique for time being. But it still hasn't solved my problem using "follow path" constraint. I want to be able to use the "influence" factor to animate the object. Any idea how to get that working?

What do you want to do exactly with the influence?

I'm animating a car following a path on a racetrack. I feel I have better control over the object while using the influence factor, but unable to get it to work.

I'm not sure how the Influence value could be better than either the Evaluation Time of the curve or the Offset of the constraint but I may miss something


text:
Does Blender's gltf exporter export Custom Properties that are on bones?
Blender's gltf exporter has an option to include Custom Properties when exporting under Include > Data > Custom Properties. It seems to work when the property is on a mesh, but not when it's on a bone. Has anyone else tried this and had any luck? It seems to me the exporter doesn't support Custom Properties on bones, only on meshes. I did a test export in .fbx and it was able to keep the Property.

I think I found the answer to this, basically gltf does write out custom properties on bones, but the custom property needs to be set on the bone in Object Mode and not Edit or Pose Mode. That was my fix, at least.


text:
Is there any way to export soft body simulation to Unity?
I have a mesh with soft body simulation. Is there any way to export it to Unity?
So far I have baked the simulation into shape keys, and created key frames for shape keys values in every frame, using this script: https://blender.stackexchange.com/a/35564/13487
But I can't import it into Unity - I see my object freezed, or invisible at all.
I would be super gratefull for help in finding a solution!
Thank you in advance!

I had the same problem. Try to export .fbx file manually from Blender and import to Unity as described in one of the answers here https://blender.stackexchange.com/questions/101935/cloth-simulation-for-game-engine-doesnt-get-animated-despite-shape-keys-have-be


text:
Why I can't find my mesh in menu?
I wrote the script, begining looks in this way:
bl_idname = "mesh.tree_add"
bl_label = "Trees Generator"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOL_PROPS'

I installed my script from User Pref. menu and checked this box:

but still I can't find my script in menu called by Shift+A. Also I can't find others extra objects. But I can find it by SPACE menu and it work correctly. Any ideas?

You can't find it in the menu because you didn't add it to the menu. Menus don't automatically pick up new entries based on the class properties, you have to write code to add them:
import bpy

def add_menu_item(self, context):
    self.layout.label("Added this line")
    self.layout.operator("mesh.tree_add")

bpy.types.INFO_MT_mesh_add.append(add_menu_item)

Try updating it to:
bl_idname = "mesh.tree_add"
bl_label = "Trees Generator"
bl_options = {'REGISTER', 'UNDO', 'PRESET'}
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'

It then should appear here:

This doesn't answer the original question, of adding custom entries to the Shift+A menu.


text:
How to get the directory of open blend file? (from Python)
What's the best way to get the full directory of the current Blender file in Python?
It should be cross-platform.

http://blender.stackexchange.com/questions/2545/quick-way-to-get-current-opened-filename-in-a-script

@stacker, I was hoping for something cleaner. Both Adhi and iKIsR's answers would return the whole filepath including filename.  I'd have to split the string using '/' for Linux/Mac and '\', then strip it off the end.  Is there not a single command to get the directory?

Python as well as Blender provide path util functions, you shouldn't ever split using / and \\. Or at least use os.path.sep to get the separator for the current platform. But keep in mind Blender's own notation for relative paths (starting with //). And always check windows compatibility, python may fail for paths which are directly on a drive (drive missing the colon or the backslash).

Path Utilities module provides bpy.path.abspath("//") where the // prefix is a Blender specific identifier for the current blend file.
You can also do...

bpy.path.abspath(os.path.join("//", "my", "file.txt"))
To reference the file in a portable way (Unix & MS-Windows).
bpy.path.abspath(os.path.join("//, os.pardir, "file.txt")To go up a directory and reference a file.

This is used by all internal paths in blender, image, video, render, pointcache etc - paths. so blend files can reference paths relative to each file.
Worth noting that the path may be an empty string, so you may want to check bpy.data.is_saved first.

you missed to escape the backslash, edited your answer to show two ways to handle them. General note: with raw strings, you can't have a \  as last character, nor can you escape it like \\  (will be used literally, as double backslash, repr(r"\\") gives \\\\ ). [had to add a space after \ for stackexchange]

To get the correct separator character, you should use os.path.sep.

You can use the functions provided by os.path for handling pathnames independendly from a platform.
import bpy
import os

filepath = bpy.data.filepath
directory = os.path.dirname(filepath)
print(directory)

To add a file to the basename you could use os.path.join:
newfile_name = os.path.join( directory , "newfile.blend")


text:
Override range number buttons
Many parameters have restricted ranges and if you input a value higher than the maximum, it'll snap back to the maximum value.
Examples include:

speed in a fluid simulation is limited to 100.
energy of a lamp is limited to 10.
etc.

Is there any way to override these restrictions?

Related: http://blender.stackexchange.com/q/2832/599. This works for lamp energy.

I think others (like fluid speed and domain size) are hardcoded in. There might be some technical reason why those are the max allowed values..

Interesting, I wonder what the benefits to the code of those limits are.  From a user's perspective, they seem to get in the way sometimes.

No kidding.. :P

Typically the hard-limits are set quite high, what setting was

@ideasman42, the actual limit that was causing me an issue was the substeps for a Dynamic Paint canvas set to Image Sequence.  It's limited to 20, but I needed something more like 200 since the brush was making sudden jumps.  I've run up against these limits in the past, but I can't remember now which ones those were.

In short, there is no way to override internal limits.
However blender has 2 limits per setting:

soft-limits: which is for number button mouse motion
hard-limits: allow you to type in more extreme values, but there still is a limit.

These let you enter lamp energy of 10000000.0 for eg.


text:
Suppress output of Python operators (bpy.ops.*)
Every time the bpy.ops.remove_doubles() operator is used, it outputs to my terminal (where I called Blender from).  How can I suppress this output?
The code is:
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='TOGGLE')
bpy.ops.mesh.remove_doubles()

and the undesired output is:

Info: Removed 48 vertices

I don't know how to suppress it or if it's even possible, but I believe that message is generated by the report method (stuff will appear in stdout every time something is displayed in the info panel) See this related post.

Python can temporarily redirect the stdout, this is ideal since you may not want to suppress output for _all_ scripts, just selectively silence some operations.
eg:
import bpy

import io
from contextlib import redirect_stdout

stdout = io.StringIO()
with redirect_stdout(stdout):
    bpy.ops.mesh.remove_doubles()

If you want you can read the output back out or use it however you like.
stdout.seek(0)
output = stdout.read()
print("Report was %r" % output)

If you want to redirect both stdout and stderr.
import bpy

import io
from contextlib import redirect_stdout, redirect_stderr

output = io.StringIO()
with redirect_stdout(output), redirect_stderr(output):
    bpy.ops.some.operator_that_may_print_text()

This doesn't work for bpy.ops.wm Could you help me out with this?

This does not work with bpy.os.render. See Marc Morcos' answer for that.

To filter the shell output of Blender you can start it via command line using a pipe with sed (Linux / OSX) or findstr (Windows). We can use sed or findstr to omit every line that starts with Info.
Linux / OSX:
blender 2>&1 | grep --line-buffered -v '^Info'

Windows:
blender.exe 2>&1 | findstr /v /b "Info"

findstr on Windows doesn't seem to have a similar option like --line-buffered. You could install grep for Windows though.
If you want to mute Blender all together preventing it from printing anything you can do this too.
Linux / OSX:
blender > /dev/null 2>&1

Windows:
blender 2>&1 > NUL

Cool!  I wouldn't have thought of that.  I guess the only disadvantage is the output (which I do care about) is not displayed until I quit Blender.

I updated my answer to account for realtime output (I hope).

I tried the command above (blender 2>&1 | grep --line-buffered -v '^Info'), but again, it displayed no output at all until I closed Blender, at which point, it correctly suppressed all the lines starting with 'Info'.

You can verify this behavior by opening a new Blender file, then go to Text Editor, then entering: print("Info - don't display"); print("Hello - display this"), then running the script.

Hm, in that case try the other answer :(

blender 2>&1 | grep --line-buffered -v '^Info'
Works like a charm. Thank you, @Maccesch!

This worked for me (at least for bpy.ops.render) . https://stackoverflow.com/questions/5081657/how-do-i-prevent-a-c-shared-library-to-print-on-stdout-in-python
It makes a context manager you can use to block the output of specific lines.
import os
import sys
from contextlib import contextmanager

@contextmanager
def stdout_redirected(to=os.devnull):
    '''
    import os

    with stdout_redirected(to=filename):
        print("from Python")
        os.system("echo non-Python applications are also supported")
    '''
    fd = sys.stdout.fileno()

    ##### assert that Python and C stdio write using the same file descriptor
    ####assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stdout")) == fd == 1

    def _redirect_stdout(to):
        sys.stdout.close() # + implicit flush()
        os.dup2(to.fileno(), fd) # fd writes to 'to' file
        sys.stdout = os.fdopen(fd, 'w') # Python writes to fd

    with os.fdopen(os.dup(fd), 'w') as old_stdout:
        with open(to, 'w') as file:
            _redirect_stdout(to=file)
        try:
            yield # allow code to be run with the redirected stdout
        finally:
            _redirect_stdout(to=old_stdout) # restore stdout.
                                            # buffering and flags such as
                                            # CLOEXEC may be different

Then just use as follows:
with stdout_redirected():
     bpy.ops.render.render(write_still=True)

This should be the accepted answer!

This looks to be exactly what you need. This process would work well for redirecting stdout and/or stderr to /dev/null when you're about to display something that you don't want to see.
Essentially, point the current references to /dev/null, which will make output go away:
devnull = open(os.devnull, 'w')
sys.stdout, sys.stderr = devnull, devnull
...then point them back to stdout and stderr when you're done, which will restore normal output:
sys.stdout = self.__stdout__
sys.stderr = self.__stderr__

Note: sys already contains the original values for stdout and stderr. You do not have to save them. To restore: sys.stdout = sys.__stdout__. The same is true in many other cases. Also /dev/null is not valid python syntax.

I see, but in the Python docs udner sys.__stdout__, it says "the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object."

While this will work, it would be better to temporarily override stdout, see: http://blender.stackexchange.com/a/34218/55

This doesn't work for bpy.ops.wm.


text:
Random maps in cycles
I want to assign a "random" factor to my materials. I want to load 5 different diffuse maps in my material and assign the same material to 300 objects. The "random node" should take any one of the loades maps and assign it to a object.
Is this or any similar operation possible? Or is it possible to "shift" the uv coordinates randomly to another place in one texture, or to mix the original map with a color (randomly choosen?).

If you want to shift the UV maps around you could use the random output from the Object Info node to give each texture a random location.

My simple node layout:

thank you! the object info node was the needed hint!- lots more on http://blendersushi.blogspot.co.at/2012/12/cycles-object-info-node.html

@Rosebarb be sure to accept an answer, if it effectively answered your question... ratings are the life blood on stack exchange websites... im sure that if there was a "thuglife.stackexchange.com" you would get shot for that check mark lol =)

You can also plug the random into a mix node in order to pick a random one of your five diffuse maps.


text:
Get current editor toolbar tab via Python?
How can I detect and/or change the active tab in the current editor via Python?
Is this doable? I have been digging through bpy.context.region/screen and not yet found a way to list the active tab.

This isn't currently exposed to the API (but we can if its useful), can you explain why you would want to access this?

@ideasman42 I'd like to expose it in the API so as to add hotkeys for switching tabs. This has been a commonly requested feature and something that I would like to play with in Python.
This could also allow some more advanced functionality, like automatic tab switching for specific addons or tasks (not so sure on this one, but could be interesting to play with).

Hotkeys to switch tabs sounds good to me (no one can moan if it's an addon), but scripters could abuse it to make their addons show on activation or during certain actions - two of such addons and it could end in an annoying loop. Nonetheless, it should be exposed, since there are little security checks overall in Blender and official addons are controlled.

@CoDEmanX It's been a while since this question was raised, but has this been tried / implemented by the devs in the past two years? Or were the concerns regarding Guerilla Addons causing loops too big?

I'd also like to know about how this progressed, if at all.

I would also like to abuse the blender UI to make my tab stay on top after a user duplicates the region (from my own tab of course)

Not to 'abuse' but I'd like to add a 'tutorial' mode to an addon, and possibly also make a general 'tutorializer addon' to make tutorials directly inside Blender.

This isn't currently exposed to the API (but we can expose it if it's useful).

If you mean that you want to turn, let's say, your current editor to the UV Image Editor, you could use the following code:
bpy.context.area.type = 'IMAGE_EDITOR'

Here are the rest of the strings you put for different screens:
3D Object Editor - 'VIEW_3D'
Timeline editor - 'TIMELINE'
Graph Editor - 'GRAPH_EDITOR'
Dopesheet Editor - 'DOPESHEET_EDITOR'
NLA Editor - 'NLA_EDITOR'
UV Image Editor - 'IMAGE_EDITOR'
Sequence Editor - 'SEQUENCE_EDITOR'
Clip Editor - 'CLIP_EDITOR'
Text Editor - 'TEXT_EDITOR'
Node Editor - 'NODE_EDITOR'
Game Logic Editor - 'LOGIC_EDITOR'
Properties Panel - 'PROPERTIES_EDITOR'
Outliner - 'OUTLINER'
User Preferences Screen - 'USER_PREFERENCES'
Info Panel - 'INFO'
File Browser - 'FILE_BROWSER'
Python Console - 'CONSOLE'

(The colours above don't mean anything)
So if you want to switch to the file browser, you would do:
bpy.context.area.type = 'FILE_BROWSER'

:)

You can get a list with description with this one-liner: [(item.identifier, item.name, item.description) for item in bpy.types.Area.bl_rna.properties['type'].enum_items]


text:
Is it possible to create a modal operator with a modal keymap in Python?
Creating a modal operator is not an issue, but hard-coding the user tools, interactions, and other events is quite cumbersome and not flexible for the user.
Is there a way to check against modal keymap properties within a modal operator through Python?
For example, in my modal I let users select elements with one of the mouse buttons. This is fine for most users but it becomes problematic if a user changes their selection mouse defaults (as an example).
I know how to create a modal keymap, like so:
kc = bpy.context.window_manager.keyconfigs.addon

# Create the mode switch menu hotkey
km = kc.keymaps.new(name='3D View', space_type='VIEW_3D')
kmi = km.keymap_items.new('wm.call_menu', 'V', 'PRESS', ctrl=True, shift=True)
kmi.properties.name = 'object.menu_name'
kmi.active = True

km = kc.keymaps.new('Addon Modal Keymap', space_type='EMPTY', region_type='WINDOW', modal=True)

kmi = km.keymap_items.new_modal('SELECTION', 'LEFTMOUSE', 'PRESS', any=True)
kmi = km.keymap_items.new_modal('REMOVE', 'X', 'PRESS')

But how do I check against these keymaps in the event system? Normally I would just hard-code it by checking for the event type, but this is not flexible.

I don't know how to use modal keymaps, but it is quite easy to write such an event system on your own.
Here is how I would do it now (I just wrote this the first time, so maybe I forgot something):
at first we need 2 classes to store the keymap information:
class EventCollection:
    def __init__(self):
        self.events = {}

    def new_event(self, name, event_settings):
        self.events[name] = event_settings

    # assumes that only one event can happen at the same time
    def get_matching_event_name(self, event):
        names = self.get_matching_event_names(event)
        if len(names) > 0:
            return names[0]
        return None

    def get_matching_event_names(self, event):
        return [name for name, description in self.events.items() if description.fits_event(event)]

class EventSettings:
    def __init__(self, event_type, event_value, shift = False, ctrl = False, alt = False):
        self.type = event_type
        self.value = event_value
        self.shift = shift
        self.ctrl = ctrl
        self.alt = alt

    def fits_event(self, event):
        return event.type == self.type and \
                event.value == self.value and \
                event.shift == self.shift and \
                event.ctrl == self.ctrl and \
                event.alt == self.alt

Here is how you can use these two classes in a modal operator
class TestKeymap(bpy.types.Operator):
    bl_idname = "my.modal_operator"
    bl_label = "label"
    bl_description = ""
    bl_options = {"REGISTER"}

    @classmethod
    def poll(cls, context):
        return True

    def modal(self, context, event):

        name = self.events.get_matching_event_name(event)
        if name == "my event":
            print("hey")
        if name == "select":
            print("select")

        if event.type == "ESC":
            return {"CANCELLED"}

        return {"RUNNING_MODAL"}

    def invoke(self, context, event):
        context.window_manager.modal_handler_add(self)

        e1 = EventSettings("A", "PRESS", ctrl = True)

        select_type = context.user_preferences.inputs.select_mouse
        if select_type == "RIGHT": event_type = "RIGHTMOUSE"
        else: event_type = "LEFTMOUSE"
        e2 = EventSettings(event_type, "PRESS")

        self.events = EventCollection()
        self.events.new_event("my event", e1)
        self.events.new_event("select", e2)

        return {"RUNNING_MODAL"}

I think this is mostly self-explanatory, so I won't go over it in detail.
Basicly you create an EventCollection when you invoke the operator. This makes sure that it is always up to date to latest changes in userprefs.
In this example I create two events (like KeyMapItems in normal keymaps). The one is very simple and the second one shows how to mimic the selection method. It checks wether you normally select with left or right and creates a corresponding EventSettings instance.
You may rename these classes
In the modal-function you can always check if the current event matches one of the predefined ones.
This makes the system very flexible and easy to extend/change.
Is that a bit like what you wanted?


text:
Control several different materials via one slider
I have to set up an exterior architecture scene… to make it more lively I put a lot of silhouettes into the scene. They are planes mapped to transparency with a mask in cycles. Now I have to change color of all of these "people".
Because this will take lots of clicks to do, I was wondering if there is a way to set up a property in an object that controls a property (RGB in this case) for many objects. I tried a driver but didn't fully grasp it. To do this in post-production is not so ideal because the reflection doesn't work… (if I mask the people out).
Alternatively, is there a way to copy only one property of an object to several others? (Like linking only the RGB between these objects?)

If you want all the silhouettes to use the same material you can use Ctrl-L and select Materials. If you want each silhouette to be different colour then you may want a tutorial by David Miller

If using node materials you could use a node group:

Simply creating a the group containing just a RGB node.

Add > Input > RGB and Add > Group > Make Group.
or ShiftA, I, R (if it gives you Render Layer Node, then it's G), CtrlG.

Go to parent node tree (leave the new group)
For each material Add > Group > (Group Name) and use that as your color.

Edits to the group will effect all instances.

If using BI:

Enable the Object Color option for each material.
Select target objects and set Properties window > Object > Display > Object Color.
Copy To Selected.

In the future it may be possible to use Object Color in cycles using the Attribute node.

Workaround for object color in cycles.


text:
How to turn a mesh into a low poly mesh
I imported a lego build from LeoCAD into Blender and it has LOTS of unnecessary vertexes.

How can I delete all the vertexes inside the mesh, but keep all the vert's on the outside, so it looks normal from the outside but without all the vert's inside

Try the decimate modifier.
Select your mesh and go to the modifiers tab, where you can add the decimate modifier. Play around with the settings until the you are satisfied with the poly count, while retaining a good look.
Learn more about the decimate modifier here: https://docs.blender.org/manual/ja/dev/modeling/modifiers/generate/decimate.html

Select your mesh
Switch to edit mode
Select all vertices
Press P to Separate the choose by loose parts. This will separate the mesh into smaller meshes
Switch to object mode
Select the meshes of the inside parts and delete them
Select the parts of the outside and press Ctrl+J

I have tried something like that but it takes forever. I was hoping that there will be a quicker way.

@JustNatBro can you provide your .blend file and I'll see if there is a quicker way?


text:
"Positional arguments" error in script
This script produces error: object_update<> takes 0 positional arguments but 1 was given
import bpy

def object_update():
    object = bpy.data.objects['Cube']
    bpy.ops.object.explode_refresh(modifier="Explode")

bpy.app.handlers.render_pre.append(object_update)

Script is a kind of working, but how to remove this error?

The functions assigned to bpy.app.handlers need to accept one parameter, even if they don't use it. While you can ignore the scene parameter I would suggest using it, rather than directly accessing global data (not that you are making use of the object variable you set).
import bpy

def object_update(scn):
    object = scn.objects['Cube']
    bpy.ops.object.explode_refresh(modifier="Explode")

bpy.app.handlers.render_pre.append(object_update)

Note that the explode_refresh operator will only work on the active object if it has an explode modifier named "Explode", so I'm not sure what you want to achieve will work, or that it is really necessary.

Thanks for answering. But now I get another error:
Traceback : line 5, in object_update
File "...blender-2.79-windows64\2.79\scripts\modules\bpy\ops.py", line 189, in call ret = op_call<self.idname_py<>, None, kw>
RuntimeError: Operator bpy.ops.object.explode_refresh.poll<> failed, context is incorrect

That would indicate that you can't run the explode_refresh operator from a handler. Have a look at the addon made for this answer as another approach that might work.


text:
How to create a simple extruded box model?
I am new to Blender and was wondering how I'd build a shape like so in blender? I.e. what tools are usually used for these type of organic curves?! the walls are 1mm thick and im wondering how would I draw that shape and set a depth and then give it a flat back as a piece I could then separate to illustrate the bezel and the shape of the curve?
Front view

side view to illustrate depth

This looks a bit too close to request for tutorial, but since its such a simple task maybe its ok?

@ideasman42 yes, I thought so as well since wasn't an explicit request imo.

The title was also a hint, how to do this - renamed, but think this is candidate to be closed still.

@ideasman42 changing the title has nominated it. ;) I thought it was valid as he didn't know what tool(s) he needed to create a certain shape. Let's see if it generates any other reactions though, it is a bit localized somewhat.

What you are asking for is not one tool but a workflow. There is no one set way to do this, curves can be better for getting rounded edges but mesh modeling can be just as good.
However, this is fairly simple and you can achieve the majority of what you ask by just extruding. You can extrude faces, edges and vertices in Blender with the Extrude tool. Just select a face, vertex or edge and press E.
(Alternatively, you can constrain your extrusions to extruding along the object normal with Alt + E), you can experiment with this.
I will use the image you provided as a quick example here..
First, get as close as you can to the shape of the object, (I create the outline of the object from top view). I add a plane  and just grab the edges and subdivide a few times using W > Subdivide while in Edit mode to get some more geometry. I then move the new vertices to fit the shape of the image as closely as possible. To make it more detailed and organic as you ask, you can add more vertices to round out the curved side.

If the face has not been filled, you can use F to make a face from several vertices. I then extrude and delete the top face to give it some depth. To get the lid, I just duplicated the object with Shift+E and moved the sides down.

You can take it anywhere from here now.. I have also quickly added a Solidify modifier to give it some thickness. Also another note, I wouldn't worry too much as a beginner on getting accurate units etc, If you insist however, you can change the units using the Scene tab under Units.
To carry on, I recommend that you see these:

How can I make sharp geometric 3d models look more realistic?
Most efficient way to round edges
When should N-Gons be used, and when shouldn't they?

The cover of the box you modelled will not fit the box in any way. The border has to be a little bit bigger and it has to be mirrored :D

@HenrikD haha, you're right. good catch!

I create the outline of the object from top view). Yes but how do you create the outline?

What you'll probably want is a tutorial on extruding.
Tools you'll need:

The Extrude tool - access with E
The Solidify Modifier - access through the modifiers menu
To measure, probably another tutorial or discussion like this.


text:
Can I change the default color for Relationship Lines?
Sorry but I didn't found where to change the default color for relationship lines (for constraints and parents) among Theme settings. Since I really really need to do so in the current project. Thanks in advance!

Yes you can, but not on their own, this uses the themes wire color which is also used for many other unselected wire-frame data in the view-port. (See: 3D View -> Wire)

Thanks ideasman42. However, it's only work for parents relations, doesn't work for constraint relations. You know, the dark blue line.

Regarding the discuss here http://blender.stackexchange.com/questions/1941/theme-option-for-changing-relation-line-for-constraints
I bet the answer is: "Z axis" mixed with "Grid". (Quite strange through)


text:
How to animate morphing a rectangular plane into a sphere
How to make a grid-to-sphere animation like this?

Thanks cegaton, but shape key is linear deformation. Obviously my case isn't. I mean, each vertex doesn't move along a straight line.

Unbelievably stupid that blender doesn't just have the coding to do this automatically when applying an image to a sphere...

@reee What are you talking about? The question is not about having a sphere object and projecting an image onto it, this is about having a plane object and converting it into a sphere by a kind of "curling up" animation.

I think the one who made that reference GIF (in another software) used two Simple Deform modifiers:

Create a plane, switch to Edit mode, SY2. then use a loop cut to divide it into two squares, then subdivide;
Add a Simple Deform modifier, set deform method to Bend, use a new empty object as its origin, select the empty, then RX90. (to bend it along an expected Z axis)
Add another Simple Deform modifier, also set deform method to Bend, use a second empty object as the origin, select the empty, then RX90, RZ90.
At frame 1, set 0 as the Angle value for both Bend modifiers, insert keyframe for them. Then jump to, say, frame 60, set 180 for the first Angle, 360 for the second Angle (for 360, you may have to type on keyboard), again, intert keyframe for both.
If normal direction is incorrect, flip it in Edit Mode.

UPDATE: In the incoming v2.8, the Simple Deform modifer has a new option that allows choosing Local Axis, so you can use only one Empty in this case, like this:

Nicely optimized! This is better than raising it with the shape-key, those bend origins are very nice.

Exactly how do you make the GIFs? I want to be able to answer questions more efficiently and I have no idea how to make a GIF.

@TheMinecrafterandBlendmist you can use screen capture like: http://www.cockos.com/licecap/

@TheMinecrafterandBlendmist I tried almost all of them and the best was ScreenToGif 1.4

If the plane is not bending correctly (or overlapping itself), you may need to reverse the values (180° in X and 360° in Z). Thanks, Leon Cheung for this great tip!

Also, add a "Weld" modifier last in the stack to remove double vertices at the seam. :-)

Add an UV Sphere, you can use any segments and rings counts (memorize segments). Then rotate it -90d in Y and translate it +1.0 in Z. Adjust the spheres origin to [0,0,0] with Shift+S > To Center and Object > Transform > Origin To 3D Cursor. Important is to not change the scale and have the sphere with radius of 1.0:

In edit-mode delete almost all of the vertices but leave the most bottom "meridian". Extrude the mesh in Y direction to a distance of 3.142 with E + Y + 3.142. Subtract 2 from your segment count and divide by 2, add that many loopcuts ((32 - 2) / 2 = 15 for me):

Create a shapekey. Switch to 3D Cursor Pivot point and scale the mesh down to 0 in local X axis (hold down Ctrl). Animate this shapekey from value 1.0 to 0.0:

Add a Simple Deform Bend modifier. Add an Empty as Origin to control the direction of bending. Rotate the empty 90d in X, -90d in Z.

Animate the modifier's angle from 0d to 180d. Duplicate the mesh and scale it -1.0 in Y. Tadaa!

Edit: Oh and the Bend modifier can be animated to 360d, so you can extrude the mesh in 3rd step both ways and have the whole thing in 1 piece, no need to duplicate and flip..

Shapekey is good, just the initial grid seems not evenly distributed?

authors: فاطمه اقاجانی


text:
Select vertex if vertex color is dark
I've baked AO to vertex colors and would like to use the smooth modifier only on vertices that have a vertex color darker than 0.1 (for example).
How can I select vertices whose colors are below that threshold? I'd then create a vertex group from that and use it in the modifier.
I know you can access the vertex colors with bpy.context.object.data.vertex_colors.active.data[0].color.

It's possible that 1 vertex has at 2 or more (4..5..6) different colors associated with it (for each of the corners of the surrounding faces).

If your script is only going to check greyscale, you can just check the value of the red: if bpy.context.object.data.vertex_colors.active.data[0].color[1] < .1:

There are currently two questions here, "how to convert Vertex Colors to Groups" and "how to subtract values below a value from a Vertex Group". While they can be done in one step in a script, I think they should still be asked separately.

I think it's still valid as a single question: how to parametrically assign a vertex to a vertex group, in this case the parameter is the vertex's own color.

I'm inclined to agree with Aldrik, that perhaps unbeknownst to GregZaal this question requires somewhat elaborate answers. 1) getting the colors attached to a vertex (do you select weighted average or mean?) then 2) selecting verts based on some critera (trivial) 3) the smooth modifier portion / vertex group portion. Essentially making a complete answer very long. Rather split your questions into atomic/modular parts, so that others may benefit from the individual sections of these answers.

I would agree with this. I would be interested in contributing to some solutions to combining the per-face vertex colors into a per vertex, vertex color; a constraint I for an export format.

This will give you a dictionary of colors attached to each vertex:
in the form {vertex_index :  [ color(s) ] ,... } .
import bpy

mesh = bpy.context.active_object.data
color_layer = mesh.vertex_colors['Col']

tk = {}
i = 0
for poly in mesh.polygons:
    for idx in poly.loop_indices:
        loop = mesh.loops[idx]
        v = loop.vertex_index
        linked = tk.get(v, [])
        linked.append(color_layer.data[i].color)
        tk[v] = linked
        i += 1

print(tk)

There are nicer ways to write this, using collections.defaultdict. In this example I also import pprint to nicely display the vertex<-->colors dict (tk).
import bpy
from collections import defaultdict

tk = defaultdict(list)

mesh = bpy.context.active_object.data
color_layer = mesh.vertex_colors['Col']

i = 0
for poly in mesh.polygons:
    for idx in poly.loop_indices:
        loop = mesh.loops[idx]
        color = color_layer.data[i].color
        tk[loop.vertex_index].append(color)
        i += 1

# you must cast this as a dict manually like  tk = dict(tk) ,
# if you need it as a dict, but defaultdict will behave mostly the same
import pprint
pprint.pprint(tk)

This will get you as far as being able to average the colors. The output for this Col (for sake of simplicity i use a 9 vertex planar surface)

is
{0: [Color((0.800000011920929, 0.4313725531101227, 0.04313725605607033))],
 1: [Color((0.11372549086809158, 0.800000011920929, 0.0))],
 2: [Color((0.27450981736183167, 0.27843138575553894, 0.27843138575553894))],
 3: [Color((0.7882353067398071, 0.7921568751335144, 0.800000011920929))],
 4: [Color((0.800000011920929, 0.4313725531101227, 0.04313725605607033)),
     Color((0.27450981736183167, 0.27843138575553894, 0.27843138575553894))],
 5: [Color((0.11372549086809158, 0.800000011920929, 0.0)),
     Color((0.7882353067398071, 0.7921568751335144, 0.800000011920929))],
 6: [Color((0.7882353067398071, 0.7921568751335144, 0.800000011920929)),
     Color((0.27450981736183167, 0.27843138575553894, 0.27843138575553894))],
 7: [Color((0.800000011920929, 0.4313725531101227, 0.04313725605607033)),
     Color((0.11372549086809158, 0.800000011920929, 0.0))],
 8: [Color((0.800000011920929, 0.4313725531101227, 0.04313725605607033)),
     Color((0.11372549086809158, 0.800000011920929, 0.0)),
     Color((0.7882353067398071, 0.7921568751335144, 0.800000011920929)),
     Color((0.27450981736183167, 0.27843138575553894, 0.27843138575553894))]}

To complete this, here's an example of how to average a list of colors (naturally, for greyscale colors you only have to concentrate on 1 component as R,G and B should all be the same.
import pprint
from mathutils import Color

cols = tk[8]   # unadulterated color list for that vertex
pprint.pprint(cols)

def avg_col(cols):
    avg_col = Color((0.0, 0.0, 0.0))
    for col in cols:
        avg_col += col/len(cols)
    return avg_col

print('average')
col = avg_col(cols)
print(col)

Now using the defaultdict that represents the vertices and their occurrence in vertex_colors you can average them, or do whatever calculations and create a new dict with a dict comprehension.
import pprint
import bpy

vcol_averages = {k: avg_col(v) for k, v in tk.items()}
pprint.pprint(vcol_averages)

''' outputs, nicely the averages.
{0: Color((0.800000011920929, 0.4313725531101227, 0.04313725605607033)),
 1: Color((0.11372549086809158, 0.800000011920929, 0.0)),
 2: Color((0.27450981736183167, 0.27843138575553894, 0.27843138575553894)),
 3: Color((0.7882353067398071, 0.7921568751335144, 0.800000011920929)),
 4: Color((0.5372549295425415, 0.3549019694328308, 0.16078431904315948)),
 5: Color((0.45098039507865906, 0.7960784435272217, 0.4000000059604645)),
 6: Color((0.5313725471496582, 0.5352941155433655, 0.5392156839370728)),
 7: Color((0.45686274766921997, 0.615686297416687, 0.021568628028035164)),
 8: Color((0.4941176474094391, 0.5754902362823486, 0.2803921699523926))}
'''

From this you might create a list of vertex indices following a threshold test.
vertices_of_interest = [k for k, v in vcol_averages.items() if v.r < 0.5]

pprint.pprint(vertices_of_interest)
# [1, 2, 5, 7, 8]

Selecting vertices, is easy once you get to this point.

Once you have your weight group there are a couple of ways to modify it:

You can use the group remove setting of the Vertex Weight Edit Modifier.

Group Remove
Removes vertices with a final weight below Rem Threshold from the vertex group.

Alternatively you could use the Weights | Clean operator: bpy.ops.object.vertex_group_clean.


text:
Check if a property is animated or has a driver
Using python, how can I check to see if some property (like context.object.location) has any keyframes, or has a driver attached?

This usage of the api might give some pointers http://blendersushi.blogspot.de/2013/06/python-driving-arrays-like-boss.html

A keyframe check could be done like this:
import bpy

def has_keyframe(ob, attr):
    anim = ob.animation_data
    if anim is not None and anim.action is not None:
        for fcu in anim.action.fcurves:
            if fcu.data_path == attr:
                return len(fcu.keyframe_points) > 0
    return False

print(has_keyframe(bpy.context.object, "location"))

But don't think there is an easy way to test for drivers.

drivers can be done similarly with ob.animation_data.drivers - thanks :)

Nice, I didn't know you could access drivers that easily. You could extend my has_keyframe() function so it handles single properties as well (e.g. location.x), but it should work for array properties already.

What we call "drivers" are technically "driven f-curves" attached through a Python object's animation_data attribute, just like action data. In an object, those attributes are present in the object itself, its data (whatever type it is), shape keys, particle settings, materials and textures. So we need to check those places to know if there's any driver.
The following sample code is adapted from my driver-copying operator, it merely prints the data paths of available animation and driver f-curves:
import bpy

def main():
    obj = bpy.context.active_object

    # Collect places where animation/driver data possibly present.
    keyable_list = [getattr(obj.data, 'shape_keys', None)]
    for ms in obj.material_slots:
        if not ms:
            continue
        keyable_list.append(ms.material)
        for ts in ms.material.texture_slots:
            if not ts:
                continue
            keyable_list.append(ts.texture)
    for ps in obj.particle_systems:
        keyable_list.append(ps.settings)
    keyable_list.append(obj)
    keyable_list.append(obj.data)

    # Print data paths of available animation/driver f-curves.
    for keyable in keyable_list:
        if not keyable or not keyable.animation_data:
            continue
        action = keyable.animation_data.action
        for fc in keyable.animation_data.drivers:
            print(fc.data_path)
        if action:
            for fc in action.fcurves:
                print(fc.data_path)

main()

I'm keeping it simple, but it's possible to extract only the name of the attribute using e.g. regular expression, if one needs to.

Good answer - but a bit over complicated for my needs - thanks anyway :)

@GregZaal: Great if you've found a solution. If a code doesn't capture all drivers in an object, just note that there are several places in the object that contains animation_data.