C语言 如何使用按位运算轻松生成长方体中的点?

wko9yo5t  于 2023-02-11  发布在  其他
关注(0)|答案(1)|浏览(117)

假设我有一个长方体,它有一个中心(Vec3float[3])、宽度、高度和深度,我想给一个Vec3[8]数组赋值,这个数组包含长方体的8个顶点,我想在一个嵌套的for循环中完成,为了在for循环中完成,我必须使用下面的公式:

  1. points[n][dim] = cub.center[dim] (+ or -) dimensions[dim]/2;
  2. //n is nth point, dim is the dimension of the point: 0 = x, 1 = y, 2 = z
  3. //dimensions is {cub.width, cub.height, cub.depth}

例如,如果一个长方体面向您,您需要左上角背面点的x坐标,则等效于:

  1. points[0][0] = cub.center[0] - dimensions[0]/2;

但是对于右上方:

  1. points[1][0] = cub.center[0] + dimensions[0]/2;

我们可以将其抽象为:

  1. int coefficient = (cond)?1:-1;
  2. points[n][dim] = cub.center[dim] + coefficient * dimensions[dim] / 2;

如果我确定像这样排列这些点:

  1. [0] = back top left
  2. [1] = back top right
  3. [2] = back bottom left
  4. [3] = back bottom right
  5. [4] = front top left
  6. [5] = front top right
  7. [6] = front bottom left
  8. [7] = front bottom right

它们的系数为:

  1. [0] = back top left | - - -
  2. [1] = back top right | - - +
  3. [2] = back bottom left | - + -
  4. [3] = back bottom right | - + +
  5. [4] = front top left | + - -
  6. [5] = front top right | + - +
  7. [6] = front bottom left | + + -
  8. [7] = front bottom right | + + +

这类似于二进制,但我不熟悉位运算符,需要帮助来确定cond使用的是n和dim。cond = dim'th binary digit of n == 1任何帮助以及使用for循环分配8个点的任何更简单的方法都将受到赞赏。

w80xi6nr

w80xi6nr1#

  1. int coefficient = (n & ( 1 << dim)) ? 1:-1;

假设<0,n,7><0,dim,2>

相关问题