text:
How can I transform my coffee cup into a torus as seen on wikipidea?
I'm animating the coffee mug torus homeomorphism.

I want my animation to match this gif as closely as possible.
The gif above, along with the POV-ray code used to create it, can be found here:https://en.wikipedia.org/wiki/File:Mug_and_Torus_morph.gif.
I'm working with a relatively low poly mesh for now and here is what I have created:

The first part of the Wikipedia animation where the base of the cup rises is easy  to make, so I'm excluding that part of the animation for this post. I just need help on the main transformation part.
To create this, I wrote a python script that sends the points of the cup to the closest point on the torus. The pseudocode of the python code is roughly as follows:
# for each vertex of the mug,
    # keyframe the vertex coordinate at initial frame
    # find the angle of the vertex relative to the center of the torus
    # find the central point of the torus of which this angle belongs to (this new central point is a point along the major radius ring)
    # solve for where the line through the vertex and central point intersects the torus (there are two points of intersection)
    # set vertex coordinate to value of intersection that's closest to the vertex
    # keyframe vertex coordinate at final frame

Here is the actual code:
import bpy
from math import *
from mathutils import *

mug = bpy.context.scene.objects["MorphingMug"]
verts = mug.data.vertices

#initial handle torus and target torus have a major radius of:
bigR = .5
#target torus has radius of:
r = .25
#center of both initial handle torus and target torus has x value of:
originX = .8

#for each vertex of the mug
for v in verts:
    #keyframe vertex at framei
    v.keyframe_insert(data_path = "co", frame = 1)

    #get x, y, and z values of vertex
    x = v.co.x
    y = v.co.y
    z = v.co.z

    #difference vector between vertex and (center of torus = [originX, 0, 0])
    d = Vector([x - originX, y, z])

    #find the angle in the xz-plane of this difference vector
    if v.co == Vector([originX, 0, 0]):
        theta = pi
    elif d.x == 0 and d.z > 0:
        theta = pi/2
    elif d.x == 0 and d.z < 0:
        theta = -pi/2
    elif d.x < 0:
        theta = pi + atan(d.z/d.x)
    else:
        theta = atan(d.z/d.x)

    #find the central point of the target torus of which this angle belongs to
    c_1 = bigR * cos(theta) + originX
    c_3 = bigR * sin(theta)

    #line parameterization values of where the line through vertex and central point intersect target torus
    t1 = -r/sqrt(c_1**2 - 2*c_1*x + c_3**2 - 2*c_3*z + x**2 + y**2 + z**2) + 1
    t2 = r/sqrt(c_1**2 - 2*c_1*x + c_3**2 - 2*c_3*z + x**2 + y**2 + z**2) + 1

    #first value of intersection
    v1 = x + t1*(c_1 - x)
    v2 = y + t1*(c_2 - y)
    v3 = z + t1*(c_3 - z)

    vec1 = [v1, v2, v3]

    #second value of intersection
    v1 = x + t2*(c_1 - x)
    v2 = y + t2*(-y)
    v3 = z + t2*(c_3 - z)

    vec2 = [v1, v2, v3]

    #difference of these intersection values and vertex
    diff1 = Vector(vec1) - v.co
    diff2 = Vector(vec2) - v.co

    #choose the value that's closest to vertex
    if diff1.magnitude > diff2.magnitude:
        vec = vec2
    else:
        vec = vec1

    #set vertex equal to closest intersection
    v.co = vec

    #keyframe at final position
    v.keyframe_insert(data_path = "co", frame = 120)

There are clearly some issues with my animation. I don't think I'm seeing the math to this projection clearly. I do see that the top face up the cup should be sent to the uppermost point of the torus and same for the bottom face and the lowermost point. I also see the rightmost points of the non-handle part of the cup that are also at y = 0 are mapped upwards and downwards, which is incorrect, except for the point [.8, 0, 0], which I manually mapped to the correct position.
Maybe I need to pick different projective origin points based on the vertex position? Maybe I should split the mesh into vertex groups to make it more of a piecewise transformation? Maybe I need to reposition the non-handle part of the mug slightly more in the +x direction? Any help would be greatly appreciated. Thanks.
my file can be downloaded here:

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

Animate vertices with shape keys

1) Making mug
You can make mugs by running my script
import bpy, bmesh, math

def select_vert(verts, i):
    bpy.ops.object.mode_set(mode = 'OBJECT')
    verts[i].select = True
    bpy.ops.object.mode_set(mode = 'EDIT')

def create_mug():
    bpy.ops.mesh.primitive_circle_add(vertices=6, fill_type='TRIFAN', calc_uvs=True, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
    cup = bpy.context.object
    md = cup.modifiers.new(type = "SUBSURF", name = "sub")
    md.levels = 2
    bpy.ops.object.modifier_apply(modifier="sub")
    bpy.ops.object.mode_set(mode = 'EDIT')
    for r in range(10):
        bpy.ops.mesh.extrude_region_move(MESH_OT_extrude_region={"use_normal_flip":False, "use_dissolve_ortho_edges":False, "mirror":False}, TRANSFORM_OT_translate={"value":(0, 0, 0.2), "orient_type":'NORMAL', "orient_matrix":((-0.290283, 0.956941, -4.25348e-09), (-0.956941, -0.290283, -1.40219e-08), (-1.46529e-08, 0, 1)), "orient_matrix_type":'NORMAL', "constraint_axis":(False, False, True), "mirror":False, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "cursor_transform":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False, "use_automerge_and_split":False})
    bpy.ops.mesh.select_less()

    def extrude():
        bpy.ops.mesh.extrude_region_shrink_fatten(MESH_OT_extrude_region={"use_normal_flip":False, "use_dissolve_ortho_edges":False, "mirror":False}, TRANSFORM_OT_shrink_fatten={"value":0.2, "use_even_offset":False, "mirror":False, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "release_confirm":False, "use_accurate":False})
    def rotate(v):
        bpy.ops.transform.rotate(value=v, orient_axis='Y', orient_type='GLOBAL', orient_matrix=((-1, 0, -0), (-0, -3.42285e-08, 1), (0, 1, -3.42285e-08)), orient_matrix_type='VIEW', mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)
    def scale():
        bpy.ops.transform.resize(value=(0, 0.9, 1), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(True, True, True), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)

    bpy.ops.mesh.select_all(action='SELECT')
    bpy.ops.transform.rotate(value=0.523599, orient_axis='Z', orient_type='GLOBAL', orient_matrix=((1, -0, -0), (-0, 1, -0), (0, -0, 1)), orient_matrix_type='VIEW', mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)

    v = -math.pi/8

    bpy.ops.mesh.select_all(action='DESELECT')
    for i in (118, 130, 141, 209, 247, 279, 293, 305, 332):
        select_vert(cup.data.vertices, i)

    extrude()
    scale()
    rotate(v)

    for r in range(3):
        extrude()
        rotate(v)

    bpy.ops.mesh.select_all(action='DESELECT')
    for i in (90, 103, 106, 109, 117, 145, 158, 186, 194):
        select_vert(cup.data.vertices, i)

    extrude()
    scale()
    rotate(-v)

    for r in range(3):
        extrude()
        rotate(-v)

    for i in (397, 410, 411, 412, 413, 414, 415, 416, 417):
        select_vert(cup.data.vertices, i)
    bpy.ops.mesh.bridge_edge_loops()
    bpy.ops.mesh.select_all(action='SELECT')
    bpy.ops.transform.translate(value=(-0.3, -3.42816e-08, -1), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(True, True, True), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)
    bpy.ops.mesh.select_all(action='DESELECT')

    bpy.ops.object.mode_set(mode = 'OBJECT')
    return cup

mug = create_mug()
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
md = mug.modifiers.new(type = "SUBSURF", name = "sub")
md.levels = 2
bpy.ops.object.modifier_apply(modifier="sub")
bpy.ops.object.shape_key_add(from_mix=False)
bpy.ops.object.shape_key_add(from_mix=False)

2) Making Torus
Add > Mesh > Torus
3) Push the mug usisg Proportional Editing.
Make it look like the Torus and be inside the Torus.

4) Add a mesh path
Add > Mesh > circle
Used to hit a ray from a point of the path to the torus and find the target position.

5) Make sure apply All transforms to all object
Object > Apply > All Transforms
6) Run script
rename the object to mug, path, torus and select the mug
import bpy, bmesh, math
from mathutils import Vector
import mathutils

def find_nearest_from(path, co):
    l           = 99999999999999
    path_verts  = path.data.vertices
    for path_vert in path_verts:
        new_l   = (path_vert.co - co).length_squared
        if new_l < l:   l, output = new_l, path_vert

    return output.co

def tran(mug, torus, path): # context.object must be mug
    bpy.ops.object.mode_set(mode = 'EDIT')
    me          = mug.data
    bm          = bmesh.from_edit_mesh(me)
    mug_verts   = bm.verts
    mug_verts.ensure_lookup_table()

    for mug_vert in mug_verts:
        nearest     = find_nearest_from(path, mug_vert.co)
        direction   = mug_vert.co - nearest

        success, location, normal, face_index = torus.ray_cast(nearest, direction, distance=10)
        while not success:
            direction.y *= 0.99
            success, location, normal, face_index = torus.ray_cast(nearest, direction, distance=10)

        mug_vert.co = location

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

objs        = bpy.data.objects
mug         = objs["mug"]
torus       = objs["torus"]
path        = objs["path"]

tran(mug, torus, path)

7) Keyframe the ShapeKeys

Addition) Make the inside of the mug
Like step 1 to 7
End


text:
Any way to accordingly color separate parts of these LaTeX meshes with python?
I'm writing some functions in python which implement the latex2blender addon. Information about this addon can be found here: https://github.com/ghseeli/latex2blender
I'm able to create a few strings with a color associated to each string. I then combine these strings into one line, send the string to the latex compiler, and spawn in a line of latex with separate parts of the latex mesh colored accordingly.
For example, I have created a "Str" class so I can associate hex colors with strings.
str0 = Str("$\dfrac{1}{2}$", 0xE7E7E7)
str1 = Str(" is a ratio", 0xBE0000)

I then store str0 and str1 into a list and send the list into a "write" function
strs = [str0, str1]
write(strs)

I'm able to display the LaTeX fine and I split the spawned in LaTeX mesh by loose parts. However, coloring the individual meshes gets tricky. I don't think there's a way to be able to tell python which mesh came from which string because the information is lost when compiled. I just set all of the meshes to 0xBE0000.

