How do I get rid of the delay when my program ends

BlitzMax Forums/BlitzMax Programming/How do I get rid of the delay when my program ends

When using OpenGL there's no delay when I end my program, but when I use Direct3D, there's a two second delay when the program ends before it goes back to the desktop when running in fullscreen mode.

Has anyone figured out how to reduce this delay? I don't see why there should be any delay at all.

There's no noticeable difference in a test I just ran.
How about providing some example code which shows the problem?

I discovered something odd just now...

If I run the game fullscreen initially, it loads fast, but takes forever to quit.

Also, if I start the game in fullscreen, but switch to windowed mode, it takes forever to make the switch. But it will then toggle back and forth quickly and exit quickly.

However, if I run the game in a window initially, it loads fast, and it exits fast.

And finally, if I run the game in a window initially, then toggle to fullscreen, it takes forever to switch to fullscreen, but once fullscreen it will exit fast and toggle back and forth between windowed and fullscreen fast.

How about providing some example code which shows the problem?


SuperStrict

Import MaxGUI.MaxGUI 
Import MaxGUI.Win32MaxGUI 

' Includes:
	
	
' Globals:

	' Use Time% for game timing.  Time% is paused when the game is minimized and starts at 0, so it will not roll over for 23 days. 

	Global FPS%
	Global State%
	
	' Timing
	
		Global Time%, Time_Delta%, Time_Delta_Sec#, Last_Time_Delta%, Last_Time_Delta_Sec#
		Global System_Time%, Last_System_Time%

	' Frame smoothing
		
		Global Frames% = 1				' Initially the FrameTime array will only have one frame's time stored in it, but the array and this count of the number of values in it will be 
		Global FrameTime%[Frames]		' resized each frame to have more or less frames depending on the current framerate.
		Global Max_FrameTime%
		Global Frame%
		Global FrameDelay%

	Global Loop%
	Global IMG_Dust:TImage[100]

					
' Main:
		
	' Set the video mode.
	
		' Currently, we are setting the video mode to that of the desktop, and running the game fullscreen.  But it may be desirable to run the game at some other resolution so it can run
		' in a window, or run faster.  The scaling code will work no matter what resolution is used here, but it would not be desirable to use an aspect ratio for windowed mode which is
		' different from the 16:10 aspect ratio of the game, because there would be uneccessary letterboxing displayed.
	
		App.Create("Attack of the Alien Space Beetles!", ClientWidth(Desktop()), ClientHeight(Desktop()), 0, True, False)
		
		For Loop = 1 To 1
			IMG_Dust[Loop] = LoadImage("gfx\background\dust2.jpg")
		Next
			
	' Scale the graphics onscreen and display them letterboxed if needed.
	'	ProjectionMatrix.SetLetterBox(800, 500)

	SeedRnd MilliSecs() 
	System_Time = MilliSecs()
					
	Repeat
	
		Repeat 
			Last_System_Time = System_Time									' Store start time of last frame.
			System_Time 	 = MilliSecs()										' Get the current system time.  
			Time_Delta       = System_Time - Last_System_Time						' Calculate how long last frame took to render, in milliseconds.
			Time_Delta_Sec#  = Float(Time_Delta)/1000.0							' Convert frame time to seconds.
		Until (Time_Delta > 0) And (Time_Delta < 250)							' Handle unnaturally long pauses between frames gracefully.
								
		EventHandler()														' Process window events.
		
		If Not AppSuspended()
									
			Time = Time + Time_Delta											' Calculate current game time.  
			'Sprite.SetTimeStep(Time_Delta)									' Set the timestep for the sprites this frame.
									
			If App.Windowed Then ActivateGadget App.Canvas						' If windowed, make sure canvas stays active, or else polled input will go elsewhere.		

			UpdateMouse()													' Get mouse input.
			'StateSystem.Update()											' Update game.
			
			'Sprite.Update() 												' Animate sprites, do physics.

			SetClsColor 0, 0, 0												' Clear screen and draw sprites.
			Cls
			
			'Sprite.DrawAll()												' Draw the sprites.

			' Draw letterbox.
				ProjectionMatrix.DrawLetterbox()
									
			If KeyHit(KEY_F) Then App.ToggleFullscreen()							' Toggle fullscreen/window mode when user presses F.  (May need to disable this during user input.)
			If KeyHit(KEY_ESCAPE) Then End 
						
			'Last_Time_Delta      = Time_Delta									' Store timestep for this frame so we can reference it next frame.
			'Last_Time_Delta_Sec# = Time_Delta_Sec#

			' Smooth out framerate.
				
				If Not KeyDown(KEY_S)
				
					' Find the longest amount of time a frame took to render over the last few frames.	
								
						Max_FrameTime = 0
						For Frame = 0 To Frames-1
							If FrameTime[Frame] > Max_FrameTime Then Max_FrameTime = FrameTime[Frame]
						Next
					
					' Shift all times toward the end of the array by one to free up the first slot for a new time.
						
						For Frame = Frames-1 To 1 Step -1
							FrameTime[Frame] = FrameTime[Frame-1]
						Next					
					
					' Resize the array to have 1/8 as many elements as we are rendering frames per second.
					
						' The reason we do this is so that no matter what the framerate is, the system will adjust to big changes in framerate within 1/8
						' of a second.  The response time is only a concern so far as the system would render at a lower framerate for longer than it
						' really needs to.
					
						If Max_FrameTime > 0 Then Frames = Floor((1000.0 / Max_FrameTime) / 2.0)
						If Frames = 0 Then Frames = 1
										
						FrameTime = FrameTime[..Frames]						
					
					' Calculate how long this frame took to render.
						Time_Delta = MilliSecs()-System_Time
					
					' Add this frame's render time to the start of the array.
						FrameTime[0] = Time_Delta
				
					' Delay this frame to make it last as long as the longest in our array of frame times.
						
						If Max_FrameTime < 70
							While Time_Delta < Max_FrameTime
								Delay 0 
								Time_Delta = MilliSecs()-System_Time
							Wend
						EndIf
								
				EndIf

			' Draw framerate if user presses tab.
				If KeyDown(KEY_TAB) 
					FPS = 1000.0 / Float(Time_Delta)
					SetScale 1, 1
					DrawText FPS, 16, 16*1
					'DrawText "Sprites = "        + Sprite.SpriteList.Count(), 16, 16*2
					'DrawText "FruitSpawned   = " + Powerup.FruitSpawned,      16, 16*4
					'DrawText "FruitCollected = " + Powerup.FruitCollected,    16, 16*5
				EndIf

			' Flip new frame into view.
				Flip 0
					
		EndIf 
		
					
	Forever



' ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
' This type allows you to make games that can run at any resolution.
' ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Type ProjectionMatrix
	
	Global _Width%				' The size of the screen, in BlitzMax coordinates. 
	Global _Height%				' Normally BlitzMax coordinates correspond 1:1 with pixels on the screen, but when you adjust the projection matrix, that relationship changes.
	
	Global _VirtualWidth%		' The size of the visible region in which gameplay takes place.  The area inside the letterbox.
	Global _VirtualHeight%


	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	' This function sets the scale of the projection matrix.
	'
	' If you simply wish your game to stretch vertically and horizontally to match the current resolution, and fill the screen, call this function with your desired "virtual" resolution.
	' Ie, if you want to build your game around an 800x600 resolution, then set Width and Height to 800,600.  If the game is then run at 1920x1200, it will be squashed vertically.
	'
	' If you want letterboxing however, call InitLetterbox() and then DrawLetterBox() every frame just before you flip.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		Function SetScale(Width%, Height%)
			
			_Width  = Width
			_Height = Height
			
			_VirtualWidth  = Width
			_VirtualHeight = Height
				
			?Win32

				Local D3D7Driver:TD3D7Max2DDriver = TD3D7Max2DDriver(_max2dDriver)
    
				If D3D7Driver
			
					Local Matrix#[] = [2.0/Width, 0.0, 0.0, 0.0,..
   		    	    			      0.0, -2.0/Height, 0.0, 0.0,..
       		    	      			  0.0, 0.0, 1.0, 0.0,..
           		    	  			  -1-(1.0/Width), 1+(1.0/Height), 1.0, 1.0]
    
				    D3D7Driver.device.SetTransform(D3DTS_PROJECTION, Matrix)

				Else
			? 
					' If on platform other than Win32, or using OpenGL run this code.
		
					glMatrixMode(GL_PROJECTION)
					glLoadIdentity()
    
					glortho(0, Width, Height, 0, 0, 1)
    
					glMatrixMode(GL_MODELVIEW)
					glLoadIdentity()
		
			?Win32

				EndIf
			?
		
		End Function


	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	' This function initializes the letterbox.
	'
	' Call it with the virtual resolution you want to use for your game after you have set the graphics mode, and then DrawLetterBox() every frame just before you flip.
	'
	' These functions will automatically handle both letterboxing on screens which are too tall, and pillarboxing on screens which are too wide.  So if you design your game for 800x600,
	' then InitLetterbox() will squash things horizontally to maintain the proper aspect ratio, and DrawLetterbox() will add black bars to the sides of the display for you.
	'
	' 
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		Function SetLetterbox(Width%, Height%)	

			Local NewWidth#, NewHeight#
						
			NewWidth#  = Width
			NewHeight# = Float(GraphicsHeight()) / (Float(GraphicsWidth()) / Float(Width))
		
			' If screen is wider than the desired apsect ratio...

				If NewHeight# < Height
				
					' Use pillarboxing instead of letterboxing.
										
						NewHeight# = Height
						NewWidth#  = Float(GraphicsWidth()) / (Float(GraphicsHeight())/Float(Height)) 	' Commenting this out will squash the game vertically on screens which are too wide.
																										' But without additional changes, black bars will still be drawn.						
				EndIf
			
			' Adjust the scale of the projection matrix to achieve the desired result.
				ProjectionMatrix.SetScale(NewWidth#, NewHeight#)
		
			' Store the size of the visible game region.
				_VirtualWidth  = Width
				_VirtualHeight = Height
	
		End Function 
		
		
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	' This function draws black bars over the portions of the screen which are outside the gameplay area.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		Function DrawLetterbox()
		
			Local Size%
			
			RenderState.Push()	
			
			If _VirtualHeight < _Height
				
				' Draw Letterbox.
				
					Size = (_Height-_VirtualHeight) / 2
				
					SetColor(0,0,0) 
							
					DrawRect(0,            0, _Width, Size)
					DrawRect(0, _Height-Size, _Width, Size)
					
			Else
				
				' Draw pillarbox.

					Size = (_Width-_VirtualWidth) / 2
				
					SetColor(0,0,0) 
							
					DrawRect(          0, 0, Size, _Height)
					DrawRect(_Width-Size, 0, Size, _Height)
				
			EndIf			
			
			RenderState.Pop() 	' Render push and pop simply resets the color and other display properties to whatever they were beforehand.  These two functions are in the code archives.
			
		End Function


	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	' These functions return the virtual width and height of the usuable region of the screen, inside any letterboxing.
	'
	' Basically, these functions are equivalent to GraphicsWidth() and GraphicsHeight() when using a projection matrix where coordinates don't match up 1:1 to pixels
	' and/or letterboxing is being used.
	'
	' These functions will not return useful values until either ProjectionMatrix.SetScale() is called, or ProjectonMatrix.SetLetterbox() is called!
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

		Function Width#()
			Return _VirtualWidth
		End Function
		
		Function Height#()
			Return _VirtualHeight
		End Function
		
	
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	' These functions tell you where the center of the screen is when using letterboxing.  
	'
	' Note that they do not calculate this using the width and height of the visible area of the screen, but rather, the size of the whole screen including the letterboxed regions.
	' This is important, because if you draw objects using the size of the visible region only, they will be higher on the screen than they should be, or more to the left.
	'
	' In my games, what I do is create a pivot called Origin, and place it in the center of the screen, and attach all my sprites to that, so the only time I need to worry about where
	' the center of the screen really is is when I position that pivot initially. 
	'
	' Then when I've done that, the top of the screen is at -ProjectionMatrix.Height#()/2, half the height I passed to SetLetterbox(), and so on.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		
		Function CenterX#()
			Return _Width/2
		End Function
			
		Function CenterY#()
			Return _Height/2
		End Function
				
		
End Type
	
	

Const DEFAULT_IMAGE_FLAGS% = MIPMAPPEDIMAGE|FILTEREDIMAGE  ' BlitzMax defaults to MASKEDIMAGE|MIPMAPPEDIMAGE|FILTEREDIMAGE.

 
Type App

	Global Name$
	
	Global Width%
	Global Height%
	Global Depth%

	Global Window:TGadget
	Global Canvas:TGadget
	Global Panel:TGadget
	
	Global TG_FullScreen:TGraphics
	Global TG_Canvas:TGraphics
	
	Global Windowed%


	' -------------------------------------------------------------------------------------------------------------------------------------------------------
	' This function creates the game window, and sets up the graphics objects for windowed and fullscreen modes. 
	' -------------------------------------------------------------------------------------------------------------------------------------------------------

		Function Create(AppName$, AppWidth%, AppHeight%, AppDepth%=0, Fullscreen%=False, UseGL%=False)
	
			Local X%, Y%	
			
			' If we should use OpenGL on all platforms, then enable the openGL driver.
				If UseGL% Then SetGraphicsDriver GLMax2DDriver()
			
			' Warn programmer if the game is running in debug mode so they don't wonder why game is running choppy.
				DebugLog("WARNING: Game running debug mode - Performance will be reduced!")
									
			' Store application settings.
				Name$  = AppName$
				Width  = AppWidth
				Height = AppHeight	
				Depth  = AppDepth
				
			' If Depth is 0, try to find a suitable fullscreen bit depth.
			
				If Depth = 0
				
					If GraphicsModeExists(Width, Height, 16) Then Depth = 16
					If GraphicsModeExists(Width, Height, 24) Then Depth = 24
					If GraphicsModeExists(Width, Height, 32) Then Depth = 32
				
				EndIf		
					
			' Create a window in the center of the screen.
			' ClientWidth/Height is used because GadgetWidth/Height returns the entire width of the desktop in dual screen setups.
		
				X = ClientWidth(Desktop())/2  - Width/2
				Y = ClientHeight(Desktop())/2 - Height/2

				Window = CreateWindow(Name$, X, Y, Width, Height, Null, WINDOW_TITLEBAR|WINDOW_RESIZABLE|WINDOW_CLIENTCOORDS|WINDOW_HIDDEN)
				SetMinWindowSize(Window, GadgetWidth(Window), GadgetHeight(Window))
								
			' Create a panel in the window, drawn behind the canvas, which fills the empty space around the gameplay area when the window is maximized.
				
				Panel = CreatePanel(0, 0, Width, Height, Window)
				
					SetPanelColor(Panel, 0, 0, 0)
					SetGadgetLayout(Panel, EDGE_ALIGNED, EDGE_ALIGNED, EDGE_ALIGNED, EDGE_ALIGNED)
							
			' Set game to windowed or fullscreen as desired.
				Select Fullscreen
					Case False SetWindowed()
					Case True  SetFullscreen()
				End Select
												
		End Function
		

	' -------------------------------------------------------------------------------------------------------------------------------------------------------
	' This function toggles between fullscreen or windowed mode, choosing the opposite of whichever is currently enabled.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------
	
		Function ToggleFullscreen()
		
			Select Windowed
				Case False SetWindowed()
				Case True  If (Depth <> 0) Then SetFullscreen()
			End Select
			
		End Function

	' -------------------------------------------------------------------------------------------------------------------------------------------------------
	' This function puts the application in windowed mode.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------
		
		Function SetWindowed()
		
			' End fullscreen mode if enabled.
				
				If TG_Fullscreen <> Null
					CloseGraphics TG_Fullscreen
					TG_Fullscreen = Null 
				EndIf	
			
			' Create a canvas.
											
				If Canvas = Null 
					Canvas    = CreateCanvas(ClientWidth(Window)/2-Width/2, ClientHeight(Window)/2-Height/2, Width, Height, Panel)
					TG_Canvas = CanvasGraphics(Canvas)
				EndIf	
																			
				If Canvas = Null    Then RuntimeError("Error in Application.SetWindowed() : Could not create canvas!")															
				If TG_Canvas = Null Then RuntimeError("Error in Application.SetWindowed() : Could not get canvas graphics context!")
				
				SetGraphics TG_Canvas
				
				ShowGadget Window
				ActivateGadget Canvas
			
			' Record that windowed mode is enabled.
				Windowed = True
							
			' Canvas must be activated for input or else game will make user click on canvas before any polled keyboard input is returned.
				EnablePolledInput()			
			
			' Show mouse if mouse is currently supposed to be visible.
				If MouseVisible Then ShowMouse(True)					
			
			' Set the blending mode to alpha.
				SetBlend(ALPHABLEND)
				
			' Set mask color to magenta so black pixels are not made transparent when images without an alpha mask are loaded.
				SetMaskColor(255, 0, 255)

			' Set midhandle so images are loaded properly.
				AutoMidHandle True
			
			' Set image flags.
				AutoImageFlags(DEFAULT_IMAGE_FLAGS)
								
			' Buffer sprite images in video memory.	
			'	Sprite.BufferImages()									

			' Scale the graphics onscreen and display them letterboxed if needed.
				ProjectionMatrix.SetLetterBox(800, 500)
				
		End Function


	' -------------------------------------------------------------------------------------------------------------------------------------------------------
	' This method sets the application to fullscreen mode, unless no fullscreen mode in the desired resolution exists.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------

		Function SetFullscreen()
			
			' If no fullscreen mode is available, set windowed mode instead.
				If Depth = 0
					DebugLog("Error in Application.SetFullscreen() : Depth = 0.  Could not set full screen mode!") 
					SetWindowed()
					Return
				EndIf
			
			' Hide window, free canvas.			
				HideGadget Window
				
				If Canvas <> Null 

					'CloseGraphics(TG_Canvas) 
																		
					FreeGadget Canvas
					
					Canvas    = Null
					TG_Canvas = Null
										
				EndIf
														
			' Set drawing operations to fullscreen.
				If TG_Fullscreen = Null Then TG_Fullscreen = Graphics(Width, Height, Depth)
				
			' If the attempt to set a fullscreen mode fails, put us back in windowed mode. 
				If TG_Fullscreen = Null 
					DebugLog("Error in Application.SetFullscreen() : TG_Fullscreen = Null.  Could not set full screen mode!") 
					SetWindowed()
					Return
				EndIf

			' Record that fullscreen is enabled.
				Windowed = False

			' Show mouse if mouse is currently supposed to be visible.
				If MouseVisible Then ShowMouse(True)
				
			' Set the blending mode to alpha.		
				SetBlend(ALPHABLEND)

			' Set mask color to magenta so black pixels are not made transparent when images without an alpha mask are loaded.
				SetMaskColor(255, 0, 255)
				
			' Set midhandle so images are loaded properly.
				AutoMidHandle True

			' Set image flags.
				AutoImageFlags(DEFAULT_IMAGE_FLAGS) 
				
			' Buffer sprite images in video memory.	
			'	Sprite.BufferImages()									

			' Scale the graphics onscreen and display them letterboxed if needed.
				ProjectionMatrix.SetLetterBox(800, 500)
																		
		End Function

				
End Type						


' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' These functions override the regular image loading functions so that we can display an error when an image is missing. 
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

	Function LoadImage:TImage(Url:Object, Flags%=-1, ReturnNull%=False)
	
		Local Image:TImage
					
		Image = Brl.Max2D.LoadImage(Url, Flags)
		
		If Image = Null 
			If ReturnNull  
				Return Null
			Else	
				RuntimeError("The following image failed to load: '" + String(Url) + "'.  Please reinstall the game.")
			EndIf
		EndIf
		
		' Buffer image in video ram.
			DrawImage Image, App.Width, App.Height
		
		'LoadScreen.Update(Url)
		
		Return Image
		
	End Function
	

	Function LoadAnimImage:TImage(Url:Object, Cell_Width%, Cell_Height%, First_Cell%, Cell_Count%, Flags%=-1, ReturnNull%=False)
	
		Local Image:TImage
		Local Frame%

		Image = Brl.Max2D.LoadAnimImage(Url, Cell_Width, Cell_Height, First_Cell, Cell_Count, Flags)
		
		If Image = Null 
			If ReturnNull  
				Return Null
			Else	
				RuntimeError("The following image failed to load: '" + String(Url) + "'.  Please reinstall the game.")
			EndIf
		EndIf
		
		' Buffer image in video ram.
			For Frame = First_Cell To First_Cell+(Cell_Count-1)
				DrawImage Image, App.Width, App.Height, Frame
			Next  
		
		'LoadScreen.Update(Url)
		
		Return Image
		
	End Function


	Function LoadPixmap:TPixmap(Url:Object, ReturnNull%=False)
	
		Local Pixmap:TPixmap
					
		Pixmap = Brl.Pixmap.LoadPixmap(Url)
		
		If Pixmap = Null 
			If ReturnNull  
				Return Null
			Else	
				RuntimeError("The following image failed to load: '" + String(Url) + "'.  Please reinstall the game.")
			EndIf
		EndIf
		
		'LoadScreen.Update(Url)
		
		Return Pixmap
		
	End Function		


' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' This function overrides the standard RuntimeError function which does not work properly.  (Assert also does not work.)
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

	Function RuntimeError(Error$)
		EndGraphics
		DebugLog(Error$)
		Notify(Error$, True)
		End
	End Function
	
	
' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' This function oveerides the standard Flip() function with a lag fix for DirectX.
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

	' No longer needed in latest version of BlitzMax.

	'Function Flip(Sync%=-1)
		
		'Brl.Graphics.Flip Sync
		
		'?Win32
		'	If TD3D7Max2DDriver(_max2dDriver)
		'		Local sdesc:DDSurfaceDesc2 = New DDSurfaceDesc2
		'		sdesc.dwSize = SizeOf(sdesc)
		'		Local res:Int = PrimaryDevice.backbuffer.Lock(Null,sdesc,DDLOCK_WAIT|DDLOCK_READONLY,Null)
		'		PrimaryDevice.backbuffer.unlock(Null)
		'	EndIf
		'?
		
	'End Function


' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' These functions override the standard mouse visibility functions so that we can keep track of the mouse visible state.
'
' For ShowMouse:
'
' If Force% is False, then the mouse will not be shown if the current state indicates it is visible.  This is to avoid mouse flicker which is caused by
' showing the mouse over and over.
'
' If Force% is True, the mouse is shown regardless of what state MouseVisible indicates it is in.  This is used during fullscreen/window mode switches where
' the mouse is hidden by the system automatically.
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

	Global MouseDown_Left%, MouseDown_Right%, MouseDown_Middle%
	Global MouseHit_Left%, MouseHit_Right%, MouseHit_Middle%
	Global Mouse_X#, Mouse_Y#
	Global Old_Mouse_X# = MouseX()
	Global Old_Mouse_Y# = MouseY()
	Global Mouse_Speed_X#, Mouse_Speed_Y#
	Global MouseVisible% = True
	Global Mouse_ForceRecenter% 


	Function ShowMouse(Force%=False)
		If (MouseVisible = False) Or (Force = True)
			MouseVisible = True
			Brl.System.ShowMouse()
		EndIf
	End Function

	
	Function HideMouse()
		MouseVisible = False
		Brl.System.HideMouse()	
	End Function
	
	
	Function AutoRecenterMouse(Recenter%=False) 
		
		Mouse_ForceRecenter = Recenter
		
		Select Recenter
		
			Case True  
				HideMouse()
				MoveMouse App.Width/2, App.Height/2
				
			Case False 
				ShowMouse()
			
		End Select
		
	End Function
	
	
' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' This function gets the mouse input for this frame.
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

	Function UpdateMouse()								
		
		Const SAFEZONE_RADIUS# = 100		
				
		Mouse_X# = MouseX()
		Mouse_Y# = MouseY()
			
		Mouse_Speed_X# = Mouse_X# - Old_Mouse_X#
		Mouse_Speed_Y# = Mouse_Y# - Old_Mouse_Y#

		MouseDown_Left   = MouseDown(1)
		MouseDown_Right  = MouseDown(2)
		MouseDown_Middle = MouseDown(3)	
				
		MouseHit_Left    = MouseHit(1)
		MouseHit_Right   = MouseHit(2)
		MouseHit_Middle  = MouseHit(3)
		
		' Recenter mouse if desired.
		' Recentering the mouse allows Mouse_Speed to work consistently.

			If Mouse_ForceRecenter 
				
				If (Abs(App.Width/2 - Mouse_X#) > SAFEZONE_RADIUS#) Or (Abs(App.Height/2 - Mouse_Y#) > SAFEZONE_RADIUS#)
			
					MoveMouse App.Width/2, App.Height/2
				
					Old_Mouse_X# = App.Width/2  - Mouse_Speed_X#
					Old_Mouse_Y# = App.Height/2 - Mouse_Speed_Y#
					
				Else
				
					Old_Mouse_X# = Mouse_X#
					Old_Mouse_Y# = Mouse_Y#
									
				EndIf			
				
			EndIf
	
	End Function


' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' This function checks for events in the event queue and acts upon them.
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

	Function EventHandler()

		MouseHit_Left   = False
		MouseHit_Right  = False
		MouseHit_Middle = False

		While PollEvent() <> 0
		
			'DebugLog("EventID: " + EventID())
			'If Scoreboard.TEXT_AngerMeter <> Null 
			'	If EventID() <= 258 Then Scoreboard.TEXT_AngerMeter.Set(EventID()) 
			'EndIf
			
			Select EventID()
					
				Case EVENT_APPSUSPEND 		' Application suspended. Triggered when window is minimized.
					
					' Pause music.
'						If Sound.MusicChannel <> Null Then Sound.MusicChannel.SetPaused(True)
				
				
				Case EVENT_APPRESUME  		' Application resumed.
				
					' Resume music.
'						If Sound.MusicChannel <> Null Then Sound.MusicChannel.SetPaused(False)
				
				 
				Case EVENT_APPTERMINATE 	' Application wants to terminate. 
				Case EVENT_KEYDOWN 			' Key pressed. Event data contains keycode. 
				Case EVENT_KEYUP 			' Key released. Event data contains keycode. 
				Case EVENT_KEYCHAR 			' Key character. Event data contains unicode value. 
				
				Case EVENT_MOUSEDOWN 		' Mouse button pressed. Event data contains mouse button code.
				
					Select EventData()
					
						Case 1 
							MouseDown_Left   = True
							MouseHit_Left    = True
							
						Case 2 
							MouseDown_Right  = True
							MouseHit_Right   = True
							
						Case 3 
							MouseDown_Middle = True
							MouseHit_Right   = True
							
					End Select
					
					
				Case EVENT_MOUSEUP 			' Mouse button released. Event data contains mouse button code. 
				
					Select EventData()
						Case 1 	MouseDown_Left   = False
						Case 2 	MouseDown_Right  = False
						Case 3 	MouseDown_Middle = False
					End Select
				
				
				Case EVENT_MOUSEMOVE 		' Mouse moved. Event x and y contain mouse coordinates.
				
					Mouse_X = EventX()
					Mouse_Y = EventY()
				
						 
				Case EVENT_MOUSEWHEEL 		' Mouse wheel spun. Event data contains delta clicks. 
				Case EVENT_MOUSEENTER 		' Mouse entered gadget area. 
				Case EVENT_MOUSELEAVE 		' Mouse left gadget area. 
				Case EVENT_TIMERTICK 		' Timer ticked. Event source contains timer object. 
				Case EVENT_HOTKEYHIT 		' Hot key hit. Event data and mods contains hotkey keycode and modifier.
				Case EVENT_MENUACTION 		' Menu has been selected. 
				Case EVENT_WINDOWMOVE 		' Window has been moved. 
				Case EVENT_WINDOWSIZE 		' Window has been resized.
				 
				Case EVENT_WINDOWCLOSE 		' Window close icon clicked. 
					End
					
				Case EVENT_WINDOWACTIVATE	' Window activated. 
				Case EVENT_WINDOWACCEPT 	' Drag and drop operation was attempted. 
				Case EVENT_GADGETACTION 	' Gadget state has been updated. 
				Case EVENT_GADGETPAINT 		' A canvas gadget needs to be redrawn. 
				Case EVENT_GADGETSELECT		' A treeview node has been selected. 
				Case EVENT_GADGETMENU 		' User has right clicked a treeview node or textarea gadget. 
				Case EVENT_GADGETOPEN 		' A treeview node has been expanded. 
				Case EVENT_GADGETCLOSE 		' A treeview node has been collapsed. 
				Case EVENT_GADGETDONE 		' An HTMLview has completed loading a page. 

			End Select

		Wend

	End Function


' -----------------------------------------------------------------------------------------------------------------------------------------------------------
' This hooks the gadget paint event so it can redraw the canvas as needed while another window is dragged over the game window.
' -----------------------------------------------------------------------------------------------------------------------------------------------------------

		
	AddHook EmitEventHook, MyHook	
		
	Function MyHook:Object(iId:Int, tData:Object, tContext:Object)
	
 		Local Event:TEvent=TEvent(tData)
		
		If App.Canvas <> Null
			If (Event.Source = App.Canvas) And (Event.ID = EVENT_GADGETPAINT)
				Flip		
				Return Null
			EndIf	
		EndIf

		Return tData
		
	End Function





Type RenderState


	Global RenderStateList:TList = CreateList()
				
	
	Field Alpha#
	Field Blend%
	Field ClsColor_R%, ClsColor_G%, ClsColor_B%
	Field Color_R%, Color_G%, Color_B%
	Field Handle_X#, Handle_Y#
	Field ImageFont:TImageFont
	Field LineWidth#
	Field MaskColor_R%, MaskColor_G%, MaskColor_B%
	Field Origin_X#, Origin_Y#
	Field Rotation#
	Field Scale_X#, Scale_Y#
	Field Viewport_X%, Viewport_Y%, Viewport_Width%, Viewport_Height%


	' -------------------------------------------------------------------------------------------------------------------------------------------------------
	' These methods allow you to save and restore the current render settings
	'
	' Each time you call the push method, the current state is placed on the stack.
	' Each time you call the pop method, the last state placed on the stack is restored and removed from the stack.
	' -------------------------------------------------------------------------------------------------------------------------------------------------------

		
		Function Push()

			Local RS:RenderState = New RenderState

			RS.Alpha# = GetAlpha#()
			RS.Blend  = GetBlend()
			GetClsColor(RS.ClsColor_R, RS.ClsColor_G, RS.ClsColor_B)
			GetColor(RS.Color_R, RS.Color_G, RS.Color_B) 
			GetHandle(RS.Handle_X#, RS.Handle_Y#)
			RS.ImageFont = GetImageFont()
			RS.LineWidth# = GetLineWidth#()
			GetMaskColor(RS.MaskColor_R, RS.MaskColor_G, RS.MaskColor_B)
			GetOrigin(RS.Origin_X#, RS.Origin_Y#)
			RS.Rotation# = GetRotation#()
			GetScale(RS.Scale_X#, RS.Scale_Y#)
			GetViewport(RS.Viewport_X, RS.Viewport_Y, RS.Viewport_Width, RS.Viewport_Height)
		
			RenderStateList.AddLast(RS)
		
		End Function		


		Function Pop()
		
			Local RS:RenderState = RenderState(RenderStateList.RemoveLast())	
				
			SetAlpha(RS.Alpha#)
			SetBlend(RS.Blend)
			SetClsColor(RS.ClsColor_R, RS.ClsColor_G, RS.ClsColor_B)
			SetColor(RS.Color_R, RS.Color_G, RS.Color_B) 
			SetHandle(RS.Handle_X#, RS.Handle_Y#)
			SetImageFont(RS.ImageFont)
			SetLineWidth(RS.LineWidth#)
			SetMaskColor(RS.MaskColor_R, RS.MaskColor_G, RS.MaskColor_B)
			SetOrigin(RS.Origin_X#, RS.Origin_Y#)
			SetRotation(RS.Rotation#)
			SetScale(RS.Scale_X#, RS.Scale_Y#)
			SetViewport(RS.Viewport_X, RS.Viewport_Y, RS.Viewport_Width, RS.Viewport_Height)

		End Function


End Type



Change the loop at the start to load a large image, say 800x600. Run the program. It will run in fullscreen, display a mouse cursor only, and with one image loaded it should exit fullscreen immediately when you hit ESC.

Now try changing the loop to load 10 images. There should be a significant pause before it exits when you hit ESC. If not, try 100 images.

Pressing F will toggle between fullscreen and windowed. Changing the App.Create() function call so that the first True is a False will make the app begin in a window. You may then test it to see if it pauses when you press F to toggle to fullscreen. The window will dissapear while it's taking its time switching modes. This indicates that it executes everything up to the HideGadget Window call in the SetFullscreen() function.

I suspect the point where it chokes in both scenarios is the If TG_Fullscreen = Null Then TG_Fullscreen = Graphics(Width, Height, Depth) line in the SetFullscreen() function.

If I set to 100 then I get an Unhandled Memory Exception as the array is only declared for 100 (e.g. 0 to 99).
If I press 'esc' quickly then I get the delay but, my guess, is it is still in the image loading loop. If I wait for 10-15 secs to ensure the load has ended to seems to esc immediately.
<edit> Sorry if I have missed something. I added
		For Loop = 1 To 99
			IMG_Dust[Loop] = LoadImage("background.png")
			Print "doing"
		Next
		
		Print "Done"

and whenever I hit 'esc' I always see 'done' printed as it can only end once out of the loop. (e.g. the 'ESC' key is buffered for reading after the loop.

<EDIT> You might also want to make your example code a bit simpler.

Yeah, I just checked it, and the test code isn't reproducing the error after all.

However, the problem is real, and I'm sure that the error isn't in my code.

When you hit ESC in the game, it's just like in this demo. It simply calls END. You can be playing the game, hit ESC, and it freezes up for a little bit before going back to the desktop. And the issue doesn't present itself when running in OpenGL.

Maybe the problem is the images aren't being drawn to cause them to be cached. I'll try that.

Hm... nope. Loading the same large dust image 50 times and drawing each one doesn't expose the issue. Nor does loading 30 different smaller images of enemies which I load when my game begins.

Doesn't make any sense. :-(

I would have debug/trace messages in all functions/methods but, more specifically, I would have 'esc' key call onend() which draws some text or an image. If that is seen before the delay then it's probably some clean-up happening in DX and not OGL.

I don't see how making ESC print something would provide me with any additional information. I already know that keyboard input gets responded to instantly.

And debug messages if I can work out a way to see them will almost certainly show me that it freezes at that fullscreen set graphics line.

As for it being some kind of clean up, that was the first thing I suspected but the fact that the delay happens when going from windowed to fullscreen and then never again doesnt really fit that theory.

I'll see if I can prove it's locking up at the graphics line though. Maybe I can have it play a sound.

Okay I did the sound test. When in windowed mode and switching to fullscreen, it seems like, the FreeGadget Canvas line in the fullscreen() function is the culprit.

But that doesn't mean much because a simple END is the culprot when the game starts in fullscreen mode and you attempt to quit.

But maybe end calls FreeGadget internally and freeing that canvas the first time it's created causes the hiccup. No idea why recreating it and freeing it again would not exhibit the same behavior though.

I don't see how making ESC print something would provide me with any additional information. I already know that keyboard input gets responded to instantly.

it was the delay from hitting esc to onend displaying anything to the program finishing I was suggesting might be useful.

And debug messages if I can work out a way to see them will almost certainly show me that it freezes at that fullscreen set graphics line.


... write them to a log with a statement when you hit 'esc' during onend(). Again a suggestion because, basically, you have all the code I am having to make guesses.
As for it being some kind of clean up, that was the first thing I suspected but the fact that the delay happens when going from windowed to fullscreen and then never again doesnt really fit that theory.


Unless there is some cleanup when switching for the first time. Again, I haven't got any code to recreate so am guessing.
Anyway, you seem to have it well in hand and seem intent on keeping all the information to yourself so... good luck.

Maybe it has to reload/wipe images in video ram as you switch?

Speculation of this nature isn't really gonna help things. I was really hoping someone else had encountered this issue themselves and could confirm that way that it is in fact a BlitzMax issue so that maybe I could then convince Mark to look into it.

It's obviously some kind of graphics related issue, and given that it doesn't occur when using OpenGL it almost certanly is either a limitation of DirectX, or a problem with how BlitzMax is shutting down/starting up DirectX apps.

Unfortunately since we don't have access to the code that does those things, the only person who can really be of any help with this problem is Mark or Simon or whoever the other guy working on the code is.

I already know the lines where the delay occurs. One is "FreeGadget Canvas" line, and the other is "End".

The issue's clearly something internal, dealing with freeing up something DirectX graphics related, and no amount of debug logging is going to provide me with any more information about what is going on.

Putting code in OnEnd() is pointless. It won't tell me anything. We'd have to know what shutdown code is actually executed before and after that for it to narrow down the problem.

It sounds like you are using Vista

Nope. XP.

And one of the latest Nvivia graphics cards.

hmm... the only time I have run into what you described is on Vista systems and I chalked it up to DX7 being emulated. :/

" there's a two second delay "

That's not an application killer by a long shot. ;) I've experienced the same delay, sometimes it's 1 second, sometimes it's 2-3 seconds. I think it's related to how much graphics are in the gpu at the time the program calls "EndGraphics()". I would guess images in the gpu are being flushed, copies in sram are being flushed, etc.

I didn't really think anything of it. If it was 10 seconds or longer, I would be very concerned though.

As a work around could you close/hide the window before ending?

Then the user does not see a delay?

e.g. CloseGraphics() or EndGraphics()

Just a thought but could there be any connection to the polled input mode which is started with the Graphics?

No, the problem isn't running in a window. Running in a window the game opens fast and exits fast.

It's only when toggling from windowed to fullscreen, or from fullscreen to windowed, or starting in fullscreen and exiting from there, that the game hangs up for a bit.

Though I haven't tried minimizing/tabbing out of the game from fullscreen to see what happens there. Guess that's an area I could explore.


Just a thought but could there be any connection to the polled input mode hich is started with the Graphics?


Unlikely, because the delay doesn't just happen when switching to fullscreen. It also happens when toggling from fullscreen to windowed mode and when exiting.

[edit]

Alt-tabbing out of the app is fast. Don't know yet if minimizing from within the app is. Also, alt-tabbing out, then returning to fullscreen does not get rid of the delay when ending the program.

Argh, now I've got a new issue. When tabbing out and back, blitzmax resets the projection matrix, so my code to display everything the same regardless of video resolution breaks, and everything gets stuck in one small corner of the high res screen because it's rendered at 800x500 but should be stretched over 1920x1200.

I thought it was an easy fix. When switching from windowed to fullscreen, I just call my function that sets the projection matrix again after I set the graphics up. But for some reason, when tabbing back into the game, even though my code is in there for setting the projection matrix up again when the APPRESUME event occurs, it doesn't put things back the way they were.

It's almost as if BlitzMax is giving my app the APPRESUME event first, and then it gets around to setting up the graphics again afterwards.

Also, the events it triggers are weird. This is what I get when loading the game fullscreen, alt-tabbing out, then alt tabbing back in, and quitting:

DebugLog:EVENT_WINDOWMOVE
DebugLog:EVENT_WINDOWSIZE
DebugLog:EVENT_APPRESUME
DebugLog:EVENT_APPRESUME
[TAB OUT]
DebugLog:EVENT_APPSUSPEND
DebugLog:EVENT_APPSUSPEND
DebugLog:EVENT_APPSUSPEND
[TAB IN]
DebugLog:EVENT_APPRESUME
DebugLog:EVENT_APPRESUME

Why three suspend events and two resume events when the app is alt-tabbed out of?

What I had to do with the retroremakes framework to sort out the projection matrix issue you describe

Method CheckIfActive()
	If AppSuspended()
		TGameEngine.GetInstance().LogInfo("Game Suspended")
		rrPauseSound(True)
		Local susTimer:TTimer = CreateTimer(60)  'temporary timer to help free up CPU when game suspended
		'wait until app is active again
		While AppSuspended() 
			WaitTimer(susTimer)   'Do nothing and free up CPU
		Wend
		TGameEngine.GetInstance().LogInfo("Game Resumed")
		If Not windowed
			'When resuming from minimised full-screen display we need to recreate Grahics
			'and set up the projection matrix again due to DirectX oddness
			TGameEngine.GetInstance().LogInfo("Resetting Graphics Mode")
			Reset()
		EndIf
		'Reset the fixed timestep timer so we don't have any glitches
		rrResetFixedTimestep()
		rrResetFPS()
		rrPauseSound(False)
	EndIf		
End Method


The Reset() method does EndGraphics(), creates the Graphics mode again and then sets up the projection matrix again.

If you want to check all the code you can grab it from the Google Code link in my signature.