简体   繁体   English

将矢量夹紧到最小和最大?

[英]Clamping a vector to a minimum and maximum?

I came accross this: t = Clamp(t/d, 0, 1) but I'm not sure how to perform this operation on a vector. 我来到这里:t = Clamp(t / d,0,1)但我不确定如何在矢量上执行此操作。 What are the steps to clamp a vector if one was writing their own vector implementation? 如果有人正在编写自己的矢量实现,那么钳制矢量的步骤是什么?

Thanks 谢谢

clamp clamping a vector to a minimum and a maximum 钳夹矢量至最小值和最大值

ex: 例如:

pc = # the point you are coloring now
p0 = # start point
p1 = # end point
v = p1 - p0
d = Length(v)
v = Normalize(v) # or Scale(v, 1/d)

v0 = pc - p0

t = Dot(v0, v)
t = Clamp(t/d, 0, 1)

color = (start_color * t) + (end_color * (1 - t))
clamp(vec, lb, ub) == min(max(vec, lb), ub)

edit 编辑

min and max are usually primitive operations on vectors. min和max通常是对向量的原始操作。 For example, if you're using SSE vectors, there are _mm_min_ps and _mm_max_ps intrinsics that turn into MINPS and MAXPS instructions on x86. 例如,如果您正在使用SSE向量,则有_mm_min_ps_mm_max_ps内在函数会转换为x86上的MINPSMAXPS指令。

I think that once you state clearly what you mean you'll find that most of the work is done for you... 我想,一旦你明确说出你的意思,你会发现大部分的工作都是为你完成的......

I'm guessing you want to limit the length of the vector quantity (rather than a vector data structure) to lie within a specified range without changing its direction, no? 我猜你想要限制矢量的长度 (而不是矢量数据结构)在指定的范围内,而不改变它的方向,不是吗?

So: 所以:

if (v.length > max)
   v.setlength(max)
else if (v.length < min)
   v. setlength(min)

where the implementation of length() and setlength() depend on how you have stored your vector. 其中length()setlength()取决于你如何存储向量。


If your vector is stored in (angle,magnitude) form this is nearly trivial. 如果你的矢量以(角度,大小)形式存储,这几乎是微不足道的。 If stored in Cartesian form (ie. (x,y,z) ) you get length from the Pythagorian theorem and setlength should scale each commponent by a factor of desired_length/current_length . 如果以笛卡尔形式(即(x,y,z))存储,则从Pythagorian定理得到length ,并且setlength应该将每个组件缩放一个desired_length/current_length因子。

The easiest answer is when you consider a vector in a spherical coordinate system: {R, φ, θ}. 最简单的答案是在球面坐标系中考虑矢量时:{R,φ,θ}。 φ and θ are already limited to [-π,+π] and [-½π, +½π] anyway. 无论如何,φ和θ已经限于[-π,+π]和[-½π,+ 1 /2π]。 Hence, you only need to clamp the distance from the origin R. 因此,您只需要夹住原点R的距离。

Well, I'd assuming you'd want to clamp each of the coordinates individually. 好吧,我假设你想要分别夹住每个坐标。 So... 所以...

void clamp(const Vector3 &v, const Vector3 &min, const Vector3 &max)
{
    v.x = clamp(v.x, min.x, max.x);
    v.y = clamp(v.y, min.y, max.y);
    v.z = clamp(v.z, min.z, max.z);
}

int clamp(int value, int min, int max)
{
    if (value < min)
    {
        return min;
    }
    else if (value > max)
    {
        return max;
    }

    return value;
}

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM