Ray-casting algorithm: Difference between revisions
Content deleted Content added
added Ursala |
→{{header|Smalltalk}}: ++ R |
||
Line 632: | Line 632: | ||
print ' ]' |
print ' ]' |
||
_convert_fortran_shapes()</lang></div> |
_convert_fortran_shapes()</lang></div> |
||
=={{header|R}}== |
|||
<lang R>point_in_polygon <- function(polygon, p) { |
|||
count <- 0 |
|||
for(side in polygon) { |
|||
if ( ray_intersect_segment(p, side) ) { |
|||
count <- count + 1 |
|||
} |
|||
} |
|||
if ( count %% 2 == 1 ) |
|||
"INSIDE" |
|||
else |
|||
"OUTSIDE" |
|||
} |
|||
ray_intersect_segment <- function(p, side) { |
|||
eps <- 0.0001 |
|||
a <- side$A |
|||
b <- side$B |
|||
if ( a$y > b$y ) { |
|||
a <- side$B |
|||
b <- side$A |
|||
} |
|||
if ( (p$y == a$y) || (p$y == b$y) ) { |
|||
p$y <- p$y + eps |
|||
} |
|||
if ( (p$y < a$y) || (p$y > b$y) ) |
|||
return(FALSE) |
|||
else if ( p$x > max(a$x, b$x) ) |
|||
return(FALSE) |
|||
else { |
|||
if ( p$x < min(a$x, b$x) ) |
|||
return(TRUE) |
|||
else { |
|||
if ( a$x != b$x ) |
|||
m_red <- (b$y - a$y) / (b$x - a$x) |
|||
else |
|||
m_red <- Inf |
|||
if ( a$x != p$x ) |
|||
m_blue <- (p$y - a$y) / (p$x - a$x) |
|||
else |
|||
m_blue <- Inf |
|||
return( m_blue >= m_red ) |
|||
} |
|||
} |
|||
}</lang> |
|||
<lang R>######## utility functions ######### |
|||
point <- function(x,y) list(x=x, y=y) |
|||
# pts = list(p1, p2, ... )... coords |
|||
# segs = list(c(1,2), c(2,1) ...) indices |
|||
createPolygon <- function(pts, segs) { |
|||
pol <- list() |
|||
for(pseg in segs) { |
|||
pol <- c(pol, list(list(A=pts[[pseg[1]]], B=pts[[pseg[2]]]))) |
|||
} |
|||
pol |
|||
}</lang> |
|||
<lang R>#### testing #### |
|||
pts <- list(point(0,0), point(10,0), point(10,10), point(0,10), |
|||
point(2.5,2.5), point(7.5,2.5), point(7.5,7.5), point(2.5,7.5), |
|||
point(0,5), point(10,5), |
|||
point(3,0), point(7,0), point(7,10), point(3,10)) |
|||
polygons <- |
|||
list( |
|||
square = createPolygon(pts, list(c(1,2), c(2,3), c(3,4), c(4,1))), |
|||
squarehole = createPolygon(pts, list(c(1,2), c(2,3), c(3,4), c(4,1), c(5,6), c(6,7), c(7,8), c(8,5))), |
|||
exagon = createPolygon(pts, list(c(11,12), c(12,10), c(10,13), c(13,14), c(14,9), c(9,11))) |
|||
) |
|||
testpoints <- |
|||
list( |
|||
point(5,5), point(5, 8), point(-10, 5), point(0,5), point(10,5), |
|||
point(8,5), point(9.9,9.9) |
|||
) |
|||
for(p in testpoints) { |
|||
for(polysi in 1:length(polygons)) { |
|||
cat(sprintf("point (%lf, %lf) is %s polygon (%s)\n", |
|||
p$x, p$y, point_in_polygon(polygons[[polysi]], p), names(polygons[polysi]))) |
|||
} |
|||
}</lang> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |