text:
blf module: How to draw text in the center?
I have a frame, and I want to draw text for it, which will be in the very center:

Oh no. It works fine, but I'm still not happy

import bpy, blf, gpu, gpu_extras.batch
from mathutils import Vector as Vec

def DrawRect(pos1, pos2, col):
    gpu.state.blend_set('ALPHA')
    gpuShader.bind()
    gpuShader.uniform_float('color', col)
    vpos = (pos1[0],pos1[1]), (pos2[0],pos1[1]), (pos2[0],pos2[1]), (pos1[0],pos2[1])
    gpu_extras.batch.batch_for_shader(gpuShader, type='TRI_FAN', content={'pos':vpos}).draw(gpuShader)

def CallbackDraw():
    #Frame for centered text:
    pos1 = Vec((200,200))
    pos2 = Vec((430,260))
    DrawRect(pos1, pos2, (.75,.75,1,.15))
    col = (1,1,1,.5)
    DrawRect(pos1, (pos2.x, pos1.y+1), col)
    DrawRect(pos1, (pos1.x+1, pos2.y), col)
    DrawRect((pos2.x-1, pos1.y), pos2, col)
    DrawRect((pos1.x, pos2.y-1), pos2, col)
    #Visualisation:
    blf.size(fontId, 28)
    dim = Vec(blf.dimensions(fontId, txtForTest))
    cen = (pos1+pos2)/2
    bou1 = cen-dim/2
    bou2 = cen+dim/2
    col = (1,1,1,.5)
    DrawRect((0, bou2.y), (1000, bou2.y+1), col)
    DrawRect((0, bou1.y), (1000, bou1.y+1), col)
    DrawRect((cen.x+dim.x/2, 0), (cen.x+dim.x/2+1, 1000), col)
    DrawRect((cen.x-dim.x/2, 0), (cen.x-dim.x/2+1, 1000), col)
    #Text:
    blf.position(fontId, cen.x-dim.x/2, cen.y-dim.y/2, 0)
    #blf.position(fontId, bou1.x, bou1.y, 0)
    #blf.position(fontId, cen.x, cen.y, 0)
    blf.enable(fontId, blf.SHADOW)
    blf.shadow_offset(fontId, 1, -1)
    blf.shadow(fontId, 5, .1, .1, .1, 1)
    blf.color(fontId, .9, .9, 1, 1)
    blf.draw(fontId, txtForTest)

txtForTest = "GJKLPgjklp!?"
fontId = blf.load(r"C:\Windows\Fonts\consola.ttf")
gpuShader = gpu.shader.from_builtin('UNIFORM_COLOR')

bpy.types.SpaceNodeEditor.draw_handler_add(CallbackDraw, (), 'WINDOW', 'POST_PIXEL')
bpy.types.SpaceTextEditor.draw_handler_add(CallbackDraw, (), 'WINDOW', 'POST_PIXEL')
bpy.types.SpaceView3D.draw_handler_add(CallbackDraw, (), 'WINDOW', 'POST_PIXEL')

Most fonts have this problem:

Because of this problem, the font does not "visually" look in the center:

Especially here

But I want it to be like this:

Of course, this is not a center either, but it will still be better.

^ For this font comici.ttf, you need to add offset +9 pixels on the Y axis.
But these are different values for each font and each font size. How can I calculate this automatically?
How do I get the "zero point" for a given font or individual letters, by any means?

Thanks for the bounty, how about the external library solution, have you considered it?

No, I didn't think about it. I wanted to have a solution using only the available tools.

First, some clarification on the problem: the blf module draws text on a given position, by aligning the baseline of the font to the given screen $y$ coordinate:

What you're interested in, is to get the bounding box of generated text: for xxx you want to get the x-height and $0$. For S you want to get cap height and $0$ (with a caveat: it's a very common convention that rounded curves like in "S" or "O" go beyond the guidelines, so that they visually seem to be exactly limited by them; same principle as with distorted Greek columns that seem straight because of that). For p and the above font, you want to get a descender height (perhaps with a negative sign) and a little bit more than the x-height etc. This means if you use your bounding box to align vertically, the text will move as it changes, which is probably not what you actually want, but once your problem, as currently phrased, is solved, you can simply align vertically based on a static text like "x" or "S" or "h" or "Hp" (see the "recommended" comment in code).
Unfortunately the blf capability for obtaining font metrics is very poor. As I already said, it aligns the font to the baseline:

And the only metric it provides is the blf.dimensions you already use. The reported size is not some 'constant' metric, e.g. the height always being the distance between the descender height and ascender height, because it changes based on text passed (so the text is not needed just to multiply a single character dimensions by the number of columns and lines):
>>> import blf
>>> consola = blf.load('C:/Windows/Fonts/consola.ttf')
>>> blf.size(consola, 1000)
>>> blf.dimensions(consola, "GJKLPgjklp!?")
(6600.0, 901.0)

>>> blf.dimensions(consola, "GJKLP")
(2750.0, 656.0)

>>> blf.dimensions(consola, "H")
(550.0, 639.0)

>>> blf.dimensions(consola, "S")
(550.0, 656.0)

>>> blf.size(consola, 100)
>>> blf.dimensions(consola, "S")
(55.0, 66.0)

>>> blf.size(consola, 10)
>>> blf.dimensions(consola, "S")
(6.0, 6.0)

Also notice the rounding of the dimensions, perhaps because of font hinting:
I don't know if there is some better library in vanilla Blender available to measure text. In general you want to google for "font metrics" - there are Python libraries available, including solutions involving popular libraries like PIL.
I don't like relying on installing libraries through PIP, however, I find it unreliable, and if your customer has a PIP-related problem, you're in a world of hurt… On the other hand, my solution won't work in context where you can't evaluate an object, or in a tight-loop for performance reasons. If you can't optimize it by gathering required data once and storing it, then you're forced to use an external library. I don't think you need help with that, however; I might still add the answer for that for future visitors… Or you may share your solution if you go this route.
Geometry Nodes Text Curve solution
Thanks to lemon simplified the answer by removing geonodes. Read earlier revision if you want to see something silly.

create a temporary object
and a temporary "font" curve
set a one-line text (unless you explicitly use newline characters)
read the bounding box corners
you want the center of the bounding box in the center
therefore its offset from the origin=baseline is the (inverse) offset you want to apply
unfortunately the size of $1$ isn't the same in text object and blf
therefore multiply the offset by the ratio of one bounding box height to the other
also when obtaining the height from blf use a very big size for improved accuracy

font_size = 28
txtForTest = "GJKLPgjklp!?"

import bpy, blf, gpu, gpu_extras.batch
from mathutils import Vector as Vec
from bpy import context as C, data as D

def DrawRect(pos1, pos2, col):
    gpu.state.blend_set('ALPHA')
    gpuShader.bind()
    gpuShader.uniform_float('color', col)
    vpos = (pos1[0],pos1[1]), (pos2[0],pos1[1]), (pos2[0],pos2[1]), (pos1[0],pos2[1])
    gpu_extras.batch.batch_for_shader(gpuShader, type='TRI_FAN', content={'pos':vpos}).draw(gpuShader)

def CallbackDraw():
    #Frame for centered text:
    pos1 = Vec((200,200))
    pos2 = Vec((430,260))
    DrawRect(pos1, pos2, (.75,.75,1,.15))
    col = (1,1,1,.5)
    DrawRect(pos1, (pos2.x, pos1.y+1), col)
    DrawRect(pos1, (pos1.x+1, pos2.y), col)
    DrawRect((pos2.x-1, pos1.y), pos2, col)
    DrawRect((pos1.x, pos2.y-1), pos2, col)
    #Visualisation:
    blf.size(fontId, font_size)
    dim = Vec(blf.dimensions(fontId, txtForTest))
    cen = (pos1+pos2)/2
    bou1 = cen-dim/2
    bou2 = cen+dim/2
    col = (1,1,1,.5)
    DrawRect((0, bou2.y), (1000, bou2.y+1), col)
    DrawRect((0, bou1.y), (1000, bou1.y+1), col)
    DrawRect((cen.x+dim.x/2, 0), (cen.x+dim.x/2+1, 1000), col)
    DrawRect((cen.x-dim.x/2, 0), (cen.x-dim.x/2+1, 1000), col)

    DrawRect((0, cen.y-.5), (1000, cen.y+.5), col)

    #Text:
    blf.position(fontId, cen.x-dim.x/2, cen.y-centering_offset, 0)
    blf.enable(fontId, blf.SHADOW)
    blf.shadow_offset(fontId, 1, -1)
    blf.shadow(fontId, 5, .1, .1, .1, 1)
    blf.color(fontId, .9, .9, 1, 1)
    blf.draw(fontId, txtForTest)

def get_text_centering_offset(txt, font_path, blf_height):
    temp_name = "Temporary datablock - delete it"

    font = D.fonts.load(filepath=font_path, check_existing=True)
    txt_curve = D.curves.new(name=temp_name, type='FONT')
    txt_curve.font = font
    txt_curve.body = txt

    ob = D.objects.new(name=temp_name, object_data=txt_curve)
#    C.collection.objects.link(ob)

    # left/right, front/rear, top/bottom
    # ^    ^      ^     ^     ^   ^
    # see numpad orthographic views for reference
    lfb, lft, lrt, lrb, rfb, rft, rrt, rrb = ob.bound_box

    top_in_2D = lrb[1]
    bottom_in_2D = lfb[1]

    D.objects.remove(ob)
    D.curves.remove(txt_curve)

    height = top_in_2D - bottom_in_2D
    ratio = blf_height / height

    return (top_in_2D + bottom_in_2D)/2 * ratio

# using main() helps to avoid bugs related to namespace pollution
def main():
    global fontId, gpuShader, centering_offset
    txt_for_measurement = txtForTest
    #txt_for_measurement = "Sp"  # recommended

    font_path = r"C:\Windows\Fonts\consola.TTF"
    fontId = blf.load(font_path)
    blf.size(fontId, 1000)  # big size for accuracy; don't go too crazy, e.g. 100k doesn't work
    blf_height = blf.dimensions(fontId, txtForTest)[1]
    blf_height /= 1000  # cancel out the temporary magnification

    centering_offset = get_text_centering_offset(
        txt=txtForTest,
        font_path=font_path,
        blf_height=blf_height
    )
    print(centering_offset)
    centering_offset *= font_size  # because 1000 was a constant value, not a multiplier

    gpuShader = gpu.shader.from_builtin('UNIFORM_COLOR')

    # for easy script changes:
    s3D = bpy.types.SpaceView3D
    try:
        s3D.draw_handler_remove(s3D.my_handler, 'WINDOW')
    except (AttributeError, ValueError):
        pass
    s3D.my_handler = s3D.draw_handler_add(CallbackDraw, (), 'WINDOW', 'POST_PIXEL')

main()

I tested at a big sizes and it fails then. Looks like the multiplication by size is not enough. For the consolas you need to multiply the centering_offset by an additional 1.3, but that depends on a font. I wonder if that could maybe be dependend on the height ($y$ dimension) of the bounding box...

Fixed. At least mostly. There could be some off-by-one errors not related to the text measurement.

+1 but why the hell are you using gn for that?

@lemon I edited the answer just about when you wrote this comment, maybe the new revision clarifies why. I have another idea that works in most cases for the most part, will post soon, but I think this solution is just the most reliable solution not using an external library. And as I wrote: I don't think OP needs any help on using an external Python library for font metrics, so I'm not rushing into writing an answer involving pip install or git pull

Markus, I meant bpy.data.curves.new(type="FONT", name="Font Curve") instead of gn

@lemon aaah haha, yes, that's a very reasonable observation. I've never used the font objects much, maybe that's why I didn't intuitively think of it... I just checked and the bound_box works (out of the box). The default text alignment is set to baseline as well. I'll rework this answer to use a text object instead soon!

Here's a much simpler answer than my other answer.
It works most of the time for the most part, that is, it relies on 2 assumptions, that most of the time are roughly right:

Assumption #1: the "qypg" letters have tops aligned with "x"
Assumption #2: nothing goes lower than "qypg" letters

font_size = 28
txtForTest = "GJKLPgjklp!?"

import bpy, blf, gpu, gpu_extras.batch
from mathutils import Vector as Vec
from bpy import context as C, data as D

def DrawRect(pos1, pos2, col):
    gpu.state.blend_set('ALPHA')
    gpuShader.bind()
    gpuShader.uniform_float('color', col)
    vpos = (pos1[0],pos1[1]), (pos2[0],pos1[1]), (pos2[0],pos2[1]), (pos1[0],pos2[1])
    gpu_extras.batch.batch_for_shader(gpuShader, type='TRI_FAN', content={'pos':vpos}).draw(gpuShader)

def CallbackDraw():
    #Frame for centered text:
    pos1 = Vec((200,200))
    pos2 = Vec((430,260))
    DrawRect(pos1, pos2, (.75,.75,1,.15))
    col = (1,1,1,.5)
    DrawRect(pos1, (pos2.x, pos1.y+1), col)
    DrawRect(pos1, (pos1.x+1, pos2.y), col)
    DrawRect((pos2.x-1, pos1.y), pos2, col)
    DrawRect((pos1.x, pos2.y-1), pos2, col)
    #Visualisation:
    blf.size(fontId, font_size)
    dim = Vec(blf.dimensions(fontId, txtForTest))
    cen = (pos1+pos2)/2
    bou1 = cen-dim/2
    bou2 = cen+dim/2
    col = (1,1,1,.5)
    DrawRect((0, bou2.y), (1000, bou2.y+1), col)
    DrawRect((0, bou1.y), (1000, bou1.y+1), col)
    DrawRect((cen.x+dim.x/2, 0), (cen.x+dim.x/2+1, 1000), col)
    DrawRect((cen.x-dim.x/2, 0), (cen.x-dim.x/2+1, 1000), col)

    DrawRect((0, cen.y-.5), (1000, cen.y+.5), col)

    #Text:
    blf.position(fontId, cen.x-dim.x/2, cen.y-centering_offset, 0)
    blf.enable(fontId, blf.SHADOW)
    blf.shadow_offset(fontId, 1, -1)
    blf.shadow(fontId, 5, .1, .1, .1, 1)
    blf.color(fontId, .9, .9, 1, 1)
    blf.draw(fontId, txtForTest)

def get_text_centering_offset(txt, fontId):
    txt_height = blf.dimensions(fontId, txt)[1]
    x_height = blf.dimensions(fontId, 'x')[1]
    qypg_height = blf.dimensions(fontId, 'qypg')[1]

    # ASSUMPTION 1: the "qypg" letters have tops aligned with "x"
    descender_height = qypg_height - x_height

    # ASSUMPTION 2: nothing goes lower than "qypg" letters
    offset = -descender_height  # move up so the bottom of text is spawned on the given coordinate
    offset += txt_height/2  # move down so the middle of text is spawned on the given coordinate
    return offset

# using main() helps to avoid bugs related to namespace pollution
def main():
    global fontId, gpuShader, centering_offset
    txt_for_measurement = txtForTest
    #txt_for_measurement = "Sp"  # recommended

    font_path = r"C:\Windows\Fonts\consola.TTF"
    fontId = blf.load(font_path)
    blf.size(fontId, font_size)

    centering_offset = get_text_centering_offset(
        txt=txtForTest,
        fontId=fontId,
    )

    gpuShader = gpu.shader.from_builtin('UNIFORM_COLOR')

    # for easy script changes:
    s3D = bpy.types.SpaceView3D
    try:
        s3D.draw_handler_remove(s3D.my_handler, 'WINDOW')
    except (AttributeError, ValueError):
        pass
    s3D.my_handler = s3D.draw_handler_add(CallbackDraw, (), 'WINDOW', 'POST_PIXEL')

