1
$\begingroup$

With the following code

def weight_from_distance( scene ):
    floor = bpy.data.objects['GridGrass'] 
    cam   = bpy.data.objects['Camera']

    vert_distances = [ 
        ( cam.location - floor.matrix_world @ v.co ).length for v in floor.data.vertices 
    ]

    maxDist = max( vert_distances )
    minDist = min( vert_distances )

    for i, d in enumerate( vert_distances ):
        # Normalize distance and set as vertex weight
        floor.data.vertices[i].groups[0].weight = ( d - minDist ) / ( maxDist - minDist ) #Line 16

    pSysName      = 'ParticleSystem' 
    vertGroupName = 'GrassGrowth'

    floor.particle_systems[ pSysName ].vertex_group_density = vertGroupName # Update / Refresh

I get an error

enter image description here

Which seems to be saying that my mesh has no vertices, even though it is a huge terrain mesh with thousands of vertices?

Here's my terrain. It may be worth noting that it's a Grid.

enter image description here

$\endgroup$
2
  • $\begingroup$ Is your code actually indented like that, with the code at same level as the function definition? $\endgroup$ Jan 22, 2021 at 17:09
  • $\begingroup$ @ArmoredWolf I wish the solution was as easy as that but no, it just got changed when pasting. $\endgroup$
    – Joehot200
    Jan 23, 2021 at 12:10

1 Answer 1

2
$\begingroup$

A vertex has no vertex group.

Given the error is complaining that a collection does not have a single member (index 0) and the distances list is made from the vertices

floor.data.vertices[i].groups[0].weight = ( d - minDist ) / ( maxDist - minDist ) #Line 16

implies the error is that a vertex is assigned to no vertex group. Test for this.

if not floor.data.vertices[i].groups:
    continue

or ensure in some other way that all the vertices are assigned at least one group.

See second script in this answer re getting all the vertices in a group. Example below edited somewhat to match above

import bpy
from collections import defaultdict

scene = bpy.context.scene

vgs = defaultdict(list)
ob = scene.objects.get("GridGrass")
assert(ob is not None) # make sure it exists
me = ob.data
for v in me.vertices:
    for g in v.groups:
        vgs[ob.vertex_groups[g.group].name].append(v)

# print all verts in GrassGrowth vg

print(vgs["GrassGrowth"])
$\endgroup$
1
  • 1
    $\begingroup$ crap. Should have known I was being stupid. Super helpful answer, thank you :) $\endgroup$
    – Joehot200
    Jan 23, 2021 at 21:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .