Having problems with python int types specifying mesh faces again Last year I discovered here that blender is sensitive to the type of integer used to create faces. Now I want to do this with NumPy and I am at a loss for how to do this. I CAN NOT use the previous answer face = (int(iv1),int(iv2),int(iv3),int(iv4)), since my faces will not have a fixed number of vertices, and the source of integers may be other NumPy methods as well.

Question: how in general can I make my vertex list generated by np.arange or other NumPy integer type arrays the "right kind of int" for me.from_pydata(verts, [], faces)?

(Optional question: Is this sensitivity to the type of integer protective - for example, does it make sure the integers aren't too big or something like that?)

If dtype is not specified:

  TypeError: bpy_struct: item.attr = val:
  expected sequence items of type int, not numpy.int64

If dtype = int:

  TypeError: bpy_struct: item.attr = val: expected
  sequence items of type int, not numpy.int64

If dtype = int8:

  TypeError: bpy_struct: item.attr = val: expected sequence items of type int, not numpy.int8

import bpy
import numpy as np

def make_7_seg(hw, hl, gapxy, slant_factor):

    xnom = np.array([-hl, -hl+hw, hl-hw, hl, hl-hw, -hl+hw])
    ynom = np.array([0.0, -hw, -hw, 0.0, hw, hw])
    znom = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])

    xoffs = (hl+gapxy) * np.array([0, 1, 1, 0, -1, -1, 0])
    yoffs = (hl+gapxy) * np.array([2, 1, -1, -2, -1, 1, 0])
    rots  = 0.5 * np.pi * np.array([0, 1, 1, 0, 1, 1, 0])
    sinrot, cosrot = np.sin(rots), np.cos(rots)

    X = cosrot[:,None]*xnom[None,:] - sinrot[:,None]*ynom[None,:] + xoffs[:,None]
    Y = sinrot[:,None]*xnom[None,:] + cosrot[:,None]*ynom[None,:] + yoffs[:,None]
    Z = np.zeros_like(X, dtype='float')

    X = X + slant_factor*Y

    a = np.arange(7*6).reshape(7,6)
    b = np.arange(7*6,dtype='int').reshape(7,6)    # try some stuff
    c = np.arange(7*6,dtype='int8').reshape(7,6)
    d = np.arange(7*6,dtype='int16').reshape(7,6)

    faces = [tuple(thing) for thing in a]

    verts = [tuple(thing) for thing in zip(X.flatten(), Y.flatten(), Z.flatten())]

    me = bpy.data.meshes.new('digit')
    ob = bpy.data.objects.new('digit', me)
    bpy.context.scene.objects.link(ob)
    me.from_pydata(verts, [], faces)

    return ob

digity = make_7_seg(0.5, 2.0, 0.1, 0.15)
#
#  ---A---
# |       |
# F       B
# |       |
#  ---G---
# |       |
# E       C
# |       |
#  ---D---
#
#      A  B  C  D  E  F  G
# "0"  X  X  X  X  X  X  -
# "1"  -  X  X  -  -  -  -
# "2"  X  X  -  X  X  -  X
# "3"  X  X  X  X  -  -  X
# "4"  -  X  X  -  -  X  X
# "5"  X  -  X  X  -  X  X
# "6"  X  -  X  X  X  X  X
# "7"  X  X  X  -  -  -  -
# "8"  X  X  X  X  X  X  X
# "9"  X  X  X  X  -  X  X

Pretty cool script btw, doing this worked:

faces = [ [int(i) for i in thing] for thing in a]
verts = [ thing for thing in zip(X.flatten(), Y.flatten(), Z.flatten())]

or

faces = np.arange(7*6).reshape(7,6).tolist()
verts = [ thing for thing in zip(X.flatten(), Y.flatten(), Z.flatten())]

But I imagine there's a faster way to cast down to regular python ints from Numpy -- That is however really a Numpy/Python problem and not BPY/Blender. I doubt that in this scenario speed is of the utmost importance.


How to select/list all users of an Action? I have a (comparably) complicated, non-humanoid character rig. I am having a lot of trouble exporting this thing to Unity, so I am trying to clean it up without ruining all the animations I made (for the second time). I have one Action that has 3 users, but I only have 2 armatures; No meshes need to be linked to the action because I am using shape key driver-bones to do those deformations.

I have looked through all meshes for this character, selecting the Action and pressing the "x" button, but it is not clearing a link to a user--I can't figure out WHAT extra object is the 3rd, superfluous link to this action! I need to remove that link.

How can I get a list of objects that are linked to this action? Or select them? I do not remember how to use Python scripts in Blender but am open to it.

Any animation editor will show you such a list, provided the keyframed objects are selected at the moment. If you don't know which specific object contains the action you want unlinked, you can simply select everything in your scene, with a, and then check an animation editor. All keyframed objects, and ONLY keyframed objects, will be revealed in the animation editor in question. This list will show both the name of all keyframed objects, as well as the actions to which they are associated. Below, I show the view from the Dope Sheet, but it also works with the Graph Editor.


What's the easiest format to use to create a mesh object? I think that I have to create a beveled mesh 3D shape out of a stock image. (I am using 2.69 on Linux.)

Say, it's a dollar sign.

I was told to use an SVG curve image and convert it to mesh, and then extrude it, etc.

I've followed a bunch of tutorials and instructions here on how to do that, but it's not working as for example this explains:
How can I convert an SVG to a mesh?

After conversion, the mesh is still a mess off planes, edges - in plane and diagonal - and so many vetices that i don't know how to even select them to fill or do a limited dissolve that people suggest here. Extruding it makes it even more unmanageable.

So, i wonder if there is actually a different format with which i should start?

Or should i just somehow create the object myself, rather than deal with converting some other format?

Or should i not even use Blender, but something else?

I am so new to using Blender, that i don't even know what questions i should be asking or how - even after several days googling this, watching tutorials, and reading what i think is applicable in the manual. The explanations just create more questions.

Thank you in advance.

For a dollar sign there are quite a few options.

1.- create a text object, modify it on edit mode to be a dollar sign using the font of your choice. You can then extrude and bevel.

2.- Import a SVG vectorial object and set some extrusion
 and bevel to it.

3.- Using your image as background you can trace the shape manually as a curve object.


How to blur part of the screen in the game engine? I'm making an FPS game, and for some of my guns, i want to be able to zoom in so that i can see farther. This isn't the problem. What i really want is to make the rest of the screen (The part not looking through the scope) blurry so that it looks like the character is focusing through the scope.

I want everything that is not seen directly through the scope to be blurred, for example, refer to the scopes of Crysis 3.

Extending the sample shader linked by @NoviceInDisguise:

How it works: the shader gets the rendered image as a texture its x/y coordinates range from 0 to 1.0

The distance from center is calculated by sqrt(x*x+y*y) > .3 to exclude a circular region from blur.

uniform sampler2D bgl_RenderedTexture;

void main(void)
{
  vec4 texcolor = texture2D(bgl_RenderedTexture, gl_TexCoord[0].st);
  float x =  gl_TexCoord[0].st.x - .5;
  float y =  gl_TexCoord[0].st.y - .5;

  if ( sqrt(x*x+y*y) > .3 ) {
       float value = 0.0015;
       vec4 color = texture2D(bgl_RenderedTexture, vec2(gl_TexCoord[0].st.x + value, gl_TexCoord[0].st.y + value)); // Sample area around current pixel
       color += texture2D(bgl_RenderedTexture, vec2(gl_TexCoord[0].st.x - value, gl_TexCoord[0].st.y - value));
       color += texture2D(bgl_RenderedTexture, vec2(gl_TexCoord[0].st.x + value, gl_TexCoord[0].st.y - value));
       color += texture2D(bgl_RenderedTexture, vec2(gl_TexCoord[0].st.x - value, gl_TexCoord[0].st.y + value));
       color /= 4.0;
       gl_FragColor = color;
   }
   else {
       gl_FragColor =texcolor;
   }
}

Node setup: Add a Filter 2D configure it as Custom Shader and select the above script.

Sample render

Disclaimer: A decent blur needs to incorporate values from a 3x3, 5x5 or bigger matrix, the sample code only uses the left and right neighbor.


How to have a continuous ColorRamp in a broken spline (spline with removed segments) I've got a spline to which I assign a color ramp along its length, so that its color varies continuously from (let's say) blue to red from one end to the other. So far, everything ok. Now I remove a segment on the spline, but now what I see in the render is something quite different: each 'subspline' (i.e. each part of the original spline) start with blue and goes to red. What I want is just the original spline going from blue to red with a missing segment, but what I get is two splines each of which go from blue to red.
Any hint as how to solve this will be greatly appreciated.
Edit:
Someone suggested I added detail about how I got the colouring along the length of the curve. This link explains it; I've followed that (the selected answer) to the letter to achieve it.

The simplest solution is, don't delete spline segments.  If you want part of your spline to "not exist", then use its UV to make these parts hidden, or use a mesh object with a curve modifier to create your spline:

Once you delete spline segments, Blender no longer has an understanding that the newly separated splines have any particular relationship to each other, and cannot draw a colorramp along their length.


What is the workflow to sculpt construction lines using the Curve Stroke Method? I was watching this tutorial and around the 5:50 mark he starts cutting (sculpting) construction lines using the Curve Stroke Method. The problem is that I can't reproduce the effect and the Blender manual seems to leave out the Curve Stroke Method. Can someone shed some light on how to use this technique?

I think I figured it out,

after you choose your brush type(scrape maybe)

and choose your stroke type to curve, make the curve by Ctrl LMB  all over the place

then try pressing Enter a couple of times, or just keep holding it down, or increase the strength of the brush.

I didnt know this was possible, nice


Image to walls of maze I want to add an image file to the maze created but i am unable to find the color option to make the edit.

If i understood the question 1st think notice is that your in Blender Game

If you want to color

Go to the Material Tab -> click on Diffuse below

Change the color as per needed

If you want to apply textures

Click the texture tab -> click New

Select below Image / movie option and below that select open and access the image.


Pack all into .blend file changes material outcome I did a few tests now and so far nothing works except if I change the material entirely, which I do not want to do.

Basically, I have finished my project and need to render it, and I want to use a renderfarm (SheepIt in this case) to save several days/hours. So I need to Pack everything to into the .blend file.

I placed all the textures in same root folder as the .blend file.

The .blend file is in this location:

D:\Program\Blender Foundation\Project Folder\Landscape

All my textures are in this folder:

D:\Program\Blender Foundation\Project Folder\Landscape\textures

Different objects textures have sub-folders:

D:\Program\Blender Foundation\Project Folder\Landscape\textures\Shaft
D:\Program\Blender Foundation\Project Folder\Landscape\textures\Shield
D:\Program\Blender Foundation\Project Folder\Landscape\textures\Sword
D:\Program\Blender Foundation\Project Folder\Landscape\textures\ToonLinkBody
D:\Program\Blender Foundation\Project Folder\Landscape\textures\Navi

On SheepIt.com:
When I upload without pressing this: File > External Data > Pack All into .blend
I get this warning: Cannot find file. and it spams all the textures missing.

When I upload, having this pressed: File > External Data > Pack All into .blend
I get no warnings. But the rendered picture at the end looks like the shading is totally weird, as if the material drastically changed itself.

But! I still get the results below when I render on my own computer:

Picture 1: Without File > External Data > Pack All into .blend

Picture 2: With File > External Data > Pack All into .blend

What am I doing wrong. Why does packing change the glossy/light on those specific materials? I thought packing a blend file, everything would still look the same. To get a decent result with packing, I had to tweak my materials alot, and I am still not happy with them comparing to the "original" if you know what I mean.

Is it only these 3 objects in the entire scene that gets affected by packing into .blend

Toon Shader Diffuse
Toon Shader Glossy
Mix Shader.

Diffuse Map (color)
Normal Map

I have had similar issues with packing files into blend. I have found that my lighting is corrupted while packed, but if I unpack the blend after I've moved it to wherever it needs to be the lighting goes back to normal. So pack -> move -> unpack -> save -> render


Lines on Donut after texture painting I've been following the BlenderGuru's tutorial, I'm at the last part of level 2. unfortunately I found this weird line (looks like'N's) on the inside of my donut. I've just finished doing texturing using nodes. I've no idea where it came from.
One major deviation from the tutorial I did is applying a decimate modifier to lessen my vertices (subdivide subsurface modifier too much).
The Second picture showcases the problem using viewport shading.
EDIT: Included the UV map of the donut. Hope it helps

Managed to get rid of the lines by decimating the donut again until the I got a more basic mesh of the donut and then re-applying the subdivide modifier.


is it possible to keep the texture attached to my project? every time i remove a texture from a file it also vanish from my project and it get replaced with a pink texture instead
is there a possible way to keep the texture attached to my project even if i removed them from my PC ?

To make sure that all the images you use are part of your blend file you can go into the File menu > External Data > Automatically Pack Into .Blend. If you don't want to make it automatic but just want to pack the current images, choose Pack All Into .Blend.

If you want to do it for just one or several images, you can go in the UV Editor or Image Editor, select the image you want, and Image menu > Pack.


Make androids "wave" effect in blender I want to make an animation of a wave like the following images:

I want to achieve that same transparent material. As you can see they are two waves, one over the other. One wave is dark gray, and the other one is light gray. I want these two waves to move the opposite waves, like one moves to the right and the other one moves the the left and then return to the start point in a "smooth" way and repeat. I only need the guide on how to make the animation, the materials are not a problem. Thanks in advanced.

Why not use a simple plane with some modifiers? I have added a Subdivision + Wave modifier, then added a Solidify modifier to give it thickness.

Then I changed the camera to Orthographic to shoot only the wave part.


Cell fracture explosion with followed by reform of the object? How can I explode an object then have them come back to form the original object. Kind of like going back in time.
The object is cell fractured into many peaces and it uses a ball object to explode it out. But how do I make the exploded pieces come together to original form?

To do what your asking:

You can bake the rigid body action by pressing Space, then searching for Bake Action. This will convert the rigid body simulation to an actual animation for the object.

Trim off the extra animation (when the objects fall forever):

Duplicate the remaining keys, press S (scale), then type -1. This will flip the keys.

Position them after the original keys:

And you get:


Are there shortcuts to show and hide the 3D View header? What shortcuts will show and hide this panel?

If there aren't any, how can I make them?

AltF9 toggles the header .. ShiftSpace toggles full screen for the area with focus.


Why object does not snap? Below is my setting but the building won't snap on the face of the ground.

This should work.. strangely, the behaviour of Snap with these settings is view-dependent. In the orthogonal view parallel to the surface there's an ambiguity in 'Closest' that the system can't handle.  The snap is fine if you view from an angle, and just to make sure, constrain the move, too.. say... GZ


Graph editor for shape key animation I have animation where object changes his shape using shape keys, and I want to make some animation smoothing with graph editor. Is there a way to use graph editor for shape key animation?

By keyframing the influence value of the Shape Key I (while mouse over the slider, RMB to open the context menu) you can edit a the F-Curve in the Graph Editor.


How do I make animation nodes drive the vertices of my object? I recently got into animation nodes in Blender, and want to know if I can drive the vertices of an object using sound.

I found this example here:https://www.youtube.com/watch?v=PtD5UQE5Xj0

However, I can't find some of the nodes in the latest version of animation nodes.

I'm trying to make a sound file adjust the vertices of a circle with the method shown in the video.

Best to start by breaking down your problem:
- You want a node tree setup to control vertices of mesh
- Sound to drive the vertices

Check AN Templates for those two:
* Simple Sound Controller
* Random Vertices Offset

The YouTube demo is cool, but if node is missing, you probably can try to look for similar node.

Try a simpler setup first like maybe have a LINE and try to drive the vertices of the line by using sound.


Model clipped after OBJ import I imported an obj file and this is what I get. I cannot figure out how to solve this.

Try lowering the clip start and increasing the clip end in the view panel?


Blender Rigging: Mirrors Changes I have a character body made and im getting it ready for animation in Iclone 6.Im at the Armature stage in blender.The problem is when i test it in pose mode.It mirrors the bone movements to the other side as well and it look all deformed.The left side of the arms and legs dont move with the armature.Im thinking its caused by the mirror modifier i put on the mesh but,Im not sure.  Please help.

To prevent the bones from mirroring , you just have to uncheck "X-Axis Mirror" in the tool panel, while in armature edit mode.


How to make changes to mesh after animating I have animated a bird. However I forgot to add eyes so I want to add them now, but when I change from Edit mode to  Object mode in order to add new eyes the bones, the bird itself gets deformed to pose animation, leaving eyes behind.
Edit Mode:
Object Mode:

I watched https://www.youtube.com/watch?v=R2fx8TMQDoc and it help me to attach eyes to body itself, but I had to put eyes higher in mesh to make it good in animation. Tell me please if you know how to put them the right way.


More pixels rendered, worse screen space reflection result. [EEVEE] Hello everyone, I'm having this problem: The more pixels being render, the worse screen space reflection outcome, also in contradict, the less pixels being render, the better the reflection.
It's actually not like better or worse though, looks like the reflection just disappear. Look at the ground of the 1000px version vs 3000px version, the reflection of the roof where the lights is being placed just simply disappears, and the reflection on the other parts disappear as well but the picture I'm having for you here is too poor quality to be analyzed further. Also if the render had even less pixels to be rendered (below 1000px for example), then it will have even better reflection than the 1000px version itself. And if it got more pixels to be rendered, reflections will gradually disappear.
Please help me solve this problem. It's a important project for my class. Any help is greatly appreciated! Thank you.
[EDIT] PROLEM SOLVED:

NEVER NEVER set the trace precision to the max (1000) as it will cause reflection errors like this. 0.999 works great, as long as not the maximum setting.

Solution to the problem:
Don't set the Trace Precision to the maximum (1000) as it will cause reflection errors like this. The screen space reflection will work perfectly if set to be around 0.950 or lower.


Checker deselect with disconnected faces on same object Select random even works on unconnected faces when part of the same object.
Why checker deselect doesn't work that way?

Okay, as Jachym Michal pointed out checker deselect only looks in all directions and stops at disconnected geometry. It doesn't jump over to the next elements index of the object when it finds disconnected geometry.
Here is a script that selects every other polygon, assuming their indices are ordered.
import bpy
obj = bpy.context.active_object
i=0
for p in obj.data.polygons:
    if i%2:
        p.select = True
    i+=1


How to calculate the cross-section area of an object? I have a 3D model that is sized according to actual dimensions in the real world. I'd like to use Blender to calculate the cross-sectional area of the object, because the cross-section/cutaway shape is too complex to calculate by hand.

One method is:

Enable the "3D Print Toolbox" (follow instructions here).
It can make it easier to move the object to be measured to the origin such that the axis for which you want the cross-section is aligned with a coordinate axis.
Create a cube.
Move the cube using the text entry feature to align with the axis of the object for which you want the cross-section.
For the axis perpendicular to the cross-section, scale this side of the cube to almost nothing (e.g. 0.000001 should be enough).
Scale the other two sides of the cube such that they are larger than the object cross-section to be measured.
Add a Boolean modifier to the cube with an Intersect Operation on the object. Apply the modifier.
Select the object and press H to hide it, so the cross-section profile can be selected.
Select the cross-section profile. Select 3D view > Tool shelf > 3D Printing tab, and select the Area button.
Divide the displayed area result by two (the area measured is the whole surface area of the intersecting object. Ignoring the insignificant side area, that leaves the front and back areas contributing to the total cross-section area).

This illustrates the process visually (unfortunately some recorded key presses were accidental):

Useful resource: Create Cross Sections and 2D planes in Blender


Normal Map Cycles Baking Help I baked a normal map in cycles with a method I found on youtube where you select the high poly (sculpted) version > then the low poly (non-sculpted) version > then bake with selected to active checked.

This gave me a nice normal map where all my sculpting showed up nicely on my low poly version. HOWEVER, it completed ignored my painted texture on my low poly object. I painted some wood tiles and figured when I baked it would recognize it and add some bump map action however it did not. How would I go about baking my sculpting from my high poly to my low poly version AND my low poly painted texture all onto one normal map image?

I’m creating this object for Unity so I kind of need it to all be on one normal map, thanks for the help.

This is my current node setup.

Plug your texture image into the displacement shocket on the material output node. You can add a (converter>>math>>multiply) node between them to adjust the strenght.

Edit.
Excuse me. I forgot that the "selected to active" means the active doesn't count, just the selected. So what you can do, duplicate the lowpoly object, than select all three model. This method gives much better result with Blender render.


Can I use an HDRI for reflections only, and not have its light affect the scene? I have my scene perfectly lit without the use of a HDRI, however I would now like to add one just so I can have some world reflections in my glossy objects. I can't seem to get the HDRI reflecting in my objects without it also adding light to the scene, though. Is there any way to use an HDRI solely for reflections, and not have its light also affect the scene? I am using Cycles.

Thanks

Sure, you need to go into the Properties panel > World > Ray Visibility, and deactivate Diffuse.


obj sequence to alembic format Hello I'm quite new in blender.

I've been working on converting obj sequence to alembic format by using blender.

I've used 'Stop Motion Add-on' and 'obj sequence as shape keys' , but it seems like it's not helpful to export objs as abc format.

I have different obj files per frame. And unfortunately each has different number of vertice. Because of this reason, I guess those add-ons are not suitable on what I am doing.

Any suggestions ???

I've just tried 'ShrinkWarp Modifier' to make the objs as shape keys. It works however I am not satisfied with the mesh made from this modifier...

I'm trying to do something similar. This video might help you. https://youtu.be/Kx4IU8lUCDs?list=PLxQxoABIf8KYi8c_gVqUGSfIUyxX-NrKf

Basically, put a displace modifier with 0 influence on the object you want to export to trick blender into exporting it as an alembic cache properly.

Let me know if you found a different way to do this. I'm still experimenting and trying to find a good workflow.


How can I draw a new single vertex? I´m trying to make these boots and I need to draw this opening on the front but I don´t have the vertex in the way I needed to. How can I create those new vertex? Thanks!

You can use the knife tool K to draw a gap.  Then you can do it with two different ways.

Just manually delete the the faces you drew and fill the inside.
Or you can use default add-on named loop tool. You can enable it in preference section. Just select the top and bottom face and apply bridge in loop tool.
Hope that helps.


Why the transition is disabled? So, I was trying to apply Wipe transition to an image but it was disabled like in the picture. Is there something I'm doing wrong?

You need to have two overlapping strips to be able to add a Wipe transition.


What's the point of mixing the same shader types? Many time I've seen some material using mixing of two same nodes like this:

Is there any difference from using this?

They are not equivalent. Mixing two different roughnesses produces a subtly different distribution of angles at which light can be scattered:

Note the shaper highlights on the right hand example (mixed roughness).

To visualize what is going on, take this (very approximate) example:

The length of the arrows represents the amount of light that gets scattered in that direction.


When I saved the file (Ctrl + S) the texture disappeared I was painting the textures onto the model when I decided to do an incremental save as to not lose all my work, so I pressed Ctrl S and saved the blend file.

When I looked at Blender again (I did not close Blender at all) the object was black and I can't find the texture image I saved? Sorry, I'm really new to Blender. Here's a screen:

I advise is that you go on UV / Image Editor and choose the Image menu and click save the image, choose the output file format the image and click save the image, so you do not lose your work.


Apply All Modifiers via Add-On? I'm attempting to write my first add on. It cycles through all the objects in the scene and applies all the modifiers each object has.

I've set up the panels correctly so when I press a button it calls the following method:

def applyAllModifiers():
    context = bpy.context
    scene = context.scene
    settings = 'PREVIEW'
    apply_modifiers = True
    bpy.ops.object.mode_set(mode='OBJECT')

    for ob in bpy.context.selected_objects:
        print ("Applying modifiers on object " + ob.name)
        bpy.context.scene.objects.active = bpy.data.objects[ob.name]
        numModifiers = len(ob.modifiers)
        if numModifiers != 0:

            # Get all the info we need from the object
            objName = ob.name
            objLocation = ob.location
            objRotation = ob.rotation_euler
            objScale = ob.scale
            mesh = ob.to_mesh(scene, apply_modifiers, settings)

            # Delete the current object
            scene.objects.unlink(ob)
            bpy.data.objects.remove(ob)

            # Create a new object with all modifers applied
            new_object = bpy.data.objects.new(objName, mesh)
            scene.objects.link(new_object)
            new_object.location = objLocation
            new_object.rotation_euler = objRotation
            new_object.scale = objScale
            new_object.select = False
            print ("   applied {} modifiers".format(numModifiers))

        else:
            ob.select = False
            print ("   object has no modifiers")

    bpy.ops.object.select_all(action='SELECT')

It works if I have a single object selected, but if I have multiple objects selected it will randomly move some objects to (0,0,0). I can't seem to get any consistent behavior when I have more than 1 object selected. I'm not really sure this is even the best approach to what I'm trying to do.

Any help would be appreciated. Thanks!

based on this answer https://blender.stackexchange.com/a/7197

import bpy

context = bpy.context
bpy.ops.object.mode_set(mode='OBJECT')

for ob in bpy.context.selected_objects:
    n = len(ob.modifiers)
    if (n) and (ob.type not in ('LAMP','CAMERA','ARMATURE','EMPTY')):
        print ("Applying " + str(n) +  " modifiers on object " + ob.name)
        oldmesh = ob.data
        ob.data  = ob.to_mesh(context.scene,True, 'PREVIEW')
        ob.modifiers.clear()
        bpy.data.meshes.remove(oldmesh)


Hide subdivision dots/normals in edit mode? Somehow I managed to activate a display where I see a lot of dots (normals?) when I'm in edit mode and the object is subdivided.

The image to the left is without the subsurf, and the right is with it on, but I still want to "Display modifier in viewport".

This only happens in Face select mode, but I don't remember it looking like this...?

It doesn't happen when I create a new object, so it seems to be an object setting. I think I have pressed a shortcut but mistake somehow...

I found the answer, I had "Adjust edit cage to modifier result" on the rig I was working on:


Objects appear mixed and transparent when compositing I am working on a sci-fi project, I rendered my scene and my objects are rendered on separate render layers. I encountered a problem and that is the spaceship and the planet in the scene both appeared mixed and transparent. I wanted to ask if maybe someone know a solution to this issue. Here is a picture of the compositing.

Many thanks in advance

Looks like you need to enable Transparency in the Render panel. This would allow you to composite your layers with more Alpha Over nodes instead of Add nodes. In general, I would keep Add nodes only for layering lighting effects.


How to get glare on a specific emission reflection I am attempting to make a red dot sight that is (relatively) physically-correct, but I would like to add a bloom/glare effect to the red dot.  Basically, a face that emits red light reflects off a lens back to the camera, and the emitting face is not visible at all.  Is there an easy way that I can filter out only that reflection and add glare to it in the compositor?

(diagram from Wikipedia):

You basically need to have some way to get only the reflection so that you can perform some effect on it (e.g., glare or blurring the reflection and adding it to the image). You could use color keying if you can't see anything else that is red, you could map an object to the screen of the red dot that was on a different layer only used for compositing, and you can also provide access to the glossy reflections in the compositor. Actually, all three techniques can be used to do this in a more universal manner, but depending on your situation, you will have to make the best choice.

Here is an example I just made:

Enable glossy direct in render layers

My compositor node setup (could be much improved...I just blur the bright parts of the reflection)

Result

Blend file:


Application addon using bpy.data.scenes causes: AttributeError: '_RestrictData' object has no attribute 'scenes' From what I can find this appears to be an issue with what Blender allows access to at the time the addon loads. Posts such as this:

Accessing bpy.context gives a '_RestrictContext' warning, how to fix this?

Suggest that access is restricted due to the the problem with cross functional addons. That makes sense, and I understand the restriction. What I can't find is how to work within that limitation.

In my situation the addon is really an overlay application that user will only run this one thing. So I actually do want to modify the working environment for the whole application. In this instance changing from metric to imperial units. I've tried two ways and both give the same error:

bpy.context.scene.unit_settings.system = 'IMPERIAL'
bpy.data.scenes["Scene"].unit_settings.system = 'IMPERIAL'

How can I make this change from an addon perspective? No matter how it's done this is a global change (at least from a scene perspective) and is going to affect other addons anyway.

You shouldn't access or change properties before the add-on is properly loaded. The unit settings can be changed for example in an operator as can be seen below:

bl_info = {
    "name": "Make Imperial",
    "author": "Robert Guetzkow",
    "version": (1, 0),
    "blender": (2, 80, 0),
    "location": "Dummy panel in View3D",
    "description": "Changes the unit settings to imperial",
    "warning": "",
    "wiki_url": "",
    "category": "3D View"}

import bpy

class EXAMPLE_OT_make_imperial(bpy.types.Operator):
    bl_idname = "example.make_imperial"
    bl_label = "Set unit settings to imperial"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.context.scene.unit_settings.system = 'IMPERIAL'
        return {'FINISHED'}

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

    def draw(self, context):
        layout = self.layout
        layout.operator(EXAMPLE_OT_make_imperial.bl_idname)

classes = (EXAMPLE_PT_panel, EXAMPLE_OT_make_imperial)

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

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

if __name__ == "__main__":
    register()


My smoke renders as squares/cubes I'm making an animation scene where black fog swallows a grassy field, but I have a problem with the smoke simulation. In the view port it looks fine, but when I render the smoke it is boxed and squared, and looks like cubes (I have baked the simulation).

I have tried different things, from people with similar problem, but nothing works..

Any idea why, or advice?

Thanks :)

example:

Smoke domain set up:

Smoke compositing:

Increasing resolution divisions in domain and, in smoke high resolution fixed the problem.

Thanks to Merlin.


Lock pose during animation? is it possible in blender to lock relative positions of bones for a number of frames and during these frames animated the armature as a static object? For example, beginning of animation move around individual bones using bone constraints etc, to  get to a specific pose, and then once in that pose, have the character freeze that pose and then move/rotate the 'frozen' character around without the armature deforming (thus altering the pose?) This would be extremely helpful if possible.

Another way to ask this question, getting more to the purpose of the question: can you rotate an animated armature independently of its constraints? This would allow the constraints to function for the purpose of correctly animating the model's individual parts, but simultaneously rotate the model as if the animation of its parts was a separate entity from the model's rotation as a whole. As if the model's animation was set in stone so you had this animation and now you want to rotate the animation while its playing.

I already tried parenting the armature object to another object and rotating the parent while the armature's animation is playing - however, this altered the poses greatly.

I know it's probably too late but maybe it will help someone in the future. I had the same problem and found out that you can key bone constraints during the animation, so after trying a few options I found out that if you apply Limit Location constraint, check all the boxes without changing their values and set Convert to Local With Parent the bone ignores parent and stays in place as if it was "independent", so the only thing left is to key Influence to 1 whenever you want the constraint to take effect, hope it helps
If there are any issues with language feel free to point it out as my English is far from perfect


Bone angle in python I have an armature found in my .blend file here and I want to know the angles of the joints of my armature in degrees?
I want to know how I can get the angle in degrees through python?

As shown below the bone angle is set to be 0,0,0 around x,y,z although the bone is bent, I don't know why?

Also if I rotated the selected bone 30 degrees around x by selecting the bone pressing R then X then 30, the transform menu angle around x is not 30 as shown below, I don't know why?  I've tried this bpy.data.objects['MyRig'].pose.bones['Bone2'].rotation_euler but it doesn't give the same result as shown in the transform menu.

Test code that equates the angle between the two bones.  It doesn't take into account bone roll.

import bpy
from math import degrees

from bpy import context
arm = context.object

pb1 = arm.pose.bones.get("Bone")
pb2 = arm.pose.bones.get("Bone.001")

v1 = pb1.head - pb1.tail
v2 = pb2.head - pb2.tail

if pb1 and pb2:
    print(degrees(v1.angle(v2)))
else:
    print("Invalid bone name(s)")


Can't Find any of the add-ons on "Testing" for 2.8 I'm trying to find the import-export after effects add-on; the youtube tutorial I was watching said I should find it in the "Testing" section of the "add-on" menu. But Nothing shows up on my "Testing" section

The Testing Add-ons are only shipped with the experimental buildbot releases, see DevTalk. This is even true if you would compile Blender yourself. Go to the Download section at blender.org and scroll down to the area where the experimental versions can be downloaded:

Those builds should contain the Testing Add-ons you are looking for. If you want to use it in your 2.80 stable release too, you can simply extract it from the zip archive, and put it into the scripts/addons_contrib folder of your 2.80 installation, or your Blender user scripts directory:


How to show Point Density data in 3D viewport the same way a smoke simulation is visualised? I'd like to visualize Point Density cycles node in 3D view with python. Something basic - iterate through all vertices or particles and draw a (voxel?) sphere for each of them.
How is smoke visualization done in real time in the viewport? Is that accessible from python?

Smoke visualization in the viewport is based on a 3D texture, which gets mapped on a stack of coplanar planes facing the camera and using alpha-blending. You can access the raw values for density, color, etc. from the smoke domain, but i doubt this is of much use for visualization.

The point density texture works differently. In cycles it is implemented in the same way as smoke, using a 3D volumetric texture. However, it's internal data (you cannot access Cycles' own data anyway) is in the form of a kd-tree. This data structure is not accessible from the texture directly, but you could construct an equivalent tree through the bpy.mathutils.kdtree module, depending on the texture settings.


How can I accurately flatten a surface? I want to flatten some places of a sculpted plane back to the original level, but flatten and smooth don´t work the way I want them to. The grease pencil marks the areas where the sculpt should be flat. What can I do?

In order to flatten faces the surface, select all the faces that you want to flatten and scale 0 to the axis you want it to be flat to. I'm assuming you want to flatten it to the Z axis. In order to do this, press SZ 0 enter.


How to connect two sections of a mesh (sawed off shotgun) I was wondering how I could connect the grip of my shotgun to the body like image one instead of the way i have it where it is just laying on the object.(check picture two)

To join 2 separeted meshes press CTRL + J in Object Mode. If you want to split them press instead CTRL + P. Hope I was useful


Why does this mirror, made using a glossy material, not fully reflect all the incomming light? As shown in the picture, I have this scene where I want to film this girl from her reflection in the mirror, and from the front I have lighted her face up for the shot, but when I render it with camera pointing to her mirror reflection, her face just appeared pale and unlighted. No matter how much I jack up the light strength (even to a ridiculously high value), it just stay this way.

I tried messing with light paths, limited and full global doesn't make any difference. higher or lower sample rate doesn't make difference. Tried several glossy mode, no difference either.

Anyone know why glossy behave like this? And, if I wanted this shot done properly, what can I do?

Make sure Render Settings > Clamp Indirect is set to a suitably high number, or 0 to disable clamping all together.


Trouble understanding the poll function I assume this code defines "i" as the selected objects while the selected objects X location is set to the value from the active object. Right?

def LocX(context):
    for i in bpy.context.selected_objects:
        i.location.x = bpy.context.active_object.location.x

Then there is the following code with the poll function and then the LocX command is being executed. Does this mean it will check each non active object and execute the LocX command onto it? As far as I understand the return {'FINISHED'} is a statement to say that an evaluation is done.

@classmethod
def poll(cls, context):
    return context.active_object != None

def execute(self, context):
    LocX(context)
    return {'FINISHED'}

You can think of the poll function as the bouncer that determines if the operator should be allowed to go on and process something. The return value of the poll function determines if the execute function is called.

The poll in this case checks if the scene has an active_object, if it does then context.active_object will evaluate to True, and therefore be not None or (different syntax same meaning) != None.

The LocX function here doesn't even use the context parameter that was passed. The same could have been written this way:

def LocX():
    for i in bpy.context.selected_objects:
        i.location.x = bpy.context.active_object.location.x

....

@classmethod
def poll(cls, context):
    return context.active_object != None

def execute(self, context):
    LocX()
    return {'FINISHED'}

or this way

def LocX(context):
    for i in context.selected_objects:
        i.location.x = context.active_object.location.x

....

@classmethod
def poll(cls, context):
    return context.active_object != None

def execute(self, context):
    LocX(context)
    return {'FINISHED'}

The for-loop in LocX loops over the collection of selected_objects and for each object therein sets its location.x to be the same as active_object.location.x.

An aside

As a convention we tend to use o or ob or obj for temporary references to objects. i is usually (again this is a convention) used for numbers, integers, indices.


How to get old Mapping and Voronoi nodes into Blender 2.82? I noticed that some nodes changed significantly with Blender 2.81 and 2.82.
Now I can't follow older tutorials, because some have different options than me.

Voronoi Node is totally different
Mapping Node is missing it's maximum / minimum clipping controls

Q: How to get these older nodes back into Blender 2.82?

Good news. Blender will automatically convert these old nodes for you.
Just get an older Blender version and copy/paste them.

Download Blender 2.80 and create your material.
Make sure the nodes are connected (or it won't work).
Copy/paste an object with the  material into Blender 2.82, the nodes will be converted.


UV Maps - is it possible to use the third channel (W?) The Vector of a UV map consists of 3 channels as for any vector in 3D space (whether Generated, Object, World, etc.) and as can be accessed via the Separte XYZ node. The 'U' and 'V' correspond to the 'X' and 'Y' outputs but the 'Z' ('W' in UVW space) is always zero.

Is there any way of assigning values other than zero to that 'W' channel? Obviously not via the standard 'UV unwrap' functions (since those only deal with the surface mesh so W is always zero) - but is this possible via Python?

I have tried using BMesh to assign the UV coordinates as in this answer  but that only assigns uv[0] and uv[1] but doesn't seem to allow uv[2].

I have tried using Vertex Colors as an alternative (as they do allow 3 channels) but those are only to 8-bit precision (ie, 0.0 to 1.0 in 256 distinct steps) and so are far from ideal. The other potential solution would be to store the vertex points in another data structure such as pixels in a 32-bit color image (similar to this answer but storing vertex data rather than object data), referenced via an Image Texture from a vertex ID assigned using Vertex Colors but that's just plain messy - it would be far simpler to be able to use a 3-channel UV map to store 3 channels of float-32bit data.

Any ideas as to how the 3rd UV channel can be assigned or does the code behind the scenes not even store it?

Looking into the Blender source code, the UV processing does not account for the third channel - so this is not possible within a single standard UV map. In order to store an additional (W) channel you could use an additional UV map - eg, 'UVMap1' could hold U and V while the 'U' channel of 'UVMap2' could hold the 'W' channel. However, this method does not provide a simple method of manipulating the UVW map (since the W channel needs to be manipulated separately.

That said, by considering the two UV maps as a 'front view' and a 'side view' of UVW space we can achieve a similar effect - but you need to be careful when manipulating the UV maps to ensure they stay consistent.

To demonstrate, start with your initially unwrapped mesh - a standard UV map :

Copy the UV map (click the '+' alongside the list of UV maps in Edit mode) and rename them to make it clear that one is the UV "front" view and the other is the 'WV' "side" view. 'Select all' (A), scale to zero in the X-axis (SX0Enter) and select everything and move it to the size (GX then drag to the side). You should now have something like this :

Now to move points into the W dimension you can simply select them (or select a whole face) and drag them along the X (U) axis with GX.

To combine the separate 'front' and 'side' UV maps into a UVW map you simply need to separate the channels and re-combine into a single UVW vector :


What do the dashed lines in the outliner mean? Two of my objects are somehow linked to each other in that one of the items are copying itself on the other but I can't figure out how. I don't think its instancing because when I unparent the object and reparent it with another one it doesn't work, and its not using a hair modifier to do it either.
Main question: What relationship are the dashed lines in the outliner indicative of?
I know the green triangle with three dots is a mesh and the solid orange triangle is an object. I pointed an arrow to it in case its hard to see.

Dashed line means the child object isn't present in the same collection.
It probably got left in a different one.
The parent-child relationship still exists, but the 'misplaced child' :( won't be treated as a part of the collection (for instancing, particles or simulations)


Moving mirrored UVs to other quadrant for baking I'm exporting a model into substance painter 2 for baking/texturing, and I'm confused by what people tell me in regards to moving the mirrored UVs out of 0-1 space. I have a vague idea of how this works, but don't actually know how to do it in Blender with any precision. I only know how to move the UVs manually (G) until they visually line up with the texture, but that's hardly ideal.

Is there a better way?

In the UV editor check the Coordinates Normalized property (Properties Panel > Display).

Instead of moving them manually in grab mode, you can enter values in grab, rotate or scale mode. They will appear in the menu bar of the active area (image editor). Minus - and Backspace work, while entering a value in a transformation mode.

To move some faces 100% out of the uv space, press the following: G > -1 > Enter.

With normalized coordinates many similiar transformations can be made, for example flipping or flopping vertices. Just set the cursor coordinates to (0.5, 0.5) and the Rotation/Scaling Pivot to 2D Cursor. Then scale with a value of -1 along x or y. (S > X > -1 > Enter)


How can I fix an unintended hole in my mesh? I've created a hollow object with a Boolean Difference, but it has left a hole in the mesh that I can't seem to fix. There are no vertices on the periphery of the hole itself, and it extends across two faces at right angles to each other.

When I look inside the hollow (as far as I can), I see that there are "shadow" connections between vertices that I would have expected to be unrelated.

I've tried manually reducing the NGON faces to quads and triangles, but it's had no effect on the hole. I've tried Mesh > Cleanup > Fix Holes, also with no effect. I've tried to Beautify the affected faces, again with no effect.

I've attached a link to the file in a state prior to my messing around trying to fix it (approx. 10MB)

Link to the .blend file, approx 10MB

There is no hole in the mesh, but a non-planar n-gon (a polygon with more than 4 vertices) that is ovelapping on top another face.

You should delete it and try to reconnect the remaining geometry using quads...


Clicking "OK" on pop up closes Blender I am new to Blender and just started scripting for our pipeline. I have written a small script which when run sets up the scene unit settings. The script is run from a button in a panel.

To let the user know that the script has been run, a popup appears with a single "OK" button.

Whenever I click the button it closes Blender.

Edit: Blender also closes if I click elsewhere (not on the OK button)

Can anyone tell me why? Or tell me how to write this correctly?

Here's the code:

class SceneSettings(bpy.types.Operator):

  bl_idname = "la.scene_settings"
  bl_label = "Scene Settings Set Up"

  def execute(self, context):
    scene = bpy.context.scene
    scene.unit_settings.system = 'METRIC'
    scene.unit_settings.scale_length = 0.5
    context.window_manager.invoke_props_dialog(self,  width=175, height=50)
    return {'FINISHED'}

Thank you in advance,

Sofia

You seem to misunderstand how operators work. If there's supposed to be a props dialog, it is displayed before the operator execution. More specifically, in the invoke phase:

poll(cls, context) -> invoke(self, context, event) -> execute(self, context)

The poll classmethod of an operator is used to determine if the context allows the operator to run at all. If the context is not suitable (wrong area type, no object selected, ...), it needs to return False. You won't be able to run this operator until there's a valid context (not only from a button, but also spacebar menu and Python console). Operators in panels (=buttons) will be grayed out if polling fails.

What happens next depends on the execution context. If you run an operator from spacebar menu or by a button click, it will be usually INVOKE_DEFAULT and thus call invoke() of the operator. Notable about this method is, that an event object is passed to it. You need to return the result of wm.invoke_props_dialog(self) in invoke() to make the dialog work. It will open the dialog and wait for user input. If the user clicks outside the dialog, the operator will be aborted. If he/she clicks on OK, execute() will be called.

The execute() method of an operator contains the actual code of the operation. It is immediately executed if the execution context is DEFAULT_EXECUTE, which is the case for scripts and the Python console by default. There is usually no point in invoking the operator to get user input prior to the actual operation, and it's sometimes not even possible because of an incorrect context (an invocation from the Python console would run invoke() in the Python console, but a 3D View might be required). You would need to pass custom context along the execution context, like this:

bpy.ops.your.operator({'area': my_area}, 'INVOKE_DEFAULT')

Your operator does not define invoke(), therefore execute() is called immediately. The scene parameters are changed, but then you call the props dialog. It can't be used here and does crash for that reason. It is not supported to display a dialog after an action (operators supporting undo can display something in the redo panel, but that's about it).

class SceneSettings(bpy.types.Operator):

    bl_idname = "wm.scene_settings"
    bl_label = "Scene Settings Set Up"

    def invoke(self, context, event):
        wm = context.window_manager
        return wm.invoke_props_dialog(self, width=175, height=50)

    def execute(self, context):
        scene = context.scene
        scene.unit_settings.system = 'METRIC'
        scene.unit_settings.scale_length = 0.5
        return {'FINISHED'}

A more appropriate way to inform the user is to use self.report():

import bpy

class SceneSettings(bpy.types.Operator):

    bl_idname = "wm.scene_settings"
    bl_label = "Scene Settings Set Up"

    def execute(self, context):
        scene = context.scene
        scene.unit_settings.system = 'METRIC'
        scene.unit_settings.scale_length = 0.5
        self.report({'INFO'}, "Applied scene settings.")
        return {'FINISHED'}

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

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

if __name__ == "__main__":
    register()

Run this code in the Text Editor, then search for the operator in the 3D View spacebar menu.


2.79 vs. 2.8 F6 key to recall menu When I add a new shape a context window shows up with some useful settings to the new object, but as soon as I move or pan, or even accidentally, such additional menu disappears.

In the 2.79 Blender I used F6 key to recall it.
How about the new release?

The shortcut is F9 or you can access it through Edit > Adjust Last Operation.

Quoting from the Manual:

After an operation is complete you can tweak the parameters of the operation afterwards. In editors that support it, there is a “head-up display” panel in the bottom left based on the last performed operation; dependent on mode and context. Alternatively, you can create a pop-up with F9 which does the same thing.


Mesh in not straight any more, when I render it becomes rounded Trying to make a simple cylinder

It looks fine in the object view, but then when I render it turns out weird, like this:

What do I do?

There are two settings for subdivision in the subsurf modifier (and other modifiers as well)

View determines the number of subdivisions for the viewport.

Render controls how many subdivisions it will have when you render.

It is designed that way so that the computer is not bogged with unnecessary computations while you work on the scene, and is more responsive while modeling, and then when you want to render you can have a smoother model.

Also, modifiers have switches that might be toggled for viewing and rendering. It is possible that one of the modifiers is disabled for viewing but is enabled for rendering.

The Camera icon enables or disables rendering using the modifier.

The Eye icon toggles visibility on the 3D viewport.


How do you lock the rotation of a bone in an IK chain? How can you make an IK chain of bones where one of the bones does not rotate relative to it's parent bone but is still part of the IK chain?

Specific example: I have this simple arm rig with IK that I want to split the forearm so the wrist can rotate properly...

I tried putting the IK constraint on the 2nd forearm bone and making the IK chain 3, but the two forearm bones bend. How do I make them not bend while still having the arm move normally?

How do you keep those locked? Again, this is a pretty simple IK setup otherwise, until I wanted to split the wrist/forearm. Thanks for any help!

You need to use the IK Limit rotation found as shown below:


SubSurf modifier does not fill corner The boundary edges of this tape consist of sharp edges (crease = 1), the interior edges are soft (crease = 0). Nevertheless, the SubSurf modifier does not fill up all the way to the corner. How come?

I found out why myself. The long edge that starts from the corner (yellow line) isn't a sharp edge. When I changed its crease to 1, the corner filled up nicely ...


Creating a transparency mask using a texture and blending with shaders I want to give my ship's wings a kind of glitched holographic effect using a texture. I'm struggling with making a mask with a texture and making it so that the texture only affects,

The blue part of the wings
Only affects the edges.

I've tried just creating a simple gradient transparency using a color ramp with mapping+coordinates, but I think since the blue and white stars are separate shaders connected to a mix node with a color ramp controlling the factor it's not giving me the results I want. I'm not sure how to go about this though?

Here's how the wings look now and a concept of what I have in mind.

And here are my nodes

I think I can point you in the right direction.

You need to define a wave texture and apply it along a gradient, so we'll need a wave texture node, and if you use a separate XYZ node you should be able to find a direction that gives you the gradient you need.  For this object it's the Z axis.

I'm going to use a Color Ramp to invert the Z gradient and give us a little more control if we choose to exercise it, a Math node to bump up the value, and then subtract out the wave texture.  I've clamped the last operation, but maybe it's not necessary.

If we use this map as the factor of a mix shader between the blue emission and a transparent BSDF, we can assemble the rest of your shader behind it and we get very close to your desired effect.

From here I think you can find something you like.  The way I chose to do this was to animate a 4d noise texture mixed into the coordinate space, and then move the minkowski voronoi texture along the Z axis.


What could disable keyframes? I have a situation where selected keyframes can't be deleted what could cause this?

.blend

You have set your keyframes to be 'Protected'. Click the padlock icon next to the 'Rotation' channel to unlock the keyframes so they can be edited.


How can I make a custom fbx exporter for unity? I want to export fbx for unity based on manual way in this video I know there is an option as !!EXPERIMENTAL!!, I don't want to use it because sometimes it doesn't work.

Manual Way
manual way works fine I just want to do manual way by code.
because I have to repeat these steps on every 3d models!!!
suppose we have a fish model and we want to export it to untiy

1.Manually rotate the object by -90 degree around X-axis
(if you don't see this panel - press N key)

2.press Ctrl + A and Apply => Rotation

3.and set X rotation to 90 degrees
(do not apply this time)

you can make steps automatic
1.rotate the object by -90 degree around X-axis
obj.rotation_euler = (math.radians(-90),0,0)

2.press Ctrl + A and Apply => Rotation
bpy.ops.object.transform_apply(location=False, rotation=True, scale=False)

3.and set X rotation to 90 degrees
(do not apply this time)
obj.rotation_euler = (math.radians(-90),0,0)

also, you can export it by unit scale
bl_info = {
    "name": "Unity Fix",
    "author": "Kamali",
    "version": (1, 0),
    "blender": (2, 80, 0),
    "location": "File > Export > Export For Unity",
    "description": "Fix Pivot ,Location , Rotation , Scale ",
    "warning": "",
    "doc_url": "",
    "category": "",
}

import bpy
import math

def write_some_data(context, filepath):
    bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS', center='MEDIAN')
    obj= context.object

    # reset location to the center
    obj.location = (0,0,0)

    # reset everything to make sure it won't change
    bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
    # set rotation to -90

    obj.rotation_euler = (math.radians(-90),0,0)
    # reset everything
    bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)

    # rotate 90 degree along x axis
    obj.rotation_euler = (math.radians(90),0,0)

    # apply unit scaling
    bpy.ops.export_scene.fbx(filepath=filepath, use_selection=True,apply_scale_options='FBX_SCALE_UNITS',apply_unit_scale=True)
    return {'FINISHED'}

from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator

class ExportSomeData(Operator, ExportHelper):
    """Export For Unity"""
    bl_idname = "export_test.some_data"
    bl_label = "Export For Unity"

    filename_ext = ".fbx"

    filter_glob: StringProperty(
        default="*.fbx",
        options={'HIDDEN'},
        maxlen=255,
    )

    def execute(self, context):
        return write_some_data(context, self.filepath)

# Only needed if you want to add into a dynamic menu
def menu_func_export(self, context):
    self.layout.operator(ExportSomeData.bl_idname, text="Export For Unity")

def register():
    bpy.utils.register_class(ExportSomeData)
    bpy.types.TOPBAR_MT_file_export.append(menu_func_export)

def unregister():
    bpy.utils.unregister_class(ExportSomeData)
    bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)

if __name__ == "__main__":
    register()


How do I prevent object distortion when applying a curve modifier? This is the profile of the object I'd like to wrap...

Here is the object's profile after being wrapped...

Is it possible to prevent the distortion? The following post here: http://blenderartists.org/forum/showthread.php?293735-Dublicating-an-object-along-a-curve-without-distortion-Array-or-DubliFrames did not affect my object. It seemed very promising, maybe I'm missing something?

Note: I have applied the scale to both my object and curve.

You can use a proxy mesh as the curve object, then use Dupli faces to place an object at each face. This has the added advantage of using instances, which are more memory efficient than the array modifier.

Add a plane and set it up with the curve and array modifiers:

Parent the actual object to the plane (CtrlP).

With the plane selected, enable Faces in Properties > Object > Duplication > Faces.


how to access a rigify armature selector UI? I generated a rig using rigify but I can't seem to find a UI to select the armature i want. I know other VFX setups usually have a 'paper doll' like image with buttons for each part of the character available to animate. Does rigify provide this UI?

There is no such feature as far as I know.
Rigify give you a menu that helps hide/unhide parts of your rig. Look in the N-panel (press "n"). In Item you should see Rig Layers.


How can I easily model an extruded organic shape? I am currently seeking help from the blender community to model this:

I've tried almost every tool (including subsurf) but it doesn't look like it

Can anyone show the steps on how to model that shape? I could be grateful if someone helped me

By the way,the top and "butt" (bottom left on the "sides" image) are supposed to be a little rounded and a little low-poly like (maybe both)

It also needs to be fully 3D,not 2d or flat

You can easily do it with a curve. Press Shift+A > Curve > Circle.

In Edit Mode do something like this:

Then:

Hope that helped you!


Hear timing reference audio from VSE while editing other scenes? (2.8 beta) I'm making an animation using grease pencil, based on a narration track. What I'd like to do:

Import and place the master audio file (narration) as a single sound
strip in the VSE, in Scene0
Create visuals as grease pencil scenes sequenced in the VSE too, from which a final export can be made. Scene1 - Scene50.
I want to use the narration track in the VSE in Scene0 as a timing reference for all visuals in all scenes of the project. e.g. in Scene3 I want a specific action to coincide with a particular word in the narration. In general while working on the action in Scene N I want to hear the relevant part of the narration audio which has been placed in the VSE in Scene0, a different scene.

I have a good handle on 1 and 2, but I'm not sure how to realise 3. Is it possible?

Suggestions for workarounds or alternative approaches are welcome too. Though I'd like to avoid any workaround that involves having to re-render audio files if the duration of any of the grease pencil scenes has to change.

EDIT

In After effects there's a plugin called 'universal audio' that achieves something similar to what I'm looking for in Blender: It provides some buttons that allow you to designate a 'master audio' track, and then from child comps automatically copy in the appropriate section of audio from the master audio track, with in point correctly reflecting its position with regard to how the two comps are related. https://aescripts.com/universal-audio/

EDIT 2

I think that if I make sure I use the Scene name 'Master' for the one containing the VSE and name the narration sound clip 'Narration', then I'd need something like the following script (i'd run this somehow each time I opened one of the scenes to work on). But I'm not clear yet on how to have this accessible via a button or something convenient.

# Run this from a 'child' scene to add narration track with correct timing offset.
# TODO add routine for removing narration track from child scene if it already exists, before re-adding it.

    import bpy

    current_scene = bpy.context.scene
    current_se = current_scene.sequence_editor_create()

    master_se = bpy.data.scenes['Master'].sequence_editor
    narration_sequence = master_se.sequences['Narration']

    timing_ref_sequence = master_se.sequences[current_scene.name]

    if timing_ref_sequence:
      offset = timing_ref_sequence.frame_final_start * -1
      path = narration_sequence.sound.filepath
      current_se.sequences.new_sound('new',path,0,offset)

To have the python script conveniently accessible, we have to embed it into an addon for 2.8.

To activate the addon for this file only, copy the code (at the end of the post) and save it in a file (e.g. adjustNarratorTrack.py). Open it in the script editor in Blender and check the Register checkbox in the header of the script editor. With register enabled, a saved file will be automatically executed once the blend file is loaded, even if you close the script editor.

To run the script, without reloading the blend file, click RunScript.

The script creates a python operator. The operator can be called by

opening the search menu in the 3D View F3 and typing Adjust Narrator
clicking on the menu item, which we created under 3D View ▶ Object ▶ Adjust Narrator Track

Note, that this "addon" is not quite complete yet. Further research should be done as to how scene/sound strips behave, when they are cut off in the sequencer.

In the script

a custom Operator AdjustNarratorTrackOperator is defined. This will be called by Blender when you click on the menu items. It will be also available to python through bpy.ops..
two annotations of the operator are defined: audio_strip_name, cut_scene_name. These are adjustable after the operator has been executed. This is useful if you have changed your naming conventions.

The operator annotations appear in the 3D View after the operator has been executed.
there are two methods:

execute: called by Blender
adjust_audio_reference: a modified version of your script

In adjust_audio_reference the current_scene, audio_strip_name and cut_scene_name are referenced from the operators context.
Various checks are done to ensure, that

the "Master" scene exists
the "Master" scene contains the audio track
the current scene is not the "Master" scene
the current scene is contained as a strip in the "Master" scene
the sound strip is replicated in the current scene if necessary
the offset in timing is applied

In this case we want to use the frame_start property and not the frame_start_final property, since the frame offset to the frame_start_final doesn't reflect on the audio strips position at the start of a scene strip.

import bpy

class AdjustNarratorTrackOperator(bpy.types.Operator):
    """Adjusts the narrator track"""
    bl_idname = "object.adjust_narrator_track"
    bl_label = "Adjust Narrator Track"

    audio_strip_name: bpy.props.StringProperty(default='Narration')
    cut_scene_name: bpy.props.StringProperty(default='Master')

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

    def execute(self, context):
        try:
            self.adjust_audio_reference()
        except Exception as e:
            self.report({'ERROR'}, str(e))
            return {'CANCELLED'}

        return {'FINISHED'}

    def adjust_audio_reference(self):
        current_scene = bpy.context.scene
        audio_strip_name = self.audio_strip_name
        cut_scene_name = self.cut_scene_name

        # check if the master scene exists and contains the audio_strip
        master_scn = bpy.data.scenes.get(cut_scene_name)
        if master_scn == None or master_scn.sequence_editor == None:
            raise Exception('Master scene not defined.')
        master_se = master_scn.sequence_editor
        ref_audio_strip = master_se.sequences.get(audio_strip_name)
        print(ref_audio_strip)
        if ref_audio_strip == None or ref_audio_strip.type != 'SOUND':
            raise Exception('Audio strip not found.')

        # check if the current scene is embedded in the master scene
        timing_ref_seqs = [s for s in master_se.sequences if s.type == 'SCENE' and s.scene == current_scene]
        if len(timing_ref_seqs) == 0:
            raise Exception('Current scene is not contained in the Master scene.')

        ref_scn_strip = timing_ref_seqs[0]

        current_se = current_scene.sequence_editor
        if current_se == None:
            current_se = current_scene.sequence_editor_create()
        current_audio_strip = current_se.sequences.get(ref_audio_strip.name)
        if current_audio_strip != None:
            if current_audio_strip.type != 'SOUND':
                current_audio_strip.name = current_audio_strip.name + '_notSound'
                current_audio_strip = None
        if current_audio_strip == None:
            path = ref_audio_strip.sound.filepath
            current_audio_strip = current_se.sequences.new_sound(ref_audio_strip.name,path,0,0)

        timing_difference = ref_audio_strip.frame_start - ref_scn_strip.frame_start + current_scene.frame_start

        current_audio_strip.frame_start = timing_difference
        current_audio_strip.frame_final_start = timing_difference

def menu_func(self, context):
    self.layout.operator(AdjustNarratorTrackOperator.bl_idname)

def register():
    bpy.utils.register_class(AdjustNarratorTrackOperator)
    bpy.types.VIEW3D_MT_object.append(menu_func)

def unregister():
    bpy.utils.unregister_class(AdjustNarratorTrackOperator)
    bpy.types.VIEW3D_MT_object.remove(menu_func)

if __name__ == "__main__":
    register()


Why does removing the dot from bl_idname break my addon? I've made an export script, sorry to say much of it is copy paste coding.

It was working fine, but now:

There should be an extra menuitem 'Waveller' -- it was there and it was working, but it has just disappeared!  ARGH!

I must have done a nono while refactoring the code.

I have tried removing and adding in:

What is going wrong?

Here is my code:

bl_info = {
    "name":         "Waveller",
    "author":       "π",
    "version":      (0, 0),
    "blender":      (2, 6, 2),
    "location":     "File > Import-Export > Waveller",
    "description":  "Export Verts and Faces in Waveller Format",
    "warning":      "",
    "wiki_url":     "http://www.waveller.com",
    "category":     "Import-Export"
}

if "bpy" in locals():
    import imp
    if "export_waveller" in locals():
        imp.reload( export_waveller )
else:
    import bpy

from bpy.props import StringProperty, BoolProperty

class WavellerExporter( bpy.types.Operator ):
    '''Save in Waveller format'''
    bl_idname = "export_waveller.vert"
    bl_label = "Export Waveller"

    filepath = StringProperty(
            subtype='FILE_PATH',
            )

    check_existing = BoolProperty(
            name = "Check Existing",
            description = "Check and warn on overwriting existing files",
            default = True,
            options = { 'HIDDEN' },
            )

    def execute( self, context ):
        from . import export_waveller
        export_waveller.export_all( self.filepath )

        return {'FINISHED'}

    def invoke( self, context, event ):
        if not self.filepath:
            self.filepath = bpy.data.filepath
        # bpy.path.ensure_ext(bpy.data.filepath, "")
        wm = context.window_manager
        wm.fileselect_add( self )
        return { 'RUNNING_MODAL' }

