text:
Create a square block extrusion in sculpt?
Newbie here. I am new to Blender, I am wondering is it possible(in sculpting mode), to model a square indent into the object.
Say I have a cylinder or a cube, and I want to extrude a small square region on  one of its surface(you can imagine this to be a building). It has a square window, and the window is slightly out of the building's wall plane. I hope to repeat this effect for every surface, and each surface will have three by three windows. I don't need the window to have perfectly sharp corners. It could be slightly rounded. Thanks for the guidance.

You can use multiple tools to achieve the effect, but I think the easiest is to use a stencil mapped texture with the shape of the window and a Layer brush. The height of the layer brush determines the depth of the effect. For best results, the sculpt plane should be "Area Plane" locked (ticking the lock icon next to the drop down menu).
Here is a rough picture with the settings:

There are several ways to do this, the best is to use a texture as a kind of stencil. Here is a quick example.. (I am using a bolt alpha from Eat3D's excellent free pack.  Additionally, you can find some more lovely free alphas here to play with if need be from Pixologic under INDUSTRIAL.)
If you add the texture as a Brush texture and tweak the settings a bit you can get some nice hard edged extrusions or details on your models.
As I have it below, I have set the brush shape under Curve in the toolshelf to MAX (the flat one) and bumped the brush strength up to a bit to about .350. You can grab the pack and test it to see how it works, basically, the closer you get to white, the more the surface will be extruded so if you mix your shades you can get even more details. In your case, I am assuming a simple one will do so, just an image in the shape of a window with the frame in white or a shade of gray depending on what you need.

I would edit this further but Psy-Fi has some more tips in his answer, you can refer to that for more information.

Yeah in sculpt mode you would have to use either the grab tool or the add clay tool and "extrude" until you get the desired look, then you would have to use the crease and smooth tools to smooth the edges and create those corners if you want them. Another easier way is to instead of sculpt it use edit mode and create loop cuts CTRL + R to out line the shape of the windows. After that take the window "faces" and extrude them inward or out ward. this was my result using the later method and some mirror and array modifyers.

He did ask to do it in sculpt mode. This is a perfectly fine answer, it's just the right answer to the wrong problem. Please update it to match the question.

The first part was in sculpt then the later being in edit mode as an alternative.

Yes, but the focus of your question was on the edit mode part, and he specifically asked for a way to do it in sculpt mode.

Got it, sorry 'bout that. Just trying to provide other options.

That's fine, just make sure to make that point(using headers or lists or something)


text:
What are the not so obvious features of Rigify?
I watched a tutorial which explained that scaling the finger controls would make them curl.
Are there more features like curl by scale in rigify which are not intuitively discoverable  ?

This is a bit broad but can be answered. As it's a custom rig, there are several unique things about it, most of these are powered by simple drivers and constraints.

The main challenges here are: The title is misleading, and there are multiple questions in one question body, which is a bad practice on SE. There should be a single question per post (though "sub-questions" are allowed if they fit within the scope of the original question. Unfortunately the scope here might be a bit too wide for that).

@RolandXor Thanks for your reply, I understood and reduced it to a single question.

This is a really broad question that would be very difficult to answer in a single response. It's also pretty subjective (e.g. for people who have been using rigs in Blender for a long time, scale controls on the fingers are a long-standing convention that doesn't feel alien at all).

I don't think there are any other "hidden features" like the finger curl. The finger curl is the only driver that is generated in the rig.

Let me start by saying that I think that the finger curl trick might have mislead you a bit. As complicated and advanced a mechanism as Rigify is, it's nothing really 'unique' in terms of rigging in Blender and rigging in general and as Fweeb says above..

...for people who have been using rigs in Blender for a long time, scale controls on the
fingers are a long-standing convention that doesn't feel alien at all.

Apart from the finger curl when scaled, there isn't really anything much left to 'discover' per se, it is just a nice collection of common operations etc. and control interfaces to give animators more control and allow people to skip most of the arduous work when rigging as it can be expanded on if needed.
You might know most if not all of these already.. and I won't attempt to explain Rigify in full detail, that would be very difficult to do and is beyond the scope of this question. — However, as a future reference for beginners…

The top (n) or so things that are not so obvious at first glance about Rigify are:
1. This is not the rig you are looking for…

The very first thing is that Rigify is not really the default armature you get when you add it to a scene. To get the full rig, you go to the Armature: Object Data panel and under Rigify Buttons hit Generate. After that, you can just move the default meta-rig to another layer to keep it out of your way.

2. Now you see me, now you don't

Rigify is a complicated mechanism and often times might get in the way of what you are doing, to hide different parts of the rig as they are needed, you can open the Rig Layers group in the Properties panel and toggle the visibility of each layer of controls as needed.

3. FK or IK?

The rig comes ready to be used in any way you want to animate. It has sliders to change between Forward Kinematics and Inverse Kinematics or give you a blend of both and more depending on how you adjust the slider(s) under Properties and or Rig Main Properties as they are presented or made avilable in the Properties panel.

4. Those aren't really bones..

The custom handles you see aren't really bones per se, they are bones with custom shapes and are actually objects that you can modify and by default they are placed on the last layer (layer 20).

These can also be changed using the Custom Shape input box under Display in the Bones panel but it is worth noting that modifying these can lead to problems with your rig later on so be careful.

5. Bits and pieces

You can encode the meta-rig to python code so that you can generate select parts of the rig as needed. Look in the toolshelf under Rigify Dev Tools and experiment with this.

6. Wait.. who's driving?

This is out of the scope of the question but might be useful if you're planning to build your own rig. Rigify makes extensive use of drivers to automate and make certain operations more 'smooth' etc.

At any time, you can poke around and select a bone and if any of the transform panels turn purple (the default color if you haven't changed it) this means that a driver is acting on it. To dig into this, just open the graph editor and open the Drivers view.

It is also worth noting that since Rigify is glued together by scripts and not manually put together for the most part, a lot of these features will be hard to trace and pull apart etc. but can serve as good reference nonetheless.

Most of these explanations are a bit vague and short, it is a bit more indepth than this but this is enough to get someone new to the rig at least a bit more familiar with it… and so as a last note, I would suggest reading up on Bone Constraints, Drivers and Properties.
Also related.. Armature FK/IK toggles

Another little thing is in the event that you use a rigify rig as part of a group that you link into another scene (very common large-project workflow). In that case, it's worth noting that the script that generates rigify's panels and menus is not part of the linked group. You'll need to link that script separately.

@iKlsR Wow thanks for this awesome answer!

Don't forget the snap to buttons for FK and IK.  I found them handy when I was doing some more complicated animations that required the character to change between FK and IK in mid animation. By having both FK and IK control bones in the same location during the key frames, I was able to switch between them with less problems.

source: Stack Exchange

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

sort: votes


text:
How do I make a normal/displacement map when all I have is a photo?
In order to make a rendering look more realistic some additional maps are useful.
The documentation lists: diffuse,specular displacement-maps .
I watched a video tutorial The Secrets of Realistic Texturing which uses a commercial tool.
Are there any alternatives to calculate normal and displacement maps from an image texture, or can this also be achieved by some build-in transformations?
NOTE: As requested, this is related to image-textures that have been downloaded from a site like cgtextures which are image-only and lack of normal- and displacement-maps.

Can you be more specific? - Give some examples at least of other types.

@ideasman42 Thanks you, I added a note. Currently I don't have a specific problem, just want to know how to create those maps.

eh define those maps ?, still not sure what your question is, but this sounds like it may be too vague stack-exchange.
Or the question should be: How do I make a normal/displacement map when all I have is a photo.

I've compiled a list of options when it comes to normal and bump map creation. All that remains is to try few of these out and see which results you like best.
To me, the most advanced of the free solutions is MaPZone 2.6, but I haven't tried any of these so I am not sure.
Or you can try the web based Smart Normal, for very basic normal maps generation.
Another tool is  Knald which offers high quality, accurate height maps generated from a Normal/Derivative or photo-sourced texture.
I didn't include urls, since they can be easily googled.

@Dwelle thank you, excellent way to answer this question.

SSBumpGenerator claims to be OpenSource but on SourceForge you don't get any sources.

I believe it's on their SVN, http://sourceforge.net/p/ssbumpgenerator/svn/HEAD/tree/

Great answer! I'd love if it was updated to reflect which solutions Mac and PC users (or both) have access to - maybe one color on the chart for Mac, one for PC one for both?

Another possible answer might be the Gimp plugin called Insane bump.
To my knowledge it has a Normal, specular, AO, the same as Crazy bump and it's free and open source.
There is also another plugin called Normalmap, which can be installed as .deb gimp-normalmap in Ubuntu.

Just to add, Insane Bump needs gimp normalmap to generate normal maps

answer is invalid

Generally it is much better quality-wise to do custom images based on the desired properties of the surface, using software made specifically for this. For a quick and dirty bump map, blender supports using a colour image as a bump map directly, without conversion to a black and white format. If you want a way to generate a bump/normal map inside blender, you can use baking.
The steps are roughly:

Add a plane mesh, go to edit mode and unwrap it
While still in edit mode and with everything selected go to image editor and add an empty image from the menu Image->New. Enter the dimensions of the colour image you want to convert to normal/bump map. Name your image appropriately.
Add a texture to the material of the plane mesh, go to the Texture Properties tab, Change the tyoe to image, select the image texture that will be converted to bump/normal map, use UV coordinates and turn colour influence to 0 and normal influence to 1.
Go to the Render Properties tab, Bake panel. Now you can choose the format to bake to, either bump or normal (tangent space is usually the preferred space here) and press the big Bake button.
Watch your empty image that was added in step 2 get baked over by the renderer.
Go to image editor again and save the image to a file.

If you have a situation where it's something you can photograph - Then you can go to structure from motion.
I take photos for every 15 degrees of a subject, use ppt-gui or vsfm to convert the photos into a point cloud, meshlab or cloudcompare to convert the point cloud to a high density mesh.
I then take the high density mesh into blender and create a low poly version either using the decimate modifier or by building it. I uv map the low poly version then I bake (using selected to active) normals, ao, vertex color and displacement.
This workflow can take more time, particularly computer time and will require a fairly fast machine. The most labour intensive bit is usually the uv mapping if you are mapping a complex object. It gives you a lot of maps that line up exactly and is quite physically accurate.

The method I use is not exactly "expert" and may yield different results. However, it is easy and free, and produces acceptable results for me. What I do, is make a black and white copy of my image texture, then with GIMP's built in filters, I apply the bump map filter.
You can find this under:
Map→Bump Map.
You can then apply other effects, such as increasing the contrast, to achieve better results. I have used this to generate displacement and normal maps for planets, for instance. It's not necessarily a "professional" method, but it's easy and works well for small scale projects.
Example:

This texture I used to generate a normal map on this asteroid:

Please note that it is not as clear here because the asteroid has an "atmosphere" on top. I also used other (procedural) textures for displacement.

@RolandXor Thanks, I tried it, a nice trick to add some fake structure.

Just to add to the list, even though the question is old. I've used AwesomeBump (https://github.com/kmkolasinski/AwesomeBump) to generate Normal, Specular, Bump and Height (which I guess is Displacement). It can also generate PBR textures.
It's open source under LGPL.

I found a standalone version of insane-bump 2.5 from 2013. There is no documentation but it works: https://sites.google.com/site/ccdsurgeon/download  (not sure this is related to the gimp-plugin). At least my anti virus software says it is clean.

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

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


text:
Report Error - RIGIFY ERROR: Bone 'brow.B.L.004': Input to rig type must be a chain of 2 or more Incorrect armature for type 'stretchy_chain'
Report Error - RIGIFY ERROR: Bone 'brow.B.L.004': Input to rig type must be a chain of 2 or more Incorrect armature for type 'stretchy_chain'
I'm really new to blender and character rigging. I was following closely to a tutorial, or so I thought. Because when I went to generate the rig, I got this (above) error message.
I searched as best as I could to see if anybody had the same or similar problem. While their were a couple that were similar, it wasn't anything that I found helped with my issue.
I wouldn't be surprised if its the most easiest solution or something so obvious....
Thanks in advance!

This error concerns this bone:
In Rigify, each bone that gives you special controllers (when generated) is defined by a specific Rigify type. To see what type a bone has, you can go into pose mode and select the bone you want. In its bone properties, under "Rigify Type", you'll be able to see wich one it is. Here is the rigify type of brow.B.L.004:

Some Rigify types are quite fiddly, and will give you errors if you make a small mistake. In our case, the skin.stretchy_chain type requires you to have at least a chain of 2 or more bones.
The Rig type is applied on brow.B.L.004, that means it is the first bone of the chain. So we must have an other bone after it for the rig type to work.

In rigify's face bones, the brow.B.L.004 bone is followed by the nose.L bone, (the second bone of the chain). This nose bone is supposed to be connected and parented to the brow bone. You probably unparented it, disconnected it or you simply deleted it. Also, the tail of brow.B.L.004 and the head of nose.L must be perfectly aligned (as circled is the screenshot), otherwise you'll get an error.

note also that certain bones tail and head positions need to be exactly the same as their related bones. This becomes an issue when you move the bones around to match a custom face mesh. (using ctrl+S to ove the cursor to the target position and then the bone tails/head is a good way to align everything up correctly)

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


text:
Changing Rotate/Pan modes on the fly. Keymap settings
Worked a long time ago in NX Unigraphhics, and still have some habits from that CAD like switching Rotate/Pan modes on the fly(without releasing middle mouse).
I made this keymap settings.

And it works ok, but not quite right in this scenario of actions
Middle mouse - "moving mouse/check rotating" - pressing SHIFT(not releasing) - "moving mouse/check panning" - release middle mouse(for confirm) - "moving mouse/its still panning" - release SHIFT - "moving mouse/its still rotating".
The main thing is that it starts to rotate and pan without middle mouse pressed.
I just want to know is this a problem, or unknown for me commands are conflicting.
I tried to make additional commands like "CONFIRM - MIDDLE MOUSE - NOTHING" for both modes, hoping that blender will check status for MIDDLE MOUSE as unpressed. But it doesn't work.


text:
issue with edges bevel weight messing up my mesh
i am pretty new to blender (been learning for a couple months) but i am having an issue with the edges bevel weight messing up my mesh. i am watching a video guide for making a car so the modifiers i currently have are the exact same as the guy has, but the issue doesn't happen to him and his mesh looks totally fine.
i thought it was because of the bevel modifier then adding the edges bevel weight but changing/removing it didn't help.
any advice on why this is happening and how i can fix it would be greatly appreciated :)

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


