# Visual Basic > Visual Basic 6 and Earlier >  Direct2D Typelib+ for VB6

## baka

in the other thread: GDI+ Load Png + Resize dilettante mentioned Direct2D IDL/TLB,
DEXWERX also answered that it shouldn't be that hard to do, but wonders if theres any interests in doing one at all. He also says its "very simple" API.
well, I would really like one and for me its not easy at all as I don't even know where to start and how the functions/API looks like.

so, what say, is this possible? any other would like to play with Direct2D in VB6?

----------


## Elroy

Hi baka,

I'm a bit out of my depths here, but I'm going to jump in anyway.  And here are understandings/expertises I do have:

I'm not too bad at Linear Algebra (particularly when it comes to objects in 3D space).  As such, I could do everything I need without DirectX, but it'd be much slower and much more involved.  And displaying graphics and animations on the screen, directly using our graphics accelerators, is what DirectX is all about.I've developed a decent project using DirectX using DX8.It's my understanding that the API for DX8 is directly accessible via VB6 (i.e., no TypeLib needed).  Also, all that's required to use it is to place the Dx8vb.dll in the same path as your executable (i.e., no registration necessarily required).It's my understanding (but not entirely sure) that something changed (possibly the calling conventions) about DX9 and beyond that makes the APIs impossible to directly call from VB6.I've been contemplating a couple of DX projects, but both of mine will probably use Direct3D rather than Direct2D, but stepping back to Direct2D should be fairly easy once Direct3D is understood.  I'll probably start the beginnings of one of those projects today, probably leaning on my knowledge of DX8.  I may start another thread to assist with getting advice on that project.

Take Care,
Elroy

EDIT1:  And, just to say a bit more about the one project using DX that I have developed.  It was a static project with a dynamic camera.  As such, I didn't worry about frames or FPS (frames-per-second).  The two projects I'd like to work on in the future both involve both dynamic frames (along with a FPS setting) and a need for a dynamic camera (able to change perspective, zoom & pan).

----------


## dilettante

To do everything you want you might also need DirectWrite and Windows Imaging Component (WIC).

----------


## baka

I will follow that thread Elroy, and I do hope it will be "noob" friendly as im clueless when its about DirectX. those matrix things confuses me a lot and the different calls to "initialize" the screen/engine is hard to grasp.

Dilettante, yeah, I did a search and found out that TextOut equivalent is DrawText (using DirectWrite) and loading bitmap we need to use WIC,
but I also read that it is possible to combine GDI and Direct2D, so we could use GDI/GDI+ to load and we can use the GDI DC. so we can render directly into a DC from Direct2D.
now, Im not sure if thats good or bad, but I do like the options to use both.

----------


## Jacob Roman

Ooooor you can talk to me about DirectX, as I'm an expert at it  :big yellow: 

I have tons of DX VB6 stuff in my signature, including the infamous Massive DirectX Tutorial. But to be honest, with VB6, it only gone as far as DirectX8. Even the .NET languages are stuck with DirectX9. We have DirectX12 now, which is why I switched to C++. But even then, DirectX12 only works on Windows10 computers, and won't work on Windows7, which is why I do DirectX11 instead. But if you do ever decide to make the leap to DirectX11, you will no longer be stuck in the fixed graphical pipeline. Everything you do will now require shaders, so you will need to learn the HLSL language (high level shading language). Its not hard once you learn about vertex shaders and fragment shaders. And you will now have more control over how your polygons are drawn, 2D and 3D. Also the entire syntax of DX11 is different, and makes use of what is called "swapchains." With that said, the D3DX library is now deprecated! So you will have to write your own math functions and use the DirectXTK library to do simple things such as texture mapping.

----------


## baka

the reason Im not using directx is that im working with 2D, I need functions that are similar to gdialphablend that allow me to use raster png's and copy/paste parts of a bitmap into a memory device context and later render it all into a picturebox.
so the idea is:
have a memory device context: say 800x600
clear it
a loop that will copy a number of 32bit bitmaps into that context, any rect allowed and opacity.
a number of "textout" with different fonts and sizes.
the final render to a picturebox
and repeat

i can do this quite easily and fast with GDI. but once i apply any filters or resize algorithms the fps is getting extremely low.
when I tried directx, for different sources, even your tutorial i just get confused, I coudln't load a simple png and render it, theres matrix that i need to work with but changing them resulted in 3d effects or strange shapes.
also, i think its nice if VB can use Direct2D as well!

----------


## Jacob Roman

DirectX isnt that hard at all. Its a small learning curve, but once you are pass that, you can do so much so fast. Take my "Your First DirectX Window Application" for example


vb Code:
'---------------------------------'Title: DirectX Tutorial''Description: This is your first DirectX8 application.'             I made it to where this is the easiest'             method to initialize and render. No'             extra subs/functions, no error handling,'             no modules/classes, no nothing. It can't'             get any easier than this, and makes it easy'             for any beginner to understand.''Author: Jacob Roman''Date: 12/01/2005''Contact: [email]jacob_c_roman@hotmail.com[/email]'--------------------------------- Option Explicit Private DirectX8 As DirectX8 'The master DirectX object.Private Direct3D As Direct3D8 'Controls all things 3D.Private Direct3D_Device As Direct3DDevice8 'Represents the hardware rendering. Private Running As Boolean 'Helps determine whether the main game loop is running. Private Sub Form_Activate()     frmMain.Caption = "DirectX Tutorial"     Dim Display_Mode As D3DDISPLAYMODE 'Display mode desciption.    Dim Direct3D_Window As D3DPRESENT_PARAMETERS 'Backbuffer and viewport description.        Set DirectX8 = New DirectX8 'Creates the DirectX object.    Set Direct3D = DirectX8.Direct3DCreate() 'Creates the Direct3D object using the DirectX object.        Direct3D.GetAdapterDisplayMode D3DADAPTER_DEFAULT, Display_Mode 'Use the current display mode that you                                                                    'are already on. Incase you are confused, I'm                                                                    'talking about your current screen resolution. ;)        Direct3D_Window.Windowed = True 'The app will be in windowed mode.    Direct3D_Window.SwapEffect = D3DSWAPEFFECT_COPY_VSYNC 'Refresh when the monitor does.    Direct3D_Window.BackBufferFormat = Display_Mode.Format 'Sets the format that was retrieved into the backbuffer.        'Creates the rendering device with some useful info, along with the info    'we've already setup for Direct3D_Window.    Set Direct3D_Device = Direct3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, frmMain.hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, Direct3D_Window)     Running = True 'Initializations all set. It's now ok to activate the game loop.     Do While Running = True                DoEvents 'Allow events to happen so the program doesn't lock up.                '----------------------------------------------------        'DirectX automatically handles the framerate for you        'which makes it run (at most) as fast as the monitors        'refresh rate, so you don't need to add extra code to        'slow down the loop and run at a certain number of frames        'per second.        '----------------------------------------------------                'Clears the backbuffer.        Direct3D_Device.Clear 0, ByVal 0, D3DCLEAR_TARGET, D3DColorRGBA(0, 0, 0, 0), 1#, 0                    'Rendering code goes here, but in this tutorial, it will be empty for now.                'Flips the backbuffer into the form window.        Direct3D_Device.Present ByVal 0, ByVal 0, 0, ByVal 0            Loop End Sub Private Sub Form_Unload(Cancel As Integer)     Running = False 'Helps the program bail out of the game loop.        'Unload all of the DirectX objects        Set Direct3D_Device = Nothing    Set Direct3D = Nothing    Set DirectX8 = Nothing        Unload Me 'Unload the form        End 'Ends the program        'Although the Unload statement located above exits the program, you    'will end up with an Automation error after doing so. The End statement    'will help prevent that, and end the app completely. End Sub

Since DirectX handles the framerate automatically for you, and does everything hardware, you don't have to worry about "low framerate". I have everything heavily commented to explain what everything does line by line. But if you do not want to run inside a window, and run inside a picturebox instead, change this



```
Set Direct3D_Device = Direct3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, frmMain.hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, Direct3D_Window)
```

to this



```
Set Direct3D_Device = Direct3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, PictureBox1.hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, Direct3D_Window)
```

And DirectX allows you to do some awesome things that Windows GDI is incapable of, such as these 3 games I made, all on VB6!!!

----------


## Elroy

Baka,

I suspect you need to get the concepts of a 2D Transformation Matrix under your belt.  Here's a link to a particularly helpful figure.  Understanding the underlying geometry (particularly in 3D) can get complex, but it's not too bad in 2D.  However, once it's all transformed into a matrix, you really don't even need to know the geometry.  Just do what that figure tells you to do.

Good Luck,
Elroy

----------


## dilettante

Yeah, the "bonehead UserControls as sprites" approach burns a lot of cycles and isn't very flexible.  For gaming you are better off using one of the drawing libraries intended for the purpose.

Here the "bugs" just crawl around the edges of the Form.  I didn't bother to rotate them as their travel orientation changes.

----------


## baka

thx for all the suggestions and samples, i still want to see if its possible to make a Direct2D Typelib.
using DirectX8 could be an alternative, while GDI+ is too slow for my needs, that is why im using StretchBlt, BitBlt and AlphaBlend.

that is quite helpful Elroy, if im gonna dig into dx8 or dx9 i will use that so the image will show correct.

----------


## Elroy

Hi baka,

Yes, I'm trying to cobble together a DX8 project right now.  It's just taking me a bit to get back up to speed with this stuff.  You don't need a Typelib with DX8.  Under the VB6 IDEs references, just explore to a copy of Dx8vb.dll, and you're all set.  Worst case, just make sure that DLL is in your project's VBP folder, and then make sure the following line is near the top of your VBP file:



```
Reference=*\G{E1211242-8E94-11D1-8808-00C04FC2C603}#1.0#0#dx8vb.dll#DirectX 8 for Visual Basic Type Library
```

And then, you can start using the object browser (F2) to explore that DLL's abilities.  However, DirectX can be somewhat overwhelming, possibly more so than even GDI+.  That's why examples of how to do things is of paramount importance.

Also, just to say it, I'm not sure I see DirectX and GDI+ as terribly similar.  Sure, they both render and display images.  However, the GDI+ is truly meant to display those images in such a way that they can be edited and manipulated in a variety of ways.  And, I think the big advantage that GDI+ brings to the table (as opposed to GDI32), is that it truly handles the alpha layer correctly.  Although, it's my understanding that DirectX also handles alpha correctly, possibly in a much more complex way than either GDI32 or GDI+, in that it considers everything behind the object when working out the translucency and the actual color of each pixel.

