Introducing the Microsoft Direct2D API


One of the challenging aspects of working on a product development team is that you often have to keep the subject of your work secret for various reasons. I’m a Dev Lead in the Windows Desktop Graphics organization, and my team has been working quietly for the past year on an exciting new graphics technology – Direct2D –that was announced recently at the Professional Developer’s Conference (PDC) in Los Angeles.


 


Direct2D (or D2D) is a native immediate-mode 2D graphics rendering API that is built on top of Direct3D, and offers some compelling performance and visual quality improvements over GDI and GDI+:


·         Hardware-acceleration


·         Software fallback when hardware isn’t available


·         Interoperability with GDI, GDI+, and Direct3D


·         ClearType text rendering


·         Per primitive antialiasing


·         Device-independent coordinate system


·         Draw and fill commands for geometries (lines, curves) and bitmaps


·         Solid color, linear, radial, and bitmap brushes.


·         Rendering to intermediate layers


·         Rich geometry operations (eg. unions, intersections, widening, outlining, etc)


·         Server-side rendering


·         Preservation of rendering state


 


Since Direct2D is now public, I can finally talk about it, and this blog is intended to provide a forum for sharing information and tips. I encourage you to send me your feedback and comments, and I will share them with the rest of the development team. While I can’t promise that we’ll act on every piece of feedback, we will take everything that you submit seriously, and we will use the data to better understand your development priorities.


Back to the Future


Do we really need another 2D API? To answer this question, we need to backtrack a little bit and discuss some ancient graphics history. Windows applications continue to rely overwhelmingly on GDI/GDI+ 2D graphics technologies that were designed for hardware that shipped in the 1990’s. Hardware in that era was optimized largely for simple, fixed-function scenarios (eg. BitBlt, StretchBlt, DrawRect , etc). Modern graphics hardware has evolved dramatically since that time. Much of the processing that used to occur in software has now migrated down to the video card’s Graphics Processing Unit (GPU) in the form of programmable pixel and vertex shaders; which increase performance by moving pixel data closer to where it will be manipulated & consumed, in massively parallel (SIMD) fashion. These changes have staggering implications for graphics applications. Expensive pixel-processing operations can be offloaded from the CPU to the GPU which, in turn, frees the CPU to take on other useful tasks, such as creating rich UI, driving animations, doing computations, etc. It also allows applications to scale up primitive counts dramatically with minimal CPU impact.


One of the first proposals on the table was to update GDI/GDI+ to take advantage of these technologies; however, as we surveyed the requirements, we ran into some fundamental limitations that would have made the effort very difficult. For example, GDI/GDI+ are limited to 32 bits-per-pixel, and there’s a ton of stuff – both public and internal – that would need to be revamped or extended (eg. RGBQUAD, COLORREF, PALETTEENTRY) to support high dynamic range pixel formats beyond 32 bits-per-pixel. Similarly, there are quality and performance issues: modulo ClearType text, GDI can only produce aliased graphics (jaggies) and, while GDI+ can render anti-aliased graphics, it can only do so in software. GDI uses an integer coordinate system, so it can’t take advantage of improvements related to sub-pixel positioning. Another fundamental problem is that GDI/GDI+, and Direct3D are wholly separate graphics subsystems, with their own formats, memory structures, and synchronization constructs. Getting all of these moving parts to work in unison would have been a huge challenge, to say the least, so we went back to the drawing board to consider an alternative proposal:  to create a new 2D graphics stack on top of Direct3D — which would interoperate with the latest Direct3D hardware — while also providing a migration path for GDI and GDI+ applications.


When we compared the development costs of these two proposals, it became clear that creating a new graphics stack would take far less time, would avoid destabilizing the huge number of GDI and GDI+ applications, and would enable us to provide a more cohesive, interoperable, and forward-thinking API. So, we embarked on building the new API, which went through several geeky name changes, until it emerged from the primordial acronym-soup as Direct2D. This isn’t surprising, given that my team is part of the same group that produces Direct3D. It was a natural fit.


Basic Goals


 


We started with some fundamental goals for Direct2D:


 


·         Native Code – Should be accessible to the widest possible community of developers. Minimal footprint for native code callers, and also callable by managed code.


·         Lightweight COM – Should use C++ style interfaces which model Direct3D usage. No support for proxies, cross-process remoting, BSTRs, VARIANTs, COM registration (e.g. the heavyweight stuff).


·         Immediate Mode – Simple BeginDraw/Draw/EndDraw semantic. No expensive retained tree structures.


·        Hardware – Should leverage available hardware for rendering.


·         Scalable – Pay-for-Play. Performance and memory usage should scale as linearly as possible while primitive counts increase. No hidden costs. Hardware improvements should scale performance accordingly.


·         Policy-Free – Should impose as little policy as possible on callers; that is, it should seek to do no more (and no less) than what the caller expects it to do. Minimal amount of abstraction.


·         Software Fallback – Should automatically fall back to software when hardware isn’t available (eg. session 0, server rendering scenarios).


·         High Quality Output – Should produce superb anti-aliased and aliased content. ClearType for text.


·         High Performance – Should leverage GPU hardware as much as possible and minimize CPU usage.


·         Interoperable – Should permit rendering to and from a Direct3D surface, as well as to and from a GDI/GDI+ device context (HDC). Serialization of content to and from surfaces and device contexts must be explicit and predictable. Should work seamlessly with other native Windows technologies (DirectWrite, Windows Imaging Codecs, etc).


·         Direct3D 10.1 – Should utilize D3D10.1 (and/or D3D10Level9) for hardware support.


·         Device-Independent Coordinate System – Should allow applications to be written that automatically handle DPI changes and differences.


·         Rich Geometry – Should provide a rich set of functions for both defining geometries and performing common geometric operations (eg. combining, intersecting)


 


 


 


PerfDemo Chomp


ChartDemo


 





Direct2D Team Members


I want to thank the following folks for their tireless passion and dedication to making D2D possible:



Mark Lawrence, Chris Raubacher, Tom Mulcahy, Anthony Hodsdon, Miles Cohen, Ben Constable, Leonardo Blanco, Alexander Stevenson, Megha Jain, Kam VedBrat, Andy Precious, Brett Bloomquist, Bilgem Cakir, Chris Chui, Bob Brown, Samrach Tun, Sriya Blanco, Jason Hartman


Furthermore, I’d like to acknowledge the following folks for understanding the importance of this new technology and funding the effort:



Anuj Gosalia, Anantha Kacherla, Jeff Norris, Todd Frost


Additional Materials




Watch the Platform Overview PDC session: https://channel9.msdn.com/pdc2008/PC04/


Watch the Direct2D and DirectWrite PDC session: https://channel9.msdn.com/pdc2008/PC18/

Also, I’m posting a Direct2D whitepaper that was distributed at the PDC. Future posts will drilldown into interesting code examples.

 


More Direct2D Blogs


Tom Mulcahy — Tom is a Software Design Engineer on the Direct2D team, and owns a good swathe of infrastructure (bitmaps and texture management, WIC interop, clipping, etc). Prior to Direct2D, Tom worked on WPF and is widely regarded as our resident video guru.
http://blogs.msdn.com/tmulcahy/default.aspx



Mark Lawrence — Mark is a Senior Software Design Engineer on the Direct2D team, and driving force behind the design and philosophy of the Direct2D API. He brings a ton of experience from his previous work on WPF, Windows Print architecture, and private industry.
http://blogs.technet.com/MarkLawrence/


 


Ben Constable — Ben is a Senior Software Design Engineer on the Direct2D team, and implemented all of the Direct3D and GDI Interop functionality within Direct2D. He is a self-described “graphics nerd” who brings  considerable experience in 2D and 3D rendering to the team, and has contributed to numerous Microsoft products (Visual Studio, Windows, Office, SQL, etc).


http://blogs.msdn.com/bencon/


 

PDC08_Introducing Direct2D.docx