def menu_export( self, context ):
    self.layout.operator(
                         WavellerExporter.bl_idname,
                         text = "Waveller"
                         )

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

    bpy.types.INFO_MT_file_export.append( menu_export )

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

    bpy.types.INFO_MT_file_export.remove( menu_export )

if __name__ == "__main__":
    register()

I did do a bit of fiddling, I remember changing:

bl_idname = "export_waveller.vert"

to

bl_idname = "export_waveller"

(changing it back doesn't fix this)

Well if anyone can put me right I'm very grateful. Also, corrections to any hideousnesses you see lurking in the code are most welcome!

It was that line!

Can anyone tell me why I'm not allowed to change bl_idname from "export_waveller.vert" to "export_waveller"?

My only guess is that this string is used as a token somewhere, and changing it creates some disparity.

I don't see why resetting factory settings doesn't cure this...

Anyone?


Blender 2.8 - How to create new view ports / windows? In blender 2.7 you could easily create new windows and configure your workspace as you wished, by draggin the symbols seen in the screenshot below:

How does it work in blender 2.8? Was this great feature removed??

It still works the way it always did. But for some reason, the "triangle in the corner" icon has been removed. If you hover your mouse cursor over the corner of a window, you will see it change from a pointer to a kind of plus sign. When this change happens, clicking and dragging will create your new window in the expected way.


Add button to TOPBAR_MT_render I want to add a button to the “TOPBAR_MT_render” menu (basically the menu in the top bar were you click to render.) The button should look like the Lock Interface one, so it should have a checkbox.

Would be nice if you could help me with this.

Append or Prepend a draw method to menu class.

Very closely related How to add a checkbox to a pie menu?

import bpy

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

    layout.prop(render, "use_lock_interface")

def register():
    bpy.types.TOPBAR_MT_render.append(draw)

# make your unregister and remove draw
if __name__ == "__main__":
    register()

TIP Turn on developer extras in user preferences and can right click to  view source (Edit Source, as it opens in text editor.) of most UI elements.

Add toggle hotkey to custom checkbox


Might it be possible to use scripts in blender to do what Mandelbulber does? This would be a sort of extension of this question: Fractals in Blender?.

I was playing around in unity and found a tutorial for making fractal objects via C# scripts. I used the script from the tutorial and set up a scene to port to android and discovered the frame rate when looking at the fractal object was extremely low due to the vert count and number of individual objects. As I was unable to figure out how to merge the meshes properly in unity I figured I'd turn to blender with python scripts since I figured I could do the same thing in python and have seen how simple it is to copy and merge meshes via the array modifier.

Long story short, after trying to find scripting tutorials for blender 2.7 and getting lost in the API I started to wonder if what I'm trying to do is even possible. What is my end goal, you ask? I want to make a fractal landscape similar to what you might generate in mandelbulber, but finite in each direction. Fake 'infinite depth' is also unnecessary, as I'm fine with simply stopping recursion at a predefined depth. I want this landscape to be a single mesh that I can export to unity.

Sure you can generate such fractals at finite poly resolution.

You just need to figure out the fractal math and positions of vertices. Then you can build such mesh in python with the BMesh module.


Lightmap Pack is non-uniformly scaling my geometry? I selected all my objects, then I did a "Lightmap Pack". Initially, it seemed like everything went ok. However, when I look closer, it seems to have stretched some the UVs.

The shape of the selected UV on the left, is not a match for its corresponding face on the right. Why couldn't it preserve the shape?

Update #1: I did more looking around, and noticed that the smallest faces seem to map correctly; notice how this tiny square face (from the same object as the big one) actually did the mapping correctly. I also (for sake of trying) did an "Apply Scale" to all my objects, it seems to have made no difference (even after re-doing the lightmap pack).

Update #2: Max'ing the "quality" setting for Lightmap Pack didn't seem to fix it, or even make it any less distorted.

The purpose of Lightmap Pack command is to utilize as much UV space as possible by storing each face (individually) in the UV space bounds.

I must admit that I can't tell you how exactly the algorithm works, but if you consider two similar objects that differ only from the lenght of a face (8.0 vs 8.1) you'll see different results of the lightmap pack command.

In the shortest parallelogram, each face is not "enough" different from the average face size of the object, so they are all stored with the same size in the UV. The proportion are not preserved. They are stretched to fill the boundaries.

In longest parallelogram, Blender sees instead that some faces are much longer than other (they just get over the alghorithm thereshold), so it is aware that they should need more space.

Notice that also in this case, despite what could it seem, proportions are not mantained. The Face is 2:8.1, while the UV is more 2:4. That's because Blender look for the best way to fill all the UV space, regardless proportion. This is a uv layout for Baking textures efficently.

If you are interested in keeping the proportions, Lightmap pack is not the right UV unwrapping method.

In the brought example I would separate each face by extruding them individually by a 0 factor, than Crtl+i to invert seelction and Canc to delete unwanted faces.

Than a simple Unwrap or Smart unwrap, should pack all the faces preserving their proportions in the UV map.


How do I make a mirrored part of a mesh merge with the one I modeled I created this head by mirroring the right side.  I didn't know how to merge the mesh but when I checked the Merge option in the Mirror Modifier, as I was prompted when I typed the title, I was able to grab all of the mesh.  Then I could mark the seams for  the UV map.  When I unwrapped the mesh as a UV map, it appears that only half of the mesh unwrapped.  I think I made the mirrored portion of the mesh of the head a part of the whole so what did I miss, and how can I fix the unwrapped mesh?

If you apply the mirror modifier after UV unwrapping, you have two identical UV overlapped.
Select linked faces (mouse over the UV, then press L) and move the UV to reveal the other UV.

To mirror the UV horizontally, select the U option before applying the modifier


beginner using v2.81 basic script format error please help (creating poses) compile error Im ultra new to blender and am using v2.81 to create some poses for a game mod.

Can someone please correct this script below so that it will compile in v2.81 as it wont compile based on the format..and i have no clue after reading up for hours about the known script error in v2.8 i just cant get my head around the issue. i do not understand scripting or coding very well despite trying to fix this all night. Also i cannot understand the blender versions below 2.8  for creating poses seem so clunky compared to the newer version,no camera navigation without pain!!!no easy way of moving bones without a nightmare .. otherwise my script would compile in earlier versions but i just cant create the poses anywhere near as accurately or as fast as in v2.81

This is where the compile error is in the log:

SelectedObject = bpy.context.scene.objects.active
Armatura = SelectedObject.data

Appreciate any help Thanks

Use bpy.context.object instead of bpy.context.scene.objects.active that does not work in 2.8x.

Works fine in 2.81:


Using Blender with processing or Max MSP interactive programmes We design installation using a combination of Max MSP and processing. I am wondering if you can intergrate animations which are controlled from live input algorithms. We already have live movement that can control sounds and as we get better at Blender we wonder if we could do the same with animations we create in Blender.

Basically you could use the game engine to perform real time updates using input from another system.
You could trigger playback of pre-recorded actions using an Action Actuator Logic Brick by a script that does the communication with the external component.

Related:

Blender armature control in real time?


Make character and plane interact in pose mode? https://drive.google.com/file/d/1fOs4cfkD9Pmj4wb4plDLNib-LdbA9WnN/view?usp=sharing

Attached is my file. I have my rigid body constraints set up so that when I press play it sort of... kind of interacts with it? The character clips through the plane until the calve legs, then collides, and that's one problem.

But what I want to figure out is, how do I make my character collide with the plane in pose mode? I'm trying to make a running cycle and want the feet to stop and bend at it when they touch instead of clipping through. Any help?

In pose mode you manually position a bone at a certain position at a specific frame. With physics simulations like rigid body, the simulation positions items over time.

You cannot use physics to control a bone while you are manually positioning it in pose mode. You need to visually position the bones while creating keyframes, this is often best done from the camera view to ensure the desired visual result.

You can bake a physics simulation into keyframes and then manually adjust some of the generated keyframes.

You cannot mix keyframe animation and simulations at the same time, you use one or the other. Some physics can be turned on and off at specific keyframes allowing you to use both at different times during the animation. This is commonly used to animate an initial velocity of an item at the time the physics begins.


Bones, weight painting and very weird deformations I'd just like to be able to assign an object to a bone and have it be 100% controlled by that bone.  Surely this is possible without the weight painting business. Its so easy to miss a vertex or two somewhere, and then I end up with these long stretchy deformities when I set a pose.
Thanks.

Enter edit mode for the armature and select the bone you want to be the parent. Go back to object mode.

Select the object to be the child, then shift select the armature.

Press CtrlP and select Bone. You can't choose which bone here, it will be set to the bone that was selected when the armature was in edit mode.

You can verify the settings under the Object Properties - Relations

You can choose to set these properties manually but you may need to re-position the object afterwards.


How to prevent particles from spawning on its emiter's edges? For example here you can see the highlighted particles are spawned on the edges of the emitter.
How to prevent this ?

Let's say you have a plane object,

then a border to restrict the particles can be added by pressing I once to inset the face(s), adjust the border as to how big you need it. Then press I once more and add another border close to the first one. This is needed for the weighting to have some space to change from 1 to 0, as otherwise a single face loop border would have a gradient from inner(1) to outer(0) resulting in particles still spawning there.

With the inner face(s) selected, switch to weight paint mode and make sure the Weight is set to 1:

Now with the mouse over the 3D-Viewport, press Shift+K to set the inner face(s) to a value of 1.

By default the weight is 0, so the outer border should look like in the picture above.
With the weighting done, all you need to do is go in the ParticleSettings under Vertex Groups and select the (with the weight painting) created Group in the Density field.

Happy Blending


How do I make the object I set as a dynamic paint brush invisible in the render? I am trying to animate this scene where I want a wave effect with a Dynamic paint system. The Plane is acting as my canvas while and a (hidden) sphere is acting as my brush.

However when I render it the Sphere is still visible.

Is there a way to keep the sphere hidden in the final rendered animation? Why does the wave also do not render in the final rendered versions?

Open an outliner.

Enabeling that option allows you to hide objects from render by clicking the camera. IDK why this isn't enabled by default anymore. If you only want to hide it from the camera so it still casts shadows etc. you can go the object settings under visibility uncheck camera.


How can I make and animate a laser beam looking like an HOURGLASS in blender? I need to make a laser beam that when it goes out from its source it looks like an hourglass. The strongest density of the beam is where the beam is more thin (basically where the sand clock is thinner - the middle part).

Is there a way to do it with particles? If not show me another way, no problem :)

