GithubHelp home page GithubHelp logo

smourier / directn Goto Github PK

View Code? Open in Web Editor NEW
302.0 19.0 27.0 15.3 MB

Direct interop Code for .NET Framework, .NET Core and .NET 5+ : DXGI, WIC, DirectX 9 to 12, Direct2D, Direct Write, Direct Composition, Media Foundation, WASAPI, CodecAPI, GDI, Spatial Audio, DVD, Windows Media Player, UWP DXInterop, WinUI3, etc.

License: MIT License

C# 99.96% Batchfile 0.01% HLSL 0.04%
dotnet directx wic mediafoundation wasapi dxgi direct2d directwrite directcomposition gdi

directn's People

Contributors

riqq avatar smourier avatar vmx17 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

directn's Issues

Registering remote font file loader

Hi,
Sorry I'm here again with another problem. I follow this tutorial creating-a-custom-font-set-using-known-remote-fonts-on-the-web and everything is working except one step.
I successfully created an instance of IDWriteRemoteFontFileLoader (which inherit from IDWriteFontFileLoader), now i have to register it (step 4) using IDWriteFactory.RegisterFontFileLoader which require an IDWriteFontFileLoader as param. Should work if I pass the instance IDWriteRemoteFontFileLoader but, instead, I receive an invalid cast exception.

I don't know if I'm doing something wrong or there is a bug

Thanks

Getting pixel data from `ID2D1Bitmap1.Map()` are not correct

Hi @smourier

I create this method to get the pixel color:

private IComObject<ID2D1Bitmap1>? _imageD2D;
private IComObject<ID2D1DeviceContext6>? _device;


public byte[] GetColor(int x, int y)
{
    var bmpProps = new D2D1_BITMAP_PROPERTIES1()
    {
        bitmapOptions = D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CANNOT_DRAW | D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CPU_READ,
        pixelFormat = new D2D1_PIXEL_FORMAT()
        {
            alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED,
            format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM,
        },
        dpiX = 96.0f,
        dpiY = 96.0f,
    };


    var size = _imageD2D.GetSize().ToD2D_SIZE_U();
    using var bitmap1 = _device.CreateBitmap<ID2D1Bitmap1>(size, bmpProps);
    bitmap1.CopyFromBitmap(_imageD2D);

    var map = bitmap1.Map(D2D1_MAP_OPTIONS.D2D1_MAP_OPTIONS_READ);
    var startIndex = ((y * size.width) + x) * 4;
    var dataSize = (int)(size.width * size.height * 4);

    var bytes = new byte[dataSize];
    Marshal.Copy(map.bits, bytes, 0, dataSize);
    bitmap1.Unmap();


    var b = bytes[startIndex];
    var g = bytes[startIndex + 1];
    var r = bytes[startIndex + 2];
    var a = bytes[startIndex + 3];

    var color = new byte[] { r, g, b, a };

    return color;
}

Problems

When I debug it, with this image (4 x 4 pixels), there are 2 problems:

  1. The bytes only contains the first row of the pixel data, the rest are just 0.
  2. The pixel data with alpha (x=2, y=0) are not correct:
  • Expectation: [b=47, g=196, r=227, a=92]
  • Actual value: [b=17, g=71, r=82, a=92]

Debug data

image

Could you please help?
Thank you!

Are there any example for using geometry shader?

Are there any good sample using geometry shader? There seems no device.CreateGeometryShader(), I made *.cso in dummy C++ project, then read it with device.Object.CreateGeometryShader() like below. There seems something bad (around second variables?) returns null in geometryShader. How can I read it as shader? Is using device.Object right way? Also I'm seeking CreateGeometryShaderWithStreamOutput usage because to make fat line (line to narrow triangles).

var path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Shaders\\GeometryShader.cso");
using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open)))
{
    var buffer = reader.ReadToEnd();
    var sz = buffer.Length;
    var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.ToArray(), 0);   // ToArray() - costly
    _ = m_device.Object.CreateGeometryShader( ptr, (IntPtr)sz, null, out var geometryShader);  // out is null
    // and/or
    //_ = m_device.Object.CreateGeometryShaderWithStreamOutput(buffer, (IntPtr)buffer.Length, null,0,0,...);
}

MFCreateSourceReaderFromMediaSource function signature seems incorrect.

Thank you very much for the last corrections, it is much better now! Here I have another one which appears to me as being wrong:

MFCreateSourceReaderFromMediaSource:

C++
STDAPI MFCreateSourceReaderFromMediaSource( _In_ IMFMediaSource *pMediaSource, _In_opt_ IMFAttributes *pAttributes, _Out_ IMFSourceReader **ppSourceReader );

C#
[DllImport("mfreadwrite", ExactSpelling = true)] public static extern HRESULT MFCreateSourceReaderFromMediaSource(/* _In_ */ ref int pMediaSource, /* _In_opt_ */ IMFAttributes pAttributes, /* _Out_ */ out IMFSourceReader ppSourceReader);

The first parameter types seem to be incompatible !

Incorrect types in DWRITE_GLYPH_RUN_DESCRIPTION

Fields localeName and @string are declared as char in DWRITE_GLYPH_RUN_DESCRIPTION, but there should be string instead, or just IntPtr without marshalling. Type char is incompatible with MarshalAs(UnmanagedType.LPWStr) attribute, and when DWrite is trying to call the DrawGlyphRun method in a C# implementation of the IDWriteTextRenderer interface (that takes DWRITE_GLYPH_RUN_DESCRIPTION as an argument), the marshaler quietly returns 0, while actual managed member is not called. DWrite is pretty happy with the result and reports success too. It took me a while to figure out what had been going wrong...

GetFrameDirtyRects / GetFrameMoveRects have erroneous `out` on the buffer argument.

The GetFrameDirtyRects and GetFrameMoveRects methods in IDXGIOutputDuplication are being auto-generated with out IntPtr arguments for the buffers:

[PreserveSig]
HRESULT GetFrameDirtyRects(/* [annotation][in] _In_ */ uint DirtyRectsBufferSize, /* [annotation][out] _Out_writes_bytes_to_(DirtyRectsBufferSize, *pDirtyRectsBufferSizeRequired) */ out IntPtr pDirtyRectsBuffer, /* [annotation][out] _Out_ */ out uint pDirtyRectsBufferSizeRequired);
[PreserveSig]
HRESULT GetFrameMoveRects(/* [annotation][in] _In_ */ uint MoveRectsBufferSize, /* [annotation][out] _Out_writes_bytes_to_(MoveRectsBufferSize, *pMoveRectsBufferSizeRequired) */ out IntPtr pMoveRectBuffer, /* [annotation][out] _Out_ */ out uint pMoveRectsBufferSizeRequired);

The MSDN documentation is vague on this, but Microsoft's examples (e.g. the DuplicationManager example) make it clear that a pointer to a pre-allocated buffer is supposed to be passed in, rather than the functions passing a pointer to a buffer back out. As such, these should be IntPtr rather than out IntPtr.

The correct signature would be:

[PreserveSig]
HRESULT GetFrameDirtyRects(uint DirtyRectsBufferSize, IntPtr pDirtyRectsBuffer, out uint pDirtyRectsBufferSizeRequired);
        
[PreserveSig]
HRESULT GetFrameMoveRects(uint MoveRectsBufferSize, IntPtr pMoveRectBuffer, out uint pMoveRectsBufferSizeRequired);

Alternatively, it should be possible to do something like this to avoid having to use Marshal to do the alloc and structure copies:

[PreserveSig]
HRESULT GetFrameDirtyRects(uint DirtyRectsBufferSize, [In, Out] RECT[] pDirtyRectsBuffer, out uint pDirtyRectsBufferSizeRequired);
        
[PreserveSig]
HRESULT GetFrameMoveRects(uint MoveRectsBufferSize, [In, Out] RECT[] pMoveRectBuffer, out uint pMoveRectsBufferSizeRequired);

Although I've never done this with COM interop in particular, so it's possible there's some complexity I've overlooked in terms of array passing.

It could also be useful to add extension methods to automagically handle everything in a single call. Something along the lines of:

public static RECT[] GetFrameDirtyRects(this IDXGIOutputDuplication outputDuplication)
{
    // start with a reasonably sized buffer
    uint count = 4;
    uint size = (uint)(count * Marshal.SizeOf<RECT>());
    RECT[] rects = new RECT[count];
    // attempt to read dirty rects
    HRESULT hr = outputDuplication.GetFrameDirtyRects(size, rects, out size);
    // if we need more space, re-allocate the array based on the requested buffer size
    if (hr == HRESULTS.DXGI_ERROR_MORE_DATA)
    {
        count = (uint)(size / Marshal.SizeOf<RECT>());
        rects = new RECT[count];
        hr = outputDuplication.GetFrameDirtyRects(size, rects, out size);
    }
    // if there's still an error, return nothing (or maybe throw an exception?)
    if (!hr.IsSuccess)
    {
        return Array.Empty<RECT>();
    }
    // correct for fewer entries being returned than we asked for
    count = (uint)(size / Marshal.SizeOf<RECT>());
    return rects.Take((int)count).ToArray();
}

(plus the same kind of thing for GetFrameMoveRects)

fails in device.CreateTexture2D()

Hi! It's me, again. I'm sorry my too much questions.
Recently I hit same situation with issue #26. Because I'm using Microsoft.UI.Xaml.Controls.SwapChainPanel, I try to use DirectX resources in single thread.
I'm making a string texture to show text on D3D11 space. The texture is made by CPU. Then, the first, I made font textures using Windows.Win32.PInvoke.GetGlyphOutline.
It seems working.
The second, I try to make Texture2D using the font bitmap with CreateTexture2D() method.

My code is as follows (using DirectNCore on .Net6);

