[Community Project] - Win32 GDI graphics

BlitzMax Forums/BlitzMax Programming/[Community Project] - Win32 GDI graphics

** Download - GDI Graphics
_________________________________________________


As a possible community project what do you guys think with regards to creating a Win32 GDI graphics driver?

Here are my thoughts on the pros and cons:

+ No need to rely on OpenGL or DX
+ Uses internal API graphics (smaller executables)
+ Ideal for simple window graphics (boxes, lines, filled ares)
+ Suitable for applications such as paint programs
+ Maxiumum compatibility
- Not as fast (or fully-featured?) as OpenGL or DX
- Windows only

Anyhow, here's something I've been playing with ..



Ideally, I would like to see something which mimics all of the Max2D commands but relys solely on API calls to avoid the need for OpenGL, DX. Example:

SetGraphicsDriver GDIGraphicsDriver()
SetGraphics mypanel ' send graphics output to panel gadget
SetPenColor 100,200,200
SetPenWidth 4
SetFillColor 50,60,70
DrawRect 10,20,40,50


At the moment, I have a GDI type with the following methods:
gdi1:GDI=GDI.CreateGDIPanel(x,y,w,h,group:TGadget)

methods:

.Free - free the GDI panel and resources

Rendering
--------------------------
.SetRenderMethod
.SetBuffer
.Cls
.Flip

Color Handling
--------------------------
.SetPenColor
.SetPenWidth
.SetPenStyle
.SetFillColor
.SetFillPattern

2D Drawing
--------------------------
.Plot
.Point()
.DrawLine
.DrawOval
.DrawRect
.InvertArea
.ScrollArea
.FloodFill

Text Handling
--------------------------
.DrawText
.SetFont
.SetTextFormat

Bitmap/Icon handling
--------------------------
.LoadBitmap
.FreeBitmap
.DrawBitmap
.DrawScaledBitmap
.LoadIcon
.DrawIcon
.FreeIcon


Also, the following events are returned to the Max event system when the mouse is over a GDI gadget:

Event               Source       Data          EventX()     EventY()

EVENT_MOUSEMOVE  | gdi panel | n/a           | mouseXpos  | mouseYpos
EVENT_MOUSEUP    | gdi panel | button(1/2/3) | mouseXpos  | mouseYpos
EVENT_MOUSEDOWN  | gdi panel | button(1/2/3) | mouseXpos  | mouseYpos


Handy Links:
API Guide
Microsoft MSDN
Win32 API reference - 5.43MB

I'll try and update the source code with any mods/additions you come up with ...

TODO:



[1] - Fix cursor stuck at 'busy' state whilst over GDI panel
[2] - Change the way images are created
[3] - Grabbing/pasting areas of the gdi
[4] - Lot's of other drawing methods added (XOR, AND, COPY, DIFF - via CombineRgn API)
[5] - Gradient fills (GradientFill API)
[6] - Turn the whole system into a proper graphics driver which can be used via SetGraphicsDriver and SetGraphics.

I found that *should* be something like this:
Extern "Win32"
'Public Const WM_SETREDRAW = &HB
	Function SendMessage(HWND%,WM_SETREDRAW:Int,par1:Int,par2:Long)
...


	Method Refresh()
		SendMessage(hWND,WM_SETREDRAW,0,0)'<--- ????
	End Method
...

		Case EVENT_WINDOWMOVE
			gdi.refresh


of course it don't work...I obtain an error message on SendMessage()..."Compile Error: Too Many Function Parameter"
I suspect that somewhere (where?) in the bmax mods there is a SendMessage Functions...

Thanks degac.
I had a play with SendMessageA and the WM_SETREDRAW flag but I can't get it to work as desired.
Locking the redrawing of the window after drawing the graphics means the panels border and contained graphics are not drawn after another window passed over the top.

For the time being I'm calling gdi.DrawGraphics DrawTest which executes the DrawTest() function when an event occurs such as EVENT_APPRESUME , EVENT_WINDOWACTIVATE, EVENT_WINDOWMOVE

It's by no means perfect though. The InvertArea screws up for starters. Plus, once the window is inactive there is no notification to re-draw the graphics.

Perhaps you could have a look at this

http://www.blitzbasic.com/Community/posts.php?topic=53212

Just something I was playing around with a while ago.

this one i've missed! thanks

Nice work. What about the SDL community project, is that also useful?

Updated with WM_PAINT method. Thanks Skn3[ac]!
I'm not sure if its right but there are no flames coming out of the PC's tower as of yet.

Although the graphics are now permanently displayed a bug still needs attention:

2) The cursor remains in a 'busy' state until I move OFF the panel gadget. Not sure whats going on there.

Currently, graphics commands are sent to a bitmap buffer device context which is then BitBlt'd into the gadgets device context via the Flip and WM_PAINT calls.


