Matt W
Matt W

Reputation: 12423

Calculate the angle between a point and a 3D facet

I have a 3D point (x,y,z) and a facet which is defined by three (x,y,z) points. I am trying to calculate the angle between the facet and the point. This is so I can shade the facet appropriately as though a light were moving across it in 3D space.

Hopefully this image gives an idea of what I'm trying to work out. The 3 dots are points in space relative to the facet and have different angles relative to its facing direction. It is this angle that I want to find. If the dots were points of light, the black dot would provide the brightest light, the blue would be about 50% brightness and the green would be very dark. enter image description here

While I can calculate the magnitude, length and dot product of any two points, I am at a loss as to how to calculate the angle between the facet itself and the point.

I would like to know how to calculate whether the point is above or level with the facet, i.e.: the angle of the point relative to the facet.

The code I have so far is:

-- Get length of 2D or 3D vector
local function vector2d3dLength( vector )
    return math.sqrt( vector.x*vector.x + vector.y*vector.y + (vector.z or 0)*(vector.z or 0) )
end

-- Normalise 2D or 3D vector
local function normalise2d3dVector( vector )
    local len = vector2d3dLength( vector )

    if (len == 0) then
        return vector
    end

    local normalised = { x=vector.x/len, y=vector.y/len }

    if (vector.z) then
        normalised.z = vector.z/len
    end

    return normalised
end

local function crossProduct3d( a, b )
    return { x=a.y*b.z − a.z*b.y, y=a.z*b.x − a.x*b.z, z=a.x*b.y − a.y*b.x }
end

local function dotProduct3d( a, b )
    return a.x*b.x + a.y*b.y + a.z*b.z
end

-- subtract vector b from vector a
local function subtract_vectors( a, b )
    local sub = { x=a.x-b.x, y=a.y-b.y }

    if (a.z ~= nil and b.z ~= nil) then
        sub.z = a.z-b.z
    end

    return sub
end

Upvotes: 0

Views: 306

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23757

-- black/blue/green point
local lightsource = { x = 111, y = 112, z = 113 }    

-- 3 points on the facet, first point is the center
local facet = {{ x = 1, y = 2, z = 3 },  
               { x = 4, y = 5, z = 6 },
               { x = 7, y = 8, z = 9 }}

local facet_normal = normalise2d3dVector(crossProduct3d(
   subtract_vectors(facet[2], facet[1]),
   subtract_vectors(facet[3], facet[1])))

local direction_to_lightsource = 
   normalise2d3dVector(subtract_vectors(lightsource, facet[1]))

local cos_angle = dotProduct3d( direction_to_lightsource, facet_normal )
-- cos_angle may be negative, it depends on whether facet points are CW or CCW

local facet_brightness = cos_angle * max_brightness

Upvotes: 1

Related Questions