The following image would be my desired output:

I've thought about splitting things up into multiple compiles and then aligning the meshes afterwards. For example, I could compile "$\dfrac{1}{2}$" set its color to 0xE7E7E7, and then separately compile "is a ratio", and then color is 0xBE0000. However, these latex figures don't spawn in at consistent heights. Aligning them is a pain and I've actually tried to do this. I've played with bounding boxes, resetting the objects origin, etc, but there's just no clean way to do so.
If there was some way to be able to count how many mesh object come from each Str object, that would be nice. The code "\dfrac{1}{2}" produces three disjoint mesh objects The 1, the overline, and the 2. Whereas the string itself has 12 elements, so there's no correlation there.

source: Stack Exchange

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

sort: votes


text:
Object clipping/non-selectable after keyframing vertices
If I start off with a cube (same global and local coordinates), I'm able to select it fine. However, after I keyframe its vertices elsewhere, I'm unable to select the cube while it's near the initial keyframes. Also, I get clipping when I zoom in too far or if I'm viewing it at some other angle towards the initial frames. Why is this and what can I do to avoid this?

import bpy

cube = bpy.data.objects["Cube"]
verts = cube.data.vertices

for v in verts:

    v.keyframe_insert("co", frame = 1)

    v.co.z += 8

    v.keyframe_insert("co", frame = 200)

I think it's a bug.

Darn. I've been trying to find a trick around this. It seems that it's not even associated with +-z. Instead, I think the objects selectable area is where the object is at during the final keyframes.  With the object selected towards the beginning keyframes, you can verify this by pressing numpad "." <--- period/dot. It'll bring you to where it's located at the final keyframes.

Bizzarly enough, I found that the following script fixed this issue:
import bpy

def update_mesh(scene):
    for v in verts:
        v.co.z += 0

scene = bpy.context.scene
bpy.ops.mesh.primitive_cube_add()
cube = bpy.data.objects["Cube"]
verts = cube.data.vertices

for v in verts:
    v.keyframe_insert("co", frame = 1)
    v.co.z += 10
    v.keyframe_insert("co", frame = 200)

bpy.app.handlers.frame_change_pre.append(update_mesh)

It seems that specifically using the function bpy.app.handlers.frame_change_pre.append() and passing into it a "dummy" function that accepts the scene, and does a null operation on the vertices, fixed this issue.
I tried many permutations of this script, some being: for the update_mesh function, placing the keyframing inside it, not looping through the verts into it, not passing the scene into it. I've also tried a few different ways to update the scene, which semi-fixes some issues, but not completely (able to select only when select box fully engulfs)

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


text:
How to quickly fix (or avoid) the n-gons caused by boolean operation?
I'm trying to model a pistol slide with grooves in it which is supposed to look like this:

What I did was creating an array of cubes and subtracting it from the slide with boolean modifier. This precedure ended up with multiple n-gons:

I thought those n-gons might cause some trouble later on, so I used the knife tool to manually cut all the faces into quads.

As there were only 7 grooves in the mesh, I didn't spend too much time doing this. But I wonder if there is a easier or better way to get the same result, in case the object is much more complex than the one I'm making.

If you were making a lot of these grooves, maybe it would be quicker to model them than to fix a Boolean ... something like this ...
Throughout the example, the pivot is set to 'Active Element', and Snap is set to 'Vertex' and 'Active'. This object is X along, Z up.

Starting with your beveled cuboid
Decide on the depth of the groove, CtrlR cut a loop in the base and, using an active vertex on it,  GY snap it in Y to the corresponding bevel-profile edge. Select all the faces which will contain the grooves
ShiftDMake a duplicate of the whole object (to keep your selection)
On the duplicate, deselect all but three of the sections.

In the duplicate, CtrlI Invert the selection,  X delete all other faces, and EY extrude the central section in Y
Select all the vertices on the front of the extrusion, and lastly, one of the ones on minimum Y, and SY0scale in Y to 0. select all, and CtrlVRRemove Doubles.
X Delete faces appropriate to making a repeating unit.

Assign an Array modifier to the unit, with merge switched on, with the right length to fill the grooved section, and select the edges you will want to dissolve later. Apply the array, and the edge selection is preserved, CtrlX Dissolve the selected edges in the arrayed grooves.

X Delete the selected faces on the original ,and CtrlJ join the ridged section to it.
Again , with all vertices of the ridged section selected, and an active vertex somewhere on its minimum Y, snap the ridged section back into the original mesh, and remove doubles.

Thank you for your effort making this very detailed answer! This inspires me a lot.

BTW is it possible to make the grooves and gaps between them have different widths? For example let grooves be 3mm in width and gaps 2mm?

@sacrish Sure. Surrounding details permitting, instead of patching the grooves in, as in this answer, probably the quickest way would be to build the entire block from an array of in+out elements, where the in and out sections have different X-widths. I don't quite know why I didn't do that here. I think I was imagining surrounding pre-existing details, handles, etc, and trying not to interfere with transitions to them.

Select the N-gons with Shift+G
CTRL+T
Alt+J

This is the fast and easy way. The minus is that it's not always all quads. And avoid Boolean if you can as corrections are required if you use it
OR, easier yet

Use CTRL+R once on the pointed edge and snap it to vertices before you OK it.
Btw. okaying answers gives you +2 reputation.

UV for the attempted  bribery in your answer :D

Sorry but I tried the easier way you suggested, and it seemed only to add one loop cut on that single face (probably because the face next to it was not a quad). Did I do something wrong?


text:
Convert particles to animated mesh including existing armature animation
The situation
I am using a boid physics particle system in Blender 2.82. I am rendering the particles using an object that has armature animation. Following a process similar to what is described in this tutorial. This works fine within Blender.
The problem
I would like to export the generated 'flock' to a model (glb to be specific) and in order to do so I need to create real bits of geometry for each particle and copy over the animation per frame of each particles to the newly created geometry.
I saw the answer and script here which works perfecty in terms of copying static geometries, but it does not allow for creating copies of models that have armature included (unless I am mistaken?)
So I adapted the script to the following
import bpy

# Set these to False if you don't want to key that property.
KEYFRAME_LOCATION = True
KEYFRAME_ROTATION = True
KEYFRAME_SCALE = False
MATCHPARTICLE_SCALE = True
KEYFRAME_VISIBILITY = False  # Viewport and render visibility. set this to false otherwise animations don't export to gltf

def create_objects_for_particles(ps, ps_name):

    #deselect source
    bpy.data.objects[ps_name].select_set(False)

    # store a ref for every object to match every particle
    obj_list = []

    for i, _ in enumerate(ps.particles):

        #need to rename duplicate bones for gltf export
        boneName = "bone_{}".format(i)

        #duplicate objects and store the armature to animate
        dupli = bpy.ops.object.duplicate()

        #select the recent duplicate objects
        activeObjects = bpy.context.selected_objects

        #loop through the objects
        for ob in activeObjects:

            #just get the armature
            if ob.type == 'ARMATURE':

                #rename bones
                for bone in ob.data.bones:
                    bone.name = boneName

                #add the new object to the list
                obj_list.append(ob)

    return obj_list

def match_and_keyframe_objects(ps, obj_list, start_frame, end_frame):
    # Match and keyframe the objects to the particles for every frame in the
    # given range.
    for frame in range(start_frame, end_frame + 1):
        print("frame {} processed".format(frame))
        bpy.context.scene.frame_set(frame)
        for p, obj in zip(ps.particles, obj_list):
            match_object_to_particle(p, obj)
            keyframe_obj(obj)

def match_object_to_particle(p, obj):
    # Match the location, rotation, scale and visibility of the object to
    # the particle.
    loc = p.location
    rot = p.rotation
    size = p.size
    if p.alive_state == 'ALIVE':
        vis = True
    else:
        vis = False
    obj.location = loc
    # Set rotation mode to quaternion to match particle rotation.
    obj.rotation_mode = 'QUATERNION'
    obj.rotation_quaternion = rot
    if MATCHPARTICLE_SCALE:
        obj.scale = (size, size, size)
    #obj.hide_viewport = not(vis) # <<<-- this was called "hide" in <= 2.79
    #obj.hide_render = not(vis)

def keyframe_obj(obj):
    # Keyframe location, rotation, scale and visibility if specified.
    if KEYFRAME_LOCATION:
        obj.keyframe_insert("location")
    if KEYFRAME_ROTATION:
        obj.keyframe_insert("rotation_quaternion")
    if KEYFRAME_SCALE:
        obj.keyframe_insert("scale")
    if KEYFRAME_VISIBILITY:
        obj.keyframe_insert("hide_viewport") # <<<-- this was called "hide" in <= 2.79
        obj.keyframe_insert("hide_render")

def main():
    #in 2.8 you need to evaluate the Dependency graph in order to get data from animation, modifiers, etc
    depsgraph = bpy.context.evaluated_depsgraph_get()

    # Assume only 2 objects are selected.
    # The active object should be the one with the particle system.
    ps_obj = bpy.context.object
    ps_obj_evaluated = depsgraph.objects[ ps_obj.name ]
    ps_name = ps_obj.name

    ps = ps_obj_evaluated.particle_systems[0]  # Assume only 1 particle system is present.
    start_frame = bpy.context.scene.frame_start
    end_frame = bpy.context.scene.frame_end
    obj_list = create_objects_for_particles(ps, ps_name)

    match_and_keyframe_objects(ps, obj_list, start_frame, end_frame)

if __name__ == '__main__':
    main()

Which works... ish, the problem is that it is very inconsistent.

Sometimes it works perfectly,
sometimes it only duplicates the objects but does not produce any keyframes,
sometimes it just crashes blender altogether.
etc. I can't see any logic to when it does or doesn't work.

I think my script is logical and since it does work sometimes I think it must be going in right direction but I am a bit of a novice when it comes to scripting so I may be making basic errors.
I wonder if anyone would be willing to have a go with that script and see if it works for them?
The instructions are similar to the original,

first you need to select your armatured object (both the mesh and the bones)
then you select the object that has the particle system attached to it

so you should have 3 objects selected in total. Then run that script.
See below a link to example file, you will find an object with animated armature, a particle system set up and the script is in the scripting tab called 'convert'.
https://cdn.glitch.com/50a342dd-f2eb-4ff5-81ed-e7dff1e4e4cc%2Fparticletogeom_example.blend.zip
Any advice is much appreciated, there might just be some basic issues with my python, too many loops or something.

Often a good idea to provide a blend file with test scene setup (and script inside to run).  https://blend-exchange.giantcowfilms.com/

thanks for the tip @batFINGER I have added a link to a zipped example file

wonder if depsgraph needs to be evaluated for each frame?

Another, perhaps simpler, approach that would work if the animation is simple enough would be to convert the poses to shape keys (https://blender.stackexchange.com/questions/54174/creating-saving-a-shape-key-from-moving-a-bone-rig) and make small modifications to the original script to just copy the shape keys on the particle instances.

hi @daylanKifky thanks for your response, I know what you mean and I had tried an early version converting to shapeKeys and I think ultimately that might be a better approach, unfortunately (and not that I specified this in the question) my target environment does not currently support shapekeys as animation so I need to find a solution for bones.

Which is your target environment? If you have to stick with armatures my suggestion is to work on a simpler version of the scritp that just duplicates one instance and copies all the animation you need. Once you have that stable apply it to the more complex script

@daylanKifky Right now I'm trying to make a model that can be viewed in https://modelviewer.dev/ which allows models to be seen in AR in both IOS and android, some investigations suggest that shapekeys can't be used here. Another case would be ARKit where models can currently only include armature animations. Thanks for advice, I am trying a different version of my script that is closer to your original.

have you tried THREE.js? it's one of the most complete webGL libraries out there. It supports shape keys. I have used it on AR applications and it works great. It also has this onliver viewer to test your models https://threejs.org/editor/

yes, three.js is great and I would definitely prefer to be using that but i can't for this. I've got the script working now, will post as an answer.

So I kept playing around with this and it turns out that my script was basically fine, but trying to rename the bones during the initial duplication of objects was what was causing the problems/crashes etc. So I've broken that out into a separate function - that particular bit is specific to glb export anyway so I also added a flag to run that or not.
Anyway, posting my working script below for anyone interested.
import bpy

# Set these to False if you don't want to key that property.
KEYFRAME_LOCATION = True
KEYFRAME_ROTATION = True
KEYFRAME_SCALE = False
MATCHPARTICLE_SCALE = True
KEYFRAME_VISIBILITY = False  # Viewport and render visibility. set this to false otherwise animations don't export to gltf
RENAME_BONES = True

def create_objects_for_particles(ps, ps_name, particles_coll):

    #deselect particle source
    bpy.data.objects[ps_name].select_set(False)

    # store a ref for every object to match every particle
    obj_list = []

    #loop through particles to make a copy for each
    for i, _ in enumerate(ps.particles):

        #duplicate objects
        dupli = bpy.ops.object.duplicate()

        #select the recent duplicate objects
        activeObjects = bpy.context.selected_objects

        #loop through the objects
        for ob in activeObjects:

            #get current parent collection
            currColl = ob.users_collection[0]
            #unlink from that
            currColl.objects.unlink(ob)
            #add to newly created collection
            particles_coll.objects.link(ob)

            #pull out the armature to add to obj_list for animation
            if ob.type == 'ARMATURE':

                #add the new object to the list
                obj_list.append(ob)

    return obj_list

def match_and_keyframe_objects(ps, obj_list, start_frame, end_frame):
    # Match and keyframe the objects to the particles for every frame in the
    # given range.
    for frame in range(start_frame, end_frame + 1):
        print("frame {} processed".format(frame))
        bpy.context.scene.frame_set(frame)
        for p, obj in zip(ps.particles, obj_list):
            match_object_to_particle(p, obj)
            keyframe_obj(obj)

def match_object_to_particle(p, obj):
    # Match the location, rotation, scale and visibility of the object to
    # the particle.
    loc = p.location
    rot = p.rotation
    size = p.size
    if p.alive_state == 'ALIVE':
        vis = True
    else:
        vis = False
    obj.location = loc
    # Set rotation mode to quaternion to match particle rotation.
    obj.rotation_mode = 'QUATERNION'
    obj.rotation_quaternion = rot
    if MATCHPARTICLE_SCALE:
        obj.scale = (size, size, size)
    #obj.hide_viewport = not(vis) # <<<-- this was called "hide" in <= 2.79
    #obj.hide_render = not(vis)

def keyframe_obj(obj):
    # Keyframe location, rotation, scale and visibility if specified.
    if KEYFRAME_LOCATION:
        obj.keyframe_insert("location")
    if KEYFRAME_ROTATION:
        obj.keyframe_insert("rotation_quaternion")
    if KEYFRAME_SCALE:
        obj.keyframe_insert("scale")
    if KEYFRAME_VISIBILITY:
        obj.keyframe_insert("hide_viewport") # <<<-- this was called "hide" in <= 2.79
        obj.keyframe_insert("hide_render")

def rename_bones(particles_coll):

    #create count for naming bones
    count = 0

    #get the new copies collection
    coll = bpy.data.collections[particles_coll.name]

    #loop through collection
    for obj in coll.objects:

        #make a new name for each bone
        boneName = "bone_{}".format(count)

        #loop through bones in armature and rename
        if obj.type == 'ARMATURE':

            for bone in obj.data.bones:
                bone.name = boneName

            count = count+1

def main():

    #set frame to 0 in case it isn't
    bpy.context.scene.frame_set(0)

    #in 2.8 you need to evaluate the Dependency graph in order to get data from animation, modifiers, etc
    depsgraph = bpy.context.evaluated_depsgraph_get()

    # The last object should be the one with the particle system.
    ps_obj = bpy.context.object
    ps_obj_evaluated = depsgraph.objects[ ps_obj.name ]
    ps_name = ps_obj.name

    ps = ps_obj_evaluated.particle_systems[0]  # Assume only 1 particle system is present.
    start_frame = bpy.context.scene.frame_start
    end_frame = bpy.context.scene.frame_end

    #create a new empty collection to store duplicates
    #do here so can pass to rename_bones
    particles_coll = bpy.data.collections.new(name="particle_copies")
    bpy.context.scene.collection.children.link(particles_coll)

    obj_list = create_objects_for_particles(ps, ps_name, particles_coll)

    match_and_keyframe_objects(ps, obj_list, start_frame, end_frame)

    if RENAME_BONES:
        rename_bones(particles_coll)

if __name__ == '__main__':
    main()
```


text:
Blender api: How to set shapekeys as keyframe in a loop?
I am writing a simple script using the blender api (2.8) that essentially translates keyframed animation info from a rigged model to another model using shapekeys. It attempts to do this by the following;

Moves through a scene frame by frame, applying an armature modifier to a mesh and then setting that modifier as a shapekey
Moves through the same scene frame by frame setting the above created shapekeys as keyframes one by one setting their value to 1 in their corresponding frame.

Part 1 works fine, and I think I understand how to write part 2 as the keyframes are added. The problem I have is that the value of 1 is only applied to the last shapekey and does not change per frame.
Please see below my code. Please note I am a python novice:
    import bpy
    #save the total number of frames as var
    frames = bpy.context.scene.frame_end + 1

    #loop through frames, jump to each frame, add the armature, set as shapekey
    for frame in range(frames):
        bpy.context.scene.frame_set(frame)
        bpy.ops.object.modifier_add(type='ARMATURE')
        bpy.context.object.modifiers["Armature"].object = bpy.data.objects["rig"]
        bpy.ops.object.modifier_apply(apply_as='SHAPE', modifier="Armature")
        #loop through shapekeys and add as keyframe per frame
        for shapekey in bpy.data.shape_keys:
            for i, keyblock in enumerate(shapekey.key_blocks):
                if keyblock.name != 'Basis':
                    curr = i - 1
                    if curr != frame:
                        keyblock.value = 0
                        keyblock.keyframe_insert("value",frame=curr)
                    else:
                        keyblock.value = 1
                        keyblock.keyframe_insert("value",frame=curr)

And here is screenshot of the results you can see the shapekeys are applied, that they are all keyframed, but the value of 1 is only applied to the last shapekey and does not change per frame. (Hard to see that here but please see attached file).

What I expect to happen is that for each frame, the corresponding shapekey will have a keyframed value of 1 and all the others have 0.
So;

for frame 0, 'Armature' shapekey has value 1, all others have 0
for frame 1, 'Armature.001' shapekey has value 1, all others have 0
for frame 2, 'Armature.002' shapekey has value 1, all others have 0

etc. and so on, the result being the equivalent of the original animation but using shapekeys instead of a rig.
It is probably easier to understand the intent and the issue by looking at an example file so if you are willing, I attach the file here. Please open and select the 2nd model ('Cube.001') then go into the scripting layout and run the 'Test' script. You will see the shapekeys are successfully created and the keyframes are applied but the values are not correct.
Downloadable file here
My feeling is that there is an issue with my loop, that is does actually work but it keeps overwriting it each time which is why only the last one shows. No tweaking can get it working though so any advice would be much appreciated. Any more info needed please ask.
Thanks

Answering my own question as I figured it out. Just in case anyone else has a need for it, the below script works as expected.
import bpy

#save the total number of frames as var
frames = bpy.context.scene.frame_end + 1

#loop through frames, jump to each frame, add the armature, set as shapekey
for frame in range(frames):
    bpy.context.scene.frame_set(frame)
    bpy.ops.object.modifier_add(type='ARMATURE')
    bpy.context.object.modifiers["Armature"].object = bpy.data.objects["rig"]
    bpy.ops.object.modifier_apply(apply_as='SHAPE', modifier="Armature")

#for each frame, loop through shapekeys and add as keyframe per frame, set value to 1 if current frame = corresponding shapekey
for frame in range(frames):
    for shapekey in bpy.data.shape_keys:
        for i, keyblock in enumerate(shapekey.key_blocks):
            if keyblock.name != 'Basis':
               curr = i - 1
               if curr != frame:
                   keyblock.value = 0
                   keyblock.keyframe_insert("value", frame=frame)
               else:
                   keyblock.value = 1
                   keyblock.keyframe_insert("value", frame=frame)


text:
How to trigger menus from operators in Python?
I am fairly experienced with both Python and Blender, but using them together is still new to me, and so I am not entirely clear on how everything referneces each other.
To avoid confusion, I have a script that is executed when clicked from the "space" menu:

At the moment, I have three variables hardcoded in, that I would like to be changable by the user. This means that rather than executing the addon's function when "Slow" is clicked, I instead want a menu to be brought up, with sliders I can change the variables with, much like "Bake Action":

I then want it to execute when I press "OK".
However, I don't know where to put the actual code. At the moment it is just in the file that adds "Slow" to the menu, but if I add another menu, should I put the code in the second one, and the first just triggers the second?
Or should it be seperate from both, but then how would the sliders change the values?
Currently the values are coded like this:
        bpy.types.Scene.firstSlowFrame= bpy.props.IntProperty(
            name = "First Slow Frame:", # as you want it to appear on the slider
            default = 40, # optional
            description = "This is the first frame that will be in slow motion"
            )

        bpy.types.Scene.lastSlowFrame= bpy.props.IntProperty(
            name = "Last Slow Frame:", # as you want it to appear on the slider
            default = 60, # optional
            description = "This is the last frame that will be in slow motion"
            )

        bpy.types.Scene.scaleFactor= bpy.props.IntProperty(
            name = "Slow Factor:", # as you want it to appear on the slider
            default = 1, # optional
            description = "This is how much it will be slowed by (1 is nothing, 2 is half as fast"
            )

Since I read this is the way to put them in sliders, however I tried keeping my code in the first and making a panel that used them in sliders and it didn't work.
Overall, I am looking for someone to explain the proper way of using multiple menus, and where various bits of code should go for what I described to happen.
Thank you

Okay, so it took me a little while (and a lot of searching online), but it was this link (https://wiki.blender.org/index.php/Dev:Py/Scripts/Cookbook/Code_snippets/Interface#A_popup_dialog) that showed me what I needed.
What I have done is definitely a hack, and there are more elegant solutions, but if you are just looking for a way that works, then this will help a lot.
(Warning: Lots of code)
So it works by having three classes, which call each other in turn.
The "Clicked On" Operator
The first is an operator that simply exists to invoke the dialog box when clicked in the "search menu".
class slowClick(bpy.types.Operator):
bl_idname = "slowclick.move_operator"
bl_label = "Slow"

def execute(self, context):
    # Default can be used since I only have a single dialog
    bpy.ops.object.dialog_operator('INVOKE_DEFAULT')

    return {'FINISHED'}

The Dialog Box
The second is the dialog box itself. This is invoked in the line bpy.ops.object.dialog_operator('INVOKE_DEFAULT'), and then displayed.
The actual dialog box is built somewhat counter-intuitively. Rather than putting in sliders using the standard layout.row().prop, all you actually do is define the variables, and on creation they can be changed. In my program that looked like this:
# create the sliders (and checkbox) in the dialog box so the user can change where the slo-mo starts and ends
firstSlowFrameP = bpy.props.IntProperty(
    name="First Slow Frame:",  # as you want it to appear on the slider
    default=40,  # optional
    description="This is the first frame that will be in slow motion"
)

globalSelect = bpy.props.BoolProperty(
    name="Global",  # affect all objects in scene
    default=False,
    description="If true, all available objects will be affected"
)

As with normal panels, how you define the property defines what kind of item it will be (e.g. slider for 'Int' and checkbox for 'Bool'), and at the bottom it has an "OK" button.
def execute(self, context):
    # first thing is to globalise the variables needed, and yes I know this isn't the best way
    global firstSlowFrame, globalSelect

    # reassign the variables based on the user's input on the sliders
    firstSlowFrame = self.firstSlowFrameP
    globalSelect = self.globalSelect

    # this actually calls the operator that does the editing
    bpy.ops.slow.move_operator()
    return {'FINISHED'}

def invoke(self, context, event):
    # call itself and run
    wm = context.window_manager
    return wm.invoke_props_dialog(self)

So the def execute() details what happens when the "OK" button is pressed. It globalises all the variables that were changed in the slider, so they can be accessed by the main and final function.
(The def invoke() just describes its creation when invoked)
The Main Function
Finally we get to the actual function. I won't put the main code here (If you want the addon go to How can I slow down or animate time?), but this is just your standard operator:
class Slow(bpy.types.Operator):
    bl_idname = "slow.move_operator"
    bl_label = "OK"

    # get the global variables since this is in a class
    global firstSlowFrame, globalSelect

    #PROGRAM

All you have to do is get the variables that were changed by the sliders, and it all works nicely.
(Technically, if you press "space" and type "OK" you will get this and it will probably not work since the variables don't exist yet, so at the very beginning of the program I would define a "default" value for each that will be used if the user accidentally bypasses the whole dialog box.)
Example
This is a template that can be used, feel free to use it, modify it, I doubt I invented this hack so I mean credit me if you want but I'm really not fussed, just hope this can help someone.
import bpy
import math
from bpy.props import *

scn = bpy.context.scene

# initialising the variables that will be in the dialog
intVariable = 10
strVariable = "Hello"
boolVariable = True

# This is the operator that is clicked by the user, triggering the dialog box
class ToBeClicked(bpy.types.Operator):
    bl_idname = "toBeClicked.move_operator"
    bl_label = "WHATEVER YOU WANT YOUR USER TO TYPE IN"

    def execute(self, context):
        # Default can be used since I only have a single dialog
        bpy.ops.object.dialog_operator('INVOKE_DEFAULT')

        return {'FINISHED'}

class DialogOperator(bpy.types.Operator):
    bl_idname = "object.dialog_operator"
    bl_label = "Dialog Operator"

    # create the sliders (and checkbox) in the dialog box
    intVariableProperty = bpy.props.IntProperty(
        name="Integer Variable:",  # as you want it to appear on the slider
        default=10,  # optional
        description="This is an integer"  # what you get when you hover over
    )

    strVariableProperty = bpy.props.StringProperty(
        name="String Variable:",  # as you want it to appear on the bar
        default="Hello",  # optional
        description="This is a string"  # what you get when you hover over
    )

    boolVariableProperty = bpy.props.BoolProperty(
        name="Boolean Variable:",  # as you want it to appear on the checkbox
        default=True,
        description="This is a boolean checkbox"  # what you get when you hover over
    )

    # This is what happens when "OK is pressed
    def execute(self, context):
        # first thing is to globalise the variables needed, and yes I know this isn't the best way
        global intVariable, strVariable, boolVariable

        # this is just for troubleshooting
        print("Dialog Runs")
        print(self.intVariableProperty, self.strVariableProperty, self.boolVariableProperty)

        # reassign the variables based on the user's input on the sliders
        intVariable = self.intVariableProperty
        strVariable = self.strVariableProperty
        boolVariable = self.boolVariableProperty

        # this actually calls the operator that does the editing
        bpy.ops.slow.move_operator()
        return {'FINISHED'}

    # This is just saying that when it is invoked, how to display it
    def invoke(self, context, event):
        # call itself and run
        wm = context.window_manager
        return wm.invoke_props_dialog(self)

# This is the actual program that does something with the variables
class Main(bpy.types.Operator):
    bl_idname = "main.move_operator"
    bl_label = "OK"

    # get the global variables since this is in a class
    global intVariable, strVariable, boolVariable

    # This just makes sure that everything can be applied
    # if (CONDITION):
    # PROGRAM

    return {'FINISHED'}

    # This can give an error if you want certain conditions met
    # else:
    # self.report({'ERROR'}, 'There is no animation')
    # return {'CANCELLED'}

# registers everything
def register():
    bpy.utils.register_class(Main)
    bpy.utils.register_class(ToBeClicked)
    bpy.utils.register_class(DialogOperator)

if __name__ == "__main__":
    register()

I know this is really very long, in answer to a very unimportant question, but it took me a while to solve this and I'm pretty pleased with it, so I hope other people can find it just as useful.
Feel free to add corrections in the comments!

It's been almost 2 years but I don't know if you realized what you were doing is roundabout and wrong. Since you didn't post any update, I assume either you didn't, or you didn't care to post them.
execute() function is called when ran through python ex: bpy.ops.op.path()
invoke() function is called when the operator is clicked and essentially everywhere outside of python, except explicitly declared; ex: bpy.ops.op.path('INVOKE_DEFAULT')
Otherwise, python assumes bpy.ops.op.path('EXEC_DEFAULT')
if no invoke is declared, operator defaults to execute.
If no execute is declared, operator defaults to invoke.
import bpy

class OPERATOR_OT_name(bpy.types.Operator):
    bl_description = "Displayed on hover"
    bl_idname = 'ops.path'
    bl_label = "Found in Search"
    bl_options = {'REGISTER', 'UNDO'}
        # enum set in {'REGISTER', 'UNDO', 'UNDO_GROUPED', 'BLOCKING', 'MACRO', 'GRAB_CURSOR', 'PRESET', 'INTERNAL'}
    bl_undo_group = ""  # Unused without 'UNDO_GROUPED'.
        # This is used when you want to have a different name displayed in Undo from the Label

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

    def invoke(self, context, event):
        print("I have been called with an event, now I will draw myself")
        wm = context.window_manager  # there are some other functions here
        return wm.invoke_props_dialog(self)
        # This return means to exit and bring a popup with an OK button
        # To call execute function instead, you use: return self.execute(context)

    def draw(self, context):
        layout = self.layout
        layout.prop(self, 'string', text="")
        layout.prop(self, 'bool')
        layout.prop(self, 'inemene')

    def execute(self, context):
        print("I will actually run by blazing the execs, then return to nothing")
        print("String", self.string)
        print("bool", self.bool)
        print("Ee nee Me nee My nee mo", self.inemene)
        return {'FINISHED'}

    string = bpy.props.StringProperty(name="Ambience", default="{Insert text here}")
    bool = bpy.props.BoolProperty(name="Always Truther", options={'SKIP_SAVE'})
    inemene = bpy.props.FloatProperty(description="No display name given, so displayed text is lowercased")

    # The order of the 4 def functions, the 3 variables, and the 5 bl_ vars don't matter, I just put them that way.
    # However, for the desired process, this is essentially the order that Blender/Python will internally read them
        # (except the vars, those go up with the bl_ vars)
    # Also, the poll isn't needed (because it doesn't check anything),
        # and some of the bl_ vars aren't needed, I just chose to include them both.

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

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

# This section is used for when you want to debug the script inside Blender's text editor, using Live Edit
if __name__ == "__main__":
    register()

When you need to read the event values (like key-presses, mouse location, etc), you use the invoke function and send it to vars in self, not global vars.
global vars are for when you need to store properties outside of operators and classes/function during the blender session.

Since you control the operators, you could also send properties to a context copy.
In the layout, it's done with layout.context_pointer_set('var_name', data_pointer) (data_pointer is strict on what type of things can be sent)
note: for UI buttons, not this wm.invoke function
In ops, it's used like
context_to_dict = context.copy()  # Creates a duplicate as dict()
context_to_dict['custom_var'] = "Whatever"
bpy.ops.op.path(context_to_dict, 'INVOKE_DEFAULT', self_var="A registered variable for self")

In the operator called, the custom variables will be found in context. To poll for whether or not they were declared, you just use hasattr(context, "var") or getattr(context, "var", "value to default to if not found")

When I use the layout.context_pointer_set() in the panel, and then the operator uses invoke_props_dialog() in an invoke() function, it then looses the context I have set in the UI in the execute function. How can I pass it on?
I tried copying the context in the invoke function, but it didn't work.

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


text:
Parent bone being rotated by child bone
I have created a rig that has a ground bone that can move the entire rig. It moves fine when all of the control bones are connected, but as soon as I parent the root bone for the entire rig (the root spine bone), I get some weird issues. If I move the spine bone, it rotates the parent ground bone around the ground bone's head. If I move the ground bone, it wiggles when it is moved. I must be missing something simple, any ideas?

Can you upload your blend file to http://blend-exchange.giantcowfilms.com/

There is most likely a dependency cycle issue between some constraint (most likely IK) or a driver and bone parents. The rig has to be inspected to debug where exactly the problem is.

@MartyFouts Here is the rig:

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


text:
How to access the 3D cursor with 'Local View' support?
Some scripts use the 3D cursor (for adding new objects or for a point of reference).
A common way to do this is using bpy.context.scene.cursor_location.
However in Local View each view has its own cursor, making tools behave strangely when local-view is enabled.

So the question is:
What's a good way to access the 3D cursor which will use the cursor as seen by the user?

Here's an example of 2 different ways to access the cursor.
Checking the space type and using only 3D views.
def context_cursor(context):
    scene = context.scene
    space = context.space_data

    cursor = (space if space and space.type == 'VIEW_3D'
              else scene).cursor_location
    return cursor

Using getattr with a fallback, however this isn't so reliable since it may return a 2D cursor for the image space (which probably isn't what you want).
# don't use this example!
def context_cursor(context):
    cursor = getattr(context.space_data, "cursor_location",
                     context.scene.cursor_location)
    return cursor

Note that when the 3D view isn't a Local View. context.space_data.cursor_location  will use the scene's cursor.

It appears that the local view's cursor is the VIEW_3D space's cursor (rather than the context scene's cursor):
import bpy
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        for space in area.spaces:
            if space.type == 'VIEW_3D':
                print( space.cursor_location )
                break

Right, pasted the wrong version for some reason, thanks @batFINGER.

Wonder what voodoo magic ideasman42 has for this one.  I feel context.space_data.cursor_location always gives you the "as seen by the user" cursor loc. when it's the 3D_VIEW type space.  Could set up a bpy.types.Context.cursor_location property that returns such or...


text:
How to find the Python equivalent operation for tools, settings & menu?
When you press a button or change a setting, this is an operation which you can also do in Python, how do you find the Python equivalent to accessing these user interface elements.

Settings (text, numbers, colors... etc)
Buttons (tools you access via key bindings, menu items etc)
Menus (accessed via headers, other menus or key-bindings)

Enable Python Tooltips, and hover over the setting/button/thing and there will be a data path which points to the function; You can also press Ctrl + C to copy it.

Ya, you posted an hour ago. @someonewithpc, Didn't think about that. Answer removed

@BlendingJake Sorry for the inconvenience....

Edit Source
If you wanted to find out the python code for some of the user interface and panels you could right-click on parts of the UI (such as buttons or properties within the panel you wanted to know about) and choose 'Edit Source'.
For example, if I wanted to know about the render panel:

I could right-click on the 'Render' button and choose 'Edit Source':

A notification will then appear in the Info header at the top of the screen (in a default layout) informing you that a text file had been created for viewing in the text editor:

You can check this file and view the python code that makes up the panel:

In this example you can see information which might be useful such as: The panel class name which can be used to append new UI elements into existing parts of the UI (RENDER_PT_render), the operator names and categories (render.render for example) and general UI code for creating rows (row = layout.row(align=True)).
Autocomplete
Sometimes, if you are searching for the python equivalent of a property, it might be useful to use the autocomplete feature (CTRL+Space) of the 'Python Console' to explore the api.
Autocomplete will show you all the possible options branching off the current one. For example, using autocomplete on bpy.data.objects['Cube'] would result in showing me all the available python properties for that object:

Online API documentation
You can also browse the online 'Python API Reference' (that link always redirects to the latest version) which can be found via the help menu:

This documentation includes several pages serving as an introduction to the API as well as a full reference to all the python commands and properties available to use in blender. While this doesn't provide the python command to an exact tool/panel instantly, a simple generic search of "panel" using the search box would provide results relating to existing panels in blender and examples of how to create a new one.
Hotkey Preferences
If you wanted to find out the python name of a menu that appears when you press a hotkey, you can search for that hotkey in the preferences. For example, if I wanted to know the python name of the menu that appears when I press Ctrl+H in edit mode (the hook menu), I can search using the shortcut (when search type is 'key binding') in File> User Preferences> Input:

This provides several results, one of which is a 'Call Menu' item in the 'Mesh' category which reveals the name of the menu being called:

Here we can see the menu being called with that shortcut is VIEW3D_MT_hook, which you can then call in your own scripts.

You can use Python Tooltips.
To enable them, go to the 3D Header, press file and the User Preferences; You can also use the shortcut Ctrl + Alt + U. Then go to the Interface tab, and check Python Tooltips.
Now when you hover your mouse over any button/field, it will show you, in blue text, the datapath to the function/field associated with that button/field. For example, the Render button's tooltip reads Python: bpy.ops.render.render(), so it's datapath is bpy.ops.render.render()
To copy this automagically, you can press Ctrl + C, or RMB and select Copy Data Path.

Don't forget this-> http://blender.stackexchange.com/questions/18420/copy-python-code-of-operation

One way to get a whole lot of info about what is going on behind the scenes when it comes to Pyhon is to open the sneaky window hidden up at the top of the main Blender window.  Click and drag the top header bar down to reveal it.

Upon adjusting the Lamp Strength in the Node Editor, an entry in the top window will appear that shows the Python command with the value entered which matches the value from the node which was recently adjusted as shown in the next image.

Others have given a partial answer, the full answer is usually a combination of each method. Unfortunately finding the python equivalent is not a one method answer.
Python tooltips are helpful but can be truncated so you may need to find extra information or be familiar with what is cut out. From 2.72 you don't need to keep tooltips enabled, hold down Alt and move the mouse over an item to see the tooltip when they are turned off. This is an area that the auto complete in the python console can be helpful. Sometimes you may need to search through the api docs to find the truncated sections.
Many properties are easily visible in tooltips and right click->copy data path will give you the most unique part of data path, you then add that to current object or material nodes etc. There is also an API navigator addon that can be useful to find data paths.
Buttons are used to run an operator and most will show up in the info window once you expand it, a right click->Edit source is usually a good second option. There are areas that edit source fails, such as most of the properties sidebars (for non-addon panel items).
For menus, they are a collection of operators and python tooltips are normally sufficient. You can't edit source for each menu item but as long as you haven't collapsed the menus you can edit source for the menu in the header and follow the list to find the one you want.


text:
Why do only some tools have redo capability?
Many tools can have their settings modified after activating them (via the toolbar or F6 popup), however some tools have this panel greyed out.
eg:

Ctrl+Click Extrude.
Editmesh rip tool.
Bend transform.
Knife.

Is this a bug in the tool, whats the reason for this limitation?

First of all there are cases where redo doesn't make any sense (render, save, open), in those cases simply running the operator again is fine.
Operators have their own internal data which is used to execute an action, in most cases this is sufficient to store all information needed to redo an action (make use of the F6 popup, or be called from a Python script).
But consider the knife tool for example, can have the view manipulated as its accessed, so the tool would need to store the viewport orientation of every line added.
While this is possible of course (in principle), the benefit of adding this is limited since these tools are intended to be accessed interactively.
Another example is the rip tool, which will give different results based on where you're cursor is in relation to the selected vertices. Its also possible to simple store the mouse location and re-use that, but its unlikely to be very useful.
There are cases such as bend transform which could be made to redo, but depend on the view orientation, 3d cursor to define a line to the mouse and the distance the mouse moves once the tool is activated. Manipulating these values only-via buttons is possible but would end up being an nonintuitive matrix of buttons. Such settings would be better manipulated via an adjustable on-screen widget however blender currently doesn't have such facilities.


text:
Can Cycles use multiple UV layers?
I'm trying to match Cycles to a Blender-Internal material setup and I didn't see a way for cycles to have an image reference more then one UV map.
Is it possible to have a node setup with 2 image textures, each using a different mesh UVLayer?

Yes, the different UVMaps can be selected by an attribute node and plugged into the vector input of an image texture node as well as into another image texture node vector input holding an alpha mask of the image referenced from the first texture node. This way multiple textures (and UVMaps) can be mixed for a single material output.
This technique is demonstrated in this tutorial.

Update
There is now a dedicate UV map node (will be in 2.71).

Original answer:
As already mentioned by stacker, this can be achieved with the Attribute node (ShiftA> Add node > Input > Attribute)

Attribute
Retrieve attribute attached to the object or mesh. Currently UV maps and vertex color layers can be retrieved this way by their names, with layers and attributes planned to be added. Also internal attributes like P (position), N (normal), Ng (geometric normal) may be accessed this way, although there are more convenient nodes for this.

For example:

Simply put the name of the UV map in the Name parameter, and use the Vector output as the UV coordinates.
The UV map with the camera icon selected in Object data > UV maps will be used by the Texture coordinate node:

While you can mix Attribute nodes with Texture Coordinate nodes, I personally find using only Attribute nodes is easier with more than one UV map, as the name of the UV map is already on the node.


text:
Is it possible to create a path from an existing object animation?
Once you have an animated object using typical key-framing (other methods such as physics, driver or NLA apply too).
It could be useful to apply the motion to a path:

to adjust the evaluation time
edit curve points points may be easier
have many objects move along the same path.
ability to follow the path.

Is there a way to do this?

Note that rotation and scale won't be taken into account.

Would the BTracer Addon work for you?
It creates a bezier curve object from any animation by tracing an object, mesh vertex or particle motion path through the scene space for every frame.
Have in mind that it doesn't convert the animation for you it only traces and creates a curve object from it. You may then manually rebuild your animation to use this path, although some transformations may be lost or not translate completely as expected, like rotations.
Workflow
Select your animated object, and in 3D View > Tool Shelf > Misc Tab > BTrace Panel you will find all the settings you need.

Choose the Mesh Follow option
Expand the Settings button
Choose Object option to trace the object center.
You can also set the step size so there is less than a vertex per frame, although it probably comes at the cost of accuracy
Press the Curve Settings button bellow
Choose the desired Bezier curve interpolation (you can change here the type of handle from vector to aligned or auto)

In the end if there are too may vertex maybe you can clean up a bit with the Simplify Curves addon (in Blender by default), though again probably at the cost of accuracy.
Now I am not much into animation so I am not sure how this may go, maybe someone else more experienced as a better workflow but:

You can then either clear the animation of your object and parent it to the curve and use the Properties Window > Object Data > Path Animation for the curve object;
Or clear the animation of your object and use a Properties Window > Constraints > Relationship > Follow Path and pick your curve.

Not sure which one is best.

The BTrace addon from the link above crashes for me on 2.77.  A quick look at the code and it creates a curve path from the objects location for each frame, rather than using the objects matrix_world.to_translation() hence it doesn't give a reliable path for physics or  constraint driven animation.  Try with a simple rigid body gravity fall.

Just did a quick test and it didn't crash for me in 2.77, but yes, it does seem to work around the blender animation data, only reading directly world transformations every frame, not really extracted from animation data itself, so it may not be as precise as required..

Note that if BTraces is a solution, could be good to give steps to use this for moving keyframe to object-path animation.

I tried to use the addon and managed to get it to create a curve that followed a meshes vertices, but not the object center. However it added a single point per keyframe, used vector handles (not nice for editing). So while it seems similar but not really usable to convert a keyframe animation to a path animation.

You can track object centers too and set your preferred bezier handle type. Added further info to my answer, check above. I am not fluent in animation, so not sure if the method above is the "correct" way to do the animation part though.

Added further info about the amount of vertex you can either tweak the step size or clean up afterwards using the Simplify Curves addon, although both options come at the cost of accuracy which probably is not much to start with.

I was wondering the internet and just found out about this. Never used it myself, and I am not sure it still works on current versions of Blender, but have you ever heard of Motion Trail Addon?
It seems to provide what you are looking for, a direct way to control an existing animation straight from the 3D viewport.
It doesn't seem to interpolate every single frame into a point on the bezier curve, instead providing a bezier curve with handles only on keyframes
Demo Video Wiki page and Official Website

From the two answers in this question, I find an easy way to do this. First set the target object as a particle emitter, then construct a Bezier curve with animation nodes.

This is what it looks like:

There's an add-on called motiontrail3d, link: https://animationtoybox.gumroad.com/l/motiontrail3d
Here's a demo of it in action: https://www.youtube.com/watch?v=zk8OCvYLeDk
I was looking for a similar technique and stumbled on your thread, seems like this could help you out. I manually modeled the mesh though, however its a cool add-on to have. Hope its useful.


text:
What are the common reason for this? (I Can't Join Vertices)

For some reason, I am unable to join vertices using 'J'.

Hello, please tell what vertices you are trying to join and maybe share your file?

I was just trying to join the vertice of the the currently selected vertice to the bottom vertice of the object vertically

Use 'F' instead but since you're trying to do it on a section with a Simple Deform modifier on it you may not get the result you expect.

You have overlapping vertices that you need to merge here, otherwise the faces are ripped and the join won't work:

To merge the vertices, you can select all, press M > Merge by Distance then increase the Distance in the Operator Box, or AltZ for transparency, select the 2 vertices and M > Merge at Center.

Thanks a lot!!!

One more question tho, how do you merge it?

I've edited my answer


text:
How to create an animated gradient backdrop with noise-like effect
Im trying to create an animated backdrop that creates a similar effect to the noise-like textures often used in Illustrator or Adobe after effects. Is there a simple and easy way to achieve that in blender;
My current methodology is to create a frost glass vertical plane at the front (to soften the effect - and add grain-like effect) and place a voronoi texture behind that which is going to be animated; illuminating onto the front glass;
I will link a video to show what Im going for approximately
https://streamable.com/xj0vz7

What Im doing kind of works, but Im interested to find out whether this is overkill and theres other better ways to go about it;
PS. Yes, I just started Blender a few days ago, complete noob.
Thanks for your time.

You can get something close to what you show with a Noise Texture plugged into a ColorRamp. Also mix a Musgrave with the Texture Coordinate into a MixRGB in order to twist the spots a bit. Then animate the Mapping on the Z location (or, as Allen Simpson says, switch the Noise Texture to 4D and keyframe the W value). If you want some grains, do it in the Compositor, see this answer:

You could also make it more complicated and mix several of these effects with a n&b musgrave as factor...

Beautiful, thank you!

Noise texture also has a 4d option which gives you a W value for changing the noise over time instead of moving it through space. :)

@Allen Simpson oh you're right I always forget the W value, I'm going to edit


text:
How to fix defects on the lower jaw? (Fill Holes in a Mesh)
I'm trying to prepare the lower part of the skull that I took from the tomography image for 3d printer in blender.
I saw some defects as seen in the picture. How can I fix these defects?
This is the image I am working on.

Defects.

hello, are they holes? in that case you can boolean small objects then sculpt a bit

@moonboots Yes holes. How can I fix?

You have tools to fill the holes like:

Select all in Edit mode and Mesh > Clean Up > Fill Holes (increase the Sides value in the Operator box if necessary)

Or Switch to Edge select, don't select anything and Select > Select All By Trait > Non Manifold and F to fill.

Or, let's say that you have your object with holes (1). You can create a second object that looks like a small flatten sphere (2):

Give your object a Boolean modifier, Union mode, with the small sphere as boolean Object. Apply the modifier:

Then sculpt to smooth the surface (use the default sculpt brush, press Shift to smooth):


text:
How to make these shapes? (Nokia 3310)
I am modelling this Nokia 3310. Now I want to make the white and the black shapes within the model. I tried cutting shape with knife tool, but as soon as I apply subdiv modifier it becomes stretched. How do I do it?

You'll need to learn more about the sub-d modifier, learn how to add crease to your edges crease

A very good resource for hard surface modeling is Josh Gambrell

@Psyonic josh gambrell isn't the right person to learn modelling from. He ignores topology.  Moreover he makes random shapes that doesn't conform to any design guideline. Such designing practices are only valid for rough concept art.

You could begin with the screen (it will probably needs inner edges):

Then extrude and move the vertices around the white shape:

Extrude again and create the rest of the phone shape:

The answer from @moonboots is good, but in my opinion it may need some improvement, because the location of the 5 quads pole is just located right between the edge of the white panel and the red keypad. This can make the edge of the white panel no longer completely smooth.
Also, if you want to extrude the white panel along the Y axis to be more protruded or have more definition, then the 5 quads pole will cause a geometric problem.

Even if you subdivide the quads, the 5 quad pole is still there!
To mitigate this issue, you can move the 5 quad pole downward, like the following way:

But be aware that this can only mitigate the issue, and can not completely solve the issue. When you use the subdivision, you have lost a part of the precise control on the shape of the geometry. You may also have lost some of your ability to bake a normal map to a high precision.
Instead of using the subdivision to model this phone, it would be better by using the bevel in the Edit mode. You can make 3 bevelled surfaces, and then use Ctrl +  j to join the 3 surfaces into one object, and connect them with N-gons or quads, as the screenshot below (no subdivision is used):

By using the bevel, you can precisely control the shape of the white edge.
Also, the subdivision does not support N-gon when baking a normal map, but the bevel does support N-gon in the baking.

Those are some very valid points you've raised (and illustrated) here. The last image - where you joined the 3 shapes is something I tried before but was unable  to move further because I need to use subdivion modifier. I suppose you are asking not to use subsurf modifier and just shape the curve using bevel? But I think subsurf is needed for a close up model, like those is Apple (or any phone) advertisements.

There are a lot of free tutorials on making phone. Here, I just name a few tutorials below. It would be great for you to observe whether they have used the subdivision modifier for the close up model or not. For myself, I usually use the subdivsion modifier for organic shapes, and the bevel for non-organic shapes. Good luck!   https://www.youtube.com/watch?v=lZPedlX6CMw https://www.youtube.com/watch?v=Up3cxVQRQrI

This method os not adding subsurf modifier is very limiting. Any shape away from straignt lines or consisting of curved surfaces will end in bad looking results

For a curved surface, if you want to use subsurf modifier, then it's necessary to break this Nokia phone into at least 4 pieces: the black screen, the white panel, the keypad, the bulk, etc. And then you can use subsurf modifier for each piece respectively. By this way, the problem with the 5 quads pole can be avoided. You can observe how other people model the curved surface, such as the following tutorial, in which he divide the car by many pieces: the trunk, window, doors, lights, etc. And then use subsurf on each piece.  https://www.youtube.com/watch?v=VGPvxIrobFE

I have seen this video earlier in its entirety. This method definitely a "thumb of rule" way to model anything. Break down piece by piece. I saw another channel, who uses C4D to model, but he is exceptional in modelling. https://www.youtube.com/c/polygonpen


text:
How do i learn something like this? (Apple Watch)
I want to learn product modelling like attached in the image below. Kindly guide me from where I can learn something like this in Blender. Youtube videos are not very helpful, they are abstract. I want to learn professional methodology of creating quad based product models.

They are all from the same image set. It looks so perfect!

Hello, your question is a bit too broad, and I'm not sure why you're not glad with the youtube tutorials, you can learn everything with youtube only, including this kind of objects

this has been asked multiple times before and there are answers here https://blender.stackexchange.com/questions/15355/resources-for-blender

@moonboots There are couple of Apple Watch modelling videos but none of them are accurate. They're all just random look alike watch and doesn't do the intricate details of the model as shown here. It may seem simple but it isn't , atleast not for me.

maybe, but Blender Stack Exchange is not made for such a complicated question that would need a long answer, maybe tell one particular obstacle you're fighting with?

I think you should give up on hoping there is someone doing exactly what you need in the exact quality or skill level you want on a specific object. I know for myself Blender can be difficult to learn, but you won't get around it if you ever want to do complex objects yourself. I've learned very much from tutorials, and I've watched many even dealing with things I didn't need (at least not in that moment). With this and trying out things for yourself you will get the skills you need. If you need the object right now, maybe you should rather buy a model.

Sorry, don't mean to be offensive, it's just how it is. You see I've been using Blender for so many years now, but there's always something to learn (especially when things are changed over time and new features are implemented)... and nowadays I watch tutorials and are amazed by some cool things the tutor does on the one hand and shake my head about how complicated he does something else which I know how to do much easier. Nobody can fully teach you everything and even then you might be more comfortable with different workflows or methods for certain things.

@GordonBrinkmann I am not offended. But, I want to learn. Of course I can make this model myself, in fact I already have but, it is not accurate. It is more of makeshift model, where I used random techniques to make the model. But such effort always has limitation. I want to learn, make perfect models that can be zoomed in and no one could tell the difference between the real thing and 3D model. Cheers

But when you already have modeled it, you could ask about specific things you are not happy with. This question is a general "how do I do this?" which requires more of a tutorial or guide as you call it. If your goal is to get from building a good topology model to having a photorealistic render, there are many, many very different steps inbetween. This is not what this site is for. And if you are not happy with the tutorials you watched and want us to name others - do you have a list which ones we should not suggest...? Or do you simply want us to find one for you doing exactly this model?


text:
Textures Changing when selected
So I'm making a wood shed with wood textures and stuff.
For whatever reason, when I select certain objects, their texture changes.
Before I select them

After I select them

Now it is a slight difference, but it should not be doing that.
Anyone know what the heck is happening?

Hey, this is interesting :). Would you mind sharing the file?

Oh I do have the finished file, but I just deleted those objects and re-made them to solve the issue :/  here is the file anyway.
https://drive.google.com/open?id=1c5cdI4Kr5V6kAJajZ9PSBLFM8KJY0wui


text:
How do I make a luminescent gas cloud?
How can I make a luminescent gas cloud, similar to the one shown in the picture below (labeled "Trapped Atoms")? Thank you.

Simple Sphere with Emission as a Volume would be sufficient. We will use for both methods mostly the same setup. Gradient Texture > Color Ramp > Emission shader.
Color Ramp will control color and smoothness.
Emission > Strength... Strength.
Without Emission.

They will look like gas spheres and emission will not affect other meshes.

With Emission.

This ones will affect meshes with light.

Aw, beat me to it! Great answer, have an upvote. (:

Hi cgslav, I have tried using your method. However, when I increase the emission strength, the cloud goes back to being a solid sphere again. Do you know a method that works at all emission strength? Thank you.

@user3886914 than you will need to tweak color ramp to make it soft again.


text:
why wont the particles show up on this mesh?
I've set the grass particle to work off 'density' in the vertex groups. first time this has happened. there are no modifiers except 2 particle systems on this object. is this a glitch or am I missing something?

I don't know if this makes a difference with your file since we don't have a stripped down version uploaded to look at, but one of your particle systems is set to not be visible. Is that on purpose?

no both of the particle systems were set to the same vertex group. I managed to fix the problem by painting in weight paint the what seemed to update the system then reapply the weights in edit mode. It now works fine so must be a bug


text:
Built-in Keyframes
What is the difference between the built-in keyframes? For some reason, automatic key framing is not working for so I have to manually set it. If anyone has an idea on it, please help.
Built-in Keyframes

Available
BBone Shape
Delta Location
Delta Rotation
Delta Scale
Location
LocRot
LocRotScale
LocScale
Rotation
RotScale
Scaling
Visual Location
Visual LocRot
Visual LocRotScale
Visual LocScale
Visual Rotation
Visual RotScale
Visual Scaling
Whole Character
Whole Character (Selected bones only)

Note: I am video editing on Blender not modeling.

Those settings only apply to the 3d view and don't affect the video editing process. Like you said, auto keyframing has no effect either

Each of these options selects which property will be saved to the keyframe. For example, if I select LocRot it will save a keyframe for location and rotation, However, if I also scale the object, but do not set a scale keyframe, the scale will not be animated.
However, you say you are video editing. These options do not apply to video editing. Try switching to the video editing workflow. If you would like to set a keyframe for a property, hover your mouse over it and press "i". Then move the timeline cursor, change the value, hover again, and press "i". This will animate the desired property.


text:
Texture is stretched on certain faces
I'm currently modeling a football stadium, applying a texture to the stairs I created using the array modifier from a simple cube shape.
When I apply a texture to the stairs, the texture is clear on the flat part of the step, but the front of the step is stretching the texture horizontally, and does't look like the concrete surface I'm trying to achieve. Does anyone know an easy solution to this issue?

Please show you work with a Blender screen capture.  Please do this consistently for all future questions.   Your words and a carefully considered image will clarify your question.

sounds like you did not unwrapped the mesh correctly. Apply scale and then unwrap again.

Sorry... I'm new to all of this. I've placed the images in the post

Without seeing your node tree this is my best guess. Under the texture image node change the projection from flat to box. You can also change the blend value but if your stairs are perpendicular it probably won't change anything
Edit: sorry picture is sideways i am on my phone.

For reference, this might provide a way of taking slightly higher quality screenshots: https://www.take-a-screenshot.org/

Its a photo of my computer screen, taken on my phone, as I was replying via the app

In you node tree we can see you're using the box projection while using the UV coordinates. Most of the time it doesn't work that way.
Either you use the UV coordinates and you set the textures to flat projection:

Either you use any other texture coordinate (usually generated) and any projection you want:

It's important to note a few other things:

You must have even scales on your object, meaning the scale of your objects should always be the exact same value on each axis, and ideally equal to 1.
If you don't have even scales, select your object in object mode and hit CtrlA → apply scale.
For using UV coordinates, you must have unwrapped your object.


text:
Grease pencil strokes disappear in surface mode in Blender 2.8
I'm learning grease pencil in Blender 2.8, hope you can help with a small frustrating issue:
When the stroke placement mode is set to 'surface' for drawing directly on a mesh, only the current stroke is visible as it is being made. Any previous strokes drawn on the surface disappear while a new stroke is drawn, and then reappear as soon as the current stroke is stopped. This makes it quite hard to draw.

I've seen videos of grease pencil 2.8 being used on a surface without this behavior, but I can't find any setting to alter it. If anyone can help (new to Blender) be very much appreciated.
Many thanks in advance!

I just recently experienced the same problem!
Maybe a solution to your problem:
In the "stroke placement" dropdown if you select "surface" there is also an option for an offset.
This works good.
However I found out that the offset to the projected surface as well as the thickness of the Gpencil is relative to the viewing distance to the object.
There should be an option for relative to object and relative to screenspace if you have placement on surface selected.
Where can we report this? I don't know how I can get in touch with devs...
Anyways, I hope that helped!


text:
Automatic Weights Rigging makes model warp horribly on posing
I've used Automatic Weights for rigging humanoid models a lot of times and it worked more or less perfectly. But for this one model, any movement of bones just grabs most of the mesh and deforms it strangely instead of affecting the appropriate part, weight painting does little to help as it just makes every bone affect the rotation of the entire mesh.
I have no idea what's causing this, tried cleaning the mesh up as much as possible but to no avail.
Redid the skeleton 3 separate times, and the results are always the same.
Update:
The problem seems to be that the bones only deform the mesh, and don't move it at all otherwise. If deform is disabled, bones cease to have any effect on the mesh.

upload your .blend here https://blend-exchange.giantcowfilms.com/

its a weight paint issue, one of the bones had too much influence.

Thank's a lot ! Though it still does a similar thing, I've tried altering the weight painting, even substracting all of it completely, and it still bugs out, as if every bone was affecting every part of the mesh, unlike when applying it to any other model I've tried. Essentially it looks as if it was only deforming the mesh without moving if that makes any sense.
To demonstrate, this is what it looks like when trying to move a bone with and without deform on respectively
https://i.imgur.com/11A7z6l.png
https://i.imgur.com/jhlujfz.png

Essentially, if I turn off deform of all the bones, the mech doesn't move at all with the movement of bones. Just tested it.


text:
How to get all images for an image sequence? (from Python)
When Blender references an image sequence, the image.filepath only ever references one image at a time.
However for renderfarms and copying projects between systems, you may want to get all the images associated with in image sequence.
How would you go about getting all the images in an image sequence for a Blender Image or Movie-Clip?

posted as an example since I needed to solve myself.

This function returns all the images which share the same prefix, suffix (and have a number suffix), eg:
/path/to/my_image_0001.png
def image_sequence_resolve_all(filepath):
    import os

    basedir, filename = os.path.split(filepath)
    filename_noext, ext = os.path.splitext(filename)

    from string import digits
    if isinstance(filepath, bytes):
        digits = digits.encode()
    filename_nodigits = filename_noext.rstrip(digits)

    if len(filename_nodigits) == len(filename_noext):
        # input isn't from a sequence
        return []

    return [
        f.path
        for f in os.scandir(basedir)
        if f.is_file() and
           f.name.startswith(filename_nodigits) and
           f.name.endswith(ext) and
           f.name[len(filename_nodigits):-len(ext) if ext else -1].isdigit()
    ]

# example use
print(resolve_image_sequence("/path/to/my_image_0001.png"))
>> ["/path/to/my_image_0001.png",
    "/path/to/my_image_0002.png",
    "/path/to/my_image_0003.png",
    ]

You can use https://pypi.python.org/pypi/Clique/1.5.0
Clique module. It was created for tasks like that.


text:
isometric deformation of a plane
can you please address my query.
I want to smoothly deform a plane such that the distance between the 2 points on the plane are preserved(Isometric deformation).
For example
1) In the 1stfigure, you can see in the flat mesh grid(undeformed) the distance between the vertices are constant (.222 blender units).
2) In the 2ndrd figure, i apply the wave modifier to deform the mesh. As you can see, the distance between the 2 vertices is not the same anymore.
I want to achieve the smooth, isometric deformation. Where the distance between the vertices remain constant after deformation.
How can i achieve this isometric deformation in blender?(using any of the available modifiers such as wave, wrap, deform, cloth etc etc).
Thanks
Demon

Could you please clarify how this plane would be distorted? Twisting, skewing, scaling, waving? Perhaps edit your question and provide some more details like a more thorough description and reference images.

Hi :) , Thanks for the reply. I have updated my question with figures.

Final:
As far as I know your best shot would be with Curve modifier. It will not be perfectly even though but I don't think it's possible to preserve 1:1 edge length with any modifier.

Steps:

Add Curve > Bezier Curve.
Rotate it 90 degrees on X axis.
Select Plane and add Curve Modifier.
Choose BezierCurve.
Move a Plane on X axis.

If it help you in any way consider accepting it and/or upvoting ;)

@demon, don't thank in the comments, consider upvoting the answer if it helped, or mark it as accepted if it solved your problem


text:
Precise commutative rotation on global X and Y
I am trying to find a way to rotate a vector with python so that the angle between the z axis and this vector is exactly _x° from the right ortho view and the angle between the z axis and this vector is exactly _y° from the front ortho view.
[![Front ortho][1]][1][![Right ortho][2]][2]
Using the XYZ Euler rotation system dont look a good way to perform such a rotation since an y rotation will modify the initial x rotation, and rotating around the local y axis after the first x rotation will keep a valid x rotation but give an invalid _y angle from the global point of view.
What i am trying to find is an Axis angle, (or quaternion) were the rotation axis is a combination of global x and y vector ([1,0,0] and [0,1,0]) and a corresponding angle.
In this case if _x==_y , the resulting rotation vector will be [0.5,0.5,0.0] and the corresponding angle will be a little more than _x. But i have some difficulties to figure out the maths to find this vector and this angle for any _x and y between 0 and 89.99° (90 would be a problem for sure), or a built in function in Blender that could give this exact result.
NB: The example given here is based on blender global axis but my problem is actualy to rotate around any two perpendicular vectors (local axis of an object). A basic solution in global referential would be enough to find the solution to my initial problem.

I asked a pretty similar question once: https://plus.google.com/102817843024907935934/posts/HLxXBU7x6fu You have to claculate the rotation on the 3rd axis to compensate the other two to your desired angle

Wouldn't moving the origin to the base fix this problem?

Aoradon: Moving the origin wont solve the problem since i'm stritcly talking about vectors, and a vector has no origin. The origin problem when making rotations will only have an impact on the translation part of a transformation . I dont care about that i only need a rotation ;)
knekke: i will take a look it can be interrestiong but i'm not sure it's the same problem.
I '(maybe) managed to find a solution for now, by computing two vectors, one for the x rotation, oneother for the y rotation and combining them:
xVector.x = yVector.x*xVector.z/yVector.z
return xVector.normalized()

yes, it's a slightly different problem. I might have a solution to your problem in a couple of minutes

maybe not.... I have to leave now :/

Please don't post the answer mixed with the question. If you found a proper solution please post it below as a real answer.

The angle between a vector and the Z axis and a vector in the right ortho view appears to be such that tan(θ)=y/z.  The angle between a vector and the Z axis in the front ortho view appears to be such that tan(φ)=x/z.
As long as θ and φ aren't going to be π/2 you can pretty easily set z=1 and then y=tan(θ) and x=tan(θ) .  If the π/2 is a possibility you'll want to have code to check for that case and use an alternate formula like tan(π/2-θ) = z/y and similar for φ.
So after following that procedure we have an <x,y,z>, but since you talk about rotations, I assume you have an object with some feature you want to align with this vector.
To accomplish this requires an understanding of quaternions, or you just copy the code from http://web.purplefrog.com/~thoth/blender/python-cookbook/rotate-to-match.html
import bpy

from mathutils import *
from math import *

def compute_rotation(src_vec, dest_vec):

    a = src_vec.normalized()
    b = dest_vec.normalized()

    c = a.cross(b)

    theta = asin(c.magnitude)

    if (c.magnitude>0):
        d = c.normalized()
        st2 = sin(theta/2)
        q = Quaternion( [cos(theta/2), st2*d.x, st2*d.y, st2*d.z] )
    else:
        q = Quaternion( [1,0,0,0] )

    return q

obj = bpy.context.active_object

obj.rotation_quaternion = compute_rotation(Vector([1,1,1]), Vector([1,0,0]))

The src_vec is a vector on the object (it might be the X, Y or Z axis, or some other important feature like an antenna) and dest_vec is the world space vector we want that source vector to be rotated to match.
Another thing to consider is that there are many orientations that are compatible with dest_vec = q*src_vec (just imagine spinning the object around src_vec), but the q calculated by this procedure will have the minimum θ.
To see how messy things can get, read http://web.purplefrog.com/~thoth/blender/python-cookbook/narratives/animate-random-spin.html

Thanks for this answer. Your solution is close to mine but you explanation is more accurate. Actually i use this vector as a z component of a base, and i use them to create à transformation matrix. I can easily find two vectors for x and y based on the z and my other contraints, then i only have to create a transformation matrix with mathutils.Matrix([x,y,z]).transposed().to_4x4().

Creating a transformation matrix reminds me of https://blender.stackexchange.com/a/30809/660

I think a found a solution that looks to work pretty well: I compute two vectors, on for the y rotation and onother rotation. Then I combine them this way:
xVector = V.copy()
xVector.rotate(xRotation)
yVector = V.copy()
yVector.rotate(yRotation)
xVector.x = yVector.x*xVector.z/yVector.z

I'm not sure this solution is correct but the results looks good. The ratio y/z will define the angle between z axis and the vector from x view, and The ratio y/z will define the angle between z axis and the vector from y view. If i define an x value in the x vector with the same x/z ratio as in the y vector, i now have my two angles defined. Is it correct?

Adding my answer to the mix:
from math import *
import mathutils

# Define the angles
x_angle = 20
y_angle = 30

# Get the directions
xdir_x = cos(radians(90-x_angle))
xdir_z = sin(radians(90-x_angle))
xz_vec = mathutils.Vector((xdir_x, 0, xdir_z))

ydir_y = cos(radians(90-y_angle))
ydir_z = sin(radians(90-y_angle))
yz_vec = mathutils.Vector((0, ydir_y, ydir_z))

# Get the normals
xz_normal = xz_vec.cross((0,1,0))
yz_normal = yz_vec.cross((1,0,0))

# The cross product of the normals gives us the final direction vector
dir_vector = -xz_normal.cross(yz_normal)

# And the euler for this vector
rotation = dir_vector.to_track_quat('Z', 'X').to_euler()

# Print the results
print('Direction Vector: %s' %dir_vector)
print('Rotation: %.2f, %.2f, %.2f' %tuple(degrees(a) for a in rotation))


text:
Is there a way to fix these weird faces without adding more polygons?
Imported mesh from Maya over to Blender. The shading and faces are weird.
Here's the blend file, mega.nz/#!N3RTgRwD!b2t7DqLzu3H7MyUrZ5SDdfC8wZW3mngz2LzeHe6jY2E

Here it is in Maya.

Maybe related - https://blender.stackexchange.com/questions/76513/strange-black-shading-cannot-fully-light-mesh-cycles. Not black here but seems the same, mesh with even that amount of faces should be relatively smooth once shading is set to Smooth.

Are you sure shading is set to smooth? You may also want to use the "Triangulate Faces" function to see if that helps.

I tried the Clear Custom Split Normals Data, turning off Auto smoothing, and the triangulate modifier. Shading is on smooth, here it is flat, https://gyazo.com/4c06dc701244220f399bdcda8fc24747

Maybe every face is separated?  Try remove double?  And.. try turning off viewport ambient occlusion?  And if you are in Cycles mode, Cycles do have problem shading low polys up close on screen.

It looks like you have view port ambient occlusion turned on.  From what I can tell the viewport ao doesn't recognize quads and likes to shade the quad's underlying triangle structure.

@LukasValine Woo! Thank you Lukas, that seemed to have been the problem.

While we model using quads, blender always draws to screen using triangles. The current triangulating algorithm for quads always triangulates the same way, while the newer ngon triangulating is more intelligent, see this question for some more insight.
While the vertex order used to make each face could be re-arranged to get a better result, I don't think there is an easy way to do that.
You should find that a subsurf modifier will hide most of the effect you are seeing.


text:
Cycles Render Renders all white
When I render in Cycles it turns into solid white.  I've spent the past 2 hours researching the answers to this online, mostly through this Blender Stack Exchange.
1.) All my layers are turned On
2.) My World is not emitting anything, it's just black. I have my camera facing the model (as you can see in the screenshots).
And after messing with it some.. it now renders in solid static (as seen in screenshots). Trying to upload the file now to tiny upload.. so hopefully during this weekend someone can figure this out for me. Ugh!!.. lol.
Thanks so much!

Make sure you're not accidentally viewing the alpha channel in the UV image editor.  Also, I can't see your screenshots, maybe try uploading them again.

If you want to upload your .blend you could do so here: http://blend-exchange.giantcowfilms.com

Thank you!  Yes, I have it selected to "Color" in the UV image editor. Darn! I forgot to upload them. Then I went to try and upload and says "Can't upload this type of file".

Screenshots uploaded! whoo hoo!  Okay, I'm off for the weekend! Talk to ya throughout, but won't be back to fix this issue till Monday. Cheers~

Make sure the DOF aperture size it set to 0 in your camera settings.

You have DOF enabled but haven't set a focus distance.  Turn off depth of field by setting the aperture size to 0.


text:
Normal baking not working
I'm trying to bake the normal from high poly to a low poly model. I made a cage that perfectly fits outside the high poly but when baking I get weird artifacts that don't look like a ray distance problem (see screenshot).
The baking texture is set to noncolor, ive tried with 32bit as well and there are no intersections. The strange thing is that only a part of my model gets these artifacts, the rest is fine.
I separated the part of the model that doesn't bake correctly so maybe someone can help me understand what i did wrong (the shared file has the same settings I used to bake).

Blend file:

hello, could you please share your object?

hi, yes I'm trying to upload it rn but my connection is slow

Here it is, it was slow cause of the packed bake that was too big, so i removed the image (if u want to recreate it I used 4k non-color 32bit)

Try to bake without cage. If it helps, recreate the cage.

I already tried both those things and the problem was still there, but thanks for the help!

actually not having the cage gets rid of those kind of artifacts but produces others (green ones, look like a ray distance problem because my model has both big shapes and small details, so a cage is definitely needed imo because adjusting the ray distance value never gets rid of the green artifacts completely)

It looks like your cage is too big, it must hit unwanted surfaces. I can't put my finger on where exactly, but if I duplicate your low-poly and fatten it only a bit it will have a much better result