Now, I see DirectX as having a different purpose.  Of the three (GDI32, GDI+, & DirectX), it's the only one (AFAIK) that makes full use of whatever GUI accelerator hardware we have.  And, as such, it's really designed to be a "display" tool, as opposed to an "editing and image manipulation" tool.  Sure, you can paint textures (i.e., images) on DX objects.  And then, you can rotate and scale these objects, and their textures will rotate and scale with them.  However, I don't think you could do brightness, gamma, color corrections and other adjustments to these textures-on-objects.  Also, I'm not sure how you'd re-read a texture from an object's face (especially maintaining the way it's scaled and oriented).  I suppose you could just read the pixels off the screen's DC, but hmmm.

However, I'm not the guru on these things.  Maybe DirectX is the correct tool for your needs.

Good Luck,
Elroy

----------


## Jacob Roman

Read this, and you will see why it's best to jump off the GDI bandwagon:

http://www.vbforums.com/showthread.p...47#post4420647

----------


## dilettante

I thought he explained he was making twitch games, not an image processing tool or even just a dollied up gauche UI.  But maybe I misinterpreted his other thread.

----------


## Elroy

@Dilettante: You may be correct.  I just scanned the other thread, and I don't see where the purpose is well outlined.

@Baka: Yes, if you're designing some kind of "game", you'd probably do best to learn DirectX.  I'll go ahead and get my other thread started, but it's still in the process of "coming to life."

Best Regards,
Elroy

----------


## baka

please read OP, this thread is not about my game, but a question and a proposition to create a typelib for Direct2D.
of course i will use it for my needs, why not? i started this thread because of the discussion of Direct2D started by Dilettante and also the posts by DEXWERX.

I want to keep this thread about that and not about my game or any other solutions, even if welcome, i really want to stick with the OP question.

the idea of using DX8 could be useful and I will explore that "BUT" its not what this thread is about, its better we start a new thread about DX8, and I will go and participate to the new thread Elroy created.

so, back to OP, what say about Direct2D? I would love to see a typelib for that and why not? we do love VB6 and more we have better it is and im sure others out there if they knew there where a Direct2D typelib they would even consider returning or even starting using VB6.

and my game is a 2D platform game using 5 layers, with background animations, effects, animated creatures and npc and so on. the screen is constantly changing with multiple animation working in the background creating depth and distance. it is set to 125fps default but i can easily go up to 250fps without problems. my somehow middle range computer i can go up to 500fps but in some places it can be a bit laggy.
the game works fine with low-end computers where fps goes up to at least 67fps, and i mean very low-end, with integrated graphics and low memory. so my game works just fine i dont need to replace anything.
but, if i get something even better i could add filters and resize algorithms, its not needed but would make it even better. now can we go back to the OP questions or you want to know more?

----------


## Elroy

Hi Baka,

Ok, just to clarify though ... Direct2D is one of the sub-libraries within DirectX.  However, the first thing we must do is decide which version of DirectX we're talking about (DX8?  DX9?, more recent?).  Once that's decided, then we can figure out what we need to use Direct2D.

Having said that, if we're happy with DX*8*, then we don't need a TypeLib.  It's all directly accessible via the Dx8vb.dll (including Direct2D).  If we want to use DX9, we can use Trick's TypeLib, but I'm not terribly familiar with that.  If we want to use something more recent, then I'm not sure.

If DX8 will do, this is an excellent document/tutorial that goes through all of it.  And, if you go into the graphics section, sections #3 & #4 (parts 1 & 2) are a rather thorough description of Direct2D.  Furthermore, it's all described using VB6 examples.

Best Regards,
Elroy

----------


## baka

reading about it, it says:


```
Direct2D is a user-mode library that is built using the Direct3D 10.1 API. 
This means that Direct2D applications benefit from hardware-accelerated
rendering on modern mainstream GPUs. Hardware acceleration is also achieved
on earlier Direct3D 9 hardware by using Direct3D 10-level-9 rendering. 
This combination provides excellent performance on graphics hardware
on existing Windows PCs.

Starting with Windows 8, Direct2D is built using the Direct3D 11.1 API.
```

so, if someone creates a typelib, will that only work on either windows 8+ or windows 7- depending on what API is used?

----------


## Jacob Roman

Technically DirectX is already a typelib. Much like OpenGL is. Otherwise wed all be writing in assembly to access hardware. It's not hard to learn and pick up. Creating a library out of a library would not be worth it. Well unless you learn Unity or Unreal Engine. But even that's a learning curve. Just learn how to use DirectX. If you need to ask me any questions at all regarding it, I can help  :Wink:

----------


## dilettante

> Having said that, if we're happy with DX*8*, then we don't need a TypeLib.  It's all directly accessible via the Dx8vb.dll (including Direct2D).


Seems unlikely.  There wasn't any Direct2D or DirectWrite until Windows 7 and it was tied to DirectX 10.  Then another version came along with Windows 8, tied to DirectX 11.1, and so on and so on.

----------


## Jacob Roman

> Seems unlikely.  There wasn't any Direct2D or DirectWrite until Windows 7 and it was tied to DirectX 10.  Then another version came along with Windows 8, tied to DirectX 11.1, and so on and so on.


And now D3DX is deprecated and you are FORCED to use shaders in both OpenGL and DirectX

Living Without D3DX

----------


## dilettante

> And now D3DX is deprecated and you are FORCED to use shaders in both OpenGL and DirectX


Now?  That issue dates back to 2012 or so.

----------


## Jacob Roman

> Now?  That issue dates back to 2012 or so.


Exactly

----------


## The trick

I was working on that library (Direct2D), i can continue if community need for that library and no one work on it.

----------


## baka

that would be awesome The trick!  :Smilie:

----------


## The trick

Okay, i'll check if i made the enough interfaces and will made the helpers module. Then i'll make the several examples. After all i'll publish the all stuffs.

----------


## baka

im quite excited! this will be definitely worth understanding and spending time to learn as im working with 2D not 3D  :Smilie:

----------


## Jacob Roman

DirectX as well as OpenGL does both 2D and 3D and utilize the hardware. Since you are eager to learn the 2d aspect, my Massive DirectX Tutorial is all 2D. And covers texture mapping, animation, tile engines, alpha blending, rotation, and so much more! My signature even has the World of Warcraft Spell Cooldown effect done in VB6 and DirectX

----------


## DEXWERX

@The Trick, Since you've been working with it - would you agree that the API lends itself to VB nicely?
(considering that the resources are COM Objects?) 

I think Direct2D is better suited for VB than GDI and GDI+ even with class wrappers.

----------


## baka

yeah DEXWERX, in the other thread by Elroy and DirectX8, im with you. that is one reason why im a bit reluctant to start learning DX8. we do have DX9, but so far I felt overwhelmed and couldn't grasp it to convert GDI to it.
now with The trick working with a Direct2D Typelib, maybe its time to learn something new and replace GDI once and for all.
I wonder why nobody else thought about it before, reading about Direct2D it seems to be suited for VB. at least now it seems we will get it and I can't wait to try it!  :Smilie:

----------


## The trick

> @The Trick, Since you've been working with it - would you agree that the API lends itself to VB nicely?
> (considering that the resources are COM Objects?) 
> 
> I think Direct2D is better suited for VB than GDI and GDI+ even with class wrappers.


Seems yes, but sometimes i get crashes. (i need to check all declarations before publish). I changed little bit declarations because some methods accepts objects from DirectWrite (to any) and some methods accepts ByVal UDT, i've changed them too. Just i'm working on the helpers library *D1D2.bas* in order to we can write like in C++:


```
Option Explicit

Dim cFactory        As ID2D1Factory
Dim cRenderTarget   As ID2D1HwndRenderTarget
Dim cSolidBrush     As ID2D1SolidColorBrush

Private Sub Command1_Click()
    Dim tArea   As D2D1_SIZE_F
    Dim lX      As Long
    Dim lY      As Long
    Dim lIndex  As Long
    
    cRenderTarget.BeginDraw
    cRenderTarget.SetTransform D2D1.Matrix3x2F_Identity()
    cRenderTarget.Clear D2D1.ColorF(D2D1_COLORS.Beige)
    
    tArea = cRenderTarget.GetSize

    For lX = 0 To tArea.Width - 1 Step 10
        cRenderTarget.DrawLine lX, 0, 0, lX, cSolidBrush, 0.5
    Next
    
    For lIndex = 0 To 100
        
        cSolidBrush.SetColor D2D1.ColorF(Rnd * &H1000000)
        
        cRenderTarget.DrawEllipse D2D1.Ellipse(D2D1.Point2F(Rnd * tArea.Width, Rnd * tArea.Height), _
                                               Rnd * 50, Rnd * 50), cSolidBrush, Rnd * 5
        
    Next

    cRenderTarget.EndDraw

End Sub

Private Sub Form_Load()

    Set cFactory = D2D1.CreateFactory()
    Set cRenderTarget = cFactory.CreateHwndRenderTarget(D2D1.RenderTargetProperties(D2D1.PixelFormat()), _
                                                        D2D1.HwndRenderTargetProperties(Me.hWnd, D2D1.SizeU()))
    Set cSolidBrush = cRenderTarget.CreateSolidColorBrush(D2D1.ColorF(D2D1_COLORS.Red), ByVal 0&)
    
End Sub

Private Sub Form_Resize()
    cRenderTarget.Resize D2D1.SizeU(Me.ScaleWidth, Me.ScaleHeight)
End Sub
```

That's the real code example.

----------


## The trick

Just the progress. Direct2D requires the Windows Imaging Component to open images (if you want to open PNG, JPG and other files). I made that type library too (need to check all). The helpers library for Direct2D is done.

Also it requires DirectWrite to write text i'll do too.

----------


## baka

looking good!
checking the code you posted, I think I can learn that, it seems a bit easier then dx9.
im quite interested in the DrawBitmap function, I hope I can use it to replace gdialphablend.

----------


## DEXWERX

@TheTrick We can use a lightweight COM Object, to intercept the QI so that a D2D1CreateFactory helper can deduce the riid/IID similar to the C++ templates do with __uuidof(). I'll go ahead and post a code sample once I've got it working.

----------


## The trick

Hi DEXWERX. Okay, thanks. only i don't understand what's it for, i'll wait for you example.
Current code of CreateFactory:


```
' // Create ID2D1Factory object
Public Function CreateFactory( _
                Optional ByVal eType As D2D1_FACTORY_TYPE = D2D1_FACTORY_TYPE_SINGLE_THREADED, _
                Optional ByVal eDebugOptions As D2D1_DEBUG_LEVEL = -1) As ID2D1Factory
    Dim tOptions    As D2D1_FACTORY_OPTIONS
    Dim pOptions    As Long
    Dim cIID(1)     As Currency
    
    If eDebugOptions <> -1 Then
    
        tOptions.debugLevel = eDebugOptions
        pOptions = VarPtr(tOptions)
        
    End If
    
    ' // IID_ID2D1Factory
    cIID(0) = 506948672004902.9703@
    cIID(1) = 53149071617564.8146@
    
    Set CreateFactory = D2D1CreateFactory(eType, cIID(0), ByVal pOptions)
    
End Function
```

----------


## DEXWERX

> Hi DEXWERX. Okay, thanks. only i don't understand what's it for, i'll wait for you example.
> Current code of CreateFactory:
> 
> 
> ```
> ' // Create ID2D1Factory object
> Public Function CreateFactory( _
>                 Optional ByVal eType As D2D1_FACTORY_TYPE = D2D1_FACTORY_TYPE_SINGLE_THREADED, _
>                 Optional ByVal eDebugOptions As D2D1_DEBUG_LEVEL = -1) As ID2D1Factory
> ...


Ah I was over-thinking it. D2D1CreateFactory/DWriteCreateFactory only ever uses a single IID (IID_ID2D1Factory/IID_IDWriteFactory).
I thought CreateFactory was for other resources, based on IID. 
If It's just the one function - that creates the factory, no need to intercept the QI.

----------


## DEXWERX

Here's a copy of my Matrix3x2F class. It needs to be set to PreDeclared and the Matrix Property needs to be set to Default.



```
Option Explicit

Private m_Matrix As D2D1_MATRIX_3X2_F

Public Property Get m11() As Single
    m11 = m_Matrix.[_11]
End Property
Public Property Let m11(ByVal Value As Single)
    m_Matrix.[_11] = Value
End Property
Public Property Get m12() As Single
    m12 = m_Matrix.[_12]
End Property
Public Property Let m12(ByVal Value As Single)
    m_Matrix.[_12] = Value
End Property
Public Property Get m21() As Single
    m21 = m_Matrix.[_21]
End Property
Public Property Let m21(ByVal Value As Single)
    m_Matrix.[_21] = Value
End Property
Public Property Get m22() As Single
    m22 = m_Matrix.[_22]
End Property
Public Property Let m22(ByVal Value As Single)
    m_Matrix.[_22] = Value
End Property
Public Property Get m31() As Single
    m31 = m_Matrix.[_31]
End Property
Public Property Let m31(ByVal Value As Single)
    m_Matrix.[_31] = Value
End Property
Public Property Get m32() As Single
    m32 = m_Matrix.[_32]
End Property
Public Property Let m32(ByVal Value As Single)
    m_Matrix.[_32] = Value
End Property

Public Function Identity() As Matrix3x2F
    Set Identity = New Matrix3x2F
    Identity = IdentityMatrix
End Function

Public Function Init(ByVal m11 As Single, _
                     ByVal m12 As Single, _
                     ByVal m21 As Single, _
                     ByVal m22 As Single, _
                     ByVal m31 As Single, _
                     ByVal m32 As Single _
                     ) As Matrix3x2F
    Set Init = New Matrix3x2F
    With Init
        .m11 = m11
        .m12 = m12
        .m21 = m21
        .m22 = m22
        .m31 = m31
        .m32 = m32
    End With
End Function

Public Property Get Matrix(ParamArray Terms()) As D2D1_MATRIX_3X2_F
' This property must be set as Default
    If UBound(Terms) = -1 Then
        Matrix = m_Matrix
    ElseIf UBound(Terms) = 5 Then
        Matrix = Init(Terms(0), Terms(1), Terms(2), Terms(3), Terms(4), Terms(5))
    Else
        Err.Raise 5
    End If
End Property

Public Property Let Matrix(ParamArray Terms(), ByRef Value As D2D1_MATRIX_3X2_F)
    m_Matrix = Value
End Property

Public Function Translation(ByVal X As Single, _
                            ByVal Y As Single _
                            ) As Matrix3x2F
    Set Translation = Init( _
        1!, 0!, _
        0!, 1!, _
        X, Y)
End Function

Public Function Scale_(ByVal X As Single, _
                       ByVal Y As Single, _
                       ByVal CenterX As Single, _
                       ByVal CenterY As Single _
                       ) As Matrix3x2F
    Set Scale_ = Init( _
        X, 0!, _
        0!, Y, _
        CenterX - X * CenterX, _
        CenterY - Y * CenterY)
End Function

Public Function Rotation(ByVal Angle As Single, _
                         ByVal CenterX As Single, _
                         ByVal CenterY As Single _
                         ) As Matrix3x2F
    Set Rotation = New Matrix3x2F
    Dim M As D2D1_MATRIX_3X2_F
    D2D1MakeRotateMatrix Angle, CenterX, CenterY, M
    Rotation = M
End Function

Public Function Skew(ByVal AngleX As Single, _
                     ByVal AngleY As Single, _
                     ByVal CenterX As Single, _
                     ByVal CenterY As Single _
                     ) As Matrix3x2F
    Set Skew = New Matrix3x2F
    Dim M As D2D1_MATRIX_3X2_F
    D2D1MakeSkewMatrix AngleX, AngleY, CenterX, CenterY, M
    Skew = M
End Function

Public Function Determinent() As Single
    With m_Matrix
        Determinent = (.[_11] * .[_22]) - (.[_12] * .[_21])
    End With
End Function

Public Function IsInvertible() As Boolean
    IsInvertible = D2D1IsMatrixInvertible(m_Matrix)
End Function

Public Function Invert() As Boolean
    Invert = D2D1InvertMatrix(m_Matrix)
End Function

Public Function IsIdentity() As Boolean
    With m_Matrix
        IsIdentity = .[_11] = 1! And .[_12] = 0! And _
                     .[_21] = 0! And .[_22] = 1! And _
                     .[_31] = 0! And .[_32] = 0!
    End With
End Function

Public Sub SetProduct(ByRef A As Matrix3x2F, _
                      ByRef B As Matrix3x2F)
    m_Matrix.[_11] = A.m11 * B.m11 + A.m12 * B.m21
    m_Matrix.[_12] = A.m11 * B.m12 + A.m12 * B.m22
    m_Matrix.[_21] = A.m21 * B.m11 + A.m22 * B.m21
    m_Matrix.[_22] = A.m21 * B.m12 + A.m22 * B.m22
    m_Matrix.[_31] = A.m31 * B.m11 + A.m32 * B.m21 + B.m31
    m_Matrix.[_32] = A.m31 * B.m12 + A.m32 * B.m22 + B.m32
End Sub

Public Function Multiply(ByRef Matrix As Matrix3x2F _
                         ) As Matrix3x2F
    Set Multiply = New Matrix3x2F
    Multiply.SetProduct Me, Matrix
End Function

Public Function TransformPoint(ByRef Point As D2D1_POINT_2F _
                               ) As D2D1_POINT_2F
    With m_Matrix
        TransformPoint.X = Point.X * .[_11] + Point.Y * .[_21] + .[_31]
        TransformPoint.Y = Point.X * .[_12] + Point.Y * .[_22] + .[_32]
    End With
End Function
```

----------


## baka

i hope not forgotten. any news/issues?

----------


## DEXWERX

I can tell you it's a can of worms. Maybe we can discuss what should be in this typelib? 

*DXGI* partial - does anyone see any value in including all of DXGI?
*D2D1* almost complete - missing effects and property get/set callback support
*DWrite*  partial - missing dwrite_1 + dwrite_2 interfaces
*WIC/wincodec* complete up to Win8, missing win10 additions
*DComposition* not yet added

*edit:* all the extra APIs is possibly why trick hasn't posted a typelib yet. 
I intend to have a pretty complete typelib.

I also still need to add GDI to my GDI+ typelib.

----------


## baka

for me, what i need is:

- load a png into the memory (replace gdi32/gdi+)
- a replace to fillrect (that is used to fill any color to the hdc and is also used to clear the memorydc)
- a replace to gdialphablend (so i can copy/paste however i want)
- a replacement for textout and AddFontResourceEx (so i can load a font from file and render the text into the memoryhdc)
- a replacement to bitblt (that i use to clear the memorydc if theres a background pattern/picture instead of just fillrect)
- and finally a replacement to stretchblt (that i use to render to the picturebox)
- right now im using a loop and timer to make a fps. maybe in Direct2D is different, need some examples how to do instead.

thats it i think  :Smilie:

----------


## The trick

Hi baka.
I'm working on it when i have free time. I see DEXWERX does the same work too. What the sense to make the same task if Dex does the same? DEXWERX, do you plan to publish your type library? If so, i'll stop developing then. I see you has more much implemented things than me.
I send now my current progress with the demos. I used oleexp typelib to make compatible types (thanks fafalone).

----------


## baka

awesome! thx a bunch The trick!
I will create a new project using direct2d and see if i can re-create the game im doing in gdi. I will post the progress.

not sure whats best, you should discuss and see whats the best approach for this. maybe cooperate?
no matter what i appreciate you both taking your time for it.

----------


## baka

ok, Im now trying the typelib.
the first thing is cRenderTarget.DrawBitmap
It says: *destinationRectangle as any* but the type used in the demo is D2D1_SIZE_F that contains width and height, shouldn't it be D2D1_RECT_F instead?
it seem to work with either so maybe it doesnt matter?

another parameter is interpolationmode and I can choose between 3 (dword, linear and nearest_neighbor) 
is there a way to not use any interpolation at all? when not resizing i would not want any interpolation.
linear seems to be the best quality, what kind of interpolation is that? bilinear? bicubic? not sure what dword is but i can't use it, creates an error.

as I have a Long value for the background color I need either RGB or RGBLong.
Using ColorF2 doesnt work. Not sure if im doing it wrong, but this function seems to work for RBG:


```
Private Function RGBa(ByVal R&, ByVal G&, ByVal B&, Optional ByVal Alpha! = 1) As D2D1_COLOR_F
    With RGBa
        .R = R / 255!
        .G = G / 255!
        .B = B / 255!
        .a = Alpha
    End With
End Function
```

for Long I just do:


```
Private Function RGBL(ByVal Lng&, Optional Byval Alpha! = 1) As D2D1_COLOR_F
    Dim R&, G&, B&

    B = Lng \ 65536
    G = (Lng - B * 65536) \ 256
    R = Lng - B * 65536 - G * 256
    RGBL = RGBa(R, G, B, Alpha)
End Function
```

----------


## The trick

> It says: destinationRectangle as any but the type used in the demo is D2D1_SIZE_F that contains width and height, shouldn't it be D2D1_RECT_F instead?


What's the demo exactly?




> another parameter is interpolationmode and I can choose between 3 (dword, linear and nearest_neighbor) 
> is there a way to not use any interpolation at all? when not resizing i would not want any interpolation.


If you don't transform the image it doesn't affect. When you rotate/scale/skew - it affects (see ImageDrawings demo). dword - is not mode.




> Using ColorF2 doesnt work. Not sure if im doing it wrong, but this function seems to work for RBG:


It's work with &HAARRGGBB.

----------


## baka

demo: ImageDrawings, in Form_Load() you use D2D1.SizeF(100,100)

right now my project is using 1 picture (1024x579) that is a background with clouds.
I use the DrawBitmap function to create a moving animation that will loop the image, copying 800x579.
the animation works, but theres still stuttering every 1½ seconds. sure im just using a timer right now so its not 100% accurate.
so, now with Direct2D, what is the best way to render and to prevent stuttering?

----------


## The trick

baka, i use SizeF in CreateCompatibleRenderTarget that accepts D2D1_SIZE_F.



> I use the DrawBitmap function to create a moving animation that will loop the image, copying 800x579.
> the animation works, but theres still stuttering every 1½ seconds. sure im just using a timer right now so its not 100% accurate.
> so, now with Direct2D, what is the best way to render and to prevent stuttering?


Usually a game use a loop.

----------


## baka

The trick i was thinking about waitforvblank or VSync.
I read in a forum about calling "IDXGIObject" to access WaitForVBlank, that is called before EndDraw to sync with the monitor.

here's a "test" project (source code).
even when compiled theres some "stuttering".
https://www92.zippyshare.com/v/XJgUVYNZ/file.html

I will use a loop when I figure out things. but the timer should be enough accurate for just 1 picture.

----------


## Elroy

Baka,

Here's the code for my TimerEx also.  It uses the *QueryPerformanceCounter* & *QueryPerformanceFrequency* for a much more accurate timer than VB's Timer() function.  I've given it to you in Notepad (rather than just the code from the IDE) form so you can get the *VB_PredeclaredId = True* and *Attribute Value.VB_UserMemId = 0* settings.  Just put it into a .CLS module with Notepad, and then add to your project.  No need to declare any object variable, or anything.  Just use TimerEx like a new function in the language.

This will help if you use a Loop rather than a timer event for your frames.  I just put this in my loop to make it run at the desired speed.  It completely eliminates any pauses caused by VB's slow timer control.



```

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "TimerEx"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'
' This class has VB_PredeclaredId = True.
' Also, the Value is set to the default property.
' Therefore, TimerEx will just act like a new built-in function.
' No need to declare an object variable or explicitly instantiate.
'
Option Explicit
'
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As Currency) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As Currency) As Long
'
Private cFreq As Currency
'

Private Sub Class_Initialize()
    QueryPerformanceFrequency cFreq
End Sub

Public Function Value() As Double
Attribute Value.VB_UserMemId = 0
    ' Must be Public (not Friend) so we can set default property.
    ' Returns seconds, a double, with high-precision.
    ' Caller is responsible for keeping track of start/stop times.
    ' Basically, it works exactly like the built-in Timer function, but with much more precision.
    Dim cValue As Currency
    QueryPerformanceCounter cValue
    Value = cValue / cFreq  ' The division will return a double, and it also cancels out the Currency decimal points.
End Function


```

Best Of Luck,
Elroy

EDIT1:  Also, the units returned by TimerEx is seconds, but it's a Double and very accurate with the use of the Double's decimal points.

EDIT2:  And just to say it, I'd save the value for TimerEx at the beginning of rendering one of your cloud frames, do the rendering, and then fall into a loop, waiting for the appropriate amount of time to expire, looking at your saved time value and comparing it against more calls to TimerEx.

----------


## baka

thx Elroy, but this "test" project is just to figure out the stuttering, I do have a loop in my other game, not vb6.timer.
in my Gdi32 project I also get stuttering when I go below 100fps, that because I don't have any means to get the exact moment the monitor refreshes, that is why Im asking if we can do differently with Direct2D, otherwise I have the exact same problem with Direct2D I have with Gdi32.
no matter how precise the timer is, theres no point when we can not sync.
in my Gdi32 project, I refresh so many times that we don't notice that its not in-sync. that is why when I reach 125fps, I don't see any stuttering, its quite smooth, but still is very bad optimized and a waste of cpu.

even if we can not get any sync with Direct2D its better then Gdi32 anyway, the auto-size feature is quite neat, I dont need to do anything, Direct2D is doing it automatically, I just need to adjust the x/y mouse and thats it.

----------


## The trick

baka, Direct2D has option D2D1_PRESENT_OPTIONS where you can specify v-synch.
You can use loop like this:


```
Private Sub Form_Load()
    Me.Show
    
    Set D2D = New direct2d

    D2D.LoadImage App.Path & "\back1.png"
    
    bIsRunning = True
    
    Do While bIsRunning
    
        D2D.Render
        DoEvents
        
    Loop
    
End Sub
```

----------


## baka

nice! thx for explaining that. i dont even need to do any fps-measurements now.
is there a return variable to get the vsync rate?
I read in a forum that Direct2D uses vsync, and if used on a laptop the sync could change from 60fps to 30fps to save power.
if going slower I also need to know how fast so that I can adjust the speed of the animations.
I could get it using a timer, but if theres a parameter for it, i would save me time making one!  :Smilie:

----------


## The trick

Just use a timer like Elroy suggested and get time difference between two frames.

----------


## baka

ok. i will add the timer , i need a timer anyway as i use a "timer" in-game as i need to calculate seconds. not a big deal. thanks  :Smilie:

----------


## The trick

Updation. 

Added DirectWrite interfaces (Win7).

Examples:
Text basic drawing;
Font families enumeration;
Inline object implementation example;
Custom text renderer implementation.

----------


## wqweto

So, some samples depend on OLEEXP - olelib With Modern Interfaces by fafalone, v4.3 as far as I can see.

Can it be internalized by any of the *four* typelibs that come in the zip?

cheers,
</wqw>

----------


## The trick

wqweto,



> I used oleexp typelib to make compatible types (thanks fafalone).


I don't want to use the internal definitions of the UDTs and the interfaces because in that case we can't assign the same types defined in the different typelibs.

----------


## wqweto

> wqweto,
> 
> I don't want to use the internal definitions of the UDTs and the interfaces because in that case we can't assign the same types defined in the different typelibs.


You can both assign equal GUIDs to UDTs to create compatible structs. Assignment in VB6 should work across typelibs, although personally never tested it.

cheers,
</wqw>

----------


## The trick

> You can both assign equal GUIDs to UDTs to create compatible structs. Assignment in VB6 should work across typelibs, although personally never tested it.
> 
> cheers,
> </wqw>


Won't work.


```
Sub Main()
    Dim t1  As tlb_01.s1
    Dim t2  As tlb_02.s1
    
    t1 = t2 ' // Type mismatch
    
    test_sub t1 ' // ByRef argument type mismatch
    
End Sub

Sub test_sub( _
    ByRef t As tlb_02.s1)
    
End Sub
```

----------


## wqweto

Pity! A very unfortunate shortcoming of the current compiler and a feature request for vNext.

cheers,
</wqw>

----------


## The trick

We can use LSet to copy:


```
LSet t1 = t2
```

Anyway, we can't pass it to a function.

----------


## baka

hello, im back from a weekend trip. thanks for the DirectWrite, Its essential so its much appreciated.
2 things:

*1*
the demos, I can't make work: CustomRenderer
I get error: Compile Error, Error in Loading DLL and I get that from "Dim cCustRender As CRenderer"
everything else works.

*2*
I use AddFontResourceEx to add a custom fonts in GDI. is there a equivalent in DirectWrite?
googling I found this: https://stackoverflow.com/questions/...ile-at-runtime
but Im unsure how to do it!

----------


## The trick

1. Can you please provide screenshot? What dll exactly?
2. It isn't implemented yet. The article how to do it here.

----------


## xxdoc123

> 1. Can you please provide screenshot? What dll exactly?
> 2. It isn't implemented yet. The article how to do it here.


in my system win7 32 chinese . have error 

can you fix?

----------


## The trick

Progress.

xxdoc123, baka there is the bug in Direct2D on some OS.
ID2D1GeometrySink inherits ID2D1SimplifiedGeometrySink but if you call QueryInterface(ID2D1GeometrySink, IID_ID2D1SimplifiedGeometrySink) it raises the type mismatch error. I've fixed that error by manually casting types.

----------


## baka

questions:
Im trying to use 2 render hwnd.
one I call cTarget and is set to be rendered in picturebox1
and the other cTargetSys on picturebox2
I have tried with different approaches but always giving me the error: automation error (runtime error "-2003238891" (88990015)

first I render cTarget first, using the .presentOptions = D2D1_PRESENT_OPTIONS_NONE, with begin to end.
after that I call cTargetSys, that i using .presentOptions = D2D1_PRESENT_OPTIONS_IMMEDIATELY to make it immediately.
but I get the error.

are there any way to 2 hwnd or do I need to make it on 1 hwnd only?

----------


## The trick

Attach the project please.

----------


## baka

here the source: https://www80.zippyshare.com/v/RywqEggN/file.html

i also use a typelib (custom) that includes a bunch of API im using. i added the ODL if you want to look into it.

----------


## The trick

Updation.

Fixed bug with "Compile Error, Error in Loading DLL".
Added example with embedded fonts collection.

----------


## The trick

baka you use the resources from different render target (D2DERR_WRONG_RESOURCE_DOMAIN). You should use either the compatible resources (bitmaps created by the same render target) or use D2D1_RENDER_TARGET_TYPE_SOFTWARE flag.

----------


## baka

review of the latest build:
- SaveImage
try to run or make I get: 
Unexpected error (32810) 
at "Private Sub Form_Load()"

everything else works! the old errors are fixed. also, I can change the target flag to either SOFTWARE or HARDWARE and both works!  :Big Grin:

----------


## The trick

> try to run or make I get: 
> Unexpected error (32810) 
> at "Private Sub Form_Load()"


Please show the screenshot.

----------


## baka

original: https://postimg.cc/gallery/3geeungqk/
Attachment 159389Attachment 159391

also, the demo CustomFont loads from the resource file, how to load from external file?

----------


## The trick

baka, i can't produce that error on all my VM.




> also, the demo CustomFont loads from the resource file, how to load from external file?


It doesn't matter you can load it to a byte array from a file instead the resources.

----------


## DEXWERX

Here's a harder one, save an image from a render target using Windows 7 interfaces. (MSDN only shows the windows 8+ interfaces)

*edit:* also thanks for all the hard work on this Trick. I won't be releasing a typelib for a long time. If I do it will most likely be a large all in one typelib, including all of DirectX, sort of like SharpDX/SlimDX for VB6.

----------


## xxdoc123

> Updation.
> 
> Fixed bug with "Compile Error, Error in Loading DLL".
> Added example with embedded fonts collection.


Still shows error "load dll error"

----------


## The trick

> Still shows error "load dll error"


You should either replace tlbs or re-register them.

----------


## The trick

> Here's a harder one, save an image from a render target using Windows 7 interfaces. (MSDN only shows the windows 8+ interfaces)


Yes, but CreateWicBitmapRenderTarget works since Vista SP2. It's look like a compiler error (bug?).




> also thanks for all the hard work on this Trick. I won't be releasing a typelib for a long time. If I do it will most likely be a large all in one typelib, including all of DirectX, sort of like SharpDX/SlimDX for VB6.


Okay, then maybe i'll post that sources on CodeBank (after i add comments, fix bugs, and make more examples).

BTW, i accept the suggestions for the new demos.

----------


## baka

what kind of termination/unload should be applied for direct2d?
right now I just use Set variable$ = Nothing. 
the same when I unload a picture, and re-use the bitmap, as :

Set Image(0) = LoadImageEx(Filename) that is a ID2D1Bitmap
and when Im unloading it I use:
Set Image(0) = Nothing

is this enough of do I need to do more?
I notice that direct2d is not stable in IDE. if Im running a few times and do some changes in the project (like adding a picturebox) the IDE can crash (need to save the project before running)

----------


## The trick

baka, i don't know the reason why you have the crashes. If you provide me the project caused the crash i can see.

----------


## baka

ok, just run it once in IDE, click the "X" to quit, and add a textbox anywhere and run again. it will crash.
https://www30.zippyshare.com/v/FwjwVIvf/file.html

but if you run it again without adding anything it will run without crashing.
that is why im asking if there a termination/unload procedure.

----------


## baka

I asked in one of my previously post about the refresh rate, since D2D1_PRESENT_OPTIONS is following the monitor refresh-rate, i think its useless to calculate fps.
sure, the fps could fluctuate a bit, but nothing i want to monitor, the user need to take responsibility to not overuse the cpu/gpu when running the game, or change the refresh rate during play.

the easiest way is to use the API GetDeviceCaps with the parameter VREFRESH.
it's working on my machine and im running windows 7. 
my questions, is this compatible with all windows version, also 10? any other method that can be used?

----------


## Elroy

Hi Baka,

I haven't started messing with Direct2D.  But, as I'm sure you know, I managed to get a fairly substantial Direct3D project going, using The Trick's typelib.

One of the early problems I ran into was my FPS being faster than my monitor's refresh rate.  By default, Direct3D refreshes the screen at the monitor's refresh rate as the fastest it'll go.

However, with some digging, I found the PresentationInterval item of the D3DPRESENT_PARAMETERS structure (UDT), which is used to initialize a IDirect3DDevice9 device.   By default, it's PresentationInterval is set to D3DPRESENT_INTERVAL_DEFAULT, which won't go faster than the monitor's refresh rate.  However, if you explicitly set PresentationInterval to D3DPRESENT_INTERVAL_IMMEDIATE, the Direct3D refresh rate becomes completely detached from the monitor's refresh rate, allowing you to render frames as fast as your CPU/GPU will do it for you.  You must do this as you're instantiating your IDirect3DDevice9 device.

That solved a huge problem for me, and allowed me to make perfect sense of my FPS.

I don't know for certain, but I have to believe there's a similar setting in the Direct2D system.

Good Luck,
Elroy

----------


## baka

in D2D we got .presentOptions in the D2D1_HWND_RENDER_TARGET_PROPERTIES, where we can choose:
NONE, IMMEDIATELY and RETAIN_CONTENTS.
right now Im using "NONE", that seems to follow the monitor refresh rate (that is 60 for me)
with IMMEDIATELY it will not pause at all, and that most be the same as D3DPRESENT_INTERVAL_IMMEDIATE for D3D.

im not done with the conversion of the game, theres a lot more to do, but if i need more fps i will definitely use IMMEDIATELY and create the fps of my choosing.
but using NONE, i think theres no need to calculate fps each second, instead i use the API i mentioned before and make the calculation one time before start (the speed factor)

as i dont know the refresh-rate, and the only way to get it is by running 1 time and that could give me 59-61 instead of 60, i think GetDeviceCaps is quite useful.

----------


## baka

another issue.
i just started the project in another computer, now the aspect ratio is wrong. the same project using GDI i dont get this behavior.

it seems that the DrawBitmap is not following pixel but DPI, and will render it incorrectly. the dimension of the target picturebox is not considered.

so, if I set 800x600 the picturebox, DrawBitmap will render like 1000x750 (or something), going outside the boundaries.

looking at the code, if I enter cTarget.Resize and use 1000x750 the aspect it almost correct, but the picturebox is only 800x600
how can I let direct2d use the picturebox dimension?

----------


## The trick

https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx

----------


## baka

ha. i was about to edit/post something but you where faster.
i wanted to ask about this:



```
cTarget.GetDpi X, Y
oSize.Width = 8 * X
oSize.Height = 6 * Y
cTarget.Resize oSize
```

where the original size is 800x600 and X/Y will return 120/120 (in this monitor) and it seemed to work, but a faster fix as you posted is to simply:



```
cTarget.SetDpi 96, 96
```

thanks!  :Smilie:

----------


## baka

another thing i would like to ask/discuss is the cleanup procedure.
while coding and "testing" i get too often crashes.
right now i use "set x = nothing" to cleanup for the images and everything else.
even so sometimes when i "try again" to run, after some changes, the IDE crashes.
i need to save everytime i run. its good practice anyway but its quite annoying that it crashes.

so, if I run, and close, run and close, no crashes.
but if I run, and close, add something, and run it crashes (but not always)

----------


## fafalone

Was just reading through this thread for the first time, just wanted to note types can be cross-tlb compatible in almost all cases, it's almost always acceptable to simply change the UDT argument to a long and pass VarPtr(udt). 

I feel bad now for not finishing WIC last year; that's a lot of work and there's a half converted unincluded source file sitting in all the oleexp zips forever now.

----------


## baka

would be nice to be able to remove oleexp.tbl and only use wicvb.tbl and d2dvb.tbl.
right now oleexp.tbl is needed to run, where i move it down in the priority list and its conflicting against my custom tbl.
if i try to copy the part needed from the oleexp.tbl to my custom tbl it doesn't work.

----------


## fafalone

baka, you can get around conflicts by explicitly declaring types. Put oleexp at the bottom of the priority list, then whenever you're using something from it that's also in your custom tlb, define the module specifically; e.g. Dim var As oleexp.IWhatever -- and not just interfaces, types, enums, etc too.

----------


## baka

thx fafalone, i knew about that i could write the typelib's name to specify which one to use, but i think that a better typelib for the wic package should be complete without the need to use the oleexp.

another thing.
we have D2D1_INTERPOLATION_MODE to specify the algorithm used to scale the image.
we have: 
D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR 
D2D1_BITMAP_INTERPOLATION_MODE_LINEAR  
and its supported from 7, Vista SP2, so unfortunately no xp support.
reading in the docs, I notice that we have more algorithms
D2D1_INTERPOLATION_MODE_CUBIC
D2D1_INTERPOLATION_MODE_MULTI_SAMPLE_LINEAR 
D2D1_INTERPOLATION_MODE_ANISOTROPIC 
D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC
but are only supported from windows 8 and Platform Update for Windows 7 [desktop apps | UWP apps]
not sure what this Platform Update is, but its nothing I have.

maybe an update would be nice, even if Im still on windows 7 I will eventually move to 10 and to have 4 more

another thing about this. changing the interpolation modes doesn't seem to do much. it seems to be identical.

----------


## baka

so I read that 
D2D1_BITMAP_INTERPOLATION_MODE
has 2 modes while
D2D1_INTERPOLATION_MODE
has 6 modes

the latter is Direct2D 1.1 and should be available in windows 7 from a patch, but no vista/xp support.
the second mode require ID2D1DeviceContext and its DrawBitmap and DrawImage while the one available uses ID2D1RenderTarget : DrawBitmap
any way to add the other method?

----------


## The trick

I'm was doing the typelib which works on Win7 (because i have this one).

----------


## baka

fair enough, maybe its better to be compatible for now!  :Smilie: 

a question:
I have trouble to make the interpolation work. I know from the demo you created that it should work but not for me:

I add inside a class:
Dim InterPolationMode                   As D2D1_BITMAP_INTERPOLATION_MODE

Sub Quality(ByVal Interpolation As D2D1_BITMAP_INTERPOLATION_MODE)
    InterPolationMode = Interpolation
End Sub



```
the rendering loop is:
cTarget.BeginDraw
cTarget.Clear ClsRGB
----------------
- any amount of:
cTarget.DrawBitmap ui(index), dRect, 1, InterPolationMode, sRect
----------------
cTarget.EndDraw ByVal 0&, ByVal 0&
```

everything works, but no matter what Interpolation Im using its always D2D1_BITMAP_INTERPOLATION_MODE_LINEAR it seems. 
in the class_initialize It doesnt matter what I choose with in InterPolationMode, its always the same anyway.                   

maybe its the dRect/sRect as Im cutting parts of the graphics into a specific position.
they are both D2D1_RECT_F
also, I have a "default" pixelsize in HwndRenderTargetProperties set to 800x600 (thats the default size I use)
when I maximize the form, Im not changing anything in dRect/sRect, I let direct2d upscale. I also set cTarget.SetDpi 96, 96 so it will always use the same dpi.

----------


## The trick

Please make the small demo that produces the error.

----------


## baka

Interpolation.zip

heres the project.
the rendering will show:
cut and paste, using D2D1_RECT_F
direct rendering using SetTransform to skip D2D1_RECT_F (byval 0&)
and SetTransform using a bit of rotation and no D2D1_RECT_F
only when rotation is involved the interpolation works.

----------


## The trick

Seems all is correct. You draw the picture with original size, what's the behavior do you expect? For example if you change aspect/or sizes you can see interpolation:

----------


## baka

hm. in my testing I get this:


if I resize the window I get this (Linear up and Nearest down)


so I dont get the same as you!
as you can see in the picture, only the "rotated" pictures show different, the other 4 pictures are identical-

original pictures: (seems that the insert image is converting the pics)
https://i.postimg.cc/13fJnqsh/Image2.png
https://i.postimg.cc/Kj1Rrxzz/Image3.png

----------


## The trick

The interpolation mode is related to bitmap drawing. You should use the Resize method to ensure the proper backbuffer size. If you want to use the fixed screen (500x300) and stretch it to a window you can use an additional compatible render target in which you can draw the bitmaps. Finally you can draw the produced bitmap to the window with the needed interpolation mode (don't forget call Resize method!).

----------


## baka

hm, im trying to figure out where to put CreateCompatibleRenderTarget.
but no matter what im doing i get errors or nothing happens. the resize works, but it will not stretch the image.

lets say the small project that i shared. what do I do to have a fixed screen (500x300) and let i stretch using interpolation with the CreateCompatibleRenderTarget.?

----------


## The trick

```
Option Explicit

Dim mcFactory       As ID2D1Factory
Dim mcHwndTarget    As ID2D1HwndRenderTarget
Dim mcMemTarget     As ID2D1BitmapRenderTarget

Private Sub Form_Load()
    Dim cBrush  As ID2D1SolidColorBrush
    
    Me.ScaleMode = vbPixels
    
    Set mcFactory = D2D1.CreateFactory()
    
    Set mcHwndTarget = mcFactory.CreateHwndRenderTarget(D2D1.RenderTargetProperties(D2D1.PixelFormat()), _
                                                        D2D1.HwndRenderTargetProperties( _
                                                        Me.hWnd, D2D1.SizeU(100, 100)))
    Set mcMemTarget = mcHwndTarget.CreateCompatibleRenderTarget(ByVal 0&, ByVal 0&, ByVal 0&, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE)
    
    Set cBrush = mcMemTarget.CreateSolidColorBrush(D2D1.ColorF(BurlyWood), ByVal 0&)
    
    ' // Paint to mem target
    mcMemTarget.BeginDraw
    
    mcMemTarget.DrawEllipse D2D1.Ellipse(D2D1.Point2F(30, 30), 15, 15), cBrush, 3
    mcMemTarget.DrawLine 0, 0, 80, 90, cBrush
    
    mcMemTarget.EndDraw ByVal 0&, ByVal 0&
    
End Sub

Private Sub Form_Paint()
    
    ' // Draw to hwnd
    mcHwndTarget.BeginDraw
    
    mcHwndTarget.DrawBitmap mcMemTarget.GetBitmap, D2D1.RectF(0, 0, Me.ScaleWidth, Me.ScaleHeight), _
                            , D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, ByVal 0&
    
    mcHwndTarget.EndDraw ByVal 0&, ByVal 0&
    
End Sub

Private Sub Form_Resize()
    mcHwndTarget.Resize D2D1.SizeU(Me.ScaleWidth, Me.ScaleHeight)
End Sub
```

----------


## baka

its working! thanks a lot! i didnt think that i could use a memory-bitmap, its like i do with gdi, i thought that i could do it without. i think its quite odd that they created an automatic stretch feature but didnt include interpolation.

im doing it a bit different, without paint-event as im using a loop, but its working nevertheless.
i just replace all DrawBitmap with the memory-bitmap and at the very end, im adding:


```
Sub RenderDC()
    cTarget.EndDraw ByVal 0&, ByVal 0&
    hTarget.BeginDraw
    hTarget.DrawBitmap cTarget.GetBitmap, oRect, 1, InterPolationMode, ByVal 0&
    hTarget.EndDraw ByVal 0&, ByVal 0&
End Sub
```

where cTarget is the memory-bitmap.
oRect contains the width and height of the picturebox (im using that to render, as the form itself, when maximized will retain the aspect ratio)

----------


## baka

problem with:
Run-time Error '-2003238900 (8899000c)'
Automation Error

and it happens here: hTarget.EndDraw ByVal 0&, ByVal 0&
it occurs when I use "ctrl+alt+del" in windows 7 to bring up the "login menu"
im inside a "loop" to render animations in monitor-refresh rate.
it happens both IDE and compiled.

if I try with "On Error Resume Next" it will not work.
I also tried the GetForegroundWindow to only render when the form is active, but don't work.

any ideas?

----------


## The trick

https://docs.microsoft.com/en-us/win...2d-error-codes



> *D2DERR_RECREATE_TARGET*
> _0x8899000C_
> A presentation error has occurred that may be recoverable. The caller needs to re-create the render target then attempt to render the frame again.


https://docs.microsoft.com/en-us/win...-with-direct2d



> While your program is running, the graphics device that you are using might become unavailable. For example, the device can be lost if the display resolution changes, or if the user removes the display adapter. If the device is lost, the render target also becomes invalid, along with any device-dependent resources that were associated with the device. Direct2D signals a lost device by returning the error code D2DERR_RECREATE_TARGET from the EndDraw method. If you receive this error code, you must re-create the render target and all device-dependent resources.
> 
> To discard a resource, simply release the interface for that resource.

----------


## baka

ok, thanks for that info, i will try to create a function that will reset everything if that happens!  :Big Grin:

----------


## baka

i added 1 more loop,
do while state = 0
do while state = 0
- game & rendering -
loop
cleanup/unload
if state=1, I do another loop waiting for GetForegroundWindow=Form.Hwnd. when, it will restart direct2d and load all resources. and set state to 0
loop
terminate

in the render function Im adding a "On Error Resume Next", and CheckWindowState, if "1" D2D1_WINDOW_STATE_OCCLUDED, I know something is wrong. state is the variable I store this.
when I exit normally, with the "x" close button, i add state=2 and it will exit both loops.

----------


## xman2000

Hi, i am begginer, i not know this libraries, Direct2d, Direct3D, is open-source? 
someone know or can make a GraphicsLibary Pure VB6  like Aforge?
 the base of library with cornersDetectors, EdgeDEtectors, Thereshould, some scientifc algorithms, and next, add more features?
the algorithms of geometry in VB6 is more easy found in web, but the base of library not.
cheers!

----------


## xman2000

duplicated

----------


## Elroy

Hi xman2000,

I took a look at the AForge library, and it looks like it would take quite a bit of work to build an interface for it for a VB6 program.  However, you might be better off if you just ask for the specific functions/algorithms you want.  I know that you said, "cornersDetectors, EdgeDEtectors, Thereshould, some scientifc algorithms", but maybe you could be more specific ... especially if you're trying to get some VB6 program written and need something specific.  These forums are quite rich with many graphics and scientific algorithm solutions.

Also, when asking for these things, you may do better to start your own thread (or even start your own thread when discussing AForge).

Good Luck,
Elroy

----------


## baka

for more info about direct2d just google and check microsoft's direct2d page.
The trick created this "typelib", that need to be included in the "references" to work.
The trick created samples to try so there should be enough to get started.
theres a lot of functions to use for geometry and other things, but like any other library theres limitations so you need to create your own functions/formulas, but direct2d is enough to do any kind of graphic work and its fast, u can control dpi and it can do all the upscaling automatically. theres typelibs for directx9 as well if u want to work with 3d u can find them in this forum.
its not open source, but the typelibs are "free" and do not require dependencies except os requirements for that directx version and should be already installed.

----------


## xman2000

> Hi xman2000,
> 
> I took a look at the AForge library, and it looks like it would take quite a bit of work to build an interface for it for a VB6 program.  However, you might be better off if you just ask for the specific functions/algorithms you want.  I know that you said, "cornersDetectors, EdgeDEtectors, Thereshould, some scientifc algorithms", but maybe you could be more specific ... especially if you're trying to get some VB6 program written and need something specific.  These forums are quite rich with many graphics and scientific algorithm solutions.
> 
> Also, when asking for these things, you may do better to start your own thread (or even start your own thread when discussing AForge).
> 
> Good Luck,
> Elroy


Hi Elroy, I'm trying to motivate people to create a ImageComputerVision in PureVB6, and know about if someone done it.
Aforge.net is C# and a good start to make a VB6 library, but my intention is PureVB6 and not a wrapper, wrapper have in web like this:

Professional Image Modifier 2 Dave A. Gordon
https://code.msdn.microsoft.com/vstu...hId=1920673660

"https://code.msdn.microsoft.com/vstudio/Professional-Image-280a2421/sourcecode?fileId=107118&pathId=1920673660"

this example with Aforge.net use SUSAN Corners Detector and VB.NET and some examples have source-code others the compiled dll.

Elroy you can convert Algoritms of other Languague like C#, C++ , Python, Java, Jscript or Matlab to VB6?
i found many open-source image libraries on the web, greate alogrithms or samples, but not can convert to vb6.
I think if you can make the basis of Libary with 2 or 4 algorithms in a free to commercial use open-source, other people can add more features.

i am like corners detectors: SUSAN, FAST, AGAST
edge detection: SUSAN, CANNY, SOBEL
contour DualContour (DC) : DualContouring
image: KNN nearest neighbor, kmeans, image segmentation, image clustering
thereshould: otsu thereshould, diferentialThereshould, others
i can put the list here antoher moment, the ACCORD.NET have more algorithms that AForge.net (Accord is other version of Aforge)
if you look the source-code of ACCORD.NET you understand, but i can speak the name of most important algorithms not found in VB6 on the web.
thanks.

----------


## Elroy

Hmmm, I must be in a cantankerous mood this morning.

But, as I see it, a hijack by any other name is still a hijack. 

And I just don't understand why you don't start your own thread.  I suspect many of us have been quite motivated by trying to address clear questions in the starting post of a new thread.

----------


## xman2000

> Hmmm, I must be in a cantankerous mood this morning.
> 
> But, as I see it, a hijack by any other name is still a hijack. 
> 
> And I just don't understand why you don't start your own thread.  I suspect many of us have been quite motivated by trying to address clear questions in the starting post of a new thread.


Hi Elroy, i am not have too many knowlegde and conditions now to manage the project, but if you start a thread and start the project i am follow you or other people.
I am not able to create the basis of a Library and not to convert of other programming languages entire algorithms, but i know many others things about image procesing an the most important algorithms, i have the vision about this.
i am not found powerfull ImageLibrary in pure VB6 open-source like have in other languagues like C# Aforge.net.
i think the key is create the small structured hierarchy with few algorithms and in the future add more.
cheers!

----------


## The trick

See that project. There is the convolution-based algorithms you can use for the start point:

----------


## xman2000

Hi The Trick, i have many source-code i am collecting and yours code too.
but some algorithms i am not found in VB6 and not able to convert to VB6, i am try but gives error like illegal words (online translator).

i am begginer programmer, not professional, but i know many things about programming and image procesing.
If one people make the Basis Struture with Hierarchy and few algorithms, then, other people will translate algorithms and add to library.  Aforge.net the people translate to many other language programming.
i to my personal purpose need more CornersDetectors, DualContouring and Thereshould algorithms, but, to use to more professional cases, need a more complete library.
i am not understand the reason community of VB6 and VB.net not make a VisionLibrary like other communities.
the big problema of VB6 is not open-source and outdated.
then, is a greate think make the librarys open-source to make the language possible to update with new features and not outdated.
The trick, thanks for your contibution, se i can, i will start the project next year, but if someone want, please start the thread, leader the project.
thanks.

edit: The trick, please a compiled exe  version of this sample above?

----------


## reexre

> Hi Elroy, I'm trying to motivate people to create a ImageComputerVision in PureVB6, and know about if someone done it.
> Aforge.net is C# and a good start to make a VB6 library, but my intention is PureVB6 and not a wrapper, wrapper have in web like this:
> 
> Professional Image Modifier 2 Dave A. Gordon
> https://code.msdn.microsoft.com/vstu...hId=1920673660
> 
> "https://code.msdn.microsoft.com/vstudio/Professional-Image-280a2421/sourcecode?fileId=107118&pathId=1920673660"
> 
> this example with Aforge.net use SUSAN Corners Detector and VB.NET and some examples have source-code others the compiled dll.
> ...


You can take a look at my PhotoModularFX in signature. It is written in Vb6. 
Eventually I will make some effect public. 
Or I could help in translating algorithms from other languages to Vb6

----------


## xman2000

> You can take a look at my PhotoModularFX in signature. It is written in Vb6. 
> Eventually I will make some effect public. 
> Or I could help in translating algorithms from other languages to Vb6



reexre, YES, yes !! i know your work, your software!!
yes, please, i can send to your some algorithms, links, etc, and your translate when you have time.
please star you the new thread if you can and like, yes, greate good news my friend!!


edi: user reexre, you can download the sample file of Dave A Gordon Professional Image Modifier (vb.net) using AForge.net to study how make similar sample file using only pure VB6 and not AForge?  
i think this sample file have few files and only source-code and not DLLS.
please answer to me.

----------


## reexre

Honestly I was not going to open a new thread.
Anyway, I saw that Elroy already did it here
Hope to find even other people interested in this too.

----------


## xman2000

> Honestly I was not going to open a new thread.
> Anyway, I saw that Elroy already did it here
> Hope to find even other people interested in this too.


reexre, good new, mens at work ! thanks !

----------


## baka

im trying to figure out how to get the context of a hdc/hwnd and send it to a direct2d bitmap.
using WIC, CreateBitmapFromHBITMAP but that require hBitmap and hPalette so its not really what i need.
so they idea is: copy picture1.hdc to ID2D1Bitmap and render it to a direct2d RenderTarget.
also, it would be nice to be able to take a screenshot of any hwnd/hdc and send it to a ID2D1Bitmap.
still the examples i can find googling are based in c++.
any idea?

----------


## baka

ok i figure it out.
so, first we create a compatiblebitmap using: getdc, createcompatibledc,createCompatibleBitmap and use selectobject (u can find tons of examples for that)
what we need is: thisone = CreateCompatibleBitmap(hDC, width, height)

now we use BitBlt to take the screenshot and we store it into the created compatibledc. thats it for the gdi part.

now we use CreateBitmapFromHBITMAP to create a wicbitmap:


```
Set wicBitmap = cWICFactory.CreateBitmapFromHBITMAP(thisone, ByVal 0&, WICBitmapUsePremultipliedAlpha)
Set cConverter = cWICFactory.CreateFormatConverter()
cConverter.Initialize wicBitmap, WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, Nothing, 0, WICBitmapPaletteTypeMedianCut
```

and lastly we create a ID2D1Bitmap using:


```
Set hBitmap = hTarget.CreateBitmapFromWicBitmap(ByVal cConverter, ByVal 0&)
```

of course to render it we use BeginDraw,DrawBitmap and EndDraw

----------


## ris_vb@yahoo.com

Well , CreateDCRenderTarget and BindDC doesn't work properly ...
oleviewer shows that the type of the second paramarray of BindDC can't read ...
Error 32810(Unknown Error)

----------


## xman2000

wrong post

----------


## joaquim

- can you share a load file, draw project?
- can i get\set pixels using the HDC or hBitmap?

----------


## baka

Direct2D uses ID2D1Bitmap not hBitmap.
you can create a IWICBitmap from a hBitmap (CreateCompatibleBitmap) using the CreateBitmapFromHBITMAP from WICImagingFactory

so its possible to copy a hBitmap to IWICBitmap and make it a ID2D1Bitmap that you can use to render.
but why do you want to do that?

better work with WIC/Direct2D

I have never worked with pixel data, 
but theres tons of functions. check the property of each container and look into microsoft direct2d pages for information.

----------


## joaquim

my code is very slow  :Frown:

----------


## The trick

> my code is very slow


What's your end goal? Why do you want to manipulate pixels?

----------


## baka

in Direct2D, what u do is to paint a ID2D1Bitmap, in any way u want, and after that render the entire ID2D1Bitmap to a picturebox/form.
this should be very fast since you are working in GPU.

so, you are saying you want to use a get/set pixel. why? 
are there any other way to draw? why do you need to get? is there a purpose for that?
why can't you just load .png pictures and render those onto the screen, or use any functions, like rectangle, circle, polygons etc together with a brush of your choosing?

any manual loop takes time, 
if you want to loop through the entire screen it will slow things down,
its like, if I try to use a Sinc and Lanczos resampling it will takes a lot of time to do that. that is why I would never try to make such thing, at least not in a "real-time" situation.
Direct2D offer Nearest-neighbor and linear interpolation so Im stuck with those.

what I can do, is to use WIC, that offer WICBitmapInterpolationModeCubic that I use to resize on load, instead of real-time use of linear interpolation that is not as good.

----------


## joaquim

- we have a 3D plane(it's like a flat rectangle but on 3D world);
- using that 4 3D points, i can get the left and right(both vertical) lines points;
- using that points, we can have the origin and destination of the horizontal line;
- know the horizontal line points, we can draw the image on a pixel way.
that's why i need a pixel way... unless you can advice me a better method... and yes the 4 points can have Z different coordinates.
the Stretchblt() API don't works, for draw the entire horizontal line, because the Z can be different.

----------


## baka

working with 3D is much better with DirectX,
we have directx9 typelib by the Trick, that can deal with such things and render it fast.
Direct2D is suited for 2D work.

not sure if this is enough, its quite new but it uses DirectX11, I would also look into it first and see if its enough:
https://www.vbforums.com/showthread....0-Type-Library

but theres a lot more for DirectX9
if so check
https://www.vbforums.com/showthread....-VB6-Direct3D9
other threads of interests
https://www.vbforums.com/showthread....601&viewfull=1
https://www.vbforums.com/showthread....-getting-error

----------


## joaquim

the tutorial\book of directx9, will help me use these library? or the Trick have is own doc?

----------


## baka

check the 3 threads that is all about DirectX9, theres sources to download and examples to check.
theres no .pdf/.doc to download but theres tons of information if you check
https://docs.microsoft.com/en-us/win...9/dx9-graphics

even if the source code is not VB6, its almost the same since the name are the same.

----------


## The trick

I'll make special example.

----------


## Schmidt

> - we have a 3D plane(it's like a flat rectangle but on 3D world);
> - using that 4 3D points, i can get the left and right(both vertical) lines points;
> - using that points, we can have the origin and destination of the horizontal line;
> - know the horizontal line points, we can draw the image on a pixel way.
> that's why i need a pixel way... unless you can advice me a better method... and yes the 4 points can have Z different coordinates.
> the Stretchblt() API don't works, for draw the entire horizontal line, because the Z can be different.


The term you are looking for is "texture" (aka "some bitmap in a 3D-context")

And the problem you want solved is the "bread-and-butter"-stuff in 3D-scenarios:
 Texture-Mapping (the mapping of Bitmap-Points to arbitrary 3D-Surface-Objects).
https://en.wikipedia.org/wiki/Textur...exture_mapping

As said already, better to use a library which has builtin support for it - 
any 3D-lib (OpenGL, DirectX, etc.) will offer you:
- APIs to "upload a texture-bitmap into the GPU"
- APIs to "bind an uploaded texture to some Surface-Object" (a bunch of vertices)

Olaf

----------


## reexre

> ...As said already, better to use a library which has builtin support for it - 
> any 3D-lib (OpenGL, DirectX, etc.) will offer you:
> - APIs to "upload a texture-bitmap into the GPU"
> - APIs to "bind an uploaded texture to some Surface-Object" (a bunch of vertices)
> Olaf


About *OpenGL* could someone tell me where to find the latest version (for VB6, with some useful tutorial)
I did some research and failed.
I have OpenGL API 2.0 tbl but it seems to me it does not support Fragment Shader GLSL language (which is what interests me the most)

I am very interested in this, in fact I made a Raymarching renderer using DirectX11.
I wanted to do it with OpenGL because I think it has a better language. But I don't find tutorials and examples.
The most interesting thing I've found about OpenGL raymarching is a tutorial for Godot GameEngine. (which has a Shading Language very close to  OpenGL)

You can Download an example here of what I achieved  (for now) using Godot.

ps Merry Christmas to all !

----------


## Schmidt

> About *OpenGL* could someone tell me where to find the latest version (for VB6, with some useful tutorial)
> I did some research and failed.
> I have OpenGL API 2.0 tbl ...


That's the version I have here as well (guess, nobody out there advanced it any further).
But the good news is, that it is all "StdCall-able flat-APIs" - so, enhancements could be done via normal VB-Declares as well... 




> I wanted to do it with OpenGL because I think it has a better language. 
> But I don't find tutorials and examples.


OpenGL is nice - and the primary lib for other platforms ...
(DirectX would not be portable, therefore the 3D-classes of the RC6 will not be based on it).

As for a decent (though still kept simple) tutorial - there is one (in german language) on ActiveVB.de (numbered from chapters 1 to 8).

Below is a link to chapter3, which covers textures (which I plan to make uploadable, directly from Cairo-Surfaces)
https://activevb.de/tutorials/opengl...tchapter3.html

Here the google-translated link for english:
https://translate.google.com/transla...tchapter3.html

And (FWIW) also in italian:
https://translate.google.com/transla...tchapter3.html


Olaf

----------


## reexre

Thanks! Very interesting tutorials! (Lot to learn from)

OpenGL Typelib for VB6 doesn't seem to have the key functions to do what I want.
For example those functions found in this link
https://learnopengl.com/Getting-started/Shaders
glGetUniformLocation (shaderProgram, "ourColor");
glUseProgram (shaderProgram);
(It'd be cool there was a more updated Typelib! )

What I'm most interested in is not so much the usage of inherent functions but *the utilization of GPU speed using a Shader Language*.
This for me has two main purposes:
1) - The realization of Rendering with RayMarching technique (here done with Godot)
2) - If possible the integration of mini programs written in Shader language (GLSL/HLSL) to be used in my image manipulation program. This would speed up some Effects immensely.

As you can see in the examples already given.
The graphic results are the result of a Shader programs.
This is the HLSL for DirectX code used in the example RayMarching with DirectX11 (using wqweto typelib).
In this other example (made with Godot) inside the WindowsExport-32.pck file (to open with some text editor) you can see (glimpse) the code used to draw the _whole scene_.

For a raw speed comparison the same Scene rendered with pure VB6 takes about 1.30 -2.00 minutes per frame, while with GPU (Shader language) a fragment of a second per frame. (If I'm not mistaken something in the order of magnitude 1000X or more.)


EDIT:

*I have accomplished task one (The realization of Rendering with RayMarching technique )
using TrueVision3D as support.*

----------


## baka

a OpenGL class would be really nice to have.
a class we can simply add to any project and use it to draw lines, rectangles, bitmaps etc
including a non-gdi loading function so we can load pictures into textures directly.
not sure why nobody thought of that?

----------


## reexre

seems that someone did it (HLSL image processing)  10 years ago:

----------


## Schmidt

> ...seems that someone did it (HLSL image processing)  10 years ago...


I'm already working on GLSL support for at least the Vertex- and Fragment-shaders - 
you can expect some results at the end of next week ...

Olaf

----------


## The trick

I made the example of perspective-correct corner-pin distortion (like AfterEffects effect) using Direct3D9. It requires this type-library. You can move 4 points to change perspective effect:

----------


## joaquim

thank you so much.
i never programmed DirectX...  i have DirectX 9 tutorials, but are for C\C++.. and not VB6.. so what you can advice for i learn more?

----------


## joaquim

from C++ - Beginning DirectX 9 book(it's for C\C++), we have:


```
LPDIRECT3D9 pD3D; // the Direct3D object
LPDIRECT3DDEVICE9 pd3dDevice; // the Direct3D device
```

but your library don't have these 2 types(LPDIRECT3D9  and LPDIRECT3DDEVICE9 ).... so how can i follow for learn it?

----------


## The trick

> thank you so much.
> i never programmed DirectX...  i have DirectX 9 tutorials, but are for C\C++.. and not VB6.. so what you can advice for i learn more?


You can use C++ tutorials. If you have questions you can ask them there (this thread also contains the examples) or create a new topic in the main section.




> from C++ - Beginning DirectX 9 book(it's for C\C++), we have:
> 
> 
> ```
> LPDIRECT3D9 pD3D; // the Direct3D object
> LPDIRECT3DDEVICE9 pd3dDevice; // the Direct3D device
> ```
> 
> but your library don't have these 2 types(LPDIRECT3D9  and LPDIRECT3DDEVICE9 ).... so how can i follow for learn it?


From MSDN:



> The LPDIRECT3DDEVICE9 and PDIRECT3DDEVICE9 types are defined as pointers to the IDirect3DDevice9 interface.

----------


## joaquim

i'm sorry, if i 'atack' your topic... but believe me that i'm not the only one getting these type initial problems.
thank you so much for correct me.. and i saved that msnd link: https://docs.microsoft.com/en-us/win...pi/_direct3d9/
and heres for who needs use the DirectX8(in VB 6): http://directx4vb.vbgamer.com/DirectX4VB/TUT_DX8_DG.asp
now i can read that book without more problems
thank you so much for all.. thank you... now i can start more easely... thanks
readers: don't forget the  DirectX8 and DirectX9 have their own vb library. don't forget forget add the library on References, on Project menu.

----------


## reexre

> I'm already working on GLSL support for at least the Vertex- and Fragment-shaders - 
> you can expect some results at the end of next week ...
> Olaf


Good to know!
I have made progress using TrueVision3D to handle the shader.
All in all, the TrueVision3D tool is of a unique simplicity. (also for passing variables from VB6 to the shader)

I take this opportunity to apologize for having gone a little off topic of this thread. (topics that I hope interesting anyway)

----------


## baka

yeah, its off topic,
but I think its acceptable a few post here  and there, since its about graphics and we all want VB6 to be able to use as much possible.
but its better to make a new thread and continue in a thread with 3D in mind.

----------


## reexre

> I'm already working on GLSL support for at least the Vertex- and Fragment-shaders - 
> you can expect some results at the end of next week ...
> Olaf


Hi,
do you have something ready about it ?
If yes ( or when you have it) please post it in this other thread (or a your own thread) (... not to be off topic here)

----------


## olek_w1

Dear Sirs,

I'm first time here.  I''m vba Programmer - I'm coding mostly Microsoft Access and sometimes Microsoft Excel.  I'm very impressed by examples provided code provided here.  

I'm wondering - will it be possible to adapt this type library to be used also with Microsoft Access forms?  Currently I'm using clsPictureBox written by Stephen Lebans
but this one works with GDI32....and on modern computer the GDI32 is working very slow.

Kindly please let me know your opionion.

----------


## Black_Storm

hi guys i downloaded direct 2d samples from this threads No #40 , #53 , #64 from "the trick" and in alls samples this error in "save image" sample (windows 8 64 bit)
i see in that sample used *"OLEEXP - olelib With Modern Interfaces by fafalone, v4.3"
*i cound not find verion 4.3 but i did try by these versions and error :




image link : https://postimg.cc/Z0SpnMBj
how can fix that ?

----------


## baka

tRect what is that?
u maybe need to use the same structure from the right typelib.

remember that u can tell exactly where u get "rect"
example:
Dim tRect As oleexp.Rect
will use oleexp.Rect and not from whatever in the priority list.
try changing it using another typelibs. (check F2 to see all the typelib in use)
sometimes the IDE is confusing and will not understand.

----------


## fafalone

Weird, the version of the Direct2D library that loads when I open it has

Sub BindDC(hDC As Long)
    Member of D2DVBLib.ID2D1DCRenderTarget


No RECT member at all. Check exactly what it's expecting there. If it's a type mismatch, it might expecting a LPRECT instead, in which case object browser would show a Long as the 2nd argument and you'd pass VarPtr(tRect).

I really, really doubt it matters since the RECT definition has remained unchanged since the earliest version of the project oleexp was forked from (and a type library isn't like an active-x control or DLL; it shouldn't matter which version you're using unless the exact thing you're using has been changed-- which seems to be the case with the BindDC call in different versions of the Direct2D TLB), but if you wanted to try I'll attach v4.3

----------


## baka

also, not sure what u are doing, when I decide a render target I do:



```
    With HwndRenderTargetProperties
        .Hwnd = Main.area.Hwnd
        .pixelSize.Width = 800
        .pixelSize.Height = 600
        .presentOptions = D2D1_PRESENT_OPTIONS_NONE
    End With

    With RenderTargetProperties
        .pixelFormat.Format = DXGI_FORMAT_UNKNOWN
        .pixelFormat.alphaMode = D2D1_ALPHA_MODE_UNKNOWN
        .usage = D2D1_RENDER_TARGET_USAGE_NONE
        .minLevel = D2D1_FEATURE_LEVEL_DEFAULT
        If SoftWare Then .Type = D2D1_RENDER_TARGET_TYPE_SOFTWARE Else .Type = D2D1_RENDER_TARGET_TYPE_HARDWARE
    End With
    Set hTarget = cFactory.CreateHwndRenderTarget(RenderTargetProperties, HwndRenderTargetProperties)
```

thats my initialization.
why do u need to Bind?

----------


## Black_Storm

> tRect what is that?
> u maybe need to use the same structure from the right typelib.
> 
> remember that u can tell exactly where u get "rect"
> example:
> Dim tRect As oleexp.Rect
> will use oleexp.Rect and not from whatever in the priority list.
> try changing it using another typelibs. (check F2 to see all the typelib in use)
> sometimes the IDE is confusing and will not understand.



I didn't write any code, I just opened the sample code named "Save Image" attached in the threads #40 , #53  from "the trick"  :

and it gave an error(i did show in image before), in that version it was necessary to use version 4.3, but I didn't have version 4.3 and tested with other and newer versions. I did that it doesn't work


Now the question that has arisen is how can I coordinate this project with the newer version 5.1 of oleexp.

----------


## Black_Storm

> Weird, the version of the Direct2D library that loads when I open it has
> 
> Sub BindDC(hDC As Long)
>     Member of D2DVBLib.ID2D1DCRenderTarget
> 
> 
> No RECT member at all. Check exactly what it's expecting there. If it's a type mismatch, it might expecting a LPRECT instead, in which case object browser would show a Long as the 2nd argument and you'd pass VarPtr(tRect).
> 
> I really, really doubt it matters since the RECT definition has remained unchanged since the earliest version of the project oleexp was forked from (and a type library isn't like an active-x control or DLL; it shouldn't matter which version you're using unless the exact thing you're using has been changed-- which seems to be the case with the BindDC call in different versions of the Direct2D TLB), but if you wanted to try I'll attach v4.3



yes thanks its work now but am i use just 4.3 version only? just download that  samples from "the trick" in thread no #40 , #53 , i guess #53 is last update version and run "save Image" project with newer versions of oleexp like as 5.1,the question that has arisen is how can I coordinate this project with the newer version, 5.1?

----------


## Black_Storm

> also, not sure what u are doing, when I decide a render target I do:
> 
> 
> 
> ```
>     With HwndRenderTargetProperties
>         .Hwnd = Main.area.Hwnd
>         .pixelSize.Width = 800
>         .pixelSize.Height = 600
> ...



can you just open that save image project from thread #40 , #53.i guess #53 is last updated and just Change the project to be compatible with oleexp newer versions like as 5.1?

----------


## fafalone

> I didn't write any code, I just opened the sample code named "Save Image" attached in the threads #40 , #53  from "the trick"  :
> 
> and it gave an error(i did show in image before), in that version it was necessary to use version 4.3, but I didn't have version 4.3 and tested with other and newer versions. I did that it doesn't work
> 
> 
> Now the question that has arisen is how can I coordinate this project with the newer version 5.1 of oleexp.


Your problem isn't the oleexp version, it's the Direct2D TLB version. Check the reference, you must have another one on your system that got loaded instead of the version that came with the project. 

Use the Object Browser, navigate to the ID2D1DCRenderTarget interface, and look at what arguments it's expecting for BindDC. It's obviously not expecting a RECT, and there's no difference whatsoever between the RECT in oleexp 4.3 and the one in 5.1. And I posted 4.3 in Post #151 just so you could rule that out even though I'm 99.99% sure that's not the problem here.

----------


## Black_Storm

I did not say that the problem is from new versions of oleexp but I asked there is a way to make the trick project compatible with the newer version 5.1 if that direct 2d of the trick is old? i asked frm baka too




> the question that has arisen is how can I coordinate this project with the newer version, 5.1?


 because It seems that the only way to use the trick project (save image project) is to use version 4.1 of oleexp.i  answered in #154 about ur post in#151 about used 4.3,and of course, I had checked in the reference, it is already the same file in Project Trick,if that direct2d tlb (D2DVB.tlb) is old any new version available introduce me to download new direct tlb version ? because I couldn't find any other version and i just use that version attached in project #53 of trick.

did u try open the tick project in no #53 and check with new versions like as oleexp 4.7 or 5.1? if works for u so can attach ur direct 2d tlb version used? if not how can change code to can work with new version of 5.1 oleexp as i asked before too.

i attach again here to can download and check it from the trick attached:

----------


## fafalone

Apologies, I've never seen a bug like this before, it's truly bizarre. It's looking like D2DVB must have imported oleexp, and the object browser simply omits the 2nd argument in the object browser when there's a binary incompatibility between the tlb it was compiled against and the current TLB version, which makes it look like a completely definition than it actually is.

This won't be correctable without the source of D2DVB.tlb, which wasn't included, or a good deal of cleanup of the source generated by OLEView. 

That's a big problem with importlib statements in TLBs... even completely unrelated minor changes to the TLB import break the TLB that imports it. I've encountered somewhat similar issues before and my only conclusion is that instead of reference the type like RECT, it just uses some raw byte offset into the TLB so if the definition moves, it breaks. Edit: This does indeed seem to the case as when you load D2DVB in OLEView it loads a memory mapped section of oleexp.tlb, but can't recognize the TLB or it's types... it's basically like instead of 'Import RECT from oleexp', it's saying 'Import type at offset 0x12345678', so if it's not byte-for-byte identical, it doesn't understand it.

If The trick could post the IDL source, it would simply need to be compiled again with the current version of oleexp in SysWOW64.

----------


## The trick

There are conflicts with the newer versions of oleexp regarding to WIC. The new oleexp already has WIC declarations which are incompatible with wicvb.tlb. I can't compile this TLB because of UUID redefinitions and this TLB requires some OLEEXP types.

ADDED:

The sources of the typelib are in the attachment. I've updated the references to OLEEXP5.1 but wicvb.tlb won't work so SaveImage project won't work too. You could remove wicvb.tlb from the references and use OLEEXP interfaces declarations instead with the small modifications of the code.

----------


## fafalone

Shouldn't the original wicvb.tlb work if it's higher in the priority list than oleexp? Any definitions in 2 TLBs resolve to the one higher in the list, so "IWICImagingFactory" would resolve to "wicvb.IWICImagingFactory" if that was higher in the list. Or do you mean that had an importlib(oleexp) too so can't recompile?

----------


## The trick

> Or do you mean that had an importlib(oleexp) too so can't recompile?


This.

----------


## Black_Storm

> There are conflicts with the newer versions of oleexp regarding to WIC. The new oleexp already has WIC declarations which are incompatible with wicvb.tlb. I can't compile this TLB because of UUID redefinitions and this TLB requires some OLEEXP types.
> 
> 
> ADDED:
> 
> 
> The sources of the typelib are in the attachment. I've updated the references to OLEEXP5.1 but wicvb.tlb won't work so SaveImage project won't work too. You could remove wicvb.tlb from the references and use OLEEXP interfaces declarations instead with the small modifications of the code.





I have no experience in using this Direct 2d, can you send the "saved image" project modified to work without problem and new versions of  oleexp like as 5.1?


about your attached i saw these errors after open and run demos projects with some defaults with 4.3 oleexp and replaced with oleexp 5.1 :


about  *CustomRenderer* and *Inline object* projects these errors :
image link : https://postimg.cc/CdNf50GP







about *ImageDrawings* project this error :
image link : https://postimg.cc/vxLyRYMq







about *SaveImage* this error :
image link : https://postimg.cc/rzFwzwzW





about *Laser* its same basic drawing project :
image link  : https://postimg.cc/m1t4jhF5



can u attach modified projects to work without error?

----------


## fafalone

Honestly I have no idea how oleexp.UUID is a type mismatch for an argument expecting oleexp.UUID.

----------


## The trick

> Honestly I have no idea how oleexp.UUID is a type mismatch for an argument expecting oleexp.UUID.


wicvb.tlb refers to the types from OLEEXP4.3 whenas D2D refers to the types declared in OLEEXP5.1

----------


## The trick

Black_Storm, projects which use WIC won't work with OLEEXP5.1. It needs to modify projects according to the OLEEXP5.1 WIC declarations.

----------


## The trick

I've removed the OLEEXP references from the typelibraries (some types was redefinited like UUID and some changed to void*/IUnknown). Some projects use OLEEXP but you can use any version now because it's a VB reference not a tlb reference.

----------


## baka

my references:
- Direct2D1 v1.10
- Wincodec v1.0
- OLEEXP v5.01

so if I would update from OLEEXP 5.01 to 5.1 it will stop working?
the WIC is only used to load PNG files. with some scaling/rotating and thats it.

----------


## fafalone

> wicvb.tlb refers to the types from OLEEXP4.3 whenas D2D refers to the types declared in OLEEXP5.1


I'm talking about the version you posted in #159 that doesn't reference wicvb.tlb, and using it with oleexp 5.1.


Sidenote: If people ever wonder why oleexp is a massive single library, it's because of issues like this. The trick, would it be ok if I incorporated your D2D libraries into oleexp? I'll of course credit you.

----------


## baka

if u can incorporate wic+d2d into oleexp it would be best, at least to avoid this kind of situations.
the other alternative is to make d2d+wic its own tlb that don't need any dependencies from oleexp or other

another thing.
d2d is compatible with windows 7, so all the new features we get in windows 10 (more interpolation modes, SVG rendering etc) are not implemented.
if so it could make it not working in windows 7 anymore. 

do u think its possible to add more features without messing with compatibility?
so, say, 
if u system is windows 10 u can use a better interpolation mode, but if windows 7, it will use the default D2D1_INTERPOLATION_MODE_LINEAR

because I can't use
D2D1_INTERPOLATION_MODE_CUBIC,
D2D1_INTERPOLATION_MODE_MULTI_SAMPLE_LINEAR,
D2D1_INTERPOLATION_MODE_ANISOTROPIC,
D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC,

https://learn.microsoft.com/en-us/wi...rpolation_mode

it says Platform Update for Windows 7 (and that should be available for all windows 7, part of the updates)

----------


## The trick

> I'm talking about the version you posted in #159 that doesn't reference wicvb.tlb, and using it with oleexp 5.1.


Yes Direct2D and DirectWrite use OLEEXP5.1 in #159 post but wicvb.tlb doesn't because it has the same UUID for WIC interfaces.




> The trick, would it be ok if I incorporated your D2D libraries into oleexp? I'll of course credit you.


Yes it would be very good.

BTW why don't you use HRESULT in your WIC implementation?

----------


## fafalone

Because it's easier to check success/handle failure when you can access the HRESULT directly instead of having to rely on VB raising runtime errors and jumping into a handler.

I made sure to use them in the callback interfaces... are there others that are used with Implements that aren't using all HRESULT?

It'll be a day or two before I post the version with it merged... there's quite a bit of syntax incompatible with MKTYPLIB; oleexp can't be compiled with midl.

----------


## The trick

> I made sure to use them in the callback interfaces... are there others that are used with Implements that aren't using all HRESULT?
> 
> It'll be a day or two before I post the version with it merged... there's quite a bit of syntax incompatible with MKTYPLIB; oleexp can't be compiled with midl.


For example when use wicvb.tlb (uses HRESULT):


```
    ' // Create WIC bitmap that is saved to file
    Set cBitmap = cWicFactory.CreateBitmap(Me.ScaleWidth, Me.ScaleHeight, _
                                           WIC.GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)

    ' // Inverse half pixels
    Set cLock = cBitmap.Lock(WIC.WICRect(0, 0, Me.ScaleWidth, Me.ScaleHeight / 2), WICBitmapLockWrite)
```

If i'd use OLEEXP WIC definitions (without HRESULT):



```
    ' // Create WIC bitmap that is saved to file
    If cWicFactory.CreateBitmap(Me.ScaleWidth, Me.ScaleHeight, _
                                 WIC.GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad, cBitmap) < 0 Then
        ' error handle
    End If

    ' // Inverse half pixels
    If cBitmap.Lock(WIC.WICRect(0, 0, Me.ScaleWidth, Me.ScaleHeight / 2), WICBitmapLockWrite, cLock) < 0 Then
        ' error handle
    End If
```

The second one is like C-style coding. Nothing bad just i prefer to use [out, retval] and etc in VB.

----------


## baka

same here, I also prefer HRESULT

----------


## Black_Storm

> I've removed the OLEEXP references from the typelibraries (some types was redefinited like UUID and some changed to void*/IUnknown). Some projects use OLEEXP but you can use any version now because it's a VB reference not a tlb reference.



thanks i downloaded from post 166,all project attached work good exepct these 3 projects : 

custom font project error:



custom render project error:




save image error :




Is it not possible that these 3 projects work without the need for oleexp 5.1 (without depened)?

----------


## fafalone

I believe The trick was saying he removed the oleexp dependency *from the TLBs*, so you can use any version because only VB is referencing it and VB doesn't depend on it being byte-for-byte identical.

If you remove it entirely you'll have to replace all the constants/declares that are in it.

----------


## The trick

> Is it not possible that these 3 projects work without the need for oleexp 5.1 (without depened)?


As *fafalone* wrote i removed OLEEXP from tlbs not project references.

----------


## Black_Storm

i removed oleexp from refrences of that 3 projects and fixed these project like as this :

in *custom font* :


```
' orginal depend on oleexp
'Err.Raise E_INVALIDARG
' without oleexp
Err.Raise &H80070057
```

in *save image* : 
i redeclared this type without need oleexp now :


```
Private Type SAFEARRAYBOUND
    cElements As Long
    lLbound As Long
End Type
```

but about *custom render* project ,how can redeclare this sub movememory as i shown in post 174


```
Private Function IDWriteTextRendererImp_GetCurrentTransform( _
                 ByVal pClientDrawingContext As Long) As DWVBLib.DWRITE_MATRIX
    MoveMemory IDWriteTextRendererImp_GetCurrentTransform, mcRenderTarget.GetTransform, _
                Len(IDWriteTextRendererImp_GetCurrentTransform)
End Function
```

i can just  see this sub like as this :


```
Sub MoveMemory(pDest As Any, pSource As Any, ByteLen As Long)
```


i have another question too to i wanna do something like this :

i want show a png pic with direct 2d like as layred window and then i rotate it like as 3d with rotate effect or skew effect like this :
for example i want just rotate that png on Y and then show it like as layred window



how can do that? i hv no experience about direct 2d and show like as layred window useing direct 2d,any sample about it?
am i need use direct 2d for that rotate 3d or any sample without need direct 2d?

----------


## The trick

> how can do that? i hv no experience about direct 2d and show like as layred window useing direct 2d,any sample about it?
> am i need use direct 2d for that rotate 3d or any sample without need direct 2d?


Open *ImageDrawings* project and replace transform to:



```
    cRenderTarget.SetTransform D2D1.Matrix3x2F_SetProduct(D2D1.Matrix3x2F_Translation2(-tSize.Width / 2, 0), _
                                D2D1.Matrix3x2F(Cos(fPhase / 10), Sin(fPhase / 10) / 2, 0, 1, tSize.Width, tSize.Height / 2))
```

----------


## Black_Storm

about my question in post 177 *custom render* project ,i fixed movememory function with this declaration :


```
Private Declare Sub RtlMoveMemory Lib "kernel32.dll" (pDst As Any, pSrc As Any, ByVal ByteLen As Long)
```

and then i removed oleexp from refrences of custom render project.




> Open *ImageDrawings* project and replace transform to:
> 
> 
> 
> ```
>     cRenderTarget.SetTransform D2D1.Matrix3x2F_SetProduct(D2D1.Matrix3x2F_Translation2(-tSize.Width / 2, 0), _
>                                 D2D1.Matrix3x2F(Cos(fPhase / 10), Sin(fPhase / 10) / 2, 0, 1, tSize.Width, tSize.Height / 2))
> ```


this is my means , i just make a fake image for preview :
how can do that like as this ?
image link : https://postimg.cc/KKP78bYV


- how can centered in form?
- and still about show like as leyred window too?

----------


## Black_Storm

i found that rotate effect as i shown in post 179 and layered window with opengl by this :
https://www.vbforums.com/showthread....layered-window

----------

