text:
Shadows won´t dissapear even with Light
I applied a texture on a UV Sphere. But it has a shadow on it, even though I placed 3-4 Light sources.
It seems like the shadow is moving with the camera. I can not figure out why and how.
Do you know what this is? Screenshots below

Here is the wetransfer link with the Files:
we.tl/t-XF3ej9V6hx
Updated Link with the screenshots and the Texture:
https://wetransfer.com/downloads/c1242365d72957744ac6dac7de118fc820230811114808/133c22640cb585327203c2f323fff82920230811114826/fc24c5

Hello could you please pack the images and share the file? https://blend-exchange.com/

Sure, but with the File, the size is too big. max. 30 MB

I can provide a wetranfer link if you want

Yes please copy paste the wetranfer link

Hey, sry it took this long. I wasn´t home during the past few days. But here is the wetransfer link with the Files. https://we.tl/t-XF3ej9V6hx

You didn't pack the images, tbut the problem is probably that you have a weird setup of 3 nodes: Displacement > Bump > Normal Map??!!???

As mentioned @moonboots you do have a weird set of nodes.

Plus, they have quite exaggerated values (like the Bump node's 139 distance).
You also seem to use twice the same texture, so you could just remove the second node and plug the first one in the roughness socket. The color ramp inverts the texture's color, but as we will see later: it isn't needed there.
Normal input in Principled BSDF
Principled BSDF's Normal input controls the normal of the shader on a per-pixel basis and is meant to fake 3D shape.
The Bump works from a black and white texture and interprets it as elevation, while the Normal Map works from a RGB texture where each pixels represents a XYZ orientation.
The Displacement node is similar to the Bump as it takes a black and white texture and interprets it as elevation, but it is meant to actually deform the geometry and is plugged in the Material Output node's Displacement input.
There are only two nodes you should connect between a texture and the Principled BSDF's Normal input: the Bump node or the Normal Map node.
In your case, your texture is a black and white data, so I would keep only the Bump node, and give it more reasonable values.
Height reads black as the lowest point and white as highest by default. If your texture uses a different system, that's where the Midlevel setting us changed. It is by default set to 0.5, and in some rare cases needs 0 or 1.
Your texture seems to use the default height representation, so not only the Midlevel should be 0.5, but you also do not need to invert the texture with your color ramp.

Displacement
If you want to displace the geometry, plug in the Displacement node where it belongs.
By default, it is treated as a Bump Node and will look weird if used while using another Bump Node. You could either remove the Bump node and set the shader's Displacement settings to do both displacement and bump, but you can't control them independently, or you keep the Bump node and set the Displacement setting to do only displacement.
Personally I like to keep both things independent for control. Regardless of your preference, you find this setting in the sidebar > Options tab > Settings Panel > Surface subpanel, set the Displacement to "Displacement Only" or "Displacement And Bump".
Displacement needs mesh density, so you need to add a subdivision modifier, and play with the displacement node's scale

Final Result
This is the final result with subdivision level 4:

Good to note for the next time you need to post a blend file online for help:

remove everything not related to the issue
If you need to ship textures: File > External Data > Pack Resources
If you need to ship linked files or libraries: File > External Data > Pack Libraries
Save as a new compressed file : File > Save As > enable Compress in the sidebar before saving

This way I got a 10MB file with your textures included that can be uploaded on Blend-Exchange, instead of your 136MB file without texture. No need to make a zip file with extra screenshots, screenshots are for your question.

To learn more:

Principled BSDF — Blender Manual
Bump Node — Blender Manual
Displacement Node — Blender Manual
Normal Map Node — Blender Manual

Hi, Thank you very much for your help! I updated my first post with a new updated wetransfer link. The Texture and a few screenshots are included in the zip file. I will try to adjust the settings as you described.

I update my answer with new screenshots and details, but it's the right solution.


text:
Python: access addon preferences default value
How to access the default value in addon preferences
class TEST(bpy.types.AddonPreferences):
    bl_idname = __package__

    test_int: bpy.props.IntProperty(name = "", default = 9)

bpy.context.preferences.addons[__package__].preferences.test_int = 0

# given a string to get property default value
def return_default_value(name):
    P = bpy.context.preferences.addons[__package__].preferences
    output = P.bl_rna.properties['test_int'].default
    return output

if return_default_value("test_int") == 9:
   print("success!")

In which case this should answer the question https://blender.stackexchange.com/a/31041/86891

The edited version of the question makes it perfectly clear that the proposed duplicate does not answer the question.

source: Stack Exchange

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

sort: votes


text:
Python: Check data path is valid of driver variable
Need a function to check the data path is valid of driver variable target

import bpy

# add cube in object mode
bpy.ops.mesh.primitive_cube_add(size=1, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
cube = bpy.context.object
md = cube.modifiers.new(type="BOOLEAN", name="boo")

fc = md.driver_add("double_threshold")
dr = fc.driver
vs = dr.variables
v = vs.new()
tar = v.targets[0]
tar.id = cube

# end add cube

def is_path_valid(tar):
    tar_id = tar.id
    path = tar.data_path
    if path == "":
        return False
    else:
        # Other casees
        # for example:
        # 'modifiers["hello"].solver' --> return False
        # 'modifiers["boo"].solver'   --> return True
        ...

# test
tar.data_path = f'modifiers["hello"].solver'
if is_path_valid(tar):
    print("not red")
else:
    print("red")

# if result is "red", then success

# test 2
tar.data_path = f'modifiers["boo"].solver'
if is_path_valid(tar):
    print("not red")
else:
    print("red")

# if result is "not red", then success

https://blender.stackexchange.com/a/167129/86891 ?

I checked dr.is_valid is True when variable Path == "", it is not success.

why don't you directly test the path and see if it returns something ? like try : eval(path) except (AttributeError, KeyError): return False else: return True

That's a good idea

@XY Please take this as constructive advice.  Blender code should conform to Python's PEP 8 Style Guide.  You use extra white space before equal signs (=) in a way that is explicitly called out as wrong in the style guide.  It makes your code harder to read for people who are used to conforming code.  Please follow the style guide.

I will notice next time.

I think you're confusing yourself by trying to insert a function that returns true or false. Python already makes this stuff easy, You don't have to do "if tar.data_path == '' or vice versa.
In some languages, there are terms like "Truthy" or "Falsy" meaning things that evaluate to True or False if you ask the interpreter what it thinks.
Things like a string, float or int greater or less than 0, or a list or dict with a len > 0, that all evaluate to True.
Things like the number zero, empty strings, dicts, sets, lists or evaluate to False.
bool_list = ['', 1, 0, ["foo"], {}]

for b in bool_list:
    print(bool(b))

>>> False
    True
    False
    True
    False

So with your code you could just go:
if tar.data_path:
# Insert the stuff that you want it to do if the path is valid.
else:
# stuff that you want it to do if the path is invalid.

Works in Blender:

Edit - Additional info Regarding use of the 'getattr' operator
Think of getattr(cube, 'data_path') as as another  way of writing cube.data_path. It's only meant to get existing attributes from an object, by passing the string name and the object to the operator.
Usually you only use getattr inside of another function where you don't know what the attribute will be necessarily at runtime.
class Obj:
    def __init__(self, a, b):
     self.a = a
     self.b = b

def get_object_attr_bad(obj, attr):
    print(obj.attr)

# create a new instance of the object
obj1 = Obj(10, 20)

# This won't work because inside this scope the
# attribute "a" doesn't exist yet.
get_object_attr_bad(obj1, a)

---------------------------------------------------------------------------
>>> NameError
Traceback (most recent call last)
      8
      9 obj1 = Obj(10, 20)
---> 10 get_object_attr_bad(obj1, a)

NameError: name 'a' is not defined

def get_attr_obj_good(obj, attr):
    # pass the attribute as a string and let
    # getattr handle it
    print(getattr(obj, attr))

get_attr_obj_good(obj1, 'a')
# works like a charm
>>> 10

A good way to debug issues like this and make sure the object you're working with is to occasionally use the dir() operator or __dict__ attribute , to quickly take a look at what attributes an object has.
# Using the previous example

import pprint

## pprint is a built-in module that let's you
# print nested dictionaries and lists in a more readable way

pprint.ppprint(dir(obj1))

>>> ['__class__', # all the built in attributes that come with
 '__delattr__', # Objects in python

...              # omitted for brevity

 '__weakref__',
 'a',            # our custom attributes
 'b']

# or we can use the more succinct __dict__ attribute. It doesn't
# always work if cause sometimes the object doesn't have the __dict__
# method defined.

print(obj.__dict__)
>>> {'a': 10, 'b': 20}

if you see the example on line 25, it is not work in your suggestion.

I edited the post to make sure it works, It works for me in the blender script editor? Are you sure you're asking a question about the right issue?

It should print "doesn't work" , because getattr(cube, "..") does not exist.

I added more info to my answer.

By Gorgious's idea, use eval to test the path,
any answers can success are welcome.
def is_path_valid(tar):
    try:
        tar_id = tar.id
        eval(f'tar_id.{tar.data_path}')
        return True
    except:
        return False

# test
tar.data_path = f'modifiers["hello"].solver'
if is_path_valid(tar):
    print("not red")
else:
    print("red")

# >>>> red

# test 2
tar.data_path = f'modifiers["boo"].solver'
if is_path_valid(tar):
    print("not red")
else:
    print("red")

# >>>> not red

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


text:
Anti-Aliasing in GPU shader Module(OpenGL)
How to smooth the bound of the shape?
If you run the following script in blender,
you can see the Jagged Edge in that shape.
import bpy, gpu, bgl
from gpu_extras.batch import batch_for_shader

vertices = [[150, 41.52], [150, 71.52], [56, 234.39],
    [30.0, 249.4], [270, 249.4], [244.02, 234.39]]
indices = ((0, 1, 2), (0, 2, 3), (2, 3, 4), (2, 4, 5), (0, 1, 4), (1, 5, 4))

shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices)

def draw():
    # bgl.glHint(bgl.GL_POLYGON_SMOOTH_HINT, bgl.GL_NICEST)
    # bgl.glEnable(bgl.GL_BLEND)
    # bgl.glEnable(bgl.GL_POLYGON_SMOOTH)

    shader.bind()
    shader.uniform_float("color", (0, 0.5, 0.5, 1.0))
    batch.draw(shader)

bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_PIXEL')

So, I try some code to smooth the bound.
bgl.glHint(bgl.GL_POLYGON_SMOOTH_HINT, bgl.GL_NICEST)
bgl.glEnable(bgl.GL_BLEND)
bgl.glEnable(bgl.GL_POLYGON_SMOOTH)

But it has some gap inside. I am no idea how to fix it.

As far as I know (and from looking at the docs), I don't see any smoothing options for gpu module. Also note that bgl is likely to be deprecated eventually.
I know you said you'd rather not, but as my answer, I'd suggest loading an image. Ideally there would be a way to tint the image within Blender (not sure if that's the case), but if not you can create multiple icons of different colors.

It's been four years, and there still doesn't seem to be a way to set anti-aliasing with the GPU module. Such a shame...


text:
How to detect active modifier changed
My goal is to print out a message when you click on the UI to change the active modifier.

I tried different methods but failed
import bpy

def message_callback(*k, **kw):
    print("You changed the active modifier by clicking through the UI!")

# method 1
bpy.msgbus.subscribe_rna(
    key=(bpy.types.ObjectModifiers, "active"),
    owner="method_1",
    args=(),
    notify=message_callback)

# method 2
bpy.msgbus.subscribe_rna(
    key=bpy.context.object.modifiers.active,
    owner="method_2",
    args=(),
    notify=message_callback)

# method 3
bpy.app.handlers.depsgraph_update_post.append(message_callback)

Finally I thought of a way
I provided a draw level solution below, but the performance was poor since the draw function will run a lot on some operations, so I'm looking for another answer.

Does this answer your question? Automatically run a script when an object is transformed or a condition is met - one approach would be to set up (could be programmatically) a driver with a variable being a property of the modifier? Not sure if just any property will work, or you need to set up variables for all of them. On the opposing end of the spectrum, you could use a view draw handler hack.

I'm not considering using the Driver method since I'm using it in addon development. imagine users deleting this driver will then cause some problems, but thanks for your attention.

Check all objects on draw level with poor performance
import bpy
DATA = {}

def message_callback(*k, **kw):
    print("You changed the active modifier by clicking through the UI!")

def check_all_objects():
    for ob in bpy.data.objects:
        if hasattr(ob, "modifiers"):
            if hasattr(ob.modifiers, "active"): # need check, In old version blend file, It is possible that only a few objects have this property and others do not
                if ob in DATA and DATA[ob] == ob.modifiers.active: continue

                store_data()
                return True
    return False

def store_data():
    DATA.clear()
    DATA.update({ob: ob.modifiers.active for ob in bpy.data.objects
        if hasattr(ob, "modifiers") and hasattr(ob.modifiers, "active")
    })

def draw():
    print('draw')

    if check_all_objects():
        message_callback()

# doesn't work if no viewport
bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')

Finally found a good solution that works for me
ACT_MD = [None]
def draw_callback(self, context):
    ob = context.object
    if hasattr(ob, "modifiers") and hasattr(ob.modifiers, "active"):
        if ob.modifiers.active != ACT_MD[0]:
            print('active object changed or active modifier changed!!')
            ACT_MD[0] = ob.modifiers.active

bpy.types.TOPBAR_HT_upper_bar.append(draw_callback)

Iterating over all objects is harsh on every redraw. Maybe it would be enough to only check the active object? After all when you check the active modifier, you do in on the active object, right?

You are right, i forgot this. Can't seem to change the active modifier without changing the active object in UI.

Well you can change the modifiers on an inactive object, if you pin the panel using the button in the top right, but it's a rather extreme usecase and I don't think many people even know it exists. Depends on your workflow.


text:
Changing MakeHuman mesh vertices by scripting
how can I change the mesh in MakeHuman from script? For example, I want to change the geometry of the nose, given that I have the desired coordinates values of the nose vertices, how can I assign these values to vertices by loading from a file or scripting?

You can create a vertex group and then assign the new coordinates to them based on some criteria (for instance traversing from left to right and then down to identify which vertex the coordinate values are getting assigned). It will be easier for users to answer your question if you are more specific. Is it possible for you to share a sample blend file or part of it and the coordinates?

Thank you first. The models I have is somehow credential by our regulations/privacy issues. Could you recommend an example code of assigning the coordinates to the vertex group? I think there must be some, but I have not found any answers after quite some searching work...

Here is a small script that grows or shrinks the nose by changing the z coordinates of the vertices defined in the vertex group 'nose' (please refer the gif above). If you have the new coordinates with you, you need to have some criterion to determine which coordinate is to be applied to which one in the group. For instance you can sort the vertIdxs based on coordinates (cf. the commented line sorting the vertices by y, x and z). If you have that criterion, you can simply assign the new coordinate values in a loop as done in the sample code.
import bpy

def changeSize(by):
    for idx in vertIdxs:
        obj.data.vertices[idx].co.z += by

vertGrpName = 'nose'
obj = bpy.context.object

if(obj.vertex_groups.get(vertGrpName) == None):
    print('Please create a vertex group with the name', vertGrpName, 'for nose vertices')

else:
    vertIdxs = [v.index for v in obj.data.vertices if (obj.vertex_groups[vertGrpName].index in [g.group for g in v.groups])]

    #vertIdxs = sorted(vertIdxs, key = lambda x: (obj.data.vertices[x].co.y, obj.data.vertices[x].co.x, obj.data.vertices[x].co.z))

    changeSize(by = 0.05)
    #changeSize(by = -0.05)

Thumb up for this fantastic answer! It offered much help and brought me on the track.

Glad that it was of use to you :)


text:
Converting metaball object to mesh in python returns empty mesh
In my script I'm trying to:

Create a metaball object (works)
Add metaball elements to it (works)
Convert it to a mesh (returns empty mesh)
Store the data in a bmesh (works, but is of course still empty)
Delete the metaball object (works)

I'd like to understand, why my mesh is always empty and to fix the underlying issue.
My source code:
# Create metaball object
mball = bpy.data.metaballs.new("TempMBall")
mball_obj = bpy.data.objects.new("TempMBallObj", mball)
context.view_layer.active_layer_collection.collection.objects.link(mball_obj)

# Add one element to it
ele = mball.elements.new()
ele.co = (0.0,0.0,0.0)
ele.use_negative = False
ele.radius = td.sk_base_radius / td.sk_min_radius

print([ele for ele in mball.elements])  # Make sure there is data in mball (there is)

# Convert it to a mesh
mball_mesh = mball_obj.to_mesh()
print([v for v in mball_mesh.vertices]) # Empty!

# Store copy of the mesh in a bmesh for further manipulation
bm = bmesh.new()
bm.from_mesh(mball_mesh)    # Still empty!

# Delete metaball object
bpy.data.objects.remove(mball_obj)
bpy.data.metaballs.remove(mball)

# My custom mesh manipulation and writing the bmesh into a different object

bm.free()

Thanks to this answer on blenerartists I now know what my error was.
In order to properly convert a metaball into a mesh you have to look at the evaluated metaball. The correct code looks like this:
# Create metaball object
mball = bpy.data.metaballs.new("TempMBall")
mball_obj = bpy.data.objects.new("TempMBallObj", mball)
context.view_layer.active_layer_collection.collection.objects.link(mball_obj)

# Add one element to it
ele = mball.elements.new()
ele.co = (0.0,0.0,0.0)
ele.use_negative = False
ele.radius = td.sk_base_radius / td.sk_min_radius

print([ele for ele in mball.elements])  # Make sure there is data in mball (there is)

# Convert it to a mesh
depsgraph = context.evaluated_depsgraph_get()
mball_mesh = mball_obj.evaluated_get(depsgraph).to_mesh()

# Store copy of the mesh in a bmesh for further manipulation
bm = bmesh.new()
bm.from_mesh(mball_mesh)

# Delete metaball object
bpy.data.objects.remove(mball_obj)
bpy.data.metaballs.remove(mball)

# My custom mesh manipulation and writing the bmesh into a different object

bm.free()


text:
Should I add a sun lamp when using an hdri environment?
In experimenting with an hdr environment texture for the World (with Cycles), I do not see very pronounced shadows in my scene even though the image has an uncloudy sun.  I expect my objects to cast shadows because even though the sky is bright, the sun is much brighter.
For outdoor scenes, is it typical practice to use a Sun lamp in addition to the environment texture or am I missing some other setting?

You might be interested in this post on Blender Nation.

Very informative post.  Thanks very much for the link.

Depends how your hdr looks like. If there is a bright light source, then you might increase contrast for the hdr.
Standard setup gives result like this:

If you increase a contrast:

You can multiply or perform any other mathematical operation to get the brightness and the contrast you like.
Also if you'd like to keep the background plate with the original colors, you could mix in original, unchanged background like this:

I like this approach and will give it a try today.  In your second node setup ( to display the background itself), shouldn't the Environment Texture be set to 'Color'?

Thanks to all that responded but I am marking this as the answer because provides the solution for my problem -- how to get shadows from ibl without using a lamp.  For Blender, the answer is to modulate the Strength property of the background with the image.  There are several node setups that do this.  The one that I found that works best for me is at the end of this blog post.  Also, I found that it is very important to enable Multiple Importance Sample in the World panel.

Yes, the Multiple Importance Sample is important for hdr's that have dark and bright spots, I should have mentioned that too. It gives the bright areas of the hdr higher priority to cast the light rays for the camera and it makes perfectly sense, since it's the bright areas that give more light. It's a little less accurate (but almost unnoticable), but cleans up noise a lot faster.

Oh as for the color space for the Environment texture - I'm not really sure how it works for cycles, but from what I have experienced it doesn't really matter (I may be mistaken here though, so double check this statement) for the background if you pick color or non-color data. The latter simply uses linear color space, which is important for hdr images and helps operating on them for brightness and contrast space, not to mention that it provides much more information on the color. Anyway cycles should handle both in the best way.

Using just a HDR-Environment map leads to less pronounced shadows, you need some objects in the scene to receive the shadow (here just a plane).

HDR environment map from http://www.hdri-hub.com/free-samples more free HDR samples at openfootage
You could add a Hemi-Lamp at a position close to the image's sun get well pronounced shadows:

For comparision the hemi-lamp has been changed by a sun.

I see how that could work, but I thought that it was more common to use hemi lamps as a fill light.  The HDR image is doing that.  The sun lamp gives more realistic outdoor shadows, no?

When using an additional sun instead of a hemi-lamp in the scene the shadow wouldn't be sharply demarcated. I would say it depends on the detail and scene which one is more believable. I added another image for comparision,

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


text:
Which particle system is best for trees in a forest?
In using the particle system to render trees in a forest, is there any advantage in using the Emitter system over the Hair system given that the render will be done in Cycles?
I have played with both using tree images with alpha on planes as well as 3D geometry and can get similar results with either system in my small tests.
I believe that:

Cycles does not support billboards which could otherwise be used in
the Emitter system.  So a track to constraint system is needed in
either case.
If using the Emitter system, I have to make sure the
trees are not dynamically popping in and out during animation.
The Hair system has a special panel for Cycles.  If one is duplicating
objects instead of strands, does it matter?

Hair seems to be the logical choice for grass but is it the best system for trees?  I have seen tutorials for both but perhaps the ones using Emitter are older.

I've always used Emitter to populate a large number of static objects. I don't think hair is needed here.
In the particles panel:

Set the start and end value to -1, and the lifetime to some high value that's longer than your total animation. This avoids any popping in and out.
Turn off particles newtonian physics completely.
Use object instancing or group instancing to replace each particle with a tree
Play with other settings (variable size, initial rotation, etc)

Cycles is surprisingly good at rendering large number of instanced geometry. So unless performance is really important, rending actual geometry shouldn't be too bad. And lastly, this tutorial might help.

It's a good tutorial.  The rocks are instanced objects in the emitter particle system but the trees are placed using billboards (the tutorial does not use cycles.)  The use of weight painting to control the density of the placed objects is really nice.

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


text:
Importing animations for Rigify in Blender for use in Unity
I've spent some time attaching the Rigify human armature to a skin in Blender, I can import the model into Unity and all looks well with the initial model.
I understand the steps involved in creating key frames for animations however I would like to know if there are any default animations which are designed to work with Rigify which I can apply to any skin I import into Blender?
I'd like to use animations composed by someone with more time/experience.

In the unity asset store, there is a seller named Mixamo. They have an animation store that sells mecanim animations, like a run cycle for $10 each.
https://www.assetstore.unity3d.com/#/content/362
Here is a short demo of it:
http://www.youtube.com/watch?v=17V3_j1NZhM
As far as I know, you have to use mecanim (the new and improved animation system in unity).
With the Mixamo animation store you can download and preview the animations on any character. But the names on the bones have to be right. I'm not entirely sure if rigify does this right, should be a minor problem compared to making all those animations.
Edit:
Oups, according to this page:
http://meglassons.com/?page_id=1971
Rigify isn't compatible with mechanim. You have to rename the bones or create the rig yourself.


text:
Armature bones created in python disappear after exiting edit mode
I'm writing an importer for a file format with skeletal data, so I'd like to generate an armature with bones to represent it. I can put the object into edit mode and create EditBones without any trouble, but the bones then vanish as soon as I exit edit mode.
As far as I can tell, exiting Edit mode is supposed to convert EditBones to actual Bones, but that's not happening. Instead, when I exit Edit mode, the armature is reset back to the state it was in before I entered Edit mode.
Here's a test case that can be run line-by-line in Blender's Python console.
# Create a new armature, make it active, and put it into edit mode.
bpy.ops.object.armature_add( enter_editmode=True )

# Add a new bone named "test"
C.object.data.edit_bones.new( "test" )

# At this point, you can see the armature object with two bones ("Bone" and "test") in the Outliner

# Exit Edit mode by switching back to Object mode.
bpy.ops.object.mode_set( mode='OBJECT' )

# Result: the "test" bone vanishes without a trace.

I've tried a bunch of variations, all with the same end result. It feels like I'm missing a step; perhaps something to explicitly apply the edits.
I'm using Blender 2.68a and Blender 2.69.

At the point of creation, the new bone's head and tail is both (0, 0, 0), which gives zero (invalid) length. You only need to modify at least one of them, giving a valid length, to keep the new bone outside of Edit mode:
>>> bone = C.object.data.edit_bones.new("test")
>>> bone.head = (0, 1, 0)
>>> bone.tail = (1, 1, 0)
>>> bpy.ops.object.mode_set(mode='OBJECT')
# The new bone won't disappear after exiting edit mode.

I have the same problem but I want to use a matrix, how do I do that?


text:
find the centers of the parts of the object in blender and write them down
I have been fighting with gpt for 2 days now and I can't win(
I have an object with a fairly curved shape

I need to visually divide the object into 25 parts by Y and find out the deviation of their center from the coordinate center for each of these parts. In other words, the position of their center
After each part, you need to write down this value, I think it will be easier to save it in the Color Attribute. Blue color for positive deviation and red for negative deviation
This is how it looks in manual execution on a simplified model
The value depends on the degree of deviation from the center In the case of the green part, this is (0, 0.576172, 0) Blue (0, 0, 0.52214)
We are sort of looking for where the geometric center of the project would be if the object consisted only of this part

I would be grateful for any help.

"I have been fighting with gpt for 2 days now" - imagine spending the 2 days on actually learning Python... So you want to divide the coordinate space of the object into 25 equal y-sections (I see the green line), and for each face find the face's distance to the nearest section's y-coordinate? Are you sure you want Python for this? As it's easier in geonodes. Also: why you need this? It might be an XY problem... https://en.wikipedia.org/wiki/XY_problem

this is definitely not an XY problem
I need this information to correct the position of other objects. I need them to be attached to the center of the object part

Hello, what do you mean by "center" ?

@Gorgious point is important, especially if the cross-sections are not circular, and/or the plane of the cross-section is not defined

Can you present an example of some perhaps simpler geometry (less than 25 parts, maybe 5), input (before) and output (after)?

added an explanation for simplified models, I hope it will be clearer
Sorry for the confusion, this project is just very important to me.

Sorry it still looks like this is missing some parts, maybe this is a barrier language ? A center is the point that is equally distant from all the points of a circle, here I don't see any circle. Do you mean the median displacement along Z axis ? It looks like all subdivisions have the same span along the Z axis ?


text:
Mixamo Character Control Rig Disappeared After Animating
First timer posting on the exchange, I've hit a bit of a wall here. I've searched just about everything I could think of but haven't been able to find a solution or at the very least a reason. Basically what happened was I created the scene below with a fight animation that played all the way out. I used the Mixamo blender add on to create a control rig for the Mixamo alien character. I completed the animation saved everything and then moved on to my main file where I then appended this animation. To the problem now a few weeks later when I come back to this animation file I found my armature basically in a correctly oriented T-Pose and all of my control rig layers were missing. I tried Alt-H in object edit and pose mode but no luck in unhiding the control rig. Anyone got any suggestions to save this scene as I wanted to add on to the current animation. This is 3.3 btw.
Also on a side note (I think) does anyone know why when I originally appended these characters into this scene I got all the control rig objects seen at the bottom of the list. You can see them on my character however this is like a different set but if I delete them it also deletes the rig seen on my character. Sorry for the wordy post, any help is appreciated! Dropbox link below.
https://www.dropbox.com/scl/fi/5nzotb3rsa0gsn4h0bf3w/Overgrown-ruins-Fight-Scene-1.blend?rlkey=v3k6dk3nwp9vdjeaoi3d6bh5a&dl=0

I reckon the addon in question is Mixamo in Blender - Substance 3D
Where are the shapes gone
The objects you highlighted in green are what the rig uses as custom shapes. Deleting them doesn't delete anything else, the rig is the same, but the bones only have their default display options possible. It's only aesthetics.
What's going on with the controll rig
When it comes to your control rig, the t-posed skeleton you see is the FK part of the rig.

If you look closer on the hands and feet, you will see you have also the hands and feet's IK controllers, fingers and pole target, which do influence mixamo's original rig:

This is because, as it is right now, your rig is using its IK controllers to animate. And since you didn't use the FK rig, it's left to whatever pose it was.
If you want to switch between IK/FK animation or snap one's controllers to the other, the addon have tools for that in its UI.

Fixing the rig
On itself, you can continue animating as is if you wanted, the rig is functional. Just not in its best looking dress but it works:

Though of course it would make things easier to fix the issues.
Mixamo's addon display a UI that allows you to generate and handle the rig, and I notice there is a rig_ui.py script included in your file that might give you more UI, but it doesn't seem to do anything visible on my side and I couldn't find mention of it in their presentation video.
I couldn't see the custom shape objects in your file, so I guess you deleted them. You can append their collection from an older version, it might work and it's still easier to animate with those than without.
If you don't have an older version to append from or if appending them doesn't work, then I would suggest making a new file and re-generate the rig from scratch with the addon. Then, if you need to, append the animations you made already (or just keep working on a clean file).
General practice
I highly suggest you to always save your rigger character - without any animation of any kind - in a distinct file that you keep clear of any form of edition. Then when you want to work on an animation, create a new empty file, link or append your rigged character in, and save this into a new file for that animation. This will avoid quite a lot of issues, including destroying your rig with no backup.

Thanks so much for the answer! Yes sorry I had delated the backup rig items trying to reduce the file size as much as I could. Thanks for the suggestions I think I'll take your advice and start a new scene with a fresh character and append the animation data in. One quick question, what is the setting you used to display all he bone names in the viewport?

Select the armature and go to Properties Editor > Armature data tab > Viewport Display > enable "Names". For the file size, I bet that you appended your environment in your scene too? Like the rig, try instead to have each asset in a blend file. Then make a new scene where you link the assets and place them around to form the environment and save it as a different file. And in your animation file, you link both the character and the environment. Basically link as many things as possible.

Ok ya this project has had me thinking about best practices more for keeping things manageable on my sub par computer. My final scene will have a large terrain along with high detailed characters with animations and physics simulation so will definitely be necessary. Thanks again for the help and suggestions!

Basically, divide an conquer ;)


