text:
problem with parent actuator in BGE
I wrote a module to rotate the camera with middle mouse button pressed, zoom in/out with wheel up/down and at last push the camera towards the direction of the mouse if the mouse is getting near to the end of the screen.
I want the camera to be a parent to the player that I have only when the rotation is taking place.So I activate/deactivate the parent actuator but a problem or an error occurs.
While the camera moves as the mouse suggests if the mouse reaches the end of the screen (That is before I press middle button once!), after I rotate the camera I can no longer "push" it under the same conditions.
I tried activating/deactivating the parent actuator or set the mode to remove itself.And all this time I was reading the physicsId of the camera to make sure it can move with linear velocity.All the readings were ok,and no errors popped so I do not know why the camera stops moving after I rotate it once.
Here is the blend file with the module inside it : test blend
and below is the script clean,without comments. Can anyone find what I am doing wrong?
import bge

bge.render.showMouse(True)

scene = bge.logic.getCurrentScene()

player = scene.objects["player"]

cont = bge.logic.getCurrentController()

wh_up = cont.sensors["wh_up"]
wh_down = cont.sensors["wh_down"]
wh_pressed = cont.sensors["wh_pressed"]

par_to_player = cont.actuators["par_to_player"]

cam = scene.active_camera

mousePos = bge.logic.mouse.position
if not wh_pressed.positive:
    par_to_player.mode = 2
    mX = max(0.0,min(1.0,mousePos[0]))
    mY = max(0.0,min(1.0,mousePos[1]))

if mX < 0.05:
    cam.localLinearVelocity.x = -5*(2-mX)
    cam.localLinearVelocity.y = (0.5-mY)*5
elif mX > 0.95:
    cam.localLinearVelocity.x = 5*(2+mX)
    cam.localLinearVelocity.y = (0.5-mY)*5

if mY < 0.05:
    cam.localLinearVelocity.y = 5*(2+mY)
    cam.localLinearVelocity.x = -(0.5-mX)*5
elif mY > 0.95:
    cam.localLinearVelocity.y = -5*(2-mY)
    cam.localLinearVelocity.x = -(0.5-mX)*5

cam.localLinearVelocity *= 0.9

if (wh_up.positive):
    cam.ortho_scale = cam.ortho_scale+5
if (wh_down.positive):
    cam.ortho_scale = cam.ortho_scale-5

if (wh_pressed.positive):
    bge.render.showMouse(False)
    cont.activate(par_to_player)
    par_to_player.mode = 1
    print (par_to_player.mode)
    mX_rot = max(0.0,min(1.0,mousePos[0]))
    if (mX_rot < mX):
        player.applyRotation([0, 0, -0.01], 0)
    elif (mX_rot > mX):
        player.applyRotation([0, 0, 0.01], 0)

print ("I reached the end of the module")

Much appreciate @Chebhou. Did you understand why the camera gets thrown? I checked the cube and it does not  move after I release the MMB.

it keeps some angular-velocity from the rotation , do a check after unparenting if the camera has an angular V set both Linear and angular velocities to Zero

@Chebhou if you can check this, http://blender.stackexchange.com/questions/29092/how-to-instantly-stop-the-rotation-of-an-object-in-bge
Can't seem to stop it.

you are not unparenting the camera after rotation correctly , you have to set the mode to 2 and activate the actuator to take effect :
if not wh_pressed.positive:
    par_to_player.mode = 2
    cont.activate(par_to_player)

also you may need to kill the rotation after unparenting ( the camera gets thrown away after rotation )


text:
sphere acts weird while changing its worldPosition
I have an empty and I have set a sphere as its child. When I change the empty's worldPosition(via right-clicking with mouse) the sphere teleports to entirely different location. The strange thing is that when I print the sphere's coordinates it is exactly the same as the empty's and the mouse cursor's. Any ideas?
Here is the module I wrote.
#Import the bge library.
import bge

#Make the mouse cursor visible during game running time.
bge.render.showMouse(True)

#Set the current game scene and python controller to variables.
scene = bge.logic.getCurrentScene()
cont = bge.logic.getCurrentController()

#The function "initialization" is responsible for setting all scene objects, object sensors and object actuators to variables.
#These variables are created into the function but are for global use. Their names are the names of the objects/sensors/actuators in blender.
def initialization():
    for k in scene.objects:
        exec("globals()[\"%s\"]=scene.objects[\"%s\"]"%(k,k))
    for k in ground.sensors:
        exec("globals()[\"%s\"]=ground.sensors[\"%s\"]"%(k,k))
    for k in cont.actuators:
        exec("globals()[\"%s\"]=cont.actuators[\"%s\"]"%(k,k))

def mouse_2D_coor():
    global mX, mY
    mouse_pos = bge.logic.mouse.position
    #Cramp the coordinates to what the camera sees. (0, 0) at the top left corner and (1, 1) at the bottom right corner.
    mX = max(0.0,min(1.0,mouse_pos[0]))
    mY = max(0.0,min(1.0,mouse_pos[1]))
    #print ("Mouse coor :",mX,mY)

def empty_to_pos():
    cursor_empty.worldPosition = (mop.position[0],mop.position[1],cursor_empty.worldPosition.z)

initialization()
#print (mop.hitPosition)
if (right_click.positive):
    empty_to_pos()
    print (cursor_empty.worldPosition)
    print ("Mouse",mop.position)
    print ("sphere",sphere.worldPosition)

print ("I reached the end of track.py")

Here is the blend file

The answer came from the blenderartist's forum where the user agoose77 wrote

You need to use

mop.hitPosition

. The position attribute of the base class of KX_MouseFocusSensor,
  SCA_MouseSensor, returns the pixel position of the mouse, which can
  reach a value in the thousands.

And it worked.

source: Stack Exchange

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

sort: votes


text:
Timers and animation frame rate
The following image represents a timer with minutes and seconds that I created:

What is the correct value of the "skip" option in the always sensor if I want it to activate every 1 second?
Also, what is the connection, if any, with the "animation frame rate" under the "display" section in the "render" toolbar?
And at last, is there any connection between one of the above values and the fps of my game? Will those values be affected by the fps of my game somehow or the other way around?

Thanks

Funny. Someone renamed "Freq:" to "Skip:". I think it is still misleading. It is a period or delay between to consecutive triggers when the sensor's evaluation state does not change. I understand "skip" as a flag that is either True or False, but not a number. Anyway it does not help your problem, but why you can't find something when you search for that parameter.

Please post just one question at the time.

Thanks, I only asked those questions together cause I thought they had a connection due to a video I watched.

No big deal, I could see the connection. The problem is that it it is (in a lot of cases) difficult to give one answer for several questions. I think in your case it was possible to do that.

The default (logic) frame rate is 60 frames/sec. Therefore 60 is a good value for your purpose.
There are more frame rates:

Animation frame rate (usually 24 frames/sec) used to play actions.
Physics frame rate (usually matching the logic frame rate) to calculate the physics influence to a scene. Be aware it can be even finer with so called-substeps. More sub steps increase the precision of the physics calculation (but costs more processing time).
Render frame rate (usually matching the logic frame rate) which tells how many images are rendered. If a frame lasts too long (exceeds the 1/60 time available) the BGE starts skipping the render trying to meet the frame rate. This can happen up to 5 times in a row. After that there is a forced render ignoring the time limit. The render frame rate is never higher than the logic frame rate as it is assumed there is no change to the scene and the output would be the same.

But:
I suggest to avoid this method to measure time. The BGE will try to keep the given frame rate as much as possible, but there is no guaranty.
I recommend to use a timer property. It counts the seconds. I think that is what you really want.
Then you have several ways to show the time. I think you want to format it to minutes:seconds. You can use this little script timeToText:
import bge
from datetime import datetime

textObject = bge.logic.getCurrentController().owner
time = datetime.fromtimestamp(textObject["time"])
textObject.text = '{:%M:%S}'.format(time)

It expects a property time to provide the seconds and should be applied to an text object.

You can indeed refresh the display each 60 frames. But you will not know when the seconds changed. Therefore I suggest to run it constantly.
Hint: If you want to show microseconds too, use this format: {:%M:%S.%f}

I am gonna post a question about inverting the timer and quote part of your answer. If you know how, feel free to answer. Thanks again for your elaborated answers.

I think you can simply copy&paste the text from here and use the block quotation button <ctrl+Q> when editing your post.

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


text:
Disallow objects to be rendered from specific cameras during playtime
Can I order specific cameras to not render objects during play-time?
And how?

You can dynamically toggle visibility of objects. So when you switch a camera you toggle the visibility to your needs.

First thing I thought was layers , masking etc. I forgot the simple solution. Make it an answer if you like.

You can dynamically toggle visibility of objects. So when you switch a camera you toggle the visibility to your needs.


text:
Dissimilar movement between parent and child in BGE
In this blend file I have the following problem.

Every time I rotate the "Player" the camera rotates in a radius way huger than it should. Check the "Plane" to verify this or through the camera view.

It used to work fine till I appended the object "Flashlight", which is a child of the "Flashlight_empty". Also when I appended it, it spawned as "Flashlight.001" while I have/had no other object with the same name. I changed it back to "Flashlight". I think it has something to do with the physics boxes, cause when collision box option is deactivated the player has a sphere around it(maybe it is a default thing) while when I activate it goes with the box. I played with it and might have messed it. Anyways it might be something simpler also.

There is no need to upload a 3MB file. It would be better to provide a very small file that focus on the problem.  I can't see that something rotates = I can't see any problem.

Your problem description indicates you have a non-uniform scale on one or more parents. According to your file the problem is the "Player" object.
Solution:
Ensure the scale is set to (1.0, 1.0, 1.0).
You can do this by pressing ⎈ CtrlA > Scale.

That was it, but how could I possibly have scaled it and then remain visually scaled but not in the numbers?

You scaled the object, rather than the mesh. Be aware object scaling gets inherited by the children (objects too). This has impact on the space the child is living in. If that space is inhomogene scaled, an rotation would result in an ellipse rather than a circle.


text:
PIP in blender as part of Makefile
How can you install packages into blender's python a makefile? I want to be able to run a "make python-deps" and have it automatically install a list of dependencies

The solution is to have a makefile target that installs pip using the specific blender python version.
PYTHON_DEPS = \
    pyyaml \
    pillow \
    scipy

# Change these as needed
BLENDER_BIN_DIR = ~/bin/src/blender/build_linux/bin
BLENDER_VERSION = 2.78

# With luck you shouldn't need to touch these
PYTHON_PACKAGE_DIR = $(BLENDER_BIN_DIR)/$(BLENDER_VERSION)/python/local/lib/python3.5/dist-packages/
PYTHON3 = $(BLENDER_BIN_DIR)/$(BLENDER_VERSION)/python/bin/python3.5m

python-deps:
    # Install pip
    wget -nc https://bootstrap.pypa.io/get-pip.py
    $(PYTHON3) get-pip.py

    # Install dependencies
    $(PYTHON3) $(PYTHON_PACKAGE_DIR)/pip install $(PYTHON_DEPS)


text:
Where is Bleders bpy Python library located
I've been a text editor (Visual Studio Code) and somebody made an awesome add-on that lets you deploy python, and for that its great! but to be able of read an external api you need to tell some file where is located, so I would like to know where the bpy and preferably the bge files are, and of course all it dependencies.

http://blender.stackexchange.com/questions/42520/blender-module-bpy


text:
Finishing 2.76 version project, how to render the animation in object/material "viewport" mode in 2.7?
I am finally finishing a project I began years ago in 2.76.  Can anyone recall how to render out an animation in "object" mode rather than "render" mode?  The instructions for the new versions do not work with 2.76.  Thank you!!!

Was that option even available in such an early version? The option only appears in the Blender manual from version 2.80.

@JohnEason   It had to be available because I found animation image sequences in my temp folder that are viewport/object mode!  Unfortunately it's been so long since I worked on this, I have no idea how I made it happen.  Maybe I can bring these files into 2.8 just for this function?  I kinda thought I couldn't bring 2.7 files into 2.8.

I've no idea since it's so long since 2.7 was in use and I don't have it on my PC nowadays. There doesn't seem to be any mention of it in the 2.79 docs as far as I can see although I haven't searched thoroughly. You should be able to open 2.7 files in 2.8 (and even in version 4 although there may be some limitations).

@JohnEason I found it!  "OpenGL Render Animation" under "Render" at top of screen!  Thank you for responding!

Ah ok. Good luck!

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


text:
Will Blender files saved on a Windows version of Blender, work on a Linux version of Blender?
I am building a new PC and considering installing a Linux distro rather than Windows.  I am concerned that the files that I saved on my Windows PC will not be able to load onto a Linux version of Blender.  Could I use Wine and use the Windows versions of my software for better compatibility?  I have read that Blender runs better on Linux.  Any advice welcome.  Thank you.

Short answer: Yes, the Blender files will work no matter what OS you saved them on

It does not matter if you save it at Windows, Mac or Linux. A blend file is a blend file. Important is the Blender version. Blend files that are saved with the same version of Blender opens in Blender, regardless at which platform.
Wine is not necessary nor recommended. Blender runs natively at Linux. It would just add another software layer that would slow Blender down.
If it makes sense to use Linux is your personal decision. Blender itself runs on all platforms.

just a small remark to Tiles right answer: a blend file just consists of the "settings" of the scene in his "own" Blender-format. Just the Blender executables (.exe in windows, .app on mac ...) are different and platform specific.

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


text:
Snapping an unselected face to a different objects edge by moving vertices
I am 'building' a house in blender and currently struggle with the rooftop. I have fixed the very top of the roof and now want to 'snap' the roof both roof parts to the wall below.  I try this by moving some vertices and I want to snap a face connected to these vertices to another objects (the wall) top edge.
This is the roof and the top floor, I want to snap the section marked on the left.

I select the outward facing part of the roof (4 vertices, 1 face) and want to move them down until the face snaps to the edge noted by the circle.

Afaik, all snapping tools in Blender can only snap the selection to other elements (vertices, edges, faces), so it is not possible. To get those two shapes perfectly stick, you could use a physics simulation (but it is not a transformation tool, anyway). I could show you a workaround in an answer, if needed, but works differently than you asked.

Yes please.  I was expecting that Blender does not support this using snapping ... so any best practice on how to do this is appreciated.

I'm sorry I replicated my workflow today, as I did the other day, and then wrote an answer, but then I played with it again, and... it didn't work anymore... maybe it works only in some cases, but I'm not sure. I'll add an answer when I'm absolutely sure that it works... in the meanwhile, yes, Blender could get much ebetter snap tools :)

I played a bit more. here is what i get: you can get the face to snap to a point or edge on the horizontal "plane", using rotation, pivoting upper corner of the rotating shape. Is not exactly what you asked but works perfectly - until - you apply that rotation. Yes, after applying rotation, it doesn't work anymore... it snaps badly and you can't get a precise snap.  It may be a bug or not, I just wished to put my findings here.


text:
Rescaling in the VSE yields low resloution, blurry images
I want one segment of my video to be zoomed in, showing only part of the original images. I managed to create that effect by scaling using the VSE Transform Tools addon, but that made the resolution for those parts decrease.
The original images are big enough to maintain a good resolution, but the transform seems to be made on the strips where it is set to 720x576 (that I want as the final result). Is there a way to avoid this?
-- Edit to include images --
This is how it looks after scaling in Blender (blurry as if it only uses part of the image data):

This is the original image cropped and scaled to the same size in Gimp:

Screenshot of how the rendered animation looks:

It seems that it's not possible (or at least not easy) to pack image sequences into a .blend file, but here is the file + one image:
https://www.dropbox.com/sh/0ckrx13hl6f3jnm/AABk7Km4Ofqu1YE_RtFTv7HUa?dl=0

It seems you do not understand the nature of resolution, because if you zoom in on an area where no more pixel data exists, the only thing that can be done is to magnify the existing data - this means a drop in resolution relative to the final output resolution. Do you follow?

Well, I know, but there IS more pixel data in the original image, and I was hoping to access that somehow.
What I need is a way to get a cropped image with the same resolution as the rest of the video, and I was hoping I could use scaling to get there.

In that case it may be an "order of operations" problem. If you are squashing the pixel data before magnifying, then you will only magnify squashed (pixelated) data. If you magnify before squashing then everything should appear as desired. Sorry, but this is about the best answer I can provide without more clear examples or a .blend of your project to examine. If you can provide a .blend I would be happy to take a look. (For the sake of file size, if you do upload a .blend you probably only need it to include a still image, not an animation. And please pack the .blend)

Mentalist: Yes, "order of operations" sounds right. Added some screenshots, but failed to create a packed .blend file that includes the image...
cegaton: Yes they are at 100%. The problem is that the resolution for the transformed part is different from the rest, and I think that difference will remain no matter how I set the resolution.

That might actually be considered a bug and be posted at Blenders bug tracker. It's worth a try. And did you use proxies? Can you take a Screenshot of the finally rendered movie at this frame?

@Samoth: No, I'm not using proxies (unless that is some sort of default?). Added a screenshot of the resulting animation, it's as blurry as the earlier picture. If it's a bug, then at least it's not just me using it completely wrong...

Guessing: You imported a sequence of images into the VSE?

This is an open ToDo "All images are cropped to the render resolution inside Input strips, making effects like Transform less useful" which has been reported as a bug before.

Another way to get a still image to rerasterize from original size, is to use the MCE or Tracking tool.
Simply load a still at the first frame, then key frame the value "Start Frame" from 1 to 250 (or whichever frame is scene length).

Then add a tracker/marker to the middle of the shot.
Then turn on the 2D stabilzer.
Start with a 1-1 pixel scale by dividing image size (Footage info) into the Project dimensions. This will give you a starting scale that you can increase or decrease to zoom in or out. Increasing the value will subsample the pixels and create a blurry image again. Best to only decrease this value.
You can also keyframe rotation and transform (move left or right).
In the MCE you can turn on Display > Display Stabilization to view any changes in realtime.

Note: you MUST press the Sequencer Referesh button or play button to see the effect in the VSE. Images that don't match scene aspect ratio will be distorted due to the VSE "fitting" the image.

The Transform strip in VSE will only scale the target output resolution. Especially if you're rendering to a lower resolution than your original video, then this would result in a very ugly result.
If you don't want to animate the zoom, then check the video's strip "Image Offset" or "Image Crop" (see segaton's answer)
If you want to animate, then a trick is using the Compositor:

Create a new scene copying settings (to keep the resolution and FPS, but don't create a full/linked copy else you'll need to align time between MCE and VSE).
Open Compositing (Shift + F3)

☒ Use nodes
Add (Shift + A) > Movie Clip > Select video file
Add (Shift + A) > Transform
Link the video to the Transform node and that to the Composite node
Preview, either:

Link to a Viewer node and check Backdrop
Image editor (Shift + F10) area type to view the Render Result

Properties (Shift + F7):

Set scene’s end time to match the video clip
Note: Normally defaults should be fine but check that "OpenGL Preview" is not checked, and also Output > Processing > ☒ Compositing and ☒ Sequencer.

Add that scene into the original scene's VSE as Scene strip.

Alternatively for (3), is to render each Scene as image sequence first (prefer 16 bit PNG) and add them in VSE instead of using Scene Strips, performance wise it would result in a huge gain.
An easy but giving a bit less good results (a bit less sharp in my tests even if your don't resacle the generated video), is to set the target output resolution to the original video's resolution (or higher), use the VSE Transform strip, render to a file, and then possibly encode that file again at a lower resolution (which means that scaling happens twice).

This really bugged me, but I got a solution:
Create a new scene, and in that - using the node compositor zoom in/out of the clip.
Add that scene into the other scene's VSE as a 'strip'. You are then able to "use the resolution" of the original clip re-sized however you like. It's slower and more clunky, but works (and very powerful!). As others have said the "transform" simply takes the existing canvas output and makes it bigger or smaller. It has no access to any extra resolution in the original, and can't "see beyond the edges" either. Image offset / crop do not allow you to control the size, they simply set it at "the original's resolution". Which is good enough for what it is.

Guessing:
You imported a sequence of images into the VSE?
These were in some high definition?
Blender created a video strip from those images and this video strip is in the resolution that you set for the final output?
So, if true, it would seem that Blender converts the image input into the chosen resolution and throws away the extra data???
(I don't know if it does or not, but.....
Suggested work around.... change your resolution to the same as the input image, do the editing and only then reduce the resolution when rendering output.

Yes. And I think that the difference in resolution will remain no matter what I do in between...

-1 as I tried that and the effect is exactly the same, the image stays cropped


text:
Remove relationship between two objects
I have an dae file which I import into blender version 2.76. There is one pool cue stick in this file.  There seems to be a relationship(shown by relationship line)between cue stick and another point which is at 0,0,0 as shown in the image below. I want to remove the relationship between this cue stick and I want that the tip of the cue stick be at 0,0,0 point.
Please let me know how to remove relationship between cue stick  with a point which is at 0,0,0

press Alt + P , and select "clear parent" :)

I tried Alt + P and selected clear parent but I can still see the relationship line

You should select the child object - in the screenshot it seems you selected the parent object instead, which is in fact the parent itself.

I selected the child objects with Shift+ G and then I pressed Alt + P.. Now instead of one object with parts of a cue 26 small objects( which are part of the cue stick are showing). How to join these 26 small cue objects. Is there a way by which without clearing the parent I can make the whole object point to 0,0,0

You could join the objects by pressing ctrl + J while having them selected, and then align the object the way you want it, yes :)

Hi MaVCArt. Job done. Thanks for your help

My please, glad I could help

For all clearity: use ALT+P in the 3D view, not the hierarchy view

Click the object, then press Alt + P. This opens the Clear Parent menu.
Select Clear and Keep Transformation.
If this does not work for you, you may have selected the parent instead of the child.


text:
How to preload a python module into blender console on startup
I have a set of tools that I use with blender and wanted to know how can I pre-import this module into blender's python console and have it accessible all the time. Just like how bpy works and I don't need to import every time I'm opening the program.

At startup, Blender reads the contents of the scripts/startup/ directory for python modules and imports them.  You can also choose to use scripts as add-ons (turn on/off via Add-Ons manager):
http://www.blender.org/api/blender_python_api_2_73_release/info_overview.html

I think I wasn't clear enough. So I have this module that I don't want to copy into blender's folders as add-on or startup script. I'm trying to write Another startup script or addon that basically tells blender console to "import mymodule as MM" and have it available when I'm working in console. is that possible at all?

Around line 97 in scripts\modules\console_python.py, there is some code regarding the imports / convenience variables:
    namespace["__builtins__"] = sys.modules["builtins"]
    namespace["bpy"] = bpy

    # weak! - but highly convenient
    namespace["C"] = bpy.context
    namespace["D"] = bpy.data

It doesn't work however if you add import bmesh; namespace["bmesh"] = bmesh here.
Maybe this code isn't really used, you might wanna check the C code.


text:
H.265 support in the VSE?
Will we be able to edit 4k H.265 footage in the VSE in a near future?
Thanks!

Apologies but actually it seems that one is able to edit 4k H.265 footage in the VSE, am I right? I was able to bring in 4k H.265 footage in the vse without any convertion and do a soft cut at least.

which codec do you use and how did you install it? This would be useful for other users.

converting isn't that much of a problem, you can use ffmpeg or handbrake if blender won't let u input it. If the colour bits of your h.265 are only 8 bit and ur worried about artifacts you can just upscale to 16 bit png or something and input that into blender. The problem though is you STILL can't output it as h.265 in blender anyways...but u can just export it back out as ur png and do it in ffmpeg or handbrake which is just ffmpeg with a gui.


text:
Python: Select specific parent object automatically on selection change?
I have written an add-on which visualizes objects on a racing game track.
Each in-game object is an empty object in Blender with one or more children mesh objects being the visible model as seen in-game. The empty holds the game-relevant properties in a PropertyGroup which are visualized in a custom Panel.
Basically, the object hierarchy looks like this:

ItemBox < Empty object holding custom properties the user is interested in

ItemBoxOuter < A model the user selects
ItemBoxQuestionMark < Just another model the user might also select

Start < Another empty holding custom properties

StartLine < Another model

and so on

Since empties are hard to select and often covered and encased by the models, I want to redirect the selection of such child mesh objects to the parent empty object. Is it possible to modify how the selection operator works here?
Background: At first I worked around this by letting the Panel which displays the PropertyGroup use the parent object to show its data. However, users began to move around the child model objects (having selected those), effectively keeping the in-game object at the same place as it uses the transform of the empty object.

I could solve this with an apphandler I registered to. I added a custom property to the model objects to recognize them in there.
def register():
    bpy.app.handlers.scene_update_post.append(addon.scene_update_post)

def unregister():
    bpy.app.handlers.scene_update_post.remove(addon.scene_update_post)

# ---- In the addon module ----

def scene_update_post(scene):
    ob = scene.objects.active
    if ob:
        # Redirect the selection of a model mesh object to the parent track object.
        if ob.is_model:
            scene.objects.active = ob.parent
            ob.parent.select = True
            ob.select = False

This works even when multi selecting objects!


text:
Python: Store rotation / normal in bezier curve point?
Still trying to visualize a game file format in Blender, I think I reached a limit of what I can do with Blender Bezier Curves.
The game file format defines the coordinates of the curve point and the two handles. It additionally, however, defines a rotation of the curve point, basically a normal, because it needs to move and rotate objects along the path the curve forms.
Is it possible to store a normal in a Bezier Curve Point?

I didn't find anything like a normal / rotation for bezier curve points in the documentation.
Also, curves don't seem to support custom data layers like with the BMesh API where I could at least store the original normal information. Also it would be hard to edit those normals then visually.
I think it would be a monstrous task for someone who has never worked with the Blender C(++) codebase to add a new object type supporting that, or is it possible to relatively "easily" add normals to curve points or derive a new curve type from the existing one, just adding this information and keeping big parts of the base curve class?

You can always have a parallel data structure to store this additional information and go from it to the curve (and from the curve to it) using a dictionary

I thought about that, but what when the user deletes curve points? I can only identify them by index correctly AFAIK, and then the mappings get all messed up.

the user has the ability to delete it in your game while you don't know it ?

No. For each point, I need to remember additional data (2 floats, and a rotation). If I store that in a parallel data structure it will desync as soon as a vertex in the curve is deleted.

Bezier curve objects can store a property called tilt.
It is basically a per point rotation value or normal that controls it's twisting on a per.vertex basis.
It can be set through the UI in edit mode under the Properties Shelf > Transform > Tilt or through the Python API with bpy.types.BezierSplinePoint.tilt

As far asI know curves don't support arbitrary data layers per vertex like BMesh does, but I may be wrong.

That looks quite promising. I just have to find out how to calculate the tilt angle from an XYZ normal rotation the data I got gives me. And yeah, there are no custom data layers according to the docs, which is another issue since I need to store 2 game specific floats for each point...


text:
Python: Edit panel to edit custom bmesh face layers?
With the bmesh module, I added a custom data layer to a mesh, holding information for each face.
bm = bmesh.new()
collision_flag_layer = bm.faces.layers.int.new("collision_flags")
for triangle in model.triangles:
    vertices = model.get_triangle_vertices(triangle)
    vert1 = bm.verts.new(vertices[0])
    vert2 = bm.verts.new(vertices[1])
    vert3 = bm.verts.new(vertices[2])
    face = bm.faces.new((vert1, vert2, vert3))
    face[collision_flag_layer] = triangle.collision_flags

Now, in Edit Mode, I created a panel to display this property in labels:
class MarioKart8EditPanel(bpy.types.Panel):
    bl_label = "Mario Kart 8"
    bl_region_type = "UI"
    bl_space_type = "VIEW_3D"

    @classmethod
    def poll(cls, context):
        # Only allow in edit mode for a selected mesh.
        return context.mode == "EDIT_MESH" and context.object is not None and context.object.type == "MESH"

    def draw(self, context):
        obj = context.object
        bm = bmesh.from_edit_mesh(obj.data)
        face = bm.faces.active
        collision_flag_layer = bm.faces.layers.int.get("collision_flags")
        if collision_flag_layer is None or face is None:
            self.layout.row().label("No collision face selected.")
        else:
            #self.layout.prop(face, '["collision_flags"]')
            row = self.layout.row()
            row.label("Collision Flags")
            row.label(str(face[collision_flag_layer]))

That's pretty awesome already, displaying the custom data like this:

However, since this is edit mode, I want the user to be able to edit this value of course. As you might have noticed from my code already, I commented out a line where I failed to create a number picker for this with the layout.prop method.
How can I implement an edit control for this custom data?

Set up an approach similar to https://blender.stackexchange.com/a/40264/15543.  One instance of an edit bmesh is added to a global dictionary on editmode toggle via a scene update handler.
A dummy int property is added to the window manager and is used to set the face layer int via an update method.
The dic bmesh instance can also be used in your panel.
import bpy
import bmesh
from bpy.app.handlers import persistent
from bpy.props import IntProperty

# global to hold the bmesh.
dic = {}
# update method
def setlayerint(self, context):
    eo = context.edit_object
    bm = dic.setdefault(eo.name, bmesh.from_edit_mesh(eo.data))
    face = bm.faces.active
    cfl = bm.faces.layers.int.get("collision_flags")
    if face and cfl:
        face[cfl] = self.layer_int_value
    return None
#layer_int_value is used to set the value
bpy.types.WindowManager.layer_int_value = IntProperty(name="Collision Flag",
                                                      update=setlayerint)
#keep wm.layer_int_value updated to active face
def set_collision_flag(bm):
    face = bm.faces.active
    if face is not None:
        #print("BFace", face, face.index)
        cfl = bm.faces.layers.int.get("collision_flags")
        if cfl:
            bpy.context.window_manager.layer_int_value = face[cfl]
    return None
#scene update handler
@persistent
def edit_object_change_handler(scene):
    obj = scene.objects.active
    if obj is None:
        return None
    # add one instance of edit bmesh to global dic
    if obj.mode == 'EDIT' and obj.type == 'MESH':
        bm = dic.setdefault(obj.name, bmesh.from_edit_mesh(obj.data))
        set_collision_flag(bm)
        return None

    dic.clear()
    return None

class MarioKart8EditPanel(bpy.types.Panel):
    bl_label = "Mario Kart 8"
    bl_region_type = "UI"
    bl_space_type = "VIEW_3D"

    @classmethod
    def poll(cls, context):
        # Only allow in edit mode for a selected mesh.
        return context.mode == "EDIT_MESH" and context.object is not None and context.object.type == "MESH"

    def draw(self, context):
        obj = context.object
        bm = dic.setdefault(obj.name, bmesh.from_edit_mesh(obj.data))
        face = bm.faces.active
        collision_flag_layer = bm.faces.layers.int.get("collision_flags")
        if collision_flag_layer is None:
            self.layout.row().label("No collision layer.")
        elif face is None:
            self.layout.row().label("No collision face selected.")
        else:
            wm = context.window_manager
            self.layout.prop(wm, "layer_int_value")
            #self.layout.prop(face, '["collision_flags"]')
            row = self.layout.row()
            row.label("Collision Flags")
            row.label(str(face[collision_flag_layer]))

def register():
    bpy.utils.register_class(MarioKart8EditPanel)
    # clear the handler for testing purposes.
    bpy.app.handlers.scene_update_post.clear()
    bpy.app.handlers.scene_update_post.append(edit_object_change_handler)
register()

Note could add something like the active_face_index to the dic and check on change, instead of constantly setting the face layer value.

Thanks for the answer; I'll try it as soon as possible I get back to the above project! =)

How would I actually write the bmesh back to the mesh? Right now, if someone edits a face property, and then exports, it has not been written back to mesh. Would I have to update the mesh everytime I do an edit? Otherwise the export hasn't changed at all.


text:
Horrible scene_update_post performance
Since the Python API does not support events when objects are removed I had to go a pretty "uncomfortable" way to visualize contents of a game level to which I write an addon.
The game places different stuff in a level, and in Blender, I represent that stuff with Empty's. Each Empty has children mesh objects attached to it holding the model(s) to visualize that stuff (e.g. an item box, coin, banana with sunglasses or whatever crazy ideas the lead designers get).
Now, whenever someone deletes the Empty, I also want to delete all the children. Since Blender does not delete children automatically when the parent is killed, I check for "lose" children in scene_update_post. (I also do it the other way round: If an Empty has no children, I add the models to it).
This worked fine on a i7 6700K fullblown atomic power plant until I tested it on a 5 year old PC with an AMD Athlon 6000+ CPU. Blender uses one whole core all the time, so I cut down the code I do in scene_update_post to see what's causing this performance rape. Already these few lines make Blender use 24% of the core, when there are like 100 objects in the scene:
@bpy.app.handlers.persistent
def scene_update_post(scene):
    for ob in scene.objects:
        hl3 = ob.halflife3_props  # Yes, this name is made up

That's quite horrible. But I don't know any other way to check for objects which just lost their parent. It would be even more horrible to tell the level designers (which are not the biggest Blender boys) to select all children first and then delete them with the parent.
Are there better solutions to solve this problem? I thought about overriding the deletion behavior for objects of a specific type string I stored in my custom properties, but I have no clue if that's even possible.

You are running python code inside not well optimized software on outdated hardware. It is to be expected. The only thing you can do is to design the code in a smart way - for example only loop through the objects when the size of scene.objects array changes, etc.

further to Jerryno .. a simple print or timer in a scene_update : its run a phenomenal amount of times per second.  A modal timer would be a less heavy duty approach.. Adding a custom property to the model objects with the empty parent's name? would me my approach.

The idea with checking the object array length, additionally only in a timer sounds like the best idea.
@batFINGER I don't quite understand what the parent name attached to the child models would help though; I still have to check wether they have such name, then I could also just check if their parent isn't None? =3

... and you'll have a situation where if you add a new mesh without a parent it will be deleted immediately.  Surely some kind of test other than just having no parent would be more workable.

@batFINGER Ah that's right. I always create the parents first at the moment, so that doesn't happen yet.

The scene_update handlers are called on every update, which is basically the Blender's refresh rate. On empty scene I measured 200 updates/sec. On every cycle Blender has to update the whole scene and run the python code on top of that - that leaves a very small processing time for the python part (cca 17ms is ok which translates into 60 updates/sec).
Thus any code that is being run inside scene_update handlers is extremely performance sensitive and should be optimized.
Optimization tips:

Before updating or processing anything, check if it has to be updated or processed. In this case run the code only when number of objects changes, check the length of the scene.objects list first:
import bpy

num_objects = 0

def handler(scene):
    global num_objects
    if len(scene.objects) == num_objects:
        # Nothing to do
        return
    num_objects = len(scene.objects)
    # Your code here
    return

bpy.app.handlers.scene_update_post.append(handler)

You can use global variables, custom properties, properties of objects or binary flags to memorize when code needs to be run.
Update or process your stuff in an efficient way:

pre-sort arrays where it will increase performance
use data-structures optimized for the task (like dictionaries, numpy arrays, etc.) and access them in an efficient way
use list comprehension for cycling through list elements
use local variables wherever possible
profile your code to know where the bottlenecks are: How can you profile a Python script?

If it needs to be really fast, write it in Fortran, C, C++ or Assembly, then call it from Python.

Python is not C, Java or Haskell. Knowledge of how other languages perform to Python isn't very well transferable, your python code will pick up speed and performance with your experience in the language. The next example illustrates it well (from: wiki.python.org - Performance Tips):

% timeit.py -s 'x = 47' 'x * 2'
  loops, best of 3: 0.574 usec per loop
  % timeit.py -s 'x = 47' 'x << 1'
  loops, best of 3: 0.524 usec per loop
  % timeit.py -s 'x = 47' 'x + x'
  loops, best of 3: 0.382 usec per loop
Note that there is a significant advantage in Python to adding a number to itself instead of multiplying it by two or shifting it left by one bit. In C on all modern computer architectures, each of the three arithmetic operations are translated into a single machine instruction which executes in one cycle, so it doesn't really matter which one you choose.

Other resource for performance tips: Optimizing Python Code


text:
Select edges by length?
Is it possible to select all edges with a specific length?
I have a very exotic problem. In a computer game model, there is audience projected on several billboards, and depending on a billboards width, I know the number of characters seen in that billboard.
I want to find out the approximate complete count of characters in the audience.
The problem is, that there are 4146 billboards, which I can't count by hand, but classify by their length at least, and then calculate it up:

Any way to select, for example, all the widest audience billboard edges seen on the terrace?

Yes.
Select an edge and press ⇧ ShiftG> Length. By default this will select all other edges with equal length to the active edge.
By adjusting the options in the redo panel (F6) or at the bottom of tool shelf (T), you can also select edges with greater or lesser lengths and compare lengths with a threshold to select edges that are not exactly the same length, but similar.

Once you have a partial selection on the billboards you want to select, you can select all geometry connected to the selection with ⎈ CtrlL. Or in the case of a plane, by switching to face select mode (⎈ Ctrl↹ Tab) while holding ⎈ Ctrl.
In Blender 2.8 (and higher) the UI changed a bit:

The redo panel is now called Adjust Last Operation (F9)
Make sure your are in Edit Mode and have choosen the right selection mode. It's Edge select (2) for the Select > Select Similar > Length option

Being in Edit Mode select a desired mesh (or meshes) using a face selection. Then go to Select-->Select Similiar-->Perimeter (or Area).

Also note that this is accessible from the keyboard with Shift G while in face select mode.

Perfect! Wish I could accept both answers =)

@Ray Koopa, right choice :). I think gandalf3 's answer is closer related to your question. Nice to hear I helped anyway :).


text:
How to repeat a texture mirrored?
I'm using the Blender render, and miss a texture repeat option I know from OpenGL. It is used in one model which has been finished poly-wise, but texture mapping is wrong.
Look at our good old Lakitu friend here, who has obvious texturing issues:

If you look at the UV mapping on the left, the source to the texturing issue becomes clear: It would be mapped correctly only if the texture would be repeated and mirrored outside its bounds (as if you would use GL_MIRRORED_REPEAT in OpenGL).
However, I do not find such an option in the texture repeat options of the Blender render. Can I only fix this by manually modifying the out-of-bounds UVs (mirroring them back into the texture space and splitting triangles spanning the texture borders)?

try to delete the incorrect texture part and apply the Mirror Modifier again

Will using Mirror option from Image Mapping scroll help ? It may mirror your texture along X, Y or both axes.

@IgorTatarnikov: That wouldn't be an optimal solution, as the model should stay untouched, and some triangles are not aligned on the middle of the mesh.

@MrZak:  You're right... it looked like these options were disabled (half-transparent checkboxes), so I didn't click them! That's exactly what I needed. If you make that an answer, I'll accept it.

What Blender version are you referring to for these comments? That link to the Image Mapping documentation is no longer functional - the documentation defaults to version 2.81, and it doesn't seem to be available in version 2.79 either. Blender is not helping its documentation issues by invalidating old links.

Question and comments are about pre-2.8 and Blender Internal renderer, both legacy now. Not finding any old links.

In order to repeat the texture, at the same time mirroring it, you should check 2 options in the Image Mapping scroll:

increase value of the Repeat slider to something more, than 1 (otherwise Mirror options will continue being disabled, like you've mentioned);
check Mirror X and / or Mirror Y checkboxes.

The texture will be repeating as the pattern, mirrored on selected axes.

I had the same problem and this answer solved it. You can use the ping-pong node:

The 'image mapping scroll' from Mr Zak's seems to have disappeared in newer Blender versions.
The downside to this method is that the texture is un-mirrored again if you export, to .FBX for example. If someone knows how to avoid that, please leave a comment or edit this answer...


text:
Export FBX options are missing
I'm trying to export one of my meshes however the options which I normally would have when exporting my mesh as an FBX are missing. Primarily what I need is to export selected objects only as it's exporting the entire scene.

I am guessing you have a bad UI layout in file.
(They changed the export layout in 2.81. Did you open up the 2.81 beta, save the file, and return to 2.80?)
Try to close blender, Re-open it with default scene, go to File->Open, deselect "Load UI" and open your blender file. Export settings should be back now.

If that does not work, (Or you are also missing the Open Blender File settings), go to File->Defaults->Load Factory Settings, then File->Defaults->Save Factory Settings.
Restart blender and try to deselect "Load UI" again.

So it looks like using the Blender 2.81 and then going back to 2.8 is what's causing the issues. Going back to 2.81 allowed me to export everything without any issues.

Why is the export menu's UI saved to the .blend file? Why would it ever make sense to save this information?

@AaronFranke Most of UI layout in a blender project is saved in the .blend file. It can really useful to return to an old project and have the same setup. (Or different projects with different setups.) In my opinion, it could save more to .blend file. Not just the export layout, but most recent export configuration setting (obj/fbx/etc) should be included too. So I can quickly re-export a model with same settings as last time.

This answer really saved my day, I was stuck trying to figure out why in the world the exporting options were gone... Thank you so much


text:
Knurled pattern on different types of surfaces
What's an efficient way to make a knurled pattern on any surface? I am able to get great results on a simple square surface, but when it comes to anything else it becomes very tricky.
Here's what I made on a simple square surface:

Here's my best attempt on a circular surface. I had to make the pattern on a square surface, then do a knife project to cut out a circle. Then I just put a cylinder behind it...

Here's what I'm modeling. End goal is a game ready asset. These patterns will be used to bake a normal

Any tips would be very appreciated! I'm doing the mag eject button, still need the trigger, safety, and slide release. Would be great to have a better way of doing this to save time.

Since this is a geometrical pattern, did you try using a displacement map? you can prepare the pattern in a graphic app "like Illustrator" then apply it as a displacement map after unwrapping the object.
Another method is using texture mask in Sculpting Mode, then use a large scale brush to make the unmasked mesh bump out. Of course you need to have a Multires Modifier applied first.

Hi, I had mixed results with your methods. But in doing what you suggested, I learned a lot more about map textures in general and found a solution that works for me. Basically, I'm just making the normal from a simple shape as usual, and then copy/pasting that normal to other parts of the UV :)

Yes, that's a clever way to mix both methods ;)

You could make an inverted pattern that's gonna boolean cut the surface you are going to use.
Then after using it as boolean cut over the surface you want to get that pattern on.
Keep in mind that the pattern you are going to use to cut out the pattern on the object needs to be the inverted version of the pattern. Holes in the object are standing cylinders on your pattern cut-object.
On curved surfaces you could use array and curve modifiers to use the boolean over the surface like so:
The boolean modifier should be applied to the object that's going to have the end result of the pattern. And the operation should be "difference".
This method works for all surfaces you would like to use.


text:
Have multiple parts of model share same UV/texture
I've noticed many people who have their final texture only have one half the model, or have multiple parts of the model share the same UV area. For example, two halves of a gun, or the ridges of a scope mount. How can I accomplish this?

Mark Seams in edit mode and uv map as in image above.

Move UV island on top of the other as in image above. You can do a more precise job than I did.  I did not place them on exactly top of each other because I wanted to emphasize that both halves of the sphere have UV coordinates.  I wanted you too see both almost coincident.
If I did a perfect job and the islands were coincident that would be useful too.  So in the image/uv window you might think some pieces of the uv are missing when they are coincident.  That could be confusing.  Islands can be scaled small, merged to same point, or moved off the uv coordinate area.  So again they would be difficult to notice.
Select the vertices of the discussion, view othogonal, so that the vertices line up, then project.
Lastly there are three modifiers you might consider.  UV Warp, UV Project and Data Transfer.

Hi, that's how I currently do my UV maps. Works nicely, however I was asking how I could for example use the same UV/texture of one half of the sphere for both, with only using the UV space for one half of the sphere

@ethosium, that is what they are trying to explain (in poor english), you only texture half of a model. Then, UVMap two halves to the same area on your texture. You could, in theory, map the entire sphere with only two faces showing in the UVMap.  (one tri, one quad, in ths case.) Then, all faces just get stacked, like layers. (coincident) In blender specifically, model with the mirror modifier, and UV unwrap before applying the modifier, then both halves are done for you.


text:
Bone rotation does not match Model rotation
can someone tell me how to fix my bone rotations being all skrewed up?
preferably with pictures?
as you can see here his model hip is all desynced with the bone hip

you need to correct the parentage, either in Weight Paint mode, or in Edit mode with the Vertex Groups list where you can assign the vertex to the group you want.

Hard to tell with so little infowes, I think you should upload your file.

here is the link to the link :P https://drive.google.com/open?id=1jCtVwGrpB8jsSrX-HJOWVn4WSeDpMIW7


text:
I want a linked duplicate to keep form change but have separate material
My goal is to have two meshes that deform together as linked duplicate, but that each have it's own material.
I tried to make single user material only but it does not work. It just makes both meshes to have the same new material.
Either I manage to have both form and material being linked, or both unlinked.

https://blender.stackexchange.com/questions/143434/different-materials-with-linked-objects


text:
Distort object coordinates into a spiral
Good day guys, I'm failing misserably on distorting the coordinates for a texture in a spiral pattern for an object, my target is to display a spiral of clouds onto a sphere, and those clouds to look like a spiral wrapping around it, in a faction similar to the one in the picture
Could someone better in trigonometry than me provide an idea on how to perform this?
Thanks in advance

I reckon you're fine with seams between the marked lines marking the flow of the spiral? You can't stretch the coordinate space to be side-by side with space that is one circumference before/after without a seam or some extreme, ugly stretching in the opposite direction to the main stretch direction.

Alternatively, you don't want to change the coordinate space at all, which is the X in XY problem whereas the real problem, Y, as described, is just to make clouds following a spiral...

To achieve what you want, you may do as little as shifting the texture coordinate upwards based on angle - I'm using the UV map, because the UV sphere already has the azimuthal angle unwrapped to $U$ (x) axis.
The generated "Color Grid" texture puts one caption per each 128×128 pixel square, so as I'm using a default 1024×1024 dimensions texture, I have 8 rows (8×128 = 1024) in the texture, therefore in order to align the captions after the shift, one needs to  shift by a multiple of one row: ⅛ or 0.125 of the height:

Imgur mirror (SE image hosting has problems)
I'm adjusting the effect to the texture to look nicely but any vertical displacement will do, question is just what is the climbing rate of the spiral you want. On the GIF above I shifted by two rows (0.125 × 2 = 0.25) so that the alternating row coloring matches:

Imgur mirror
The shearing happens where the UV seam already was, so you don't get any additional seam, and any seamless logic you would use on normal UV map of a UV sphere, you also have to apply here, just with an adequate $V$ offset (here the two rows offset).
You can however recalculate the texture coordinate to have a single strip, that then has the seams on the edges of that strip, where its glued together to self; remember to change texture to adequate, here I divided the height by 8 (to get only one row) and multiplied by 8 (to keep the same area), resulting with 8192×128 texture:

Imgur Mirror
Where the old seam used to be, there are still color grid cell boundaries just because of my exact maths, but you could for example animate the texture by adding #frame/1000 to the x coordinate, and then you would see it is in fact continuous:

Imgur mirror
Now let's adjust some values to be able to go back to a square texture as likely you will use one (and generated textures are square):

Imgur mirror
Isolate the logic as a custom group because it will be needed twice:

Imgur mirror
And now it's easy to generate two strips, one based on modified original coordinate by half of a row so that one strip overlaps the seam of the other. Using ping-pong to get a smooth edge on that top (actually bottom in nodes) strip, it can smoothly mix with the bottom while covering the seam. I purposefully only stretch one strip's coordinate to make it more visible:

Imgur mirror

Imgur mirror

Great! thank you


text:
Problem with bluring a light which is behind another object
Good night, I have a problem on applying blur effect on the node compositer on an object which is between 2 other objects, like this:

I can't find a way to make the blur look just like the shot itself :S anyone could give me a hand? thanks :D

Try and re phrase your question, I don't quite understand what you are looking for. Both images looks like they have blur applied to them. Insufficient blur ? Or is it glow effect you are looking at? Or is it that in the first image, some the laser should be occluded and they are showing through the model? A blend file from you may help us to troubleshoot your issue.

mmmm I need the gaussian blur to be applied to just the shot, the motion blur is applid to both
yeah, I was looking for some glow effect for the shot and adding a blur was the way I figured on how to do that

You will need to find a way to capture the layer alpha mask for the laser beam you want to affect. Then isolate the laser beam using the mask and apply the blur before compositing on top of the back plate. You might also add the compositing node you have at the moment for a preview of how your node setup is like at the moment.

can't find a way to diferentiate one object from another, should I separate the wings in 2 different objects on different layers? what if the ship would turn around and shoot? I can't find a way of doing that :S

Could you attach a simplified version of the blend file and I will try to see if I can create a mask from the laser beam on every animation frame. Basically you will want a black and white mask to tell the compositor which part of the laser you wanna see minus the ship object's alpha.

I finally solved it by using pass index on the material :) thank you anyway dude :D

It would help others in future if you post your finding in the answer box below ? Cheer glad you found your solution.

Finally I could fix the problem by using index pass as factor for mixing the image in the compositiing nodes. I used the original image itself and its blurred version as the inputs for the mixing.


text:
How to apply rotation on a loop on BGE?
I have this problem, I created a while loop in my script, my intention is to rotate my object with a decreasing over time speed
My script looks like this:
def rotar(obj, sentido):
velocity = 2
while velocity > initialVelocity:
    obj.applyRotation((0,0, sentido*velocity), True)
    velocity = velocity/1.5
    print(obj.worldOrientation.to_euler().z)

The loop isn't working as intended, as it applies the rotation after all the loop ends, how can I apply the rotation on each iteration of the while loop?
I also would love to set the limit of the rotation where the object reaches certain rotation, say 72º on the local Z axis, but for the moment it seems like a dream

You can do it with this but need more work.
This example rotate a cube from 0 degrees(0.0 radians) and stop when it reached 170 degrees(2.96 radians, when distance angle of cube and angle to reach is 0) even if key still pressed (you can work on that to meet your need), it slow rotation when key is relase if the angle is not reached, but the problem is that if the rotation speed go less than 0 will start a turn to the other way (set minimun rotation speed, actual is set to 0.002) and if angle is more that 180 degrees(3.13 radians) the radians will turn negative e.g 181 degrees(-3.14 radians) so you need to work on that.
Have nice a day!
from bge import logic
import math

class Rotation():

    def __init__(self, owner, angle):
        self.rotation = 0.01 # rotation speed
        self.rotate_bool = False
        self.rotating = False
        self.body = owner
        self.angle_to_rotate = angle
        self.main = self.state

    def rotate(self):
        self.body.applyRotation([0,0,self.rotation], 1)
        self.rotating = True

    def relase(self, distance):
        if self.rotation > 0.002 and self.rotating:
            self.rotation -= 0.00002 #decrease rotation speed
        print('rotation:',self.rotation)
        if distance > 0 and self.rotation > 0:#avoid negative rotation, it will turn the other way
            self.body.applyRotation([0,0,self.rotation], 1)
        elif self.body.localOrientation.to_euler().z == math.radians(self.angle_to_rotate):#Stop rotation when the angles are equal
            self.body.applyRotation([0,0,0], 1)
            self.rotating = False

    def state(self):
        rotation = self.body.localOrientation.to_euler()
        angle = math.radians(self.angle_to_rotate)
        angle_distance = angle - rotation.z
        print(rotation.z, angle, angle_distance)
        if self.rotate_bool:
            self.rotate()
        elif not self.rotate_bool and self.rotating:
            self.relase(angle_distance)

