1

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

Duarte Farrajota Ramos
  • 59,425
  • 39
  • 130
  • 187
Joehot200
  • 592
  • 2
  • 7
  • 28

1 Answers1

2

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"])

batFINGER
  • 84,216
  • 10
  • 108
  • 233