text:
Is it possible to apply a 'holdout' to a transparent 'image as plane'?
Does anyone know how to apply a 'Holdout' texture to just the solid image in a transparent image PNG and not the blank area around it?
Thanks in advance

You could use the image as a factor between the Holdout node and the image itself (instead of the image you could use an image with the same background color, or a pure color), use a ColorRamp if you want to make sure that you don't see any black contour:

Perfect! Many thanks!


text:
How to print out all Shared Enum items via Python API
This is the all Shared Enums that I want to print out their names and identifiers of every enum_items:
https://docs.blender.org/api/current/bpy_types_enum_items/index.html
import bpy

def get_all_shared_enum():
    ...
    return [...]

for rna in get_all_shared_enum():
    print(rna)
    for item in rna.enum_items:
        print(item.name, item.identifier)
    print()

If not, how to print out one Shared Enum like Window Cursor Items: https://docs.blender.org/api/current/bpy_types_enum_items/window_cursor_items.html

Unfortunately it seems it's not directly accessible to the API. The only way I know of is to set the enum prop to a known wrong value, catch the exception and parse the valid values. You read that right :) https://blender.stackexchange.com/q/284383/86891


text:
How to get last message in console via Python
How to making a function that return the last line of string in the console (Assuming the console is not open). I'm using blender 3.4 and trying to use the stdout method, but it doesn't work, is there another way to achieve

How can I catch reports from Operators in Python script?
My situation is assuming I have a handler running in the background. It runs on every redraw in my add-on. When the user triggers any condition in the interface to display any text in the console, then assign the string to a global variable for me to access in some special cases.
For example, When the value of Rest Source changes from Original Coords to Bind Coords in Corrective Smooth modifier, the console will print a line: ERROR (bke.modifier): C:\Users\blender\git\blender-v350\blender.git\source\blender\blenkernel\intern\modifier.cc:459 BKE_modifier_set_error: Object: "Cube", Modifier: "CorrectiveSmooth", Bind data required.
Since this triggers redraw, I can put a function into the handler to listen.

Do you need the code to be able to retrieve the last line in the stdout stream on your second script run or is it ok if it is in the same script run session?

I think it's the latter.

I think it's not possible to read the lines from the system console. you will have to find another way.


text:
Determine if keyframe of Enum Set match in Python
If the keyframe matches, it appears yellow in the UI, otherwise it appears brown.

Now, add a keyframe to Data Transfer Modifier (data_types_verts)
import bpy

bpy.context.scene.frame_current = 1

ob = bpy.context.object

md = ob.modifiers.new(type="DATA_TRANSFER", name="")
md.data_types_verts = {'COLOR_VERTEX', 'BEVEL_WEIGHT_VERT'}
md.keyframe_insert('data_types_verts')

