Merge pull request #8632 from Mailaender/openra-platform

Removed the OpenAL/OpenGL/SDL2 dependency from the game engine
This commit is contained in:
Pavel Penev
2015-08-24 00:45:27 +03:00
27 changed files with 202 additions and 156 deletions

View File

@@ -215,7 +215,7 @@ namespace OpenRA
GeoIP.Initialize();
GlobalFileSystem.Mount(Platform.GameDir); // Needed to access shaders
var renderers = new[] { Settings.Graphics.Renderer, "Sdl2", null };
var renderers = new[] { Settings.Graphics.Renderer, "Default", null };
foreach (var r in renderers)
{
if (r == null)
@@ -234,18 +234,6 @@ namespace OpenRA
}
}
try
{
Sound.Create(Settings.Sound.Engine);
}
catch (Exception e)
{
Log.Write("sound", "{0}", e);
Console.WriteLine("Creating the sound engine failed. Fallback in place. Check sound.log for details.");
Settings.Sound.Engine = "Null";
Sound.Create(Settings.Sound.Engine);
}
Console.WriteLine("Available mods:");
foreach (var mod in ModMetadata.AllMods)
Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Title, mod.Value.Version);
@@ -287,7 +275,7 @@ namespace OpenRA
Settings.Game.Mod = mod;
Sound.StopVideo();
Sound.Initialize();
Sound.Initialize(Settings.Sound, Settings.Server);
ModData = new ModData(mod, !Settings.Server.Dedicated);
ModData.InitializeLoaders();
@@ -403,7 +391,7 @@ namespace OpenRA
Bitmap bitmap;
using (new PerfTimer("Renderer.TakeScreenshot"))
bitmap = Renderer.TakeScreenshot();
bitmap = Renderer.Device.TakeScreenshot();
ThreadPool.QueueUserWorkItem(_ =>
{

View File

@@ -15,11 +15,11 @@ using OpenRA.Graphics;
namespace OpenRA
{
[AttributeUsage(AttributeTargets.Assembly)]
public sealed class RendererAttribute : Attribute
public sealed class PlatformAttribute : Attribute
{
public readonly Type Type;
public RendererAttribute(Type graphicsDeviceType)
public PlatformAttribute(Type graphicsDeviceType)
{
if (!typeof(IDeviceFactory).IsAssignableFrom(graphicsDeviceType))
throw new InvalidOperationException("Incorrect type in RendererAttribute");
@@ -29,7 +29,8 @@ namespace OpenRA
public interface IDeviceFactory
{
IGraphicsDevice Create(Size size, WindowMode windowMode);
IGraphicsDevice CreateGraphics(Size size, WindowMode windowMode);
ISoundEngine CreateSound();
}
public interface IHardwareCursor : IDisposable { }

View File

@@ -84,10 +84,6 @@
<HintPath>..\thirdparty\download\MaxMind.Db.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="SDL2-CS">
<HintPath>..\thirdparty\download\SDL2-CS.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Activities\Activity.cs" />
@@ -120,7 +116,6 @@
<Compile Include="Graphics\LineRenderer.cs" />
<Compile Include="Graphics\MappedImage.cs" />
<Compile Include="Graphics\Minimap.cs" />
<Compile Include="Graphics\Renderer.cs" />
<Compile Include="Graphics\SequenceProvider.cs" />
<Compile Include="Graphics\Sheet.cs" />
<Compile Include="Graphics\SheetBuilder.cs" />
@@ -228,8 +223,6 @@
<Compile Include="Graphics\IGraphicsDevice.cs" />
<Compile Include="Sound\Sound.cs" />
<Compile Include="Sound\SoundDevice.cs" />
<Compile Include="Sound\OpenAlSound.cs" />
<Compile Include="Sound\NullSound.cs" />
<Compile Include="Effects\SpriteEffect.cs" />
<Compile Include="Graphics\SelectionBarsRenderable.cs" />
<Compile Include="Graphics\TargetLineRenderable.cs" />
@@ -249,6 +242,8 @@
<Compile Include="Graphics\TerrainSpriteLayer.cs" />
<Compile Include="Map\ProjectedCellRegion.cs" />
<Compile Include="Map\MapCoordsRegion.cs" />
<Compile Include="Renderer.cs" />
<Compile Include="Platform.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="FileSystem\D2kSoundResources.cs" />
@@ -298,7 +293,6 @@
<Compile Include="Support\PerfTimer.cs" />
<Compile Include="Exts.cs" />
<Compile Include="MiniYaml.cs" />
<Compile Include="Platform.cs" />
<Compile Include="StreamExts.cs" />
<Compile Include="Map\Map.cs" />
<Compile Include="Map\MapCache.cs" />

View File

@@ -13,9 +13,10 @@ using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using OpenRA.Graphics;
using OpenRA.Support;
namespace OpenRA.Graphics
namespace OpenRA
{
public sealed class Renderer : IDisposable
{
@@ -49,7 +50,7 @@ namespace OpenRA.Graphics
var resolution = GetResolution(graphicSettings);
var rendererName = serverSettings.Dedicated ? "Null" : graphicSettings.Renderer;
var rendererPath = Platform.ResolvePath(".", "OpenRA.Renderer." + rendererName + ".dll");
var rendererPath = Platform.ResolvePath(".", "OpenRA.Platforms." + rendererName + ".dll");
Device = CreateDevice(Assembly.LoadFile(rendererPath), resolution.Width, resolution.Height, graphicSettings.Mode);
@@ -79,12 +80,12 @@ namespace OpenRA.Graphics
return new Size(size.X, size.Y);
}
static IGraphicsDevice CreateDevice(Assembly rendererDll, int width, int height, WindowMode window)
static IGraphicsDevice CreateDevice(Assembly platformDll, int width, int height, WindowMode window)
{
foreach (RendererAttribute r in rendererDll.GetCustomAttributes(typeof(RendererAttribute), false))
foreach (PlatformAttribute r in platformDll.GetCustomAttributes(typeof(PlatformAttribute), false))
{
var factory = (IDeviceFactory)r.Type.GetConstructor(Type.EmptyTypes).Invoke(null);
return factory.Create(new Size(width, height), window);
return factory.CreateGraphics(new Size(width, height), window);
}
throw new InvalidOperationException("Renderer DLL is missing RendererAttribute to tell us what type to use!");
@@ -160,11 +161,6 @@ namespace OpenRA.Graphics
DrawBatch(tempBuffer, 0, numVertices, type);
}
public Bitmap TakeScreenshot()
{
return Device.TakeScreenshot();
}
public void DrawBatch<T>(IVertexBuffer<T> vertices,
int firstVertex, int numVertices, PrimitiveType type)
where T : struct

View File

@@ -111,7 +111,7 @@ namespace OpenRA
public class GraphicSettings
{
public string Renderer = "Sdl2";
public string Renderer = "Default";
public WindowMode Mode = WindowMode.PseudoFullscreen;
public int2 FullscreenSize = new int2(0, 0);
public int2 WindowedSize = new int2(1024, 768);
@@ -139,7 +139,7 @@ namespace OpenRA
public bool Shuffle = false;
public bool Repeat = false;
public string Engine = "AL";
public string Engine = "Default";
public string Device = null;
public bool CashTicks = true;

View File

@@ -1,50 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
namespace OpenRA
{
class NullSoundEngine : ISoundEngine
{
public NullSoundEngine()
{
Console.WriteLine("Using Null sound engine which disables SFX completely");
}
public ISoundSource AddSoundSourceFromMemory(byte[] data, int channels, int sampleBits, int sampleRate)
{
return new NullSoundSource();
}
public ISound Play2D(ISoundSource sound, bool loop, bool relative, WPos pos, float volume, bool attenuateVolume)
{
return new NullSound();
}
public void PauseSound(ISound sound, bool paused) { }
public void StopSound(ISound sound) { }
public void SetAllSoundsPaused(bool paused) { }
public void StopAllSounds() { }
public void SetListenerPosition(WPos position) { }
public void SetSoundVolume(float volume, ISound music, ISound video) { }
public float Volume { get; set; }
}
class NullSoundSource : ISoundSource { }
class NullSound : ISound
{
public float Volume { get; set; }
public float SeekPosition { get { return 0; } }
public bool Playing { get { return false; } }
}
}

View File

@@ -1,357 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.FileSystem;
using OpenRA.GameRules;
using OpenRA.Primitives;
using OpenRA.Traits;
using OpenTK;
using OpenTK.Audio.OpenAL;
namespace OpenRA
{
class OpenAlSoundEngine : ISoundEngine
{
class PoolSlot
{
public bool IsActive;
public int FrameStarted;
public WPos Pos;
public bool IsRelative;
public ISoundSource Sound;
}
const int MaxInstancesPerFrame = 3;
const int GroupDistance = 2730;
const int GroupDistanceSqr = GroupDistance * GroupDistance;
const int PoolSize = 32;
float volume = 1f;
Dictionary<int, PoolSlot> sourcePool = new Dictionary<int, PoolSlot>();
static string[] QueryDevices(string label, AlcGetStringList type)
{
// Clear error bit
AL.GetError();
var devices = Alc.GetString(IntPtr.Zero, type).ToArray();
if (AL.GetError() != ALError.NoError)
{
Log.Write("sound", "Failed to query OpenAL device list using {0}", label);
return new string[] { };
}
return devices;
}
public static string[] AvailableDevices()
{
// Returns all devices under Windows Vista and newer
if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATE_ALL_EXT"))
return QueryDevices("ALC_ENUMERATE_ALL_EXT", AlcGetStringList.AllDevicesSpecifier);
if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATION_EXT"))
return QueryDevices("ALC_ENUMERATION_EXT", AlcGetStringList.DeviceSpecifier);
return new string[] { };
}
public OpenAlSoundEngine()
{
Console.WriteLine("Using OpenAL sound engine");
if (Game.Settings.Sound.Device != null)
Console.WriteLine("Using device `{0}`", Game.Settings.Sound.Device);
else
Console.WriteLine("Using default device");
var dev = Alc.OpenDevice(Game.Settings.Sound.Device);
if (dev == IntPtr.Zero)
{
Console.WriteLine("Failed to open device. Falling back to default");
dev = Alc.OpenDevice(null);
if (dev == IntPtr.Zero)
throw new InvalidOperationException("Can't create OpenAL device");
}
var ctx = Alc.CreateContext(dev, (int[])null);
if (ctx == ContextHandle.Zero)
throw new InvalidOperationException("Can't create OpenAL context");
Alc.MakeContextCurrent(ctx);
for (var i = 0; i < PoolSize; i++)
{
var source = 0;
AL.GenSources(1, out source);
if (0 != AL.GetError())
{
Log.Write("sound", "Failed generating OpenAL source {0}", i);
return;
}
sourcePool.Add(source, new PoolSlot() { IsActive = false });
}
}
int GetSourceFromPool()
{
foreach (var kvp in sourcePool)
{
if (!kvp.Value.IsActive)
{
sourcePool[kvp.Key].IsActive = true;
return kvp.Key;
}
}
var freeSources = new List<int>();
foreach (var key in sourcePool.Keys)
{
int state;
AL.GetSource(key, ALGetSourcei.SourceState, out state);
if (state != (int)ALSourceState.Playing && state != (int)ALSourceState.Paused)
freeSources.Add(key);
}
if (freeSources.Count == 0)
return -1;
foreach (var i in freeSources)
sourcePool[i].IsActive = false;
sourcePool[freeSources[0]].IsActive = true;
return freeSources[0];
}
public ISoundSource AddSoundSourceFromMemory(byte[] data, int channels, int sampleBits, int sampleRate)
{
return new OpenAlSoundSource(data, channels, sampleBits, sampleRate);
}
public ISound Play2D(ISoundSource sound, bool loop, bool relative, WPos pos, float volume, bool attenuateVolume)
{
if (sound == null)
{
Log.Write("sound", "Attempt to Play2D a null `ISoundSource`");
return null;
}
var currFrame = Game.OrderManager.LocalFrameNumber;
var atten = 1f;
// Check if max # of instances-per-location reached:
if (attenuateVolume)
{
int instances = 0, activeCount = 0;
foreach (var s in sourcePool.Values)
{
if (!s.IsActive)
continue;
if (s.IsRelative != relative)
continue;
++activeCount;
if (s.Sound != sound)
continue;
if (currFrame - s.FrameStarted >= 5)
continue;
// Too far away to count?
var lensqr = (s.Pos - pos).LengthSquared;
if (lensqr >= GroupDistanceSqr)
continue;
// If we are starting too many instances of the same sound within a short time then stop this one:
if (++instances == MaxInstancesPerFrame)
return null;
}
// Attenuate a little bit based on number of active sounds:
atten = 0.66f * ((PoolSize - activeCount * 0.5f) / PoolSize);
}
var source = GetSourceFromPool();
if (source == -1)
return null;
var slot = sourcePool[source];
slot.Pos = pos;
slot.FrameStarted = currFrame;
slot.Sound = sound;
slot.IsRelative = relative;
return new OpenAlSound(source, ((OpenAlSoundSource)sound).Buffer, loop, relative, pos, volume * atten);
}
public float Volume
{
get { return volume; }
set { AL.Listener(ALListenerf.Gain, volume = value); }
}
public void PauseSound(ISound sound, bool paused)
{
if (sound == null)
return;
var key = ((OpenAlSound)sound).Source;
int state;
AL.GetSource(key, ALGetSourcei.SourceState, out state);
if (state == (int)ALSourceState.Playing && paused)
AL.SourcePause(key);
else if (state == (int)ALSourceState.Paused && !paused)
AL.SourcePlay(key);
}
public void SetAllSoundsPaused(bool paused)
{
foreach (var key in sourcePool.Keys)
{
int state;
AL.GetSource(key, ALGetSourcei.SourceState, out state);
if (state == (int)ALSourceState.Playing && paused)
AL.SourcePause(key);
else if (state == (int)ALSourceState.Paused && !paused)
AL.SourcePlay(key);
}
}
public void SetSoundVolume(float volume, ISound music, ISound video)
{
var sounds = sourcePool.Select(s => s.Key).Where(b =>
{
int state;
AL.GetSource(b, ALGetSourcei.SourceState, out state);
return (state == (int)ALSourceState.Playing || state == (int)ALSourceState.Paused) &&
(music == null || b != ((OpenAlSound)music).Source) &&
(video == null || b != ((OpenAlSound)video).Source);
});
foreach (var s in sounds)
AL.Source(s, ALSourcef.Gain, volume);
}
public void StopSound(ISound sound)
{
if (sound == null)
return;
var key = ((OpenAlSound)sound).Source;
int state;
AL.GetSource(key, ALGetSourcei.SourceState, out state);
if (state == (int)ALSourceState.Playing || state == (int)ALSourceState.Paused)
AL.SourceStop(key);
}
public void StopAllSounds()
{
foreach (var key in sourcePool.Keys)
{
int state;
AL.GetSource(key, ALGetSourcei.SourceState, out state);
if (state == (int)ALSourceState.Playing || state == (int)ALSourceState.Paused)
AL.SourceStop(key);
}
}
public void SetListenerPosition(WPos position)
{
// Move the listener out of the plane so that sounds near the middle of the screen aren't too positional
AL.Listener(ALListener3f.Position, position.X, position.Y, position.Z + 2133);
var orientation = new[] { 0f, 0f, 1f, 0f, -1f, 0f };
AL.Listener(ALListenerfv.Orientation, ref orientation);
AL.Listener(ALListenerf.EfxMetersPerUnit, .01f);
}
}
class OpenAlSoundSource : ISoundSource
{
public readonly int Buffer;
static ALFormat MakeALFormat(int channels, int bits)
{
if (channels == 1)
return bits == 16 ? ALFormat.Mono16 : ALFormat.Mono8;
else
return bits == 16 ? ALFormat.Stereo16 : ALFormat.Stereo8;
}
public OpenAlSoundSource(byte[] data, int channels, int sampleBits, int sampleRate)
{
AL.GenBuffers(1, out Buffer);
AL.BufferData(Buffer, MakeALFormat(channels, sampleBits), data, data.Length, sampleRate);
}
}
class OpenAlSound : ISound
{
public readonly int Source = -1;
float volume = 1f;
public OpenAlSound(int source, int buffer, bool looping, bool relative, WPos pos, float volume)
{
if (source == -1)
return;
Source = source;
Volume = volume;
AL.Source(source, ALSourcef.Pitch, 1f);
AL.Source(source, ALSource3f.Position, pos.X, pos.Y, pos.Z);
AL.Source(source, ALSource3f.Velocity, 0f, 0f, 0f);
AL.Source(source, ALSourcei.Buffer, buffer);
AL.Source(source, ALSourceb.Looping, looping);
AL.Source(source, ALSourceb.SourceRelative, relative);
AL.Source(source, ALSourcef.ReferenceDistance, 6826);
AL.Source(source, ALSourcef.MaxDistance, 136533);
AL.SourcePlay(source);
}
public float Volume
{
get
{
return volume;
}
set
{
if (Source != -1)
AL.Source(Source, ALSourcef.Gain, volume = value);
}
}
public float SeekPosition
{
get
{
int pos;
AL.GetSource(Source, ALGetSourcei.SampleOffset, out pos);
return pos / 22050f;
}
}
public bool Playing
{
get
{
int state;
AL.GetSource(Source, ALGetSourcei.SourceState, out state);
return state == (int)ALSourceState.Playing;
}
}
}
}

View File

@@ -11,13 +11,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using OpenRA.FileFormats;
using OpenRA.FileSystem;
using OpenRA.GameRules;
using OpenRA.Primitives;
using OpenRA.Traits;
using OpenTK;
using OpenTK.Audio.OpenAL;
namespace OpenRA
{
@@ -30,6 +29,17 @@ namespace OpenRA
static ISound video;
static MusicInfo currentMusic;
static ISoundEngine CreateDevice(Assembly platformDll)
{
foreach (PlatformAttribute r in platformDll.GetCustomAttributes(typeof(PlatformAttribute), false))
{
var factory = (IDeviceFactory)r.Type.GetConstructor(Type.EmptyTypes).Invoke(null);
return factory.CreateSound();
}
throw new InvalidOperationException("Platform DLL is missing PlatformAttribute to tell us what type to use!");
}
static ISoundSource LoadSound(string filename)
{
if (!GlobalFileSystem.Exists(filename))
@@ -56,26 +66,12 @@ namespace OpenRA
return soundEngine.AddSoundSourceFromMemory(rawData, channels, sampleBits, sampleRate);
}
static ISoundEngine CreateEngine(string engine)
public static void Initialize(SoundSettings soundSettings, ServerSettings serverSettings)
{
engine = Game.Settings.Server.Dedicated ? "Null" : engine;
switch (engine)
{
case "AL": return new OpenAlSoundEngine();
case "Null": return new NullSoundEngine();
var engineName = serverSettings.Dedicated ? "Null" : soundSettings.Engine;
var enginePath = Platform.ResolvePath(".", "OpenRA.Platforms." + engineName + ".dll");
soundEngine = CreateDevice(Assembly.LoadFile(enginePath));
default:
throw new InvalidOperationException("Unsupported sound engine: {0}".F(engine));
}
}
public static void Create(string engine)
{
soundEngine = CreateEngine(engine);
}
public static void Initialize()
{
sounds = new Cache<string, ISoundSource>(LoadSound);
music = null;
currentMusic = null;
@@ -86,14 +82,11 @@ namespace OpenRA
{
var defaultDevices = new[]
{
new SoundDevice("AL", null, "Default Output"),
new SoundDevice("Default", null, "Default Output"),
new SoundDevice("Null", null, "Output Disabled")
};
var devices = OpenAlSoundEngine.AvailableDevices()
.Select(d => new SoundDevice("AL", d, d));
return defaultDevices.Concat(devices).ToArray();
return defaultDevices.Concat(soundEngine.AvailableDevices()).ToArray();
}
public static void SetListenerPosition(WPos position)

View File

@@ -8,10 +8,13 @@
*/
#endregion
using System;
namespace OpenRA
{
interface ISoundEngine
public interface ISoundEngine
{
SoundDevice[] AvailableDevices();
ISoundSource AddSoundSourceFromMemory(byte[] data, int channels, int sampleBits, int sampleRate);
ISound Play2D(ISoundSource sound, bool loop, bool relative, WPos pos, float volume, bool attenuateVolume);
float Volume { get; set; }
@@ -41,7 +44,7 @@ namespace OpenRA
}
}
interface ISoundSource { }
public interface ISoundSource { }
public interface ISound
{