text:
How to apply a Texture to an Object with Blender Python?
I try to combine random 3D Models with random Textures.
I know the results will probably will look sketchy but that is fine.
But now to my problem: It seems like it doesn't work applying a texture to an object in blender python script. There is some problem with my code.
I'm not sure how to apply a texture to an 3D Model/Material.
As example I try to load a texture from a game to a banana 3D Model.
I show you both here:

I load and apply the texture with following code:
def load_texture(file_path, obj, apply=True):
"""
Creates a material, loads a texture and applies it to active material, if apply is true.
"""
# create new material
material = bpy.data.materials.new('My_Awesome_Texture_Material')
material.use_nodes = True

# create texture and apply to material
material_shader = material.node_tree.nodes["Principled BSDF"]
texture = material.node_tree.nodes.new('ShaderNodeTexImage')
texture.image = bpy.data.images.load(file_path)
material.node_tree.links.new(material_shader.inputs['Base Color'], texture.outputs['Color'])

# apply material to object
if apply:
    if len(obj.data.materials) > 0:
        next_material = material
        for i in range(len(obj.data.materials)):
            cache_material = obj.data.materials[i]
            obj.data.materials[i] = next_material
            next_material = cache_material
        obj.data.materials.append(next_material)
    else:
        obj.data.materials.append(material)

return material

And this is the result:

Maybe the scaling/mapping from texture to Model is not right...Does anyone knows how to fix this?
I tries different texture applying methods, like Reapeat, extend and clip, but all results look the same.
The usage of an new material with random properties works fine, but textures not work for me right now.
Version: Blender 4.1
I Tried:

Change material texture by loading an external .png file with Python
https://blenderartists.org/t/assign-image-texture-for-material-in-script/1392848/3
https://stackoverflow.com/questions/75869593/apply-material-and-texture-image-using-python-in-blender-3-4
and more...

I hope anyone can help me :)
Here is my full code:
##############
# This is a Blender Python Script
# Run me in Blender
##############

########################
####### Imports ########
########################
import os
import random
import math
import json

import bpy

# load addons
bpy.ops.preferences.addon_enable(module='io_scene_3ds')
bpy.ops.preferences.addon_enable(module='export_mesh_stl')
bpy.ops.preferences.addon_enable(module='io_scene_obj')

########################
######## Tools #########
########################

def load_texture(file_path, obj, apply=True):
    """
    Creates a material, loads a texture and applies it to active material, if apply is true.
    """
    # create new material
    material = bpy.data.materials.new('My_Awesome_Texture_Material')
    material.use_nodes = True

    # create texture and apply to material
    material_shader = material.node_tree.nodes["Principled BSDF"]
    texture = material.node_tree.nodes.new('ShaderNodeTexImage')
    texture.image = bpy.data.images.load(file_path)
    material.node_tree.links.new(material_shader.inputs['Base Color'], texture.outputs['Color'])

    # apply material to object
    if apply:
        if len(obj.data.materials) > 0:
            next_material = material
            for i in range(len(obj.data.materials)):
                cache_material = obj.data.materials[i]
                obj.data.materials[i] = next_material
                next_material = cache_material
            obj.data.materials.append(next_material)
        else:
            obj.data.materials.append(material)

    return material

def clear_scene(clear_all=False):
    """
    Deletes all objects, but not the Light and Camera Object.
    """
    scene_objects = bpy.context.scene.objects

    for obj in scene_objects:
        if obj.type != 'LIGHT' and obj.type != 'CAMERA':
            bpy.data.objects.remove(obj)

    if clear_all:
        bpy.ops.object.select_all(action="SELECT")
        bpy.ops.object.delete()

        bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)

def import_model(file_path):
    """
    Imports/loads an 3D Model.

    Supported Formats: obj, stl, glb, fbx
    """
    if file_path.endswith(".obj"):
        imported_object = bpy.ops.wm.obj_import(filepath=file_path)
    elif file_path.endswith(".stl"):
        imported_object = bpy.ops.wm.stl_import(filepath=file_path)
    elif file_path.endswith(".glb") or file_path.endswith(".gltf"):
        imported_object = bpy.ops.wm.stl_import(filepath=file_path)
    elif file_path.endswith(".fbx"):
        imported_object =  bpy.ops.import_scene.fbx(filepath=file_path)
    # elif file_path.endswith(".blend"):
    #     imported_object =  load_blend(filepath=file_path)
    else:
        print(f"Failed loading 3D Model -> unknown/unsupported datatype:'{file_path}'\n-------")
        return "TRIGGER_CONTINUE"

    return imported_object

def export_model(filepath, target_format, only_active=False):
    """
    Exports an 3D Model.

    Supported Formats: obj, stl, glb, fbx, blend
    """
    if target_format.lower() == "stl":
        bpy.ops.wm.stl_export(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "obj":
        bpy.ops.export_scene.obj(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "glb" or target_format.lower() == "gltf":
        bpy.ops.export_scene.gltf(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "fbx":
        bpy.ops.export_scene.fbx(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "blend":
        bpy.ops.wm.save_mainfile(filepath=filepath, check_existing=True, use_selection=only_active)
    else:
        print(f"Unsupported datatype for convertation: '{target_format}'")

########################
###### Functions #######
########################

def load_model(model_path, texture_path):
    """
    Tries to load a model and a material/texture file and puts them together.
    """
    clear_scene()

    print(f"Tries to load '{model_path}'...")

    # load object
    import_model(file_path=model_path)
    object = bpy.context.selected_objects[0]

    # create and add material
    print(f"Tries to load texture: '{texture_path}'...")
    texture = load_texture(texture_path, object, apply=True)

    # render scene
    print(f"Tries to render the scene...")
    bpy.ops.render.render(write_still=True)

########################
#Here we run the script#
########################

load_model(model_path="/home/tobia/src/res/stl_models/Banana.stl",
           texture_path="/home/tobia/src/res/textures/texture_00166.png")

You probably need to unwrap the mesh.

The UV from my model was missing to successfull apply a texture to an object/material, the model first have to mapped to 2D.
Following code does this wrapping:
def apply_uv(use_smart=True):
    # Select the object
    obj = bpy.context.object
    bpy.context.view_layer.objects.active = obj
    obj.select_set(True)

    # Switch to edit mode to perform mesh operations
    bpy.ops.object.mode_set(mode='EDIT')

    # Select all mesh elements
    bpy.ops.mesh.select_all(action='SELECT')

    if use_smart:
        # Smart UV unwrap the mesh
        bpy.ops.uv.smart_project(angle_limit=1.15192, margin_method='SCALED', island_margin=0, area_weight=0, correct_aspect=True, scale_to_bounds=False)

    else:
        # Unwrap the mesh
        bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001)

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

    # Access the UV loop layer
    bm = bmesh.new()
    bm.from_mesh(obj.data)
    bm.faces.ensure_lookup_table()
    uv_layer = bm.loops.layers.uv.verify()

    # Update the mesh with the new UV coordinates
    bm.to_mesh(obj.data)
    bm.free()

And than it looks like I wanted:

Here is the complete working code:
##############
# This is a Blender Python Script
# Run me in Blender
##############

########################
####### Imports ########
########################
import os
import random
import math
import json

import bpy
import bmesh

# load addons
bpy.ops.preferences.addon_enable(module='io_scene_3ds')
bpy.ops.preferences.addon_enable(module='export_mesh_stl')
bpy.ops.preferences.addon_enable(module='io_scene_obj')

########################
######## Tools #########
########################

def load_texture(file_path, obj, apply=True):
    """
    Creates a material, loads a texture and applies it to active material, if apply is true.
    """
    # create new material
    material = bpy.data.materials.new('My_Awesome_Texture_Material')
    material.use_nodes = True

    # create texture and apply to material
    material_shader = material.node_tree.nodes["Principled BSDF"]
    texture = material.node_tree.nodes.new('ShaderNodeTexImage')
    texture.image = bpy.data.images.load(file_path)
    material.node_tree.links.new(material_shader.inputs['Base Color'], texture.outputs['Color'])

    # apply material to object
    if apply:
        if len(obj.data.materials) > 0:
            next_material = material
            for i in range(len(obj.data.materials)):
                cache_material = obj.data.materials[i]
                obj.data.materials[i] = next_material
                next_material = cache_material
            obj.data.materials.append(next_material)
        else:
            obj.data.materials.append(material)

    return material

def clear_scene(clear_all=False):
    """
    Deletes all objects, but not the Light and Camera Object.
    """
    scene_objects = bpy.context.scene.objects

    for obj in scene_objects:
        if obj.type != 'LIGHT' and obj.type != 'CAMERA':
            bpy.data.objects.remove(obj)

    if clear_all:
        bpy.ops.object.select_all(action="SELECT")
        bpy.ops.object.delete()

        bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)

def import_model(file_path):
    """
    Imports/loads an 3D Model.

    Supported Formats: obj, stl, glb, fbx
    """
    if file_path.endswith(".obj"):
        imported_object = bpy.ops.wm.obj_import(filepath=file_path)
    elif file_path.endswith(".stl"):
        imported_object = bpy.ops.wm.stl_import(filepath=file_path)
    elif file_path.endswith(".glb") or file_path.endswith(".gltf"):
        imported_object = bpy.ops.wm.stl_import(filepath=file_path)
    elif file_path.endswith(".fbx"):
        imported_object =  bpy.ops.import_scene.fbx(filepath=file_path)
    # elif file_path.endswith(".blend"):
    #     imported_object =  load_blend(filepath=file_path)
    else:
        print(f"Failed loading 3D Model -> unknown/unsupported datatype:'{file_path}'\n-------")
        return "TRIGGER_CONTINUE"

    return imported_object

def export_model(filepath, target_format, only_active=False):
    """
    Exports an 3D Model.

    Supported Formats: obj, stl, glb, fbx, blend
    """
    if target_format.lower() == "stl":
        bpy.ops.wm.stl_export(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "obj":
        bpy.ops.export_scene.obj(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "glb" or target_format.lower() == "gltf":
        bpy.ops.export_scene.gltf(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "fbx":
        bpy.ops.export_scene.fbx(filepath=filepath, check_existing=True, use_selection=only_active)
    elif target_format.lower() == "blend":
        bpy.ops.wm.save_mainfile(filepath=filepath, check_existing=True, use_selection=only_active)
    else:
        print(f"Unsupported datatype for convertation: '{target_format}'")

# new method
def apply_uv(use_smart=True):
    # Select the object
    obj = bpy.context.object
    bpy.context.view_layer.objects.active = obj
    obj.select_set(True)

    # Switch to edit mode to perform mesh operations
    bpy.ops.object.mode_set(mode='EDIT')

    # Select all mesh elements
    bpy.ops.mesh.select_all(action='SELECT')

    if use_smart:
        # Smart UV unwrap the mesh
        bpy.ops.uv.smart_project(angle_limit=1.15192, margin_method='SCALED', island_margin=0, area_weight=0, correct_aspect=True, scale_to_bounds=False)

    else:
        # Unwrap the mesh
        bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001)

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

    # Access the UV loop layer
    bm = bmesh.new()
    bm.from_mesh(obj.data)
    bm.faces.ensure_lookup_table()
    uv_layer = bm.loops.layers.uv.verify()

    # Update the mesh with the new UV coordinates
    bm.to_mesh(obj.data)
    bm.free()

########################
###### Functions #######
########################

def load_model(model_path, texture_path):
    """
    Tries to load a model and a material/texture file and puts them together.
    """
    clear_scene()

    print(f"Tries to load '{model_path}'...")

    # load object
    import_model(file_path=model_path)
    object = bpy.context.selected_objects[0]

    # apply uv
    apply_uv()

    # create and add material
    print(f"Tries to load texture: '{texture_path}'...")
    texture = load_texture(texture_path, object, apply=True)

    # render scene
    print(f"Tries to render the scene...")
    bpy.ops.render.render(write_still=True)

########################
#Here we run the script#
########################

load_model(model_path="/home/tobia/src/res/stl_models/Banana.stl",
           texture_path="/home/tobia/src/res/textures/texture_00166.png")

Thanks to scurest!
And maybe someone has a similiar problem and this helps someone :)


text:
How to Accurately Retrieve Camera's Linear and Angular Velocity per Frame in Blender?
Hello Blender community,
I am a complete beginner with Blender, working on generating synthetic data for a computer vision project that requires the linear and angular velocities of a camera for each frame it renders. My scene is already set up with objects and a camera that follows a predefined path.
To track the camera’s movement, I've attempted to use bpy.data.objects['Camera'].location.copy() in the Python console to fetch the camera's position in order to compute the linear velocity (assuming velocity = change in position/change in time, with time = 1/FPS). However, this method returns the same position for every frame, which doesn’t seem correct.
Could someone advise me on what I might be doing wrong? How can I ensure Blender updates the frame and fetches the new position of the camera for each frame in my script? Additionally, any tips on how to calculate the angular velocity would be greatly appreciated.
Thank you in advance for your help!


text:
Shader to render Flow map/Directional Map
I am creating a pipeline to render all needed maps to create haircards and I am missing the directional/flow map from hairs. Basically what I need is a material to override the render in cycles that can render the direction of the hairs. I have this shader in Maya that does exactly that, but I have had not success on my own trying to replicate it in Blender.
The shader comes from this page where you can see what is the purpose of it for rendering realtime hair. Just scroll down there a bit and there are some visual examples. https://shuma.artstation.com/projects/L22Z3P

Thanks so much


text:
Masking for sculpting through edit mode
When I am sculpting in dynamic topology I can hide part of my mesh, and it not only works as a 100% mask, but it also hides this part of mesh in dynatopo as well. I find it extremely useful when I sculpt.
Is it possible to achieve something similar with multirez? I would like to be able to achieve masking either through vertex weights or selection. In many cases it would give more precise mask than drawing it in sculpting mode.

The short answer is no.
While in edit mode you can hide individual vertices, which also remain hidden in sculpt mode. Dynamic topology respects these hidden vertices as it is working directly with the mesh you have partly hidden.
The multires modifier works differently as it creates new vertices that are stored within the modifier, it isn't changing the existing mesh, therefore the multires doesn't hide vertices generated around the original vertices you have hidden.
When sculpting you have several options to adjust visibility of your mesh.

AltB to make only a section of your model visible
H to hide sections of you mesh
ShiftH to unhide sections of your mesh
Use a Mask brush M to paint out parts that you don't want to sculpt on
Hide parts that have been masked out with mask brush Hide/Mask->Hide Masked

Using dynamic topology or multires modifier has no effect on these methods, they are always available.

I found a work around to use vertices as a mask for multirez. In this example I wanted to keep a surface perfectly flat:

I created a vertex group which included all my flat surface.
I added multirez modifier to the model and subdivided it a few times
I made a copy of the object and uplied modifier
in the copy I went to edit, hid the selected by the group vertices
Sculpted right at the edge -- none of the hidden vertices were affected
Selected both copy and original (original last)
Used Reshape button to copy new geometry from the copy.


text:
Blender rigify problems
I'm new to blender and am trying to attach rigify to my model, but it is not working. When ever I attach the mess to the rig weird things happen, I can't see all of the mess and my model is all messed up. Also, when I take bind to vertex groups off in the armature modifier the model goes back to normal. But, then i cant animate it! This is what happens:

Rigify problems can only be solved with the help of blend file.
Anyway, Before parenting your mesh to armature, make sure that rotation, location and scale is applied to the mesh(Ctrl+A show the menu for it).
Then apply your armature.

violentmonk it didnt work


text:
Object in pose mode does not translate
I am doing this super tutorial (NLA editor), in which we animate an object using armatures.
As mentioned in the image below (23:23 in video), I try to translate the object to create some keyframes for the pelvis. I select the pelvis and I move it by hitting G, but I can't see the translation. However, we can remark that the dx, dy, and dz are changing!

I have to deconnect pelvis from other armatures

As you don't appear have any constraints, I would look at the locks under the Transform Locks panel.


text:
How to fix a 6 point vertex
I have a character I am modelling and I'm having a little trouble around the mouth. Somehow I've managed to get a 6 point vertex at both corners of the mouth. I know I should resolve this somehow, but I'm not sure what I should do.
I've tried merging the vertices on the other end (the 2 red circles) but that didn't fix it.

What step should I take from here to resolve this?

This is odd, merging those two verts should fix the problem. Perhaps the surrounding geometry is too skewed and far apart.

Could I just ask, what's so bad about a 6 point vertex?

@iKlsR - RE your first comment, I does reduce the points from 6 to 5, but from there I still don't know.

@DavidS.- From everything I've seen in tuorials, a point like this is bad practice. I'm trying to clean up my object and have everything in quads.

There are some great resources out there (non-specific to Blender) about how to solve these kinds of problems. I'd recommend looking for some facial modeling tutes that talk about topology specifically.
To answer your question, though, you will have to have a tri or a 5-point vertex :-/ It's a veritable law of facial modeling and there's great debate (apparently) on where the unavoidable tris and 5's should go.
In this case, you'll probably want to make a face out of those three vertices you have circled, to make a tri. This will give you an edge loop that goes around the mouth, which is highly desirable. The debate usually surrounds how far away from the lips that tri should be. It's usually helpful to put the tri somewhere that it will mostly be flat, and won't distort very much. If it's small enough, it might not matter.

Thanks Matt, I ended up joining those right 2 vertices and adding some more edges to make the corner of the mouth more clean. I didn't get rid of the 5 pointer, but at least the topography is cleaner.

Cool! I finally found one of the tutes that was particularly helpful to me: http://www.3dtotal.com/index_tutorial_detailed.php?id=858#.Up5IgcSkpN4
Good luck!


text:
Cycles OpenCL on a OS X?
I'm trying to get Blender working with OpenCL on a Mac but I get errors during the run (it tries to do compilation first and that fails).

Could you copy/paste the specific error to your answer?

ERROR when running on a NVIDIA GPU
[~]$CYCLES_OPENCL_TEST=all ~/Downloads/Blender/blender.app/Contents/MacOS/blender
Device init success
Compiling OpenCL kernel ...
Build flags:
OpenCL error (GeForce GT 650M): [CL_DEVICE_NOT_AVAILABLE] : OpenCL Error : Error: Build Program driver returned (10007)
OpenCL error (GeForce GT 650M): OpenCL Warning : clBuildProgram failed: could not build program for 0x1022700 (GeForce GT 650M) (err:-2)
OpenCL error (GeForce GT 650M): [CL_BUILD_ERROR] : OpenCL Build Error : Compiler build log:
Error getting function data from server

ERROR when running on an Intel Integrated GPU
Device init success
Compiling OpenCL kernel ...
Build flags:
OpenCL error (HD Graphics 4000): [CL_DEVICE_NOT_AVAILABLE] : OpenCL Error : Error: Build Program driver returned (10015)
OpenCL error (HD Graphics 4000): OpenCL Warning : clBuildProgram failed: could not build program for 0x1024400 (HD Graphics 4000) (err:-2)
OpenCL error (HD Graphics 4000): [CL_BUILD_ERROR] : OpenCL Build Error : Compiler build log:
Compile Server Error.
OpenCL kernel build output:
Compile Server Error.
OpenCL build failed: errors in console

I already ran clInfo on my machine to check if the OpenCL runtimes are working, and clInfo works fine. Also, other apps like LuxRenderer works fine using OpenCL

I m using Blender v2.75a


text:
Lighting parameters to render interior architectural scene?
I'm rendering some indoor architecture, and I'm having trouble with the texture color, because it changes a lot depending on the HDRI I use. I would like to know what the setup of lights is recommended for the so that the textures do not change color as much.

What do you mean by "the colors change a lot depending on the lighting"? That's sort of what they're supposed to do. Are you asking how to get even lighting?

the problem is that, for example, if an oak is of a certain color in the texture image, must be the same color / tone in the render appearance changes depending on the hdr image of background I use.
I use hdr in blender cycles by improving render times and make renders cleaner, in my experience.

if you really want to go for a specific texture color tone, try setting your HDR image to a single one and then adjust the colors of your textures manually (nodes) while keeping a look on the realtime cycles viewport render. If you change the HDR of course you have to redo the process.
Another way would be to be sure your original texture's color has not been affected by colored light before you loaded it into blender.(e.g you took a photo of of your oak furniture wood while having a light turned on that has a yellowish tone and used the image as a texture, resulting in a weird appearance in your render).


text:
How to copy animation attributes to multiple objects?
Very basic question here, I am afraid.
I have hundreds of shattered pieces of a mesh and I am trying to animate their visibility over the scene.
How can I animate the visibility and render visibility parameter for one piece, then copy/transfer to all the others?

Your objects are already in a group right? If yes, the answers of this: http://blender.stackexchange.com/questions/7335/cannot-keyframe-visibility-in-outliner-groups-view are maybe helpful. Also related: http://blender.stackexchange.com/questions/16132/python-stop-motion-insert-keyframe

I was hoping for a very "handy" solution like a "copy animation" or something similar. Can't figure out why it's not possible to simply copy and paste one f-curve from one obj to others

Ahh, ok. Try to create a sample object, animate it, select all desired objects (last one should be the sample object) and press Ctrl + L > Animation Data. I can not test it at the moment, but it could work :)

Poor 23: Perfect! It works!
thank you so much!!

Link the Animation Data of the active object to the other selected objects via Make Links menu:

Create an Empty (or every other type of object) and animate it (according to the scene)
Select all desired objects and finally the Empty to make it the active object
Press Ctrl+L and select Animation Data

Object visibility animation
Note: Since all those objects now share a single Action datablock you can update the animation on any one of the objects and the change will be shared by all the other objects.  If in the future you need to be able to edit the animation of one without affecting all the others, you can use the N-panel pop-out of the NLA editor, or use the Dope Sheet's Action Editor mode and click the Make Single User button (this will make a copy of the action so it is not shared with the others).

Great and simple way to solve it.
Thanks so much again

The reason this works is that after you perform the Make Links operation all those objects share a single Action datablock.  I would not say that it is "driven by one Empty" because you can remove that Empty and the action still exists and is shared.  Changes to that action will be shared by all the objects.  The fact that they are shared is not entirely obvious because the [n] button to make a single-user copy is only illustrated in some less-used UI elements such as the N-panel pop-out of the NLA editor, and in the footer of the Dope Sheet's Action Editor mode.

Is there a chance to limit the link to just visibilty animation data? I have multiple properties animated but just want to link the visibility.

Consider.
A driver.
In the image below a parent object visibility drives another.

The purple render icon indicates a driver is active

This menu show how one can copy and paste a driver. Earlier you would see create driver.

Thank you for this also very usefull information. But i think that the solution from Poor23 is the simplest one.
Use CTRL + L -> Animation data
(sorry for my basic English)


text:
How do I use CTRL-R to cut all the way through an object, not just one face?
Can you please tell me if there is a handy shortcut or hotkey using CtrlR or the knife tool to cut ALL the way through an object and not just it's face? I want to make a simple cut to make the tape follow the form of the bottle.

Could you explain why loop cut (Ctrl+R) doesn't work? I'm not quite sure what you're asking.

If the loop cut will not cut all the way through an object, one thing to look for is nonconforming geometry in the path of the loop cut, that is to say that the loop cut is encountering a trianglular face, an n-gon, or the edge of the geometry..

The knife tool will work in this situation. After pressing K, hit Z, which will put it in cut through mode.

Bingo! Knife / Z  was the perfect solution - Thank you.


text:
How to loop an animation in BGE?
I am trying to make a walking animation for my character in BGE, but I can't figure out to duplicate or loop the animation. This is so I can than make the animation "loop end" when you hold down the up arrow to make the animation play.

have a look at this post: http://blender.stackexchange.com/questions/1860/how-can-i-copy-all-selected-keyframes

Also see: How may I create a continuously looping animation?

Update:
If this answer seems out of place, the original question was "How do I Duplicate Keyframes?"

Probably the easiest way is to the Dope Sheet editor. There are several ways to get there:

Click the icon on the bottom left corner of the 3D view and select Dope Sheet

Click on the dropdown that says Default on the Info bar, and select Animation. (Or press CtrlLeft Arrow twice)

This will take you to the Animation layout, with a 3D view, Graph editor, and Dope sheet.

From the Dope sheet or the Graph editor, select keyframes, and press ShiftD to duplicate.
Looping in the BGE:
Once you have an animation that ends where it starts, you can make it loop in the Game Engine with Logic Bricks:

Go to the Game logic editor (CtrlRight Arrow)
Add a Keyboard Sensor (Add sensor > keyboard) and set the key by pressing the button next to the word Key.
Add an Action actuator (Add actuator > Action) and set the Action value to your walk animation, set the end value to the last frame of your animation, and set the Action playback type to Loop End.
Connect the logic bricks by dragging the dot next to the Sensor to the dot next to the Actuator. An And Controller should be automatically created between them:


text:
Not render sky texture?
I'm using a sky texture for environmental lightning. It gets rendered as background when I do that.
Can I prevent it from rendering, but still use it for environmental lightning?

Related, Can Blender render pngs with the background transparent?.

Blender Internal:
Method 1:
You could disable Sky in Properties > Render Layers > Layer:

With Sky enabled:

With Sky disabled:

Method 2:
Another way is to set the Alpha to Transparent in Render settings > Shading:

This will give the same result as disabling Sky in Render layers > Layers.
Cycles:
For cycles you could set the Film to Transparent in Render settings > Film:

With Transparent disabled:

With Transparent enabled:

Cycles
In Cycles can do that by using the Light Path node set to Is Camera Ray (You have to invert it otherwise it renders without affecting the lighting of the scene. The inverse of what you want.):

Blender Internal
In Blender internal, you have to set the alpha to the sky, then you can put anything you want into the background. To render the sky as alpha:

Under the Shading tab of the Render panel, set alpha to Transparent.
Under the Output tab of the Render panel, set Output to PNG with RGBA
Render.

In the compositor, use the Mix node to add a background color/image:
.
Before:

After:


text:
Problem when exporting from Blender to Unity 3D?
I'm having a problem when trying to import my character to the Unity Engine. It gives me message:
Unable to open Assets/untitled.fbx: Check external application preferences
Can anyone please tell my what's wrong and how to fix it?
I followed the steps from a tutorial I watched: I exported my character as a .fbx file and unchecked Include Default Take, but it doesn't work.

It's an issue with the export itself. Try exporting it to a different type (unity supports .blends, so you can simply drag and drop a .blend into the editor).

@CharlesL Thanks a lot it solved my issue :)

The Blender exporters sometimes don't work perfectly. However, Unity supports .blend files, so you can simply drag and drop the .blend file into the Unity project.


text:
How can I simulate Real camera "white balance" parameter in KELVINs
There is some presets in Color Management tab under "look" setting or via curves, but no custom setting that can bet set up with kelvins.

'Looks' is meant to simulate the way different films respond to light, not quite the same as white balance.
To render lights at different colour temperature, you can use the 'Blackbody' material node to convert a Kelvins Temperature to an RGB colour:


text:
How to use bmesh.ops.transform?
I could not find an example for the Bmesh function:
bmesh.ops.transform(bm, matrix = matrix, space, verts_extrude_b1)

What is the matrix argument and what do you pass it?

bmesh.ops.transform() expects a 3x3 rotation matrix or 4x4 transformation matrix each for matrix and space.

matrix specifies the desired transformation, which can be anything with a 4x4 matrix (translation, rotation, scaling, skewing, mirroring etc.).
space specifies the space in which this transformation is supposed to happen in. If not specified, the transformation will happen in local space (object space). If you give it the object's matrix_world, the transformation will happen in global space (world space). But you can give it any desired space if necessary (e.g. to rotate around an arbitrary point in space instead of the object's origin).

Simple example:
Translation in local and global space of an rotated object

Mesh with no transformation applied yet. The object is rotated by 45° around X.
Translate mesh 1 unit up on Z-axis in local space:bmesh.ops.transform(bm, matrix=Matrix.Translation((0,0,1)), verts=bm.verts)
Same as 1.
Translate mesh 1 unit up on Z-axis, but using matrix_world of the object to perform the transformation in global space:bmesh.ops.transform(bm, matrix=Matrix.Translation((0,0,1)), space=bpy.context.object.matrix_world, verts=bm.verts)

Giving a space-matrix is the same as multiplying the inverse of the transformation space matrix by the transformation matrix and the transformation space matrix:
matrix_world = bpy.context.object.matrix_world
bmesh.ops.transform(bm, matrix=matrix_world.inverted() * Matrix.Translation((0,0,1)) * matrix_world, verts=bm.verts)

Matrix tutorial:
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/

it would appear that the command has been modified !

bmesh.ops.transform(bm, matrix, space, verts)¶ and now need to add space inside the command - now im tryng to make a new primitive and the space ob does not exist yet so how do u deal with that ? thanks happy bl

I have no idea what you mean. If you don't need a certain transformation space, leave it out.

I'm making a new primitive with Bmesh and need to transform some verts unless there is another command to do it   looks to me that the examples given are for existing ob not while making a new primitive !  thanks

