next up previous
Next: Querying/updating a population from Up: Interacting with entities - Previous: Interacting with entities -

Querying and updating populations of entities at once

Although it is possible for the script to query a population of entities one by one, waiting for the results of the query to come back each time, it is more efficient to despatch the query to all entities of a population at once and return a vector of answers.

This works in much the same way as querying individual entities.

    Population p = lookupPopulation("layer1");
    class GetPos extends EntityQuery { 
      Object query(Entity e) { return e.getPos(); } 
    Vector pos = queryPopulation( p, GetPos );

The vector which is returned is indexed by the entity's index in the population.

Updates of all entities in a population can also be done:

    Population p = lookupPopulation("layer1");
    updatePopulation( p, new SetPos(1,2,3) );

The example above sets the position of all entities in the population to (1,2,3), which isn't very useful. The update() method needs access to the population and index concerned to allow code like:

    class SetPos2Dmesh extends EntityUpdate { 
      SetPos2Dmesh( Population p, int xsz, ysz, double x1, y1, xinc, yinc );
      void update(Entity e) { 
        // get index in this population
        int index = p.getIndex(e.getID()); 
        e.setPos(x1 + xinc * (index % xsz), y1 + yinc * (index \ ysz), 0.0);
    updatePopulation( p, new SetPos2Dmesh(p, 10, 10, 0.0, 0.0, 2.0, 2.0) );


Fred Howell