Home > Articles > Programming > Games

📄 Contents

  1. Creating Your Project
  2. Enumerating All Device Options
  3. Summary
This chapter is from the book

This chapter is from the book

Enumerating All Device Options

Now you're ready to have the framework start enumerating the devices on your system. First, declare a constructor for the game engine class, and pass in the sample framework's instance you've created from main. See Listing 3.3.

Listing 3.3 Adding a Constructor

private Framework sampleFramework = null; // Framework for samples
/// <summary>Create a new instance of the class</summary>
public GameEngine(Framework f) 
{ 
  // Store framework
  sampleFramework = f; 
}

The constructor doesn't do anything other than store the sample framework instance because that is required for almost everything that happens within the game. One of the first things the sample framework does after you invoke it is try to enumerate all the devices on your system. In your project file, you'll see a file dxmutenum.cs in the Framework folder you created earlier. This file contains all the necessary code to enumerate the devices on your system. Because it is important that you understand the how and why of the device enumeration, open that file now.

One of the first things you should notice is that the Enumeration class itself cannot be created, and every member variable and method is declared as static. Because it is (at least currently) extremely unlikely that your graphics hardware would change while your application is running (and the computer is on), it is reasonable to have the enumeration code run only once at the beginning of the application.

The bulk of the enumeration works starts from the Enumerate method, which is called by the sample framework before device creation. Notice that the only parameter this method accepts is the interface you've implemented in the game engine class so far. This interface is stored because later, as the device combinations are enumerated, the IsDeviceAcceptable method is called to determine whether the device should be added to the list of valid devices.

So how are the devices actually enumerated? The bulk of the functionality resides in the Manager class from Managed DirectX. If you're familiar with the unmanaged DirectX Application Programming Interface (API), this class mirrors the IDirect3D9 Component Object Model (COM) interface. Notice the first loop in the Enumerate method in Listing 3.4.

Listing 3.4 Enumerating Devices

// Look through every adapter on the system
for each(AdapterInformation ai in Manager.Adapters)
{
  EnumAdapterInformation adapterInfo = new EnumAdapterInformation();
  // Store some information
  adapterInfo.AdapterOrdinal = (uint)ai.Adapter; // Ordinal
  adapterInfo.AdapterInformation = ai.Information; // Information

  // Get list of all display modes on this adapter. 
  // Also build a temporary list of all display adapter formats.
  adapterFormatList.Clear();

  // Now check to see which formats are supported
  for(int i = 0; i < allowedFormats.Length; i++)
  {
    // Check each of the supported display modes for this format
    for each(DisplayMode dm in ai.SupportedDisplayModes[allowedFormats[i]])
    {
      if ( (dm.Width < minimumWidth) ||
        (dm.Height < minimumHeight) ||
        (dm.Width > maximumWidth) ||
        (dm.Height > maximumHeight) ||
        (dm.RefreshRate < minimumRefresh) ||
        (dm.RefreshRate > maximumRefresh) )
      {
        continue; // This format isn't valid
      }

      // Add this to the list
      adapterInfo.displayModeList.Add(dm);

      // Add this to the format list if it doesn't already exist
      if (!adapterFormatList.Contains(dm.Format))
      {
        adapterFormatList.Add(dm.Format);
      }
    }
  }

  // Get the adapter display mode
  DisplayMode currentAdapterMode = ai.CurrentDisplayMode;
  // Check to see if this format is in the list
  if (!adapterFormatList.Contains(currentAdapterMode.Format))
  {
    adapterFormatList.Add(currentAdapterMode.Format);
  }

  // Sort the display mode list
  adapterInfo.displayModeList.Sort(sorter);

  // Get information for each device with this adapter
  EnumerateDevices(adapterInfo, adapterFormatList);

  // If there was at least one device on the adapter and it's compatible,
  // add it to the list
  if (adapterInfo.deviceInfoList.Count > 0)
  {
    adapterInformationList.Add(adapterInfo);
  }
}

The Adapters property on the Manager class is a collection that contains information about every "adapter" on your system. The term adapter is somewhat of a misnomer, but the basic definition is anything a monitor can connect to. For example, let's say you have an ATI Radeon 9800 XT graphics card. There is only a single graphics card here, but it is possible to hook up two different monitors to it (via the video graphics adapter [VGA] port and the Digital Visual Interface [DVI] port on the back). With the two monitors hooked up, this single card would have two adapters, and thus two different devices.

NOTE

There is a way to have a single card share resources among all "different" devices by creating the device as an adapter group. There are several limitations to this approach. See the DirectX documentation for more information on this topic.

Depending on your system, this loop has at least a single iteration. After storing some basic information about the currently active adapter, the code needs to find all the possible display modes this adapter can support in full-screen mode. You'll notice here that the supported display modes can be enumerated directly from the adapter information you are currently enumerating, and that's exactly what this code is doing.

The first thing that happens when a display mode is enumerated is it's checked against a set of minimum and maximum ranges. Most devices support a wide range of modes that nothing would actually want to render at today. A number of years ago, you might have seen games running in a 320x200 full-screen window, but today it just doesn't happen (unless you happen to be playing on a handheld such as Gameboy Advance). The default minimum size the sample framework picks is a 640x480 window, and the maximum isn't set.

NOTE

Just because the sample framework picks a minimum size of 640x480, that doesn't mean in full-screen mode the sample framework will choose the smallest possible size. For full-screen mode, the framework picks the best available size, which is almost always the current size of the desktop (which most likely is not 640x480).

After the supported modes that meet the requirements of the framework are added to the list, the current display mode is then added because it is naturally always supported. Finally, the modes themselves are sorted by an implementation of the IComparer interface. See Listing 3.5.

Listing 3.5 Sorting Display Modes

public class DisplayModeSorter : IComparer
{
  /// <summary>
  /// Compare two display modes
  /// </summary>
  public int Compare(object x, object y)
  {
    DisplayMode d1 = (DisplayMode)x;
    DisplayMode d2 = (DisplayMode)y;

    if (d1.Width > d2.Width)
      return +1;
    if (d1.Width < d2.Width)
      return -1;
    if (d1.Height > d2.Height)
      return +1;
    if (d1.Height < d2.Height)
      return -1;
    if (d1.Format > d2.Format)
      return +1;
    if (d1.Format < d2.Format)
      return -1;
    if (d1.RefreshRate > d2.RefreshRate)
      return +1;
    if (d1.RefreshRate < d2.RefreshRate)
      return -1;

    // They must be the same, return 0
    return 0;
  }
}

The IComparer interface allows a simple, quick sort algorithm to be executed on an array or collection. The only method the interface provides is the Compare method, which should return an integer—namely, +1 if the left item is greater than the right, -1 if the left item is less than the right, and 0 if the two items are equal. As you can see with the implementation here, the width of the display mode takes the highest precedence, followed by the height, format, and refresh rate. This order dictates the correct behavior when comparing two modes such as 1280x1024 and 1280x768.

Once the modes are sorted, the EnumerateDevices method is called. You can see this method in Listing 3.6.

Listing 3.6 Enumerating Device Types

private static void EnumerateDevices(EnumAdapterInformation adapterInfo, 
  ArrayList adapterFormatList)
{
  // Ignore any exceptions while looking for these device types
  DirectXException.IgnoreExceptions();
  // Enumerate each Direct3D device type
  for(uint i = 0; i < deviceTypeArray.Length; i++)
  {
    // Create a new device information object
    EnumDeviceInformation deviceInfo = new EnumDeviceInformation();

    // Store the type
    deviceInfo.DeviceType = deviceTypeArray[i];

    // Try to get the capabilities
    deviceInfo.Caps = Manager.GetDeviceCaps(
      (int)adapterInfo.AdapterOrdinal, deviceInfo.DeviceType);

    // Get information about each device combination on this device
    EnumerateDeviceCombos( adapterInfo, deviceInfo, adapterFormatList);

    // Do we have any device combinations?
    if (deviceInfo.deviceSettingsList.Count > 0)
    {
      // Yes, add it
      adapterInfo.deviceInfoList.Add(deviceInfo);
    }
  }
  // Turn exception handling back on
  DirectXException.EnableExceptions();
}

When looking at this code, you should notice and remember two very important things. Can you guess what they are? If you guessed the calls into the DirectXException class, you win the grand prize. The first one turns off exception throwing in virtually all cases from inside the Managed DirectX assemblies. You might wonder what benefit that would give you, and the answer is performance. Catching and throwing exceptions can be an expensive operation, and this particular code section could have numerous items that normally throw these exceptions. You would expect the enumeration code to execute quickly, so any exceptions that occur are simply ignored, and after the function finishes, normal exception handling is restored. The code itself seems pretty simple, though, so you're probably asking, "Why would this code be prone to throwing exceptions anyway?"

Well, I'm glad you asked, and luckily I just happen to have a good answer. The most common scenario is that the device doesn't support DirectX 9. Maybe you haven't upgraded your video driver and the current video driver doesn't have the necessary code paths. It could be that the card itself is simply too old and incapable of using DirectX 9. Many times, someone enables multimon on his system by including an old peripheral component interconnect (PCI) video card that does not support DirectX 9.

The code in this method tries to get the capabilities and enumerate the various combinations for this adapter, and it tries to get this information for every device type available. The possible device types follow:

  • Hardware—The most common device type created. The rendering is processed by a piece of hardware (a video card).

  • Reference—A device that can render with any settings supported by the Direct3D runtime, regardless of whether there is a piece of hardware capable of the processing. All processing happens in software, which means this device type is much too slow in a game.

  • Software—Unless you've written a software rasterizer (in which case, you're probably beyond this beginners' book), you will never use this option.

Assuming some combination of device settings was found during the enumeration, it is stored in a list. The enumeration class stores a few lists that the sample framework uses later while creating the device. See Listing 3.7 for the EnumerateDeviceCombos method.

Listing 3.7 Enumerating Device Combinations

private static void EnumerateDeviceCombos(EnumAdapterInformation adapterInfo, 
  EnumDeviceInformation deviceInfo, ArrayList adapterFormatList)
{
  // Find out which adapter formats are supported by this device
  for each(Format adapterFormat in adapterFormatList)
  {
    for(int i = 0; i < backbufferFormatsArray.Length; i++)
    {
      // Go through each windowed mode
      bool windowed = false;
      do
      {
        if ((!windowed) && (adapterInfo.displayModeList.Count == 0))
          continue; // Nothing here

        if (!Manager.CheckDeviceType((int)adapterInfo.AdapterOrdinal, 
          deviceInfo.DeviceType, adapterFormat, 
          backbufferFormatsArray[i], windowed))
            continue; // Unsupported

        // Do we require post pixel shader blending?
        if (isPostPixelShaderBlendingRequired)
        {
          if (!Manager.CheckDeviceFormat(
              (int)adapterInfo.AdapterOrdinal, 
              deviceInfo.DeviceType, adapterFormat, 
              Usage.QueryPostPixelShaderBlending, 
              ResourceType.Textures, backbufferFormatsArray[i]))
            continue; // Unsupported
        }

        // If an application callback function has been provided, 
        // make sure this device is acceptable to the app.
        if (deviceCreationInterface != null)
        {
          if (!deviceCreationInterface.IsDeviceAcceptable(deviceInfo.Caps, 
            adapterFormat, backbufferFormatsArray[i],windowed))
            continue; // Application doesn't like this device
        }

        // At this point, we have an adapter/device/adapterformat/
        // backbufferformat/iswindowed DeviceCombo that is supported 
        // by the system and acceptable to the app. We still need
        // to find one or more suitable depth/stencil buffer format,
        // multisample type, and present interval.

        EnumDeviceSettingsCombo deviceCombo = new 
         EnumDeviceSettingsCombo();

        // Store the information
        deviceCombo.AdapterOrdinal = adapterInfo.AdapterOrdinal;
        deviceCombo.DeviceType = deviceInfo.DeviceType;
        deviceCombo.AdapterFormat = adapterFormat;
        deviceCombo.BackBufferFormat = backbufferFormatsArray[i];
        deviceCombo.IsWindowed = windowed;

        // Build the depth stencil format and multisample type list
        BuildDepthStencilFormatList(deviceCombo);
        BuildMultiSampleTypeList(deviceCombo);
        if (deviceCombo.multiSampleTypeList.Count == 0)
        {
          // Nothing to do
          continue;
        }
        // Build the conflict and present lists
        BuildConflictList(deviceCombo);
        BuildPresentIntervalList(deviceInfo, deviceCombo);

        deviceCombo.adapterInformation = adapterInfo;
        deviceCombo.deviceInformation = deviceInfo;

        // Add the combo to the list of devices
        deviceInfo.deviceSettingsList.Add(deviceCombo);
        // Flip value so it loops
        windowed = !windowed;
      }
      while (windowed);
    }
  }
}

Much like earlier methods, this one goes through a list of items (in this case, formats) and creates a new list of valid data. The important item to take away from this method is the call into the IsDeviceAcceptable method. Notice that if false is returned from this method, the device combination is ignored.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020