Click here to Skip to main content
6,292,811 members and growing! (10,330 online)
Email Password   helpLost your password?
Multimedia » DirectX » General     Intermediate License: The Code Project Open License (CPOL)

Force Feedback in Managed DirectX

By Christopher M. Park

A C# example of working Force Feedback in Managed DirectX
C# (C# 2.0), Windows, .NET (.NET 2.0), DirectX, Dev
Posted:16 Mar 2008
Views:11,805
Bookmarked:9 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
5 votes for this article.
Popularity: 3.18 Rating: 4.56 out of 5
1 vote, 20.0%
1

2

3

4
4 votes, 80.0%
5

Introduction

Managed DirectX is a great way to write DirectX applications in .NET languages, and most of the Managed DX libraries are well documented, robust, and have numerous examples floating around the Internet. I've been coding Managed DX off and on since it first arrived in 2002, but never messed with force feedback until recently.

Imagine my surprise to find that all the public examples for force feedback code in C# error out with my game pad (Logitech 2 Rumble). Many other people have posted on various Internet forums about this issue with Managed DirectX and other game pads, so this appears to be a very long running bug in the Managed DirectInput libraries. Though there are a number of people reporting this issue, I was not able to find a solution that worked for me anywhere -- so here's my own solution.

The attached project provides examples of how to create and trigger several different forces, so if you're new to force feedback in C#, this has everything you need to get started all in one place.

Background

If you'd like to see Microsoft's standard example (which doesn't work for me), visit this link.

The solution I eventually found was unique, but triggered in part by a blog post by Ayucar.

Using the Code

The attached project has the entire code, but here are the (somewhat simplified) highlights in case you are already familiar with the examples but just keep getting that "Value does not fall within expected range" error.

Basic Device Initialization

Device Dev = null;
    
foreach ( DeviceInstance instance in Manager.GetDevices( DeviceClass.GameControl,
    EnumDevicesFlags.AttachedOnly ) )
{
    Dev = new Device( instance.InstanceGuid );
}
            
Dev.SetDataFormat( DeviceDataFormat.Joystick );
Dev.SetCooperativeLevel( Parent, CooperativeLevelFlags.Background |
    CooperativeLevelFlags.Exclusive );
Dev.Properties.AxisModeAbsolute = true;
Dev.Properties.AutoCenter = false;
Dev.Acquire();

The above is pretty typical of DirectInput examples. The AutoCenter = false line is particularly needed for force feedback. The Parent variable in the SetDataFormat line must be a System.Windows.Forms.Control.

Finding the Axes

int[] axis = null;

// Enumerate any axes
foreach ( DeviceObjectInstance doi in Dev.Objects )
{
    if ( ( doi.ObjectId & (int)DeviceObjectTypeFlags.Axis ) != 0 )
    {
        // We found an axis, set the range to a max of 10,000
        Dev.Properties.SetRange( ParameterHow.ById,
        doi.ObjectId, new InputRange( -5000, 5000 ) );
    }

    int[] temp;

    // Get info about first two FF axii on the device
    if ( ( doi.Flags & (int)ObjectInstanceFlags.Actuator ) != 0 )
    {
        if ( axis != null )
        {
            temp = new int[axis.Length + 1];
            axis.CopyTo( temp, 0 );
            axis = temp;
        }
        else
        {
            axis = new int[1];
        }
    
        // Store the offset of each axis.
        axis[axis.Length - 1] = doi.Offset;
        if ( axis.Length == 2 )
        {
            break;
        }
    }
}

Everything until the int[] temp is declared is your standard DirectInput axes initialization -- you have to do those things regardless of whether or not you are using force feedback. The axis array calculation is force-feedback-specific, and is all taken directly from the Microsoft examples (I didn't add anything new there).

Creating a Force

InitializeForce( Dev, EffectType.ConstantForce, axis,
    10000, EffectFlags.ObjectOffsets | EffectFlags.Spherical, 250000 ) );
        
public static EffectObject InitializeForce( Device Dev, EffectType Type,
int[] Axis, int Magnitude, EffectFlags Flags, int Duration )
{
    EffectObject eo = null;
    Effect e;

    foreach ( EffectInformation ei in Dev.GetEffects( EffectType.All ) )
    {
        if ( DInputHelper.GetTypeCode( ei.EffectType ) == (int)Type )
        {
            e = new Effect();
            e.SetDirection( new int[Axis.Length] );
            e.SetAxes( new int[1] );

            e.EffectType = Type;
            e.ConditionStruct = new Condition[Axis.Length];
            e.Duration = Duration;
            e.Gain = 10000;
            e.Constant = new ConstantForce();
            e.Constant.Magnitude = Magnitude;
            e.SamplePeriod = 0;
            e.TriggerButton = (int)Microsoft.DirectX.DirectInput.Button.NoTrigger;
            e.TriggerRepeatInterval = (int)DI.Infinite;
            e.Flags = Flags;
            e.UsesEnvelope = false;

            // Create the effect, using the passed in guid.
            eo = new EffectObject( ei.EffectGuid, e, Dev );
        }
    }

    return eo;
}

Here's where my solution comes in. The line that normally errors out is e.SetAxes(new int[Axis.Length]); It usually gives an exception "Value does not fall within expected range", which is evidently a bug in Managed DirectX (at least affecting some game pads). Changing that line so that it always initializes an axis array of length 1 instead of length 2 (as the Microsoft example would do) fixes this issue seemingly without any other side effects to performance or function.

I should note that I have not been able to successfully load FFE files in Managed DirectX due to this same problem. Presumably, in the inner initialization code when loading from FFE, it is trying to load two axes there, as well. This problem exists with all versions of Managed DirectX, as far as I can tell, at least up through March 2008 when this article was written.

Points of Interest

Force feedback is underutilized in most PC games, possibly because the technology was not available in low end game pads until relatively recently. Adding force feedback capabilities to your games is a great way to provide a more immersive experience, and a minor way to stand out in the PC games market.

History

  • Version 1: March 16, 2008

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Christopher M. Park


Member

Occupation: Chief Technology Officer
Company: Starta Development, Inc.
Location: United States United States

Other popular DirectX articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
GeneralExcellent! PinmemberJohan Bergelo4:51 1 Apr '09  
GeneralRe: Excellent! PinmemberChristopher M. Park5:13 1 Apr '09  
GeneralA good & simple example PinmemberMarcin Smialek22:12 15 Sep '08  
GeneralRe: A good & simple example PinmemberChristopher M. Park2:54 16 Sep '08  
GeneralRuntime Error PinmemberNathan Trimble7:26 1 Aug '08  
GeneralRe: Runtime Error PinmemberNathan Trimble7:33 1 Aug '08  
GeneralRe: Runtime Error PinmemberChristopher M. Park8:49 1 Aug '08  
GeneralRe: Runtime Error PinmemberNathan Trimble9:18 1 Aug '08  
GeneralRe: Runtime Error PinmemberChristopher M. Park9:33 1 Aug '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Mar 2008
Editor: Deeksha Shenoy
Copyright 2008 by Christopher M. Park
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project