流场

作者: 大龙10 | 来源:发表于2022-07-04 06:01 被阅读0次

    书名:代码本色:用编程模拟自然系统
    作者:Daniel Shiffman
    译者:周晗彬
    ISBN:978-7-115-36947-5
    第6章目录

    6.6 流场

    继续学习Reynolds的其他转向行为。

    1、流场

    • 把Processing窗口当做一个网格,每个单元格都有一个向量指向特定方向,这样的模型就是流场。在小车的移动过程中,它会说:“位于我下方的箭头就是我的所需速度!”


      图6-14
    • 在Reynolds的流场跟随模型中,小车应该能预测自己的未来位置,并使用未来位置对应的流场向量。但为了让例子更简单,我们只检查小车当前位置对应的流场向量。

    2、Vehicle类

    • 在为Vehicle类添加额外代码之前,我们应该先创建一个流场(FlowField)类,这是一个向量网格。二维数组是一种很方便的数据结构,可用于存放网格信息。

    • 流场可用于多种效果的模拟,如不规则的风以及蜿蜒的河流等。用Perlin噪声计算向量的方向是一种有效的实现方式。流场向量的计算并没有绝对“正确”的方式,它完全取决于目标效果。

    • 现在,我们有一个二维数组用于存放流场的所有向量。下面要做的就是在流场中查询小车的所需速度。假设小车正位于某个坐标,首先要将这个坐标除以网格的resolution。如果resolution等于10,小车的坐标是(100,50),我们就应该查询位于第10列和第5行的单元格。

    • 由于小车可能离开Processing屏幕,所以我们还需要用constrain()函数确保它不会越界访问流场数组。最后,我们在流场(FlowField)类中加入一个lookup()函数——这个函数的参数是一个PVector对象(代表小车的位置),返回值是该位置的流场向量。

    • 假设有一个流场对象flow,通过调用它的lookup()函数,我们就能获得小车在流场中的所需速度,再通过Reynolds的转向力公式(转向力 = 所需速度 - 当前速度),就能得到转向力。

    3、示例

    示例代码6-4 流场跟随

    boolean debug = true;
    
    // Flowfield object
    FlowField flowfield;
    // An ArrayList of vehicles
    ArrayList<Vehicle> vehicles;
    
    void setup() {
      size(640, 360);
      // Make a new flow field with "resolution" of 16
      flowfield = new FlowField(20);
      vehicles = new ArrayList<Vehicle>();
      // Make a whole bunch of vehicles with random maxspeed and maxforce values
      for (int i = 0; i < 120; i++) {
        vehicles.add(new Vehicle(new PVector(random(width), random(height)), random(2, 5), random(0.1, 0.5)));
      }
    }
    
    void draw() {
      background(255);
      // Display the flowfield in "debug" mode
      if (debug) flowfield.display();
      // Tell all the vehicles to follow the flow field
      for (Vehicle v : vehicles) {
        v.follow(flowfield);
        v.run();
      }
    
      // Instructions
      fill(0);
      text("Hit space bar to toggle debugging lines.\nClick the mouse to generate a new flow field.",10,height-20);
    }
    
    
    void keyPressed() {
      if (key == ' ') {
        debug = !debug;
      }
    }
    
    // Make a new flowfield
    void mousePressed() {
      flowfield.init();
    }
    

    FlowField.pde

    class FlowField {
    
      // A flow field is a two dimensional array of PVectors
      PVector[][] field;
      int cols, rows; // Columns and Rows
      int resolution; // How large is each "cell" of the flow field
    
      FlowField(int r) {
        resolution = r;
        // Determine the number of columns and rows based on sketch's width and height
        cols = width/resolution;
        rows = height/resolution;
        field = new PVector[cols][rows];
        init();
      }
    
      void init() {
        // Reseed noise so we get a new flow field every time
        noiseSeed((int)random(10000));
        float xoff = 0;
        for (int i = 0; i < cols; i++) {
          float yoff = 0;
          for (int j = 0; j < rows; j++) {
            float theta = map(noise(xoff,yoff),0,1,0,TWO_PI);
            // Polar to cartesian coordinate transformation to get x and y components of the vector
            field[i][j] = new PVector(cos(theta),sin(theta));
            yoff += 0.1;
          }
          xoff += 0.1;
        }
      }
    
      // Draw every vector
      void display() {
        for (int i = 0; i < cols; i++) {
          for (int j = 0; j < rows; j++) {
            drawVector(field[i][j],i*resolution,j*resolution,resolution-2);
          }
        }
    
      }
    
      // Renders a vector object 'v' as an arrow and a position 'x,y'
      void drawVector(PVector v, float x, float y, float scayl) {
        pushMatrix();
        float arrowsize = 4;
        // Translate to position to render vector
        translate(x,y);
        stroke(0,100);
        // Call vector heading function to get direction (note that pointing to the right is a heading of 0) and rotate
        rotate(v.heading2D());
        // Calculate length of vector & scale it to be bigger or smaller if necessary
        float len = v.mag()*scayl;
        // Draw three lines to make an arrow (draw pointing up since we've rotate to the proper direction)
        line(0,0,len,0);
        //line(len,0,len-arrowsize,+arrowsize/2);
        //line(len,0,len-arrowsize,-arrowsize/2);
        popMatrix();
      }
    
      PVector lookup(PVector lookup) {
        int column = int(constrain(lookup.x/resolution,0,cols-1));
        int row = int(constrain(lookup.y/resolution,0,rows-1));
        return field[column][row].get();
      }
    
    }
    

    Vehicle.pde

    class Vehicle {
    
      // The usual stuff
      PVector position;
      PVector velocity;
      PVector acceleration;
      float r;
      float maxforce;    // Maximum steering force
      float maxspeed;    // Maximum speed
    
        Vehicle(PVector l, float ms, float mf) {
        position = l.get();
        r = 3.0;
        maxspeed = ms;
        maxforce = mf;
        acceleration = new PVector(0,0);
        velocity = new PVector(0,0);
      }
    
      public void run() {
        update();
        borders();
        display();
      }
    
    
      // Implementing Reynolds' flow field following algorithm
      // http://www.red3d.com/cwr/steer/FlowFollow.html
      void follow(FlowField flow) {
        // What is the vector at that spot in the flow field?
        PVector desired = flow.lookup(position);
        // Scale it up by maxspeed
        desired.mult(maxspeed);
        // Steering is desired minus velocity
        PVector steer = PVector.sub(desired, velocity);
        steer.limit(maxforce);  // Limit to maximum steering force
        applyForce(steer);
      }
    
      void applyForce(PVector force) {
        // We could add mass here if we want A = F / M
        acceleration.add(force);
      }
    
      // Method to update position
      void update() {
        // Update velocity
        velocity.add(acceleration);
        // Limit speed
        velocity.limit(maxspeed);
        position.add(velocity);
        // Reset accelertion to 0 each cycle
        acceleration.mult(0);
      }
    
      void display() {
        // Draw a triangle rotated in the direction of velocity
        float theta = velocity.heading2D() + radians(90);
        fill(175);
        stroke(0);
        pushMatrix();
        translate(position.x,position.y);
        rotate(theta);
        beginShape(TRIANGLES);
        vertex(0, -r*2);
        vertex(-r, r*2);
        vertex(r, r*2);
        endShape();
        popMatrix();
      }
    
      // Wraparound
      void borders() {
        if (position.x < -r) position.x = width+r;
        if (position.y < -r) position.y = height+r;
        if (position.x > width+r) position.x = -r;
        if (position.y > height+r) position.y = -r;
      }
    }
    

    4、运行结果

    相关文章

      网友评论

          本文标题:流场

          本文链接:https://www.haomeiwen.com/subject/sonfbrtx.html