Rob,
I've not really looked at SDL but I really want to keep this as independent as possible and therefore not rely on external API's or libs.

Updated with mouse events when over a panel. See 1st post.

Gulp!
Nice one - very good job!

Updated:

* Loads and draws Bitmaps and icons
* Text handling (still need to find out how to set a font)

Don't know if this is of any use:
The CreateFont function creates a logical font that has specific characteristics. 
The logical font can subsequently be selected as the font for any device. 

HFONT CreateFont(

    int nHeight,	// logical height of font 
    int nWidth,	// logical average character width 
    int nEscapement,	// angle of escapement 
    int nOrientation,	// base-line orientation angle 
    int fnWeight,	// font weight 
    DWORD fdwItalic,	// italic attribute flag 
    DWORD fdwUnderline,	// underline attribute flag 
    DWORD fdwStrikeOut,	// strikeout attribute flag 
    DWORD fdwCharSet,	// character set identifier 
    DWORD fdwOutputPrecision,	// output precision 
    DWORD fdwClipPrecision,	// clipping precision 
    DWORD fdwQuality,	// output quality 
    DWORD fdwPitchAndFamily,	// pitch and family 
    LPCTSTR lpszFace 	// pointer to typeface name string 
   );	
 

Parameters

nHeight

Specifies the height, in logical units, of the font's character cell or character. The character height value (also known as the em height) is the character cell height value minus the internal-leading value. The font mapper interprets the value specified in nHeight in the following manner:

Value	Meaning
> 0	The font mapper transforms this value into device units and matches it against the cell height of the available fonts.
0	The font mapper uses a default height value when it searches for a match.
< 0	The font mapper transforms this value into device units and matches its absolute value against the character height of the available fonts.
 

For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size. 

This mapping occurs when the font is used for the first time. 
For the MM_TEXT mapping mode, you can use the following formula to specify a height for a font with a specified point size:

  
nHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);
 

nWidth

Specifies the average width, in logical units, of characters in the requested font. If this value is zero, the font mapper chooses a "closest match" value. The "closest match" value is determined by comparing the absolute values of the difference between the current device's aspect ratio and the digitized aspect ratio of available fonts. 

nEscapement

Specifies the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement vector is parallel to the base line of a row of text. 

Windows NT: 

When the graphics mode is set to GM_ADVANCED, you can specify the escapement angle of the string independently of the orientation angle of the string's characters.
When the graphics mode is set to GM_COMPATIBLE, nEscapement specifies both the escapement and orientation. You should set nEscapement and nOrientation to the same value.

Windows 95: 

The nEscapement parameter specifies both the escapement and orientation. You should set nEscapement and nOrientation to the same value.

nOrientation

Specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device. 

fnWeight

Specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. If this value is zero, a default weight is used.

The following values are defined for convenience:

Value	Weight
FW_DONTCARE	0
FW_THIN	100
FW_EXTRALIGHT	200
FW_ULTRALIGHT	200
FW_LIGHT	300
FW_NORMAL	400
FW_REGULAR	400
FW_MEDIUM	500
FW_SEMIBOLD	600
FW_DEMIBOLD	600
FW_BOLD	700
FW_EXTRABOLD	800
FW_ULTRABOLD	800
FW_HEAVY	900
FW_BLACK	900
 

fdwItalic

Specifies an italic font if set to TRUE. 

fdwUnderline

Specifies an underlined font if set to TRUE. 

fdwStrikeOut

Specifies a strikeout font if set to TRUE. 

fdwCharSet

Specifies the character set. The following values are predefined: 

ANSI_CHARSET
DEFAULT_CHARSET
SYMBOL_CHARSET
SHIFTJIS_CHARSET
GB2312_CHARSET
HANGEUL_CHARSET
CHINESEBIG5_CHARSET
OEM_CHARSET

Windows 95 only:

JOHAB_CHARSET
HEBREW_CHARSET
ARABIC_CHARSET
GREEK_CHARSET
TURKISH_CHARSET
THAI_CHARSET
EASTEUROPE_CHARSET
RUSSIAN_CHARSET
MAC_CHARSET
BALTIC_CHARSET

The OEM_CHARSET value specifies a character set that is operating-system dependent. 
You can use the DEFAULT_CHARSET value to allow the name and size of a font to fully describe the logical font. If the specified font name does not exist, a font from any character set can be substituted for the specified font, so you should use DEFAULT_CHARSET sparingly to avoid unexpected results.
Fonts with other character sets may exist in the operating system. If an application uses a font with an unknown character set, it should not attempt to translate or interpret strings that are rendered with that font. 

This parameter is important in the font mapping process. To ensure consistent results, specify a specific character set. If you specify a typeface name in the lpszFace parameter, make sure that the fdwCharSet value matches the character set of the typeface specified in lpszFace.

fdwOutputPrecision

Specifies the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. It can be one of the following values: 

Value	Meaning
OUT_CHARACTER_PRECIS	Not used.
OUT_DEFAULT_PRECIS	Specifies the default font mapper behavior.
OUT_DEVICE_PRECIS	Instructs the font mapper to choose a Device font when the system contains multiple fonts with the same name.
OUT_OUTLINE_PRECIS	Windows NT: This value instructs the font mapper to choose from TrueType and other outline-based fonts.Windows 95: This value is not used.
OUT_RASTER_PRECIS	Instructs the font mapper to choose a raster font when the system contains multiple fonts with the same name.
OUT_STRING_PRECIS	This value is not used by the font mapper, but it is returned when raster fonts are enumerated.
OUT_STROKE_PRECIS	Windows NT: This value is not used by the font mapper, but it is returned when TrueType, other outline-based fonts, and vector fonts are enumerated. Windows 95: This value is used to map vector fonts, and is returned when TrueType or vector fonts are enumerated. 
OUT_TT_ONLY_PRECIS	Instructs the font mapper to choose from only TrueType fonts. If there are no TrueType fonts installed in the system, the font mapper returns to default behavior.
OUT_TT_PRECIS	Instructs the font mapper to choose a TrueType font when the system contains multiple fonts with the same name.
 

Applications can use the OUT_DEVICE_PRECIS, OUT_RASTER_PRECIS, and OUT_TT_PRECIS values to control how the font mapper chooses a font when the operating system contains more than one font with a specified name. For example, if an operating system contains a font named Symbol in raster and TrueType form, specifying OUT_TT_PRECIS forces the font mapper to choose the TrueType version. Specifying OUT_TT_ONLY_PRECIS forces the font mapper to choose a TrueType font, even if it must substitute a TrueType font of another name.

fdwClipPrecision

Specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. It can be one or more of the following values: 

 

Value	Meaning
CLIP_DEFAULT_PRECIS	Specifies default clipping behavior.
CLIP_CHARACTER_PRECIS	Not used.
CLIP_STROKE_PRECIS	Not used by the font mapper, but is returned when raster, vector, or TrueType fonts are enumerated.Windows NT: For compatibility, this value is always returned when enumerating fonts.
CLIP_MASK	Not used.
CLIP_EMBEDDED	You must specify this flag to use an embedded read-only font.
CLIP_LH_ANGLES	When this value is used, the rotation for all fonts depends on whether the orientation of the coordinate system is left-handed or right-handed. If not used, device fonts always rotate counterclockwise, but the rotation of other fonts is dependent on the orientation of the coordinate system.For more information about the orientation of coordinate systems, see the description of the nOrientation parameter
CLIP_TT_ALWAYS	Not used.
 

fdwQuality

Specifies the output quality. The output quality defines how carefully GDI must attempt to match the logical-font attributes to those of an actual physical font. It can be one of the following values: 

Value	Meaning
DEFAULT_QUALITY	Appearance of the font does not matter.
DRAFT_QUALITY	Appearance of the font is less important than when the PROOF_QUALITY value is used. For GDI raster fonts, scaling is enabled, which means that more font sizes are available, but the quality may be lower. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
PROOF_QUALITY	Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Although the chosen font size may not be mapped exactly when PROOF_QUALITY is used, the quality of the font is high and there is no distortion of appearance. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
 

fdwPitchAndFamily

Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font and can be one of the following values: 

DEFAULT_PITCH
FIXED_PITCH
VARIABLE_PITCH
The four high-order bits specify the font family and can be one of the following values: 

Value	Description
FF_DECORATIVE	Novelty fonts. Old English is an example.
FF_DONTCARE	Don't care or don't know.
FF_MODERN	Fonts with constant stroke width, with or without serifs. Pica, Elite, and Courier New® are examples.
FF_ROMAN	Fonts with variable stroke width and with serifs. MS® Serif is an example.
FF_SCRIPT	Fonts designed to look like handwriting. Script and Cursive are examples.
FF_SWISS	Fonts with variable stroke width and without serifs. MS Sans Serif is an example.
 

An application can specify a value for the fdwPitchAndFamily parameter by using the Boolean OR operator to join a pitch constant with a family constant. 
Font families describe the look of a font in a general way. They are intended for specifying fonts when the exact typeface requested is not available. 

lpszFace

Points to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamilies function can be used to enumerate the typeface names of all currently available fonts. 

If lpszFace is NULL or points to an empty string, GDI uses the first font that matches the other specified attributes.

 

Return Values

If the function succeeds, the return value is a handle to a logical font.
If the function fails, the return value is NULL. To get extended error information, call GetLastError. 

Remarks

When you no longer need the font, call the DeleteObject function to delete it. 
To help protect the copyrights of vendors who provide fonts for Windows operating systems, applications should always report the exact name of a selected font. Because available fonts can vary from system to system, do not assume that the selected font is always the same as the requested font. For example, if you request a font named "Palatino," but no such font is available on the system, the font mapper will substitute a font that has similar attributes but a different name. Always report the name of the selected font to the user.

See Also

DeleteObject, SelectObject, EnumFontFamilies 


Following are the functions used with fonts. 

AddFontResource
CreateFont
CreateFontIndirect
CreateScalableFontResource
DrawText
DrawTextEx
EnumFontFamilies
EnumFontFamiliesEx
EnumFontFamExProc
EnumFontFamProc
EnumFonts
EnumFontsProc
ExtTextOut
GetAspectRatioFilterEx
GetCharABCWidths
GetCharABCWidthsFloat
GetCharacterPlacement
GetCharWidth
GetCharWidthFloat
GetCharWidth32
GetFontData
GetFontLanguageInfo
GetGlyphOutline
GetKerningPairs
GetOutlineTextMetrics
GetRasterizerCaps
GetTabbedTextExtent
GetTextAlign
GetTextCharacterExtra
GetTextColor
GetTextExtentExPoint
GetTextExtentPoint
GetTextExtentPoint32
GetTextFace
GetTextMetrics
PolyTextOut
RemoveFontResource
SetMapperFlags
SetTextAlign
SetTextCharacterExtra
SetTextColor
SetTextJustification
TabbedTextOut
TextOut


Thanks Perturbatio. Font-loading works. (Updated above) ..



This is looking pretty good, one day I'll have the time to download it and test it :)

This doesnt work for someone who hasn't purchased the BMax GUI module, correct?

Sorry to bump this. Is there any way to load and draw an image with an alpha channel? Even if just 1 bit alpha, that would be fine. I've tried loading and drawing both bitmaps and icons ( because I read that they were easier to get working with alpha channels ) but I can't get it working in either case.

Why wasn't this continued? It looks fairly promising.

Or was there just nothing more to be finished?

Looking at the thread, I'd say there wasn't a lot of interest and what Jim has already put together is really very good. You can do an awful lot with it as it is.

I've read up on alpha in bitmaps and it looks as though there are two ways to do it, one of which is rarely supported and the other way is really rather complicated and unwieldy. So I think I'm just gonna draw square images and be done with it.

I did do a fair bit of work on this project mainly for my self. I Re-wrote the command set to a more friendly BlitzMax-style approach.

Currently I have these commands/functions:
GDI Command set
===============

FUNCTION			PARAMETERS


GDI Panels
_________________________________________________
=CreateGDIPanel		(x,y,w,h,parent,style)
FreeGDIGadget		g:GDI
GDICleanup

Rendering
_________________________________________________
SetRenderMethod		method
SetGraphics			g:GDI
Cls
Flip				[gdipanel:GDI]

Color Handling
_________________________________________________
SetColor			r,g,b
SetPenColor			r,g,b
SetPenWidth			width
SetPenStyle			style [,rendermode]
SetFillColor		r,g,b
SetFillPattern		bmp:BTIMAP

2D Drawing
_________________________________________________
Plot				x,y
=Point			(x,y)
DrawLine			x1,y1,x2,y2
DrawOval			x,y,width,height
DrawRect			x,y,width,height [,RoundW,roundH]
InvertArea			x,y,width,height
ScrollArea			x,y,width,height,dx,dy
FloodFill			x,y

Text Handling
_________________________________________________
SetFont			name$,size [,style,rotation]
DrawText			txt$,x,y [,width,height]
SetTextFormat		justification [,rendermode]

Bitmaps
_________________________________________________
=CreateBitmap		(Width,Height,Depth,colordata@[])
=LoadBitmap			(filename$)
FreeBitmap			bmp:BITMAP
DrawBitmap			bmp:BITMAP,x,y [,rx,ry,rw,rh]
DrawScaledBitmap		bmp:BITMAP,x,y,swidth,sheight [,rx,ry,rw,rh]

Icons
_________________________________________________
=LoadIcon			(filename$)
DrawIcon			iconhandle,x,y
FreeIcon			iconhandle


Since I am working abroad at the moment I cannot upload the GDI stuff to my UK site. Any good free sites worth registering with?

not as far as i know of, but if possible id like to get my hands on that newer version you made.

Email:*******************

Tim .. Check your email.

Ty.

Jim very kindly sent me a copy of the new version and said I could post a link in case anyone else wants to take a look.

http://www.xmystik.co.uk/gdi-new.zip

Thanks Jim :)

Steve.

To use GDI Drawing (Like FloodFill) you can only draw on a GDIPanel, correct? (It would be cool to be able to floodfill images onto other images to create a sort of texture effect for 2d game's, menu's ect)