hw/examples/example03/Util.hs

84 lines
2.5 KiB
Haskell
Raw Normal View History

2017-11-12 16:10:47 +00:00
module Util where
import Codec.Wavefront
import Control.Monad (sequence)
import SDL (($=))
import qualified Graphics.Rendering.OpenGL as GL
import qualified Graphics.GLUtil as GLU
import qualified Data.Vector as V
2017-11-16 18:48:11 +00:00
import Debug.Trace
2017-11-12 16:10:47 +00:00
data LoadedObject = LoadedObject
{ loTriangles :: [Float]
, loLines :: [Float]
, loPoints :: [Float]
2017-11-18 10:02:55 +00:00
, loLocations :: [Float]
2017-11-12 16:10:47 +00:00
, loTexTri :: Maybe [Float]
2017-11-16 18:48:11 +00:00
} deriving (Show)
2017-11-12 16:10:47 +00:00
loadObj :: WavefrontOBJ -> LoadedObject
loadObj obj =
2017-11-18 10:02:55 +00:00
LoadedObject ts ls ps locs tritex
2017-11-12 16:10:47 +00:00
where
inter = objLocations obj
interTex = objTexCoords obj
faces = map elValue (V.toList $ objFaces obj)
lns = map elValue (V.toList $ objLines obj)
2017-11-18 10:02:55 +00:00
points = map elValue (V.toList $ objPoints obj)
2017-11-12 16:10:47 +00:00
deface (Face a b c []) =
map (\i -> inter V.! (faceLocIndex i -1)) [a, b, c]
deface _ =
error "loadObj: obj with quads encountered"
deline (Line a b) =
map (\i -> inter V.! (lineLocIndex i -1)) [a, b]
depoint (Point i) = inter V.! (i - 1)
tsLocs = concatMap deface faces
lsLocs = concatMap deline lns
2017-11-18 10:02:55 +00:00
psLocs = map depoint points
2017-11-12 16:10:47 +00:00
deLoc (Location x y z w) = [x, y, z, w]
deTex (TexCoord r s _) = [r, s]
ts = concatMap deLoc tsLocs
ls = concatMap deLoc lsLocs
ps = concatMap deLoc psLocs
2017-11-18 10:02:55 +00:00
locs = concatMap deLoc (V.toList inter)
2017-11-12 16:10:47 +00:00
defaceTex :: Face -> Maybe [TexCoord]
defaceTex (Face a b c []) =
mapM
(fmap (\x -> interTex V.! (x - 1)) . faceTexCoordIndex)
[a, b, c]
defaceTex _ =
error "loadObj: obj with quads encountered"
tritex :: Maybe [Float]
tritex = concatMap deTex <$> mftxs
mftxs :: Maybe [TexCoord]
mftxs = fmap concat (mapM defaceTex faces)
-- objLocsToPtr :: WavefrontOBJ -> IO (Ptr Float, Int)
-- objLocsToPtr obj = do
-- let ivs = objLocations obj
-- faces = map elValue $ V.toList $ objFaces obj
-- vs = concatMap
-- (\(Face a b c []) ->
-- map (\i -> ivs V.! ((faceLocIndex i) - 1)) [a, b, c])
-- faces
-- ptr <- newArray $ concatMap (\(Location x y z w) -> [x, y, z, w]) vs
-- return (ptr, length vs)
--
-- objUVsToPtr :: WavefrontOBJ -> IO (Ptr Float, Int)
-- objUVsToPtr obj = do
-- let uvs= V.toList $ objTexCoords obj
-- ptr <- newArray $ concatMap (\(TexCoord r s t) -> [r, s, t]) uvs
-- return (ptr, length uvs)
loadTex :: FilePath -> IO GL.TextureObject
loadTex f = do
t <- either error id <$> GLU.readTexture f
GL.textureFilter GL.Texture2D $= ((GL.Linear', Nothing), GL.Linear')
GLU.texture2DWrap $= (GL.Repeated, GL.ClampToEdge)
return t