Comments (148)

  1. Thomas.Olsen says:

    @Yamada: “Can D2D off anti-alias ?”

    ID2D1RenderTarget::SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);

    If you pair Direct2D aliased rendering with Direct3D MSAA (Multisample Antialiasing — ie. full scene antialiasing), you should get better performance with high primitive count scenarios.

  2. On XP support. We will chain that up to management. To answer your question on Device Independent Pixels (DIPs).

    A device independent pixel is a logical pixel that maps to the physical device pixels through a scalar called the “DPI”. DPI stands for Dots Per Inch. And to further unravel this, a dot means a physical device pixel. (The nomenclature comes from printing
    where dots are the smallest ink dot that a printer can produce). Since a standard monitor used to have 96 dots per inch, a DPI of 96 means that a device independent pixel (or DIP) maps 1:1 with a physical pixel. So, if, for example, the DPI were 96*2 = 192,
    then a DIP would in fact encompass two physical pixels. When the user adjusts the “size” of what’s on the screen, what they are actually modifying is this internal scalar, which is known as the system DPI. There are many reasons why applications don’t necessarily
    handle this correctly, but, one of the simplest is that they have to do all of the heavy lifting of working out how to use this scalar value to do their rendering. In D2D, this is applied by default. You might realize that by doing this mapping, physical device
    pixels might end up at fractional DIP coordinates this is (one of) the reasons why it is also important that D2D have a floating point coordinate space.

    DIPS -> Pixels: pixel = (dip * DPI) / 96.

    Pixels-> DIPS:  dip = (pixel * 96) / DPI.

  3. Thomas.Olsen says:

    1. Will there be support for video playback.

    Yes, with certain caveats. Since we interop with Direct3D, you will be able to take frames (D3D surfaces) from a DirectShow filter graph, and render them using D2D. Keep in mind that DirectShow currently uses Direct3D9, while D2D uses Direct3D10.1, so you will need to use a Direct3D9 shared surface. We are currently working up a sample that shows how to do this. Stay tuned.

    2. Will it run on Windows XP? I assume not…

    Not currently. We’ve had a number of customers asking for XP, and we’re still evaluating downlevel support. As above, stay tuned.  😉

  4. Thomas.Olsen says:

    @jq: “I have tried d2d sample in windows 7 7057.It seems does’t work.D2D1CreateFactory return E_NOINTERFACE. But it works on build 7022 and 7000.”

    You can’t just mix and match the Beta Direct2D headers/libs with any random Windows build. We have made some changes to the Direct2D interfaces with subsequent builds and, every time we do that, we automatically regenerate new interface GUIDs. What that means is that you can’t use older headers/libs with newer builds. This avoids the problem where you’re calling interfaces with a different v-table than the actual binaries you’re using, which could cause a crash. Returning E_NOINTERFACE tells us immediately that you’re using mismatched headers/libs.

    My advice would be to wait until the Windows RC build, and use the Windows RC SDK with it. Obviously, I can’t promise that we won’t change any interfaces beyond that point, but the probability is very, very low.

  5. Thomas.Olsen says:

    Gentlemen, I’ve been asked to have you forward your questions to the DX blog from now on. It will help other people get more visibility to Q&A.

    http://blogs.msdn.com/DirectX/

    Thanks!

    Tom

  6. Thomas.Olsen says:

    I’m not terribly familiar with the whole DirectX paradigm, which may be why I’m wondering what the difference is between D2D and the (now apparently deprecated) DirectDraw. Wasn’t that also hardware-accelerated? At first glance it looks like it was dropped then resurrected and rebranded, but something tells me that’s not the case.

    DirectDraw is a deprecated technology that was all about providing hardware frame buffer access to applications, so that they could do very fast display blits and frame flipping. DirectDraw, itself, didn’t provide drawing commands for rendering high-quality 2D text, geometries, bitmaps, etc. Direct2D does. Plus, Direct2D interoperates with the latest versions of Direct3D.

  7. Thomas.Olsen says:

    @Tom

    To add to Mark’s comments, we really DO want to see both positive and negative feedback about the API. Even if we don’t necessarily agree with the conclusions of a particular piece of feedback, it doesn’t mean that we don’t want to understand that person’s point of view. We do. This is a learning process for all of us, and everything that you tell us informs our architectural decisions. Sometimes, it isn’t exactly obvious why we’ve made certain choices, but we really do try to be exhaustive in going over scenarios — evaluating, questioning, probing, debating; nonetheless, we’re only human, so it helps to have more eyes looking over our shoulders. Our primary consideration, whenever there’s been a tough decision, has been to yield more control to the developer. We understand that this won’t please all people but, then again, this API isn’t for all people. Our challenge has been to build something flexible enough to allow other developers to build GDI/GDI+, control frameworks, plug-ins, applications, etc, with our solution. Time will tell whether we’ve made the correct choices. So, by all means, we’d like to hear about what you’re building with D2D, problems you encounter, challenges, suggested improvements, etc. Keep ’em coming — we read and appreciate everything.

  8. Thomas.Olsen says:

    Questions posed in email from a reader: 

     Hi, I just read your blog post introducing Direct2D, and it looks really interesting.

    I have a few questions though:

    1. When can we expect to see it? The Nov 2008 DXSDK is probably too soon to hope for.

    The bits will be available in prerelease form to MSDN subscribers and PDC attendees. We tried to hit the November DX SDK date, but there wasn’t enough time to get all of our dependencies ready. I’m trying to get clarity on the actual public release date. Will let you know. 

    2. How much control do we have over how it renders the 2-d content?

    It’s a fairly comprehensive 2D graphics API. You have a ton of control.

    3. Can we use programmable vertex/pixel shaders with it? In our current graphics engine, we have a number of shaders specifically for 2-d sprite quads that render in various special ways.

    Yes, you can, but you need to do it via Direct3D interop. The API does not directly expose pixel/vertex shaders. I’m making a note to create a sample which shows how to do it.

    4. What is this Direct3D10Level9 that you are talking about?

    D3D10Level9 is a special adapter for D3D10 which allows it to use D3D9 drivers. So, for example, if you only have a D3D9 driver, D3D10 could still run — which greatly broadens the reach of D3D10. It will be available on Windows 7. 

    5. When Direct2D is released to the public, could the dx sdk include a sample showing how to use Direct2D for rendering a simple gui over a Direct3D app?

    We will have a sample which shows you how to do this. But not in the Nov DX SDK.

  9. Thomas.Olsen says:

    @Vertex:

     To 3.: If Direct3D10.0 hardware is available: Does Direct2D fall back to Direct3D 10Level9 or does it use Direct3D 10.0?

    Direct2D will use Direct3D 10 if a Direct3D 10.1 driver is installed; otherwise, we will fallback to Direct3D 10Level9.

    Two more questions: Let’s say someone wants to use Direct2D instead of existing GDI/GDI+ implementations. Is there anything missing in Direct2D, when replacing GDI/GDI+? (I know that you can use them together, but what I am talking
    about is only using D2D)

    Direct2D provides much of the functionality contained in GDI/GDI+. We have a smaller subset of ROPs.

    Second question: Does the software rendering of Direct2D use WARP10?

    No. Although you can use WARP in conjunction with Direct2D via DXGI interop.

    Just my thoughts (and maybe already a requirement for D2D2 sitting in front of you): It would be nice if things like geometry tessellation and other heavy CPU tasks would be ported to D3D11. ->Heavy offload to GPU. Maybe with a next
    big release, lets say D3D11.1 or whatever (at least when WARP11 gets shipped).

    Thank you for the feedback. We are interested in moving more CPU funtionality to the GPU.

    + …as far as I tested, you did great job with D2D!

    Thank you. We’ve made some performance improvements in the RC build. Please give it a try and, as always, we appreciate your feedback!

  10. Thomas.Olsen says:

    1. If you create a sample that really really works and even better, a managed wrapper – that’d be awesome.

    Samples will be posted relatively soon. Not sure about the availability of a managed wrapper. We’re still discussing that. 

    2. XP is important in gaming industry. Not the one for the PCs but rather the one that delivers games on cabinets (i.e. casino machines).

    I will pass your feedback on to my management. Thank you for letting us know what you need/want. 🙂

  11. @ Yamada

    Yeah, I am not saying that the debate is closed on MetaFiles, Drawings, or other retained structures in D2D, I would say that we do need to understand the primary application usage for them based on further customer interaction. The space is really crowded with XAML, XPS and EMF(+) already out there and we want to make sure we do the right thing (TM).

    However, here is a thought I would like to leave you with:

    * Texture creation is REALLY expensive in HW. Except under extremely narrow conditions, geomtric brushes have to be rendered through intermediate surfaces, and these intermediate surfaces need to be of different sizes each time they are drawn. It has been our experience that HW renderers that try to hide this have issues with predictability, performance and/or cost.

    * Absent a metafile implementation internally, and a set of optimizations around this, there just isn’t a huge difference between the application issuing the drawing calls and us doing it for them.

  12. Thomas.Olsen says:

    Regarding GDI/GDI+ – has GDI/GDI+ been ported so that it sits ontop of Direct2D? specifically, under Vista it was unaccelerated – given the number of applications dependent on GDI (and I assume the widget kits in Windows), will this happen?

    No, we really wanted to port GDI+ to use D2D, but the scope was way beyond possible for this release. But we’re definitely interested in the idea.

  13. Thomas.Olsen says:

    @Viktor

    I tried drawing with a HwndRenderTarget and then with a DCRenderTarget. In the first case the CPU usage is 0%, in the second case it is 60-70%. Is the the GDI interop taking that much CPU or is it me missing something ? I am simply drawing a rectangle at random locations on screen as fast as possible.

    Hi, Viktor. Are you using the Windows 7 Beta? Or the DX SDK on Vista? We have made a lot of performance improvements to Direct2D in the Windows 7 RC build.

  14. Thomas.Olsen says:

    Could you please ask your team about SERIOUSLY considering implementing polygon clipping AND hit testing?

    Direct2D supports both polygon clipping and hit-testing. Here’s a quick example of how you’d clip two geometries. The geometries can be any type of supported
    geometry (lines, beziers, etc), and it should be noted that ID2D1Geometry::CombineWithGeometry will preserve polygons; that is, beziers will remain beziers, etc. One additional note. Geometries do not provide a direct way to extract their  line or curve
    data. If you need to access that data, you should implement your own ID2D1SimplifiedGeometrySink object and pass it in to
    ID2D1Geometry::CombineWithGeometry. Direct2D will then call the ID2D1SimplifiedGeometrySink
    object that you supply (SetFillMode, SetSegmentFlags, BeginFigure,
    AddLines, AddBeziers, EndFigure) during the CombineWithGeometry. This will permit you to access the line and curve data for the resulting figure(s), so you can persist them or whatever.
     

    HRESULT ClipGeometries(

        __in ID2D1Geometry *pGeometry1,

        __in ID2D1Geometry *pGeometry2,

        __in D2D1_COMBINE_MODE combineMode,

        __in_opt CONST D2D1_MATRIX_3X2_F *inputGeometryTransform,   

       
    __out ID2D1PathGeometry **ppOutGeometry)

    {

        CComPtr<ID2D1GeometrySink> spGeometrySink;

        CComPtr<ID2D1PathGeometry> spOutGeometry;

     

        IFR(m_spFactory->CreatePathGeometry(&spOutGeometry));

        IFR(spOutGeometry->Open(&spGeometrySink));

     

        IFR(pGeometry1->CombineWithGeometry(
            pGeometry2,
            combineMode, //D2D1_COMBINE_MODE_UNION, …_INTERSECT, …_XOR, …_EXCLUDE

            inputGeometryTransform,
    //can be NULL
            spGeometrySink
            ));

     

        IFR(spGeometrySink->Close());

        *ppOutGeometry = spOutGeometry;

        return S_OK;

    }

     

    Here’s how you hit test. This method tells you whether the selected point is on a widened stroke.

     

        HRESULT
    ID2D1Geometry::StrokeContainsPoint(

            D2D1_POINT_2F point,

            FLOAT strokeWidth,

            __in_opt ID2D1StrokeStyle *strokeStyle,

            CONST D2D1_MATRIX_3X2_F &worldTransform,

            __out BOOL *contains

            );

     

    This method tells you whether a given point is contained within a given geometry.

       

        HRESULT
    ID2D1Geometry::FillContainsPoint(

            D2D1_POINT_2F point,

            CONST D2D1_MATRIX_3X2_F &worldTransform,

            FLOAT flatteningTolerance,

            __out BOOL *contains

            );

     

  15. Thomas.Olsen says:

    @dave:

    “I am so glad that the C++ Lighweight COM approach was used. I was worried that Direct2D was going to managed route and this would be terrible. The lighweight COM approach works very well.”

    Thanks for the feedback.

  16. Thomas.Olsen says:

    Direct2D looks excellent.

    Thanks.  

     I’m new to graphics programming (currently working on a charting application written in MFC) so this is likely to be a silly question but.. will Ican I already program using Direct2D using MFC or will I need to use Win32?

    Not a silly question. Currently, you would need to use Win32; however, we are definitely interested in having frameworks such as MFC, WinForms, and others (which currently use GDI or GDI+) use D2D.

  17. Anonymous says:

    1. If you create a sample that really really works and even better, a managed wrapper – that’d be awesome.

    2. XP is important in gaming industry. Not the one for the PCs but rather the one that delivers games on cabinets (i.e. casino machines).

  18. Thomas.Olsen says:

    “Server-side rendering” Does this mean support for RDP?

    This is a two-part answer. Direct2D is built on top of Direct3D 10.1 and, since D3D10.1 provides both bitmap- and primitive-level remoting via RDP, it does mean support for RDP.

    But there’s another point to made here, too. Server-side rendering also means that you can render high quality anti-aliased content using Direct2D in server environments where, for example, you would not be able to use Direct3D. We will automatically fall back to software in those scenarios. And we are considerably faster than GDI+.

    Also, are there any accessibility issues at this point?  

    Can you be more specific? We are a 2D rendering API. Other than text, we have no policy regarding layout.  

    And, what will it take for broad adoption?  Unfortunately, there seems to be a dearth of WPF apps.

    Developers should use whatever tool is appropriate for their needs. If you’re writing native C/C++ code, and you need to do high-quality 2D rendering with hardware acceleration on Win7, you should use Direct2D. If you’re using managed .NET code, you should use WPF.  The technologies are not in competition.

    I don’t know D2D would help, but currently many of our apps are quite inconsistent about their ClearType handling–sometimes ClearType is applied to text, but then in another dialog (or even in the same dialog!), you can clearly see that no font smoothing is applied.  

    Direct2D uses DirectWrite typography APIs to do font management, layout, and glyph coverage. Font smoothing is applied consistently using DWrite; in fact, DWrite goes further than previous ClearType implementations by doing y-axis smoothing, which yields unparalleled text quality.

    Is there any way existing apps can leverage D2D (without being rewritten), or is this just wishful thinking on my part?  Could GDI/GDI+ commands somehow be mapped onto a D2D renderer, gaining of its benefits (or at least some)?

    Yes, I’m glad you asked. Direct2D supports interoperability with both GDI/GDI+ and Direct3D. So, for example, you could do one of a couple things:

     1. You could create a Direct2D render target; then, whenever you need to render GDI content, you QI the render target for IGdiInteropRenderTarget, call GetDC on that interface, BeginDraw, render the GDI stuff to the resulting HDC, and EndDraw.

    2. You create a DC render target, call BindDC to your GDI HDC, BeginDraw, draw the D2D content, and then EndDraw.

     I’ll discuss GDI/GDI+ interop in more depth in an upcoming post. But, to answer your question, it’s built-in. You don’t need to rewrite your app to use Direct2D.

  19. @ Tom again

    If you really want to get creative with meshes and HW based rendering, we also have extensive DXGI interop support. See the "SciFiText" sample.

  20. Thomas.Olsen says:

    @Jack Harris: “I’m getting an E_NOINTERFACE on the D2D1CreateFactory call and I have the last version of Windows 7 (RC 7100) and the RC version of the SDK. I also installed Visual Studio 10 (Beta 1).  Need help!!!! “

    Jack, you have some kind of header/lib mismatch with the D2D binaries. Check to make sure that you’re not picking up D2D headers from either VS10 Beta 1 or from the DXSDK. If you pick up the wrong headers, you will be passing the wrong RIID as the second parameter to D2D1CreateFactory, we won’t recognize it, and we’ll return E_NOINTERFACE. The prescribed place to get the RC headers/libs is the RC WinSDK. Hope that helps. Let me know if you continue to have problems.

  21. Anonymous says:

    hello.

    Great post.I expect also future post.

    I have an unclear thing, does D3D10 GPU run as D3D10Level9 device for D3D10.1?

  22. Thomas.Olsen says:

    For those who are wondering how to create a Direct3D10 or Direct3D10Level9 device.

     HRESULT CreateD3DDevice(
       __in IDXGIAdapter *pAdapter,
       D3D10_DRIVER_TYPE DriverType,
       UINT Flags,
       __deref_out ID3D10Device1 **ppDevice
       )
    {
       HRESULT hr = E_FAIL;

       static const D3D10_FEATURE_LEVEL1 levelAttempts[] =
       {
           D3D10_FEATURE_LEVEL_10_0,
           D3D10_FEATURE_LEVEL_9_3,
           D3D10_FEATURE_LEVEL_9_2,
           D3D10_FEATURE_LEVEL_9_1,
       };

       for (UINT level = 0; level < ARRAY_SIZE(levelAttempts); level++)
       {
           hr = D3D10CreateDevice1(
               pAdapter,
               DriverType,
               NULL,
               Flags,
               levelAttempts[level],
               D3D10_1_SDK_VERSION,
               ppDevice
               );

           if (SUCCEEDED(hr))
           {
               break;
           }
       }
       return(hr);
    }

  23. Thomas.Olsen says:

    Very cool – A lot of familiar names on the “making it possible” list 🙂

    Rajat … Rajat … the name sounds very familiar… 😉

    I read the whitepaper and saw the integration with WIC. However, what is unclear is can I pass WIC a ID2D1Bitmap to decode directly into (potentially a HW decode)? If not, is this planned for Windows 7? I am a very interested party 🙂

    WIC did a fair bit of prototyping of decoding in hardware, but the metadata, TIFF, and progressive decode work was higher priority. Interesting perf note: We compared doing Map/decode/Unmap on a D3D surface to decoding into a system memory buffer and calling UpdateResource on a D3D surface — and found that the latter was actually faster.

     – Any plans on the Windows 7 team introducing a retained mode API?

    Not in Windows 7. 

    – Also curious what “Server side rendering” means?

    It means we can run in server environments using software fallback.

    – Does the API remote automagically through RDP? If so, what is the compatability story: ie. Will it remote from Windows 7 -> Vista client?

    There are 2 types of remoting a Direct2D app via RDP: bitmap remoting and Direct3D primitive-level remoting. Look at the D2D factory and render target properties for details on how to specify one versus the other.

    – Related to the previous question: What version(s) of D3D does this run on? Will it be backwards compatible?

    It runs on Direct3D 10.1, which includes so-called 10Level9 functionality — which allows you to run D3D10.1 apps on a D3D9 driver.

    ie. Can I run it on Vista?

    We are discussing downlevel support now. Keep posted. 

    Thanks!

    You’re welcome. 🙂

  24. Thomas.Olsen says:

    Hey thanks for posting the answers to my questions. Those samples would be great to have.

     

    I’m curious still about this Direct3D10Level9 adapter. What exactly is the point of an adapter to let D3D10 use a D3D9 driver?

     

    It’s all about reach. There are a fairly broad number of D3D9 drivers available on the market right now.
     Xbox360 runs on D3D9, as do most current PC games. D3D10 is gaining adoption, but it will take time. The advantage of providing a way to use D3D9 drivers from D3D10 is that it allows developers to code to a single API – D3D10 – so that
    they don’t have to write two sets of code.

     

    Since, you certainly wouldn’t be able to use any of the new D3D10 features, as the D3D9 driver certainly wouldn’t have a clue about
    how to implement them.

     

    That’s not entirely accurate. There is a reasonably broad subset of the D3D10 features which will run on D3D9; albeit with differing performance
    and quality characteristics. No, D3D9 doesn’t do everything, but it does a lot. The D3D team has done an excellent job in trying to match feature sets of the two APIs via D3D10Level9.

     

    Any D3D10 level hardware is certainly going to have a D3D10 level driver for it, or its D3D10 features are useless. Particularly,
    in regards to Windows 7, as I imagine it needs new/modified drivers to be written for it anyways. Unless you are planning to use Direct2D in the Windows 7 gui. But, you still wouldn’t be able to use any D3D10 specific features, so, why not write a D3D9 version
    of Direct2D instead? (which would also enable Xp support and support for old (but still commonly in use) hardware)

     

    Like you, we, too, are customers of D3D10 and D3D10Level9. It allows us to code to a single API, while still getting all the perf benefits of
    D3D10.

     

    Or unless you are planning on releasing D3D10 for Xp, but, that seems extremely unlikely due to the massive differences between
    Vista and Xp, and is contrary to everything I’ve heard from Microsoft with regards to that.

     

    There are no plans at present to port D3D10 to XP. The driver models are very different.

     

    A few more general questions for you (feel free to answer on your blog):

    1. You mentioned support for D3D10.1, but, what about regular D3D10? Since there’s no support from Nvidia for D3D10.1, what happens
    there?

     

    D3D10.1 drivers are a logo requirement for Win7.
     

     

    2. Will there be D3D11 support as well? Or will that require Direct2D2?

     

    D3D11 will provide compatibility with prior versions.

     

    3. Will there be support for using Direct2D with Direct3D9?

     

    Yes, to a point, but the support is essentially provided through D3D9 shared surfaces. We had a earlier question about how to render video decoded
    into D3D surfaces. We’ll have a sample which demonstrates how that works.

     

    4. Compared to rendering screen-aligned quads, how does Direct2D perform?

     

    There’s no quick answer to your question. It depends on a lot of variable factors: what kind of hardware are you using, what is the driver overhead
    for state changes, how many drawing primitives are you trying to perform, etc. Similarly, since we continue to make perf advancements in the D2D rendering code, what you see today will not be what you see in the final RTM release.

     

    5. Interally, does Direct2D work by generating and rendering screen-aligned quads, or is it more of a true bitblt DirectDraw style
    rendering?

     

    I can’t discuss internal implementation issues.

     

    6. Is this the end of ID3DXSprite and ID3DXFont?

     

    Not yet. D3DX will continue to live on. But, like everything else, there were undoubtedly be changes to D3DX. Time and technology march onward.

     

  25. Thomas.Olsen says:

    Looks like a great rendering layer for VG.net.

    Agree. Looks like a nice fit. VG.net looks very cool, btw.

    We’ve been waiting for something like this from Microsoft for years.

    So have we. 😉

    We would also love XP support.

     I’ll pass that on to my management. Thanks for the feedback.

  26. Thomas.Olsen says:

    First of all, i was waiting for a API like this for long time: i am using now GDI+ for 2D stuff and Direct3D for 3D stuff but sure Direct2D seem to be more suitable for mixing 2D and 3D in the same application. Great work !

    Thanks! 

    You say that DIP should be 1/96 inch: why not use 72 DPI instead ? It is because 1 pt = 1/72 inch and so with DIP of 1/72 inch we have exactly 1 pixel = 1 point and point seem to be a more suitable standard for device independant pixel than arbitrary 1/96.

    A DIP is 1/96 inch by default because that’s the default system DPI.  But a DIP is really an arbitrary unit that isn’t tied to any particular DPI. In fact, it’s trivial to override the default to your own preferred unit. For example, just call ID2D1RenderTarget->SetDPI(72.0f, 72.0f).

  27. Thomas.Olsen says:

    @Te-jé Rodgers:

    1, We will take a look at the ScrollWindow issues. Thanks for letting me know.

    2. Can you provide a snippet of code that illustrates how you’re creating the window and rendering the bitmap? The position of the bitmap should be relative to the top left corner of the window and the transform that you use.

  28. Thomas.Olsen says:

    Wow, that is seriously sweet. I can’t wait to start playing with this stuff. I know having access to this stuff is going to radically benefit all my programming.

    Glad to hear that, sysrpl. Always happy to answer any more questions that you have. 🙂

  29. Thomas.Olsen says:

    @John: Can we expect Direct2D on the next Windows Embedded Compact (not Standard) platform? (previously known as Windows Embedded CE or Windows CE)

    I can’t comment on future product plans for Direct2D at this time.

  30. @Keith again…

    Also, we have evaluated the sample. The brushes can be created and released at any time and don’t have to be held over the lifetime of the render target. This was just an artifact of how the sample was written.

  31. Anonymous says:

    Can DirectWrite off anti-alias?

    In WPF, I can use only anti-aliased fonts, I am troubled.

  32. Thomas.Olsen says:

    Regarding GDI+/GDI – with the widgets individual applications use; are the native widgets for Windows drawn using Direct2D/DirectWrite or are they still reliant on GDI+/GDI?

    The native controls are still reliant on GDI/GDI+.

  33. Anonymous says:

    A ID2D1Mesh does not help because I can only draw it and I have no geometric operations available.

    The performance of the ID2D1Geometry operations is comparable to our own routines, some are faster, some are slower. So a hardware assisted implementation would be desirable for performance reasons.

    Btw. I just created a blog on my current experiences with D2D: http://directblog.schmidtbonn.de

  34. There are potentially 2 ways in which this can be accomplished.

    1. Using WPFs HwndHost class: Direct2D’s ID2D1HwndRenderTarget can be embedded into WPF content by means of HwndHost. Create a derived class from HwndHost and then implement the  BuildWindowCore and DestroyWindowCore methods. Instantiate the class from an appropriate place within the WPF application. The HwndHost element is inserted in the WPF element tree like any other element and can be treated as a control for the purpose of simplicity.

    More of this can be found on the following pages:

    WPF and Win32 Interoperation Overview: http://msdn.microsoft.com/en-us/library/ms742522.aspx

    Tutorial  on creating  Application hosting Win32 content: http://msdn.microsoft.com/en-us/library/aa970061.aspx

    WPF Interoperation and concept of "Airspace": http://msdn.microsoft.com/en-us/library/aa970688.aspx

    Even though HwndHost can be used to embed an Hwnd in a WPF application, there are some limitations like HwndHost does not support transformation, alpha blending etc. The above mentioned articles describes all the limitations with reasons.

    2. Use WPF’s D3DImage Class: D3DImage inherits from the ImageSource class that is capable of displaying user created Direct3D9 content (http://msdn.microsoft.com/en-us/library/system.windows.interop.d3dimage.aspx ). However, to interoperate Direct2D with WPF, one needs to interoperate between Direct3D9 and Direct3D10 first as Direct2D is built on top of Direct3D10.1. In Windows Vista, the concept of shared surfaces was introduced that enabled sharing of resources across different devices. Even though there is an efficient mechanism to share resources, the API does not provide synchronization logic that can lead to arbitrary rendering artifacts. In Windows 7, synchronization mechanism was provided for Direct3D10 and above but not with Direct3D9. Due to this, one needs to write their own synchronization logic which in most cases is quite complicated and hard to implement correctly. There is a helper library available on MSDN Code Gallery http://code.msdn.microsoft.com/D3D9ExDXGISharedSurf that implements the synchronization. If you choose to pursue this route, you should note that the license and support policies for content on the code gallery are different from that of the MSDN Library itself. You can review the terms for this sample at: http://code.msdn.microsoft.com/D3D9ExDXGISharedSurf/Project/License.aspx.

    Mark Lawrence [MSFT]

  35. Rajat says:

    Very cool – A lot of familiar names on the "making it possible" list 🙂

    A few questions:

    – I read the whitepaper and saw the integration with WIC. However, what is unclear is can I pass WIC a ID2D1Bitmap to decode directly into (potentially a HW decode)? If not, is this planned for Windows 7? I am a very interested party 🙂

    – Any plans on the Windows 7 team introducing a retained mode API?

    – Also curious what "Server side rendering" means?

    – Does the API remote automagically through RDP? If so, what is the compatability story: ie. Will it remote from Windows 7 -> Vista client?

    – Related to the previous question: What version(s) of D3D does this run on? Will it be backwards compatible? ie. Can I run it on Vista?

    Thanks!

  36. @ Yamada Hiro

    * There is no metafile support.

    * WPF Drawing Brush is a retained mode rendering construct, it requires re-rasterizing its contents to an intermediate surface for each scale it is used at, so, directly supporting it would have violated a tenate of the API that you should control your resources (the intermediate surface in this case). It also requires a scene graph. However, it is fairly trivially implemented by creating a compatible render target, rendering the scene into it and then using the resulting bitmap in a bitmap brush. This also has the advantage that you can intentionally use the bitmap at different scales and don’t need to re-render into the compatible render target if you don’t want to.

    * We don’t output to XPS. However, D2D constructs have been intentionally chosen to correspond to the XPS XAML subset, and there is an API in windows 7 that allows you to output XPS directly using the XPS Object Model and to print it using the XPS Print Path (even to a GDI driver).

  37. Thomas.Olsen says:

    @Eric:

    Thanks for your comments. My point earlier was that customers will typically tend to choose one technology or the other; however, I do agree with you that there are customers who will want to use both WPF and D2D, and we intend to make the technologies work well with one another. We’re working on samples. Hang in there. 🙂

  38. Thomas.Olsen says:

    "I am really interested in the interop demo. Have you already made a sample application? How about performance? Is there a large overhead?"

    D3D9/D3D10 interop is tricky due (in part) to shared surface synchronization issues and driver bugs — and it’s not easy for devs to get this right. So, we’re currently evaluating the best way to address these issues. Stay tuned. We are actively working on it.

  39. Thomas.Olsen says:

    @Thomas: Are the device independent Interfaces like ID2D1Geometry implemented in hardware or software? What performance do I have to expect?

    ID2D1Geometry is implemented in software. If you want the hardware equivalent, you can use ID21RenderTarget::CreateMesh to create a ID2D1Mesh.

  40. Thomas.Olsen says:

    Questions from a reader:

    How does it relate to the managed code APIs?

    Direct2D is an unmanaged (native) code API. No part of it is managed.

    Will we see a Managed Direct2D, and another transition period during which the unmanaged and managed APIs are not in synch? 

    This is an interesting idea, and we are discussing the possibility of a managed wrapper. Stay tuned for that.

    Or should we regard Direct2D as WPF re-surfacing in the unmanaged world?

    Direct2D and WPF are targeted at different customers. Direct2D is a lightweight native code API which uses an immediate-mode calling pattern (like Direct3D), and will be used primarily by native C/C++ developers. WPF is a managed code framework which uses a retained-mode calling pattern, and will be used primarily by .NET developers.

  41. Thomas.Olsen says:

    How does the Direct2D API play with the changes to the DWM?  Do you have any examples of using this to control the windows at the DWM level? 

    Both Direct2D and DWM in Windows 7 are built on top of D3D10. D2D doesn’t handle anything relative to window orientation/sizing/etc.

    Another scenario I’d like to try is to use the multi-touch resize gestures to enable the windows to be scaled by the GPU, rather than just resized.

    Check out the PDC talk on Multi-Touch: http://channel9.msdn.com/pdc2008/PC03/

  42. Thomas.Olsen says:

    Since Direct2D is going to be C/C++ compatible and based on COM interfaces, I was wondering if you guys would be kind enough to ship it with a type library?

    I know type libraries are usually thought of as benefiting COM automation (IDispatch), but a complete type library assists developers not using C/C++. An ITypeLib can be used to machine generate alternate language source code files (interface declarations, enumerations, constants, structs, ect).

    I’ll share that feedback with the team. Thanks.

  43. Thomas.Olsen says:

    Will Direct2D be ported back to Vista?

    Microsoft announced at PDC that Direct2D will be ported to Vista. But there is no specific timetable yet. Stay tuned for that.

  44. Thomas.Olsen says:

    @Markus:

    Thanks for the feedback. Good stuff.

  45. Thomas.Olsen says:

    _Please_ make this available for Windows XP. I work in space operations, and people here are _very_ conservative. I imagine this is similar to other sectors such as banking.

    I understand. Thank you very much for your feedback on this issue. I’ll share it with the team.

  46. @ Tom

    D2D has a superset of the WPF geometric functionality, including:

    * Geometry Groups

    * Geometric transforms (i.e. pre-stroke transform)

    * Combine operators

    * Lenght/Area/Position

    * Tesselation

    * Outlines

    * etc.

    You can directly manipulate 2D triangular vertices by creating a Mesh object. You can either populate the mesh yourself, or, you can ask D2D to tesselate a geometry into the Mesh. The Mesh is stored as a vertex buffer on the GPU. It can render aliased geometries through the DrawMesh API. For an anti-aliased optimization that can be stored on the card, you can create an A8 compatible render target and either render to provide a mask, or update it yourself. This can be combined with a brush with the FillOpacityMask API.

    The extruded text sample already uses some of these operations, and the path animation sample uses others. Our geometric support is very large, I wouldn’t assume that every possible operation would end up in a sample. There is after-all an SDK.

  47. Anonymous says:

    Great stuff, Tom!  I was wondering if this technology does anything to address two problems that have been driving me crazy:

    1. Many programs fail badly if the system DPI is set to anything other than the default 96 DPI (I need to use 120).  Text is cut off, dialog buttons are invisible because they fall off the bottom of the dialog… it’s a serious problem.

    2. The Text Size setting in IE6 is ignored by many websites – I assume because it messes up their page structure/formatting.  This makes it hard for me to read the text, expecially on modern high-resolution monitors.  I know that IE7 has a zoom level control as well, but it doesn’t work in all cases…

    Any comments?

    Thanks!

  48. Thomas.Olsen says:

    does D3D10 GPU run as D3D10Level9 device for D3D10.1?

     No, D3D10Level9 is only used in conjunction with a D3D9 driver.

  49. Thomas.Olsen says:

    Will D2D be compatible with GDI device contexts? Could I blit from a D2D context to a GDI context interchangeably?

    Yes. You can render from a D2D render target to a HDC — or draw from a HDC into a D2D render target. 

    Can I use D2D to draw directly to a window?

    You need to create a HwndRenderTarget which maps to the window; then, you draw to that render target.

    Will the result be available immediately (could I read back the pixels right after a command)?

    The results of drawing operations are committed immediately upon calling ID2D1RenderTarget::EndDraw. We don’t provide readback for hwnd render targets. If you need readback, either create a WicBitmapRenderTarget or a DXGISurfaceRenderTarget and access the underlying bits after rendering.

    didn’t see this in the post, but are there going to be stroke styles, join and end caps, miter types, spline curves, and blur effects?

    Yes to stroke styles, join and end caps, miter types, and spline curves. No to blur effects. You can implement your own blur but it requires using a shader via D3D interop. 

    Will this be a Windows 7 only feature or to which OS will it be back ported?

    Initially, Windows 7. We are still looking at which platforms we want to backport the functionality to.

  50. Thomas.Olsen says:

    @ViktorSkarlatov: "Is Direct2D suitable for drawing UI components?

    Yes, it is suitable. There are some things to keep in mind. For example, remember that Direct2D uses a float coordinate space and does per-primitive antialiasing; in other words, it supports sub-pixel positioning. GDI uses an INT coordinate space and can
    only do aliased primitives. What this means is that you have more flexibility with Direct2D about positioning but, at the same time, getting precise pixel alignment (as envisioned by UI designers) needs to take into account the differences between sub-pixel
    and pixel alignment. Just something to keep in mind. Of course, you can turn on aliased rendering in Direct2D if you prefer the GDI style.

    I am currently playing around (in Windows Forms) with the SlimDX managed Direct2D wrapper and I was wondering if there is a point to this. I am concerned about resource creation and disposal, since these operations are expensive. My idea is to make
    an implementation of the IGraphics interface which uses Direct2D underneath.

    Resource creation and disposal can be expensive, but there are ways that you can mitigate the cost. For example, you can reuse textures rather than constantly thrash thru creation and disposal. It’s one of the reasons that many games preload most or all
    of their textures up front. Consider using a single atlas texture and updating tiles, as needed. Certain types of resources are mutable (eg. ID2D1SolidColorBrush) so, if you need to use a bunch of them, you could call ID2D1SolidColorBrush::SetColor rather
    than create separate resources. There are other things that you can do. Check out this article.

     http://msdn.microsoft.com/en-us/library/dd372260(vs.85).aspx

    I’m always happy to brainstorm on your scenarios, too.

  51. Thomas.Olsen says:

    @Tihiy:

    The ‘benchmark’ that was shown on PDC – GDI vs GDI+ vs D2D, how fair it is? AFAIK GDI primitives (like LineTo) is not accelerated on Vista/W7 anymore. So the question then, if the same test compared XP GDI vs W7 D2D, who would won?

    The benchmarks at PDC are illustrative of performance characteristics on Win7. It would be difficult to draw a direct comparison with GDI on XP because D3D10 only runs on Vista and Win7.

  52. Thomas.Olsen says:

    @Keith:

     

    ·        I want to remind everyone that
    DemoApp is not "the Direct2D API." DemoApp is sample code. Most of it is boilerplate Win32 programming that registers a window class, creates a window, processes and routes messages,
    and handles window messages. It isn’t intended to be a tutorial on Win32 programming, nor is it intended to represent the
    smallest or the best or the only possible D2D application. It merely reflects best practices. I can understand if someone doesn’t like DemoApp’s C++ class — it’s a personal preference, after all — but the benefits
    of object-oriented languages are well-known and, given the state of optimizing compilers, characterizing a single wrapper class as "bloat" is a gross mischaracterization. I don’t have much to say about comment style. Comments are for documentation, and they
    vary widely.

     

    ·        
    Direct2D is a general-purpose 2D rendering API. It wasn’t designed solely for the purpose of drawing a single rectangle. If you really want an honest comparison of code size, try a counter-example which draws
    antialiased ClearType text, buttons, lists, and most other common UI elements solely with Direct3D — and then tell me whether you think it requires less code than Direct2D. I don’t think so. For extra credit, try drawing complex paths, radial-gradient- or
    bitmap-filled ClearType text with Direct3D, and then get back to me about the ease of Direct3D programming. Furthermore, if anyone is going to use lines of code as the sole metric for evaluating code, then let’s be honest and include fundamental things such
    as error-handling (eg. device loss, allocation failures, etc), resource cleanup (completely absent), useful comments, etc before casting stones. I wouldn’t ship code with such low quality, so it really isn’t worthy of comparison.

     

    ·        
    All of our brushes (solid color brush, radial gradient brush, linear gradient brush, bitmap brush) derive from a common base interface. Polymorphism allows us to use each brush interchangeably for stroking
    and filling of geometries, masks, and text, without having to resort to parametric structs or other weirdness. Brushes can be created, modified, used to draw, and torn down in a similar manner to GDI brushes. Whether you create, use, and destroy a brush during
    a single rendering pass, or create and hold a brush for the duration of an app is dependent on your particular needs.

     

    ·        
    COM (particularly lightweight COM) provides a lot of positive benefits (clean separation of interface and implementation, versioning, language independence, extensibility, etc). In the interest of brevity,
    I’ll simply refer everyone to a paper on the subject (http://msdn.microsoft.com/en-us/library/ms809980.aspx).

     

  53. D2D was designed from the ground up to make it as easy as possible to write a DPI aware application.

    D2D:

    • Automatically honors the system DPI when creating a windowed render target, so long as the application manifest indicates that the application handles DPI correctly.

    • Expresses all of its coordinates in DIPs (Device Independent Pixels), which allows the application to scale automatically when the DPI changes.

    • Allows bitmaps to have a DPI and correctly scales them taking this into account. This can also be used to maintain icons at different resolutions.

    • Expresses most resources in DIPs, which are then also automatically resolution independent, especially compatible render targets and layers

    • Expresses a floating point coordinate space and can render anti-aliased, so, any content can be scaled to any arbitrary DPI.

    • We have a pipeline authored over D2D shipping in Windows 7 that scales from 96 to 1200 DPI using these techniques.

  54. Thomas.Olsen says:

    @sysrpl: 

    How do you believe this API would perform for complex realtime 2D animation?

    The performance for complex 2D animations is excellent. Check out the animation demo toward the end of the PDC session (http://channel9.msdn.com/pdc2008/PC18/).

    How would it perform as animation directly to a HWND vs a DX surface? Is there a faster blit function, or is AlphaBlend still going to the fastest way to transfer 32bpp pixel data to HDCs?

    The short answer is … it depends. 🙂 It’s difficult to give you an unequivocal answer without assessing the hardware and drivers. My advice is measure, measure, measure. 🙂

  55. Anonymous says:

    Hi Tom,

    I looking forward to managed wrapper, make sure it is a good one. And I have a couple of questions, too:

    1. Will there be support for video playback.

    2. Will it run on Windows XP? I assume not…

  56. Bluvg says:

    "Server-side rendering"

    Does this mean support for RDP?

    Also, are there any accessibility issues at this point?  

    And, what will it take for broad adoption?  Unfortunately, there seems to be a dearth of WPF apps.

    I don’t know D2D would help, but currently many of our apps are quite inconsistent about their ClearType handling–sometimes ClearType is applied to text, but then in another dialog (or even in the same dialog!), you can clearly see that no font smoothing is applied.  Is there any way existing apps can leverage D2D (without being rewritten), or is this just wishful thinking on my part?  Could GDI/GDI+ commands somehow be mapped onto a D2D renderer, gaining of its benefits (or at least some)?

  57. Thomas.Olsen says:

    Can Direct2D ‘help out’ in WPF? I mean, my experience with WPF is its quite slow in terms of rendering compared to GDI/GDI+. Maybe you guys can build an additional layer that can make WPF render using Direct2D

    WPF can interop with Direct3D9. Read these articles for more details.

    http://msdn.microsoft.com/en-us/library/system.windows.interop.d3dimage.aspx

    http://msdn.microsoft.com/en-us/library/cc656910.aspx

    http://msdn.microsoft.com/en-us/library/cc656710.aspx

     

  58. Thomas.Olsen says:

    Direct2D will be available on both Windows 7 and Vista. XP support is problematic because D2D depends on D3D10.1 which depends on Windows Display Driver Model (WDDM) which is only available starting with Vista, not XP.

  59. Thomas.Olsen says:

    What about interop with WPF? With .NET 3.5 SP1, it can work with IDirect3D9[Ex] via the D3DImage WPF class.

    We can interop with WPF since we both use Direct3D. The trick, though, since WPF is using D3D9 and we’re using D3D10, is that you would need to use a D3D9 shared surface. I’m going to post a
    sample in an upcoming blog post that shows how to do this.

    Is the software rasterizer optimized for multicore?

    Not yet. We originally had tasks on our schedule to optimize the rasterizer for multicore, but we ended up prioritizing hardware support.

    Or, is it easy (and cheap!) to do things like banded or tiled rendering so that I can multithread it myself? Are there restrictions with using an object (e.g., paths, brushes) from
    multiple threads, which is a crippling performance issue in GDI/GDI+?

    It is relatively easy to do banded/tiled rendering.

    1.     
    Allocate some system memory for a pixel buffer, and implement your own IWICBitmap wrapper to reference that memory. Your implementation of IWICBitmap should do nothing in response
    to calls to Lock/Unlock (D2D will attempt to lock and unlock the memory — but since you’re managing the bands, you don’t need to lock or unlock the memory).

    2.     
    Create a multi-threaded D2D factory.

    3.     
    Call ID2D1Factory::CreateWicBitmapRenderTarget for each band that you need, and pass in your implemented IWICBitmap. Keep in mind that resources created by a given render target
    are bound to that render target, which would require that you create separate resources for each render target (i.e. you can’t share them). The only exception is a shared bitmap. Shared bitmaps can be used across software render targets — or across hardware
    render targets on the same physical adapter.

    Also, I bet if a server wants to do a LOT of rendering, then they will want a GPU sitting in there to help out. So, any support for GPU accelerated rendering in session 0? Especially
    for these:
    http://www.nvidia.com/page/servers.html

    Direct3D cannot currently run in session 0.

     

  60. Anonymous says:

    Hello, my application was developed before 5 years on top of GDI+. Now we’d like to add a new module (DLL) to the existing application. In this case, should we convert the whole application to Direct2D and then write the new module in Direct2D? Please
    suggest!

  61. Rick Brewster says:

    What about interop with WPF? With .NET 3.5 SP1, it can work with IDirect3D9[Ex] via the D3DImage WPF class.

    Is the software rasterizer optimized for multicore? Or, is it easy (and cheap!) to do things like banded or tiled rendering so that I can multithread it myself? Are there restrictions with using an object (e.g., paths, brushes) from multiple threads, which is a crippling performance issue in GDI/GDI+?

    Also, I bet if a server wants to do a LOT of rendering, then they will want a GPU sitting in there to help out. So, any support for GPU accelerated rendering in session 0? Especially for these: http://www.nvidia.com/page/servers.html

  62. kaiwai says:

    Regarding GDI/GDI+ – has GDI/GDI+ been ported so that it sits ontop of Direct2D? specifically, under Vista it was unaccelerated – given the number of applications dependent on GDI (and I assume the widget kits in Windows), will this happen?

  63. Christopher Morgan says:

    Having come back from PDC2008 with one of the giveaway sensorboards I’m really keen on trying to put together an example that allows me to manipulate the windows on screen using the accelerometers/tilt sensors.  For example, by attaching the sensor to the lid of my laptop I could infer the relative orientation of the screen to the keyboard and therefore apply a transformation to the window layout so that shapes appear correctly from the viewers perspective.

    How does the Direct2D API play with the changes to the DWM?  Do you have any examples of using this to control the windows at the DWM level?  Another scenario I’d like to try is to use the multi-touch resize gestures to enable the windows to be scaled by the GPU, rather than just resized.

  64. sysrpl says:

    Hey Tom, thanks for answering ym blog post on Channel 9 MSDN here:

    http://channel9.msdn.com/forums/Coffeehouse/409437-WPF-and-the-Future/

    It looks like you’re really going to deliver. Great job! You’re working on the right project!

    I added a few questions at the end.

    Will it be compatible with GDI device contexts? Could I blit from a D2D context to a GDI context interchangeably?

    Can I use D2D to draw directly to a window?

    Will the result be available immediately (could I read back the pixels right after a command)?

    I didn’t see this in the post, but are there going to be stroke styles, join and end caps, miter types, spline curves, and blur effects?

    Will this be a Windows 7 only feature or to which OS will it be back ported?

  65. sysrpl says:

    Thomas,

    Thanks for the info. Your a real professional and this blog/announcement really has me psyched.

    One thing I thought of though, and I really hope you read this:

    Could you please ask your team about SERIOUSLY considering implementing polygon clipping AND hit testing?

    For an example of polygon clipping see:
    http://www.cs.man.ac.uk/~toby/alan/software/

    That would be a HUGE step forward in programmability, especially if your could design a clipping algorithm which could output complex shapes with splines.

    I know polygon clipping is not directly a graphic draw function, but it’s so closely tied to it. And think about it, if you guys could figure out a way to implement and advanced clipper using a feedback buffer from the GPU … well I would be totally blow
    away!

    By the way, for your entertainment/inspiration, you might want check this out this vector simulation program:

    http://www.phunland.com/wiki/Home

    And here is my contribution to that project:

    http://www.codebot.org/articles/?doc=9516

  66. sysrpl says:

    One modification one my request above. When I asked about polygon clipping, I meant clipping where the path data is captured and can be read back as a path.

    This would be essential for providing the ability to clip paths, and then allowing the path to be edited and/or saved between sessions.

    Editing involves showing nodes and curves handles on the screen, and allowing those nodes to be modified through dragging, joining, or deleting. Of course editing would be implemented by the programmer by modifying a path structure, but reading that path back after clipping is essential.

    Final note, most/all clipping algorithms don’t handle curves (including circle/ellipse/spline) and yours obviously should.

  67. sysrpl says:

    Wow, that is seriously sweet. I can’t wait to start playing with this stuff. I know having access to this stuff is going to radically benefit all my programming.

    TTYL

  68. sysrpl says:

    Okay, another question then. Since Direct2D is going to be C/C++ compatible and based on COM interfaces, I was wondering if you guys would be kind enough to ship it with a type library?

    I know type libraries are usually thought of as benefiting COM automation (IDispatch), but a complete type library assists developers not using C/C++. An ITypeLib can be used to machine generate alternate language source code files (interface declarations, enumerations, constants, structs, ect).

    Example of my app importing nvidia information:

    http://imagebot.org/snapshots/F6A21984971C4386F73E971CE40A9036.jpg

  69. Kaiwai says:

    Regarding GDI+/GDI – with the widgets individual applications use; are the native widgets for Windows drawn using Direct2D/DirectWrite or are they still reliant on GDI+/GDI?

  70. sysrpl says:

    I hope you don’t mind all these question. I feel like I’m abusing some privilege.

    I was thinking more about Direct2D and wanted to know if you guys were building in some of these optimizations or if developers would need to handle them ourselves:

    Would you handle, to some extend, view frustum culling?

    If rendering a complex scene with many 2D shapes, would your API discard and return immediately attempts to draw objects which are completely outside the bounds of the bitmap or window?

    That optimization would speed up things a lot and simplify development for us if we had complex drawings (think a CAD blueprint). We wouldn’t need to write boilerplate code to to transform bounding boxes and perform test ourselves.

    It would probably make Direct2D much more elastic/faster for the average user.

    Also, would you apply the optimizations for LOD (level of detail) as well? This is where 2D objects are reduced in size in to such an extent that they might to render to only a single or few pixels. An optimization on your end to reduce drawing a bunch of geometry at that point would could save many unnecessary calculations.

    Thanks again

  71. Ignatich says:

    Great stuff, especially new text renderer. Currently it’s almost impossible to measure text width properly with GDI+. GDI rendering seem to be much slower than GDI+ if I use it from managed application (at least on Vista) and UniScribe is way too undocumented.

  72. Rüdiger Klaehn says:

    I have been looking for something like this for a long time (basically since I realized that WPF is not fast enough for our purposes).

    _Please_ make this available for Windows XP. I work in space operations, and people here are _very_ conservative. I imagine this is similar to other sectors such as banking.

    It took us a long time to convince one customer to drop NT 4.0 support for our application. So if Direct2D is only available for windows 7, we won’t be able to use it for at least 5 years even though it does exactly what we need.

    The XP support would not necessarily have to be accelerated. Just make the software pipeline available for XP if that is easier.

  73. Dege says:

    We have looking for something like this, too.

    But, as MS didn’t have a 2d drawing API using hw acceleration, we felt free to create our own implementation for our cad program, almost with the same functionality that Direct2D provides. Altough it sits on top of D3D9/D3D9Ex because of the "mandatory" XP support.

    Will Direct2D be ported back to Vista? If it will, we could use it as a new implementation.

    Win7 is so far yet…

  74. Anthony Hodsdon says:

    @sysrpl:

    Hi, I’m Anthony, another dev on the D2D team (I work on the geometry and tessellation engines). I thought I’d take a crack at a couple of your questions.

    Regarding off-screen culling: D2D is optimized to take into account off-screen (and partially off-screen) content. That said, there is still some per-primitive overhead, and we expect that some app writers will find it useful to implement culling on top of us. Indeed, in many ways, app writers have a much better opportunity to perform these sorts of operations than we do, as they can group primitives together into a single unit and do one cull test for the entire unit. Think of a vectorized button, for instance: this might be composed of several individual D2D primitives, and rather than performing a cull test on each individual primitive, it probably makes more sense to cull test the button as a whole.

    Regarding LOD: Like most 2D rasterizers, D2D does have some concept of level-of-detail in that our Beziers will dynamically flatten to a level appropriate to the resolution of the display and the scale of the world transform. The concept of a more general geometric LOD (allowing the user to generate entirely new geometries based on the scale of the world transform) is an interesting idea.

  75. mike says:

    Can Direct2D ‘help out’ in WPF? I mean, my experience with WPF is its quite slow in terms of rendering compared to GDI/GDI+. Maybe you guys can build an additional layer that can make WPF render using Direct2D

  76. sysrpl says:

    Okay, another question. Previously I asked about the ability to capture data back from polygon clipping operations. This is a related request.

    Will you have a function to return the bounding box (transform or untransformed) for paths?

    This would be needed where paths contain bezier curves and determining their bounds would be difficult for programmers.

  77. Anthony Hodsdon says:

    @sysrpl: 

    Will you have a function to return the bounding box (transform or untransformed) for paths?

    This would be needed where paths contain bezier curves and determining their bounds would be difficult for programmers.

    ID2D1Geometry::GetBounds() is your friend :-). It supports Beziers and also accepts a transform.

  78. sysrpl says:

    Alright. I’m totally sold. This API is going to be awesome. I’ve been waiting for it for a long time.

    I believe the only thing more we are going need is BLISTERING SPEED through hardware acceleration.

    How do you believe this API would perform for complex realtime 2D animation? How would it perform as animation directly to a HWND vs a DX surface? Is there a faster blit function, or is AlphaBlend still going to the fastest way to transfer 32bpp pixel data to HDCs?

  79. Frank Hileman says:

    Looks like a great rendering layer for VG.net. We’ve been waiting for something like this from Microsoft for years. We would also love XP support.

  80. Tihiy says:

    The ‘benchmark’ that was shown on PDC – GDI vs GDI+ vs D2D, how fair it is?

    AFAIK GDI primitives (like LineTo) is not accelerated on Vista/W7 anymore.

    So the question then, if the same test compared XP GDI vs W7 D2D, who would won?

  81. Eric says:

    Hey, Tom,

    From later comments, I think you get this, but it scared me to see you write "Direct2D and WPF are targeted at different customers".  I think Microsoft needs to assume that *many* applications will use both.  Why?  Because WPF is a great UI platform, but the overhead of the retained mode graphics is too high for many applications, IMHO.  I think the application model of choice going forward is going to be a WPF "skin" with any serious graphical content rendered with D2D/DWrite and displayed in WPF via Interop.  That’s not to say that for many scenarios (database front ends), WPF retained-mode graphics are fine, but for others (scientific visualization), WPF graphics don’t cut it.  WPF + D2D is a great solution for those scenarios.  So please make the interop clean (looking forward to the sample app)!

    Eric

  82. Mark says:

    Direct2D looks excellent. I’m new to graphics programming (currently working on a charting application written in MFC) so this is likely to be a silly question but.. will Ican I already program using Direct2D using MFC or will I need to use Win32?

    Best regards

  83. tom says:

    This is very exciting news to me.  I develop multimedia applications as a hobby, making great use of 2-D graphics.  I’ve been thoroughly impressed by the flexibility and performance demonstrated in the sample videos.  I can’t wait to have that power at my fingertips.

    I would like to throw in some chips for XP support.  I don’t consider it mandatory, but it would definitely be convenient.  The XP market in Middle America remains fantastically huge.  I’m a technician and software engineer for a citywide school system.  Our entire district (26 buildings, plus administration) uses XP and will continue to do so for at least another three years.  Personally, I design software with XP (32-bit) as the baseline and troubleshoot on Vista (32- and 64-bit) to make sure it works every which way.  My philosophy is:  it has to run under XP.  Vista support is a convenience.

    As yet I’ve been unable to test D2D/DW first-hand.  I’ve installed the Windows 7 beta and SDK (both at work and home) under VPC, but I haven’t have time to compile anything.  It may interest you to know that the SlimDX team — responsible for picking up Managed DX where Microsoft left off — has already begun implementing Windows 7 features into the next release.  When Direct2D, et al, do hit the market, SlimDX will be my weapon of choice for utilizing them.  To that extent, an "official" managed wrapper would be strictly unnecessary, but it might yet be a good idea for folks who haven’t heard of SlimDX.

    I have only one question at the moment.  When you say "device independent pixels," how does that translate to screen pixels?  May we assume all transformations are given/retrieved in DIP’s that match the display device’s own pixels, and that all conversion is done under the hood?  I’m always a bit confused when it comes to graphical units and how they interact.

  84. Dave says:

    I am so glad that the C++ Lighweight COM approach was used. I was worried that Direct2D was going to managed route and this would be terrible.

    The lighweight COM approach works very well.

  85. Keith says:

    I’d be interested to see what reaction you have to Jonathan Blow’s (the creator of "Braid" for XBox) comments on the API examples/design.  Is this just a misunderstanding of how the API is meant to be used?

    http://braid-game.com/news/?p=466

  86. @Keith

    Well, Jonathan’s sample isn’t really a 1:1 comparison:

    * It doesn’t do anti-aliasing. D2D does an 8×8 mutli-sample AA by default.

    * On a related note – it isn’t resolution independent.

    * It doesn’t handle device lost, or any other errors at all.

    * It has a completely different coding style.

    * It has no comments.

    * It has a whole bunch of global variables.

    * It won’t do primitive remoting over RDP.

    Which, is a somewhat doubtful comparison if you are looking at LoC against a sample that is intended to be a well-structure base for someone writing something of a workable application.

    In addition, D2D doesn’t only draw rectangles, a not much more complicated sample from the D2D side would be a lot more interesting as a comparison. e.g.

    http://msdn.microsoft.com/en-us/library/dd317124(VS.85).aspx

  87. Keith says:

    Hi Thomas,

    Thanks for the responses.  Please understand that my comment was not meant to be critical; I was legitimately curious as to what you thought of Jonathan’s post.  I think many of your points are quite reasonable, but at the same time I think that they point out several issues with the demo code.  Although of course the demo code is not synonymous with the Direct2D API, I think that the fact that the sample does something (drawing a rectangle) which apparently doesn’t highlight many of the wins that you see the API providing is a real flaw.

    I hope I don’t come off as argumentative; I’m definitely not trying to claim that the API is bad.  But I do think that it’s important to have sample code that clearly demonstrates how the API is meant to be used.  Do you feel that the DemoApp meets these goals?  Is the DemoApp being taken out of context?  Is there a better set of example code somewhere, and could Microsoft be doing a better job of drawing attention to it?

    I feel like things like unnecessarily creating and releasing brushes make the demo actively harmful.  Like it or not, people take a cargo cult approach to coding and will build off of sample code that Microsoft releases.  If the demo code does unnecessary work, then 1) people will overestimate the difficulty of working with the API, leading to reduced uptake and 2) lots of other people’s code will be littered with unnecessary code, making it a maintenance burden and further reinforcing views about the difficulty of working with the API.  I have no doubt that the people writing the demo code had the best of intentions, and that things like evolving APIs can make it hard to keep samples up-to-date, but based on your responses it sounds like Microsoft could do a better job of writing sample code that concisely demonstrates using the API to achieve functionality that would be hard to do with the current set of APIs.

  88. @Keith

    Well, interestingly though – If we rewrote the sample to have the same general style, error handling, and resource handling philosophy of Jonathan’s blog post, it would most definitely be shorter than his, and do more (antialiasing, primitive remoting, resolution
    independence).

    We are very aware of the tendency that people have to copy samples — which is why we sometimes do things in the samples which are "best practice" or "safe" rather than "optimally simple". For example, D2D does have device dependent resources that can go
    away (if you use the HW rasterizer), and further, can be expensive to create because they are doing so on an external GPU. So, we structure the code to assume that resources should be created and held on to, because, this is generally best practice. However,
    brushes, as it turns out, are really cheap and can be created and thrown away at will. Was the demo wrong? That is actually a more complex question than you might think. For example, you could just maintain a single brush for your entire app, and just change
    the color whenever you draw; this would be very optimal, but, it might have decreased the readability of the sample.

    Also, since resources can be held on the GPU, they can go away. You can choose to care, or you can choose not to care about this. (Jonathan’s sample chooses not to care). There is a debate as to whether this is appropriate for a 2D rendering API. Here are
    some observations:

    * Some resources, such as bitmaps, are really big. Maintaining a system memory copy simply to update the one on the GPU is really expensive.

    * GPU video memory doesn’t count against system memory on a discrete part. So, there is a huge working set win in keeping it only on the GPU.

    * Existing APIs which maintain system memory copies do not (based on our performance measurement and experience) achieve the same performance or working set usage as D2D for the same scenario.

    * D2D is transparent and policy-free in the way that it handles resources. When you create a resource, you pay the cost of associating that resource’s data with the GPU
    immediately. Some rendering systems attempt to hide and delay this association — thus, imposing their own policy — but this simultaneously makes it difficult or impossible for the application programmer to predict what the cost is, when they’re going
    to have to pay it, and how to work around it. We would argue that it’s better to let the programmer decide if/when they want to pay that cost.

    * Some resources are inescapably on the GPU and cannot be recovered. Your render target is on the GPU, it contains a back-buffer. If the GPU device is lost, the back-buffer contents are lost. Same for an offscreen surface you are using for rendering.

    * Some of these resource might not even be on the same machine in the remoting cases.

    As to why the brushes are bound to the devices. It turns out that SOME brushes either have, create or point to device dependent resources. In fact, all of the brushes outside of the solid color brush (eg. bitmap brush, linear/radial gradient brush) do one
    of these things. Given this, it is conceptually simpler to put the brushes into the same "domain" as the render target. Otherwise, someone could get a bitmap brush, point it to an incompatible bitmap and then fail when drawing it, this is a much harder to
    understand developer experience than keeping the objects together.

    And, bear in mind, this is the very first version of this API. We generally felt that it was safer when designing it to assume a cautious contract that could be expanded based on customer feedback than to create a way open contract that we would have a hard
    time restricting in the future without breaking existing applications.

    And finally, yes there are many more samples:

    http://msdn.microsoft.com/en-us/library/dd372354(VS.85).aspx

    This one, interestingly, was chosen precisely because it closely matches the WPF introductory sample. So, it serves a good purpose if someone who knows WPF is evaluating D2D in comparison.

  89. Seth Technet says:

    I would like to see a version of Jonathan’s Direct3D code which does more advanced things such as use different stroke widths, stroke styles, etc.  The Direct2D code would be quite a bit cleaner.

    Also, custom text handling in any 3D API (OpenGL, Direct3D, I don’t care) is a pain.  The text rendering feature alone of D2D/DWrite make the APIs quite nice in my eyes.  Not everyone is able to use C# for their applications.

  90. tom says:

    Mark:  thanks for the description.  Does this mean we tell D2D/DW what DPI to use, or does it automatically detect what the current device is using?

    My only fear with Blow’s hideously malformed (and curiously vehement) opinions is that people will read his blog without bothering to do the research themselves.  That is precisely the sort of dangerous misinformation that sets back any advance.  Nevertheless, one must have faith that sensible minds will make things right, and that Blow will spit out his own feet.

  91. @ Tom

    On the DPI aspect:

    For bitmaps – You have to tell D2D what DPI to use, we default them to 96 DPI since this will tend to work acceptably if the App was authored at 96 DPI and later is scaled. Otherwise, you can set the bitmap DPI to be the same as the render target DPI and you will always get linear scaling of the pixels. Or, you could have a library of icons of different sizes and select amongst them depending on the system’s DPI to keep them sharp when rendered. In keeping with our other decisions, we have tried to keep this as policy-free and flexible as possible while adhering to a goal of helping applications be resolution independent. Also, note that the bitmap DPI isn’t relevant to the DrawBitmap API since in this case you specify the destination rectangle and we will always scale to fill it, it is relevant to the default scaling of bitmap brushes.

    You *can* ask WIC what the DPI is and apply it to the bitmap yourself, however, this value can sometimes be of limited utility. For example:

    * What is the DPI of a random camera shot?

    * Some formats specify the equivalent of DPI in metric units, so, the DPI can end up fractional in inches when converted.

    * Some applications don’t set the DPI to a good value when saving the bitmap.

    For the render target DPI, it depends on the type of render target.

    * For windowed render targets. The system DPI is used by default. However, you can override it. You also need to indicate in your manifest that you want to handle arbitrary DPIs.

    * For "surface" render targets, we default them to 96 DPI. This includes WIC bitmap render targets and DXGI surface render targets.

    * For compatible render targets, the DPI will be inherited from the parent target if you specify its size exclusively in either DIPs or pixels. Howver, if you specify both sizes, then you have also implicitly specified the DPI.

    As to negative feedback about the API, we listen, we learn, we evaluate our designs and their underlying philosophies and the samples that illustrate them. But, we also look at both positive and negative feedback, you can’t please everyone all the time, neither do you necessarily succeed if you try. 🙂

  92. tom says:

    Thanks for the clarifications.  I have one more question, related only through the PC18 video presentation.  Toward the end (right before Q&A), Kam shows off the UIAnimation API in action (not to be confused, I assume, with the iPhone API), demonstrating D2D as the renderer.  I understand they’re completely different modules and D2D is only superficially connected as a render path, but this is actually the first (and last) reference I’ve seen to UIAnimation in Win7.  Is there any chance you could point us to a site with more information?

  93. Yamada Hiro says:

    1. Is there metafile?

    2. Is there some brush such as WPF DrawingBrush?

    3. Can I output to XPS?

  94. tom says:

    Ah, good question:  can we natively load metafiles?  Also, what sort of geometry manipulation tools are we looking at?  Obviously we can apply transformation matrices; how are we able to manipulate raw vertex data?  A better question might be, is this done in any of the samples, or will there be samples demonstrating any/all of this?

  95. Yamada Hiro says:

    Thanks for your reply.

    WPF has DrawingBrush.

    GDI+ has TextureBrush. This TextureBrush.Image property is Bitmap or ‘Metafile’.

    I hope that D2D supports some geometry pattern brush.

  96. Thomas.Olsen says:

    @Yamada:

    You can create a geometry pattern brush with D2D, but you need to do it explicitly, and there are certain caveats.

    1. Call ID2D1RenderTarget::CreateCompatibleRenderTarget() with a specified size, which produces an intermediate surface (ID2D1BitmapRenderTarget) that you can draw into.

    2. Draw your geometry into the intermediate surface render target (ID2D1BitmapRenderTarget::BeginDraw|Draw*Fill*|EndDraw).

    3. Retrieve the intermediate surface texture via ID2D1BitmapRenderTarget::GetBitmap().

    4. Create a bitmap brush via ID2D1RenderTarget::CreateBitmapBrush using the surface that you obtained in Step 2.

    5. Use the bitmap brush to stroke or fill a geometry.

     As Mark said in a previous post, creating intermediate textures in GPU memory is an expensive operation, so you’re going to want to do it sparingly and then cache the result, not repeat frame-over-frame.

     

  97. Yamada Hiro says:

    Thank you for your reply. I try this method.

    There is an another question.

    I want to maximize speed of draw line, by off anti-alias.

    Our CAD application draws 100,000 lines. In ‘Edit Mode’, We don’t need anti-alias. In ‘Preview Mode’, We need high quality rendering.

    Can D2D off anti-alias ?

  98. Martyn Lovell (martynl@microsoft.com) says:

    This is delayed followup to Tom’s question above about UIAnimation (a.k.a. The Scenic Animation platform). There’s lots more information on MSDN:

    http://msdn.microsoft.com/en-us/library/dd371981(VS.85).aspx

    Scenic Animation provides a simple way to add time-based interpolation, variable management and event based animated change to apps that already have rendering. It’s used in several Windows 7 components and can be used with D2D, GDI or your own rendering. Remember that this only does the mathematics of animation – it’s still up to you to find a way to draw the pixels – of which D2D is the best way in my view.

    Do feel free to contact me if you’d like to know more.

    Martyn

  99. Myrddinson says:

    First of all, i was waiting for a API like this for long time: i am using now GDI+ for 2D stuff and Direct3D for 3D stuff but sure Direct2D seem to be more suitable for mixing 2D and 3D in the same application. Great work !

    You say that DIP should be 1/96 inch: why not use 72 DPI instead ? It is because 1 pt = 1/72 inch and so with DIP of 1/72 inch we have exactly 1 pixel = 1 point and point seem to be a more suitable standard for device independant pixel than arbitrary 1/96.

  100. Te-jé Rodgers says:

    I noticed a some bugs (?) when rendering a bitmap to a hwnd render target that has a scrollbar.

    First issue: when you call ScrollWindow on the window, the window flickers to white before direct2d updates the view.

    Second issue (this one might be my bug, but if it is, I can’t find it): when you render a clipped bitmap to a window that has a scrollbar, the bitmap is rendered with a extra space before the scrollbar (the space is incidentally equivalent to the width of the scrollbar). If you resize the window just a little (if even by a pixel) te bitmap gets snapped to the correct place.

    And there is also an issue when the render target is a window that is using a ribbon: the titlebar of the window gets rendered to, overwriting the custom titlebar the the ribbon creates.

  101. jq says:

    I have tried d2d sample in windows 7 7057.It seems does’t work.D2D1CreateFactory return E_NOINTERFACE.

    But it works on build 7022 and 7000.

  102. jq says:

    Thanks for the responses.

    I guess I should install the 7000 build to experience d2d and dwrite, and wait for the RC build.

  103. Scott-e says:

    I guess I should read these last few comments. I just installed W7 7057 specifically to start testing Direct2D. So am I dead in the water with this version?

    BTW, I too have been waiting for something like Direct2D for a LONG time, I excited to get started code with it and really hope MS backs this new API all the way!

  104. markus says:

    Your new framework sounds great! We work a lot with 2D graphics in the field of GIS (geo information systems) and are dependent on a high performance on the one side and on rich graphical possibilities on the other side. Your

    framework seems to combine both which makes it extremely interesting for us. We are using the existing 2d-frameworks (GDI, GDI+) in a very intensive manner, so there were always some things we ever wished to get better.

    Here are some things we would enjoy:

    * Support for Win XP because most of our customers use this system

    * Large Hatch Brushes, that means Brushes with a HatchStyle, a set of colors and a set of hatch-sizes which define the width of every bar in the hatch.

     Today we have a workaround for this by creating a tile and drawing it with a TextureBrush, but if printing this, the results are disappointing.

    * Support for relativly extreme transformation. If we draw in meter-based map-projections like mercator etc., we have transformation-matrices with scales about 0.001 (which means in this context: 100000 reality-metres are

    mapped to 100 pixels). We often had various problems with GDI+ and these transforms: text output and some pen-operations didn’t work correctly. We had always switch to 1:1-output whick previous rescaling fonts and pens.

    * Some more sophisticates pen-styles as they are used in map-signatures: double-lines, combined and complex lines (see

    http://mapserver.org/_images/line-symbol-complex.png for examples), or at least a possibility to define such line-styles

    * exact matrix-calculations also with nearly-0 values (I reported this GDI+-Bug in microsoft-connect:

    https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=337626)

  105. ScottBizzle says:

    After a rough time installing Windows7 multiple times I finally got Direct2D sample compiling. I notice a March DX SDK so I install and put their include/lib paths first. This stops the samples from compiling. To my suprise DirectX now includes some beta includes/libs for D2D which has some updated function calls.

    Can we assume this API will now work with Vista, or is it still only Win7 Man I wish the SDK came out a couple days earlier! haha I was pulling my hair out re-installing for days trying to get Direct2D setup for testing in Win7!

  106. Vertex says:

    Would it be possible to get specific data from Direct2D: E.g. I prepare Direct2D to draw an ellipse and instead of drawing it I want the vertices (as I may read it some posts before) to draw it with Direct3D. Any chance, and if so which interface? Mesh interface?

    Thx,

    Vertex

  107. Anthony Hodsdon says:

    Hi, Vertex. You can do this by implementing ID2D1TessellationSink and passing an instance to ID2D1Geometry::Tessellate. This will generate TRIANGLELIST data that you can then pass to D3D.

  108. Daniel Keymer says:

    I’m not terribly familiar with the whole DirectX paradigm, which may be why I’m wondering what the difference is between D2D and the (now apparently deprecated) DirectDraw. Wasn’t that also hardware-accelerated? At first glance it looks like it was dropped then resurrected and rebranded, but something tells me that’s not the case.

  109. Vertex says:

    Hi Tom,

    thx for your last comment!

    My 1st question: How is the D2D anti-aliasing level/quality comparable to D3D? Or if this is easier: What quality does D2D anti-aliasing has? (e.g. sample count, sample mask,…) This is very interesting if someone uses D2D and D3D stuff together.

    My 2nd question: D2D can use different hardware level or software to render. Can this be set and if not can someone get this info from D2D interface,factory or whatever?

    My 3rd question: Does D2D need D3D10.1 level hardware to fully work with without software emulation/computation?

    My 4th and last question: Am I right (as far what I have read) that software rendering (all that can be done on hardware) can be component wise? In other words: Is software and hardware rendering mixed?

    Thx,

    Vertex

  110. Tom Mulcahy says:

    1. D2D does 8×8 per-primitive anti-aliasing (Note: For performance reasons, in HW in some cases we use alpha ramps to simulate 8×8). The “8x8” part means that the quality is much higher, but the “per-primitive” part means that if you have abutting edges you will see artifacts. If you prefer MSAA you can do so using a ID2D1DxgiSurfaceRenderTarget.

    2. Sort of. When you create a render target you can specify a minimum feature level via the D2D1_RENDER_TARGET_PROPERTIES::minLevel parameter. We don’t allow you to get this information from the render target directly for versioning reasons. Instead, you can call ID2D1RenderTarget::IsSupported to determine if the render target has at least the minLevel of HW.

    3. No, Direct2D does not require D3D10.1 hardware. We require D3D10.1 interfaces, but these can be used on D3D9 hardware via Direct3D 10Level9. Using D3D9 hardware does impose some restrictions (e.g. bitmap and render target sizes). All rendering involves computation on the CPU since we need to send instructions to the GPU (also things like geometry tessellation are always done on the CPU). Using D3D9 level hardware may result in higher CPU usage because of the overhead associated with interacting with the D3D9 runtime, but we don’t emulate anything in software.

    4. No, Direct2D does not do mixed rendering. Each Direct2D render target is either SW or HW. If apps really want mixed rendering, they can explicitly compose results from different render target types. E.g. render to an IWICBitmap render target, then use the results in a ID2D1HwndRenderTarget that is doing HW rendering. Of course you will pay a performance penalty when copying across the bus, so apps should only do this if they have measured it to be more efficient.

  111. Vertex says:

    Thx Tom!

    To 3.: If Direct3D10.0 hardware is available: Does Direct2D fall back to Direct3D 10Level9 or does it use Direct3D 10.0?

    Two more questions: Let’s say someone wants to use Direct2D instead of existing GDI/GDI+ implementations. Is there anything missing in Direct2D, when replacing GDI/GDI+? (I know that you can use them together, but what I am talking about is only using D2D)

    Second question: Does the software rendering of Direct2D use WARP10?

    Just my thoughts (and maybe already a requirement for D2D2 sitting in front of you): It would be nice if things like geometry tessellation and other heavy CPU tasks would be ported to D3D11. ->Heavy offload to GPU. Maybe with a next big release, lets say D3D11.1 or whatever (at least when WARP11 gets shipped).

    + …as far as I tested, you did great job with D2D!

    Thx,

    Vertex

  112. Viktor Skarlatov says:

    Hello.

    I tried drawing with a HwndRenderTarget and then with a DCRenderTarget. In the first case the CPU usage is 0%, in the second case it is 60-70%. Is the the GDI interop taking that much CPU or is it me missing something ?

    I am simply drawing a rectangle at random locations on screen as fast as possible.

    Regards

    Viktor Skarlatov

  113. Viktor Skarlatov says:

    I tried with the SDK on Vista. Later today I will try it on Win 7 RC. Thank you for the reply.

    I still do not understand though. Is using a DCRenderTarget supposed to consume more CPU than a HwndRenderTarget? My questions was is this normal?

    Regards

    Viktor Skarlatov

  114. Vertex says:

    Hi, it’s me again 😉 (with feedback)

    I played a bit with porting GDI+ stuff to D2D. Doing this I mixed GDI+ and D2D drawings and found out (also in msdn docs) that clipping compatibility or interoperability is not given. (correct me if I am wrong plz!)

    GetDC of ID2D1GdiInteropRenderTarget should not be called between Push- and PopAxisAlignedClip functions. (as far as I tested, it doesn’t work anyway, the function returns no hdc)

    Any chance to see full clipping interoperability (clipping settings in e.g. D2D results in correct clipping regions in DC)in RTM?

    Using DX SDK March 09, since 7 RC is not yet available, I think. Will there be an updated SDK, and can you say if it comes out sometimes around 7 RC or some weeks later? Can we expect D2D changes (beside performance) in 7 RC?

    @Viktor Skarlatov: I had similar problems (I am working with GDI+ AND D2D, don’t know if you do). I switched over to ID2D1GdiInteropRenderTarget. As a result I changed architecture and reduced the following: Try to reduce BeginDraw/EndDraw to one if you have multiple calls (improves performance) and create factories/rendertargets only once at start (if possible).

    Thx,

    Vertex

  115. Vertex says:

    Would it be possible to support the GDI/GDI+ antialiasing modes to get fully compatible pixel output. My testings (simple Fillrectangle and a DrawRectangle for the border) showed me blurry results compared to GDI+. Nevertheless, it could also be my fault (maybe I am doing something wrong).

    Can you confirm this behaviour?

    Switching an application from GDI/GDI+ to D2D would mean that pixel output could not be guaranteed to be the same.

    Thx,

    Vertex

  116. thomas says:

    What’s the recommended way to PRINT geometries created with D2D? Creating bitmaps would be very resource intensive, especially on large-scale-printers (HP DesignJet e.g.).

    Do we have to use two different code paths for screen (D2D) and print (GDI) or can we use DC render targets?

    Thanks,

    Thomas

  117. Ben Constable says:

    @Viktor

    The way that DC render target works is by copying the DC contents to an offscreen bitmap (which is in HW or SW depending on how you created the render target), rendering the D2D content to this bitmap and then copying the result back to the DC.

    When you run Windows 7 with WDDM 1.1 drivers, window DCs are mostly backed with video memory, and therefore the copying mentioned above is done in HW in this case. This copying is very efficient – there is still some overhead but it is not too bad.

    If you do not have these newer drivers, or you have a DC that has a system memory bitmap selected into it (such as a DIB section), then you will be either doing system memory copies (for software rendering) or copies to / from video memory (for hardware rendering). Copying to and from video memory is an expensive operation. You might be able to do it quickly, but it will use CPU cycles. It is best to profile your application to figure out if the gain from rendering in HW is worth the expense to get the results to / from video memory. For example – if drawing a relatively small amount of content it might be the case that rendering in SW is the best option.

    Remember that each time you bind to a DC with a DC render target, memory is being allocated, potentially on the GPU, and this can be expensive, so try not to do it each frame. Also try to reduce how many times you do Begin / End draw per frame, because this reduces the number of copies. And remember that DC render target does not do any syncing with the presentation interval of the window manager, and this means that it does not naturally throttle like a hardware rendered HWND render target would. Using D2D1_PRESENT_OPTIONS_IMMEDIATELY will let the HWND target to unthrottled rendering if you want to compare – this creates a more apples to apples comparison for CPU usage.

    Ben Constable, D2D team

  118. Vertex says:

    I have resolved my blur problem (which wasn’t an AA problem anyway) more or less. It was the missing 0.5 Offset (which also comes with D3D10).

    Vertex

  119. John says:

    Can we expect Direct2D on the next Windows Embedded Compact (not Standard) platform? (previously known as Windows Embedded CE or Windows CE)

  120. Vertex says:

    [B]"Hi, Vertex. You can do this by implementing ID2D1TessellationSink and passing an instance to ID2D1Geometry::Tessellate. This will generate TRIANGLELIST data that you can then pass to D3D."[/B]

    Can someone explain me how this is meant exactly? The tessellationsink does not give me any triangle data. It can be used for the mesh interface. But as far as I can see mesh can only be used for drawing, not for getting the trianglelist.

    …or was the initial intention to implement the triangle stuff myself in an inherited tessellate interface?

    Anyone who can explain this to me?

    Thx,

    Vertex

  121. thomas says:

    Vertex: I just tried that.

    If you only need the data you implement an tesselationsink that copies the data.

    If you want to create a mesh at the same time you implement a tesselation sink that takes the tesseletion sink from D2D1Mesh.Open(), copy the data and pipe them to the other sink.

    Here’s a sample (2nd case, but without coyping the data):

    (MySink.h)

    #pragma once

    class MySink : public ID2D1TessellationSink

    {

    public:

      MySink(ID2D1TessellationSink *pSink);

      ~MySink(void);

       STDMETHOD_(void, AddTriangles)(

           __in_ecount(trianglesCount) CONST D2D1_TRIANGLE *triangles,

           UINT trianglesCount

           );

       STDMETHOD(Close)();

    public:

       unsigned long STDMETHODCALLTYPE AddRef();

       unsigned long STDMETHODCALLTYPE Release();

       HRESULT STDMETHODCALLTYPE QueryInterface(IID const& riid, void** ppvObject);

    private:

       LONG volatile m_cRefCount;

       ID2D1TessellationSinkPtr m_spSink;

    };

    (MySink.cpp)

    #include "StdAfx.h"

    #include "MySink.h"

    MySink::MySink(ID2D1TessellationSink *pSink) : m_cRefCount(0)

    {

    m_spSink = pSink;

    m_spSink->AddRef();

    }

    MySink::~MySink(void)

    {

    m_spSink->Release();

    }

    STDMETHODIMP_(void) MySink::AddTriangles(__in_ecount(trianglesCount) CONST D2D1_TRIANGLE *triangles,

     UINT trianglesCount)

    {

    m_spSink->AddTriangles(triangles, trianglesCount);

    }

    STDMETHODIMP MySink::Close()

    {

    return m_spSink->Close();

    }

    STDMETHODIMP_(unsigned long) MySink::AddRef()

    {

    return InterlockedIncrement(&m_cRefCount);

    }

    STDMETHODIMP_(unsigned long) MySink::Release()

    {

    if (InterlockedDecrement(&m_cRefCount) == 0)

      {

      delete this;

      return 0;

      }

    return m_cRefCount;

    }

    STDMETHODIMP MySink::QueryInterface(IID const& riid, void** ppvObject)

    {

    if (__uuidof(ID2D1TessellationSink) == riid)

      *ppvObject = dynamic_cast<ID2D1TessellationSink*>(this);

    else if (__uuidof(IUnknown) == riid)

      *ppvObject = dynamic_cast<IUnknown*>(this);

    else

      {

      *ppvObject = NULL;

      return E_FAIL;

      }

    return S_OK;

    }

    In the AddTriangles implementation you can copy the data to your own array.

    To use it you create a mesh, open it, save the tesselation sink ptr you get, create a MySink and put this ptr into the ctor:

            ID2D1TessellationSinkPtr sp_tessSink;

            hr = m_spRT->CreateMesh(&sp_mesh[i]);

            hr = sp_mesh[i]->Open(&sp_tessSink);

            MySink *pSink = new MySink(sp_tessSink);

            pSink->AddRef();

            hr = sp_path[i]->Tessellate(matResult, 3.0f, pSink);

            hr = pSink->Close();

    // insert a call here to get the data from your copy…

            pSink->Release();

    Hope that helps

    Thomas

  122. Vertex says:

    Thx Thomas!

    That helped a lot. My tests are working now!

    Thx,

    Vertex

  123. thomas says:

    Are the device independent Interfaces like ID2D1Geometry implemented in hardware or software? What performance do I have to expect?

    Thomas

  124. Jack Harris says:

    I’m getting an E_NOINTERFACE on the D2D1CreateFactory call and I have the last version of Windows 7 (RC 7100) and the RC version of the SDK. I also installed Visual Studio 10 (Beta 1).  Need help!!!!

  125. ViktorSkarlatov says:

    Is Direct2D suitable for drawing UI components?

    I am currently playing around (in Windows Forms) with the SlimDX managed Direct2D wrapper and I was wondering if there is a point to this. I am concerned about resource creation and disposal, since these operations are expensive. My idea is to make an implementation of the IGraphics interface which uses Direct2D underneath.

  126. Jack Harris says:

    I figures things out.  The problem is that the Visual Studio Beta uses older bindings then the bindings for Windows 7.  VS sets WindowsSdkDir macro to the 7.0A directory while the Window7 RC SDK using the 7.0 directory.  The problem is that even when you try to set up an environment variable VS doesn’t pick it up.  It only uses the value set in the registry.  I had to change the registry so that VS could alter the WindowsSdkDir variable.

    If you ask me this is a bug in Visual Studio because it should allow you to override the macro setting via the environment rather than the registry.

  127. Sascha Scandella says:

    "We can interop with WPF since we both use Direct3D. The trick, though, since WPF is using D3D9 and we’re using D3D10, is that you would need to use a D3D9 shared surface. I’m going to post a sample in an upcoming blog post that shows how to do this."

    I am really interested in the interop demo. Have you already made a sample application? How about performance? Is there a large overhead?

    Is texture swizzling needed?

  128. Mark R. says:

    Just adding our voice to those asking for Windows XP support. We build commercial desktop applications that would benefit greatly from this technology. But if it’s only available on Windows 7, it will be a LOOONG time before we can even *think* about using it.

  129. gl says:

    Sounds impressive overall – but XP support is crucial.  I could understand (though didn’t appreciate) that D3D 10 was limited to Vista+ (new driver model changes & marketing), but a 2D API has a much broader scope, and really requires wider compatibility to be universally useful.  Who would want to write eg. separate sophisticated vector rendering codepaths just to support XP for their GUI?  And how many games that could benefit will need to support XP for the forseeable future?

    I hope you guys find a way, once it’s on XP there should be massive uptake – I’ll be first in line.

  130. Richard says:

    I periodically search to see if Direct2D support has been added to XP but every time I’m disappointed to find it hasn’t.  

    Until Direct2D is made available for Windows XP the API is of no use since it won’t work on the majority of customers’ operating systems.  I’d love to start using it but as things stand there’s no way I can justify it.

    Please add XP support!

  131. Seth Hoffert says:

    Could you post an example of how to share Direct3D 11 surfaces (including swapchain surfaces) with Direct2D?

    I’ve created a d3d10 device (in addition to my existing d3d11 device) and I’m trying to use GetSharedHandle() to no avail… I can’t find any examples or anything on how to do this. 🙁

  132. Bob Hyatt says:

    scaling a bitmap down in d2d using stretchdraw (both interpolation types tried) produces lower quality than gdi+ using high quality interpolation. …or am i missing something?

    -bob

  133. Xiaoyi zhang says:

    Have you realized that the Dreamweaver run so slow in Vista/7.

    I think the old programs cannot gain the bennifit of D2D with no code change. It will be a big problem as the GDI performance in Vista/7 is so poor.

  134. Bob Wehner says:

    We have an Infrastructure Management application that uses its own drawing engine, originally founded on GDI, moved to GDI+, and now are looking for a solution to fix .WMF drawing issues with the GDI+ libraries and Hardware Accelaration.  This D2D looks promising.  However, without XP and 2K3 server support, we are not going to be able to take advantage of it.  Please help drive XP support into this improved library.  Also, please provide samples of GDI+ calls redone in D2D to help my code migration to the new environment, even as I utilize windows 7 environments.

    Question: Will this support 32 & 64-bit windows environments? comprehensively, which ones?

    Thanks in advance.

  135. Dave says:

    So now we have yes another new 2D library, however if I understand correctly if I want to create a simple textbox in a 3D scene I still have to do all of the drawing, cursor manipulation (backspace, arrow etc) myself?

    Your answer above says that common controls are still implemented in GDI/GDI+ so really nothing has changed. We seem to be continually stuck in this halfway house with an inconsistency with common controls and 2D rendering. I was really hoping that Windows 7 would clean this mess up!

  136. EC says:

    Hi all,

    I skipped Vista, got XP64 after 2KPro.

    Right now with these new API and capabilities,  DirectCompute, the enhanced NUMA support, and Direct2D, I’m seriously thinking of returning to developing software again, and would want to buy Windows 7 for the development platform of choice.  I’m sold on the technology and am saving some cash up for the eventual rebuild.

    BUT I worry that the recent noises from "the management" are stating that the Direct2D and 10-level-9 stuff will not be available to users running XP.  IMHO this will seriously impact the take-up of these technologies for commercial projects as a very large portion of their market segments will not be upgrading from XP for some time yet, probably not until their next PC purchase in many cases.  Most gamers don’t have bottomless wallets.  

    The new API and runtime facilities you guys are building are awesome to say the least.  I can understand that porting all this to XP would be a lot of work, however If the option remains closed for freely upgrading XP to have the ability to run games targeted at DX10/11 then game devs will lose that potential market if they use these new APIs – and the game industry and other sectors would and likely will suffer due to this.

    So: Why not make an "XP expansion" CD of your own that will add this for XP, even for a reasonably low price? 20 or 30 bucks / pounds / whatevers to keep their already stable [factory]install of XP running their games until the XP product support-cycle is over would be within folks’ budgets.  You get to sell an expansion just like like game devs do, the devs can develop using the new shiny stuff without financial penalty, and the users get to use their already-paid-for OS (maybe of choice) until they upgrade eventually anyway.

    Personally, I want to buy Windows7 to get back into developing again but using C++ native code, and graphics programming with Direct.. looks fun.  Where is my incentive to learn all this stuff, and buy the relevant kit to use it, if the market I might be able to develop for is halved or worse before I even start?

    My 2+2 cents.

    EC

    p.s. sorry about the long post.

    p.p.s.

    To add to dave’s question on textboxes etc., would it not now be feasible given these new api’s to build one stage further so to allow some form of interaction between Direct2D and the paint method of buttons et al using redirection to an artificial DC, with user-input-events being intercepted by the DX runtime and redirected to the UI control?  If the button or whatever renders instead to a bitmap that is then blitted to the Direct2D surface?  Sorta bind a UI and/or it’s elements to rects in the Direct2D scene?  Sounds simple, but then there maybe reasons this would not be simple?

  137. EC says:

    Me again.  Having re-read my post, I want to add some supporting thoughts.

    In addition to the Win-Win-Win for all sides concerned: an upgrade "expansion pack" for XP to add these new things seems natural, just like a game expansion would be, if and only if it’s priced at around game-price levels.  More would not work, nor sit well with customers.

    There is an additional thought and bonus that arises from this.

    Part of the annoyance that I and other folks get with the current ways-of-things is that the new shiny thing they buy this year becomes obsolete far too quickly, "upgrade or die!" will only push folks to seek alternatives.  The old naming strategy of incorporating the year into the product name did nothing to lessen that annoyance BTW.

    If I could buy your operating system, and know that it will suffice for my needs during it’s support-lifespan, even if new stuff from the next-gen OS might cost a _few_ dollars/whatevers more to update via an expansion to cover your development costs, then I would be far happier both immediately, AND later when it comes time to buy the next new OS for the next rig I build.  I could buy your product with far more confidence that it will remain a good and useful purchase for the machine on which it will be installed.

    Vista-buyers deserved the free-expansion they’re now getting.  I applaud the decision to provide that.

    Goodwill towards a better-supported product via a cheap expansion to keep the old machine running XP limping along until a new box is bought would be a good thing, no?

    Discuss, and flame me if you want, I’m thick [skinned] enough to take it 😀

  138. tom says:

    Direct2D’s font rendering finally makes text looks as good as on OSX, however without XP support I’m sure it will take at least another 5 years until most applications will (be able to) use it.

    Please give us Direct2D for XP (if it’s easier to implement then just make Direct2D use GDI/GDI+ on XP)

    This is absolutely essential to make Direct2D a success.

  139. kalbr says:

    @Thomas "I’ll discuss GDI/GDI+ interop in more depth in an upcoming post."

    Count me in as one interested in such a post!

    Regarding GDI+/GDI interop, I’ve been working on a Win32 wrapper of primitives (so I can  have relative consistency on Vista/Win7/XP.)

    Must say the D2D performance is very impressive.  In my sample app, I’m hitting 74-76 fps with 1024 draw rectangles of various colors alphablended.  Total CPU is around 44% (mind you effective CPU usage on this system is 11% since it’s a Quad core).  I look at the # undivided since it’s likely the UI thread load.

    GDI using alpha is around 15 fps with almost 100% CPU (majority of which is Kernel, not so good).  Turning off alpha brings it up to 45 fps but CPU is usage is still awful.

    GDI+ the load shifts from mainly kernel to mainly user, but still high.

    So well done!

    I’d be interested in any built-in interop.

    Right now I have three separate layers for the different technologies.  Of course, on XP it would not use the Direct2D layer, but I’m curious what sorts of things are possible.

    Thanks!

    Keith Albright

  140. Vertex says:

    I have some questions about clipping in D2D (I port a GDI/GDI+ Application):

    What happens if you call PushAxisAlignedClip more than once (with different rectangles). Are they combined together? Does the second replace the first one? Will the second be subtracted from the first if they overlap?

    Next question: Do PushAxisAlignedClip and PopAxisAlignedClip have to be inside BeginDraw and Enddraw, or can they also be outside (I think the latter because its from RT interface)?

    Next question: What happens if I use the gdi interoperability without calling  PopAxisAlignedClip before (I know the documentation says that I should not do that and I dont’t have a problem if applied clipping doesn’t work for the created GDI RT, but I would have a problem if some errors occur and I can’t draw with GDI or something else)

    Maybe documentation can also be extended a bit with some of that info.

    thx,

    Vertex

  141. Vertex says:

    One more: Is there a way to get the actual set clipbox like in GDI/GDI+?

    thx,

    Vertex

  142. kalbr says:

    @Vertex

    Dunno if you’ve seen the clipping sample on Code Gallery:

    http://code.msdn.microsoft.com/d2dcliprectslayers/Release/ProjectReleases.aspx?ReleaseId=2617

    I’m also interesting in this topic (haven’t yet gotten to explore clipping but intend to very soon)

    I agree much of the docs could use more details (especially for those of us coming from GDI/GDI+ world)

    Keith A

  143. Vertex says:

    thx keith,

    I will have a look at it.

    Vertex

  144. Himanshu says:

    I need to know how D2D handles the airspace issue in WPF. In D3D9 we had airspace issue when we try to put some UI controls on top of the D3D9 content.

    Thanks.

  145. Himanshu says:

    Thank you very much for the reply.

    But still i have some confusion regarding the interoperability issue.

    http://msdn.microsoft.com/en-us/magazine/dd861344.aspx

    In above article it is written that "There is no WPF airspace nonsense" while describing the Direct2D over WPF

    What i am assuming from the statement above that Direct2D has some way to handle the generic airspace issue that occurs when we try to place some alphablended UI control over Direct3D owned Hwnd in WPF.

    Or the statement above tries to say that UI designed with Direct2D does not have WPF airspace issue.

    This means that D3DImage is the only way to achieve the rendering in WPF environment by direct3d10 assuming no limitatations in terms of putting controls over the rendering area by WPF?

    Though the performance is a limit in above scenario.

    Basically i was looking for some method to render in WPF environment which gives me an experience of onscreen rendering.

    Thanks once again for reply.

  146. fred says:

    There is a standard API for 2D vector graphics called OpenVG. Why Direct2D does not follow this standard ?

  147. Raymond says:

    performance wise, does direct2D is as fast as directdraw if I just what to use it to render video frames? i.e. keep copying the new bitmap from another memory and drawbmp into hwndrender target. When I call ID2D1Bitmap::CopyFromMemory  to copy image from another memory location, does this operation take lots of CPU time? After this, when I call enddraw function, is there another memory copy will be triggered?

    thanks,