Strategy to render shadows

BlitzMax Forums/BlitzMax Programming/Strategy to render shadows

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

I've knocked up an example of what I'm talking about :-

It uses a depth test (so the shadow pixel doesn't overwrite one already there) and an alpha func which prevents pixels being written if they have an alpha below a .25 threshold.

SuperStrict


Type TBall
	Global i:Int = 0
	Field _r:Int, _g:Int, _b:Int
	Field _x:Float, _y:Float
	
	Method Update()
		_y :+ (10 * Sin(i + _x))
		i:+1
	EndMethod
	
	Function Create:TBall(x:Float, y:Float, r:Int, g:Int, b:Int)
		Local ball:TBall = New TBall
		ball._x = x
		ball._y = y
		ball._r = r
		ball._g = g
		ball._b = b
		Return ball
	EndFunction
EndType


SetGraphicsDriver GLMax2DDriver()
Graphics 800,600

' Make image to draw with
Global image:TImage = CreateImage( 100,100 )
Cls
SetColor 255,255,255
DrawOval 50,50,50,50
GrabImage image,0,0


Global ballList:TList = New TList
Global shadowMode:Int = 0

' Make some objects to render
ballList.AddLast( TBall.Create( 30,150, 255,0,0 ) )
ballList.AddLast( TBall.Create( 50,150, 0,255,0 ) )
ballList.AddLast( TBall.Create( 70,150, 0,0,255 ) )
ballList.AddLast( TBall.Create( 90,150, 255,0,255 ) )
ballList.AddLast( TBall.Create( 110,150, 255,255,0 ) )


Function RenderBackground()
	For Local i:Int = 0 To GraphicsHeight() Step 10
		SetColor Rand(100,155), Rand(100,155), Rand(100,155)
		DrawRect 0, i, GraphicsWidth(), i + (GraphicsHeight()/10)
	Next
EndFunction

Function RenderObjectDepthTestShadows()
	' Draw shadows
	glEnable GL_DEPTH_TEST
	SetColor 0,0,0
	SetAlpha 0.3
	glEnable GL_ALPHA_TEST
	glAlphaFunc GL_GREATER, 0.25

	For Local ball:TBall = EachIn ballList
		DrawImage image, ball._x + 20, ball._y + 20
	Next
	
	glDisable GL_ALPHA_TEST
	glDisable GL_DEPTH_TEST
EndFunction

Function RenderObjectShadowsNoDepthTest()
	' Draw shadows
	SetColor 0,0,0
	SetAlpha 0.3
	For Local ball:TBall = EachIn ballList
		DrawImage image, ball._x + 20, ball._y + 20
	Next
EndFunction

Function RenderObjects()
	SetAlpha 1.0
	
	For Local ball:TBall = EachIn ballList
		SetColor ball._r, ball._g, ball._b
		DrawImage image, ball._x, ball._y
		If Not KeyDown( KEY_SPACE )
			ball.Update()
		EndIf
	Next
EndFunction


SetBlend ALPHABLEND
glClearColor 255, 255,255,255
While Not KeyHit( KEY_ESCAPE )
	glClear GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT
	RenderBackground()
	
	If shadowMode
		RenderObjectDepthTestShadows()
	Else
		RenderObjectShadowsNoDepthTest()
	EndIf
	
	RenderObjects()	
	
	SetColor 255,255,255
	DrawText "DepthTest/AlphaTest shadow rendering - hold SPACE to pause", 100, 10
	DrawText "Press M to toggle Depth/Alpha shadow mode on/off", 100, 30
	Flip
	
	If KeyHit( KEY_M )	
		shadowMode = 1-shadowMode
	EndIf
Wend