def main(cont):
    key = cont.sensors['Keyboard']
    if not 'init' in cont.owner:
        cont.owner['rotation'] = Rotation(cont.owner, 170)
        cont.owner['init'] = True
        return
    if key.positive:
        cont.owner['rotation'].rotate_bool = True
    else:
        cont.owner['rotation'].rotate_bool = False
    cont.owner['rotation'].main()

related: Damped Steering>Seek via Python

I have accepted it, although I couldn't finish to implement this, but I'm so much closer thx to you

what problem do you have?

related: Damped Steering>Seek via Python

A Python controller describes the operations within a single point in time (logic frame).
This means your code performs all turns at the same point in time. The render will take place after your look completed (regardless how long your loop takes).
Animations are (change) operations over time. That means your Python controller should perform a single turn, rather than all turns. You execute the controller as long as you want the animation to take place.
Example:
def rotar(obj, sentido):
velocity = 2
if velocity < initialVelocity:
    obj.applyRotation((0,0, sentido*velocity), True)
    velocity = velocity/1.5
    print(obj.worldOrientation.to_euler().z)

(Replaced while with if in your sample)
Continual animation
While the above code performs the behavior of a single frame you need behavior at an higher abstraction.
E.g. you want:

when pressing a key

determine the final orientation
start turning

when the orientation reaches the final orientation

end turning

while turning

rotate on step towards the final orientation

You might discover a slight issue: what happens when the final step is too much? Means: the last step exceeds the final orientation.
As described the object will start shaking as it turns left/right all the time.
Solutions:

stop before the final orientation is reached (it never exceeds, but
might not match the final orientation)
stop after exceeding the final orientation (it will exceed unless it hits the final orientation)
when the last step is larger than the necessary step size immediately apply the final orientation (this will always lead to the final orientation, but the steps are not necessarily of the same size).

My intention is this: on key press rotate an object on the Z axis a predetermined amount of degrees, with a smooth rotation, could you figure out how or a tip for that? thanks

I guess smooth means: over time. This means you turn the object just a bit at each frame until the rotation reaches the desired angle.

But with an IF statement it just rotates a bit on each frame, but when I release the key it just stops, not when a predetermined orientation is reached, that's what I want to do

Another approach:

Parent the object to an empty.
Enable slow parent (with a delay > 0)
set the empty to the target orientation

Due to the slow parent the object will smoothly turn until it matches the empties orientation.


text:
Character forward roll causes reverse rotation with next animation
I'm creating a forward roll animation for my character, and my problem is that if I put that animation and any other animation after it with a blend, then the character does the reverse rotation during the blend time.
It's because the rotation on X axis goes from 0 to 360° during the animation, so as the next animation starts at 0° the blend does what it is supposed to do by going from 360 to 0°.
Is there a way to tell blender to just rotate to the nearest angle?
Thanks


text:
Adding selected objects to active keying set
I'm trying to add selected objects to active keying set but it doesn't work (no error). This is my script:
import bpy

scene = bpy.context.scene

ks = scene.keying_sets.active

for obj in bpy.context.selected_objects:
    ksp = ks.paths.add(obj.id_data, obj.id_data.name+'.location', index=-1)

Where am I wrong ?
Thanks

I finally found in the scene panel that the data path should just be "location", so my code sould be:
import bpy

scene = bpy.context.scene

ks = scene.keying_sets.active

for obj in bpy.context.selected_objects:
    ksp = ks.paths.add(obj.id_data, 'location', index=-1)
    ksp = ks.paths.add(obj.id_data, 'rotation_euler', index=-1)
    # "rotation_quaternion" for quaternion mode

Now it works !


text:
Apply scaling to rigged model without affecting visual aspect
I rigged my model and I realized that it has a scale of -1 on X axis (left/right).
Then if I mirror the model the left bones deform the right and vice versa, I tried "Mirror vertex groups" but it does strange things (seems a buggy function). I though about applying a inverse scaling to the vertices and the scaling the the object but it doesn't work. I don't know how to do.
Is there a script or something to do so ?
Thanks

With the armature selected in object mode, apply the scale - ⎈ CtrlA ->Apply Scale.
Then in edit mode select the all bones, ensure there aren't hidden bones on other layers, and scale -1 on the x axis - SX-1
Now in pose mode the bones should effect the correct side.

Didn't think about that way,  thanks sambler !

Ctrl-A>Apply Scale will set all scale values to one. This will fix that issue, but be careful it could mess up scale animation and anything depended on the scale (save your file before trying it).

In fact this is my problem as NEED to apply the scale to my model BUT it deform everything if I do...

So you tried it, it didn't say in your question...

Yes sorry for that

There is a much easier way to scale models without messing up your whole rig. Just scale the world in metric system.


text:
Scale bone in pose mode without affecting child bone?
When I scale a bone in pose mode it will also affect the size of a bone connected to it. How can do it so that the connected bone keeps the same size?

Uncheck inherit scale in the bone properties


text:
Animation flipped 180 degrees in Unity with .fbx export
I don't know if the problem is in Unity or in Blender. I'm asking both communities.
When exporting an armature animation from Blender with .fbx format and playing it in Unity, it always flips the model 180 degrees before playing it. It sometimes also moves the model to the origin. Both issues shown in the picture below.
Any idea what causes this and how to fix it? I've spent hours trying all kinds of things. The flipping issue I was once able to solve by adding a keyframe to frame 0 that contained the location, rotation and scale data, but that only worked once.

Maybe related: http://blender.stackexchange.com/questions/20859/camera-facing-backwards-when-exported-as-fbx-and-imported-to-fusion-7

Thanks, I did quickly try the 6.1 ASCII export actually, but then the model didn't seem to import at all. I'll try it some more later though, I may have made a mistake.

Well it looks like it's caused by the existence of LocRotScale keyframes in Blender, i.e. keyframes related to the objects rather than the bones. It can be cleaned up either in Blender if possible, or those keyframes can be removed in Unity from the animation window after import.
Also, exporting with FBX version 6.1 instead of 7.4 from Blender seems to eliminate the flipping problem regardless, but not the origin problem.


text:
Make Blender usable on high resolution screen
The Blender UI elements are incredibly small by default on high resolution screens on Windows (15" UHD screen).  I found the Preferences -> System -> DPI setting which can be set up to 144.  This makes Blender usable, but still uncomfortable and difficult on the eyes.  Is there a way to make the UI elements even larger?

under that there is Virtual pixel mode choose : Double

To make the UI elements even larger you can choose Double under the Virtual Pixel mode
this option is in User_Preferences->system

A combination of DPI and Double can really do the trick. My native DPI on my 4k 27" monitor is 164 dpi. I set virtual pixel mode to double and DPI: to half of 164, i.e. 82. So that 2 x 82 = 164. I wish you could go higher on DPI though.

This is obsolete by now ?

Can't find this any more in >=4.0 :-(

Another thing that is very useful is to hold down Ctrl and the Middle Mouse Button to rescale various panels.  This is the same for the 3D Viewport when zooming in or out to view a model.  The Outliner Area is the only place I've found so far where this does not function yet.

By pressing the HOME key on your keyboard, you can reset the resized panels back to the original default size.

Neat trick. I can't figure out how to do this with the keypad on a Surface Book but I was able to do it with an Arc mouse by holding CTRL and "double-tap and holding" the scroll pad. Thanks. Maybe StackOverflow needs to add the ability to have multiple correct answers because both your answer and the answer from @Chebhou are two important pieces of the puzzle.

THANK-YOU! i can now avoid going blind between 4k and 2k res ! :)

Hover the cursor over one of the panels and hit Numpad + or Numpad - keys on the keyboard to change the size of the font and UI elements.

As of the latest version, the setting name has changed.
File > User Preferences
or CTRL ALT U

And the very first entry at the top:
Display: Scale

In blender >=4.0:  Edit > Preferences > Interface > Display > Resolution Scale  (as shown in #Kryztoval's answer)

In version 2.8, this setting is now under Edit > Preferences > Interface > Resolution Scale

It would be cool that blender takes the value of gsettings get org.gnome.desktop.interface text-scaling-factor be default, so one doesn't have to search the option with a magnifier.


text:
Python: How to draw a single element of a CollectionProperty?
I've attached a custom PropertyGroup as mystuff to bpy.types.Object, and this group contains a CollectionProperty named my_array and an IntProperty my_array_index to draw a typical UIList with it.
However, I have no clue how I would make an element of the my_array CollectionProperty editable, e.g. so that I can select it from my UIList, display the element in a textbox, modify it and write it back to my CollectionProperty.
My code looks like this:
# A stupid UIList just drawing the elements of the array.
class MyStuffUIList(bpy.types.UIList):
    def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
        layout.label(str(item.value))

# Element of the array. It just represents an integer but it seems I cannot use
# bpy.types.IntProperty as base class, then MyStuffProperties fails to register.
class MyStuffPropertiesElement(bpy.types.PropertyGroup):
    value = bpy.props.IntProperty(
        name="Int Value"
    )

# The array attached to objects.
class MyStuffProperties(bpy.types.PropertyGroup):
    my_array = bpy.props.CollectionProperty(
        type=MyStuffPropertiesElement
    )
    my_array_active_index = bpy.props.IntProperty(
        # This is the currently selected index in the UIList representing the array.
    )

# A panel drawing the custom UIList.
class MyStuffPanel(bpy.types.Panel):
    ...
    def draw(self, context):
        ms = context.object.mystuff
        self.layout.template_list("MyStuffUIList", "", ms, "my_array",
                                                       ms, "my_array_active_index")
        # Accessing the array like this isn't possible it seems.
        self.layout.prop(ms, "my_array[my_array_active_index]")

You'd like to create an editable name string or something for each UI list item, right?

Almost; I created a list which displays each element of that array. When I select one entry, I wanna edit it below the list.


text:
Python: Imported Curve points lose Z coordinate in Edit Mode
I'm trying to use bezier curves for editing paths of a custom game file format.
A weird bug (?) when switching to Edit Mode makes the bezier spline points lose their Z coordinate, it being set to 0, and I have no clue why.
Here's the code that simply creates a new bezier curve, adds a spline with enough points and feeds it the coordinates of the control points and handles.
# Create a bezier curve object representing the Path.
cu = bpy.data.curves.new("Path", 'CURVE')
ob = bpy.data.objects.new("Path", cu)
self.context.scene.objects.link(ob)
self.context.scene.objects.active = ob
# Add the points to a new spline.
sp = cu.splines.new('BEZIER')
sp.use_cyclic_u = path["IsClosed"]
points = path["PathPt"]
sp.bezier_points.add(len(points) - 1)  # There is already one point in new curves, so add one less.
for i, point in enumerate(points):
    pt = sp.bezier_points[i]
    pt.co = vector_from_dict(point["Translate"], invert_z=True)
    pt.handle_left = vector_from_dict(point["ControlPoints"][0], invert_z=True)
    pt.handle_right = vector_from_dict(point["ControlPoints"][1], invert_z=True)
# Lock the transform as paths are always in the global coordinate system.
ob.lock_location = [True] * 3
ob.lock_rotation = [True] * 3
ob.lock_scale = [True] * 3
return ob

def vector_from_dict(dictionary, invert_z=False):
    # Game file format is right handed with Y up, convert accordingly.
    if invert_z:
        return dictionary["X"], -dictionary["Z"], dictionary["Y"]
    else:
        return dictionary["X"], dictionary["Z"], dictionary["Y"]

As said, this imports fine and looks well at first. Hence this path of birds flying around the palm trees and above the house ceiling in the front:

But as soon as I enter Edit Mode, the path drops down to the floor, the Z coordinate of all points has become 0 (0 is far below the game model)!

It's indeed just Z losing its value, I imported the path again without editing it this time, making it very clear - the correct one is above, the one with the edit attempt lieing flat below:

Going back to Object Mode keeps these "corrupted" coordinates! What is going wrong here?
The file format itself is stored as binary, but also nothing special, and a Path in it can be represented as dictionaries and arrays like this:
{
    "IsClosed": True,
    "PathPoints":
    [
        {
            "Handles":
            [
                {"X": -2374.132, "Y": 2985.336, "Z": 2211.747},
                {"X": -2318.274, "Y": 2964.664, "Z": 1901.128}
            ],
            # Can't import Rotate since no Blender support for bezier point normals =(
            "Rotate": {"X": -2.684734, "Y": 0.167497, "Z": -3.044649},
            "Translate": {"X": -2346.203, "Y": 2975, "Z": 2056.438}
        },
        {
            "Handles":
            [
                {"X": -2277.908, "Y": 2960.383, "Z": 1596.964},
                {"X": -2294.248, "Y": 2989.617, "Z": 1175.442}
            ],
            "Rotate": {"X": -2.808016, "Y": -0.1063031, "Z": 3.136256},
            "Translate": {"X": -2286.078, "Y": 2975, "Z": 1386.203}
        },
        # ... and so on for each point ...
    ]
}

I'm not much into scripting or coding and now very little about Python myself, so apologies if this doesn't fix your problem, but I believe this is happening because your bezier curve seems to be in 2D mode (in your first screenshot), hence when entering edit mode it will automatically ignore any Z coordinates that it should not have in the first place.
Set your bezier curve to 3D either through the Properties Window > Object Data (Curve) > Shape > 3D or using the Pyhton API through bpy.types.Curve.dimensions setting it to 3D

Just wow, how could I miss that? Interesting too see how it behaves when incorrectly set up from code. Setting it to 3D by code with cu.dimensions = '3D' fixes it =D

I had found a few instances of this weird behavior when importing curves with certain addons (DXF, SVG, etc.) The curves would allow setting up points in the Z axis even though they were 2D, then resetting them to 2D would clear up the incorrect Z values, though it had the unexpected benefit of allowing capped 3D curves


text:
Want to join objects for unity
I am making a 3d Tennis game in Unity. I have made human objects in Makehuman and successfully imported them in blender.
I want the human object in blender to hold the tennis recket object imported from another file so that when I animate in unity the tennis racket moves when the hand of the tennis player moves.
How can I achieve that in blender.


text:
How does blender calculate normal and tangent of a single vert for normal orientation?
So if we pick a single vert in normal orientation we will get x, y, z values for the transform.
We do have access to Z from bpy API that will be a vert normal but how are x and y calculated ?
Is there a simple way to check the math behind it?

It looks like it considers a line from object origin to the location of the vertex. So the normal is the vector Normalized((0, 0, 0) -> (x, y, z))

@Gorgious
it looks like you are right for the normal, normal is in the API though so vert.normal is quite easy to get, bitangent will be cross product of normal and tangent (x and z). But what is tangent for a single vert not connected to face

Hehe it beats my algebraic knowledge I'm afraid. It looks like the Red arrow always stays in the (X,Y) plane though, that might help narrow down the calculation. Or you might find it by digging in the source code if you're into that sort of kink ;)

Posting it just in case anyone needs it,
it was quite simple actually
normal of vert is given and
we can get tangent(x-axis) by calculating cross product of normal and Vector((0, 0, 1))
then co-tangent (y-axis) by calculating the cross product of tangent and normal


text:
How can I detect global/local view via python?
is there a way to detect what view global or local is active via python?
Can I set them directly somehow or at least always come back to global one?
In a way where if script is executed view is moved to global no matter what view user is in.

https://www.blender.org/api/blender_python_api_2_74_0/bpy.types.SpaceView3D.html?highlight=local#bpy.types.SpaceView3D.local_view

Here is a trick:
import bpy
is_local_view = sum(bpy.context.space_data.layers[:]) == 0

In "local_view" mode all layers disabled, while in "regular" mode one of them always enabled.

This check is using the context, assuming you are in the 3D view already, you can then exit with localview op;
if context.space_data.local_view:
    bpy.ops.view3d.localview()

It can be done this way:
for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        space = area.spaces[0]
        if space.local_view: #check if using local view
            for region in area.regions:
                if region.type == 'WINDOW':
                    override = {'area': area, 'region': region} #override context
                    bpy.ops.view3d.localview(override) #switch to global view

Thanks to Юрий Сивальнев, I searched the API a little more. The Object type has a property layers_local_view.  It is an eight member list, all false if the object is not in local view. If you know a particular object you would like to check in the local view space, then you can use this property.
https://docs.blender.org/api/blender_python_api_current/bpy.types.Object.html?highlight=local_view#bpy.types.Object.layers_local_view
def is_local(ob):
    if ob.layers_local_view[0]:
        return True
    else:
        return False


text:
How can I select all creased edges with specific weight at once, can be with python

Technically simple thing, how can I check for exact crease weight edges and then select only them? Like only that one edge on the cube ?

AFAIK There isn't a command for this, but here is a simple script which selects all Edge Creases with values above 0.5:
import bpy

obj = bpy.context.object
me = obj.data

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

for e in me.edges:
    if e.crease > 0.5:
        e.select = True
        print (e.crease)

bpy.ops.object.mode_set(mode='EDIT')

Bmesh module solution (avoids toggling into Object Mode):
import bpy
import bmesh

obj = bpy.context.object
me = obj.data
bm = bmesh.from_edit_mesh(me)
cr = bm.edges.layers.crease.verify()

me.show_edge_crease = True

for e in bm.edges:
    if (e[cr] > 0.5):
        e.select = True
        print(e[cr])

bmesh.update_edit_mesh(me, False, False)

Select a creased edge.
Shift+G> Select Similar
Crease.

It will add to the selection other edges with similar crease value. (Similar means 0.01 tolerance)
You can view and edit the selected crease value from the properties panel (toggled with N) on the Transform group.

Ah, perfect! God bless you! Just what I was looking for! :)


text:
How to randomize Animation Nodes spherical/directional falloff?
I want to have a directional falloff effect like in the picture below, but so that the edge is not so uniform and has some "randomness" instead. I'm not asking for how to widen the width of the falloff, but rather how to make it so that some of the objects come down a bit earlier than others, while still preserving the overall directionality of the falloff.

Figured out the answer before posting the question :)
So what you can do is add a wiggle falloff node and mix it with the directional falloff ("add" mode). With the "evaluate falloff" node you can then convert the combined falloff to numbers that are easy to manipulate. The idea is to clamp the resulting falloff so that the top&bottom remain flat, but just the middle is randomized. Then just convert the strengths back to a falloff with the custom falloff node.
It takes some tweaking of the values to get it line up right, but the idea is quite simple. You can see the exact values I used in the screenshot below.
I also added a "map range" node after the clamping, to restore the upper and lower limits to what they should be according to the offset matrix node. (they shift a bit as a result of the clamping)
Hope this helps somebody!

Please accept your answer if it answers the question.


text:
Simple opacity material in cycles?
Does anybody know how to achieve a "simple" opacity material in cycles? I'm fully aware of transparent node and mixing it with different shaders, but that's not what I'm looking for, for various reasons.
I'm looking for a diffuse material that treats all the faces it's applied to as a whole, and just simply reduces their opacity like in Photoshop. Below is a rough example of what I'm talking about:

So what's the main difference here is that with transparency node you can see through the faces and also see all the underlying geometry, and I don't want that. (for aesthetic reasons) What I want is a material like on the right, but without the hassle of different renderlayers and compositing.
I guess this might be too much to ask, but I just feel like maybe it could be done with some crazy node setup in cycles?

Now I feel dumb because I just realised how you can do this after posting the question.. :P
Anyways, here's one way to do it:
It's actually really simple node setup. You just have to combine a diffuse/transparent mix with a fully transparent node, and use transparency depth as a factor.

That way cycles disregards anything that is behind the first "layer" of transparency. Here's the result:

It's a much cleaner and nicer opacity-like transparency for many cases. I'll use it for illustrative/instructional animations and motion graphics, since those are all areas where simplicity is very important and transparent materials are often needed.
And best of all, you are saved from setting up different renderlayers and compositing nodes, and it also reduces rendertimes in many cases because there's no need for multiple renders!


text:
Kind of "soft link" of objects between scenes?
I want to reuse the object of one scene in another. So far, I found two possibilities, both with side effects I do not want:

Copy and paste from one scene to another. However, if I'll edit / correct the mesh in the first scene, I do not see the changes in the second scene.
Linking from one scene to another. This reflects the mesh changes, but also rotational changes. If I rotate the object in the second scene to lay it on the floor for presentational purposes, it also rotates in the first scene, where I actually want it to just stand around for modelling it.

Is there some kind of soft link which reflect mesh changes, but not rotational / position / scale ones?

You can use the 2nd method, linking your object to the other scene.
Link the object to the other scene as normal. Selecting that object (the one you want to be able to rotate but still be linked) navigate to it's 'Object' tab in the 'Properties' window and make it's object datablock a single user by clicking the '2':

Alternatively, you can press U> Object to achieve the same effect, which will make any of the selected objects a single user.
Clicking the '2' makes a copy of the transformational data for the object but leaves the mesh data, the vertices and faces etc as linked, as shown in the 'data' tab:

The '2' shows that the data is now being used by 2 distinct objects, with different transformations, whereas before it was acting as a single object, sharing both transformations and data.

Awesome! Do you know if it is also possible to automatically apply this change to all child objects? I had one child this time and had to do the step of creating a transform data copy twice, once for the parent, once for the child.

I added a bit more info under the second picture, which will make any of the selected objects a single user, if that's what you meant.

Yep, that was it :) thx


text:
part of my model are see through
Every now and then when I am working on a model this happens

Why has it become a different color and then when I import it into UE4 they are see through can i fix this or is this some sort of bug?

Make sure the normals of your mesh are pointing outwards, otherwise UE4 might not draw these faces because of backface culling.

recalculate normals : http://blender.stackexchange.com/a/15812/11431, http://blender.stackexchange.com/a/14922/11431 and http://blender.stackexchange.com/a/8325/11431 should help

Go into edit mode, select all vertices, and press Ctrl+N

yessiree. that's the one. yup yup.

tried to "recalculate answer" as Chebhou asked :)

This usally happens when normals are facing the wrong side of the mesh

Using the backface culling  in the N panel will make the concerned faces transparent (see-through as in your UE4 game engine)

You can check your faces normals with this option in the N panel. This will show you the normals in the viewport.

To make the normals consistent go in Edit Mode with Tab, select all with A (only the bad faces could be enough), and use Ctrl+N (recalculate), or  Shift+Ctrl+N (recalculate the other direction), or select the faces and click Flip directions


text:
Does keyframe 0 have a "special" use case in blender?
In computer programming indexes are (usually) 0 based but the default frame range in Blender is 1 - N which makes me think there could be a reason behind it - similar to last layer being used as a "trash layer" for helper objects - by convention.
So does keyframe 0 have such common "special" use case in workflows (eg. maybe storing default pose) or is it just a UI design choice ?

As the chosen answer isn't exactly right, I'm putting this answer to explain why the frame 0 may have an importance and why animation may start at frame 1.
The frame 0 has some uses in terms of production.

It's the frame originally used by video games software to retarget the bones/armature when it comes to dynamic adjustments. Nowadays, most game engines offer the option to set which keyframe acts as the source for retargetting and some even allow a "dynamic" generated frame -1 for T-Posing, but it wasn't always the case. (For those who don't understand what a source for retargetting, it's simply a frame during which, on every animation, the bones shared among the animations are at the exact same place. The result animation, in game, is the result of the difference between the source and the animation keyframes applied to the generated skinned mesh's bones in-game.)
Some people think that bone retargetting is something new and shiny because it has only been implemented in popular engine base systems in the last decade, but there are games that uses it from as far as around 2000's. For example, if a game has a ragdoll effect, it has a form of bone retargetting. (One example is the game Medal of Honor : Frontline which introduced the real ragdoll effect to the series.)

In terms of production, the frame 0 is often used for the rigging/T-Posing phase. It's a good practice to keep a frame for the T-Posing in case something has to be changed later in production. Some production practices suggest to import/link a rigged model into its own separate animation file, but that doesn't always works with the game engine's imported file format depending on the 3D software used for the animations. (Some 3D animation software don't have the ability to fetch all the data from a linked source file while exporting to different non-native format like FBX or GLB) Hence, the frame 0 is often used to the T-Pose phase while the frame 1 and so on is used for the animations. If you start your animation at frame 0 and then forget to keep a T-Pose at frame -1, you may have a painful time to readjust the skinning/model if, for example, the director request you add some new elements to the animated mesh mid-production.

As anything artist-related, those 2 points aren't laws and artists can do whatever they want. Especially in today's age, game engines have come a long way in terms of adapting to people who might not follow that kind of procedure. Some do it automatically without any user input (like Unity) on top of that.

'0' may be the starting point for programming, but blender is aimed at artists, who may well not have any programming knowledge, for which a zero-starting counting system may not make any sense. Of course, the artist may have programming knowledge and be aware of zero-starting counting, but it is not presumed.
Frame '0' has no significance or importance over any other frame. If users choose to consistently do something with that '0' frame then that would be an individual choice, and not a standard convention (as far as I'm aware).

Ok just wanted to check if it's safe to change this :) btw. I would say 0 counting could make sense even to artists because it's easy to think about distance from start (ie. duration of frame N from start is N-1 if you're 1 based:))


text:
How to make a sphere which number of faces is divisible by 5?
Hy all,
I am a beginner in Blender, I get all things I want done eventually, but this one is a total mystery to me, either it is too simple or simply to hard :):
Original or default UV sphere mesh has 32 faces which make circumference of the sphere (x,y direction), but I want to make a sphere which number of faces are divisible by 5, I+ve tried everything, subdividing, decimating...but can not get number divisible by 5. Merging or dissolving edges is not an option since I want even faces.
Does anyone have any suggestion? Or script perhaps?
Thank you,
Tasha

when you create a sphere hit F6 button to show properties where you can adjust the division of the sphere.

if segments*rings = a number finishing with 0 or 5, it is divisible by 5

The answer here is outdated. If you want Blender 2.8 look at https://blender.stackexchange.com/questions/130930/how-to-change-number-of-vertices-in-add-object-in-2-8


text:
bpy armature smooth rotation animation
I'm using bpy to control a blender armature using Python. I am able to get the armature to rotate properly, but it is a very jumpy rotation, there is no smooth animation of any sort. Is there anyways to create a smooth animation in bpy? This is my code:
 poseTable = [
        ('finger1joint1', 'X', -5),
        ('finger1joint1', 'X', -5),
        ('finger1joint1', 'X', -5),
        ('finger1joint1', 'X', -5),
    ]

for (bname, axis, angle) in poseTable:
    pbone = ob.pose.bones[bname]
    # Set rotation mode to Euler XYZ, easier to understand
    # than default quaternions
    pbone.rotation_mode = 'XYZ'
    # Documentation bug: Euler.rotate(angle,axis):
    # axis in ['x','y','z'] and not ['X','Y','Z']
    pbone.rotation_euler.rotate_axis(axis, math.radians(angle))
bpy.ops.object.mode_set(mode='OBJECT')

add them as keyframes to get the smooth interpolation

Hey Chebou, how exactly would I do that, say I was rotating by 45 degrees. How would I translate that into using keyframes?

take a look at this adding keyframes through python

did you solve this?

No, I added the key frames but the animation is still jumpy. My other problem is that I need to be able to monitor a file or a socket and when new information comes in, rotate the angle of the armature. I don't know how to get this constant monitoring behaviour

i'll try the keyframe thing later, but for the constant monitoring did you try bpy.app.handlers(frame_change_pre)?


text:
Merging isn't solving this. Line apparent in Object Mode
I've highlighted the lines. Tried merging the vertices, but no dice. Not sure how to make it like the bottom picture. The other side ended up pretty well.

Looks like its just edges that are separate from the model

Can you show a wire frame detail?

http://i.imgur.com/Vslir1F.png


text:
How to turn on Eevvee rendering live preview?
How can I turn on Eevee rendering live preview in 3D view window?
The new Blender version has some interface changes, and in the Eevee rendering mode I can render an image, but I don't see live preview of the shading, Bloob and other effects in the 3D view.

How can I turn it on?
Thank you very much in advance!

In the final release of Blender 2.8, you can find this toggle.

Toggle it, and in the renders tab choose Eevee:

It should work now :D

I found Rendered Shading in the Shading menu on the bottom of the 3D view window.

I cant find this menu. I downloaded Blender 2.8 Beta and there is no Shading menu like on your screenshot. Thanks for sharing that screenshot.


text:
Custom hair particle system - wrong directions
I'm trying to create a hair particle system on a sphere. Standard hair particles works exactly like I need, pointing at different directions opposite to the sphere center:

But when I replace them with custom particles, the directions are wrong.

How can I fix it?
Thank you in advance!

There may be a few issues:

Make sure the origin is at the bottom of your particle object. LMB  on the bottom of the object, then press ⌃ Ctrl + ⌥ Alt + ⇧ Shift +C, then press origin to 3D cursor:

The rotation of your objects looks off. In the hair emitter's particle settings under Render, check Rotation:

Then, in the settings of the object being duplicated as hair, rotate the object until it looks correct. For me, it was XYZ 45/90/45, but it may be different for you:


text:
Join objects (boolean) with different materials
How can I join 2 objects using the Boolean modifier, but keep their original materials assigned to them?
If it is impossible - is there another way to join 2 intersecting objects and remove useless geometry inside the intersection area?

To keep the existing materials on meshes in a boolean operation, simply put the material on those objects on both material lists. For example Cube 1 has Material 01 and Cube 2 has material 02. For those two objects to be joined in a boolean operation and keep their respective materials Cube 1 MUST have Material 01 AND Material 02 in its material list and vice versa.
Two objects with different material lists:

Now the completed Boolean with the two materials in the one list of Cube 2:

If I did not put both materials in then the original one overwrites the mesh material because the material no longer exists (child material data dissolves in a union operation) so you must make sure the material actually "exists" so that it can stay on the object. Hope that helps :)

Thank you very much, it works perfectly! :)
I also found a small cheat: you can select the second object, go to edit mode and select all the vertices. After completing the boolean operation go to edit mode and you will see the vertices still selected, and you can assign material to them. But it makes sense only if the whole object has the same material.


text:
How to render depth pass with alpha channel transparency in cycles?
I have a 3D object in the empty scene. I can click on the "transparent" checkbox to make a render with a transparent background. How can I render depth (or any other) pass with transparent background the same way?
Maybe I can use the alpha channel as a mask in compositor? What is the best way to do it?

https://blender.stackexchange.com/questions/27044/compositing-fog-destroys-png-alpha-in-images-as-planes-when-using-cycles

Yes, you need to use the alpha channel as a mask since transparency is not taken into consideration in the depth pass.
This is how I have done it:
I used the node called "Set alpha".
I Plugged the depth into te "image" and the alpha pass into the "Factor"
the normalize is optional but helps to see the depth better.

Could you please explain how can I do it, what should the node tree look like?

Just like it's there, that's all there is to it

Thank you very much, that's what I was looking for!