Creating a new vert with bmesh resets previously created verts I'm creating new vertices using bmesh at 3d cursor position but every time I add a new one, all the previously created vertices jump to their original positions (if they were moved). It's like I need to somehow update the bmesh, I'm doing bmesh.update_edit_mesh(ob.data) but this doesn't seem to help. Also I've noticed that if I manually switch to Object mode and back to Edit, verts keep their positions next time I run the script (switching modes with Python didn't help)

Here's what's happening:



And my code:

import bpy
import bmesh

def get_cursor_pos():
    for area in bpy.context.screen.areas:
        if area.type == 'VIEW_3D':
            ctx = bpy.context.copy();
            ctx['area'] = area
            return bpy.context.scene.cursor.location.copy()

def main():
  cursor = get_cursor_pos()
  ob = bpy.context.selected_objects[0]

  bm = bmesh.new()

  # convert the current mesh to a bmesh (must be in edit mode)
  bpy.ops.object.mode_set(mode='EDIT')
  bm.from_mesh(ob.data)
  bpy.ops.object.mode_set(mode='OBJECT')  # return to object mode

  bm.verts.new(cursor - ob.location)  # add a new vert

  # make the bmesh the object's mesh
  bm.to_mesh(ob.data)
  bm.free()
  ob.data.update() # ¯\_(ツ)_/¯

  bpy.ops.object.mode_set(mode='EDIT') #back to edit mode
  bmesh.update_edit_mesh(ob.data) # ¯\_(ツ)_/¯ 

main()


p.s. on a side note I also find weird that running the script selects all the verts I had selected when I had entered the Edit mode, I ownder if that's also part of the same problem
Add vert at cursor in edit mode

The cursor is in global coordinates. Set to local by multiplying by the objects world matrix inverse.

import bpy
import bmesh

context = bpy.context
scene = context.scene
ob = context.object
mwi = ob.matrix_world.inverted()
me = ob.data
bm = bmesh.from_edit_mesh(me)
bm.verts.new(mwi @ scene.cursor.location)
bmesh.update_edit_mesh(me)