It has nothing to do with objects or meshes, existing or not-yet-existing. Bmesh operations are solely performed on bmesh objects, or rather a subset of its geometrical elements - whatever you pass to the bmesh op.

A matrix is a 2dimensional array (often 4x4) of values that contains the information needed to perform a transform. One matrix can combine location, rotation and scale information to be applied to an object.
Most of the matrix functions are in mathutils. This page should get you started.

I know how to use the matrix part

but wondering the other one for Space var! what is it how do u set it up


text:
How to change value of object data property by using python script?
I import a texts as an svg file into Blender. I then need to extrude and add a bevel into it. How can I do this with a python script?

Assuming you want to add extrude/bevel to you Curve object :
Select your curves and run:
import bpy

obs = bpy.context.selected_objects

for ob in obs:
    if ob.type == 'CURVE':
        curve = ob.data
        curve.dimensions = "2D"
        curve.offset = 0            # set offset value
        curve.extrude = 0           # set extrude value
        curve.bevel_depth = 0       # set bevel depth value
        curve.bevel_resolution = 0  # set bevel resolution


text:
ATI Radeon HD 7770 no GPU rendering?
So I don't have an option to turn on GPU rendering in settings. I only have the option for CPU rendering.
Here's my specs:

ATI Radeon HD 7770 1GB  GDDR5 1GH
AMD Phenom II 4x 960T 3GHz
4Gb DDR3 1600MHz RAM

My GPU driver is version 13.9.
I see people running fine with this GPU, but for some reason I don't have an option to turn it on.
I need to deliver my design tomorrow so I need this fast and CPU just can't render it that fast.
I'm running Blender 2.69 on Windows 8.1.

Can you link to some pages that show this GPU rendering? AFAIK OpenCL doesn't work yet with cycles, see this wiki page for more information on why.

This question is too localized to specific hardware/configuration: see, http://meta.blender.stackexchange.com/questions/1/what-questions-should-be-definitely-off-topic There is lots of discussion & info on ATI/cycles compatibility on blenderartists.

OpenCL isn't fully supported yet (which is what AMD/ATI cards use to render):

Cycles has two GPU rendering modes: through CUDA, which is the
  preferred method for NVidia graphics cards; and OpenCL, which is
  intended to support rendering on AMD/ATI graphics cards. The
  implementation of OpenCL is only in an experimental stage and disabled
  in official builds. (source)

You could try to find a build on GraphicAll, but there is no guarantee it'll work.
I would recommend just rendering it on CPU. If you are really pressed for time, there are a few things you can do to speed things up:

Set the size of the tiles lower (Render Tab > Performance). The CPU renders faster if the tiles are smaller (GPU renders faster on bigger tiles).
Set the threads to fixed and set them as high as possible (Render Tab > Performance). This will make Blender use more threads which will speed up the render.
Turn the samples down. It's fairly easy to remove a few fireflies later on in compositing, and will speed up your render time a lot.

I'll try it, I know it's experimental but I see people running those GPUs fine, I'll try the stuff, but in graphicsall does OSL stand for openCL or what?

No, OSL stands for Open Shading Language. I did a quick search and I think this one should work (it says it supports OpenCL): http://graphicall.org/110 let me know if it doesn't.

Doesn't work, I've tried your suggestions but it's all still taking hours for a simple object with simple lighting, I'm trying to run Ubuntu now as I think it might be the problem with Win 8


text:
Importing UV coordinates
I'm currently writing an import script/addon.
The file format is one vertex per line: x, y, z, u, v
With 3 lines for each triangle (no quads).
So far I've got vertex's, edges and faces all importing correctly.
Now I just need to import the UV coordinates for each vertex.
However I'm having trouble trying to find a way to do this.
The best result so far was copying code from the UV operator template, which gave me a UV Map, but it puts the whole model at one point.

You'll probably find looking at other import scripts helpful - in the obj script I see me.tessface_uv_textures.new() blender_tface = me.tessface_uv_textures[0].data[i] and blender_tface.uv1 = verts_tex[face_vert_tex_indices[0]]

I posted an example on blenderartists.org, which assumes you use polys/loops for your mesh import: Importing UV coordinates

@CoDEmanX this is a rather good question. perhaps your post on BA could be summarized here.


text:
Vertex slide past edge limit?
The first Vertex Slide tool took an additional click, but you could push the vertex beyond the end of the edge. Is there a setting or method to achieve that with 2.68?
The old method of placing the cursor at the opposite vertex and scale away from it is wonderfully nostalgic, but a bit time consuming.

Yes, by using the Clamp setting.
Access by holding Alt, or toggle with C. This allows you to slide past the (0-1) limit and also prevents switching to slide along other edges then the ones currently selected.
This information is available in the header text during vertex slide.

Just wonderful. That's how a tool should feel. I must admit that I hardly ever look in the header when the action is somewhere else.


text:
How to change the Camera mesh?
Is it possible to change the camera in the 3d-viewport to something a little more camera-ish. For example in maya the camera looks like this:

Can this be done with python scripting?

You can overlay the 3D Viewport using a draw handler.
Use 'PRE_VIEW' to have it in world space behind everything else, 'POST_VIEW' for world space like a real object (depth test). 'POST_PIXEL' is screen-space on top of everything else, but requires 2D coordinates.
You would need to hide the real camera however, which is drawn by C code - maybe put it on another layer or simply hide it? Note that you can't move the camera while it's hidden.
Proof of concept:
import bpy
import bgl
import blf
from mathutils import Vector

bbox_normal = ((-1.0, -1.0, -1.0), (-1.0, -1.0, 1.0), (-1.0, 1.0, 1.0), (-1.0, 1.0, -1.0), (1.0, -1.0, -1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 1.0, -1.0))

def draw_callback_px(self, context):
    if context.scene.camera is None:
        return

    font_id = 0  # XXX, need to find out how best to get this.

    # 50% alpha, 2 pixel width line
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 0.0, 0.0, 0.5)
    bgl.glLineWidth(2)

    bbox = [context.scene.camera.matrix_world * Vector(x) for x in bbox_normal]

    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex3f(*bbox[0])
    bgl.glVertex3f(*bbox[1])
    bgl.glVertex3f(*bbox[2])
    bgl.glVertex3f(*bbox[3])
    bgl.glVertex3f(*bbox[0])
    bgl.glVertex3f(*bbox[4])
    bgl.glVertex3f(*bbox[5])
    bgl.glVertex3f(*bbox[6])
    bgl.glVertex3f(*bbox[7])
    bgl.glVertex3f(*bbox[4])
    bgl.glEnd()

    bgl.glBegin(bgl.GL_LINES)
    bgl.glVertex3f(*bbox[1])
    bgl.glVertex3f(*bbox[5])
    bgl.glVertex3f(*bbox[2])
    bgl.glVertex3f(*bbox[6])
    bgl.glVertex3f(*bbox[3])
    bgl.glVertex3f(*bbox[7])
    bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