fc = ob.animation_data.action.fcurves.find(f'modifiers["{md.name}"].data_types_verts')
kp = fc.keyframe_points[0]

print(kp.co)
# >>>> <Vector (1.0000, 134283264.0000)>

Then, the test function should be:
# This time we only consider:
#     frame_current = 1
#     value = {'COLOR_VERTEX', 'BEVEL_WEIGHT_VERT'}

def is_match_of_data_types_verts(fc):
    return fc.keyframe_points[0].co[1] == 134283264.0000

However, keyframe point values may not be the same each time.
If you restart blender and perform the same behavior you may find that it is not always equal to 134283264.0000.
On the other hand, if you use value {'VGROUP_WEIGHTS', 'COLOR_VERTEX'}, it is same as 134283264.0000.
Therefore, my test fails. I'm testing on blender 3.6.

Keyframe value table (Unexpected results)
Value                 | Evaluate  | Binary
-------------------------------------------------------
set()                 | 0         | 0000
{'VGROUP_WEIGHTS'}    | 1         | 0001
{'COLOR_VERTEX'}      | 134283264 |
{'BEVEL_WEIGHT_VERT'} | 8         | 1000

{'VGROUP_WEIGHTS',    | 134283264 |
'COLOR_VERTEX'}

{'COLOR_VERTEX',      | 134283264 |
'BEVEL_WEIGHT_VERT'}

{'VGROUP_WEIGHTS',    | 9         | 1001
'BEVEL_WEIGHT_VERT'}

{'VGROUP_WEIGHTS',    | 134283280 |
'COLOR_VERTEX',
'BEVEL_WEIGHT_VERT'}

Expected
Value                 | Evaluate  | Binary
-------------------------------------------------------
set()                 | 0         | 0000
{'VGROUP_WEIGHTS'}    | 1         | 0001
{'COLOR_VERTEX'}      | 2         | 0010
{'BEVEL_WEIGHT_VERT'} | 8         | 1000

{'VGROUP_WEIGHTS',    | 3         | 0011
'COLOR_VERTEX'}

{'COLOR_VERTEX',      | 10        | 1010
'BEVEL_WEIGHT_VERT'}

{'VGROUP_WEIGHTS',    | 9         | 1001
'BEVEL_WEIGHT_VERT'}

{'VGROUP_WEIGHTS',    | 11        | 1011
'COLOR_VERTEX',
'BEVEL_WEIGHT_VERT'}

Hello, I think you're hitting the floating point data type precision limit. You can't store a number that is both very large and very precise with this data type, you have to choose one of the two.

@Gorgious I guess it is bugs, see my table I added recently.

Ok, TBH I think at first you didn't provide enough context to your problem so it's a little hard to know exactly what going on, thanks for the added explanation. It does seem there is a kind of data type precision limit hit here, but I think it's integer rather than float. Just my 2 cents. It does look like a bug, which should be reported to the official bug tracker


text:
Selected vertex appearance settings
When I select 2 vertices, it looks like a lot of edges are selected.
I am using blender 4.1

Are there any preferences to avoid this?
like reduce its gradient radius

Hello, actually only the edge between the 2 vertices is selected

Sure, that's why I say it looks like..

It's always been like that. The connecting edges to the selected vertex get a slight highlight halfway to easily help you visualize the topolgy, so you know they are really connected. It will help you identify overlapping vertices or edges because they don't get this smooth highlighting.

Thank you for the response. It would be perfect if there was a way to reduce its gradient radius.


text:
How to update edit mesh without exit edit mode in Python
To reproduce the problem and make the script runnable, make sure:

Add a Ico Sphere to scene and
Enter edit mode and select the top vertex

# It moves the selected vertices down a bit
import bpy, bmesh

ob = bpy.context.object
me = ob.data
bm = bmesh.from_edit_mesh(me)

act_vert = next(v for v in bm.verts if v.select)
act_vert.co.z -= 0.2

me.update(calc_edges=True, calc_edges_loose=True)
me.update_gpu_tag()
bmesh.update_edit_mesh(me)

After running the code, it looks like:

When press the Tab key twice (Go to object mode and switch back), the shading are completely different

I know I can run the operator bpy.ops.object.mode_set twice to update the mesh, but I want to know how to update it without exiting edit mode

Using bmesh.update_edit_mesh before the update_edit_mesh
bm.normal_update()
bmesh.update_edit_mesh(me)

or
bm.normal_update()
me.update()


text:
Install new Python modules from within Addon (without sudo/admin privileges)
I am working under Blender 2.90 installed by snap.
If I try to run
subprocess.check_call([bpy.app.binary_path_python, "-m", "ensurepip"])

or
import ensurepip
ensurepip.bootstrap()

from within my Addon, I get told, that the site-packages of my Blender's Python are read-only. Is there any way to circumvent this?

Is this one helping? python - How to import SciPy in Blender? - Blender Stack Exchange

@HikariTW That thread was definitely interesting. However using the mentioned --user option installs the packages under ~/.local/lib/python3.7/site-packages. Is there any way to tell Blender to use those site-packages additionally to those installed under /snap/blender/45/2.90/python/lib/python3.7/site-packages which is unfortunately read-only (otherwise I would have installed my modules there in the first place).

Which OS/build are you aiming for? I don't think modify snap install folder is a good idea. And if addon need to deal with various OS/condition, ensure pip is definitely not enough

I'm on KDE Neon but all I want is for Blender to recognize ```~/.local/lib/python3.7/site-packages````as a place to look for packages.

Not familiar with kde neon, if you know exactly where the packages are: sys.path.append(R"~/.local/lib/python3.7/site-packages") might work?

What does the R accomplish?

stand for raw input without translating \\, it's python feature

Thanks to all the help, I was able to piece together a fully automatic solution that works at least on my system (tests on other Linux and Windows machines planned). It looks something like this:
import bpy
import sys
import importlib
import subprocess

# Blender's Python executable
pybin = sys.executable

def add_user_site():
    # Locate users site-packages (writable)
    user_site = subprocess.check_output([pybin, "-m", "site", "--user-site"])
    user_site = user_site.decode("utf8").rstrip("\n")   # Convert to string and remove line-break
    # Add user packages to sys.path (if it exits)
    user_site_exists = user_site is not None
    if user_site not in sys.path and user_site_exists:
        sys.path.append(user_site)
    return user_site_exists

def enable_pip():
    if importlib.util.find_spec("pip") is None:
        subprocess.check_call([pybin, "-m", "ensurepip", "--user"])
        subprocess.check_call([pybin, "-m", "pip", "install", "--upgrade", "pip", "--user"])

def install_module(module : str):
    if importlib.util.find_spec(module) is None:
        subprocess.check_call([pybin, "-m", "pip", "install", module, "--user"])

user_site_added = add_user_site()
enable_pip()
# All the modules you need, that don't come shipped with Blender
modules = ["module1", "module2", ...]
for module in modules:
    install_module(module)
# If there was no user-site before...
if not user_site_added:
    add_user_site()

Please note that automatic loading of user site-packages was intentionally disabled, see T76993. Manually appending to sys.path works, but there may be a different preferred approach in the future if progress is made on T71420. Until then this approach is a viable alternative.

I'll be more than happy to drop this Frankenstein of a workaround as soon as Blender offers a more elegant solution :D

The paths available in Blender 3.x include /home/my-user/.config/blender/3.3/scripts/addons/modules which is writable. It is possible to install your Python packages in this directory directly. For example:
pip install --target=$HOME/.config/blender/3.3/scripts/addons/modules/ my_package

Or on Windows:
pip install --target=%appdata%\Blender Foundation\Blender\3.5\scripts\addons\modules my_package

That's %appdata%\Blender Foundation\Blender\3.5\scripts\addons\modules in Windows. One can also simply copy the module directories to the directory, from wherever they get install with system Python like maybe %appdata%\Python\Python310\site-packages


text:
Weight paint not working (bug?)
I have this funny document with two scenes (file attached). The plane in Scene1 is nicely subdivided and set up, but cannot be weight painted. However the plane in Scene2 (which is a straight copy) can be weight painted.
Can anyone reproduce this behaviour or is this just happening on my end?

Hi. Please use blend-exchange if you want to provide files for us to check. Random file sharing services won't keep them up long enough.

Okay, I'll try to keep it in mind in the future.

When you're weight painting, you're painting into Vertex Groups.
The vertices you can't paint don't belong to  a group.
There's a difference between a vertex belonging to a group with 0 weight, and a vertex not belonging to a group at all.
If a vertex is not assigned to the active group, you can't paint into it.
Assign vertices (with a given weight) to a group in the Data tab > 'Vertex Groups' panel.
It's very confusing, because by default, unassigned vertices are colored blue, like 0-weight vertices.
You can fix that.. in the Overlays dropdown there's an option, even more confusingly called 'Zero Weights'. (IMO, it should be called 'Unassigned Vertices'.) Anyway, you can use it to display vertices unassigned to the active group, or those unassigned to any group, in black, not blue.


text:
Blender can't handle Numba StructRefs
I know this is really specific, but I don't really know which community to approach here.
I am currently trying to speed up my Python addon for Blender using Numba. As you might know, functions sped up with Numba's njit decorator refuse to take any argument that is not a numpy array or a Python primitive.
The solution to this problem is to write so called StructRefs.
If you want to try it out install Numba into your Blender-Python environment and paste the following code into your clipboard:
import sys
import subprocess
import bpy

# Blender's Python executable
pybin = bpy.app.binary_path_python

# Locate users site-packages (writable)
user_site = subprocess.check_output([pybin, "-m", "site", "--user-site"])
user_site = user_site.decode("utf8").rstrip("\n")   # Convert to string and remove line-break
# Add user packages to sys.path (if it exits)
user_site_exists = user_site is not None
if user_site not in sys.path and user_site_exists:
    sys.path.append(user_site)

import numpy as np

from numba import njit
from numba.core import types
from numba.experimental import structref

from numba.tests.support import skip_unless_scipy

# Define a StructRef.
# `structref.register` associates the type with the default data model.
# This will also install getters and setters to the fields of
# the StructRef.
@structref.register
class MyStructType(types.StructRef):
    def preprocess_fields(self, fields):
        # This method is called by the type constructor for additional
        # preprocessing on the fields.
        # Here, we don't want the struct to take Literal types.
        return tuple((name, types.unliteral(typ)) for name, typ in fields)

# Define a Python type that can be use as a proxy to the StructRef
# allocated inside Numba. Users can construct the StructRef via
# the constructor for this type in python code and jit-code.
class MyStruct(structref.StructRefProxy):
    def __new__(cls, name, vector):
        # Overriding the __new__ method is optional, doing so
        # allows Python code to use keyword arguments,
        # or add other customized behavior.
        # The default __new__ takes `*args`.
        # IMPORTANT: Users should not override __init__.
        return structref.StructRefProxy.__new__(cls, name, vector)

    # By default, the proxy type does not reflect the attributes or
    # methods to the Python side. It is up to users to define
    # these. (This may be automated in the future.)

    @property
    def name(self):
        # To access a field, we can define a function that simply
        # return the field in jit-code.
        # The definition of MyStruct_get_name is shown later.
        return MyStruct_get_name(self)

    @property
    def vector(self):
        # The definition of MyStruct_get_vector is shown later.
        return MyStruct_get_vector(self)

@njit
def MyStruct_get_name(self):
    # In jit-code, the StructRef's attribute is exposed via
    # structref.register
    return self.name

@njit
def MyStruct_get_vector(self):
    return self.vector

# This associates the proxy with MyStructType for the given set of
# fields. Notice how we are not contraining the type of each field.
# Field types remain generic.
structref.define_proxy(MyStruct, MyStructType, ["name", "vector"])

print(MyStruct("a",np.array([])))

The code will run just fine once. Try to execute it a second time and Blender will throw a huge list of errors. Does anyone know why this particular combination of tools works so poorly?

EDIT: Here are the errors I am encountering:
Traceback (most recent call last):
  File "/home/my_username/my_folder/work/Blender/Trees/test.blend/Text", line 84, in <module>
  File "/home/my_username/my_folder/work/Blender/Trees/test.blend/Text", line 48, in __new__
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/experimental/structref.py", line 376, in __new__
    return ctor(*args)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/dispatcher.py", line 434, in _compile_for_args
    raise e
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/dispatcher.py", line 367, in _compile_for_args
    return self.compile(tuple(argtypes))
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/dispatcher.py", line 819, in compile
    cres = self._compiler.compile(args, return_type)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/dispatcher.py", line 78, in compile
    status, retval = self._compile_cached(args, return_type)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/dispatcher.py", line 92, in _compile_cached
    retval = self._compile_core(args, return_type)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/dispatcher.py", line 110, in _compile_core
    pipeline_class=self.pipeline_class)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler.py", line 627, in compile_extra
    return pipeline.compile_extra(func)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler.py", line 363, in compile_extra
    return self._compile_bytecode()
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler.py", line 425, in _compile_bytecode
    return self._compile_core()
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler.py", line 405, in _compile_core
    raise e
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler.py", line 396, in _compile_core
    pm.run(self.state)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler_machinery.py", line 341, in run
    raise patched_exception
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler_machinery.py", line 332, in run
    self._runPass(idx, pass_inst, state)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler_machinery.py", line 291, in _runPass
    mutated |= check(pss.run_pass, internal_state)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/compiler_machinery.py", line 264, in check
    mangled = func(compiler_state)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/typed_passes.py", line 442, in run_pass
    NativeLowering().run_pass(state)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/typed_passes.py", line 372, in run_pass
    lower.create_cpython_wrapper(flags.release_gil)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/lowering.py", line 244, in create_cpython_wrapper
    release_gil=release_gil)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/cpu.py", line 161, in create_cpython_wrapper
    builder.build()
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/callwrapper.py", line 122, in build
    self.build_wrapper(api, builder, closure, args, kws)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/callwrapper.py", line 176, in build_wrapper
    obj = api.from_native_return(retty, retval, env_manager)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/pythonapi.py", line 1388, in from_native_return
    out = self.from_native_value(typ, val, env_manager)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/pythonapi.py", line 1402, in from_native_value
    return impl(typ, val, c)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/experimental/structref.py", line 167, in box_struct_ref
    ctor_pyfunc = c.pyapi.unserialize(c.pyapi.serialize_object(obj_ctor))
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/pythonapi.py", line 1363, in serialize_object
    struct = self.serialize_uncached(obj)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/pythonapi.py", line 1334, in serialize_uncached
    data = serialize.dumps(obj)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/serialize.py", line 168, in dumps
    p.dump(obj)
  File "/home/my_username/my_folder/blender-2.83.0-linux64/2.83/python/lib/python3.7/pickle.py", line 437, in dump
    self.save(obj)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/serialize.py", line 305, in save
    return super().save(obj)
  File "/home/my_username/my_folder/blender-2.83.0-linux64/2.83/python/lib/python3.7/pickle.py", line 549, in save
    self.save_reduce(obj=obj, *rv)
  File "/home/my_username/my_folder/blender-2.83.0-linux64/2.83/python/lib/python3.7/pickle.py", line 638, in save_reduce
    save(args)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/serialize.py", line 305, in save
    return super().save(obj)
  File "/home/my_username/my_folder/blender-2.83.0-linux64/2.83/python/lib/python3.7/pickle.py", line 504, in save
    f(self, obj) # Call unbound method with explicit self
  File "/home/my_username/my_folder/blender-2.83.0-linux64/2.83/python/lib/python3.7/pickle.py", line 774, in save_tuple
    save(element)
  File "/home/my_username/.local/lib/python3.7/site-packages/numba/core/serialize.py", line 314, in save
    raise _TracedPicklingError(m)
numba.core.serialize._TracedPicklingError: Failed in nopython mode pipeline (step: nopython mode backend)
Failed to pickle because of
  PicklingError: Can't pickle <class '__main__.MyStruct'>: it's not the same object as __main__.MyStruct
tracing...
 [0]: <class 'method'>: 140247150191712
 [1]: <class 'tuple'>: 140245505894272
 [2]: <class 'type'>: 140247018660896
Error: Python script failed, check the message in the system console

EDIT2: Following Londo's suggestion I changed the last function define_proxy to define_constructor which left me with the following error message:
TypeError: cannot convert native numba.TreeNodeType(('location', int64), ('parent_obj_id', array(float64, 1d, C)), ('weight', int64), ('weight_factor', float64), ('child_indices', int64)) to Python object

Maybe pasting a huge list of errors here would be helpful

@AndreySokolov Sorry, I completely forgot about that. There you go!

it's nothing wrong with your code. it runs just fine when it's set up correctly.
You only have to encapsulate your code within the Blender Environment.
I'd assume:
A new Blender instance was generated as it has been launched.
As you called your script its structure was bound to the Blender instance.
As you called it the 2nd time the Blender instance remained the same but your script generated a new instance of its own.
since the first instance is tied to the current Blender instance and did not receive a destruct call, it's still running. And the comparison of the new instance id with the tied instance id will always fail.

as you can see I only made a simple panel-addon in which your code is embedded.
your script is tied to the blender instance and does not generate a new instance of its own as long as its active instance is alive or you close the Blender instance.
you may find a better solution to handle your instances. My solution is only for showing the result:-)

