Random points inside a parallelogram

前端 未结 11 647
失恋的感觉
失恋的感觉 2020-12-02 07:43

I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.

If it really simplifies the problem, I can limit

11条回答
  •  死守一世寂寞
    2020-12-02 08:41

    A somewhat less "naïve" approach would be to use a polygon fill algorithm, and then select points from the fill lines randomly.

    C Code Sample

    //  public-domain code by Darel Rex Finley, 2007
    
    int  nodes, nodeX[MAX_POLY_CORNERS], pixelX, pixelY, i, j, swap ;
    
    //  Loop through the rows of the image.
    for (pixelY=IMAGE_TOP; pixelY=(double) pixelY
        ||  polyY[j]<(double) pixelY && polyY[i]>=(double) pixelY) {
          nodeX[nodes++]=(int) (polyX[i]+(pixelY-polyY[i])/(polyY[j]-polyY[i])
          *(polyX[j]-polyX[i])); }
        j=i; }
    
      //  Sort the nodes, via a simple “Bubble” sort.
      i=0;
      while (inodeX[i+1]) {
          swap=nodeX[i]; nodeX[i]=nodeX[i+1]; nodeX[i+1]=swap; if (i) i--; }
        else {
          i++; }}
    
      //  Fill the pixels between node pairs.
      //  Code modified by SoloBold 27 Oct 2008
      //  The flagPixel method below will flag a pixel as a possible choice.
      for (i=0; i=IMAGE_RIGHT) break;
        if   (nodeX[i+1]> IMAGE_LEFT ) {
          if (nodeX[i  ]< IMAGE_LEFT ) nodeX[i  ]=IMAGE_LEFT ;
          if (nodeX[i+1]> IMAGE_RIGHT) nodeX[i+1]=IMAGE_RIGHT;
          for (j=nodeX[i]; j

提交回复
热议问题