Thanks in advance!

I may have accidentally made what you wanted (maybe). Please correct me if something isn't right:

So I emit particles from the vertices of a circular ngon (so that the particles collide immediately with the edges of the tube).
And the tube is a collider that has a little bit of stickiness, friction and dampening that luckily seems to make the particles to flow nicely outwards as well.
That's about it.

To do this in Blender 2.79:

Add particle system to the green 'emitter' object. Put Lifetime to 250 and Emit from 'Verts':

For the 'hourglass' object, put collision and Stickiness: 2 - Particle Damping: 0.2 - Particle Friction: 0.2:

You can also go to the particle settings and in Render panel set the particles to be the 'Icosphere' object:

Here are the objects as .blend:


Curve Modifier Gives Unexpected Effects I am having problems understating the curve modifier. I can usually get it to do what I want, but only after a lot of trial and error and often I plain do not understand why it seems to work in the way it does.

I attach a blend file. I am trying to make a bridge by having a segment of the bridge, a curve for it to follow and using the array and curve modifiers replicate it along the path. I have applied scale and rotation, and made sure both the bridge segment and the curve share an origin. Still it seems to give bizarre results.

In the attached file, when I turn on the curve modifier, the bridge segment flips on its side. I am completely stumped by this. Why is this happening?

Example Blend File

The tilt of individual (or all) points on a curve can be adjusted by highlighting the relevant control points and pressing Ctrl+T followed by making the adjustment.

When you are using another object with a curve modifier this will adjust the orientation of that object as it follows the curve.


Scripted scene building - where to begin? First off, I'm very much a novice Blender user. I use Blender mainly for building mock-ups of PCBs that I design for customers to see how the designs will look when finished. (Yes, most professional PCB packages will do this for you, but I am an open-source nut and my chosen PCB design package doesn't, so I choose Blender. Also the results from Blender are far superior to what PCB packages make).

However, putting together a new PCB design in Blender is a time consuming thing, and I would love to automate it.

I have plenty of component models in blender files, all nicely textured and looking all spangly. Making the actual PCB substrate is simple enough - import an SVG of the outline and texture it with PNG exports from the PCB package. That side of things is all fine and I am happy doing that manually.

What I'd like to automate, though, is the importing of all the components from their respective blender files and positioning them within the scene. I have a CSV file with the ID, name, and location of each component, and currently I manually clone each component from a base model and type in the location details into Blender. Which works fine, it's just very slow.

Here's an example of the end result (I am still laying out some of the components on this one):

So I know that Blender can do fancy things with plugins written in Python. I am not a Python programmer, I do 99% of my programming in C and C++. That's not to say I can't program in Python, just that I don't, and as a result I don't know the finer points of Python crafting, but that will come as I learn.

As a result I'd like to write a plugin which can load this CSV file (specified at run time by me - preferably with a file browser window), parse it for components, find the right blender files (or the right models in a single large blender file, I am not fussy which), clone the models along with their textures, etc, and set the location of each one.

First off: is this something that is possible in Python in Blender, or am I asking too much of it with the automated file loading / model finding, etc?

Secondly: Where on earth would I start writing a plugin like this? I have absolutely no knowledge of how the internals of Blender work (which really helps things ;) ). Yes, I have the blender python API reference, but to use that I really need some idea of what I am looking for in it.

So I could do with a couple of things:

Some pointers to friendly plugin writing tutorials to kick-start my effort,
A clue as to which parts of the API would be of most interest to a plugin like this,
What would be the best way to store the component models:

A single file with all components in it, each named properly,
A file per component named after the component with the component named properly, or
A file per component named after the component with the component having a common name (such as "component")

Procedurally, what steps would need to occur for the plugin to do what I need of it (how I would put the different concepts from the API together to make it work).

This might get you started

BlendData.libraries
csv

import bpy
import csv

file_csv = ".../layout.csv"
file_components = ".../components.blend"

with open(file_csv, newline='') as fobj:
    reader = csv.reader(fobj)
    layout_table = list(reader)

required = set(col[1] for col in layout_table)

with bpy.data.libraries.load(file_components, link=True) as (data_from, data_to):
    available = set(data_from.meshes)
    missing = required - available
    data_to.meshes = list(required & available)

if missing:
    txt = bpy.data.texts.new("missing_components.txt")
    for comp in missing:
        txt.write(comp + "\n")

objects_data  = bpy.data.objects
objects_scene = bpy.context.scene.objects
name_to_index = {mesh.name: index for index, mesh in enumerate(data_to.meshes)}

def create_dupli(id, name, location):
    try:
        mesh = data_to.meshes[name_to_index[name]]
    except KeyError:
        return

    dupli = objects_data.new(id, mesh)
    dupli.location = location
    objects_scene.link(dupli)

for id, name, x, y, z in layout_table:
    loc = tuple(float(val) for val in (x, y, z))
    create_dupli(id, name, loc)


How to overide custom node operator variables in the execution Related to the question here I wanted now to use the export custom node from the same addon. Considering that the invoke() function calls the file browser for setting the path the filename I would like to call the execution() function directly but by overriding the self.filepath variable. I've tried to follow the same trick as in the linked question, meaning:
override = {'node': bpy.data.node_groups['<node_group_name>'].nodes['VI CSV Export'], 'self.filepath':'<path_to_save_file>.csv'}
bpy.ops.node.csvexport(override, 'EXEC_DEFAULT')

But this complaints with the following error:
Error: Traceback (most recent call last):
  File "/ttsesm/blender-2.83.6-linux64/2.83/scripts/addons/vi-suite06/vi_operators.py", line 2200, in execute
    node = self.node
  File "/ttsesm/blender-2.83.6-linux64/2.83/scripts/modules/bpy_types.py", line 713, in __getattribute__
    return super().__getattribute__(attr)
AttributeError: 'NODE_OT_CSV' object has no attribute 'node'

location: /ttsesm/blender-2.83.6-linux64/2.83/scripts/modules/bpy/ops.py:199

Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
  File "/ttsesm/blender-2.83.6-linux64/2.83/scripts/modules/bpy/ops.py", line 199, in __call__
    ret = op_call(self.idname_py(), C_dict, kw, C_exec, C_undo)
RuntimeError: Error: Traceback (most recent call last):
  File "/ttsesm/blender-2.83.6-linux64/2.83/scripts/addons/vi-suite06/vi_operators.py", line 2200, in execute
    node = self.node
  File "/ttsesm/blender-2.83.6-linux64/2.83/scripts/modules/bpy_types.py", line 713, in __getattribute__
    return super().__getattribute__(attr)
AttributeError: 'NODE_OT_CSV' object has no attribute 'node'

location: /ttsesm/blender-2.83.6-linux64/2.83/scripts/modules/bpy/ops.py:199

My questions are why the node = self.node cannot be overridden and whether the way that I am overriding the self.filepath variable is the correct one.

self.node is set in invoke.
THe operator is designed to be invoked by pressing its button displayed on its node.
The operator defines
self.node = context.node

in its invoke method, and uses self.node in its execute method, and will hence not work unless invoked.
bpy.ops.foo.bar(override, 'INVOKE_DEFAULT', filepath=somefilepath)

IMO the simple fix is to edit the operator to use context.node as the node in place of self.node by placing
self.node = context.node

in the execute method also.
Alternatively return self.execute(context) from the invoke method if the value passed to self.filepath is a valid filepath and use
bpy.ops.foo.bar(override, 'INVOKE_DEFAULT', filepath=somefilepath)

to ensure it is invoked and node is set.
A note on overriding.
What you are passing in the override dictionary are context members, eg
override = {"foo" : "bar"}

then if passed as an override to  the operator
context.foo == "bar"

is true within the operator.
The filepath is a property of the operator, not the context and is hence not going to do diddly squat if passed as part of the override.  The operator (self) and context are not the same.  Pass it to the operator as a keyword variable.
Fork it.
Finally, fork and make the changes, or suggest / request  changes to the maintainer of the addon, so that it can be executed directly, or to find out if there are reasons why it cannot.


Add contrast or saturation to render? When I render something, as image or video, is there any option to change the contrast or saturation of the image without having to use any external software?
Thanks in advance.

The compositor has a whole section of nodes for image control.

To use the compositor open the Node Editor window and set it to compositing mode:

There are nodes for brightness contrast and hue/saturation:

On top of that there are nodes for levels, color correction, curves and other ways to affect a rendered image.

Quoting from the wiki:

These nodes play with the colors in the image. They adjust the image's color intensity, adjust contrast and intensity, and, most importantly, mix two images together by color, transparency, or distance.

For an in depth explanation on each one of those nodes refer to Manual


add custom texts(labels or annotations) which are always upright to user in view port I would like to put some user defined texts(labels) besides bodies as annotations, those texts(labels) are always perpendicular to user, which means whenever I rotate or scale the object, those text's size are always the same and there orientation are always upright to the user, just like the "x,y,z" in the left bottom corner of the 3D view, see the screen shot below(pointed by red arrows).

If you use the "Ruler/Protractor" tool, you will see same kinds of texts(lables) can be added by those tools.

Any ideas about this kind of text, I need such kind of text to demonstrate the models when teaching. Thanks.

EDIT: Looks like this post https://blender.stackexchange.com/a/1606/2722 give me some ways to workaround this issue, but I definitely need a clean way.

EDIT2: Now I can correctly display a text attachment to an object in the view port. But the text is not user defined, I means I can show a matrix or a object's name, but is it possible to show a customized annotation text strings?

Labels in Render
An easy (but limited) way would be to parent the text labels to the camera.

Select text label RMB
Add camera to selection Shift-RMB
Set camara to parent Ctrl-P

After that movement of the camera or transforming the objects in the scene would no longer influence the appearance of the label.
Example rotating object and moving camera:

Labels in Viewport
If you want to draw labels in the view port you find all you need in Adhi's display_matrix.py script.


Normal map bake creases on render My pebble has small bumps where creases are if the shading is flat.

If it is on smooth shading, it has dips.

Edit

I figured out its only happening when they are on different shading modes (smooth and flat)

Now it only shows very visible creases when I back away from it.

Close:

Far:

I really hope someone can help me, thanks again!

Edit

System settings:

Save texture image then disable "Use Alpha" at image properties.