What happens when you try reloading your addon?

after a little tweaking it does the same thing again.
when you alter "structref.define_proxy" to "structref.define_constructor" it will stay in the same instance. you will receive conversion warnings which won't break the code as the vanished instance error did. you only have to tweak the type definition, if you wish. but the code keeps running even after reloading the scripts

This is really strange. I instantiate my StructRef objects as part of an Operator, so everything should be deleted as soon as the execution is finished. Note that the error does not occur on multiple executions but rather after reloading my scripts. Exchanging the define_proxy function by define_constructor produced just another error (see edit on my question).

yeah the warning your receive is what I was hinting to, as I mentioned to tweak the types definitions of your struct.
I read in the numba doc that its class destructor is being called automatically when each operation has been finished but you haven't have the possibility to call the destructor manually, by now.
what if the finish call is never being send to numba because it's running in a blender instance and its state is never set to finish as it runs now?

I do not recive a warning but an error. My code does not run with the method you suggested, unless I misunderstood you. What exactly do you mean with "tweaking type definitions"?


text:
Why is the rotation constraint between two bones behaving so strangely?
I'm currently trying to constrain the rotation of some hand-bones in my rig to an IK-bone.
However when using the rotation constraint my hand bones (Thumb.001, Index Finger.001 and Middle Finger.001) behave unpredictable. I would expect them to stay in their default position and rotate if I rotate the IK-bone. But as soon as I add the constraint the bones snap into seemingly random positions.

I uploaded a minimal working example demonstrating the problem.

Use local space -> local space instead of world -> world.

@Nathan But I want my bones to act as if they were attached to the IK-bone. In local space they would start rotating around their respective axes.

Then parent them to the IK bone, or parent them to bones with the same local axes as the IK bone which also copy rotation from the IK bone.

Thanks for the tip. While I knew of that workaround, I would like to understand what the problem is first before changing my hierarchy. That is something I am trying to avoid.

The target has non-zero world space rotation even at rest, because its axes are not aligned with world axes.  This rotation is then applied to the constrained bone.

@Nathan so the difference between the targets axes and the world axes is applied in addition to the pose rotation?

Yes, you're measuring its world-space rotation, which isn't zero.  Any pose on the target will change that rotation as well (but it might make it zero rotation, it just depends on what the posed rotation is.)

Thanks to Nathan's comment below my initial question I figured out why my constraint behaved unlike I expected.
When setting the target coordinate system to World Space it's initial rotation relative to the world origin will be added to the constrained bone. This can be avoided by changing the Target value of the constraint to Local With Parent (or Local) and the Owner value to Custom Space. Then select the target bone as reference for that custom space.


text:
Importing C++ functions created with pybind11
I am currently trying to create a C++ library with pybind11. My .cpp-file is a simple test and looks like this:
#include <pybind11/pybind11.h>

namespace py = pybind11;

std::string test()
{
    return "Test successful!";
}

PYBIND11_MODULE(TreeGenModule, m)
{
    m.def("test", &test);
}

Opening a Python interactive console I can import my compiled module and use the test-function.
However when importing the module from within a Blender-addon I'm trying to write, I can import the module itself but the interpreter cannot find any of the defined functions.
Any ideas why this error occurs?

EDIT:
Here's what happens if I navigate to the folder of my module and import the module using an interactive python session:
Python 3.7.9 (default, Nov 20 2020, 02:21:39)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import TreeGenModule
>>> TreeGenModule.test()
'Test successful!'

However, if I try the same import from within my module and invoke TreeGenModule.test():
AttributeError: module 'TBO_Tree_Gen.cpp_bin.TreeGenModule' has no attribute 'test'

So after some digging I found out, that this was caused by importlib.reload.
Blenders Reload Scripts-command only reloads the addon if the main file (in my case __init__.py) has been changed. (Also discussed here)
Since my addon consists out of several .py-files and I wanted everything to be reloaded if I hit the command, I used importlib.reload to manually force reloading.
I also used this technique on my C++-module, which you're not supposed to do!
Reloading C++-modules with importlib is not supported and may result in errors, just like in my case.
After removing this reloading instruction my C++-module works just fine in Blender. The only downside is, that I'll have to restart Blender, whenever I change my C++-module and want to see these changes in effect.


text:
Bugged script reload in Blender 2.90.1
If I hit the "Reload Scripts" command in the most recent blender snap
latest/stable:     2.90.1 2020-09-23 (47) 187MB classic
I get this cryptic error message:
  File "<string>", line 1
    def fn():
      ^
SyntaxError: invalid syntax

location: <unknown location>:-1

location: <unknown location>:-1

This happens regardless of which .blend-file I open up and which Addons are within my load order.
This does not happen on the older
2.83lts/stable:    2.83.6 2020-09-09 (46) 170MB classic

UPDATE:
I managed to reproduce this error also in the (Linux) binary that can be downloaded from Blender's homepage.

grep your blender folders for def fn  .. do you have any scripts in ..../2.90/scripts/startup  folder?

The grep returned no finds (except for something within the blender binary, maybe that's our culprit?). Within my scripts/startup directory there were a bunch of folders with python code, however no matches for def fn.

How are you executing the operator? From the search F3 or python console?

@RobertGützkow I am using the F3-menu to execute the operator.

FYI op  is also available via top LH corner  blender icon menu Blender > System > Reload Scripts  Meant to mention too, as well as your install folders there are your user folders, on ubuntu for example  ~/.config/blender/2.90/    Latest post would suggest that it is an external script.

@batFINGER my user folders are not the problem since this bug also occurs if I execute Blender as superuser. https://developer.blender.org/T81112 suggests that the devs are already aware of the issue.

Good one.  Consider putting together an answer, or could close as "about a bug in blender"  NP  kinda meant . ** ("if") it is an external script to look there .  Built 2.91 three days ago. Luckily missed issue. (if it were to come up)  Having issues building as  bpy module first build since last 2.90

Turns out this is actually a bug in 2.90.1 (see https://developer.blender.org/T81112).
It will probably be fixed once 2.90.2 rolls out.


text:
How to use the render result from one scene as a texture in another scene
Maybe there's a better way to go about this. What I want to do is render 2 scenes for every frame and use the result from the first render as a texture in the next.
Example:
Scene 2: A room animated with a computer on the desk.
Scene 1: The screen of the computer.
This probably isn't even possible in the method I'm describing, but I think you'll see what I'm getting at. How can this be done in Blender Internal?

Neither Cycles not Blender-Internal support this, You just have to render out the files to an image or a movie, then load them in as an image texture afterwards.

Are you sure that something like this can't be done by texturing via a composite? The other day, I researched how to get Cycles lighting quality with the blender internal object outline effect. The answer (this worked well) was to create a duplicate of the scene and in the compositor render both of them and overlay. For every frame, both scenes were rendered and combined. Could that not be pipelined into a texture?
Of course you may be completely right.

@JonathanTodd You could use compositing to combine both scenes in a way which would look okay, (you don't even need separate scenes, two renderlayers should be fine) but it would not technically be a texture.

@gandalf3 I'm open to it if it works. Post as an answer if that solution achieves the right effect. It would be more effective to be able to work on the scenes/render layers together rather than build the screen animation and apply it as a video texture. Having the character interact with the screen, any changes to the master scene animation would require re-rendering in the other scene separately. Maybe there's an easier way to do it? A trick that movie CGI editors use?

@Jonathan Todd - You could for example, use the compositor to overlay the output of one render onto another, using UV distortion to map it to a 3D surface, its a little more involved to have other objects in-front of it, but possible using Z-Masks.

What I was originally thinking of will not work as easily as I thought, however you could use an approach like this. Quoted from my answer here:

You can achieve this with an Image Sequence Texture node:

Set up two render layers with each layer excluding the other:

Set up compositing nodes so the render layer that is being used to influence the materials renders out to a separate directory.    This
  is possible with the File Path node:

Render only the influencing layer once to that directory by Pinning  that render layer.    The file will be named something like Image0001.png. Rename it to
  Image0000.png
Set up the material you want to be influenced.   You can pull in the result of the other render layer by adding an Image Texture
  node, setting the image to Image0000.png, setting the Source to
  Image Sequence, and setting the Offset to -1

This is the result of the other render layer.
Render the animation. (CtrlF12, or Info > Render > Render Animation
Here is a simple test with two spheres (one on each layer) and a
  moving light source:

Keep in mind that with this technique, the two layers are one frame
  apart. This could be fixed by rendering the influencing layer
  completely beforehand, and adjusting the offset accordingly.

This should work in BI as well, using an image sequence texture (as opposed to an image sequence node).


text:
How do I apply an environment map in Blender Internal?
I'm using Blender Internal due to its object outline effect, and am trying to use a 1800 degree environment map for the reflections (not lighting). I'm trying what seems like should work, and am failing.
Most of the tutorials for this are in Cycles, which is handled easily, can anyone tell me how to do it in Blender 2.6+ Internal?
EDITS:
So my question is really just "How do I apply an environment map in Blender Internal?"; the perspective of the environment map is trivial to the question.

I'm not sure what you mean by a "1800 degree environment map".. Do you mean 180 degree? Or am missing something?

@gandalf3 It's 1800. Look into the options of panorama rendering. It's not based on a 180 or 360(we think 360, but that's just a circle, 1800 is an orb) perspective view of the scene, but a 1800 degree view, which is basically a full sphere view mapped onto one image. The environment map takes that warped image and turns it into a 360 environment map emulating the actual environment for lighting and/or reflections.

For example in this short tutorial https://www.youtube.com/watch?v=XQ1rV-xOhWY if he had a cloud overhead, it wouldn't show up in the environment map because that's a 360 degree panoramic.

It might be possible in BI, I don't know. However, one option is to render the sky in cycles in a different scene and composite together.

Can you give an example of a failed attempt? Can you give an example of a 1800 degree environment map?

@Gunslinger Yes, I'll provide a 180 degree and 1800 degree version of the same environment mapped. My failed attempt is due to me not figuring out how to assign the environment map to my environment. In cycles, it's easy. A tutorial also shows it easily being done in blender internal, but that was an older interface and the way to do it must be different now. I'll post the maps in a moment.

The way the map is assigned to the environment doesn't have to do with the perspective of the map by the way. They'll both be applied the same. It's the way that the maps bend above and below that changes. It's like texturing the sphere with an environment, but blender does it for you.

So my question is really just "How do I apply an environment map in Blender Internal?"

Enable Real Sky in Properties > World to make the sky render relative to the horizon rather than the camera:

Optionally enable Environment lighting to use the sky texture to illuminate the scene.
Switch to the texture panel and create a new world texture by clicking new with the World tab selected:

Set the type to Image or Movie and open an image:

In Textures > Mapping set the projection to Equirectangular and enable Horizon in Textures > Influence:

Result:

I'm trying to use Blender Render.
How did you get a fully reflective Material here?
Thanks!

@CFS See https://blender.stackexchange.com/q/1451/599


text:
Compression & Color change
I was using blender to render some animations for a personal blog, and I was hoping to embed the videos seamlessly into the post. I know that my website uses a background of 0xE3E5E7, so I set that as my background color in blender. When I render the animation to PNG, the background color stays at 0xE3E5E7, but once I compress it to mp4, ogv, etc. the background color changes a little bit, and sort of ruins the seamless integration I was hoping for.
I've tried using the Movie Sequence editor and using RGB curves to manually change the color balance so that the compressed video comes out right, but after about half an hour of trial-and-error, I wasn't able to actually get the output video to hit the desired color (it would get close, 0xE3E4E7, but it would never hit exactly).
Additionally, I've tried increasing the bitrate so that the compression wouldn't be much of an issue, but the problem still persists.
I was wondering if anyone knew of a way to render compressed video without color degradation or a way to filter an existing video to output something with a precise target color.

This sounds like the same problem as this question, which has since been deleted..

Observation is a Start
There's much knowledge in between your observation ("color changes a little bit") and the "whys" your observation manifests. Seeing as how this is a Blender forum, and most folks are intermediate to advanced, I will delve into some of the whys with the hope that you expand your colour knowledge and help to educate others.
First, unless we have done some dark alchemy via OpenColorIO, our image will be exiting Blender as an RGB based tri-colour model. So factoid number one: RGB is a relative colour system. But what does that mean?
If we take a flash light and cut some plastic of red, blue, and green transparency, we could cover our flash light with the plastic. This would deliver a coloured light of course. But what colour? That is precisely the question to ask when someone starts speaking in terms of values like 0xE3E5E7, which is nothing more than a hex value representing a numerical value relative to the RGB colour space in question. In this case, Blender assumes sRGB / 709 primaries. That is, the absolute colours referenced are relative to the sRGB or 709 specification. If our colour spaces are not aligned, despite having identical RGB values, the colours we look at will not be the same.
Into YCbCr
When we render the colours to a codec format, in most instances we are performing a transformation of the data into the codec model's format. Typically, most codecs will store data in a very different model compared to RGB, often being YCbCr. The YCbCr model extracts / isolates the luma from the curved RGB values and stores it in Y. The Cb and Cr values then represent two axes that stretch along yellow-blue (Cb) and green-red (Cr). A very different model with a unique transformation.
Second, the codec format typically requires a scaling of the ranges to meet broadcast specification standards. This is nothing more than shrinking the values to a smaller range via a scale, and then offsetting the values slightly.
Third, due to the human eye generally being less receptive to colour as compared to intensity, a codec will often scale down the Cb and Cr channels to make the codec smaller in size.
Fourth, the codec will likely compress all of this data even further using some form of lossy encoding standard, although it may also be lossless.
When Encoding Doesn't Match Decoding
Needless to say, the above steps outline a varying number of potentially complex transformations to get your RGB data out of the RGB model and into the YCbCr model. If any one of those steps is incorrectly handled by encoding or decoding, your results will vary quite dramatically.
So the simple question is "Given all of the above maze-like transforms that happen, can I get anything close to my original RGB image?" and the answer is unequivocally "Yes!" Can you do it with a simple click of a Blender render button? The chances are likely "No."
Let's assume we do a perfect encode of our material, what then? Then we are relying on the exact inverse of all of the above transformations to end up back with our perfect RGB values1. As you can guess, this only happens when an artist checks their work and the player is perfect. Even then, to achieve real-time playback, a piece of software may hand off the YCbCr stream to the graphics card, and you guessed it, they will often decode things incorrectly for any number of reasons.
Advice
If you are interested in achieving a perfect encode, the best advice is become a knowledgeable artist in the realm of colour and pixels. You have taken the first steps in noticing that things aren't quite right.
If you encode to a series of images and then encode again to your codec, you stand a much better chance of testing your pipeline for accuracy. In particular, because most encoding software may have different design constraints2, they may make different design decisions that result in different results. Therefore, the safest way to handle video is to encode the YCbCr yourself and then pass that raw data to an encoder and test the encoded values.
If they match, it is out of your hands and into your audience's set of qualitative evaluations at their end to decode it, if this is your goal. If they don't, something went wrong and you can correct it.
The above is a quick outline as to the sad reality of the complexities of your initial, seemingly simple first observation. Controlling the output on the other hand, is relatively easy and will get faster and faster with more knowledge. This is likely beyond the scope of this Stack Exchange answer though, so I'll leave it at that3.

Quantization errors may be present depending on the many encoding options you choose. Broadcast scaling for example, will necessarily degrade your image due to a reduced number of bits storage.
Many video encoders and decoders may target speed of encoding or decoding for quick encoding or speedy playback. Of course this will come at a cost, often times being accuracy due to lower bit depths used to encode or short cuts to achieve playback speed.
Feel free to contact me if you want to explore this area. It is possible to encode your data to a bitwise precise encode, subject to quantization / specifications. I should be relatively easy to find.

You could attempt to export png files and sequence them and upscale the video. In the past i managed to get blender to compress this color correct. Unfortunately this can not be guaranteed. It may depend which type of compressor is used internally. This can vary from software encoding to hardware encoders like quicksync and nvenc. There's no setup for those inside of in blender tho. You could always try other video tools to encode.


text:
Spotlight with Halo applied is creating rings around light
Here's a portion of a render I'm working on, which is backlit from behind by a spotlight with a "Halo" effect applied:

If you look carefully in the background, you'll notice the halo effect is creating "rings" of shadow as it fades.  How can I remove these rings and make the halo effect fade out smoothly?  I've played around with all the settings I can find without any success.
Here's my current settings for the spotlight:

That is a dithering problem. Which is not really a problem at all, but rather what physically must happen. That occurs any time there is a small change in color spread over a large area.
One of the ways to get rid of the banding is to make a stronger contrast, such as a pure black background.
The best way to deal with it. Is under the Render tab in the Properties window. Set the dithering amount up a bit until the color banding is not visible.


text:
How do I limit the rotation of the camera in an FPS
I have mouselook for my game but the player can look all the way up and down.  I want the camera to be limited in rotation like a normal fps.  Please help!

Please add more information to your question (the mouselook script, etc.)

By this I mean the "up" and "Down" rotation

The mouse move script allows cutomization. In order to restrict up/down rotation you could add the properties as shown in the image.

I make BGE tutorials on my channel, and I have this exact solution, scripts, and .blend file in the description. Just keep watching through the video, I believe I show you how 3 minutes through. https://www.youtube.com/watch?v=d2BL9AxORec

Do link, but also provide an answer that will stand for itself.

Welcome to the site :) Link only answers are discouraged here; if the link goes down, so does the answer.


text:
Rigify doesn't generate my rig correctly

When I press the generate rig button, only the jaw is create properly , the others are just like an armature is (they are bones) so I can't animated my character.
I searched everywhere on Youtube but I don't find anyone fix this problem.
In this image I just select the rig rigify generated with the armature, as you can see the rig is just like my armature except for the jaw

I'm afraid we need more details than that! For a start, what are you actually trying to use Rigify on? - Without any images or being able to look at your Blend file it's impossible to help you.  You can share your file via https://blend-exchange.com/ if it's under 30Meg in size following the instructions there to copy the link to your question into the field on that page and it will then appear in your question.

Have you looked how to use Rigify to begin with? It looks like you customized the metarig with no regards to how it actually works. You can't just create any bones you want and have Rigify figure out what they each are supposed to generate, you need to use premade limbs or create and define new ones using Rigify's way of functioning. There are plenty of tutorials online to generate custom rigs with Rigify, you can also look at Rigify - Advanced Usage — Blender Manual

@JohnEason The blender file is to big even with unnecessary things ... I add a photo of what I try to rigify . Can you tell me what informations do you need because I don t know what should i give you . Also is the file with just the armature will help you because i think the file will be under 30 Meg . Thank you !

@L0Lock Yes , I watch many tutorials on YouTube and I just use a Human rig for my rigging . Then I add samples like a jaw , a simple chain , and a tongue so everything come from rigify . If you want anything more just tell me and I will answer you ! Thank you !

Have you seen CG Dive's series on rigging anything with Rigify? - That would be my first stop!

Rigify doesn't have either of a "jaw", "tongue" nor "simple chain". There is a "faces.super_face" sample that provides an entire face's rig, but you can't pick apart bits of it: it's all or nothing. A blend file would be much appreciated. Only your metarig is theoretically needed, so no need to include anything else if it makes it impossible to upload on Blend-Exchange.

@JohnEason No I never watched these videos of CG Dive's but I have seen others . But I'll hurry to watch the serie If I can see one thing I missed ! Also I shared my amrature with blender exchange , if you want to take a look . Thank you !

@L0Lock I have seen someone who did this with is character rigging (import several samples and parent them to the head bone ) and It work pretty good in his case . I will try to take the jaw that Rigify gives me with the armature but my character need a custom armature for his hands and for the straw he wear on his head . Also I shared my armature like you asked for , if you want to take a look at it . Thank You !

You'll have to include the link provided on the blend-exchange page in your question otherwise there's no way for use to download your blend file!

@JohnEason I m sorry i am new and they ask me for the link of my question so i thought it was automatically exchange somewhere in the page . Now it s good

Ok. It's now downloading ok, but as @L0Lock says there's no way that Rigify is going to be able to make sense of the mess of bones that you have in your armature. To be honest I wouldn't even know where to begin to improve matters. :^(

Yes I see the problem and I think just follow the videos you share to have a correct armature even if it mean that i do not use samples for my jaw and other things . If you have anything just tell me and i would be glad to answer you ! Thank you for your time both of you and if it's work I'll let you know !

I have to apologize, I didn't stay updated enough about Rigify x) Turns out since v3.0 a few more rig types were added, including ones for the jaw and tongue. Source: Rig Types — Blender Manual 3.6. Regardless, there are quite a few issues in your rig that need fixing to make it work. I am writing an answer, though I will have to leave for a couple of hours very soon, so it will take a while to post my final answer. But it will come!

Preamble
I have to take back some words:

Rigify doesn't have either of a "jaw", "tongue" nor "simple chain". There is a "faces.super_face" sample that provides an entire face's rig, but you can't pick apart bits of it: it's all or nothing.

This was back in v2.81. In the current 3.61 we do have move rig types for facials in Rigify:

Faces

faces.super_face

Skin

skin.basic_chain
skin.stretchy_chain
skin.anchor
skin.glue
skin.transform.basic

Face

face.basic_tongue
face.skin_eye
face.skin_jaw

Source: Rig Types — Blender Manual 3.6

All the items in the "skin" and "face" categories were added back in v3.0 as part of the new standard face rig for Rigify: #89808 - Adopting a new standard face rig for Rigify - blender-addons - Blender Projects

A few issues in your rig that make things go wrong: the orientation of the armature, the rig types declaration, and a few things about general rules of rigging. Let's go through them:
Armature Orientation
If you select your armature in Object Mode and look at its rotation, you will see it rotated 180⁰:

This means, even though it looks like your armature is facing the front side of the world, it is actually facing the back side. If you set it back to 0⁰, you would see what the armature really looks like.
And therefore, when you generate the Rigify rig, the result is the face controllers facing backwards:

With your armature facing forward, select it in object mode, and press ⎈ CtrlA > Apply Rotation. This will set the current rotation as the new zero rotation.
If you generate the rig again, it faces the correct direction:

But now you should notice most your limbs are missing from the generated rig, which leads us to rig types declaration.
Rig Type Declaration
As you can read in its documentation, Rigify uses rig types to identify what is in the metarig and what to do with them.
Right now, aside from your facial elements, none of the bones in your metarig have rig types, hence they don't generate anything.
If you add another metarig in your scene, ↹ Tab into Pose Mode and select any first parent of a bone chain (I.E. thigh.L), you can see in the Properties Editor > Bone data tab > Rigify Type panel a bunch of information and settings:

The Rig Type is what tells rigify what the chain is supposed to be, and the settings bellow it depend on the rig type and will influence the rig generation. No rig type, and the chain is ignored.
If you look at your rig's thigh.L, there's nothing set up:

Plus, some of the bones you have are incorrectly placed: Feet are too high, fingers are twisted and don't have a slight curvature to let the IK system know in which way they must bend, ...

You can fix this two ways:

manually declare the rig types and their settings for each chain (thighs, fingers, spine, arms, etc) by copying the settings from a clean default metarig, then fix your bones twisting and placements.
Delete all bones except the facial ones that work, add a new clean metarig, delete all its facial bones, join the old metarig object into the new one, and rearrange their position to your model.

Since you are not familiar with Rigify, I would suggest the last option, as it should be the most foolproof:

↹ Tab into edit mode and select only your custom facial bones, hit ⎈ CtrlI to invert your selection, and X > Delete Bones.
↹ Tab into object mode. Press ⇧ ShiftA > Add Armature > Human (Meta-Rig).
Tab into edit mode to select and delete the facial bones. That includes the face bone, but not the spine.xxx bones:

↹ Tab back to object mode, select the old metarig, then ⇧ Shift select the new metarig, and press ⎈ CtrlJ to join the selected objects to the last selected. Some of your bones will disappear: that's because they were on layers that the default metarig doesn't show right now:

You can simply ⇧ Shift LMB these two layers to display them.
↹ Tab into edit mode, now is a good time to give your custom bone a proper name instead of just "Bone". To make sure your facial bones are all on the same and correct default layer, select them all, hit M and click the first layer as they should be:

If you generate a rig at this point (I just scaled down the body's bones in edit mode so to fit them to the facial bones level), it will look like this:

Now all that's left is to move the bones to adapt them to your rig,
A few things to keep in mind:

bones must face the same direction. You shouldn't rotate them on their local Y axe. You can turn on the armature's Axes display in Properies Editor > Armature tab > Viewport Display panel > Axes.
IK chains (like fingers, spine, etc) need to be bent in a single direction so that the IK solver knows which way it is supposed to bend. That's why kneed are a little forward and elbows a little backwards. You must to the same for the fingers and spine. If you bend them in the wrong direction or multiple axes, you will get unexpected results when moving IK controllers.

Thank you so much for your time and for solving my problem ! I don’t know how to thank you enough ! I think I’ll should go back to study more . What you taught me is precious and I keep in mind this lesson for the future !

Just take it slow. Baby steps get you far ;)


text:
Is there any minimum size requirement for the pinhole in the pinhole camera?
I am trying to build a Pinhole Camera with pinhole size in micrometer range. In my setup I have placed two lights sources with maximum brightness. Still not enough light rays are passing through the pinhole.
Is there any minimum size requirement for the pinhole in the pinhole camera to allow light to pass through?

Hello and welcome. Look into Light Portals.

Thank you but Light Portals doesn't make much difference. Still not enough light rays are passing through the pinhole to get an image.

can you please share some screenshot to better understand the problem and your blend file https://blend-exchange.com, maybe the dimensions are too small.

The pinhole size I want to achieve is in the micrometer range (50μm -100μm). But even with a 3 mm pinhole I can't get a proper image.

I want to know if there is any minimum size required for the pinhole.

I don't think there is a technical limit, but I reckon there is definitely a practical one. In path tracing engines, indoor rendering with just an outdoor light going through a hole are particularly harder to render due to how the render process works. You definitely need significantly more rays, and using a portal to guide the rays. But the smaller the hole, the fewer light can go through the hole and you don't have an infinite amount of rays. Either blow up the samples and prepare for ridiculously long renders if it's even enough, or use a bigger hole.

For reference, a hair strand is between 40 to 100 µm diameter on average. I will check your file once I'm back home and see what can be done.

Related: the following video basically recreates a camera in Blender Cycles, which starts with a pinhole cam. Make Your Renders Unnecessarily Complicated - YouTube

To make a pinhole camera, you need to have a white material on the "screen" area. A black material would absorb the light rays instead of bouncing them back to you.
You did assign a white diffuse material to the back face of your cube, but you also use a boolean modifier to create the inner volume of the cube. And that boolean operation isn't set up to apply the white material to the inside, so you effectively have no white screen in your box.
To be honest, you don't need to give your cube a thickness. If you really want to, I would replace that first boolean by a Solidify modifier. You can check the presence of your black and white materials using the Material shading mode:

I also renamed things a bit for clarity.
For ease of use, I highly recommand you to not hide the pinhole object: hidden objects can't be selected and are harder to manipulate. Instead, disable it only its render visibility. Disable all its ray visibilities so that it doesn't impact viewport rendering either, and set its viewport display to wire:

Now if we try rendering with 3ųm, it works, but it's really noisy. I set this pinhole to 1cm, here's what we see in the viewport after 100 thousand samples:

In Properties Editor > Render Settings tab > Color Management panel, set the Exposure to 10:

Still very noisy, and that's normal: Rays are being shot and bouncing everywhere in the scene, only a few make it through the pinhole.
Let's help that by adding an area lamp, enable its Portal option, and place it in the pinhole.

Select the pinhole object
Press ⇧ ShiftS > Cursor to selected
Press ⇧ ShiftA > Add Light > Area
Rotate it by -90⁰ on X by pressing RX-90⏎ Enter
Under Properties Editor > Light Data tab > Light panel, enable Portal and set the size to the same dimension as your pinhole

It isn't a huge difference because it is still naturally a very noisy image, but it is there.
You can probably tweak things to get better results, use denoising, more samples, change light paths settings, play with different exposures and pinhole sizes, ...
This is the result of one million samples with and without denoising:

Thank you for the answer. Does it work in the micrometer range? Even after modification I am still not able to get the image in micrometer range.

Can you also share the blend file?

It works, but again: the smaller the hole, the less rays get in, the more noisy and dark the image. I don't have the file anymore, but you will get the same result by doing what I described in my answer.


text:
Simulation of lenslet array
I am trying to simulate lenslet(microlens array). I found a add-on Camera Generator where they are simulating microlens array on top of the camera’s sensor. But I want to simulate lenslet array as an independent object.
What I am trying to achieve is a square grid of hexagonal shaped microlens. And I also need to control the focal length of the microlens and the overall size of the lenslet.
Is there any way to simulate lenslet(microlens array) alone?

It would be nice if you could provide any information on what the result should be here instead of letting us google everything. The Wikipedia article you linked to is basically just saying that a lenslet array is an array of small lenses. Also I'm not willing to install an add-on just to know how an image of a lenslet array would look like... and since I do not know what the result should be I cannot tell you a way to achieve it. What do you mean by lenslet array "alone"? Just getting an array of lenses? Sure, lens model with Array modifier or Geometry Nodes. But using them as camera(s)?

Thank you for the reply. I want to create grid of hexagonal shaped lenses.  I am not using them as cameras. In the add-on, lenslet array comes with the camera. It is not possible to independently control the lenslet from the addon.

You see, these are all informations that were missing in the question. For example, you want a grid of hexagonal shaped lenses. I've found grids of square lenses as well while googling. Square lenses are of course simpler to arrange in a grid than hexagonal ones. Also I've seen arrays filling square areas as well as circular areas. What do you want? And if square ones for example, how should hexagonal shapes be at the borders? Alternatingly missing one? Or being cut in half for an even border?

I have attached a picture of the lenslet array I am trying to achieve.

I want to fill the a square area with the hexagonal shaped lenses. On the border, alternatively missing one is preferred but other one is also fine.