main()
```

Cool, but if the text consists only of "-", then this method is not suitable.

@ugorek I guess there's many more assumptions this relies on, than just the 2 mentioned... If you listen to the # recommended comment, then what you get is an alignment of the "text line", such that a typical usage of the text has the boundary box centered. I recommend this for dynamic text in mind, not even an "animated" text like a counter, but think about some unpleasantness when a hyphen appears at different heights depending if there's letters on the same line or not (or maybe only I notice such things).

Not sure I understood correctly, but my thought was to just use the height of (for example) an "H" as reported by blf.dimensions as the line height.
This should center the "line", but maybe not the actual text, depending on if there are descenders, only lowercase letters, etc.
import bpy, blf, gpu, gpu_extras.batch
from mathutils import Vector as Vec

def DrawRect(pos1, pos2, col):
    gpu.state.blend_set('ALPHA')
    gpuShader.bind()
    gpuShader.uniform_float('color', col)
    vpos = (pos1[0],pos1[1]), (pos2[0],pos1[1]), (pos2[0],pos2[1]), (pos1[0],pos2[1])
    gpu_extras.batch.batch_for_shader(gpuShader, type='TRI_FAN', content={'pos':vpos}).draw(gpuShader)

def DrawTextbox(
    fontid,
    text,
    center,
    margin,
    bg_color,
):
    line_height = blf.dimensions(fontid, "H")[1]
    txt_w, txt_h = blf.dimensions(fontid, text)
    cx, cy = center
    box_w = txt_w + 2*margin
    box_h = line_height + 2*margin

    # Box
    DrawRect(
        (cx - box_w/2, cy + box_h/2),
        (cx + box_w/2, cy - box_h/2),
        bg_color,
    )

    # Text
    blf.position(fontid, cx - txt_w/2, cy - line_height/2, 0)
    blf.draw(fontid, text)

def CallbackDraw():
    blf.size(fontId, 28)
    blf.enable(fontId, blf.SHADOW)
    blf.shadow_offset(fontId, 1, -1)
    blf.shadow(fontId, 5, .1, .1, .1, 1)
    blf.color(fontId, .9, .9, 1, 1)

    DrawTextbox(
        fontid=fontId,
        text="GJKLPgjklp!?",
        center=(400, 100),
        margin=20,
        bg_color=(.75, .75, 1, .15),
    )

    blf.size(fontId, 50)

    DrawTextbox(
        fontid=fontId,
        text="GJKLPgjklp!?",
        center=(400, 300),
        margin=40,
        bg_color=(1, .75, .75, .15),
    )

fontId = blf.load(r"C:\Windows\Fonts\consola.ttf")
gpuShader = gpu.shader.from_builtin('UNIFORM_COLOR')

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

The problem is: when you position the text on $y$, it's not the top of the text's boundary, nor the bottom of it, positioned on this coordinate. It's the baseline. So knowing the height is not enough to center the text. See here: ~38 vs ~30 px distance to border: https://i.imgur.com/dBJ7i2b.gif
Of course you can position the baseline in the middle easily, because that's the position of text drawing, though that's also not what you achieve above: https://i.imgur.com/btlxPBb.gif
Finally, is the center of the text in the vertical middle? Not quite: https://i.imgur.com/VEzPap4.gif


text:
How can I get "parent" node from PropertyGroup?
I have a node that contains a collection of strings:
import bpy

def UpdateTxt(self, context):
    pass

class Line(bpy.types.PropertyGroup):
    txt: bpy.props.StringProperty(name="Text", default="", update=UpdateTxt)

class NodeEx(bpy.types.Node):
    bl_idname = 'NodeEx'
    bl_label = "CustomNode123"
    bl_width_default = 200
    lines: bpy.props.CollectionProperty(type=Line)
    def init(self, context):
        for cyc in range(4):
            ci = self.lines.add()
            ci.name = str(cyc)
    def draw_buttons(self, context, layout):
        colList = layout.column()
        for ci in self.lines:
            colList.prop(ci,'txt', text="")

bpy.utils.register_class(Line)
bpy.utils.register_class(NodeEx)

The property has an 'update' method, which will be called every time a 'txt' in a group in a collection is updated. In this method, self will contain the node's collection item.
When I update a string, how does an item determine which node it belongs to?

def UpdateTxt(self, context):
    self.???.??.label = "CustomNode456"  # how?

One possible solution is to maintain a reference while filling the collection:
def UpdateTxt(self, context):
    dict_selfToNode[self].label = "CustomNode456"

...

dict_selfToNode = {}

class NodeEx(bpy.types.Node):
    ...
    def init(self, context):
        for cyc in range(4):
            ci = self.lines.add()
            dict_selfToNode[ci] = self #<-- here
            ci.name = str(cyc)
    ...

This workaround does work, but it does not scale to large projects. For example, after a certain number of items, the address of the first item changes, making it impossible to find in the dictionary. That's why I’m seeking an alternative.
How can I access the "owner" or parent of a PropertyGroup?
Here's a complete and reproducible code example. Note that at least one node editor area (Compositor, Geometry Nodes, Shader Editor, etc.) needs to be open before running the script.
import bpy

class BseTree(bpy.types.NodeTree):
    bl_idname = 'BseNodeTree'
    bl_label = "Bse Node Tree"
    bl_icon = 'SNAP_FACE'

def CnUpdateTxt(self, context):
    try:
        ndSelf = self.idk.how
    except Exception as ex:
        import traceback
        print(traceback.format_exc()[:-1])
        print("   Omg ^ See source")
    txt_message_with_important_information_about_node = 'f"You changed a line from a node named \"{ndSelf.name}\""'
    def PopupMessage(self, context):
        self.layout.label(text=txt_message_with_important_information_about_node, icon='INFO')
    bpy.context.window_manager.popup_menu(PopupMessage, title='f"{ndSelf.name}"', icon='NONE')
    #ndSelf.label = txt_message_with_important_information_about_node
class CnLine(bpy.types.PropertyGroup):
    txt: bpy.props.StringProperty(name="Text", default="", update=CnUpdateTxt)
class BseNode(bpy.types.Node):
    bl_idname = 'BseNode'
    bl_label = "CustomNode123"
    bl_width_default = 265
    lines: bpy.props.CollectionProperty(type=CnLine)
    def draw_label(self):
        return f"I'm a \"{self.name}\" node!"
    def init(self, context):
        for cyc in range(3):
            ci = self.lines.add()
            ci.name = str(cyc)
    def draw_buttons(self, context, layout):
        colList = layout.column(align=True)
        for ci in self.lines:
            colList.prop(ci,'txt', text="")

def register():
    for dv in dict(globals()).values():
        if dv.__class__.__name__.lstrip("_") in {"RNAMeta", "RNAMetaPropGroup"}:
            bpy.utils.register_class(dv)
    for wn in bpy.context.window_manager.windows:
        for ar in wn.screen.areas:
            if ar.type=='NODE_EDITOR':
                if ar.spaces[0].type=='NODE_EDITOR':
                    ar.ui_type = BseTree.bl_idname
                    tree = bpy.data.node_groups.get("Bse") or bpy.data.node_groups.new("Bse", BseTree.bl_idname)
                    ar.spaces[0].node_tree = tree
                    tree.nodes.clear()
                    nd = tree.nodes.new(BseNode.bl_idname)
                    nd.name = "first_node.001"
                    nd.select = False
                    nd.lines[1]['txt'] = "Edit me pls"
                    nd = tree.nodes.new(BseNode.bl_idname)
                    nd.name = "second_node.002"
                    nd.location.x = -300
                    nd.select = False
                    nd.lines[1]['txt'] = "The edited line must know its node --->"
if __name__=="__main__":
    register()

Upd:
Omg, I completely forgot that context has node. So another possible non-ideal solution is
def UpdateTxt(self, context):
    ndSelf = context.node
    ...

but this does not work in situations where the line was cleared via Backspace key or the line content was changed via the console:

In some types that PointerProperty supported, you can implement. But PointerProperty unsupport bpy.types.Node.
even if you can assign a blender python instance to the group, when you perform undo/redo, blender will make that object unable to access (Invalid pointer) , even will crash blender when you access.

I don't think Blender inherently stores a back-reference from a PropertyGroup item to its parent object.
Maybe add a PointerProperty to the Line PropertyGroup to store a reference to the parent node.
Or if all the parent and child nodes are hierarchal then you could build a search tree method (likely to be slow though) - can you expand on the relations of your classes please.

It would be much easier to help if you presented a full working example, otherwise the code can't be easily copy-pasted and tested. Or did you? I never implemented my own node trees, but there's no poll check for the tree type in your example which suggests you stripped the code from boilerplate.

I tried running the added code, but despite the code inside register() function, I have to manually switch to BSE node editor, create a tree, it is empty, and I can't add any node, testing on Blender 4.2. Apparently @HarryMcKenzie was able to run it, but I'm a special needs person.

@MarkusvonBroady Yeah, it doesn’t work unless you have one of the node editors open, which then switches to the new custom BseNodeTree editor when you run the script and adds the nodes. I added this note into the question before running the script.

@HarryMcKenzie Aah! Thanks! I should have figured it out based on iterating over screen's areas...

path_from_id does not work on subproperties of a custom node #51096

a design limitation: you can never go from current property to parent

working this around by providing special path functions to properties, which are iterating over all possible parents and gives path to the parent which actually hold the property

class CnLine(bpy.types.PropertyGroup):

    txt: bpy.props.StringProperty(name="Text", default="", update=CnUpdateTxt)

    def get_parent_node(self):
        for node in self.id_data.nodes:

            if node.bl_idname != 'BseNode':
                continue

            for line in node.lines:
                if line.as_pointer() == self.as_pointer():
                    return node

        raise Exception('Should not be.')

What's wrong with checking if line == self: without as_pointer()?

I was unsure about the comparison implementation for the bpy_struct but it is the same: pyrna_struct_as_pointer,  pyrna_struct_compare. Also wanted something explicit and idiomatic as self is line or id(self) == id(line).

To ensure it is not compared as a dictionary like IDP_EqualsProperties_ex.

It’s not possible to directly reference a node’s parent from a PropertyGroup without some form of indirect reference. The PropertyGroup itself does not inherently know about the node tree or its nodes. Therefore, I suggest adding a reference, such as a unique ID for the node, to each line (ci.node_unique_id = self["unique_id"]). Then, on update, loop through all the nodes to compare the ID.
Note that this approach is particularly robust in situations where nodes may be renamed, relocated, or restructured. It provides a consistent and reliable point of reference for nodes, regardless of their location or level in the hierarchy.
import bpy
import uuid

class BseTree(bpy.types.NodeTree):
    bl_idname = 'BseNodeTree'
    bl_label = "Bse Node Tree"
    bl_icon = 'SNAP_FACE'

class CnLine(bpy.types.PropertyGroup):
    txt: bpy.props.StringProperty(name="Text", default="", update=lambda self, context: self.update_txt(context))
    node_unique_id: bpy.props.StringProperty(name="Node Unique ID", default="")

    def update_txt(self, context):
        tree = context.space_data.node_tree
        ndSelf = next((node for node in tree.nodes if node.get("unique_id") == self.node_unique_id))
        txt_message_with_important_information_about_node = f"You changed a line from a node named \"{ndSelf.name}\""
        def PopupMessage(self, context):
            self.layout.label(text=txt_message_with_important_information_about_node, icon='INFO')
        bpy.context.window_manager.popup_menu(PopupMessage, title=f"{ndSelf.name}", icon='NONE')

class BseNode(bpy.types.Node):
    bl_idname = 'BseNode'
    bl_label = "CustomNode123"
    bl_width_default = 265
    lines: bpy.props.CollectionProperty(type=CnLine)

    def init(self, context):
        self["unique_id"] = str(uuid.uuid4())
        for cyc in range(3):
            ci = self.lines.add()
            ci.name = str(cyc)
            ci.node_unique_id = self["unique_id"]

    def draw_label(self):
        return f"I'm a \"{self.name}\" node!"

    def draw_buttons(self, context, layout):
        colList = layout.column(align=True)
        for ci in self.lines:
            colList.prop(ci, 'txt', text="")

def register():
    for dv in dict(globals()).values():
        if dv.__class__.__name__ in {"RNAMeta", "RNAMetaPropGroup"}:
            bpy.utils.register_class(dv)
    for wn in bpy.context.window_manager.windows:
        for ar in wn.screen.areas:
            if ar.type == 'NODE_EDITOR':
                if ar.spaces[0].type == 'NODE_EDITOR':
                    ar.ui_type = BseTree.bl_idname
                    tree = bpy.data.node_groups.get("Bse") or bpy.data.node_groups.new("Bse", BseTree.bl_idname)
                    ar.spaces[0].node_tree = tree
                    tree.nodes.clear()
                    nd = tree.nodes.new(BseNode.bl_idname)
                    nd.name = "first_node.001"
                    nd.select = False
                    nd.lines[1]['txt'] = "Edit me pls"
                    nd = tree.nodes.new(BseNode.bl_idname)
                    nd.name = "second_node.002"
                    nd.location.x = -300
                    nd.select = False
                    nd.lines[1]['txt'] = "The edited line must know its node --->"

if __name__ == "__main__":
    register()

I think the problem with pointers is that they aren't "long-lived" which you can see after trying to modify a string after using CTRL+Z (undo), which invalidates some objects and makes the pointed out-of-date.

Maybe indeed use a pointer, but if it fails, then go through all nodes of this type, and recreate pointers. It's potentially slow, but only in rare situations. Of course you could hold a node name and see if it hasn't changed. If not, good, you restore pointer fast. Otherwise loop on all nodes of the type.

@MarkusvonBroady how about now using unique_id? hehe

Using context.space_data.node_tree is an interesting alternative to unwave's self.id_data, probably both are OK. I'd remove the default None from next(), so you get an error earlier if nothing is found. And finally I don't know how reliable is the unique_id, ideally someone uses this solution and reports back if he ever gets an error.  As I mentioned earlier, you could still have a pointer and check its validity, but on second thought, a string update happens rarely, the number of nodes should be well below a million, so maybe there is no need for an optimization...

@MarkusvonBroady cool thank you for your feedback! :)

source: Stack Exchange

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

sort: votes


text:
Character Motion in BGE: Hold Two keys at the same time
I am making an FPS in BGE and I am confused on something.  Before I upgraded to Blender 2.74 it make it so if you would hold the W and A key at the same time then the character would move both along the x and y axis at the same time to make the character go diagonally.  Now it will not move at both axis at the same time, but whatever is pressed last.  The problem is that you can't move left and go forward at the same time, or right and forward ect.  I am probably making some simple mistake.  I have an example below. Thanks!

Solution
All you literally need to do to fix this is Click this button. (on all of your Motion Actuators)

Reason
When the Ad button is not clicked, each Actuator is setting the location, and is is overriding any other Actuators activated previously, regardless of whether or not they are still running. Enabling the Ad button makes each Actuator add to the change in location, enabling multiple Actuators to be executing at the same time.

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


text:
how to turn off moving objects by holding RMB?
I use for selecting RMB, but blender also has RMB for moving (hold and move mouse), but my computer is not superfast and my model is complicated enough to slow it down a little (over 800 000 verts.) and when I want to selcet a mesh, the slowed down computer automaticly thinks, that I hold it and starts to move the object. Is there a way how to turn off this function?

Go to User_Preferences->Input->Mouse->Tweak_Threshold and set it to higher value :

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


text:
is there a quick way to delete a group and leave the objects?
I added my objects into groups to append them easily and now I have got bunch of groups which I don't need anymore. how can I delete them?

Ctrl-Alt-G opens the remove from group popup where you can remove all selected objects from all groups. When the last member of a group is removed the group itself will be dissolved.

Shift-Ctrl-Alt-G removes all selected objects from all groups. Ctrl-Alt-G just removes them from a group.

I think it's clever to use the Outliner, choose Groups and then by Right clicking on it on the Group you want to delete, Unlink it:

I do think it's clever :)

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


text:
Why can't I select bones in pose mode
I have a little problem-whenever I want to select a bone in pose mode, I select an object behind it instead. If I want to select the bone, I have to select it in edit mode and then switch to pose mode and that is realy slow and anoying. how can I fix this?

Try turning off the X-Ray toggle

That's likely because there are many overlapping objects. A way to work around this is to press and hold Alt and RMB, and while still holding the mouse button, move the cursor so it is over the name of the object you want to select and then release.
This, basically gives you a list of all the objects "under" the mouse, disregarding the view Z distance, so you can pick the one you want.

Make sure the bone you are trying to select is selectable.
In the below EYE_CTL cannot be selected:

In the Viewport Display of your armature, if you've selected the In Front option, you can't select bones in pose mode, so, unselect it.

This does fix it for me, but the weird thing is I've had In Front turned on from the start and was able to select other bones without having to select them in Edit mode first. I'm not sure what changed that prevents freely selecting bones in Pose Mode now.

Having the same issue, and haven't figure it out. Have to select the bone on edit mode then change to pose mode. Very annoying. Is there a lock bone pose selection key shortcode or something?

If I am trying to select things, and it doesn't work, just selects other stuff, I his Z, which makes it wire-frame, and I can usually select with ease! I hope this helps!


text:
how to insert keyframe for pose
I need to insert keyframe for the pose I have made in posemode. How can I do that? when I hit i it writes some error (keying set failed to set any keyframes or something like that)

Does this help? http://blender.stackexchange.com/questions/16531/keying-set-failed-to-insert-any-keyframes

nope, I just don't know, how you can insert keyframe for singular bones, I think, that if it was this I wouldn't be able to set keyframe to anything

so key-framing  is working for other objects but not the bones ?

it most probably is working for them too, but I don't know, how to do it. (if I just need to hit i when the bones are selected, then itš just as you said)

Have you tried to select what type of keyframe you want to add? It is at the bottom just after the type of sync that you would like to keep while playing your animation.
Or if you would not want to set a specific type of keyframe, please click on the red button on the left of type of keyframe.


text:
how to make forest with different types of trees
I want to create a forest. I have already created a few types of trees and now I want them to "grow" out of a plane. I would use a particle system, but I have a few issues: firstly, the trees can't decide whether to stand or lie, I tried to change this using the duplicate object settings, but it was changing randomly without being afected by the settings. Secondly, I could not think of any way, how to make the two different trees not overlap each other (although I found here how to do that with only one type) and lastly, for some reason when I added the second particle system it generated only one tree instead of 1000 which is defalut.
I am not familiar with using python with blender. the trees are realy simple and low poly models, without any sofisticated details.

Related: http://blender.stackexchange.com/q/39192/599

Related: http://blender.stackexchange.com/questions/8111/which-particle-system-is-best-for-trees-in-a-forest and http://blender.stackexchange.com/questions/36892/how-to-use-emitter-for-generating-thick-forest-so-that-trees-would-not-intersect

Mask system's density and Render Groups
To avoid interaction between two particle system you should somehow mask their density in a complementary way, so where one is the other isn't.

Let's start from creating a simple forest with two type of trees and only one particle system:
After modeling the tree types, you should assigning your sample trees objects to a group (select and Ctrl+G):

Then add to your surface a particle system with these two characteristics:

Hair particles initial orientation on Global Z with random phase as well described in this answer to get trees pointin straight up and with some random rotation around the Z axis
Render option set to Group (pointing to the previously created group)
with Rotation (rotate your object towart the X axis as in the picture) and Pick random

The last mentioned option will pick a random object from the target group, resulting in an assorted forest.
To get full control, you can use the Count option instead which would let you choose in wich proportion each tree type is present in the forest

Above you can see a fores made by 90% of pines and 10% of Betullae.

Now add a second particle system, this time made by 20% Pines and 80% Betullaes:

Go to weight paint, create a new vertex group layers and start paining red the places where the Pines (90%) will be. Then duplicate the vertex group (Copy vertex grup from the menue), Invert the weight, paint some 0 weight areas (where you don't want anty tree) and rename the vertex group to Pines 20%.

Assign to each particle system the appropriate vertex weight group and you'll have a two-tree-type forest:

Apart from vertex weight, you can mask the two particles system even with textures, or splitting the surface in many different objects... it depends on what your project's workflow is.

To avoid intersection between particles you should keep an eye on this related question. Sadly there is not a exaustive answer yet.


text:
video sequence editor- how to render video with reversed picture order?
How can I reverse the picture-order (like the rendered video plays from end to beggining) in VSE? is there a quicker way than to render it as individual pictures and renameing them so that the order switches?


text:
how to save pose
The pose my model is in is not good at all, so I wanted to have some pose, which I can easily start animating from, but when I made this pose and clicked aply pose as rest pose, only the armature changed, without deforming the model itself and when positioning it's useless. So I wanted to ask, wheather I can somehow aply position as rest pose, so that in pose mode the model is deformed, or at least save the pose.

You may have to apply the armature modifier

If you apply the pose as rest pose, you are telling Blender which is the initial (rest) position of the bones: undeformed mesh, of course.
If you want to save and recall poses:
-  go to the properties window
- armature
- pose library
- plus to add or repalce a new pose
- lens icon to recall the selected pose.
Note that you can also create different libraries of poses
If you want the complete job (new pose always as starting pose):
- create the new pose in pose mode
- in object mode select the model
- Shift D to duplicate it
- apply the armature modifier
- apply the pose as rest pose
- delete the old model
- add a new armature modifier to your new model, pointing at the previous armature.
The model will have all its vertex groups, so you will not have to redo the weighting.
This procedure can be very useful because, when animating, in pose mode Alt G, Alt R, Alt S let you put the selected bones in rest position.

Updated answer since v3.0 (this answer uses 4.1) where they moved this feature to the pose library:
Open the following editors:

3D viewport with your armature selected and in pose mode
Dope sheet with the action editor
Asset browser

Create the first pose you want to save. Optionally, create a scene camera that will give a good view of your pose. If you want a preview of how your thumbnail will look, use the workbench renderer.
Now select all the bones that belong to the pose and in the dope sheet > action editor hit "create pose asset" (hit N if you don't see the toolbar):

Optionally, you can now change the name of your pose and give it a meaningful description. If you have a scene camera set, you can also generate a preview:

You can now right-click the asset and apply it to your bones, blend between them, etc.
Blender docs


text:
Suddenly created meshes are invisible (even though they are checked as visible), cannot create any new objects now
as the title states I am suddenly unable to create any new objects, when i select a mesh from the "create" bar nothing noticeably happens, other than the object name appearing in the list in the top right hand corner of the screen, i cannot edit the object, view the object, or do anything at all to it, this happened suddenly part way through a project and has caused me to be unable to continue, it's driving me nuts and I cannot for the life of me see why this has suddenly happened, im sure i must have accidentally pressed a keyboard shortcut for something, but i do not know what, any ideas?

can you add a snapshot or a blend file?

Try centering your view on the objects. Press 'Numbpad .' (Period).

it could also be that the far clipping plane of the viewport is cutting off objects that are beyond it.

Is your 3D cursor visible in the viewport? If not then the objects are probably wherever the cursor is.


text:
How can i bake an animated and extruded curve to a mesh animation?
I have a text object that i want to reveal with a kind of handwriting effect. My plan is to animate an extruded curve which i want to use as a boolean operator on my original object.

How can the animated mesh (blue) be exported or converted so i can use it later on the red text? Right now i cannot select the blue mesh as an operand in the boolean operator.

The blue mesh isn't a real mesh it is generated from a curve so it can't be used in the Boolean modifier ( and other mesh dependent modifiers ) , also the text object( red one ) is a curve so it can't be used in the Boolean modifier.
You can convert  the curve into a mesh :
 - select the curve and hit Alt+C and choose Mesh from Curve
Note: beware after converting to a mesh you loose the curve editing options ( including this animation )
The animation you have can be replicated using the build modifier  on the converted mesh :

now you can have both the animation and the Boolean modifier on this mesh

The build modifier produces unpredictable results and the resulting mesh causes "Cannot exectue boolean operation". Even with removed double vertices and fixed normals.

@dequid the build modifier follows the vertices order ( which created first ) , for the boolean modifier  see this answer

yes, and that vertex order is my problem. If i check fill caps, the polygons on the caps are builded first in the build modifier. As i understand, i need a closed mesh for the boolean modifier to work properly. Any ideas?

it seems that the vertices order can't be changed, also the boolean will need non self intersecting mesh where this is not , can you give more details on the main goal you are trying to achieve maybe there's another way?

As you can see in my first animation, i want to have a text mesh (red) which is revealed over time like it was 'written by hand'. So at the 'T' for example the lower stroke from top to bottom then the lower stroke from left to right and so on. What i also thought of: Is there a way to import a vector animation into Blender (i know this is a separate question)?

@dequid for the vector animation i have no idea ( i know that you can import SVG ) , is your scene more complex cause i can achieve the effect with material nodes ( no boolean needed ) if you want ?

No, for the text part it is just that simple. Would love to see the material approach since i dont know how to make parts of an object invisible based on its material.

here is the example file if that's what you need i'll edit the answer to include it

Goes definitely in the right direction, except the transparent BSDF does not work, when the text object is extruded (non covered areas get black instead of transparent).

this is weird  , i'll see if i can fix this

@dequid here is another file see if it does it, I had to reverse the animation and change the shaders order

@Chebdou it works. Thanks a lot. If you make it an answer, i'll upvote and accept. Cheers.


text:
A reliable way to make a brick tower
I have been trying to make a brick tower, but the method I'm using doesn't seems too reliable.
This is the method I'm using:

Move the brick origin to the center, followed by an empty object/array to rotate it.
Make another empty object for the second array (tower height) and rotate it so it mixes the bricks a bit.

The problem with this method is that I need to do lots of tinkering, since I need to rotate the second array to mix the bricks, then move the second empty object to try to get the tower "straight".
As you can see in the picture, the tower is not perfectly straight. Is there a better way to do it?

As a trick / another suggestion exactly for this case: you can use Add Mesh WallFactory, just like in this CG Geek lesson - https://www.youtube.com/watch?v=lwBBIN-pV3g

Instead of two empties use one curve and an empty as follows :

add a curve circle
add  Array modifier with some offset ( 1.05) and set it to fit curve
add a curve modifier and set to use the curve circle
add Array modifier with the empty as an offset object
this is the setup now :

and the modifiers ( on the brick ) :

the result and manipulation :
all object should be at the origin, sclale the curve to change the diamater , and rotate the empty to create the rotation offset

update : for any wall shape :

add a stack of 3 array modifiers and one curve modifier as follows  :

You control the length and shape of the wall using the curve :

Wow, really nice. just what i was looking for :D
thanks alot, and thanks for the wall input, that was other of my concerns !

Can you supply an example .blend with those two examples?

@TheMinecraftMan757 here it is the one from the screenshots :  .blend file

Important - use Ctrl + A to reset the location, rotation, and scale of the brick, circle, and empty before setting up the rest. Moving the empty along the z-axis is what makes the rows extend upwards. This can be done after the setup.

Very nice. Thank you! This really helped me out.


text:
Difference between Write Normals and Smooth Groups option in export .obj?
Hi its just a simple question, whats the difference between those two? its sound like they do something similar, but in which case should i use one over the other?
Also if i can get a good explanation of those two would be great.
(i ask this looking to make some assets from high to lowpoly and baking in xnormal, so im using auto-smooth sharp edges, etc)
Thanks!

Write Normals does what it says - it write actual normals (face corner ones, i.e. one normal per face and per vertex). This is the most powerful and precise option, since it not only allows support of sharp edges and smooth faces, but also advanced low-poly tricks used in games and architecture, like 'rounded' edges etc.
Smooth Groups are a simplified version to store some non-uniform shading, it defines groups of faces that form a smooth surface. Meaning, edges between faces of a same group are smooth, while edges between faces of different groups are sharp.
Which one to use is mostly a matter of “what is supported by target application(s)”, though I would recommend to try normals first, since they allow more possibilities.


text:
Making instances reach towards each other
I would like to make instances reach each other depending on the distance (like metaballs would) and, if close enough, merge into one without a border between them. Can somebody please suggest a node setup for that? I can do boolean but I need exactly that reaching in proximity effect

render of what I have
the current GN setup
the result I want to achieve with GN

I would try mesh to volume and then volume to mesh. That's pretty much how metaballs work, they use remeshing...

If you look at the nodes setup I tried to do exactly that. However, it does not make instances try to reach each other while in proximity like meatballs do


text:
based on each car animation
I'm finding it difficult to achieve car

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

You could unwrap your object so that the faces do a straight UV (here I've used Follow Active Quads):

Give it this node setup with a Gradient plugged into a ColorRamp and with the Mapping location value set to a value that makes it black:

Keyframe the Mapping location so that the light moves forward:


text:
Boolean difference not taking effect
I'm a blender novice trying to use the boolean difference tool to remove part of an object using another object extruded from an SVG, and while I've followed the steps detailed in a number of tutorials the modifier never seems to take effect, as per the screenshot. Any assistance with how I may be incorrectly using this modifier would be appreciated!
Blend file here

maybe you need to make the boolean object transparent, or try Solver > Fast instead of Exact, or please share your file: https://blend-exchange.com/

That boolean has worked correctly but you need to hide it to see its effect. Select the boolean object (pumpkininterface.svg) then hit H and you'll see it has cut the pumpkin correctly. (Use Alt-H to unhide it.) If you want to make its effect permanent, select the pumpkin then apply the modifier by hovering over it on the modifier properties panel and hitting Ctrl-A. Then select and delete the boolean object using X.


text:
Joining rigs deletes parts
I'm trying to give a humanoid character bird feet. I'm using rigify to make the armature. Every time I try to frankenstein the bird feet bones onto the rest of the body, it deletes the character's fingers (or vice versa depending on which armature I select first). Why does this happen, and how can I get around this?
(I have already generated the bird and humanoid rigs and deleted the parts I don't need. The finger deletion also happened before rig generation, however.)
model with armature:
Separate armatures:

Joined (fingers missing):

Without any images or a Blend file it's impossible to guess. See How to upload an image to a post and you can share your Blend file via https://blend-exchange.com/ following the instructions there to copy the link on that page. Then edit your question here and paste the link into it.

I think your really have to share the .blend, as simplified as you can make it, on https://blend-exchange.com/ , for this to be answerable. Please edit and illustrate.. as it stands, this question is vulnerable to closure as 'unclear', because, although we want to help, we don't have enough to go on.

I'm having some issues with the .blend uploader. I'll get that up as soon as I can but I've added screenshots now.

My recommendation: learn how to use Rigify correctly. Or bang your head against the wall when your frankenstein attempts fail. The choice is yours. Plug to my free Rigify course on YT :) https://www.youtube.com/playlist?list=PLdcL5aF8ZcJt1GvL-Fcxy-fPgEFG-1fLp


text:
Fluid simulation is choppy with animated obstacle descending on Z axis [video included]
see video for example HERE.
I have a cylinder that's an obstacle for my fluid simulation. It descends, and the fluid is supposed to descend with it. Well... it does, but on the bottom where the fluid meets the obstacle, it jumps instead of gradually going with the obstacle. Here's the blend file for review: blend file.
Any help would be greatly appreciated. Thanks!

I think this is due to the resolution of the domain object. Try with a higher resolution, it should descends more smoothly (shorter steps). The trick is to find the acceptable maximal resolution ;)

That's not an error; that's simply Blender telling you that your fluid it too low res. Generally, I would say, "up the Final Resolution: for a smoother result," but that won't help that much in your case (150 should be plenty for most anything).
However, in this case, the issue is that your Domain is HUGE!!! The Domain should be exactly that; a cube that encompasses anywhere your fluid might travel and NOTHING ELSE! So if you scale your domain cube from Img 1 (where it currently is) to Img 2 (what I am suggesting), your resolution (being relative to the size of the Domain) will "increase."
Img 1; how you have it:

Img 2; what I'm recommending:

Notice how it only encompasses where the water will be. Lastly, consider the following image, which shows how your fluid will bake after the modification (so much more concentration!).
I only let it bake the first frame, because baking will now take longer:

Here is a .blend file with the modifications:

Shady Puck, appreciate the reply and feedback. I'll definitely have to consider the domain size more carefully in the future! However, if you baked the simulation to around 11% with your modified .blend file, you'd see that it's still doing the same thing: when the cylinder gradually lowers, the fluid jumps down to meet it every couple of frames in a very non-fluid movement. I can't say this solution fixed the problem.

@Jesse Trying to bake now. That's very interesting. I will look at that.

I'm with you, I'm as equally curious about its behavior as I am solving it.
Appreciate the help!

@Jesse I believe that you would have to enhance the resolution to infinity before it was completely smooth. The same way Blender uses many_n_-gons instead of circles, it uses smaller and smaller cubes instead of fluid. I can think of two solutions. 1.) Up the res and move the camera farther away so you don't notice. 2.) Let it bake and then keyframe the Domain's Location on the Z-axis so the water glides w/ the cylinder. I'm sorry, but there is no perfect solution to this problem in this Blender version. By the way, if my answer or this comment helped, please consider accepting it.


text:
Create a cloth with two control points at each end? [video example included]
See video for example of problem: Watch on YouTube
I'm trying to create a cloth string object (made of a mesh with just edges and vertices. No faces) that can be controlled by two end points. Best I could find in my research, hooking both end vertices to hooks (empties being the hook point) seemed like the best option. BUT, when I playback the simulation, the hook points only affect the one vertex they're hooked to; they don't affect the rest of the string.
Is there a way I can achieve this effect of a cloth string that's controlled by two end points? Is there a better way than what I'm doing?

Could you show an example of your intended goal?

I believe the cloth simulation has to have faces to work because of structural stiffness and spring settings.

Maybe this file can point you the right way:

For simulation these kind of hairy strings, Soft Body Simulation is great. It's relatively fast to calculate, and it works on mesh edges by definition. In the sample scene, I just created an edge and subdivided it a few times. Then I added both end vertices to a group called Pinning, and created a hook for each end.
After that, I added a Soft Body Simulation to it, setting the Goal like this:

So very stiff, high damping, Goal Strength to 1 (so the end points will stick to the hooks), and choosing the Pinning Group to define the goal. When playing the animation, you get this:


text:
How to make a flexible "garden" hose that can be controlled from both ends without losing shape?
I've been spinning my brain for the last few days trying to figure out how to do this. Basically, I need to make a hose (single tube shape, it doesn't have to be twisted like the image) that:
(1) Is naturally affected by gravity.

(2) Can be controlled from both ends of the hose, so both end points can be manipulated in keyframes.

(3) Won't deform or lose it's hose-like appearance when being moved around (like if someone was to literally move a garden house around in their front lawn).
Can anyone offer some insight into how I could accomplish this? Any advice would be greatly appreciated.
Thanks!

Have you checked out this tutorial? : https://www.youtube.com/watch?v=raQs9f4x0gw May be helpful.

@PaulGonet, thanks for the reply. That video was very helpful, and it did give me some ideas to possibly make something work.
However, if there was a way to make that be affected by gravity, then we'd be in business.

Unlike the phone cord, your hose won't need to stretch, so you could use the bezier curve used for stretching the phone cord to simulate the effects of gravity, instead.

This may be a solution for you: Rig that reacts to gravity

Thanks to you both! Between these two solutions, I believe I have a way to make this happen!


text:
Copy driver transform object when creating new scene
Is there a way either when copying a scene or even and easy way after, to update the "transform object" of a driver? I've noticed that even if creating a new scene as "full copy" that although all the objects and meshes are properly duplicated, that the driver object of the newly created key is still set to the original driver object. I know I can simply change it in the graph editor, but in some cases scenes can have many meshes with many keys and this becomes quite tedious.
See in this outliner image, I've duplicated the scene with "Full Copy" and although all my objects are now single user, both keys are using the same Driver Object.

I would submit that as a bug. I would expect a new driver if I did a full scene copy, and not have a Scene 1 object still driving a Scene 2 target.

Well, I found this similar bug already reported, but they closed it as "not a bug." However, in my case I'm copying full scene so the mesh is not duplicated so should it not update the driver references to the new objects as well?

Where's the old bug report?


text:
Cloth Physics not Working after apply
i have made a female charackter and i will add Physics to the breast of the charackter. it's working fine but when i apply the cloth physics the physics object to simulate the breast physics will not move any more and the SurfaceDeform that i use to follow the breast physics object movement are not moving to, also when i apply the SurfaceDeform the brest go to the left and will also not move with the breast physics object
Blender File: https://drive.google.com/file/d/1v0MarpcC3JaH3J4ryZFaFSda-NzauCjD/view?usp=sharing

When you say apply, you mean apply a modifier? Then that's normal. Applying a modifier effectively bakes the mesh as it is when you apply the modifier. Don't apply it if you don't want that.

In Blender, "Apply" kinda means "bake the changes to the mesh and delete the modifier". There's some vertex weight or surface deform trickery you can employ if you need to get rid of the cloth physics but keep the deformations, but unless your PC's having a hard time, probably easier to leave the modifiers running


text:
How do I keep the solid objects visible when viewed through transparent objects?
Transparency works for the background but solid objects disappear behind the transparent object.
I'm new to this and watched a load of tutorials but I don't see what I'm missing.
This is my issue here:
As you can see, this has a glass/transparent panel on the front.
The unit the glass is attached to should be visible.
This is what I've used for the transparent object. I based it from another tutorial to get this transparent effect:

This is what I've got for the solid object:

Let me know if anyother screenshots would help.
I know I'm showing my full noob colours here but I appreciate anyone taking the time to check this out.
Thanks!

Hello, if you are in Eevee make sure that the object you want to see is opaque, but maybe show some screenshot, or even share your object

@moonboots I updated my post. As far as I know I'm using "All" instead of eevee or cycles. I can't really share the object since it's not really mine to share and I'm helping out a mate with it.

If you have selected the Eevee render engine, for your solid object, in the Shader Editor, open the N panel > Options > Settings > Blend Mode > Make sure that it is set to Opaque, and for the glass object enable Screen Space Refraction, and in the Render panel enable Screen Space Reflections and Refraction

@Moonboots you absolute star. You're a saint and a scholar! Thanks very much for taking the time to help me. That worked like a charm.

If you have selected the Eevee render engine, for your solid object, in the Shader Editor, open the N panel > Options > Settings > Blend Mode > make sure that it is set to Opaque, and for the glass object enable Screen Space Refraction, and in the Render panel enable Screen Space Reflections and Refraction.


text:
How to make 2 parts vertices match?
I'm making a character, but the body and head are different parts, because I the mesh in the head is a bit more detailed and I also want the possibility to use the same character for different faces. I may be implementing morph data in the future, but probably not for the neck.
But the thing is that the intersection in the neck, does not fit well with the two parts, my objective is to make them match, and, if possible, lock this intersection from future editings.

It is in the beginning yet, so it's not that good, but I intend to greatly improve it in the future, adding mouth, face rig, improving the shape, and adding morph data when everything is ready.

OK, thanks for the heads up everyone! My current solution:
Alt to select and Shift D to duplicate the edge in the head, P to separate, Shift Alt to select edges in the body, X to delete, did small adjustments in the Neck, Ctrl J to to unite the neck edge and body, Ctrl E to bridge edge loops, as suggested.
If someone has also a way to lock these edges from future editings, so I can improve this part some more, let me know.

Adding some screenshots would help a lot to understand your problem.

Hi, Lucas, I'm afraid there's unlikely to be a general method for this. You'd have to be systematic about it. Please show us an illustration of the join in your particular case, so we can do the best we can.

you can use some topology technics to make the joint, but we need the file to give a try, or at least show a screenshot, or keep the head and body as separate meshes if you don't have to show the neck?

Hello, again we can't help if you don't share your file, you could try a bridge edge loops between the head and neck, and correct manually if needed, or just hide the joint under a cloth if it's possible


text:
Animate curve point by point
I am loading the data of a line from a csv file to create a curve. If I animate the curve by keyframing the "factor end" property in the UI, I get the visual animation I want, but the mapping doesn't work, since my path is traversed with a (known - I can generate that csv data, if needed) different speed. However, in the csv data, each point is 1/50 s after the next, and I want to "extend"/animate the curve using this information.
1st
I've tried the UI with all 3 "end factor mappings", but none let me specify more in detail.
Since the points are a constant time-duration apart, I would just need a "show 1 point per frame" option, but this didn't work for the 3 mappings, that I can choose from the menu. Only start and end points are synchronized to my other motion, of which I know it's correct. Maybe the problem is with my path settings? -> see below in the script, how I generate/set the path.
2nd
Another idea is to keyframe when loading the data in python directly.
I've tried modifying my loading/curve generation script:
import bpy # blender python API
import csv

# create the Curve Datablock
curveData = bpy.data.curves.new('myCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 1

curveData.bevel_depth = 0.002 # m thickness of the path in m
curveData.bevel_resolution = 10
curveData.use_fill_caps = True # the rounded line should not be hollow

# map coords to spline
polyline = curveData.splines.new('POLY')
polyline.use_endpoint_u = True

curveOB = bpy.data.objects.new('myCurve', curveData)

bpy.context.collection.objects.link(curveOB)

#with open('/home/mike/Documents/ownCloud/3D/blender/data/p_err_2.csv') as csvfile:
with open('/home/mike/Documents/ownCloud/3D/blender/data/p_ref.csv') as csvfile:
    readcsv = csv.reader(csvfile, delimiter=',')
    k = 0
    for i, row in enumerate(readcsv):
      if (i % 1) == 0:
        if k != 0:
            polyline.points.add(1)
        polyline.points[k].co = (float(row[0]), float(row[1]), float(row[2]), 1)
        k += 1
        polyline.points[0].keyframe_insert('co',frame=k)

but the keyframes - if I undestand correctly - just place the points where they already are .. But I wanted them to appear at this keyframe.
Is there a way to change the "end factor" mapping, that reveils points by a constant time difference? Is this something that could be achieved with fcurves? Or is there a way to repair my loading keyframe thing?
3rd
I've now also tried to use Geometry nodes and the combination of the
Index -> Greater Than -> Delete Geometry (Point)

will delete the Verticies of the curve object, rather than the points that defined the curve.
If I use Spline Parameter instead of Index, either the whole curve is removed with negative values, or it is displayed in full with values greater than zero.
4th
I've tried this "hide" property of the points, but it's apparently not used to eliminate the effect of the control point?
points = curveOB.data.splines.active.points
# Loop through and hide points up to the specified index
for i, point in enumerate(points):
    if i <= 5:
        point.hide = True
        point.keyframe_insert(data_path="hide", frame=2)
    else:
        point.hide = False
        point.keyframe_insert(data_path="hide", frame=3)

# Update the curve object
bpy.context.view_layer.update()

You could use geonodes to delete every point with index higher than current frame number…

I've tried to achieve what you suggested and it seems very plausible, but I couldn't get it to work with my experiments -> see last edit of the question.

Actually I found a solution using python:
I've added points for all datapoints in the csv file.
First I set the position of all points to the first point. Next, I animate their position, such that all "not shown" points move with the next point to be shown.
import bpy # blender python API
import csv

# create the Curve Datablock
curveData = bpy.data.curves.new('myCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 1

curveData.bevel_depth = 0.002 # m thickness of the path in m
curveData.bevel_resolution = 10
curveData.use_fill_caps = True # the rounded line should not be hollow

# map coords to spline
polyline = curveData.splines.new('POLY')
curveOB = bpy.data.objects.new('myCurve', curveData)
bpy.context.collection.objects.link(curveOB)

data_path = '<file>/data.csv'
with open(data_path) as csvfile:
    readcsv = csv.reader(csvfile, delimiter=',')
    k = 0
    for i, row in enumerate(readcsv):
        if i == 0:
            # save the first value -> all points will be placed there at frame 0
            row0 = row
        if (i % 1) == 0:
            if k != 0:
                # add points for every value in the file
                polyline.points.add(1)
            # initialize all points at the row0 position at frame 0
            polyline.points[k].co = (float(row0[0]), float(row0[1]), float(row0[2]), 1)
            polyline.points[k].keyframe_insert('co', frame=0)
            k += 1

    # reset the file and reade from the start
    csvfile.seek(0)

    k = 0
    for i, row in enumerate(readcsv):
        if (i % 1) == 0:
            # place all following points at data position at frame k
            for m, point in enumerate(polyline.points):
                if m >= k:
                    point.co = (float(row[0]), float(row[1]), float(row[2]), 1)
                    point.keyframe_insert('co',frame=k)
            k += 1

Once you have your curve beveled, it becomes a mesh and in Geometry Nodes it is considered to be a mesh.

So you have to remove bevel_depth to keep it as curve, and then you can use it as curve in Geometry Nodes:

When you see the desired effect, you can add beveling after removing control points:

Thank you for the clarification! I'm sure this is a valid solution as well! Meanwhile I've managed to achieve what I needed in python, which is a very convenient way for me, since I only need to load the file similar to the other measurements, that I have.


text:
Extrusion/Bevel of Path with many points
I'm trying to visualize data in blender and the measurements often have many datapoints close to each other.
Using a NURBS curve and a bevel to make the curve have thickness, it struggles with noisy data. Here, the surface is turned into itself and looks strange. I'd like to end up with similar results to the 2D plot provided. I would assume the problem is with the very fast changes in tangent/normals directions. Is there a way to achieve similar "lines", like I have in the 2D version, where spikes are shown, but the outer surface is combined?

You could try smoothing? And/or re-meshing? Maybe you could share a typical data-set with us on https://blend-exchange.com/, and  typical target results (hand-made if necessary)

Actually, I found a way to present the line as "flat", by using an emittent shader in the material. This way, irrespective of the camera angle, the line looks like a "plane" and looks very similar to the drawing, instead of a 3D object. This way, the self-intersections of the path looks fine.


text:
Rendering darkspot
I am trying to render a glass bottle filled with mushrooms but a darkspot keeps appearing. I also tried to place a light directly above it but it keeps happening. Is there anything i can do?

Hello, maybe it's just reflecting the environment, what does it give if you use an HDRI image, or a brighter Background color?

I have added a background colour. i dont know what an HDRI image is however. The wierd thing is sometimes the darkspot is white instead of black

I have just redone the shape and that fixed it. I still dont know what the issue was tho. But thanks for holding my hand throught this moonboots :)


text:
Boolean Difference not working with one specific number
I am trying to model a D20, and I am having an issue where the boolean difference seems to be creating the hole for the 7 but is not removing the top of the face of the dice. I am having no issues with any of the other numbers than the 7 so clearly it is the 7 causing the issue, but I am not sure what it is doing.
I have tried resetting the normals, deleting doubles, and finding interior faces.
Here are some screenshots of the 7.

The weird part where the lines are created is the part of the face that is not being removed

My apologies is this topic has been solved before. I tried to search and do the common issues. I know if is something with the mesh of the 7 causing this issue.
I appreciate the help!
Thanks,
Chris
tried using both fast and exact. I think it is still something wrong with the 7.
Does this work for the blender link?

pls provide blend file, if changing settings from fast to exact or vice versa doesn't help. thx.

As Chris it would help if you shared the file, also Boolean may create bad topology like ngons so you may need to correct manually

Hi Christopher, the first thing to try is changing the Solver in the Boolean Modifier panel. Try setting it to Fast. Sometimes applying a Boolean operation on a single face using more complex object having concave surfaces could be tricky. Try subdividing your mesh a few times to see if that helps too.

Your 7 object has overlapping vertices, select all in Edit mode and press M >Merge by Distance


text:
How to model this organic leaf structure?

I am trying to make this fungi-looking leaf structure shown in the image. I am able to make the overall fungi-looking structure, but the problem is that it is in the shape of the object I create it with, like a plane. I want to have a different edge, like in the image. Also, there's a middle stem in all of the shapes, but I can't figure out how to include that geometry. I would appreciate any information that could help me.

Hi Weird Panda! How familiar are you with 3d modeling in Blender? Can you edit your question and show us a screenshot of your progress? This way we can help better in offering you a solution.

Hi Rumen! Thank you for responding. I am not so familiar with modelling in Blender, especially with more organic structures. I have only worked on hard-surface objects before, and I have added a current screenshot of what I've done. I can only make a vaguely similar-looking organic structure, which I learned from a tutorial. I hope this helps, and you can help me in any way. Thanks!

I think you have to look for 'organic modeling'. I've never done it myself but with the Tissue addon one can get these kind of models. Some links: the addon  or this channel or this video on youtube

Shout out to Irene Laschi, who's wonderful hand drawn illustration we are trying to recreate.
A basic knowledge of editing meshes menus, using Modifiers and Sculpt mode  is required.
The steps bellow show an approach on how to model the "leaves" which resemble a mixture of slime mold and dried plant leaf structures:

Start from Top view, add a Plane object and subdivide sequentially twice while shaping the overall shape of the leaf.
Add a Subdivision Surface modifier with level 2 to smooth out the shape and add extra geometry to the plane.
Add Decimate modifier to triangulate and reduce the subdivided faces. View the Wireframe to observe how the settings change the triangulation.
Add Geometry Node modifier with the simple node set up - include only the Dual Mesh node with default settings.
Apply all modifiers so far and enter Edit mode to delete any loose vertices.
In Edit mode - subdivide all edges once more and slightly Smooth the mesh vertices.
Select all faces and use the Inset operation (hotkey [I]) with Individual option turned on (check the operator settings). Make a small inset inwards and delete the selected Faces.
Extrude part of the border where the trunk will be. At this stage you can Tweak the vertices to shape the mesh.
Select the vertices that will represent the trunk and branches and assign them to a Vertex Group named "Trunk".
Optionally you can smooth the vertices weight in Weight Paint mode.
Add a Solidify Modifier with Offset = 1, Thickness = 0.065 and Only Rim option On. Choose "Trunk" vertex group and set the Factor to about 0.5
Add Mirror modifier with Z as mirror axis
Add Subdivision Surface Modifier with subdivision level 2
Apply all modifiers and enter Sculpt mode. Using the Grab brush and appropriate brush size gently adjust the shape to emphasize and straighten  the trunk and branches. Use Inflate brush to adjust the girth of the trunk and branches. Use Smooth brush to smooth the structures - less at the center, more at the ends. You can enable Z axis symmetry to apply the brushes on both sides of the symmetry plane.

Here is an animated version of the steps above:

Thanks, Rumen, for the help. This helped me a lot, and now I understand how to model the shape, so again, thanks a lot! Also, shout out to Irene Laschi for the amazing illustration.


text:
How to save changes if main window was closed?
I have opened view in separate window, then closed main window without any warning. Now when closing separate window I get

Winthout any propose to save.
How to save then?

Ctrl-S is the save shortcut

He probably created another window in the same file by Shift + Dragging the corner of a view.


text:
Show only interior of the cube?
Is it possible to show only interior of the cube in normal mode?
I made flip normals, but still see convex shape

The question isn't clear, attach images to explain the question better, what do you mean by convex shape? What render engine are you using? And what are you trying to achieve.


text:
Use modern features like SURF in camera tracking?
There are plenty of modern and effective features, which are suitable for camera tracking, like SURF. Does blender use them? Apparently not, because it's camera tracking feature requires a lot of by-hand operations.
Is it possible to use that modern features in blender? Probably licensing prevents this, but may be there is some workaround for the problem?

Blender currently uses a KLT-Tracker (Kanade–Lucas–Tomasi) which is documented here .
While algorithms like SIFT and SURF are patented, ORB (Oriented Brief) could be an alternative (BSD licensed) it was developed in 2011 and is already implemented in openCV

ORB

I have no idea whether there are plans to use other algorithms in Blender.


text:
How to Import Image Sequence as Animation in Blender 3.6
Tried adding images as planes and using nodes but cannot add an image sequence as an animation. I have found instructions for older versions of Blender that explain how to add an image sequence as an animation and I have followed them but no success. The specific issue I am having is when I import the image sequence as a plane (via shift+A with the add on 'import image sequence as plane' enabled, or as file import) a small section of frames is imported and there lined up along the x axis. Some are stills and some animate for a few frames. Pictures below.

I have also tried different settings with offset planes and the align options such as changing it to focus on camera, main axis, etc. Here is a photo of one of the combinations I tried.

Sometimes the images would all be in the same space and not offset along the x axis but it would still only import image 1, 2, 3, 4, 10, 20, 30. I tried naming the files different but it still imported the exact same way. I have tried importing images as nodes (following instructions online) and my image will not show up on the plane. I made sure it was set to the correct amount of frames, auto refresh was turned on, but can only get the pink 'no information detected'.
Has anyone else experienced this issue or have any troubleshooting tips? I am aware that you can drag and drop an image sequence into the video editor but then I have no way to tell it to hold a frame or delete a frame. At the end of the day I just want to be able to add an image sequence and edit the length of frames being held. Thanks.
quick edit as I did not show in the original question but here is a photo to show that animate image sequence was selected:

The best way to import a video footage to blender is to convert the image sequence to a video first in a software like premiere pro or a free alternative software , nest the sequence , then import the video in the Add images as planes .

Hey thanks for answering however I'm hoping to be able to select individual frames and say hold for "n" frames. I'm doing 2d animation. Ive seen people do it on older versions of Blender where they select animate img sequence and it works perfect.


text:
Cant figure out how to flip normals on this Space suit Helmet
I downloaded this space suit helmet here https://www.cgtrader.com/items/3165630/download-page and I was planning on 3D printing it. I cannot cut it into sections without converting the normals using other modelling software.
See a blend file here>

Ive tried using the clean up mesh tools and also the recalculate mesh tools.
Any help would be appreciated.
Cheers,

It looks to me that, rather than being a problem with the Normals, it’s actually a problem with Z-fighting - where the inner and outer surfaces of the mesh are touching or overlapping. The red showing through is actually the backface of the inner surface of the helmet.
To 3d-print you would need significant addition thickness in your mesh (otherwise you won’t have sufficient material) so you will need to edit your mesh to move the inner surface of the helmet away from the outer.


text:
Is there any relation between Movie Clip Editor and Video Sequence Editor?
I have a video, consisting of several shots with cuts between them. I would like to make some 3D reconstruction within it. Particulatly, I would like to place some excess 3D modelled objects into the scene.
In Movie Clip Editor I can load some clip from external file and make some reconstruction against it. But this reconstruction should not extend the shots margins. How to denote shot margins here?
In Video Sequence Editor I can cut strips, but these cuts are seem to be unrelated with what happening in Movie Clip Editor.
Is there any relation between them, or they are completely separate? Can I load some strip into Movie Clip Editor, or perform clip editing on strips from Video Sequence Editor?


text:
How to see bundles and back projecting points of different colors?
According to the wiki:

Bundles makes sense after solving the movie clip, and it works in the following way: the solved position of each track gets projected
  back to the movie clip and displayed as a small point. The color of
  the point depends on the distance between the projected coordinate and
  the original coordinate: if they are close enough, the point is green,
  otherwise it'll be red. This helps to find tracks which weren't solved
  nicely and need to be tweaked.

I am solving the scene and see nothing similar to what's described:

Points are displayed not as points, but as squares, blue means before in time, red means after in time. Yellow or white means selected point.
Where is something green?

I might be mis-interpreting something here, but those look green and red to me.. Here's an example image.

@gandalf3 but this is different. red rectangles mean that tracks are exist on other frames, not on current frame; and dirty green rectangles denote tracks on current frame; no any variation according to description


text:
UV Project Modifier doesn't use alpha correctly?
I can map textures with alpha (that I paint in the UV Image editor) and make them partially transparent in the BI renderer.
But when I use the UV Project modifier and allocate the loaded alpha image it disregards the transparency but will show the material colour.
In the material panel when I turn on transparency it ignores the texture slot. I guess because there is no available texture in the texture panel?
I have to manually add a regular texture and turn on the alpha with colour. Then back in the modifier turn off override.
It seems odd that it won't correctly apply the alpha as transparent.
Why can't alpha transparency work from the UV Project modifier?

Thank you, yes I guessed as much oh well. I need to use BI for speed of render without a GPU to render on :(


text:
AttributeError: 'NonType' object has no attribute 'name'
I am getting the error mentioned in the title:
all_objects = bpy.data.objects[:]
non_hidden = [obj for obj in all_objects if obj.hide_viewport == False]
counter = 1

# Iterate through all objects non hidden objects in the scene
for obj in non_hidden:
    bpy.ops.object.duplicate()
    duplicated_obj = bpy.context.active_object
    duplicated_obj.name = f"{obj.name}_{counter}"

It specifically complains about the last line.
I have some code comming after that and when i deleted the last line it gave me a new error in the same line now saying that object doesn't have attribute 'data', where the line looked like this:
for material in duplicated_obj.data.materials:

My code is only 45 lines, so if needed i can add the whole thing at the end of this question.
I don't understand what the problem could be, i would appreciate any help, thank you in advance!

I found the problem:
bpy.ops.object.duplicate() duplicates the selected objects not the active objects.
So, bpy.context.active_object was "None". Once I had selected the object I wanted to duplicate, it worked.

Hello ! Thanks for adding an answer to your problem. Would you mind adding the specific line of code you added to make it work to your answer ? Cheers


text:
blender api modifier_apply throwing "context is incorrect" error
so i am trying to cut holes (a lot if them) into a tabletop and i am trying to use a script which cuts each hole one by one, because blender cant handle doing the boolean for this many objects at once.
So i have implemented a loop which calls the following function:
def boolean_difference(obj, subtract_obj):
bool_mod = obj.modifiers.new(name="Boolean", type='BOOLEAN')
bool_mod.operation = 'DIFFERENCE'
bool_mod.use_self = True
bool_mod.object = subtract_obj
bpy.ops.object.modifier_apply(modifier="Boolean")

obj is the table and subtract_obj is a cylinder which i want to cut out of it.
In the main loop i then do this:
if main_obj and subtract_obj:
for axis in move_axes:
    for i in range(num_iterations[axis]):
        boolean_difference(main_obj, subtract_obj)

        copied_obj = subtract_obj.copy()
        bpy.context.collection.objects.link(copied_obj)

        if axis == 'X':
            copied_obj.location.x += move_amounts[axis]
        elif axis == 'Y':
            copied_obj.location.y += move_amounts[axis]
        elif axis == 'Z':
            copied_obj.location.z += move_amounts[axis]

        # Delete the original subtracted object
        bpy.data.objects.remove(subtract_obj)

        # Update the subtracted object for the next iteration
        subtract_obj = copied_obj

I debugged it and i noticed that i get an error for incorrerct context on only the second iteration. This is the error:
RuntimeError: Operator bpy.ops.object.modifier_apply.poll() failed, context is incorrect

So i am thinking that i do not properly copy the object or have to set something regarding the context of the object, but i unfortunately dont know what and so far i was not successfull in my search for an answer.
If you have any questions i will provide more info.
thank you in advance!

bpy.ops.object.modifier_apply() work on an active object,
use context.view_layer.objects.active = obj before modifier_apply()
def boolean_difference(obj, subtract_obj):
    bool_mod = obj.modifiers.new(name="Boolean", type='BOOLEAN')
    bool_mod.operation = 'DIFFERENCE'
    bool_mod.use_self = True
    bool_mod.object = subtract_obj
    bpy.context.view_layer.objects.active = obj
    bpy.ops.object.modifier_apply(modifier="Boolean")

You can use a context override so you don't have to mess with selection state :
def boolean_difference(obj, subtract_obj, modifier_name="Boolean"):
    bool_mod = obj.modifiers.new(name=modifier_name, type="BOOLEAN")
    bool_mod.operation = 'DIFFERENCE'
    bool_mod.use_self = True
    bool_mod.object = subtract_obj
    with bpy.context.temp_override(object=obj):
        bpy.ops.object.modifier_apply(modifier=modifier_name)


text:
Adding a camera in front of an object based on xyz rotation (Euler to Spherical conversion)
About the script:
I would like to add a camera in front of a selected object.
The front of the object is based on a calculation using a pre-defined polarangle, azimuthal angle and distance.
The problem:
When I rotate the selected object on the Y axis I can't compensate for it, the conversion between the Cartesian and Spheric coordinates resulting a wrongly added camera. It works when Y is 0.
I am using the following function to defined the xyz coordinates based on the distance and the angles from an object.
import bpy
import math

# https://planetcalc.com/7952/
def calculateDirectionPoint(distance,pol,az):
    # calculates the coordinates based on distance and angles (Spheric to Cartesian coordinates)
    x = distance * math.sin(pol) * math.cos(az)
    y = distance * math.sin(pol) * math.sin(az)
    z = distance * math.cos(pol)
    return [x,y,z]

I am using the following code to define the selected object location and the relevant angles.
# following object rotation
object = bpy.data.objects['Suzanne']
objrot = object.rotation_euler
o_x = objrot[0]
o_y = objrot[1]
o_z = objrot[2]

# FRONT x and z
#pol_x = 1.570796327
pol_x = math.radians(90)
#az_z = -1.570796327
az_z = math.radians(90)*-1

if o_y == 0:
    az_m = 0
    pol_m = 0
else:
    # This is the part where the I can't define the right correction for the o_y value from the object y rotation.
    pol_m = math.pi-o_x
    az_m = o_y*((math.pi/2)/o_y)

coord = calculateDirectionPoint(
    6,
    (pol_x+o_x)+pol_m,
    (az_z+o_z)+az_m
    )

cam = bpy.data.objects['Camera']
cam.location = (coord[0], coord[1], coord[2])
cam.rotation_euler = (pol_x+o_x, o_y, (az_z+math.pi/2)+o_z)

So technically I would like to convert the Euler coordinates to spherical coordinates.
Can someone advise how should I compensate for the Y axis?
Thanks.
I also tried the rotation matrix, which works perfectly again when the y axis rotation is 0.
import math
import bpy

locator = bpy.data.objects['Camera']
myobject = bpy.data.objects['Suzanne']

frontVector = [0,-6,0]
#Calculates a rotation of a point in 3d space
def rotationMatrix(vector,roll,pitch,yaw):
    x = vector[0]*(math.cos(pitch)*math.cos(yaw))+vector[1]*(math.cos(pitch)*-math.sin(yaw)*math.cos(roll)+math.sin(pitch)*math.sin(roll))+vector[2]*(math.sin(pitch)*math.cos(roll)+(math.cos(pitch)*-math.sin(yaw))*-math.sin(roll))
    y = vector[0]*math.sin(yaw)+vector[1]*(math.cos(yaw)*math.cos(roll))+vector[2]*(math.cos(yaw)*-math.sin(roll))
    z = vector[0]*(-math.sin(pitch)*math.cos(yaw))+vector[1]*(-math.sin(pitch)*-math.sin(yaw)*math.cos(roll)+math.cos(pitch)*math.sin(roll))+vector[2]*(math.cos(pitch)*math.cos(roll)+-math.sin(pitch)*-math.sin(yaw)*-math.sin(roll))
    print(x,y,z)
    return(x,y,z)

coordinates =   rotationMatrix(frontVector,myobject.rotation_euler[0],myobject.rotation_euler[1],myobject.rotation_euler[2])

locator.location = (coordinates[0],coordinates[1],coordinates[2])
```

After a long and exhausting search I conclude that it is not possible to directly convert Euler rotation to Spherical Coordinates.
However, here is how I circumvent this "small" problem.
The initial problem: I wanted to keep a point which is front of an object in the same absolute position to the object. For me this means that if an object rotates 45 degrees to any direction, the given point will rotate with it and from a viewer PoV it remains in the same position.
Steps:

Define a Vector, which is in front of an ideal object. Ideal object has 0,0,0 rotation and at the 0,0,0 point.
The Euler Rotation order matters! Convert everything to the same rotation, but I am using XYZ rotation.
Get the rotation from your object.
Rotate your Vector around the object coordinates (call it rotation point) with the given object rotation.
Once you have the new Vector coordinates, you can calculate the Spherical coordinates, as you can convert Cartesian coordinates to Spherical coordinates. The reason for it if you want to decrease or increase the distance from the object, but not the rotation.

Currently this is the code I am using for the vector rotation, it is still under testing but it works so far. I did not include the Cartesian/Spherical conversion.
import bpy
import math

myobject = bpy.data.objects["Suzanne"]
myobject.rotation_mode = 'XYZ'
cam_obj = bpy.data.objects["Camera"]
cam_obj.rotation_mode = 'XYZ'

def rotate_vector_around_point(vector, point, angles_radians):
    # Convert angles from degrees to radians
    #angles_radians = [math.radians(angle) for angle in angles_degrees]

    # Translate the vector to the origin
    translated_vector = [vector[i] - point[i] for i in range(3)]

    # Apply the rotation around X axis
    rotated_vector = [
        translated_vector[0],
        translated_vector[1] * math.cos(angles_radians[0]) - translated_vector[2] * math.sin(angles_radians[0]),
        translated_vector[1] * math.sin(angles_radians[0]) + translated_vector[2] * math.cos(angles_radians[0])
    ]

    # Apply the rotation around Y axis
    rotated_vector = [
        rotated_vector[0] * math.cos(angles_radians[1]) + rotated_vector[2] * math.sin(angles_radians[1]),
        rotated_vector[1],
        -rotated_vector[0] * math.sin(angles_radians[1]) + rotated_vector[2] * math.cos(angles_radians[1])
    ]

    # Apply the rotation around Z axis
    rotated_vector = [
        rotated_vector[0] * math.cos(angles_radians[2]) - rotated_vector[1] * math.sin(angles_radians[2]),
        rotated_vector[0] * math.sin(angles_radians[2]) + rotated_vector[1] * math.cos(angles_radians[2]),
        rotated_vector[2]
    ]

    # Translate the vector back to its original position
    final_vector = [rotated_vector[i] + point[i] for i in range(3)]

    return final_vector

