3. August 2015

 

It was becoming clear that Autodesk was entering the game market when they purchased BitSquid back in June of last year.  In addition to making the Magicka series of games, they also created the BitSquid game engine.  In March of 2015 Autodesk announced that Bitsquid was now the Stingray Game Engine and that it was coming soon.  Today more details emerged, including pricing and a release date.  Here is the official press release:

image

 

 

Autodesk Launches Stingray Game Engine at GDC Europe 2015


COLOGNE, Germany, August 3, 2015 --
At the Game Developers Conference (GDC) Europe 2015, Autodesk (NASDAQ: ADSK) announced that its new Stingray game engine will be available to game developers worldwide beginning August 19, 2015. Later this summer, Autodesk will also offer Autodesk Maya LT Desktop Subscription customers access to Autodesk Stingray as part of their subscription.


Built on the powerful, data-driven architecture of the Bitsquid engine, which Autodesk acquired in 2014, Stingray is a comprehensive new platform for making 3D games. The engine supports a host of industry-standard game development workflows and includes powerful connectivity to Autodesk 3D animation software that simplifies game development across a wide range of platforms.


"Between Augmented Reality, Virtual Reality and the proliferation of mobile platforms, the games industry is undergoing a major transition, which poses new complexities for both AAA and indie game developers. Autodesk developed Stingray with these challenges in mind, and we're excited to share its debut with the game developer community," said Autodesk senior vice president, Media & Entertainment, Chris Bradshaw. "Stingray makes it easy and intuitive for artists with varying skill sets and programming expertise to create the next generation of 3D blockbuster games, entertainment and even architecture."

 


Stingray feature highlights include:


-- Seamless Art-to-Engine Workflow:
Import, create, iterate, test and review 3D assets and gameplay faster with a one-click workflow and live link between Stingray and Autodesk 3D animation software.


-- Modern Data-Driven Architecture: A lightweight code base gives game developers the freedom to make significant changes to the engine and renderer without requiring source code access.


-- Advanced Visuals and Rendering: Produce visually stunning games with a powerful rendering pipeline, physically-based shading, advanced particle effects, post processed visual effects, lightmap baking and a high-performance reflection system.


-- Proven Creative Toolset: Stingray includes proven solutions like Beast, HumanIK, Navigation, Scaleform Studio (UI technology built on Scaleform), FBX, Audiokinetic Wwise and NVIDIA PhysX.


-- Versatile Game Logic Creation: Stingray includes a wide range of development tools, making game creation more accessible for game makers with varying levels of experience - including visual node-based-scripting and Lua scripting. C++ source code will also be available as an additional purchase upon request.


-- Multiplatform Deployment and Testing: Quickly make and apply changes to gameplay and visuals across supported platforms: Apple iOS, Google Android, Microsoft Windows 7 and Windows 8, Oculus Rift DevKit 2, Sony PlayStation 4 and Microsoft Xbox One.


Autodesk previewed Stingray at GDC 2015 earlier this year in San Francisco. Since then, game developers around the world have signed up for Autodesk's beta program, shipped games using this technology and provided feedback including:


"Stingray's data-driven architecture and flexibility have helped us build a broad portfolio of games, and quick iteration times for both code and content creators has boosted our productivity significantly. The engine has been a key success factor for us because we're able to produce high quality games in a shortened timeframe. We're excited to see how Autodesk will continue to evolve the engine," shared Martin Wahlund, CEO of Fatshark.


"We never know what kind of games we're going to create, and the engine is good for that. It really allows us to just make anything. We can make an FPS or an RTS, or a top-down shooter, or a role-playing game, or whatever. It's not tied to a specific genre," explained Johan Pilestedt, CEO, Arrowhead Game Studios.


The Stingray engine can also be used in design environments and is an informative next step to further understand design data before anything is physically built. The engine's real-time digital environment, on a powerful, data-driven architecture, is programmed to look and feel like the physical world. Through the high-end development tools and visual scripting system, customers can program objects, light effects, environmental elements, materials, and entourage elements to behave and react as they would in the physical world.


Connected to Autodesk 3ds Max, architecture, engineering and construction customers can import Autodesk Revit data into 3ds Max, add content to the 3ds Max scene and then place that scene in the Stingray engine to explore, animate, and interact in the designed space.


Pricing and Availability