class ModalDrawOperator(bpy.types.Operator):
    """Draw a line with the mouse"""
    bl_idname = "view3d.modal_operator"
    bl_label = "Simple Modal View3D Operator"

    def modal(self, context, event):
        context.area.tag_redraw()

        if event.type == 'ESC':
            bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
            return {'CANCELLED'}

        return {'PASS_THROUGH'}

    def invoke(self, context, event):
        if context.area.type == 'VIEW_3D':
            # the arguments we pass the the callback
            args = (self, context)
            # Add the region OpenGL drawing callback
            # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
            self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'PRE_VIEW')
            if context.scene.camera:
                context.scene.camera.hide = True
            context.window_manager.modal_handler_add(self)
            return {'RUNNING_MODAL'}
        else:
            self.report({'WARNING'}, "View3D not found, cannot run operator")
            return {'CANCELLED'}

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

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

if __name__ == "__main__":
    register()

    for area in bpy.context.screen.areas:
        if area.type == 'VIEW_3D':
            ctx = bpy.context.copy()
            ctx['area'] = area
            bpy.ops.view3d.modal_operator(ctx, 'INVOKE_DEFAULT')
            break

To draw the box on top of everything else (like X-ray):
from bpy_extras.view3d_utils import location_3d_to_region_2d

# ...

    bbox = []
    region = context.region
    rv3d = context.space_data.region_3d
    for x in bbox_normal:
        coord = context.scene.camera.matrix_world * Vector(x)
        bbox.append(tuple(map(round, location_3d_to_region_2d(region, rv3d, coord))))

    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2i(*bbox[0]) # must be 2i for 2D integer values!

    # ...

For me POST_VIEW acts normally (visible when in front of objects, and occluded when behind objects). PRE_VIEW is always occluded, even when in front of objects. POST_PIXEL seems to be invisible..

You're right, PRE_VIEW is behind all objects, POST_VIEW is like a real object. For POST_PIXEL you need 2D region coords. See my edit above.

I see that the only way to get exactly what I would like would be writing some c++ code. However, with some modification this could be pretty close. The actual camera could be the lens(witch would allow the user to select the camera) and the 'body' would be added on. The only thing remaining is to allow the user to select the 'body' of the camera and have the camera object be selected. Perhaps this could be made into an add-on.

You can make objects cameras, so you could model a camera mesh and set it as the camera with Ctrl0 (Numpad). If you delete all the faces in edit mode (X > Only Faces), it won't show up in a render, but will still show up as a wireframe in the viewport.

In addition to not having the camera settings, this doesn't seem to work for rendering (cycles renders transparent images and BI spews artifacts which look a bit like z-fighting everywhere), but perhaps you could do something with parenting a hidden camera to a custom object, so moving the object would move the camera, but a normal camera is still used? Perhaps with some kind of two way constraint so that moving the camera also moves the custom object?

This feature is (intentionally) not supported.
If you want to so this you could make a mesh a parent/child of the camera, or use some OpenGL tricks, but to change this you really would have to change Blender's source code.


text:
Creating a curved rectangle on outside of a sphere?
I'm having trouble finding a way to create a rectangular mesh that sits on the outside of a sphere (but takes the shape of the sphere).
Can someone lead me in the right direction?

can you add an image of what you want to achieve ?

Do you mean like this? http://puu.sh/5QEtZ.png Or this? http://puu.sh/5QEzT.png

It sounds like you want to do something like this:

To model that:

Add a plane (ShiftA > Add > Mesh > Plane).

Give it some extra geometry with a Simple Subdivision surface modifier:

Add a shrink wrap modifier and select the target object in the Target input box:

Add a Solidify modifier to give it some thickness:

And you get:

Seems like an unnecessary lot of work if the plane is going to take on the shape/curvature of the sphere. Why not just duplicate a part of the sphere, extrude and separate.

@iKlsR, this technique is more flexible and allows you to position the plane wherever you want on the sphere.

I agree with @iKlsR, because you can still position the plane as you wish, if you set the plane's center the same as the sphere's center, then use Rotate tool.

@Polosson, good point, but you can't shift it to a non centered position. i.e. http://puu.sh/5QMYc.png
Even so, there are multiple ways to do it. iKlsR or Polosson, could you post an answer outlining the other technique?

Thank you, this is exactly what I am looking for.  Cheers!


text:
How to disable the automatic UV stretching after an image size is changed?
I wanted to ask, if there is a way to disable the automatic UV stretching after an image size got changed?

Normally, it is not likely to happen. You need to learn more about how the UV coordinate space works. However, you can correct it by manually scale it down to the old proportion if you really want to keep the aspect ratio of that UV:
For example, let's say the old image resolution is 1000px * 1000px, and the new resolution is 500px * 1600px:

First, calculate two ratios: Rw={image_width_old}/{image_width_new} and Rh={image_height_old}/{image_height_new}. In this case, Rw=1000/500=2, and Rh=1000/1600=0.625.
Press A to select all UV elements, and SX2Enter, then SY0.625Enter. Done.

Furthermore, if you just simply unwrap it directly by some of the unwrap methods listed in the U menu (e.g. Project From View), then you can also consider do that again after switching to a different image, instead.
I'm sure this can also be done by scripting to make it semi-automatic, at least. So, welcome anyone who know the scripting version of this method and edit my answer.

Unwrapping again wont do anything, the same UV-coordinates will be the result.

@Gunslinger As I said, such as Project From View, which will certainly do something. :)

ah that is making the process easier :) many thanks.
I tried to fix it with the snap to pixels mode and that process was taking a lot of time.

@LeonCheung I did a plain unwrap of a cube and assigned a 500x1024 texture. UV looks stretched. Tries unwrap again, UV still looks stretched. Tries project form view, UV still looks stretched. I might be missing something. There is a checkbox "Correct aspect" but it doesn't do the thing I expect. Can you provide an example?

While Leon's answer will work, he also hints that you need to understand how UV coordinates work, or you're going to continue having this same problem.
Short of explaining UVs, I can offer you a better answer. The main cause of the problem is that your test texture is not the same aspect ratio as your final texture. If your test texture is the same aspect ratio (not necessarily the same resolution, but that would also work) as your real texture, then you can swap between your test texture and your final texture without having to adjust anything at all.
The main reason I'm interested in offering an addition solution is that there's a REASON it works this way. If you circumvent that reason, you loose the benefits that come along with it. E.g. Leon's answer doesn't do you much good if you spent 3 hours using the test texture to manually tweak the UV layout (which is a great idea, and you should keep using the test texture). If you then have to re-unwrap for use with the real texture, you've just lost all that work. Even manually scaling it is imprecise, at best. However, if your aspect ratios are the same, then you can change from one texture to the other, without having to adjust at all, because it automatically scales to the size of the new texture ;-) Which is why it's a feature...


text:
How to get vertex normals from a shape-key in Python?
I'm trying to create an exporter for a format, which includes shape key support. This format requires both vertex coordinates and normals to be specified. This should be logical, because the vertex selected on the image below won't have the same normals:

Comparing it to this one:

But I actually haven't found any way to export shape key normals. Both Bmesh Vertex and ShapeKey Vertex only store the coordinates.
Is there any way to get them?

The only way I can think of is to use Object.to_mesh() and read normals from this temp mesh datablock, before freeing it (see also the doc):
me = my_ob.to_mesh(scene, True, 'Render', False, False)
for v in me.vertices:
    print(v.normal)
bpy.data.meshes.remove(me)

Quite obviously, you need to set the influence of your shape key accordingly first.

Blender isn't storing these normals for each shape key, so its not simply a matter of accessing some data.
While you could calculate them yourself, this isn't very convenient.
Temporary Mesh

Pin the shape key so its active an no others are taken into account.
Read the mesh using the Object.to_mesh method.
Read the normals from the mesh.
Remove the mesh.

Existing Mesh