public HRESULT BuildNewStringTexture(in FONT_TEXTURE_DATA[] ftd)
{
  // make texture2d of text which can be written by CPU
  DirectN.D3D11_TEXTURE2D_DESC m_textTextureDesc = new()
  {
    Width = 500,
    Height = 250,
    MipLevels = 1,
    Format = DirectN.DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM,
    SampleDesc = new DirectN.DXGI_SAMPLE_DESC()
    {
      Count = 1,
      Quality = 0
    },
    Usage = DirectN.D3D11_USAGE.D3D11_USAGE_DYNAMIC,
    BindFlags = (uint)DirectN.D3D11_BIND_FLAG.D3D11_BIND_SHADER_RESOURCE,
    CPUAccessFlags = (uint)DirectN.D3D11_CPU_ACCESS_FLAG.D3D11_CPU_ACCESS_WRITE,
    MiscFlags = 0
  };
  lock (m_DeviceLock)
  {
    m_build_texture = true;   // a flag to make texture
  }
  // wait here for build m_texture: m_build_texture to be false;

Actually the parameters are in struct, I expand it to values above.
On the other hand, there is iterating Render() method in main thread. Then I put there

public bool Render()
{
  lock (m_DeviceLock)
  {
    if (m_build_texture)
    {
      m_texture = m_device.CreateTexture2D(m_textTextureDesc, null);
      m_build_texture = false;
    }
  ...

The issue is at the time m_texture = m_device.CreateTexture2D(m_textTextureDesc, null); executed,
I got an error saying;
"System.ComponentModel.Win32Exception: 'The parameter is incorrect.'"
Do you have any idea about this?
The error seems just a simple parameter mismatch. The MiscFlags is meanless because I specified CPUAccessFlags.
(Because this error occurred in "Main Thread", the issue #26 seems to be avoided.)
Even though I put the definition m_textTextureDesc in front of m_texture = m_device.CreateTexture2D(m_textTextureDesc, null);, I got same error.

The ID3D11Device (m_device) is created with following code.

private IComObject<DirectN.ID3D11Device> m_device;
private IComObject<DirectN.ID3D11DeviceContext> m_deviceContext;
private IComObject<DirectN.ID3D11Texture2D> m_texture;
...
  D3D_FEATURE_LEVEL[] featureLevels = new D3D_FEATURE_LEVEL[]{ D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_1 };
  var flags = D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT |  
D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_DEBUG;
  m_device = DirectN.D3D11Functions.D3D11CreateDevice(null, D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, flags, out m_deviceContext, featureLevels);

ah... I realized the way current m_device should be modified if I use device context out of Main Thread.
Are there any API to make second device context?

I defined the texture as DYNAMIC and D3D11_CPU_ACCESS_WRITE, so I'll copy font bitmaps to the m_texture after. That's not smart at all.

Thanks for building DirectN

Hello,

I just want to say thanks. I've used DirectN in my app StaxRip (new version with DirectN not released yet).

I was getting an exception (read/write to protected memory) from ID2D1DeviceContext.GetSize. I believe the bug is in Direct2D and not in DirectN, I used then the size of the Win32 window instead. In my C++ prototype it was working fine, I've seen before that native code works and managed code produces read/write to protected memory exception.

https://github.com/staxrip/staxrip/blob/master/General/VideoRenderer.vb

How to draw multiple VertexBuffer data at the same time

First of all, let me apologize that this is not a DirectN Issue.
I am currently creating a project using DirectN and am having trouble getting some of it to work.
I would appreciate a helping hand if you would be so kind.
For more information, please see the my question at stackoverflow.
i want to draw multiple vertexbuffers.

Missing function: MFEnumDeviceSources

Thank you for your great project! However, it seems to be missing an important function of Media Foundations: MFEnumDeviceSources

Is it possible to add it?

It also appears to me that the second parameter of IMFAttributes.GetAllocatorSTring() should be an [out] parameter, unless I don't understand something there...

Thanks!

Setting swap chain on WinUI 3.0 SwapChainPanel

I'm trying to set the swap chain on a WinUI 3.0 Xaml SwapChainPanel but cannot find a way to do this using C#/DirectN. (perhaps there isnt one and C++ is required??)

    public class D3D11Panel : SwapChainPanel, IDisposable
    {
    ....
    void Init()
    {
        //Create device and swap chain....
        ....
        ....
        _swapChain = fac.CreateSwapChainForComposition<IDXGISwapChain1>(DXGIDev, desc);
        SwapChainPanel mypanel = this;
            
        var sc = _swapChain.Object.As<IDXGISwapChain>();
        SwapChainPanel mypanel = this;
        var nativepanel = mypanel.As<ISwapChainPanelNative>();     //<<<<< EXCEPTION THROWN HERE
        nativepanel.SetSwapChain(sc);

System.InvalidCastException: 'Invalid cast from 'WinRT.IInspectable' to 'DirectN.ISwapChainPanelNative'.'

I cant figure out how to cast my SwapChainPanel to a DirectN.ISwapChainPanelNative. I'm really not familiar with WinRT or ComObjects and I was hoping to avoid having to dive into C++ / interop. I tried to create a DirectN.ComObject<> in various ways but cant get anything to work. (many hours trying)
Any help would be much appreciated.

Please add XMFLOAT2! orz

Hi! How are you doing? Not issue but request (as usual). Title says all.
Recently, I hit a question why DirectN does not support XMFLOAT2. I use XMFLOAT3 for position, XMFLOAT4 for color but what is for uv? It should not be Rect of Windows.Foundation nor MF_FLOAT2 of Windows.Win32....
Once I heard DirectXMath is not provided in dlls but you're providing XMFLOAT3 and 4, it is a lacking parts of plastic model kit, isn't it?
....
But!
Just I've hit an idea to use Vector2,3,4 from System.Numerics.

How to use DirectX11 with D3DImage

Hi @smourier 👋
I'm using this sample
to create my own control that I'll be using to draw some 2d stuff.
Since the SharpDX is not supported for .Net 5.0+, I've rewritten the code in sample with DirectN.
The code I ended with here but I faced a error
image

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

What I'm missing?
In what direction should I look?
Maybe there is a good sample?

Why I cannot use GSSetShader()?

Hi!
Today, I tried to figure out why I cannot use GSSetShader(). Yes, I want to set and unset (= set(null)) geometry shader. Though I've checked your extension code, they seems to have its definitions. Though I've attached following code to "Extensions\ID3D11DeviceContextExtensions.cs", there was no luck. As you mentioned #35, the m_device.Object seems to have original code (but I'm investigating other arguments).
Now I'm using version 1.15.0.2 from nuget.org but compiled version number was backdated to 1.13.x.y. Could you help me to use it?
What I'm trying to draw multiple kind of primitives and one of it use geometry shader (Texture2D) but others do not. So I set/unset in Render() method.

        public static void GSSetShader(this IComObject<ID3D11DeviceContext> context, IComObject<ID3D11GeometryShader> geometryShader, IComObject<ID3D11ClassInstance>[] classInstances = null) => GSSetShader(context?.Object, geometryShader?.Object, classInstances.ToArray());
        public static void GSSetShader(this ID3D11DeviceContext context, ID3D11GeometryShader geometryShader, ID3D11ClassInstance[] classInstances = null)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            context.GSSetShader(geometryShader, classInstances, (classInstances?.Length).GetValueOrDefault());
        }

D2D1_LAYER_PARAMETERS1 geometricMask

Hi,
I'm try to fill D2D1_LAYER_PARAMETERS1 structure to call PushLayer. If I understand correctly I have to pass my clipping geometry (as ID2D1Geometry) in the geometricMask field of this structure.

But how should I convert ID2D1Geometry to IntPtr?

Thanks

Unable to use MFEnumDeviceSources().

I tried using the function MFEnumDeviceSources() - reference issue #22 - with many different methods, but it seems quite difficult in C#. How should we proceed to access the contents of the out parameter pppSourceActivate?

I even tried making my own function signature, without success:

[DllImport("mf", ExactSpelling = true)] public static extern HRESULT MFEnumDeviceSources( ref IMFAttributes pAttributes, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] out IMFActivate[] pppSourceActivate, out uint pcSourceActivate);

Maybe with unsafe code?

Thanks a lot!

`VerticalBlankTicker` throws unknown error 0xc01e0006 when the monitor is off

Hi @smourier

As the title says, this error causes by line 122.

To reproduce

  1. Run the app
  2. Close laptop lid / turn off monitor
  3. See error

But the question is, should the ticker sleep while the monitor is off instead of throw the exception. With this way, the ticker can auto-recover again.

status = D3DKMTWaitForVerticalBlankEvent(ref we);
if (status == 0)
{
if (_tickDivider > 1)
{
smallCount++;
if (smallCount != _tickDivider)
continue;
smallCount = 0;
}
if (_throw)
{
Tick?.Invoke(null, new VerticalBlankTickerEventArgs(_ticks++));
}
else
{
try
{
Tick?.Invoke(null, new VerticalBlankTickerEventArgs(_ticks++));
}
catch
{
// continue
}
}
}
else
{
IsRunning = false;
throw new Win32Exception(status);
}

My suggestion:

do
{
  status = D3DKMTWaitForVerticalBlankEvent(ref we);
  if (status == 0)
  {
    // no change
    // ...
  }
  else
  {
    // the monitor is off, we put the thread into sleep to recover the VBTicker later
    Thread.Sleep(1000);
  }

  if (_stop)
    break;
}
while (true);

IDCompositionFlood Effect is Missing

The IDCompositionFloodEffect is missing in DirectN, The Microsoft has also removed this from dcomp.h, will it be possible to add it back, The haven't removed the docs about this Effect (IDCompositionFloodEffect - Microsoft Docs)

I Inspected the dcomp.dll, and the IDCompositionFloodEffect is still there, but there is no direct way to use it. Will it be possible to add it to direct N, or could you suggest any alternate method.

When I searched for GUID I get 949758ca-bc9c-4c51-907d-a12613639331

image

IDCompositionRectangleClip Not Working

I have been porting a C++ direct composition Code to CS, In my C++ code I use IDCompositionRectangleClip to clip the visual, it is working fine with C++, when I am trying to implement it in CS using DirectN, the visual Disappears.

in C++ I used :

ComPtr<IDCompositionRectangleClip> clip;

(dcompDevice3->CreateRectangleClip(&clip)

GetWindowRect(hwnd, &hostWindowRect);
clip->SetLeft((float)hostWindowRect.left);
clip->SetRight((float)hostWindowRect.right);
clip->SetTop((float)hostWindowRect.top);
clip->SetBottom((float)hostWindowRect.bottom);
rootVisual->SetClip(clip.Get());

dcompDevice->Commit()

The C# Code I Used:

public IComObject<IDCompositionRectangleClip> clip;

hr = dcompDevice3.Object.CreateRectangleClip(out var c);
clip = new ComObject<IDCompositionRectangleClip>(c);
if (hr != HRESULTS.S_OK)
{
       MessageBox.Show("Failed to Create Rectangle Clip");
}

clip.Object.SetLeft(50.0f);
clip.Object.SetTop(50.0f);
clip.Object.SetRight(500.0f);
clip.Object.SetBottom(500.0f);
visual.Object.SetClip(clip.Object);
dcompDevice3.Object.Commit();

This is how my Window looks like before clipping:

image

After Clipping the entire visual is missing, and only the window frame is visible:

image

Edited:

It's not only the RectangleClip not working, i tried SetOffsetX() method of the root Visual it is also having issues, the offset is not set. (in the code below i haven't used the rectangle clip just offset)

Here is the complete code i used to set offset:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DirectN;
using MessageBox = System.Windows.MessageBox;

namespace WPF_dllhost
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int left, top, right, bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct DWM_THUMBNAIL_PROPERTIES
        {
            public int dwFlags;
            public RECT rcDestination;
            public RECT rcSource;
            public byte opacity;
            public int fVisible; //BOOL{TRUE,FALSE}
            public int fSourceClientAreaOnly; //BOOL{TRUE,FALSE}
        }

        public IComObject<ID3D11Device> d3ddevice;
        public IComObject<IDXGIDevice> dxgiDevice;
        public IComObject<IDXGIFactory2> dxFactory;
        public IComObject<IDCompositionDesktopDevice> desktopDevice;
        public IComObject<IDCompositionDevice3> dcompDevice3;
        public IComObject<IDCompositionTarget> target;
        public IComObject<IDCompositionVisual2> visual;
        public IComObject<IDCompositionVisual2> rootVisual;
        public IComObject<IDCompositionRectangleClip> clip;

        IntPtr dcomp = IntPtr.Zero;

        [DllImport("dwmapi.dll", CharSet = CharSet.Auto, EntryPoint = "#147")]
        private static extern IntPtr DwmpCreateSharedThumbnailVisual(IntPtr hwndDest, IntPtr hwndSource,uint thumbnailFlags, DWM_THUMBNAIL_PROPERTIES prop,IntPtr device,out IntPtr visualout, out IntPtr thumb);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);


        public MainWindow()
        {
            InitializeComponent();
        }

        private void CreateCompositionDevice(IntPtr hwnd)
        {
            d3ddevice = D3D11Functions.D3D11CreateDevice(null, D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT, null, 7);
            if(d3ddevice==null)
            {
                MessageBox.Show("Failed to create D3D11 Device");
            }

            dxgiDevice = new ComObject<IDXGIDevice>(d3ddevice.As<IDXGIDevice>());
            if (dxgiDevice == null)
            {
                MessageBox.Show("Failed to get DXGI Device");
            }

            Functions.DCompositionCreateDevice3(dxgiDevice.Object, new Guid("5f4633fe-1e08-4cb8-8c75-ce24333f5602"), out var pdesktopDevice);
            desktopDevice = new ComObject<IDCompositionDesktopDevice>(Marshal.GetObjectForIUnknown(pdesktopDevice) as IDCompositionDesktopDevice);
            if (desktopDevice == null)
            {
                MessageBox.Show("Failed to Create Composition Desktop Device");
            }

            Guid IID_IDcompositionDevice3 = new Guid("0987CB06-F916-48BF-8D35-CE7641781BD9");
            Marshal.QueryInterface(pdesktopDevice, ref IID_IDcompositionDevice3, out var dcomp3);
            dcompDevice3 = new ComObject<IDCompositionDevice3>(Marshal.GetObjectForIUnknown(dcomp3) as IDCompositionDevice3);
            if (dcompDevice3 == null)
            {
                MessageBox.Show("Failed to Query IDCompositionDevice3 Interface");
            }

            HRESULT hr = desktopDevice.Object.CreateTargetForHwnd(hwnd, true, out var t);
            target = new ComObject<IDCompositionTarget>(t);
            if (hr != HRESULTS.S_OK)
            {
                MessageBox.Show("Failed to Create Composition Target");
            }

            hr = dcompDevice3.Object.CreateVisual(out var v);
            rootVisual = new ComObject<IDCompositionVisual2>(v);
            if (hr != HRESULTS.S_OK)
            {
                MessageBox.Show("Failed to Create Root Visual");
            }

            hr = dcompDevice3.Object.CreateRectangleClip(out var c);
            clip = new ComObject<IDCompositionRectangleClip>(c);
            if (hr != HRESULTS.S_OK)
            {
                MessageBox.Show("Failed to Create Rectangle Clip");
            }


            DWM_THUMBNAIL_PROPERTIES thumbnail=new DWM_THUMBNAIL_PROPERTIES();
            var sourceRect = new RECT
            {
                left =0,
                top = 0,
                bottom = 768,
                right =1366
            };

            var destRect = new RECT
            {
                left = 0,
                top = 0,
                bottom = 768,
                right = 1366
            };


            thumbnail.dwFlags = 0x00000010 | 0x00000008 | 0x00000001 | 0x00000002 | 0x00000004 | 0x4000000;
            thumbnail.opacity = 255;
            thumbnail.fVisible = 1;
            thumbnail.fSourceClientAreaOnly = 1;
            thumbnail.rcDestination = destRect;
            thumbnail.rcSource = sourceRect;

            DwmpCreateSharedThumbnailVisual(hwnd, FindWindow("progman",null), 2, thumbnail, dcomp3, out var desktopVisual, out var thumb);

            visual = new ComObject<IDCompositionVisual2>((IDCompositionVisual2)Marshal.GetObjectForIUnknown(desktopVisual));


            rootVisual.Object.AddVisual(visual.Object, true, null);
            rootVisual.Object.SetOffsetX(200); // not working
            target.Object.SetRoot(rootVisual.Object);
            dcompDevice3.Object.Commit();
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            new BorderlessWindow(new WindowInteropHelper(this).EnsureHandle());
            CreateCompositionDevice(new WindowInteropHelper(this).EnsureHandle());
            this.SizeChanged += MainWindow_SizeChanged;
        }

        private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
           

        }
    }
}

How can I write dynamic vertex/index buffer? Are there any example ?

In these days I've been trying to use DirectN to my drawing program for prototyping.
Now I'm stuck to make dynamic vertex buffer.
According to this article and that article, there is a way to translate vertex data via map.

I think this is a simple translation and resizing buffer matter when translate code from C++ to DirectN, please make me understand or point me the way to do.
The initialization (written in the first article) seems succeeded with code below;
(The code comes from the minimal example but DemoData is not in static array.)

var vertexBufferDesc = new D3D11_BUFFER_DESC();
var gc = GCHandle.Alloc(DemoData.VertexData, GCHandleType.Pinned);
vertexBufferDesc.ByteWidth = (uint)DemoData.VertexData.SizeOf();
vertexBufferDesc.Usage = D3D11_USAGE.D3D11_USAGE_DYNAMIC;  // changed
vertexBufferDesc.BindFlags = (uint)D3D11_BIND_FLAG.D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = (uint)D3D11_CPU_ACCESS_FLAG.D3D11_CPU_ACCESS_WRITE; // changed

var vertexData = new D3D11_SUBRESOURCE_DATA();
vertexData.pSysMem = gc.AddrOfPinnedObject();

_vertexBuffer = _device.CreateBuffer(vertexBufferDesc, vertexData);
gc.Free();

