SdkForTheCompleteBeginner

From X-Plane SDK
Jump to: navigation, search

The X-Plane SDK

Starting up for the Absolute Beginner For the Mac, PC too!


A Wiki only works when everyone joins in to elaborate on, to correct any misinformation, or to straighten out any misconceptions. Please join in the process.

INTRODUCTION

I saw a title in a book shop a few years back, "TaeKwonDo in Seven Days!" Not! Nor will you, the complete beginner, be writing "black belt" plugins by the end of next week. However, you can expect to be having great fun, you will amaze yourself with your progress, and most likely you will develop an overwhelming sense of awe with where this skill can take you.

My first impressions: I found the process of beginning to write plugins for X-Plane no more difficult than getting started at building my first aircraft in Plane Maker, getting started designing scenery in AC3D, getting started in building 3D cockpits in AC3D, or getting started at learning to place scenery in World Maker. Each of the preceding really intimidated me as a beginner, each held a great number of seemingly unanswerable questions, and every one of them created an anxiety that held me back from starting.

The great thing is we don't have to work alone! We don't even have to stay within our neighbourhood. We can use the various X-Plane forums to get us over or around any road blocks or pitfalls. The whole world is at our keyboard!

My Progress: After two weeks of working with the X-Plane SDK I was able to modify several of the example programs to accomplish similar but somewhat different tasks, I made two simple plugins with some assistance from members of the X-Plane Dev Forum, and I was able to see the beginnings of how the multitude of pieces fit together. I could envision that with repeated practice I could become comfortable with making a host of plugins to accomplish a variety of tasks.

Where I'm going: I'm particularly drawn towards making plugins using the camera to build new views. For me the ultimate plugin would use networking to bring pilots and copilots from around the world together in the same aircraft.

QUICK START

If you are an experienced developer and find yourself here, looking at all the documentation, and wondering where to jump in and get going, there are two simple steps you can take to get started right away:

  1. [Download] the SDK itself. (Version 2 is in beta still as of May 2008, and Version 1 plugins can be compiled from the Version 2 SDK.)
  2. Get the HelloWorld example in the [SDKExamples.zip | http://www.xsquawkbox.net/xpsdk/lib/std_examples/SDKExamples.zip] package. It is well commented and comes with project files that can be compiled by many common compilers on the big three operating systems.

You may also find the following resources useful:

  • [Build and Install | BuildInstall] notes.
  • The [Overview] contains an overview of the SDK.
  • The [Documentation] for the SDK.
  • A list of [Gotchas] that have tripped-up other new developers.

REFERENCES AND MANUALS

Please add to this list with comments.

You are going to need some instruction in programming in C++. I prefer having a book in my hand and on my desk so I bought two readily available introductory manuals. Both books are very PC oriented. If you have a recommendation for a Mac specific book please make note of this in your comments.

C++ For Dummies, $25 US. Now there's is an oxymoron! I was self conscious carrying the book to the front of the store. The book is clearly written but chatty. It lacks colour coded examples which definitely makes C++ easier to read and organize. The material may be outdated; there are a number of syntax type items that appear much different than I'm seeing on my Mac.

C++ Programming in Easy Steps, $12 US. This is the better of the two book and well priced. It's concise and has handy reference tables throughout. Reading through the first 50 pages will give you a good start. It's colour coded. Keypoints are flagged. Several things appear slightly different than what I'm seeing on my Mac.

Practical C++ Programming, 2nd Edition, by Steve Oualline, $40 US. This book makes an excellent crash course for someone with programming skills in C, Java, or Obj-C. I would not recommend this book for beginners.

C++ Programming Language, 3rd Edition, by Bjarne Stroustrup, $70 US. This is the end-all book on C++, written by the inventor of C++ himself. It makes thick reading, but is the best resource there is for a C++ programmer.

Please add your favourite books here.

There are tons of helpful C++ resources on the internet. Two of the best are www.daniweb.com and www.cplusplus.com. Also check out www.DevX.com and www.TeckTips.com. Personally I don't enjoy the constant advertisements but they are free. I'd rather have a book.

Please document your favourite C++ website resource.

Note: It is possible to program the X-Plane SDK in languages other than C and C++. For the reason of not introducing another confusing element, can we keep this thread confined to these languages for the time being, please? Once this beginner thread is established I'd personally like to explore and take part in Wiki's for other languages.


SOFTWARE

C++ programs were initially created with a plain text editor. However, editors designed specifically for the job of C++ programing use colour coding and text alignments and other features that will greatly help you to organize and read your work.

To execute your work you will need a compiler to translate and build your text file into machine readable and executable code. The compiler will also report any syntax errors in your text code that would stop your code from being built.

Most modern programs combine the two functions above into one package - A Development Environment. Plus, they include many other features to organize your work and a host of resources all in the same file. Below are descriptions of readily available, and free, development packages.

MAC

For the Mac you will need an up to date copy of Xcode. This comes on the system disc with all new Macs. Or it is available free, upon registration at: http://developer.apple.com/tools/download/ . It's a whopping one GB download so you will require a high speed connection.

WINDOWS

For the Windows platform there are a number of editors and compilers available:

Dev-CPP is free from www.bloodshed.net.

C++ Integrated Development Environment may have come with your PC.

In November 2007 Microsoft released Visual C++ 2008 Express, a free integrated development environment (IDE). It has successfully built all the SDK examples including the advanced examples and I have successfully made Win builds of my own plugins using this software. A small installer program can be downloaded at:

http://www.microsoft.com/express/vc/Default.aspx.

Setup instructions described below.

LINUX

Most versions of Linux include the GNU C++ compiler free under General Public License. This is the end-all compiler for Linux development. While one can use Makefiles to compile from the command line, there are IDEs available, such as KDevelop.

NOW GET THESE MUST HAVE FILES

Download and expand these four (4) files from XSquawkbox. Important: put all four of the expanded zips in the same folder named XSDK.

The first is from the XSquawkbox / Frontpage / Downloads page.

[X-Plane SDK|Download] for Windows, Linux and Mac Mach-O in Zip format from the Note: the Mac CFM download is not needed unless you are planning on supporting OS 9.

The remaining three are from all from the XSquawkbox / Frontpage / Library page / PluginExamples page:

[SDKExamples.zip | http://www.xsquawkbox.net/xpsdk/lib/std_examples/SDKExamples.zip] This file has 12 basic program examples each illustrating two or three features of the SDK. This is where you will begin.

AdvancedSDKExamples.zip Advance examples

WidgetLibraryExample.zip Advanced examples illustrating pop up menus and so on.

Tip: Keep the zips for the 3 example files handy; you could place them into your XSDK 1.0.2 folder too. You will want to return to fresh copies of the examples regularly until you figure out the complex Save process of your compiler.

LET'S GET STARTED WITH THE SAMPLE FILES

Mac:

Open the SDKExamples > Projects > Mac folder. Double click SDKExamples.xcodeproj. On the left hand side bar locate and open: SDK > Source > Hello World > HelloWorld.c Hopefully you are seeing your first sample program.

Windows:

Following the installation of the complete program drag your XSDK folder described above into the Microsoft Visual Studio 9 folder. At this point you can start up MVC++2008 by opening XSDK > SDKExamples > Projects > Win > SDKExamples. The projects will report successful builds with this setup but the builds will not run on X-Plane.

Sandy advises: In the left hand sidebar, select one of the projects. Right click, Project > Properties > expand Configuration Properties > expand C/C++ > Code Generation > Runtime Library > Multi-threaded (/MT)

AND

Project > Properties > expand Configuration Properties > expand Linker > Manifest File > Generate Manifest > No

Additionally you will need to apply the above properties to the Debug and Release settings. These are accessed by clicking the Properties menu, located at the bottom of the LH sidebar.

You can now test that your example build runs successfully on X-Plane by searching the MVC++ 2008 folder for the appropriate .xpl file.

To produce your own plugin from scratch simply replace the C++ source for, let's say, the Camera example with your own source. Build your example. Rename the resultant Camera.xpl with your plugin name.

VC++ 2008 offers the choice of two build types: Debug and Release. Select your choice in the pull window directly beneath Help in the top Menu Bar.

Christian Menge has kindly provided an excellent video tutorial of how he setup MVC++ 2008 on his computer. This can be viewed at:

http://www.freedomworks.ca/


Linux: Instructions needed.

HELLOWORLD

Ninety percent of what you see are required function calls of the X-Plane SDK or setup requirements of .c or .c++ programs. These are rather complex functions and they make the program look much more difficult than it really is. That's because these functions do nearly all of the work for you! There are only a few lines of actual working code here. Look at line 195, near the end, beginning with "if"

If you have read through the first few dozen pages in a C++ manual, you should be able to piece together that this line says: If you detect that the mouse button is being clicked OR if the mouse button is being "unclicked" then make the value of gclicked, which can be either a one or a zero, the opposite to what it is. There are other ways to accomplish the same task; see if you can come up with a few. You can test out your coding after you've worked through the next few paragraphs.

Let's make a change: Line 157 contains two statements. Change "I'm a plugin" to "I'm Bob's first plugin!" and change "Hello World" to "X-Plane Rules!!" Make sure your work is between quotes AND be careful not to change anything else. C++ is very exacting in syntax.

Now we need to save and "build" or "compile" our work. Click the build button at the top of your editor. XCode or whatever editor you are using is going to whir for a bit, maybe even give you a few warnings, but if you haven't changed anything else in HelloWorld it will report "successful" at the bottom right.

Note: Your compiler may have recompiled all ten sample programs. If you play around with the Target menu on the left side you can make it compile only the HelloWorld program.

Now do a search of your computer for HelloWorld.xpl. You will probably find a few. Use Get Info to find the most recent of these. Follow its path to locate the file. *Remember this file path;* you are going to need to get this file everytime you make a change. Drag the file to X-Planes > Resources > Plugins file. Start up X-Plane. Click your mouse, hold, ... Unclick your mouse!! Congratulations you've made your first modification to an XP SDK program!

HelloWorld.c is very well annotated. If you read through the comments you'll quickly associate what many of the numbers mean. For example the numbers in line 62 define the corners of a text box that XPLM will draw on the X-Plane screen. Use your logic to figure out which corner each number refers to. Change a couple of them, save and build your plugin, install your modified plugin into X-Planes plugin folder, restart X-Plane and take a look to see the effect of your change.

Now try your hand at changing the C++ code in line 195. You will find this both challenging and rewarding.

Have fun playing with HelloWorld. Change text colours, print locations, etc. There's hours of fun just exploring this simple program.


CAMERA

Camera is terrific fun to play with! First, it is not so complex that the basic structure all plugins must follow is hidden. Second, it is easy to create many useful variations of the camera view.

Plugin Structure: Plugins must follow the structure and contain the component parts of C or C++ programming. Briefly, C and C++ programs must begin with a list of library resources. Ex: #include "XPLMGraphics.h" These are tested and proven pieces of code to accomplish specific tasks, written and made available for your convenience. Why reinvent the wheel? Library resources are followed by a list declaring all global variables and a list pre-registering any upcoming functions. These lists let the computer and the X-PlaneSDK (Software Developers Kit) prepare memory and allocate unique name spaces for your variables. C++'s "main ()" function is replaced by the X-PlaneSDK's "PLUGIN_API int XPluginStart()" function.

At the same time each plugin must contain the component parts of the SDK. There are *five required* PLUGIN_API functions (Application Programming Interface). The required functions, with brief descriptions thanks to SnailPup, are:

PLUGIN_API XPluginStart () This is a forced API (must be included) by the SDK. It is called once when the plugin is loaded. (constructor)

PLUGIN_API XPluginStop () This too is forced by the SDK. It is called once when the plugin is unloaded. (destructor)

PLUGIN_API XPluginEnable () Forced. This is called when the plugin is enabled, either right after it is loaded or when a user decides to enable it via the Plugin Manager.

PLUGIN_API XPluginDisable () Forced. This is called when the plugin is disabled, either just before it is unloaded or when a user decides to disable it via the Plugin Manager.

and

PLUGIN_API XPluginReceiveMessage () Forced. Used or not, we must make provision to receive messages from keyboard, mouse, X-Plane and other plugins.


For any practical application you will also need to use at least one of a large choice of commands specific to the X-PlaneSDK. These take the form of an XPLMCommand. The Camera plugin uses several. Examples are: XPLMCommandButtonPress(), XPLMGetMouseLocation() and XPLMGetDataf(). These commands are combined to create user built functions. Camera has two user built functions: MyHotKeyCallBack and MyOrbitPlaneFunction.

You will find it very helpful to print out the source code (Camera.c) for the Camera plugin. Draw horizontal lines across the page at the end of the library resources, the declarations, and after the end of each of the API and user functions. Make specific note of the start and end brace brackets.

After studying the organization of Camera.c load it into X-Plane and try it out. Now, what can we do with it?

As mentioned in the comments all the action takes place in the MyOrbitPlaneFunction. First, after declaring local variables, it gets the screen size and the mouse location. Next it calculates the ratio of the horizontal mouse position to the screens width and multiplies it by the number of degrees in a circle. Hmmm? Can you see how this defines the cameras heading according to how far left or right you have placed your mouse.

Then it does the same with the ratio of the vertical mouse position and the screens height. What's the meaning of the 20.0? Why the times 2.0 minus 1.0? Experiment!

Now we come to the lines with the trigonometric functions. What's the 200.0; why the minus sign with the change in x (dx) but not in z; why does the change in y use the tan function; did you observe the result of the tan function when the pitch constant is changed to 90? Math has never been so much fun!

Try making the camera roll angle equal to the roll of your aircraft. Whoa!

I changed the formula for calculating the heading to a structure similar to the calculation for pitch; when the mouse is roughly centered in the screen, the view always starts to the rear of the aircraft similar to X-Planes chase view. I also made the distance to the aircraft variable by wiggling a joystick axis and also by clicking the mouse. When I figure out how to use the mouse scroll wheel to accomplish the same I will have created my very own mouse controlled "ChaseViewDeluxe" plugin! The perfect view for circling around and zooming in on a loose flying formation with a multiplayer buddy.


CREATING AND SAVING NEW PROJECTS

Creating and saving a new plugin project is more involved than creating and saving a new text file. This is because your projects need to carry along with them associated files and library resources. The easiest way to create a new project is to modify an existing project and save it with a new name.

ON THE MAC

The following instructions apply to Xcode users on the Mac. The technique pretty much follows a posting from Sandy Barbour to the X-Plane Dev Forum. The details:

Expand SDKExamples.zip to create a new copy of SDKExamples. Rename this folder with the name of your project. For now, name it Scanner, because we will be making a Scanner plugin in the following example. Locate and open the Mac folder inside and rename the SDKExamples.xcodeproj, Scanner.xcodeproj. Double click Scanner.xcodeproj to initiate Xcode and bring up the new scanner project.

On the left hand sidebar of XCode locate and open the Source folder. Delete the folders to all the examples but one, SimData.c. We will use SimData as a good starting point for the following scanner project. Using right click > rename, change the name of SimData.c to Scanner.c. Don't forget the extension because Xcode uses the extension suffix to differentiate project and build files.

Now open the newly renamed Scanner.c folder. Rename SimData.c, Scanner.c.

We'll do the same with the Products folder: Open, delete all references except SimData.xpl. Rename SimData.xpl, Scanner.xpl.

And finally with the Target folder: Open, delete all references except SimData. Rename this file Scanner. This time with no extension.

Done! Just to be certain, quit out of Xcode and restart your project by double clicking Scanner.xcodeproj in the Mac folder.

Lingering Question: I'd be curious to know if anyone can explain why my Xcode builds always report 4 warnings but never records the reason in the Errors and Warnings file. Could this have something to do with using Xcode 2.4.1 or could it be the result of the examples being written in c and not c++?

ON THE PC

PC instructions appreciated.


SCANNER

Building a plugin to simulate the rapidly rotating frequency dial of a scanner is a rewarding first project. Although it is a "novelty idea" it demonstrates usage of a flight loop. Half the work is ready made if you use SimData.c as a starting point. It is suggested that Com2 be used as the receiver.

SimData uses the XPLMMenu items to increment or decrement the Nav1 frequency via a pull down menu. Scanner will increment the Com2 frequency in a continuous loop; to do this a flight loop is substituted for the pull down menu. For the purpose of drawing your attention to details, a number of hints follow:

Scanner will not require #include "XPLMMenus.h" Below, all Menu references will be deleted.

The function MyMenuHandlerCallback() will not be used so it does not need to be preregistered.

The main function, XPluginStart(), will not need to initialize XPLMMenuID or mySubmenuItem, nor will it be required to append, or create any menu or submenu items. After these items are removed, the tasks remaining for XPluginStart() is to provide the plugins profile to the plugin system, find the data ref for the Com2 radio, and return 1 if it found the data ref and initialized correctly.

You can find the data ref for the Com2 radio from the Documentation page. You may prefer using, "Current listing of X-Plane DataRefs in plain text " over DataRefs in html. Data refs are much easier to search on the page with your browsers Find command. It's almost pointless to print out and search by hand all 88 pages! (Speaking from experience, LOL!)

MyMenuHandlerCallback() can be removed. But you may wish to use keep the XPLMSetDatai assignment statement as a starting point for pasting into the flight loop.

Now the program can be reconstructed by adding a number of flight loop items to replace the preceding deleted menu items. Many of these can be copied and pasted from the ready made TimedProcessing.c example OR for a really challenging learning experience these can be copied and pasted from XPLMProcessing . It's much harder to do from scratch.

Start by preregistering MyFlightLoopCallback() as a global function.

The XPluginEnable API and the XPluginDisable API's will need to contain XPLMRegisterFlightLoopCallback() and XPLMUnregisterFlightLoopCallback() respectively. Alternatively, these could be placed in the XPluginStart() and XPluginStop() API's.

(I'd be curious to know if there is an advantage to either of these placements. See DeferredInitialization )

Towards the end of the program add your MyFlightLoopCallback() function. This replaces MyMenuHandlerCallback and is the business part of your plugin. As a minimum it needs to find the current frequency of the Com2 channel, increment it, and return the time until the next callback when it loops around to increment the frequency again. It is more realistic, plus you will be rewarded, if you keep the frequency between 118.00 and 136.00 khz. Keep the volume turned up!

More hints: the Com and Nav frequencies are stored as an integers. Study this link, XPLMProcessing , to see how to set the time for the next iteration of MyFlightLoopCallback(). This needs to be set in more than one place.

Many more features could be built into Scanner; enjoy! Post your Scanner to the files of X-Plane-Dev; it will be interesting and instructive to see where you take it.


ON YOUR OWN NOW

Write a plugin to start up X-Plane in 3D mode. At the time of writing there are some pitfalls in the SDK.

Hint: it is easy to write a plugin to get X-Plane to start up in chase view. Try it.

Another hint: Use DataRefEditor to observe the effect of key presses to the entries in "sim/graphics/view/view_type."


DATA REF EDITOR

On the PluginExamples page you will find some platform specific, SDKPlugin archives. Expand the version for your platform. Inside you will find 3, ready to use, .xpl binary files. One of these, DataRefEditor, makes the process of searching the datarefs very efficient. Drop it into X-Planes plugin folder.

When using your browser to view the datarefs the Find command will locate only one dataref at a time. Using DataRefEditor, simply type a keyword at the bottom and you can view all instances of your keyword at once! You also get to see each datarefs current value and can quickly deduce its type. If it shows a 0 or 1 it's most likely a Boolean flag. Between 0.00000 and 1.000000 most likely a ratio, if it's a decimal number you know it's a float. Sixteen digits it's a double. If the value is flickering it's continuously being updated. All this for multiple datarefs taken in at one glance. This is very much more efficient than scouring the datarefs in a browser; thousands of times more efficient than reading a printed copy.

There's more. You can open multiple DataRefEditor windows at a time; plus each window is resizable and moveable. This will allow you to monitor a diverse set of datarefs that don't match the same "find" string.

You also get a chance to edit the dataref and simultaneously observe the effect in the sim. Edit the dataref to add fuel, and you can instantly observe the fuel gauge needle go up. I sure wish we could do this with our cars! Just as useful, you can observe that editing the dataref did not have the desired effect.

DataRefEditor is a gold mine of information right on your X-Plane screen. If you are flying X-Plane and get an idea for a plugin, turn on DataRefEditor from X-Planes plugin menu. You can easily find and observe the behavior of the datarefs you are interested in at the same time. You can quickly test out ideas while in flight to see how your plugin might be designed or if your plugin idea will work.


WHAT'S NEXT

This page has documented my growth with the X-Plane SDK over a period of one month. Starting from zilch, zero, zot, null, nothing, notta, ... it has been a challenging and rewarding project for me. I wish your entry to be equally pleasant and exciting. I'll watch this page over the foreseeable future. I'd be pleased to hear from you. Keep in touch via postings to X-Plane-Dev or write me directly, [by clicking here. |mailto:BFeaver@mac.com]

Blue side up, Bob

January, 2007.


Content added by:

[Jeff Reinecke|http://www.paploo.net/]: Added the Quick Start and some other minor changes. (May, 2008)

If you have added content to this page, please add your name here. If you wish to leave your email address you can log in to gain access to edit mode, and view the Wiki syntax I have used.