# Example usage:
initial_vector = [0, -6, 0]
rotation_point = [0, 0, 0]
rotation_angles = myobject.rotation_euler

result_vector = rotate_vector_around_point(initial_vector, rotation_point, rotation_angles)
cam_obj.location = result_vector

If "az" is rotation around the z-axis and "pol" is rotation around the y-axis:

Consider moving the frame of reference.  Specifically, rotate the y-axis around the z-axis "az" degrees before the y-axis rotation.

Or consider using Quaternion instead of Euler Angles.

"pol" stands for polar angle, which is the angle from the x axis.
"az" stands for azimuthal angle, which is the angle on the z
https://en.wikipedia.org/wiki/Spherical_coordinate_system
I did not check the Quaternion yet, thx for the suggestion!


text:
Corrected road model to conform to earth curvature
I have a 3D road model created in Blender, with a total length of less than 30km. I want to place this model into a 3D Earth system for presentation. However, I noticed that after placing it into the 3D Earth system, the model does not bend with the curvature of the Earth, resulting in an incorrect representation (some parts of the model may be submerged under the surface or floating in the air), as shown in the image.

How can I make adjustments in Blender to ensure that my road model conforms to the curvature of the Earth?part of road model

have you tried using the shrinkwrap modifier

no I haven't. That is great idea!