Autodesk Stingray runs on Windows and will be available via Autodesk Subscription starting August 19, 2015 for $30 US MSRP per month. Later this summer, Autodesk plans to offer Maya LT Desktop Subscription customers access to the engine as part of Maya LT. For more details about Stingray, visit: www.autodesk.com/stingrayengine


About Autodesk


Autodesk helps people imagine, design and create a better world. Everyone--from design professionals, engineers and architects to digital artists, students and hobbyists--uses Autodesk software to unlock their creativity and solve important challenges. For more information visit autodesk.com or follow @autodesk.

 

So there you have it, it will be available for $30 a month starting later this month.  Interestingly it seems to also be available as part of the Maya LT subscription which is also $30 a month or $240 a year, so it’s effectively free to Maya LT users.  It’s certainly a boon for existing Maya LT users, but in a world full of free game engines, is a subscription based engine going to fly?

 

You can learn more about the StingrayEngine at http://stingrayengine.com/ or by watching the video below.

 

Introducing the Autodesk Stingray 3D game engine from Autodesk Media and Entertainment on Vimeo.

News

30. July 2015

 

My primary laptop was misbehaving in so many ways I was about ready to do a complete re-install.  It was randomly turning itself on from hibernate for example, which lead to an overheating and half dead laptop half the time I got to where I was going.  Fortunately the Windows 10 release was on the horizon, so I figured I would be doing a fresh install then anyways, so I held off.  Now that I’ve finish the upgrade ( Windows 10 rocks btw… ), I’ve noticed that I have my essential programs that get installed right away on a fresh install.  The following are my go to programs on a fresh install.

 

Keep in mind, a lot of my needs also focus on blogging/writing in addition to game development, so if some of these have you scratching your head, that’s why!  I am also not completely up and running yet either, so this isn’t by any means a complete list of the tools I used, just the priority stuff I cant live without.

 

Dropbox To be honest, I think the client is starting to cause issues with both stability and battery life.  At the end of the day though, this IS my file system these days.  Thanks to Dropbox, I can be up and running productively on a new machine in a matter of hours, tops.  Plus, and I totally know you shouldn’t do this… but it’s a great poor mans version control Smile

 

7zip  Swiss army knife free archiving tool, all I ever need for all my compression needs.

 

Steam It’s where my games are.  This gets installed early as there’s about 1TB of games in there to download.  It’s kind of nice having all of my games in one spot, makes reinstalls a breeze.  I do hate the constant updates and the CPU hogging that are becoming more and more common though.

 

Visual Studio 2015 Community  The Windows based IDE, C++, C#, F# all in one home, also thankfully now free in a small developer environment.  I had great timing here, as the torch was just passed between Visual Studio 2013 and 2015, hopefully saving me about 15GB of drive space.  Hopefully.

 

SublimeText  My go to text editor.  This or Notepad++, I flip back and forth.  I go with the beta version 3 as I like living dangerously.

 

Blender  Free and comprehensive 3D graphics package

 

Paint.Net  Free 2D image app.  Not the most powerful image editor out there, but certainly a capable one, especially for the price.  My go to app for resizing and cleaning up images.

 

Java SE JDK  Even if I’m not working with LibGDX or Android right now, it’s enevitable I am going to have to install the JDK eventually so might as well do it now.  Normally go with Java 7, but trying 8 this time, mostly because Oracle made 7 enough of a pain in the ass to find.  Have a sinking feeling I am going to have to download Java 7 at some point in the near future.

 

IntelliJ IDEA  Speaking of Java, this is my Java IDE of choice.  Also my Lua and Haxe IDE of choice while we are at it.

 

WebStorm  While I’m on JetBrain’s site, I also grab WebStorm, my HTML5 IDE of choice.  I subscribe to this, 50$ a year I think.  Well worth it.

 

Windows Live Writer  Part of Windows Essentials.  It’s the software I do my Windows based blogging on, what I am typing this in as we speak.  Sadly discontinued in 2012, as it’s still the best software for blogging available IMHO.

 

FastStone Capture  I bought this app like 6 years ago for 20$ and I love it to death.  It’s my screenshot/markup/video capture go to application.

 

Camtasia Studio  When I started producing video I tried so hard to find a free alternative.  They sucked, every single one of them.  Camtasia has a price tag attached and some glaring faults ( no on screen keyboard display??? ), it’s still the best video capture/editing package on the market.

 

