通过锯齿线连接两条线

时间:2019-05-06 10:00:27

标签: c++ algorithm

我在XZ平面上有两个点, l arger / taller点是L =(X L ,Z L )和 s 小/短点是S =(X S ,Z S

2 points

通过将L和S点连接到Z = 0线,我有两条线

2 lines

我打算用锯齿形对角交叉线连接两条线

zig zag lines

我需要找到点L 0 ,L 1 ,L k ,... L N-1 以及S 0 ,S 1 ,S k ,... S N-1 ,S N

我已经知道两点了:

S 0 = S =(X S ,Z S

S N =(X S ,0)

zig zag lines with dots: 0, 1, ..., k, ... N

到目前为止,我已经实现了此算法:

float lX, lZ = ... // "L" (larger/taller) point coordinate on (X, Z) plane
float sX, sZ = ... // "S" (smaller/shorter) point coordinate on (X, Z) plane

size_t N = 5; // N sections below S
float sZsectionLength = sZ / N; // length of each section below S

std::vector<float> sZ_dots(N+1, 0.0); // N+1 points/dots below S
for (size_t k = 0; k < N+1; ++k) {
    sZ_dots[k] = sZ - k * sZsectionLength;
}
std::vector<float> lZ_dots(N, 0.0); // N points/dots below L
for (size_t k = 0; k < N; ++k) {
    // // Each point below L is average of two points below S
    lZ_dots[k] = ( sZ_dots[k] + sZ_dots[k+1] ) / 2.0f;
}

for (size_t k = 0; k < N; ++k) {
    Line *zig = new Line();
    zig->setStartDot(sX, sZ_dots[k]);
    zig->setCloseDot(lX, lZ_dots[k]);
    linesContainer.append(zig);

    Line *zag = new Line();
    zag->setStartDot(lX, lZ_dots[k]);
    zag->setCloseDot(sX, sZ_dots[k+1]);
    linesContainer.append(zag);
}            

上面的算法产生的锯齿形曲线很好。但是,我想知道是否有任何更快算法来生成锯齿形交叉线。我想念什么吗?

1 个答案:

答案 0 :(得分:1)

我会这样实现:

struct Line
{
  Line(float x1, float z1, float x2, float z2)
    :
      m_x1(x1),
      m_z1(z1),
      m_x2(x2),
      m_z2(z2)
  {}

  float m_x1;
  float m_z1;
  float m_x2;
  float m_z2;
};

using LineContainer = std::vector<Line>;

LineContainer getZigZag(float lx, float sx, float sz, size_t sectionCount)
{
  assert(lx < sx && sz > 0.0f);

  LineContainer lines;
  auto sectionHeight = sz / sectionCount;
  for (auto i = 0; i < sectionCount; ++i)
  {
    auto sz1 = sz - sectionHeight * i;
    auto sz2 = sz - sectionHeight * (i + 1);
    auto lz = sz1 - (sz1 - sz2) / 2.0f;

    // A section.
    //
    // From S to L
    lines.emplace_back(sx, sz1, lx, lz);
    // From L to S
    lines.emplace_back(lx, lz, sx, sz2);
  }

  return lines;
}

并使用如下功能:

int main()
{
  auto zigzag = getZigZag(1.0f, 2.0f, 4.0f, 2);
  [..]

您可能已经注意到,我用一个循环替换了三个循环,该循环在每次迭代中创建了两行(一个部分)。