If your earth is completely spherical, you could:
Join all your object into one, align it with the X axis, set the origin to the center, put an empty at the same location, rotate it -90° on Y:

Give your object a Simple Deform modifier, Bend mode, Axis Y, with the empty as Origin:

Increase the Angle until you have the bend you want:

You could also use a Curve modifier with a curve circle as Curve Object.

In fact, this is the method I am currently using, although there are still some minor imperfections in certain sections of the road model (due to the Earth not being a perfect sphere), the overall effect is still good!

what you can do is apply the modifier then correct manually


text:
Smoke Domain duplication over plane
I am new to Blender but I've learned a lot since I started. I am used to CAD design so I understand how a blender works as long as it's explained to me. I am having a problem where I want to make a scene where the floor is on fire. I've succeeded in making the fire simulation but now I cannot find a way to spread the simulation to the rest of the plane. I tried making a smoke domain for the plane itself but the scales of the simulation were too big and made it so it covers the model. I cannot find a way to duplicate the domain either so I could just spread it along the plane. Is there any way to complete this scene? (For Example: Using some sort of duplication node to copy the small flame across the plane)
The photo below shows how far I've gotten. I have the fire simulated in a small patch and it looks great but now I want to use it to cover the whole plane.

The fire is a basic Mantaflow Smoke Domain
(Domain Settings)
Emitter Object Settings (Texture offset goes from 0.0 to .06 in 120 keyframes)
This is what happens whenever I scale the Emitter Object and Smoke
Domain up and bake the data/noise
I'd Appreciate any help on this matter!!
(Also I would add the .blend file but I cannot figure out how to link it)