GifCam  I make a lot of animated gifs for tutorials and this little free app ROCKS.  I used to use a much more complicated process, now I just use this.  Creates high quality but small filesize images.  Highly recommended.

 

Highlight  I’ve tried all sorts of different approaches to creating marked up code for books and blogs and Highlight has been hands down my favourite.  Oh, it’s free too!

 

Scrivener  This is my primary book authoring software, and as time goes on I will mix my book and blog workflow into a single entity and this will be home.  It’s a tool for writers and really takes a bit to get used to, but once it clicks… it clicks.  Honestly though the Windows version is only so-so.  It’s the Mac version that shines.

 

What I haven’t installed:

A Browser.  Normally Chrome would be item number 1 on a new install.  Thing is, Chrome has gotten worse, a lot worse.  Microsoft Edge however… check it out, really, do.  I did however disable Bing after about 30 seconds…

A Mail Client.  I’m giving the new Windows 10 mail client a go.  Actually pretty impressed so far.  Normally I use MailBird.  If I dont like Windows 10 mail I will go back to Mailbird.

Microsoft Office.  I have a license, and will eventually need to install it, at least Word, but I try to put it off as long as possible. 

 

What I’ve not mentioned:

Game Engines.  I also install game engines… LibGDX, Unity, Stencyl, Unreal, Paradox3D, etc…  These vary based on the tutorials I am currently working on however, so I don’t include them, although they are certainly essential.  The cool part is, pretty much every single one of them is free.

 

Honourable mentions:

Krita or GIMP – 2d painting

Inkscape – Vector Graphics

Visual Studio Code – Sublime Text like editor, fairly new but becoming a bigger and bigger fan

 

 

It’s actually kind of cool if you look through this list just how low the total price tag actually is.  The amount of stuff I need to install is actually getting smaller and smaller too, thanks to more and more functionality being move to the web.

Totally Off Topic ,

28. July 2015

 

We covered viewports a while back but now we are going to go into a bit more detail, as it’s an important subject.

 

There is a 1080p version of this tutorial available here.   Please note, the full screen portions didn’t display properly in the video.

 

One very important thing to understand is, the very root of your scene, the node that owns all of the nodes in a scene, is ultimately a viewport.  Consider this hierarchy:

image

In that node if you run the code:

func _ready():
   print(get_node("/root"))

 

You will see:

image

 

So, no matter how you create your scene, you will always have at least one viewport.  On the other hand, you can create more viewports within the scene as we will see later.

 

Full Screen Applications

 

It’s possible to set your application to run full screen, both using code or in the application settings.  To do it with code, create a new autoload script as described here.  This is a script, derived from node, that gets run automatically when your game launches.  Use the following code:

extends Node

func _ready():
   var root = get_node("/root")
   root.connect("size_changed",self,"resize")
   OS.set_window_fullscreen(true)
   set_process_input(true)
   
#Event called when viewport size changed  
func resize():
   var root = get_node("/root")
   var resolution = root.get_rect()
   print(resolution)
   
#Input handler, listen for ESC to exit app
func _input(event):
   if(event.is_pressed()):
      if(event.scancode == KEY_ESCAPE):
         get_tree().quit() 

 

Of course this code does a lot more than just set the application full screen.  Due to the app going full screen, it is no longer easy to close the window, so I’ve also wired in some code to handle shutting down if the user hits Esc.  There is also an event handler connected to fire when the resolution changes, we simple print the resolution to the console when it changes.

 

You can accomplish the exact same thing (much easier) using project settings, like so:

image

Please note there are two check boxes to enable!  First you need to enable the fullscreen setting, then you need to turn it on.

 

Viewport Scaling

Now to illustrate how resolution works in Godot, I’ve created a Sprite Node( not centered, at 0,0 ) using this image, which illustrates the various screen resolutions.

image

 

The actual image is 1920x1080 in size, so it should show us the results that various settings have on our game.  Here is a run, using default settings on my laptop which has a 1600x900 display. 

The following display settings are very important.

image

The following screenshots are all scaled down but maintain the aspect ratio of the source image.  The Viewport setting has a profound effect on the results.  The options are:

image

 

Viewport == disabled.  Resolution is 1600x900 ( my native resolution ) and display resolution settings ignored.

image

 

Mode == 2d.  Image size is 1600x900.

image

 

Viewport stretch mode.  Image size is 800x600.

image

 

It’s the ultimate results that make the difference.  When viewport is set to disabled, the width/height are ignored completely and the resolution of the device is used.  In viewport set to 2D, the width and height are used and the results are simply scaled up (or down) to match the resolution of the actual device.  While in Viewport, the results are actually scaled down to the resolution specified.  This means our actual render results are at 800x600 ( or whatever resolution you specified ).   You would generally use this last mode if you were trying to create a pixel perfect game, or if you are trying to render to a lower resolution to improved performance.  Keep in mind on most machines the results will look somewhat horrible.

 

 

 

Handling Aspect Ratios

Now this resizing works great when you are dealing with the same aspect ratios, but once they start changing, it has a much more pronounced effect.  For example, content designed for a 4:3 screen ( iPad ) will look horrible on a 16:9 screen ( Galaxy Note ) for example.  You also need to decide HOW you are going to deal with different aspect ratios.  This isn’t a new problem, people watching single def signals on HD displays have been dealing with this issue for years.

I created a new Sprite, this time using a sprite 379x124 pixels in size, like so:

image

Then automatically position it in the center of the viewport on load:

 

func _ready():
   self.set_pos(Vector2(get_viewport_rect().size.width/2,
                get_viewport_rect().size.height/2))

 

As mentioned earlier, my laptops native resolution is 1600x900, so everything looks fine with an HD resolution.  For example, here is the result rendered at 1280x720 full screen (but scaled down on the blog):

image

 

Looking good!  Now lets try 640x480, a not so HD aspect ratio:

image

 

Ewwww…. ok… obviously not what we want.  The result of the resampling to fit a 640x480 image on a 1600x900 screen as stretched our ship almost to the point of being unrecognizable.

You do however have options here, once again under display settings called stretch_aspect.

image

 

Lets see the result on our 640x480 scene:

 

ignore

image

keep

IMAG0363

keep_width

IMAG0364

keep_height

IMAG0365

 

You may notice the pictures are literally camera shots of my laptop.  This is because the screenshots don’t capture the black bar portions of the image.

Basically you can choose to simply rescale the aspect ratio, which causes the sprites to distort if the source and destination resolutions don’t have a similar aspect ratio.  Choosing Keep will cause it to keep the aspect ratio specified and generate black bars, either horizontally or vertically, whichever is needed.  You can also tell it to keep the height or the width aspect ratio.  The remaining dimension ( height if you chose Keep_width for example ) will then be scaled to fit, causing distortion in that direction.

 

Sub-Viewport

As mentioned earlier, the root node in the scene is always a viewport.  You can however create a viewport node within the scene or embedded within another node.

 

Consider this hierarchy of Nodes for example:

image

 

In the Editor it looks like a complete mess:

image

But when you run it, you can immediately see the results:

image

The nodes added to the child viewport are positioned relative to, and rendered within that viewport.

 

Cameras

 

The Camera2D class in Godot is mostly just responsible for manipulating the transform of the viewport.  A Camera automatically applies itself to the closest viewport above it in the node hierarchy, and if there isn’t one, it affects the root node instead.  Only one camera can be active at a time per viewport.

 

Otherwise using a camera is extremely simple.  Consider a scene like this that extends beyond the viewport:

image

 

Simply drop a Camera2D node into the scene:

image

 

Set Current To On

image

 

And your view will automatically update to represent the camera’s position

image

 

 

Taking a Screen Shot

 

When running full screen, capturing a screen shot can become a bit tricky.  I got around it by handling the logic in code.  If you are interested, here is how I captured a screenshot using Godot:

      if(event.scancode == KEY_SPACE):
         print("Screenshot")
         get_viewport().queue_screen_capture()
         yield(get_tree(), "idle_frame")
         yield(get_tree(), "idle_frame")
         var screenshot = get_viewport().get_screen_capture()
         screenshot.save_png("user://screenshot.png")

The location of “user://” is going to change from platform to platform.  On Windows 8.1 the screenshot was located at C:\Users\Mike\AppData\Roaming\Godot\app_userdata\Viewport on my computer.  On Linux, check for a directory named .godot in your home directory.

 

The command queue_screen_capture() doesn’t happen immediately.  This is why we yeild two frames before calling get_screen_capture(), which will have the results of queue_screen_capture() or return an empty image if it hasn’t occurred yet.

 

The Video

Programming , ,

25. July 2015

 

In this chapter we are going to look at using audio in XNA.  Originally XNA supported one way of playing audio, using XACT (Cross Platform Audio Creation Tool ).  Since the initial release they added a much simplified API.  We will be taking a look at both processes.

 

There is an HD video of this chapter available here.

 

When playing audio there is always the challenge of what formats are supported, especially when you are dealing with multiple different platforms, all of which have different requirements.  Fortunately the content pipeline takes care of a great deal of the complications for us.  Simply add your audio files ( mp3, mp4, wma, wav, ogg ) to the content pipeline and it will do the rest of the work for you.   As you will see shortly though, it is also possible to load audio files outside of the content pipeline.  In this situation, be aware that certain platforms do not support certain formats ( for example, no wma support on Android or iOS, while iOS doesn’t support ogg but does support mp3 ).  Unless you have a good reason, I would recommend you stick to the content pipeline for audio whenever possible.

 

The Perils of MP3

Although MP3 is supported by MonoGame, you probably want to stay away from using it. Why?
Patents. If your game has over 5,000 users you could be legally required to purchase a license. From a legal perspective, Ogg Vorbis is superior in every single way. Unfortunately Ogg support is not as ubiquitous as we'd like it to be.

 

Adding Audio Content using the Content Pipeline

This process is virtually identical to adding a graphic file in your content file.

image

 

Simply add the content like you did using right click->Add Existing Items or the Edit menu:

image

 

If it is a supported format you will see the Processor field is filled ( otherwise it will display Unknown ).  The only option here is to configure the mp3 audio quality, a trade off between size and fidelity.

 

Playing a Song

Now let’s look at the code involved in playing the song we just added to our game.

// This example shows playing a song using the simplified audio api

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Example1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Song song;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            this.song = Content.Load<Song>("prepare");
            MediaPlayer.Play(song);
            //  Uncomment the following line will also loop the song
            //  MediaPlayer.IsRepeating = true;
            MediaPlayer.MediaStateChanged += MediaPlayer_MediaStateChan
                                             ged;
        }

        void MediaPlayer_MediaStateChanged(object sender, System.
                                           EventArgs e)
        {
            // 0.0f is silent, 1.0f is full volume
            MediaPlayer.Volume -= 0.1f;
            MediaPlayer.Play(song);
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == 
                ButtonState.Pressed || Keyboard.GetState().IsKeyDown(
                Keys.Escape))
                Exit();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            base.Draw(gameTime);
        }
    }
}

 

Notice that we added the using statement Microsoft.Xna.Framework.Media.  We depend on this for the MediaPlayer and Song classes.  Our Song is loaded using the ContentManager just like we did earlier with Texture, this time with the type Song.  Once again the content loader does not use the file’s extension.  Our Song can then be played with a call to MediaPlayer.Play().  In this example we wire up a MediaStateChanged event handler that will be called when the song completes, decreasing the volume and playing the song again.

 

Playing Sound Effects

 

This example shows playing sound effects.  Unlike a Song, SoundEffects are designed to support multiple instances being played at once.  Let’s take a look at playing SoundEffect in MonoGame:

// Example showing playing sound effects using the simplified audio 
api
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;
using System.Collections.Generic;

namespace Example2
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        List<SoundEffect> soundEffects;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            soundEffects = new List<SoundEffect>();
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw 
            textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            soundEffects.Add(Content.Load<SoundEffect>("airlockclose"))
                             ;
            soundEffects.Add(Content.Load<SoundEffect>("ak47"));
            soundEffects.Add(Content.Load<SoundEffect>("icecream"));
            soundEffects.Add(Content.Load<SoundEffect>("sneeze"));

            // Fire and forget play
            soundEffects[0].Play();
            
            // Play that can be manipulated after the fact
            var instance = soundEffects[0].CreateInstance();
            instance.IsLooped = true;
            instance.Play();
        }


        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == 
                ButtonState.Pressed || Keyboard.GetState().IsKeyDown(
                Keys.Escape))
                Exit();

            if (Keyboard.GetState().IsKeyDown(Keys.D1))
                soundEffects[0].CreateInstance().Play();
            if (Keyboard.GetState().IsKeyDown(Keys.D2))
                soundEffects[1].CreateInstance().Play();
            if (Keyboard.GetState().IsKeyDown(Keys.D3))
                soundEffects[2].CreateInstance().Play();
            if (Keyboard.GetState().IsKeyDown(Keys.D4))
                soundEffects[3].CreateInstance().Play();


            if (Keyboard.GetState().IsKeyDown(Keys.Space))
            {
                if (SoundEffect.MasterVolume == 0.0f)
                    SoundEffect.MasterVolume = 1.0f;
                else
                    SoundEffect.MasterVolume = 0.0f;
            }
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            base.Draw(gameTime);
        }
    }
}

 

Note the using Microsoft.Xna.Framework.Audio statement at the beginning.  Once again we added our audio files using the Content Pipeline, in this case I added several WAV files.  They are loaded using Content.Load() this time with the type SoundEffect.  Next it is important to note the two different ways the SoundEffects are played.  You can either call Play() directly on the SoundEffect class.  This creates a fire and forget instance of the class with minimal options for controlling it.  If you have need for greater control ( such as changing the volume, looping or applying effects ) you should instead create a SoundEffectInstance using the SoundEffect.CreateInstance() call.  You should also create a separate instance if you want to have multiple concurrent instances of the same sound effect playing.  It is important to realize that all instances of the same SoundEffect share resources, so memory will not increase massively for each instance created.  The number of simultaneous supported sounds varies from platform to platform, with 64 being the limit on Windows Phone 8, while the Xbox 360 limits it to 300 instances.  There is no hard limit on the PC, although you will obviously hit device limitations quickly enough.

 

In the above example, we create a single looping sound effect right away.  Then each frame we check to see if the user presses 1,2,3 or 4 and play an instance of the corresponding sound effect.  If the user hits the spacebar we either mute or set to full volume the global MasterVolume of the SoundEffect class.  This will affect all playing sound effects.

 

Positional Audio Playback

Sound effects can also be positioned in 3D space easily in XNA. 

// Display positional audio

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;

namespace Example3
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SoundEffect soundEffect;
        SoundEffectInstance instance;
        AudioListener listener;
        AudioEmitter emitter;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            soundEffect = this.Content.Load<SoundEffect>("circus");
            instance = soundEffect.CreateInstance();
            instance.IsLooped = true;

            listener = new AudioListener();
            emitter = new AudioEmitter();

            // WARNING!!!!  Apply3D requires sound effect be Mono!  
            Stereo will throw exception
            instance.Apply3D(listener, emitter);
            instance.Play();
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == 
                ButtonState.Pressed || Keyboard.GetState().IsKeyDown(
                Keys.Escape))
                Exit();

            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                listener.Position = new Vector3(listener.Position.X-0.
                                    1f, listener.Position.Y, listener.
                                    Position.Z);
                instance.Apply3D(listener, emitter);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                listener.Position = new Vector3(listener.Position.X + 
                                    0.1f, listener.Position.Y, 
                                    listener.Position.Z);
                instance.Apply3D(listener, emitter);
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                listener.Position = new Vector3(listener.Position.X, 
                                    listener.Position.Y +0.1f, 
                                    listener.Position.Z);
                instance.Apply3D(listener, emitter);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                listener.Position = new Vector3(listener.Position.X, 
                                    listener.Position.Y -0.1f, 
                                    listener.Position.Z);
                instance.Apply3D(listener, emitter);
            }            
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            base.Draw(gameTime);
        }
    }
}

 

In this example, we load a single SoundEffect and start it looping infinitely.  We then create an AudioListener and AudioEmitter instance.  The AudioListener represents the location of your ear within the virtual world, while the AudioEmitter represents the position of the sound effect.  The default location of both is a Vector3 at (0,0,0).  You set the position of a SoundEffect by calling Apply3D().  In our Update() call, if the user hits an arrow key we updated the Position of the AudioListener accordingly.  After changing the position of a sound you have to call Apply3D again.  As you hit the arrow keys you will notice the audio pans and changes volume to correspond with the updated position.  It is very important that your source audio file is in Mono ( as opposed to Stereo ) format if you use Apply3D, or an exception will be thrown.

 

Using XACT

As mentioned earlier, XACT used to be the only option when it came to audio programming in XNA.  XACT is still available and it enables your audio designer to have advanced control over the music and sound effects that appear in your game, while the programmer uses a simple programmatic interface.  One big caveat is XACT is part of the XNA installer or part of the Direct X SDK as is not available on Mac OS or Linux.  If you wish to install it but do not have an old version of Visual Studio installed, instructions can be found here ( http://www.gamefromscratch.com/post/2015/07/23/Installing-XNA-Tools-Like-XACT-without-Visual-Studio-2010.aspx ).  If you are on MacOS or Linux, you want to stick to the simplified audio API that we demonstrated earlier.

Xact is installed as part of the XNA Studio install, on 64bit Windows by default the Xact executable will be located in C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\Tools.  Start by running AudConsole3.exe:

image

 

The XACT Auditioning Tool needs to be running when you run the Xact tool.

Then launch Xact3.exe

image

First create a new project:

image

 

Next right click Wave Banks and select New Wave Bank

image

 

Drag and drop your source audio files into the Wave Bank window:

image

 

Now create a new Sound Bank by right clicking Sound Bank and selecting New Wave Bank

image

 

Now drag the Wave you wish to use from the Wave Bank to the Sound Bank

a1

 

Now create a Cue by dragging and dropping the Sound Bank to the Cue window.  Multiple files can be added to a cue if desired.

a2

 

You can rename the Cue, set the probability to play if you set several Sounds in the Cue and change the instance properties of the Cue in the properties window to your left:

image

Now Build the results:

image

 

This will then create two directories in the folder you created your project in:

image

 

These files need to be added directly to your project, you do not use the content pipeline tool!  Simply copy all three files to the content folder and set it’s build action to Copy.

image

 

Now let’s look at the code required to use these generated files:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;

namespace Example4
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        AudioEngine audioEngine;
        SoundBank soundBank;
        WaveBank waveBank;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            base.Initialize();
        }
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw 
            textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            audioEngine = new AudioEngine("Content/test.xgs");
            soundBank = new SoundBank(audioEngine,"Content/Sound Bank.
                        xsb");
            waveBank = new WaveBank(audioEngine,"Content/Wave Bank.
                       xwb");

            soundBank.GetCue("ak47").Play();
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == 
                ButtonState.Pressed || Keyboard.GetState().IsKeyDown(
                Keys.Escape))
                Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

 

First you create an AudioEngine using the xgs file, then a SoundBank using the xsb and a WaveBank unsing the xwb file.  We then play the Cue we created earlier with a call to SoundBank.GetQue().Play().  This process allows the audio details to be configured outside of the game while the programmer simply uses the created Que.

 

Finally it is possible to play audio files that weren’t added using the content pipeline or using Xact using a Uri. 

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw 
            textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // URL MUST be relative in MonoGame
            System.Uri uri = new System.Uri("content/background.mp3",
                             System.UriKind.Relative);
            Song song = Song.FromUri("mySong", uri);
            MediaPlayer.Play(song);
            MediaPlayer.ActiveSongChanged += (s, e) => {
                song.Dispose();
                System.Diagnostics.Debug.WriteLine("Song ended and 
                                                   disposed");
            };
        }

 

First you create a Uri that locates the audio file you want to load.  We then load it using the method FromUri, passing in a name as well as the uri.  One very important thing to be aware of here, on XNA you could use any URI.  In MonoGame it needs to be a relative path.

 

The Video

 

Programming , , ,

23. July 2015

 

I recently ran into a bit of a challenge and the work around wasn’t entirely obvious so I’ve decided to share the process here.  The XNA Game Studio install includes a couple of tools, the XACT audio tool being specifically what I was after.  Unfortunately to install XNA you need to first have Visual Studio 2010 or Visual Studio 2010 Express installed.  As that version of VS is getting increasingly dated, this is going to be an issue for many.  Fortunately there is a work around.

 

First download the XNA installer here.  The file is called XNAGS40_setup.exe

 

Now open a command prompt ( possibly with admin privledges ) and CD to directory containing the file you downloaded.

Run the command:

XNAGS40_setup.exe /x

You will now be prompted where to extract:

image

Click OK

This will create a couple files, the most important being redists.msi, run this file ( just type redists.msi and [enter] at the command line, or double click in Explorer ).

 

This will in turn create a directory structure in Program Files ( or Program Files x86 on 64bit Windows ) called Microsoft XNA.

Close the command prompt and navigate to that folder in Windows Explorer then open XNA Game Studio\v4.0\setup:

image

Run xnags_shared.msi then xnags_platform_tools.msi, both are simple installers,  take default options if asked.

Now if you check the folder XNA Game Studio/v4.0 you should see that all of the tools you need have been installed in the Tools directory:

image

Programming, General , ,

Month List

DisqusCommentsSummary