(optionally) store the vertex coordinates.
temporarily apply the shape-key to the mesh.
calculate the normals.
read them from the mesh (can store how you like, but be sure to copy them so as not to hold a reference to the original mesh data).
restore the original coordinates and optionally re-calculate normals again(though this could be postponed until after you're done with all of the shape-keys).


text:
How to install Blender on OS X (Blender directories?)
I need help installing Blender on OS X. I unzipped the file, dragged the folder to the Applications folder, ran Blender, opened User Preferences, went to the directories setup (File tab), but there were no directories listed. I looked in the manual, which referenced a folder which is not on my system, or, if it is, I cannot find it. Then, I read that I have to create each directory, but I don’t know where to create them.

TL:DR; don't worry about those, you don't need them.

You don't need to install any directories. If you're looking for where the scripts, config and cache folders are, they're in the Application Support folder under your user account directory.

/Users/$USER/Library/Application
  Support/Blender/2.74/cache
/Users/$USER/Library/Application
  Support/Blender/2.74/config
/Users/$USER/Library/Application
  Support/Blender/2.74/scripts

The cache folder is where the BVH cache files are saved, and you can sometimes free up quite a lot of space by deleting them.
The config folder is where your startup and userpref files are kept.
The scripts/addons folder is where all your installed addons will be.
There will be separate folder for each version of Blender under Application Support/Blender.
If you're looking for Scripts/Addons/Presets/Modules that come with the Blender install, you have to look inside the Blender.app file. On a Mac, the application appears as a single file, but it's actually a folder with files within it.
If you right click on the Blender.app file, and choose Show Package Contents, you'll see a Contents folder. Open that and you'll see a number of files and folders. The scripts and presets are in the Resources folder.
The file hierarchy is like this:
Blender 2.74.app
+--Contents
   +--Resources
      +--2.74
         +--datafiles
         +--python
         +--scripts

Blender has specific places that it looks for addons and config files and stores temporary files, you don't need to configure these locations.
As described in the manual most of the File Paths that can be configured in the preferences are "default search paths" which means they are the folder that will be displayed in the file browser when you choose to open a file of that type. For example if you set Fonts to desktop/MyFonts then when you click "load a new font button" in a text object, the file browser will start in your MyFonts folder,
Blender will not create these folders for you and you can create them anywhere that is convenient for you or choose any existing folder for each one.


text:
Gray cone obscuring/clipping the 3D Viewport
When looking at my objects in 3d view I'm seeing a gray cone that seems to be hiding other objects.
Can anyone help me turn this off and explain what it is please.
Screenshots attached.

It looks like a stray object. Mind uploading the .blend to PasteAll, http://www.pasteall.org/blend/, and posting it here?

Here you go http://www.pasteall.org/blend/32799

You somehow enabled the clipping region (or clipping border). It's created in 2D, but projects into 3D, thus it looks like a cone from certain angles.
Disable it by clicking View > View Region> Clipping Region... in 3D View header, or press AltB

Thanks CoDEmanX that did it. Think I'd been trying for select render border (Ctrl+B) and hit Clipping Border instead.

If you draw the border in a perspective view, it will actually be a cone.


text:
Can you scale the scope of the Proportional Editing without a 3 button mouse?
Im trying to use Proportional Editing.
I don't have a 3 button mouse.
Is there a way to modify the field of influence without having a scroll wheel?
I already have "emulate 3 button mouse" and "emulate num pad" turned on.

Update: Turns out, the Apple Magic Mouse that Im using does allow a scroll function if you swipe it down the middle. So I am able to get the functionality I am after. Thanks everyone for your suggestions.

Im on a macbook air, and the trackpad just work like spected with 2 fingers gesture.
Also, if you have a wacom with touch you can also do the gesture of the 2 fingers.

Use the Page Up and Page Down keys to adjust the circle of influence.

Im using a Mac with the small keyboard. (Makes most key commands a little challenging with 3D apps. : ) ) Unfortunately, there are no Page Up Page Down keys on this keyboard. I did however discover that the Apple Magic Mouse that Im using does allow a scroll wheel type of function if you swipe it down it's middle. So I think Im all set. Thanks.

@ThomasBricker Could you please click the check mark under the voting arrows to show this as the correct solution?

@ThomasBricker fn right and fn left are your page up/down keys.

What worked for me here in Blender 3.4.1 is Fn and the up/down arrow keys

There is a workaround, but it isn't terribly convenient:
After you've completed the action, in the tool operator, which can be found in the tool bar T or by hitting F6, you can change the Proportional size.

Using a magic mouse and you can not change the circle of influence?
Well this works for me:

Select the points.
Activate the proportional editing button.
Press G.
Use two fingers to scroll up or down in your magic mouse.

You can hit Alt and the + or - key on the numpad if you have a full sized keyboard to increases or decrease the circle size in Proportional Editing mode

I'm using blender 2.79. None of the above worked for me, here's what did:
Select the vertex/vertices you want to edit, left click and drag until proportional circle appears (if you can't see it you should see a line on the top left screen showing the proportional editing values).
Keep left button held down and scroll up or down (or click FN + ⬆ Page Up/⬇ Page Down).
Also note that under user preferences I had emulate 3 button mouse selected.

After choosing proportional followed by  S,  G etc use ⇧ Shift 1/2 to resize influence size

What is "Shift + 1/2"?


text:
How to configure which Blender version opens when clicking on a .blend file?
If I double click a recent blend file icon, the version of Blender that it calls is an old one.
The file was created using 2.76, but if I double click it it runs inside 2.72b.
If I right click it and navigate to 2.76, it still opens with 2.72b... or at least that is what I think it did. Am I imagining things? (I have just tested and that is what happens)
If I double click the 2.76 .exe it opens 2.76, but if I go to the file icon, right click and then navigate to the 2.76.exe it opens in 2.72b
I have 2.72b in a completely different folder called ART.
2.73 and 2.76 are in the normal Blender Foundation folder right next to each other. So what is causing the system to jump to another folder to open 2.72b?
This isn't a problem, but seems bizarre.
EDIT: Windows 10.  Yes, it is probably the O/S that is doing this, but it may mean that others have downloaded updated Blender, not overwritten the old install and are using the old version without noticing it. (It was a few weeks before I realised what was happening).
The thing to remember is to open Blender directly, check the splash screen and then File>Open.. the blender file. But finding the right version's icon is also hard because they don't include the version number in the icon. Perhaps it would be better if the icons change with each stable install the same way the splash screen changes.
I think I may decide to uninstall the old versions and see what happens.

I'd say this is more your OS related question. It depends, of course, but it seems that OS doesn't have necessary  associations in order to confront file extensions with files (and so it always thinks there is only one version of Blender in your system).

Sounds like you are on windows - try running blender 2.76 from a command line and use the -R option. If you are on *nix system then your PATH variable could cause one to be found one before the other, which blender should show the order they are found.

This is os dependent but a canonical answer would be nice.

I encounter the same problem and unable to open with newer version in Windows. And I found out that my newer blender folder name blender-2.80-w64 is illegal for command line since - always indicate a parameter to pass-in. After I change folder name to other name, the problem resolved.

None of the solutions on this page worked for me, so thought I better add this. I did find a way through Setting>Apps>Default apps>Choose default application by file type however I then found the much quicker way was to just pop open regedit, go to Computer\HKEY_CLASSES_ROOT\Applications\blender.exe\shell\open\command and just change the path there.

I had to try a few more things before my .blend file would open as the latest version.
Switching from 2.70 to 2.77a, just changing the Open With did not work for me. I don't know exactly which of these suggestions fixed it, but I would also try the following in this order:

Change the Blender.exe to blender 277.exe

Delete the old version information from C:\Users\\*<user\>*\AppData\Roaming\Blender Foundation\Blender\2.70\config

change Open As option to new version.

This works for me as well. I'm pretty sure any way that you can make Windows not be able to find the path to the old blender.exe will reset the "how do you want to open this" dialogue. So renaming, deleting, or moving the file should work. Then when you double click it will use whatever new version you choose. Seems like the behavior OP is describing is a bug in Windows where Windows stops searching the file system when it finds an executable whose name matches the executable it expects to find. Seems hard to believe that's true though...

This is what I did, and worked well. Thank you @EricNelson

macOS
For completeness, here's a more detailed answer for macOS users.
It helps if you have renamed the .app files in your Applications folder to include their corresponding Blender version numbers. This makes them easier to identify if you keep multiple versions installed.

Blender 3.3.app
Blender 3.4.1.app
Blender 3.5.app
...

Then... R Click or Ctrl Click on a .blend file in Finder and
Get Info

Under the Open With... drop-down section of that menu, choose the Blender version you want to designate as the default and click
Change All...

A confirmation pop-up appears.

It's also worth mentioning that each version of Blender gets its own settings folder in the User Library, which can be viewed in Finder by typing ShiftCmdG
~/Library/Application Support/Blender
You will see folders for each major release* version:

3.2
3.3
3.4
3.5
...

By "major release" I mean to one decimal place. In other words, a version as specific as 3.4.1 would not get its own folder. It would still use the 3.4 folder.
Note that installing a Blender version newer than all existing versions results in the newest version once again becoming the default.
Tip: If migrating to a new Mac, you can copy this folder to its place on the new machine and it will be used, preserving your startup file and preferences. Otherwise, upon launching that version of Blender for the first time, you will be asked if you want to import your settings from a previous version (assuming a folder for a previous version exists).
Tip: If you do Python programming and want to view console output while running Blender on your Mac, see this question.

Windows 10, open blend files with another blender version.
Go to blender directory, the version windows 10 actually opens your blend files, just rename the directory (add some letters) then, right click on any blend file , choose another app.. go to the blender version you wish , and it will work this time as you wanted .
May the Force be with you! ;)
mars.


text:
Selection Behavior and Limit Selection to Visible
Is this a bug or am I doing something wrong? Is there something I can test?
I am following the Blender 2.6 Manual with 2.68 Blender on Mac 10.6.8. Here I try to give life to the Gingerbread Man. However, the things that are explained under "Selection Behavior and Limit Selection to Visible" are understandable, but when I try to erase stacked vertices like described,

You must have the Limit Selection to Visible button unselected to continue this
  tutorial.
Now press B to activate Box Select/Border Select mode. The cursor will
  change to a couple of orthogonal grey lines. Move the cursor above the
  top left corner of the cube, press and hold LMB, then
  drag the mouse down and to the right so that the grey box encompasses
  all the leftmost vertices. Now release the LMB. The
  sequence of Box selecting a group of vertices.
The pop-up menu of the Delete (X) action.
Press X, and from the popup menu select Vertices to erase the selected
  vertices.

I only erase vertices, and I see in the front and the vertices below are not erased. Doing this by hand and following the tutorial, next time I am not able to able to extrude arms of the Gingerbread man, because again every extrusion I try is only applied on the interior vertex (I changed the view to show the problem).

Now with highlighted box:

See the discussion below in the comments:

As the tutorial explicitly states, you should have Limit Selection to visible unselected. Once it is unselected, you will be able to see (if in perspective view), select and delete the back parts of your mesh.
If using the default theme, a selected button should have a dark background  and an unselected button should have a light one .

Aahh, (Because?) I used upper window also for 3D view. Maybe this is a bug: every property changes in my window configuration in the upper window and in the lower. However, the Limit Selection to Visible button does not. Sry, for the confused question, but I did not see any difference when clicking that button.

@StefanBollmann Try resetting Blender to its defaults and try again. It's also possible your model might have hidden or excess geometry but based on your initial question, the above should work.

Now I understand - no bug - a feature. One can have multiple 3D Views. If I change the standard Info Window at the top into a 3D View, there is a second 3D View window. Because there is no more place at the top of the whole GUI, the view itself is hidden.

That button is a pain. and it's almost unrecognizable if it's selected or not. This button is one of the most frequently discovered newbie pitfalls (along with the object centers only button).

It is fine for me. If this is a pitfall for everyone, one could change the tutorial! For me this feature is a nice thing - to be able to easily add several 3D Views is a good thing.

