Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Data.List
- import Data.Function
- -- Define a data type to represent 2D points
- data Point = Point { x :: Double, y :: Double } deriving (Eq, Show)
- -- Define a data type for representing a light source
- data Light = Light { position :: Point, intensity :: Double } deriving Show
- -- Define a data type for representing obstacles (assumed to be square)
- data Obstacle = Obstacle { center :: Point, size :: Double } deriving Show
- -- Function to simulate lighting and shadows
- simulateLight :: Point -> Double -> [Obstacle] -> String
- simulateLight lightPos lightIntensity obstacles =
- let gridSize = 20 -- Size of the 2D grid
- -- Create a grid of points
- grid = [[Point (fromIntegral x) (fromIntegral y) | x <- [0..gridSize-1]] | y <- [0..gridSize-1]]
- -- Compute the illumination status for each point on the grid
- illuminatedGrid = map (map (illuminate lightPos lightIntensity obstacles)) grid
- in unlines $ map (concatMap cellChar) illuminatedGrid
- -- Function to convert illumination status to ASCII characters
- cellChar :: Bool -> String
- cellChar True = " " -- Empty space (illuminated)
- cellChar False = "#" -- Hash symbol (in shadow)
- -- Function to determine if a point is illuminated or in shadow
- illuminate :: Point -> Double -> [Obstacle] -> Point -> Bool
- illuminate lightPos lightIntensity obstacles point =
- let ray = Ray lightPos point
- -- Find intersections between the ray and obstacles
- intersections = filter (isIntersection ray) obstacles
- distanceToPoint = distance lightPos point
- -- Check if the point is blocked by any obstacle
- blocked = any (\obs -> distanceToPoint > distance (center obs) point) intersections
- in not blocked
- -- Define a data type for representing a ray
- data Ray = Ray { origin :: Point, destination :: Point } deriving Show
- -- Function to check if a ray intersects with an obstacle
- isIntersection :: Ray -> Obstacle -> Bool
- isIntersection ray obs =
- let d = destination ray `sub` origin ray
- f = origin ray `sub` center obs
- a = d `dot` d
- b = 2 * (f `dot` d)
- c = (f `dot` f) - (size obs) ** 2
- discriminant = b * b - 4 * a * c
- in discriminant >= 0
- -- Function to subtract two points
- sub :: Point -> Point -> Point
- sub p1 p2 = Point (x p1 - x p2) (y p1 - y p2)
- -- Function to compute the dot product of two points
- dot :: Point -> Point -> Double
- dot p1 p2 = x p1 * x p2 + y p1 * y p2
- -- Function to compute the distance between two points
- distance :: Point -> Point -> Double
- distance p1 p2 = sqrt ((x p1 - x p2) ** 2 + (y p1 - y p2) ** 2)
- -- Main function to run the simulation
- main :: IO ()
- main = do
- let light = Light (Point 10.0 10.0) 1.0
- obstacles = [Obstacle (Point 5.0 5.0) 2.0, Obstacle (Point 15.0 15.0) 2.0]
- result = simulateLight (position light) (intensity light) obstacles
- putStrLn result
Advertisement
Add Comment
Please, Sign In to add comment