where;

  • The vertex data (just a float[]) can be obtained as "DemoData.VertexData", but this is NOT static.
  • _device is device created by D3D11Functions.D3D11CreateDevice().

Before adding new vertex, it just work fine. Just re-sizing _vertexBuffer by vertexBufferDesc.ByteWidth cause error COM object that has been separated from its underlying RCW cannot be used.. So I tried with the code (as writtend in the second article) like below but I could not find out the way to map vertex data correctly. I think the way of "map" seems differ from the way of initialization. There article's code seems no vertex/index buffer update.;

// resize vertex buffer
private void MapVertexData() {
	var mapped_resource = new D3D11_MAPPED_SUBRESOURCE();
	mapped_resource = _deviceContext.Map(_vertexBuffer, 0, D3D11_MAP.D3D11_MAP_WRITE_DISCARD, 0);
	// NG! in below line. How to map in C#/DirectN?
	Buffer.BlockCopy(DemoData.VertexData, 0, mapped_resource.pData,0,DemoData.VertexData.SizeOf());
	
	_deviceContext.Unmap(_vertexBuffer, 0);
}

Though there are no _indexBuffer, situation is same.

Some Media Foundation helper functions are not mapped

Hello. First, thanks again for this great library, I am using it extensively in my project.
Something I noticed or didn't find is that some media foundation helper functions were not mapped, for example:

MFGetAttributeSize
MFSetAttributeSize

This is so? In case they are not, is there any interest in mapping them?
Thank you

Package DirectNCore 1.9.1 is not compatible with net5.0

Hi,

I have tried to add DirectNCore to my console app but getting this error:

Install-Package : NU1202: Package DirectNCore 1.9.1 is not compatible with net5.0 (.NETCoreApp,Version=v5.0). Package DirectNCore 1.9.1 supports: net5.0-windows8.0 (.NETCoreApp,Version=v5.0)

Creating IDCompositionGaussianBlurEffect returns E_NOINTERFACE

I have been trying to create blur Effect using IDCompositionGaussianBlurEffect but when i create the effect using IDCompositionDevice3 it throws exception with this message:

System.InvalidCastException: 'No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))'

Here is the code which throws the exception :

hr = dcompDevice3.Object.CreateGaussianBlurEffect(out var gauss);

error when create uwp app release package

InvalidCSharpIdentifierName

Severity Code Description Project File Line Suppression State
Error MCG0037: MCG0037:InvalidCSharpIdentifierName Struct 'DirectN.HRESULT' in assembly 'Assembly(Name=DirectN, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, Location=*\obj\x64\Release\ilc\in\DirectN.dll)' has a field with name 'k__BackingField' that is invalid. This could be because the name is obfuscated or the field is auto-implemented by the compiler. Please make sure the field name follows C# identifier conventions.

it's working in debug mode, but not release
also I can't find a method to dispose items created, how can I destroy them from memory

Split this project into small ones

You could split this project into small ones that have especific files, ex:

Dx9, dx11, dx12, dxdi e etc.

And, of course, upload the bins into the nuget.org to make it more easy to use.

ID3D11Device is not thread-safe

Hi,
At first, thanks for creating DirectN and currently, I used DirectN for my project.
As I know ID3D11Device is thread-safe and ID3D11DeviceContext is not, but when I use ID3D11Device to create texture or any buffer in other thread, it meets the error:

'Unable to cast COM object of type 'System.__ComObject' to interface type 'DirectN.ID3D11Device'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{DB6F6DDB-AC77-4E88-8253-819DF9BBF140}' failed due to the following error: No such interface supported (0x80004002

I can work around by just using a single thread, but I'd like to use multithread in my case.
Am I missing something on this?

Thank you.

Error when resizing window

First of all I am using this library very gratefully.
I am testing directx using winui3 swapchain.

However, when resizing the window, Device.CreateRenderTargetView throws an error. [COM object that has been separated from its underlying RCW cannot be used.
]

I don't understand this error, so I can't fix it.

please help ........

public void Resize(uint width, uint height)
{
mDeviceContext.Object.OMSetRenderTargets(0, null, null);
mDeviceContext.Object.Flush();
mRenderTargetView.Dispose();
mRenderTargetView = null;

var hResult = mSwapChain.Object.ResizeBuffers(0, width, height, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0);

var frameBuffer = mSwapChain.GetBuffer<ID3D11Texture2D>(0);
mRenderTargetView = mDevice.CreateRenderTargetView(frameBuffer);

...
}

How to pass `System.Windows.Media.Imaging.BitmapSource` to `WicBitmapSource.FromSource()`

Hi, I'm playing around with this library on .NET 6
I use Magick.NET to read the image, then convert it to System.Windows.Media.Imaging.BitmapSource.

using var imgM = new MagickImage("photo.png");
System.Windows.Media.Imaging.BitmapSource src = imgM.ToBitmapSource();


using var bmp = WicBitmapSource.FromSource(src); // ERROR!

image

Is there any way to convert System.Windows.Media.Imaging.BitmapSource to WicNet.WicBitmapSource?

where is the Guid pixelFormat paramater define ?

  public static IComObject<IWICBitmap> CreateBitmap(this IComObject<IWICImagingFactory> factory, int width, int height, Guid pixelFormat, WICBitmapCreateCacheOption option = WICBitmapCreateCacheOption.WICBitmapNoCache)
   {
       return (factory?.Object).CreateBitmap(width, height, pixelFormat, option);
   }

   public static IComObject<IWICBitmap> CreateBitmap(this IWICImagingFactory factory, int width, int height, Guid pixelFormat, WICBitmapCreateCacheOption option = WICBitmapCreateCacheOption.WICBitmapNoCache)
   {
       if (factory == null)
       {
           throw new ArgumentNullException("factory");
       }

       Guid pixelFormat2 = pixelFormat;
       factory.CreateBitmap((uint)width, (uint)height, ref pixelFormat2, option, out var ppIBitmap).ThrowOnError();
       return new ComObject<IWICBitmap>(ppIBitmap);
   }

i cant find the pixelFormat

How would I implement this into a WPF Custom Control without choking the event handler?

Hello I found your comment in the visual studio dev community and have to say, this project looks very promising.

I would like to use this in my plotter project at work since Oxyplot can't handle thousands of measurement points of flow measurements and starts to chug really badly. Like you move the plot and it takes 1-2 seconds bad.
And since all our customer software is written to target Windows 10 + WPF (.Net Core and .Net Framework [nuget packages require it]) would I like to ask if someone got experience in implementing the 3D Renderer in a C# WPF Custom Control and could show/tell me how to do it with this lib, because I just don't know how with C# and WPF (Did render stuff with pure C++ barebones dx and ogl in the past, so I got already experience). would be nice to display the airflow with an actual 3D graph.

To date I tried the Microsoft Recommended method of writing the renderer as C++ DLL, and Importing the DLL Methods in C# to display something (WPF Tut for Direct3D9).
Since this is a royal pain in the ass, I went looking for an HW accelerated alternative because the Projects like ShapDX went the way of the dodo.

I hope someone can help me or give me some pointers to educate myself.

All the best,
Tobias

When running DirectN.WinUI3.MinimalD3D11 with dpi scaling enabled, the cube is not centered.

When running DirectN.WinUI3.MinimalD3D11 with dpi scaling enabled, the cube is not centered.

I have a fix for this. Lines 186, 187:

_framebufferVP.Width = framebufferDepthDesc.Width;
_framebufferVP.Height = framebufferDepthDesc.Height;

can be replaced with:

_framebufferVP.Width = framebufferDepthDesc.Width / panel.CompositionScaleX;
_framebufferVP.Height = framebufferDepthDesc.Height / panel.CompositionScaleY;

It seems that Direct3D uses screen coordinates in DIPs, not in pixels and so the viewport must be scaled accordingly.

Example for using a geometric mask to clip a region

Hi @smourier,

I'm following this tutorial: https://learn.microsoft.com/en-us/windows/win32/direct2d/how-to-clip-with-layers
to create an inverted rectangle for selection. But it does not work due to the D2D1_LAYER_PARAMETERS is not valid.

My code is as below:

var selection = new D2D_RECT_F(0, 0, 200, 100);
var rectGeo = _d2dFactory.CreateRectangleGeometry(selection);

var lp = new D2D1_LAYER_PARAMETERS()
{
  geometricMask = rectGeo.StructureToPtr(),
  maskAntialiasMode = D2D1_ANTIALIAS_MODE.D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
};

_renderTarget.BeginDraw();

_renderTarget.PushLayer(lp);
_renderTarget.DrawBitmap(...);
_renderTarget.FillRectangle(...);
_renderTarget.PopLayer();

_renderTarget.EndDraw();

And this is what I want to draw:

image

Thank you!

`Exception thrown: 'System.InvalidCastException' in WinRT.Runtime.dll` (Again?)

Hi! I'm using DirectNCore, downloaded as an NuGet package in WindowsAppSDK desktop project. Now I hit to an exception saying Exception thrown: 'System.InvalidCastException' in WinRT.Runtime.dll before calling SetSwapChain(). If you have any suggestions, please let me know. The code below;

public override void Initialize(SwapChainPanel _pnl)
{
	lock (m_CriticalLock) {
		....
		
		var scpDesc = new DXGI_SWAP_CHAIN_DESC1();
		scpDesc.Width = (uint)_pnl.ActualWidth;
		....
		IDXGIDevice1 dxgiDevice = m_device.As<IDXGIDevice1>(true);
		m_dxgiDevice = new ComObject<IDXGIDevice1>(dxgiDevice);
		m_swapChain = fac.CreateSwapChainForComposition<IDXGISwapChain1>(m_dxgiDevice, scpDesc);
		....
		var nativepanel = _pnl.As<ISwapChainPanelNative>();	// <<<< Exception thrown here.
		if (nativepanel != null) {
			nativepanel.SetSwapChain(m_swapChain.Object);
		} else {
			throw new InvalidCastException("a SwapChainPanel could not be cast to DirectN.ISwapChainPanelNative");
		}
		....
	}
}

The _pnl is SwapChainPanel I specified in XAML as Microsoft.UI.Xaml.Controls.SwapChainPanel. Though there was similar subject, I could not figure out how microsoft.ui.xaml.media.dxinterop.h concerns. The <<peek definition>> shows decompiled result;

[ComImport]
[Guid("f92f19d2-3ade-45a6-a20c-f6f1ea90554b")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISwapChainPanelNative
{
	[PreserveSig]
	HRESULT SetSwapChain(IDXGISwapChain swapChain);
}

The Guid seems differ from the article.
My environment VS2022Pro 17.6.1, .Net 6.0, WindowsAppSDK, all packages are latest fixed.

Compatibility with .Net Core 3.1 and above.

In an attempt to use this lib in a .Net Core 3.1 the compiler issues this warning:

warning NU1701: Package 'DirectN 1.9.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETCoreApp,Version=v3.1'. This package may not be fully compatible with your project.

There are any plans to support .Net Core ?

Add Samples of Direct Composition

Hi, I have been having trouble with DirectN when I use with Direct Composition, There is not much place to refer about this, could you add more samples on direct composition. like the example from here.

This sample uses all d3d11, d2d1 and direct composition, it would be helpful, if you could add samples like this.

Various problems...

Thank you for your last correction! I was able to progress in my test of DirectN.

  1. Now it seems that DMOs are missing, like this one, for instance:

CColorConvertDMO (CLSID_CColorConvertDMO)

  1. Guids are missing like: CODECAPI_AVEncCommonQuality

  2. This enum of DirectN is far from user friendly:

public enum __MIDL___MIDL_itf_mfreadwrite_0000_0001_0001 { MF_SOURCE_READER_INVALID_STREAM_INDEX = -1, MF_SOURCE_READER_ALL_STREAMS = -2, MF_SOURCE_READER_ANY_STREAM = -2, MF_SOURCE_READER_FIRST_AUDIO_STREAM = -3, MF_SOURCE_READER_FIRST_VIDEO_STREAM = -4, MF_SOURCE_READER_MEDIASOURCE = -1, }

  1. When I call the following function with valid parameters:

Functions.MFGetAttributeRatio(pType, MFConstants.MF_MT_FRAME_RATE_RANGE_MAX, out uint frameRateNum, out uint frameRateDem).ThrowOnError();

I get the error:

System.EntryPointNotFoundException : 'Unable to find an entry point named 'MFGetAttributeRatio' in DLL 'mfplat'.'

  1. Also, in order to replace the C++ function __uuidof, I wrote the following, because I did not find how in DirectN. You can include it, if needed:

public Guid __uuidof<T>() { var attribs = Attribute.GetCustomAttributes(typeof(T), typeof(GuidAttribute)); foreach (GuidAttribute attrib in attribs) { if (attrib.GetType() == typeof(GuidAttribute)) return new Guid(attrib.Value); } return new Guid(); }

a missing member of DXGI_FORMAT

Hello!
I think "DirectN.DXGI_FORMAT.DXGI_FORMAT_A4B4G4R4_UNORM" is missing. It's value is 191. It seems the most recently added member.
And I discovered 'DXGI_FORMAT_FORCE_UINT (-1)'. Are there any situation I can utilize it?

Capture by Window Hwnd

Hi,

I have tried to capture the window by using its hwnd but still, I am getting the front(desktop) image. Is it possible to get a specific window's image by using DirectN?

class Program
    {
        static void Main()
        {
            // capture 10 shots and saves them as PNG
            // this is a C# port of https://stackoverflow.com/a/30138664/403671

           var hwnd = ..... // a MainWindowHandle of the sepecific process.

            Direct3D9TakeScreenshots(hwnd, Constants.D3DADAPTER_DEFAULT, 10).ThrowOnError();
        }

        static HRESULT Direct3D9TakeScreenshots(IntPtr hwnd, uint adapter, int count)
        {
            using (var d3d = new ComObject<IDirect3D9>(Functions.Direct3DCreate9(Constants.D3D_SDK_VERSION)))
            {
                var mode = new _D3DDISPLAYMODE();
                d3d.Object.GetAdapterDisplayMode(adapter, ref mode).ThrowOnError();

                var parameters = new _D3DPRESENT_PARAMETERS_
                {
                    Windowed = true,
                    BackBufferCount = 1,
                    BackBufferHeight = mode.Height,
                    BackBufferWidth = mode.Width,
                    SwapEffect = _D3DSWAPEFFECT.D3DSWAPEFFECT_DISCARD,
                    hDeviceWindow = hwnd, // !!!!! SET HWND !!!!!!
                };

                d3d.Object.CreateDevice(adapter, _D3DDEVTYPE.D3DDEVTYPE_HAL, hwnd  /* !!!!! SET HWND !!!!!! */, Constants.D3DCREATE_SOFTWARE_VERTEXPROCESSING, ref parameters, out var dev).ThrowOnError();
                using (var device = new ComObject<IDirect3DDevice9>(dev))
                {
                    dev.CreateOffscreenPlainSurface(mode.Width, mode.Height, _D3DFORMAT.D3DFMT_A8R8G8B8, _D3DPOOL.D3DPOOL_SYSTEMMEM, out var surf, IntPtr.Zero).ThrowOnError();
                    using (var surface = new ComObject<IDirect3DSurface9>(surf))
                    {
                        var rc = new _D3DLOCKED_RECT();
                        surf.LockRect(ref rc, IntPtr.Zero, 0).ThrowOnError();
                        var pitch = rc.Pitch;
                        surf.UnlockRect();

                        var shots = new byte[count][];
                        for (var i = 0; i < count; i++)
                        {
                            shots[i] = new byte[pitch * mode.Height];
                        }

                        var sw = new Stopwatch();
                        sw.Start();
                        for (var i = 0; i < count; i++)
                        {
                            dev.GetFrontBufferData(0, surf).ThrowOnError();
                            surf.LockRect(ref rc, IntPtr.Zero, 0).ThrowOnError();
                            Marshal.Copy(rc.pBits, shots[i], 0, shots[i].Length);
                            surf.UnlockRect().ThrowOnError();
                        }
                        Console.WriteLine("Elapsed: " + sw.Elapsed);

                        for (var i = 0; i < count; i++)
                        {
                            SavePixelsToFile32bppPBGRA(mode.Width, mode.Height, (uint)pitch, shots[i], "cap" + i + ".png", WICConstants.GUID_ContainerFormatPng).ThrowOnError();
                        }
                    }
                }
            }
            return 0;
        }

        static HRESULT SavePixelsToFile32bppPBGRA(uint width, uint height, uint stride, byte[] pixels, string filePath, Guid format)
        {
            if (filePath == null)
                throw new ArgumentNullException(nameof(filePath));

            using (var fac = new ComObject<IWICImagingFactory>((IWICImagingFactory)new WicImagingFactory()))
            {
                fac.Object.CreateStream(out var stream).ThrowOnError();
                using (new ComObject<IWICStream>(stream))
                {
                    const int GENERIC_WRITE = 0x40000000;
                    stream.InitializeFromFilename(filePath, GENERIC_WRITE).ThrowOnError();
                    fac.Object.CreateEncoder(format, IntPtr.Zero, out var encoder).ThrowOnError();
                    using (new ComObject<IWICBitmapEncoder>(encoder))
                    {
                        encoder.Initialize(stream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).ThrowOnError();
                        encoder.CreateNewFrame(out var frame, out var bag).ThrowOnError();
                        using (new ComObject<IWICBitmapFrameEncode>(frame))
                        {
                            frame.Initialize(null).ThrowOnError();
                            frame.SetSize(width, height).ThrowOnError();
                            frame.SetPixelFormat(ref format).ThrowOnError();
                            frame.WritePixels(height, stride, (int)(stride * height), pixels).ThrowOnError();
                            frame.Commit().ThrowOnError();
                            encoder.Commit().ThrowOnError();
                        }
                    }
                }
            }
            return 0;
        }
    }

missing a way to pass 'D3D_COMPILE_STANDARD_FILE_INCLUDE' macro to shader compiler

Hi
Thanks for your great work on DirectN ! FYI I'm switching my game project from SharpDx to DirectN, so I might be posting a few issues or missing stuff I find along the way...

Here's one :
In regular DirectX, a shader can be compiled with the pInclude parameter set to D3D_COMPILE_STANDARD_FILE_INCLUDE to use a default include handler. Looks like this macro isn't available in DirectN, and as far as I can find, there isn't an equivalent constant which can be passed instead.
And while we're in the compiler, I also could not find the definition for D3DXSHADER Compiler flags.
Thanks

IDirect3DVertexBuffer9 Lock Usage

Hello,
I need an help for using DirectN with Directx9.
I am using the IDirect3DVertexBuffer9 Lock method, but since this required an IntPtr, I am not able to understand how translate from c++ to c# code.
In c++ I am using this code

VERTEX* vertices; HR(m_pVertexBuffer->Lock(0, 0, (void**)&vertices, D3DLOCK_DISCARD)); ::memcpy(vertices, vertexArray, sizeof(vertexArray)); return m_pVertexBuffer->Unlock();
while in c# should become something similar
`nint ppbData = nint.Zero;
if ((hr = _vertexBuffer.Object.Lock(0, 0, ppbData, Constants.D3DLOCK_DISCARD)).IsError) { return hr; }
var gc = GCHandle.Alloc(vertexArray, GCHandleType.Pinned);

    gc.Free();

    return _vertexBuffer.Object.Unlock();`

I don't understand if I am on right way, or is totally messed up.
How should I complete it?
I don't know if i need to "allocate" the lock ppbData, and in which way.

Thank you for any support.

GetMatchingFonts - FontSet

Hi,
I don't know if it is a bug or if I'm missing something; I can't get IDWriteFontSet.GetMatchingFonts to work I always get Access Violation exception. This is my sample code:

HRESULT hr = DWriteFunctions.DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, typeof(IDWriteFactory7).GUID, out object factory);
if (factory == null)    
   return;           
IDWriteFactory7 dwritef = (IDWriteFactory7)factory;
hr = dwritef.GetSystemFontSet(out IDWriteFontSet fontSet);
hr = fontSet.GetMatchingFonts("Arial",      <-- calling this method generate exception
            DWRITE_FONT_WEIGHT.DWRITE_FONT_WEIGHT_REGULAR,
            DWRITE_FONT_STRETCH.DWRITE_FONT_STRETCH_NORMAL,
            DWRITE_FONT_STYLE.DWRITE_FONT_STYLE_NORMAL,
            out IDWriteFontSet filteredSet);

I tried different IDWriteFactory interfaces (IDWriteFactory3 to IDWriteFactory7) and different IDWriteFontSet interfaces, but I always get same exception

Any idea? I'm doing something wrong?
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.