@StefanBollmann Just in case you want to have the controls for the default 3D view at the top of the screen, you can right click on the header and select Header > Flip to top

If you are missing the Limit Selection to Visible button, get out of wireframe mode to one of the solid shading modes, as advised here

I had this problem and like you said with the windows, but for me what I did was copy all my objects press control + N to reload startup file and delete the cube then press control + V to paste you work. If you have other stuff open or worked on this wont really work though.

Copying work to another file just because of some UI problems / misundterstanding is not a solution, but a workaround which can effectively eliminate all scene settings done in the original scene.


text:
How can I add UV coords to a mesh from script?
I am adapting an old script to Blender 2.6, the script reads mesh data from a custom file type and then creates a mesh array with that data.
I managed to make almost all of it, but U can't set the UV values of each vertex to the mesh.
I create the mesh array like this:
for i in range(0,numeroparts):
    malla.append(bpy.data.meshes.new(name="2k_Part"+str(i)))
    uv = []
    xyz= []
    for j in range(0,numerovertxpart[i]):
        line=file.readline()
        x,y,z,u,v=float(line.split()[0].replace(',','.')),float(line.split()[1].replace(',','.')),float(line.split()[2].replace(',','.')),float(line.split()[3].replace(',','.')),float(line.split()[4].replace(',','.'))
        uv.append((u,v))
        xyz.append((x,y,z))
        print(x,y,z)

    aa = []
bb = []
cc = []
faces= []

for j in range(0,numerofacexpart[i]):
    line=file.readline()
    a,b,c=int(line.split()[0]),int(line.split()[1]),int(line.split()[2])
    faces.append((a,b,c))
    aa.append(a)
    bb.append(b)
    cc.append(c)
    print(a,b,c)

malla[i].from_pydata(xyz, [], faces)

for q in range(len(malla[i].polygons)):
    #malla[i].faces[q].mode |= Blender.Mesh.FaceModes['TWOSIDE']
    #malla[i].faces[q].transp = Blender.NMesh.FaceTranspModes['ALPHA']
    #malla[i].faces[q].uv=Mathutils.Vector(uv[aa[q]]), Mathutils.Vector(uv[bb[q]]), Mathutils.Vector(uv[cc[q]])

My problem is here, the lines commented out are how it worked in Blender 2.49:
for q in range(len(malla[i].polygons)):
        #malla[i].faces[q].mode |= Blender.Mesh.FaceModes['TWOSIDE']
        #malla[i].faces[q].transp = Blender.NMesh.FaceTranspModes['ALPHA']
        #malla[i].faces[q].uv=Mathutils.Vector(uv[aa[q]]), Mathutils.Vector(uv[bb[q]]), Mathutils.Vector(uv[cc[q]])

There are a few posts around how to import UV coordinates. Note that UVs are per-loop since 2.63: http://www.blender.org/documentation/blender_python_api_2_70_release/info_gotcha.html#upgrading-importers-from-2-62

I am trying to understand some examples but i can´t. Supossing that i have the uv per vertex values in uv=[], i still don´t know how to assing them to each loop.

With the next code i get the indices of the vertex that shapes each face:   for face in malla[i].polygons:
for indice in face.loop_indices:

With the next code i get the indices of the vertex that shapes each face:   for face in malla[i].polygons:
for indice in face.loop_indices:         now in tha variable indices i am getting each of the indices of each face, but after reading many examples i still don´t know how uv per loop works. In my code uv[] has the UV coords of each vertex with the same order that the vertex has on the mesh, so uv[0] has the UV values of vertex[0].I need to know how can i set to vertex[0] of the mesh the uv[0] value using uvs per loop because I still don´t know how it works

I made it work adapting this http://blenderartists.org/forum/showthread.php?321210-Importing-UV-coordinates. My problem is that it works but I don´t understand it, if someone wants to explain the code i would very grateful, anyway here is my solution:
for i in range(0,numeroparts):
    malla.append(bpy.data.meshes.new(name="2k_Part"+str(i)))
    uv = []
    xyz= []
    for j in range(0,numerovertxpart[i]):
        line=file.readline()
        x,y,z,u,v=float(line.split()[0].replace(',','.')),float(line.split()[1].replace(',','.')),float(line.split()[2].replace(',','.')),float(line.split()[3].replace(',','.')),float(line.split()[4].replace(',','.'))
        uv.append((u,v))
        xyz.append((x,y,z))
        print(x,y,z)

    aa = []
    bb = []
    cc = []
    faces= []

    for j in range(0,numerofacexpart[i]):
        line=file.readline()
        a,b,c=int(line.split()[0]),int(line.split()[1]),int(line.split()[2])
        faces.append((a,b,c))
        aa.append(a)
        bb.append(b)
        cc.append(c)
        print(a,b,c)

    malla[i].from_pydata(xyz, [], faces)

    malla[i].uv_textures.new(name="UVMap")
    uv_layer = malla[i].uv_layers[-1].data

    vert_loops = {}
    for l in malla[i].loops:
        vert_loops.setdefault(l.vertex_index, []).append(l.index)

    # Assume as uv = [(0.3, 0.6), (0.1, 0.4), ...]
    # with uv coords in order of vertices

    for q, coord in enumerate(uv):
        # For every loop of a vertex
        for li in vert_loops[q]:
            uv_layer[li].uv = coord

Below you find a very well-performaning solution to set mesh UVs from a source in a per-vertex format to Blender's per-loop (face corner).
This assumes you have a sequence of float pairs (UV coord),
e.g. ((0.2, 0.1), (0.8, 0.9), (0.2,0.1), ...).
import bpy
from random import random

me = bpy.context.object.data

# Sample data
vert_uvs = [(random(), random()) for i in range(len(me.vertices))]

me.uv_textures.new("test")
me.uv_layers[-1].data.foreach_set("uv", [uv for pair in [vert_uvs[l.vertex_index] for l in me.loops] for uv in pair])

Original thread: Importing UV coordinates


text:
How to render only the choose area
Is it possible to create a mesh with filter function in blender?
Assume i have a sphere, and i only want to render a rhombus area, the other part will be invisible.
Assume this is the sphere i want to render

and this is the filter like mesh

I want the rhombus area is visible and the other part become a Transparent film background(or maybe call invisible).

Hello, looks like you want to set the filter mesh to be set to holdout ?

Oh, yes, I just google search what is holdout, and it is what i need, Thank you


text:
Swapping Created Pose and Rest Pose?
I have a character I brought into blender from Unreal Engine in order to create custom clothing.  The character's rest pose is the standard A pose used by Unreal Engine.
I used "pose" mode to place the character into the standard T pose position used for creating clothing and then created the shirt I needed. This is when I run into a snag.
My "shirt" mesh has a rest position which is essentially a T position (arms straight out to the sides) but the rest position of my armature is in the A position with arms angled downwards.  Let's call this -45 degrees.
I now need to attach my shirt to the armature so I can reposition the arms into the original A position of the character, which is where I run into a snag.
It appears that a "pose" is relative to the original rest position, which makes sense. So as soon as I parent my "shirt" onto my "armature" the shirts arms deflect UP 45 degrees while the character arms are straight out in the T position.  If I return the character to it's rest position (A Position) the shirt arms return to their original position as well (T Position).
The logical solution is to make the character's T position the rest position first, before attaching the shirt to it. However, it creates another problem: I need to position the arms in the EXACT A position that the original character file was in so it will property align with the character when I transfer the shirt mesh into Unreal Engine.
Is there a way to "swap" my created pose with the rest pose while maintaining both in the blend file?  So far when I change the rest position, it does not preserve my other stored position as it's relative to the rest position.
I'm hoping to avoid having two separate base characters, one with am "A" rest position and a second with a "T" rest position.
Any ideas?

I think you need to create a new Action with a single keyframe for all bones on the armature with the character in the T-pose. To do so, with the armature selected, enter Pose Mode, select all bones with "A", and press "I" to insert a keyframe. Then click "Push Down Action" for that new NLA strip in the Nonlinear Animation Editor, so it sits on a track.

THEN, with the T-pose NLA strip active, parent the custom clothing to the character's armature (and do whatever weight painting adjustments are necessary). Next, put the character back into its "Rest Position" by clicking the corresponding button in the armature's Object Data Properties panel.

Finally export the .FBX file to Unreal Engine.

Unreal Engine tips: Make sure your Scene Unit System is Metric and your Unit Scale is set to 0.01 (otherwise bones will draw as big spheres in Unreal). I like to export the .FBX file from Blender with the options "Face Smoothing" and also tick "Tangent Space" but that last option requires you to select "Import Normals and Tangents" in Unreal's FBX importer under "Normal Import Method". Depending on the model, exporting with "Tangent Space" may not always give correct results, so always check the shading on your particular model after import to Unreal to be sure.
NOTE: If the armature is NOT using the default UE4/UE5 mannequin skeleton, but is a custom skeleton containing a dedicated root bone, make sure to rename the armature to Armature on export from Blender to avoid having two root bones when importing back into UE4/UE5.
(The armature of the default UE4/UE5 mannequin will have the name "root" in Blender, but this is NOT the same as actually having a real dedicated root bone (like Rigify rigs have). Since the lowest bone in the hierarchy of the default Unreal mannequin skeleton is actually the "pelvis" bone, there is no need to rename anything here.)

Thank you for your detailed reply! I essentially did exactly this with one exception... and that might make the difference... I am unfamiliar with the "Push Down Action" and what it does.
As soon as the clothing is parented to the armature, it seems that the clothing meshes un-posed position (t-pose) is matched with the armature's rest position (a-pose) and so the clothing's arm position is always roughly 45 degrees above the armature/character mesh's position. If you move the armature, the clothing position adjusts relative so the arms are always 45 deg above the armature.

You're welcome! The gray "Push Down Action" button (located in the Nonlinear Animation Editor) basically just stores the current animation into its own strip that can then be slid around the track, edited, muted, or crossfaded with other action strips. I recommend CG Dive's tutorials on YouTube to learn more about the process: https://www.youtube.com/watch?v=tAo7HxxxA08&list=PLdcL5aF8ZcJvCyqWeCBYVGKbQgrQngen3&index=16