@Chris I updated it, I'm not really sure what specific info you guys would need to help, but I'd appreciate it if you could re-read it and advise me on what else I should mention so that I can ask the correct questions! Also I couldn't figure out how to link the .blend file in the post.

just open https://blend-exchange.com/ and follow instructions.


text:
Frozen Rigid Body Simulation
Good day,
I have been encountering an issue in Blender for some time and the issue remains with Blender 4.0. I'm not sure if it's the result of my error, as occasionally removing and adding physics properties fixes the problem, but in this case nothing I do fixes the issue.
In the attached Blend files below, I added Rigid Body physics to simulate 4 cannons firing at a target simultaneously. For 31 versions of this project (I incrementally saved each modification out of habit), nothing seemed to be out of the ordinary. It wasn't until I reached the 32-34 versions where I started noticing that the physics seemed to have completely frozen. At first I simply removed the Rigid Body properties from every simulated object and then added them back. This worked for version 32, but when I tried the same thing with version 34, nothing changed. Because I thought the simulation was close to complete for this small project, I primarily focused on adding simple shading, hence why I had not checked to see if the physics worked with 33, and saved 34 with the bug uncaught.
Feel free to test the .blend file and if you know of a way to correct this issue I would be very grateful if you could share with me what I did wrong (as I have seen this problem before in other blend files).
Thank you very much.
Here are the attached .blend files using blend-exchange (edited in as I had to use the question url to upload the files):
Working older version 31:

Newer broken version 34:

Hello, could you please describe what the simulation is supposed to be exactly? (with the names of the objects)

Select the balls and move them out of their individual collections and in the Scene Collection. BTW, you have two overlapping balls in one of the cannons.

Hello @moonboots, the simulation is supposed to use the piston (Piston Ramming Rod) to launch the balls (simply named ball in each Canon collection) from each canon (Canon Body) and collide with the soft-body target (Cube, modified default cube) in the center of the platform (Floor). Because they are all supposed to launch simultaneously, I was curious to see what the target would do in respond to the collision from all sides. In 'Canon Box31.blend', the balls should collide with the target and cause it to spin.

@RumenBelev Thank you very much, this seems to have fixed the issue. I also deleted the overlapping balls, as Blender had duplicated each Rigid Body object and automatically dumped it in the Scene Collection. It's running smoothly now and I also noticed that I added the Room (named Cube.001) to a Canon collection. Putting it in the Scene Collection got it to run easily, so that advice helped a ton. I am going to try this with another Blender project with broken physics and see if the problem/solution is the same. Thank you again! If you had answered this as a solution. I'd give it a checkmark!