port from perforce

This commit is contained in:
2026-04-18 22:31:51 +02:00
commit 8d0ab5b7cc
8409 changed files with 3972376 additions and 0 deletions

View File

@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0F7D7168-08C1-45AE-AAE3-80506939D7E6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Aiwaz.Common</RootNamespace>
<AssemblyName>Aiwaz.Common</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Ionic.Zip, Version=1.8.4.29, Culture=neutral, PublicKeyToken=edbe51ad942a3f5c, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Ionic.Zip.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Animations\AnimateableAttribute.cs" />
<Compile Include="Animations\Animation.cs" />
<Compile Include="Animations\AnimationManager.cs" />
<Compile Include="Animations\CosineValueAnimation.cs" />
<Compile Include="Animations\Event.cs" />
<Compile Include="Animations\LinearValueAnimation.cs" />
<Compile Include="FileSystem.cs" />
<Compile Include="HiPerfTimer.cs" />
<Compile Include="Win32Console.cs" />
<Compile Include="Timeline.cs" />
<Compile Include="Animations\ValueAnimation.cs" />
<Compile Include="Pair.cs" />
<Compile Include="ObjectFactory.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aiwaz.Contracts\Aiwaz.Contracts.csproj">
<Project>{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}</Project>
<Name>Aiwaz.Contracts</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common.Animations
{
[AttributeUsage(AttributeTargets.Property)]
public class Animateable : Attribute
{
}
}

View File

@@ -0,0 +1,16 @@
namespace Aiwaz.Common.Animations
{
abstract public class Animation
{
public double StartTime { get; set; }
public double EndTime { get; set; }
public string AnimationName;
public Animation()
{
AnimationName = "Erroneous";
}
public abstract void Animate(double time, uint userData);
}
}

View File

@@ -0,0 +1,164 @@
using System.Collections.Generic;
namespace Aiwaz.Common.Animations
{
struct AnimationInterval
{
public AnimationInterval(double argBegin, double argEnd)
{
begin = argBegin;
end = argEnd;
}
public double begin;
public double end;
}
class ForwardComparer : IComparer<AnimationInterval>
{
public int Compare(AnimationInterval a, AnimationInterval b)
{
return a.begin < b.begin ? -1 : (a.begin > b.begin ? 1 : 0);
}
}
class BackwardComparer : IComparer<AnimationInterval>
{
public int Compare(AnimationInterval a, AnimationInterval b)
{
return a.end > b.end ? -1 : (a.end > b.end ? 1 : 0);
}
}
public static class AnimationManager
{
private static SortedList<AnimationInterval, List<Pair<Animation, uint>>> forwardSortedAnimations = new SortedList<AnimationInterval, List<Pair<Animation, uint>>>(new ForwardComparer());
private static SortedList<AnimationInterval, List<Pair<Animation, uint>>> backwardSortedAnimations = new SortedList<AnimationInterval, List<Pair<Animation, uint>>>(new BackwardComparer());
private static SortedList<AnimationInterval, List<Pair<Animation, uint>>> realTimeAnimations = new SortedList<AnimationInterval, List<Pair<Animation, uint>>>(new ForwardComparer());
private static SortedList<double, List<Pair<Event, uint>>> demoTimeEvents = new SortedList<double, List<Pair<Event, uint>>>();
private static SortedList<double, List<Pair<Event, uint>>> realTimeEvents = new SortedList<double, List<Pair<Event, uint>>>();
private static double previousDemoTime;
private static double previousRealTime;
public static void AddDemoTimeAnimation(double argBeginTime, double argEndTime, Animation argAnimation, uint argUserData)
{
forwardSortedAnimations[new AnimationInterval(argBeginTime, argEndTime)].Add(new Pair<Animation, uint>(argAnimation, argUserData));
backwardSortedAnimations[new AnimationInterval(argBeginTime, argEndTime)].Add(new Pair<Animation, uint>(argAnimation, argUserData));
}
public static void AddRealTimeAnimation(double argBeginTime, double argEndTime, Animation argAnimation, uint argUserData)
{
realTimeAnimations[new AnimationInterval(argBeginTime, argEndTime)].Add(new Pair<Animation, uint>(argAnimation, argUserData));
}
public static void AddDemoTimeEvent(double argTime, Event argEvent, uint argUserData)
{
demoTimeEvents[argTime].Add(new Pair<Event, uint>(argEvent, argUserData));
}
public static void AddRealTimeEvent(double argTime, Event argEvent, uint argUserData)
{
realTimeEvents[argTime].Add(new Pair<Event, uint>(argEvent, argUserData));
}
public static void Animate()
{
double demoTime = Timeline.DemoTime;
double realTime = Timeline.RealTime;
// Gather all active animations, they are the ones that started before now and end after now.
// Do this for both the demo time and real time.
List<Pair<Pair<Animation, uint>, double>> lk_ActiveAnimations = new List<Pair<Pair<Animation, uint>, double>>();
// Demo time animations: Demo time can go backwards, so search from both directions
if (Timeline.SpeedAndDirection > 0)
{
foreach (var entry in forwardSortedAnimations)
{
if (entry.Key.begin <= demoTime && entry.Key.end >= demoTime)
{
foreach (var animation in entry.Value)
{
lk_ActiveAnimations.Add(new Pair<Pair<Animation, uint>, double>(animation, (demoTime - entry.Key.begin) / (entry.Key.end - entry.Key.begin)));
}
}
if (entry.Key.begin > demoTime)
break;
}
}
else if (Timeline.SpeedAndDirection < 0)
{
foreach (var entry in backwardSortedAnimations)
{
if (entry.Key.end >= demoTime && entry.Key.begin <= demoTime)
{
foreach (var animation in entry.Value)
{
lk_ActiveAnimations.Add(new Pair<Pair<Animation, uint>, double>(animation, (demoTime - entry.Key.begin) / (entry.Key.end - entry.Key.begin)));
}
}
if (entry.Key.end < demoTime)
break;
}
}
// Real time animations: The time that we know doesn't allow us to travel to the past, so just check into the future:
foreach (var entry in realTimeAnimations)
{
if (entry.Key.begin <= demoTime && entry.Key.end >= demoTime)
{
foreach (var animation in entry.Value)
{
lk_ActiveAnimations.Add(new Pair<Pair<Animation, uint>, double>(animation, (demoTime - entry.Key.begin) / (entry.Key.end - entry.Key.begin)));
}
}
if (entry.Key.begin > demoTime)
break;
}
// Now that we know what animations correspond to this time, animate them!
foreach (var anim in lk_ActiveAnimations)
{
anim.First.First.Animate(anim.Second, anim.First.Second);
}
// Fire all events that happened since last time:
foreach (var entry in demoTimeEvents)
{
double time = entry.Key;
foreach (var evt in entry.Value)
{
if ((Timeline.SpeedAndDirection > 0) && (time >= previousDemoTime && time <= demoTime))
{
evt.First.Do(evt.Second);
}
else if ((Timeline.SpeedAndDirection < 0) && (time <= previousDemoTime && time >= demoTime))
{
evt.First.Undo(evt.Second);
}
}
}
foreach (var entry in realTimeEvents)
{
double time = entry.Key;
foreach (var evt in entry.Value)
{
if (time >= previousDemoTime && time <= demoTime)
{
evt.First.Do(evt.Second);
}
}
}
previousDemoTime = demoTime;
previousRealTime = realTime;
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common.Animations
{
public class CosineValueAnimation : ValueAnimation
{
public CosineValueAnimation()
: base()
{
AnimationName = "Cosine";
}
protected override float Calculate(double NormalizedTime)
{
float Interpolant = (float)((1.0 - Math.Cos(NormalizedTime * Math.PI)) / 2.0);
return (StartValue * (1.0f - Interpolant) + EndValue * Interpolant);
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common.Animations
{
abstract public class Event
{
abstract public Action<uint> Do { get; }
abstract public Action<uint> Undo { get; }
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common.Animations
{
public class LinearValueAnimation : ValueAnimation
{
public LinearValueAnimation()
: base()
{
AnimationName = "Linear";
}
protected override float Calculate(double NormalizedTime)
{
return (float)(StartValue * (1.0 - NormalizedTime) + EndValue * NormalizedTime);
}
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common.Animations
{
abstract public class ValueAnimation : Animation
{
public float StartValue { get; set; }
public float EndValue { get; set; }
public Func<float> ValueGetter;
public Action<float> ValueSetter;
public Func<string> ValueNamer;
public float Value
{
get { return ValueGetter(); }
set { ValueSetter(value); }
}
public ValueAnimation()
: base()
{
AnimationName = "Erroneous (Value)";
}
public override void Animate(double time, uint userData)
{
if (time < StartTime || time > EndTime)
return;
double Time = (time - StartTime) / (EndTime - StartTime);
Value = Calculate(Time);
}
protected abstract float Calculate(double NormalizedTime);
}
}

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using System.IO;
namespace Aiwaz.Common
{
public class FileSystem : IDisposable
{
private ZipFile zipFile;
public FileSystem()
{
if (File.Exists("data.pak"))
{
zipFile = ZipFile.Read("data.pak");
}
}
~FileSystem()
{
this.Dispose();
}
public Stream Open(string argFileName)
{
if (File.Exists(argFileName))
{
Stream fileStream = new FileStream(argFileName, FileMode.Open);
if (fileStream != null)
return fileStream;
}
if (zipFile != null)
{
var file = zipFile[argFileName];
if (file != null)
{
Stream outputStream = new MemoryStream();
file.Extract(outputStream);
return outputStream;
}
}
throw new FileNotFoundException(argFileName);
}
#region IDisposable Members
public void Dispose()
{
if (zipFile != null)
{
zipFile.Dispose();
}
}
#endregion
}
public static class BinaryReaderExtensions
{
public static string ReadNullTerminatedString(this BinaryReader reader)
{
string result = string.Empty;
char readChar = '\0';
do
{
readChar = reader.ReadChar();
if (readChar != '\0')
result += readChar;
}
while (readChar != '\0');
return result;
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Aiwaz.Common
{
public static class HiPerfTimer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long performanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long frequency);
private static double? startTime;
private static double lastTime;
public static double LastDeltaTime
{
get;
private set;
}
public static double ElapsedTime
{
get
{
long frequency, performanceCount;
QueryPerformanceFrequency(out frequency);
QueryPerformanceCounter(out performanceCount);
double thisTime = performanceCount / (double)frequency;
if (!startTime.HasValue)
{
startTime = thisTime;
lastTime = thisTime;
return 0.0;
}
LastDeltaTime = thisTime - lastTime;
lastTime = thisTime;
return thisTime - startTime.Value;
}
}
}
}

View File

@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common
{
public class ObjectFactory
{
private Dictionary<Type, Type> m_Patterns = new Dictionary<Type, Type>();
private Dictionary<Type, Dictionary<string, object>> m_StoredObjects = new Dictionary<Type, Dictionary<string, object>>();
public void RegisterPattern<O>()
{
var patternObject = typeof(O);
var patternInterface = patternObject.GetInterface("I" + patternObject.Name);
m_Patterns.Add(patternInterface, patternObject);
}
public void RegisterPattern<I, O>()
{
m_Patterns.Add(typeof(I), typeof(O));
}
public T CreateInstance<T>(params object[] args)
{
var creationType = m_Patterns.First(argPattern => argPattern.Key == typeof(T)).Value;
Type[] creationArguments = null;
if (args != null && args.Length > 0)
creationArguments = args.Select(arg => arg.GetType()).ToArray();
var constructor = creationType.GetConstructor(creationArguments == null ?
System.Type.EmptyTypes : creationArguments);
var construct = (T)constructor.Invoke(args);
return construct;
}
public T CreateNamedInstance<T>(string argName, params object[] args)
{
var construct = CreateInstance<T>(args);
var storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
if (storage == null)
{
m_StoredObjects.Add(typeof(T), new Dictionary<string, object>());
storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
}
storage.Add(argName, construct);
return construct;
}
public T FindNamedInstance<T>(string argName)
{
var storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
if (storage == null || !storage.ContainsKey(argName))
return default(T);
return (T)storage[argName];
}
public void RemoveNamedInstance<T>(string argName)
{
var storage = m_StoredObjects.FirstOrDefault(type => type.Key == typeof(T)).Value;
if (storage == null)
return;
storage.Remove(argName);
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Common
{
public class Pair<T, U>
{
public Pair()
{
}
public Pair(T first, U second)
{
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AiwazCommon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AiwazCommon")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e686f0df-9858-4478-a7fb-dea091646ff0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,22 @@
using Aiwaz.Common.Animations;
namespace Aiwaz.Common
{
public static class Timeline
{
private static double realTime;
public static double RealTime { get { return realTime; } }
private static double demoTime;
public static double DemoTime { get { return demoTime; } }
public static double SpeedAndDirection { get; set; }
private static double lastRealDeltaTime;
public static void Advance(double argSeconds)
{
lastRealDeltaTime = argSeconds;
realTime += argSeconds;
demoTime += argSeconds * SpeedAndDirection;
AnimationManager.Animate();
}
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Aiwaz.Common
{
public class Win32Console : IDisposable
{
[DllImport("kernel32.dll", EntryPoint = "FreeConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int FreeConsole();
[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int AllocConsole();
private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
public Win32Console()
{
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
#region IDisposable Members
public void Dispose()
{
FreeConsole();
}
#endregion
}
}

View File

@@ -0,0 +1,97 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Aiwaz.Contracts</RootNamespace>
<AssemblyName>Aiwaz.Contracts</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="SlimDX, Version=2.0.8.42, Culture=neutral, PublicKeyToken=b1b0c32fd1ffe4f9, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\SlimDX\x86\SlimDX.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Resource.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="EngineStates.cs" />
<Compile Include="IBone.cs" />
<Compile Include="ICamera.cs" />
<Compile Include="IGeometryBuffer.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="IPickHull.cs" />
<Compile Include="IRenderTargetBase.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="IResource.cs" />
<Compile Include="IShader.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="IShaderParameterCollection.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ISwapChain.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ITexture.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ITransformationAnimation.cs" />
<Compile Include="IUpdatable.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Reference.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,5 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ShowAllFiles</ProjectView>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,10 @@
namespace Aiwaz.Contracts
{
public class EngineStates
{
public IShader LastShader;
public IRenderTargetBase LastRenderTarget;
public IGeometryBuffer LastVertexBufferProvider;
public IGeometryBuffer LastIndexBufferProvider;
};
}

View File

@@ -0,0 +1,18 @@
using System.Collections.Generic;
using SlimDX;
namespace Aiwaz.Contracts
{
public interface IBone
{
Matrix GetTransformationAtTime(float time, Matrix rootTransformationMatrix);
Dictionary<int, IBone> BoneIndexList { get; }
List<IBone> ChildBones { get; }
int Index { get; }
Matrix[] MatrixArray { get; }
string Name { get; }
Matrix PoseTransformation { get; }
IBone Parent { get; set; }
ITransformationAnimation TransformationAnimation { get; set; }
}
}

View File

@@ -0,0 +1,31 @@
using SlimDX;
namespace Aiwaz.Contracts
{
public class ViewFrustum
{
public Plane[] Plane = new Plane[6];
};
public interface ICamera
{
Matrix ProjectionMatrix { get; }
Matrix ViewMatrix { get; }
float FarClip { get; set; }
float NearClip { get; set; }
ViewFrustum ViewFrustum { get; }
};
public interface IPerspectiveCamera
{
float Fov { get; set; }
float AspectRatio { get; set; }
};
public interface IOrthographicCamera
{
float Width { get; set; }
float Height { get; set; }
};
}

View File

@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
namespace Aiwaz.Contracts
{
public struct VertexElement
{
public enum Format
{
Position,
PositionT,
Normal,
Binormal,
Tangent,
Color,
BlendWeight,
BlendIndices,
Texture2D,
Texture3D,
Texture4D,
PointSize
};
public VertexElement(Format argFormat)
: this(argFormat, 0)
{
}
public VertexElement(Format argFormat, int argNameIndex)
{
NameIndex = argNameIndex;
WellKnownFormat = argFormat;
switch (argFormat)
{
case Format.PositionT:
{
SemanticName = "POSITIONT";
ElementFormat = SlimDX.DXGI.Format.R32G32B32A32_Float;
Size = 4 * sizeof(float);
break;
}
case Format.Normal:
{
SemanticName = "NORMAL";
ElementFormat = SlimDX.DXGI.Format.R32G32B32_Float;
Size = 3 * sizeof(float);
break;
}
case Format.Binormal:
{
SemanticName = "BINORMAL";
ElementFormat = SlimDX.DXGI.Format.R32G32B32_Float;
Size = 3 * sizeof(float);
break;
}
case Format.Tangent:
{
SemanticName = "TANGENT";
ElementFormat = SlimDX.DXGI.Format.R32G32B32_Float;
Size = 3 * sizeof(float);
break;
}
case Format.Color:
{
SemanticName = "COLOR";
ElementFormat = SlimDX.DXGI.Format.R8G8B8A8_UNorm;
Size = 4 * sizeof(byte);
break;
}
case Format.BlendWeight:
{
SemanticName = "BLENDWEIGHT";
ElementFormat = SlimDX.DXGI.Format.R32G32B32A32_Float;
Size = 4 * sizeof(float);
break;
}
case Format.BlendIndices:
{
SemanticName = "BLENDINDICES";
ElementFormat = SlimDX.DXGI.Format.R32G32B32A32_SInt;
Size = 4 * sizeof(int);
break;
}
case Format.Texture2D:
{
SemanticName = "TEXCOORD";
ElementFormat = SlimDX.DXGI.Format.R32G32_Float;
Size = 2 * sizeof(float);
break;
}
case Format.Texture3D:
{
SemanticName = "TEXCOORD";
ElementFormat = SlimDX.DXGI.Format.R32G32B32_Float;
Size = 3 * sizeof(float);
break;
}
case Format.Texture4D:
{
SemanticName = "TEXCOORD";
ElementFormat = SlimDX.DXGI.Format.R32G32B32A32_Float;
Size = 4 * sizeof(float);
break;
}
case Format.PointSize:
{
SemanticName = "PSIZE";
ElementFormat = SlimDX.DXGI.Format.R32_Float;
Size = 1 * sizeof(float);
break;
}
case Format.Position:
default:
{
SemanticName = "POSITION";
ElementFormat = SlimDX.DXGI.Format.R32G32B32_Float;
Size = 3 * sizeof(float);
break;
}
}
}
public string SemanticName;
public SlimDX.DXGI.Format ElementFormat;
public Format WellKnownFormat;
public int NameIndex;
public int Size;
};
public interface IGeometryBuffer
{
void ConvertToAdjacency();
void DeleteIndexData();
void DeleteVertexData();
int IndexBufferLength { get; }
int IndexBufferOffset { get; set; }
int IndexBufferUsableLength { get; set; }
void SetIndexData(IEnumerable<uint> argIndexData, bool argNeedsDynamicAccess);
void SetIndexData(int argIndexCount, SlimDX.DataStream argIndexData, bool argNeedsDynamicAccess);
void SetVertexData<TVertex>(IEnumerable<TVertex> argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess) where TVertex : struct;
void SetVertexData(int argVertexCount, SlimDX.DataStream argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess);
SlimDX.DataStream MapIndexBufferRaw(SlimDX.Direct3D10.MapMode argAccessMode);
uint[] MapIndexBuffer(SlimDX.Direct3D10.MapMode argAccessMode);
SlimDX.DataStream MapVertexBufferRaw(SlimDX.Direct3D10.MapMode argAccessMode);
TVertex[] MapVertexBuffer<TVertex>(SlimDX.Direct3D10.MapMode argAccessMode) where TVertex : struct;
void UnmapIndexBuffer();
void UnmapVertexBuffer();
SlimDX.Direct3D10.PrimitiveTopology PrimitiveTopology { get; set; }
int VertexBufferLength { get; }
bool IsPickable { get; set; }
IPickHull PickHull { get; }
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX;
namespace Aiwaz.Contracts
{
public interface IPickHull
{
bool TryPick(Ray pickRay, Matrix worldMatrix, out float distance);
BoundingSphere CalcBoundingSphere(Matrix worldMatrix);
BoundingBox CalcBoundingBox(Matrix worldMatrix);
}
}

View File

@@ -0,0 +1,60 @@
using SlimDX;
using SlimDX.Direct3D10;
namespace Aiwaz.Contracts
{
public class ViewPort
{
public ViewPort()
{
MaxDepth = 1.0f;
}
public int TopLeftX;
public int TopLeftY;
public int Width;
public int Height;
public float MinDepth;
public float MaxDepth;
public static implicit operator SlimDX.Direct3D10.Viewport(ViewPort vp)
{
return new SlimDX.Direct3D10.Viewport(vp.TopLeftX, vp.TopLeftY, vp.Width, vp.Height, vp.MinDepth, vp.MaxDepth);
}
};
public enum BindFlags
{
None = 0x000,
ClearDepthStencil = 0x001,
ClearColor = 0x002,
ClearAll = 0x00F,
BindAdditionalTexture0 = 0x010,
BindAdditionalTexture1 = 0x020,
BindAdditionalTexture2 = 0x040,
BindAdditionalTexture3 = 0x080,
BindBaseTexture = 0x100,
BindAllTextures = 0xFF0,
Default = ClearAll | BindAllTextures
};
public interface IRenderTargetBase
{
float ClearDepth { get; set; }
byte ClearStencil { get; set; }
Color4 ClearColor { get; set; }
ViewPort ViewPort { get; set; }
int RenderTargetWidth { get; }
int RenderTargetHeight { get; }
SlimDX.DXGI.Format RenderTargetFormat { get; }
bool HasDepthStencilBuffer { get; set; }
RenderTargetView DX10RenderTargetView { get; }
DepthStencilView DX10DepthStencilView { get; }
void AddAdditionalRenderTarget(IRenderTargetBase target);
void RemoveAdditionalRenderTarget(IRenderTargetBase target);
void Bind(BindFlags bindFlags);
void UnbindAllRenderTargets();
};
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace Aiwaz.Contracts
{
public interface ICreationParams
{
}
public interface IResource
{
ICreationParams CreationParams { get; }
string WellKnownName { get; set; }
IResource Parent { get; set; }
ObservableCollection<IResource> Children { get; }
}
}

View File

@@ -0,0 +1,12 @@
using SlimDX.Direct3D10;
namespace Aiwaz.Contracts
{
public interface IShader
{
string TechniqueName { get; set; }
EffectTechnique Technique { get; }
byte Priority { get; set; }
int CurrentPass { get; }
Effect Effect { get; }
};
}

View File

@@ -0,0 +1,32 @@
using SlimDX.Direct3D10;
using SlimDX;
namespace Aiwaz.Contracts
{
public enum ParameterBindType
{
BindBySemantic,
BindByVariable
};
public interface IShaderParameter
{
ParameterBindType ParameterNameType { get; }
void ApplyValue(EffectVariable argVariable);
};
public interface IShaderParameterSet
{
bool IsPreconditionForFollowingShaders { get; set; }
void SetParameter(string argParameterName, IShaderParameter ar_Parameter_);
void SetParameter(string argParameterName, ITexture argParameter, ParameterBindType argParamNameType);
void SetParameter(string argParameterName, float argParameter, ParameterBindType argParamNameType);
void SetParameter(string argParameterName, Vector3 ar_Parameter_, ParameterBindType argParamNameType);
void SetParameter(string argParameterName, Vector4 ar_Parameter_, ParameterBindType argParamNameType);
void SetParameter(string argParameterName, Matrix argParameter, ParameterBindType argParamNameType);
void SetParameter(string argParameterName, bool argParameter, ParameterBindType argParamNameType);
void SetParameter(string argParameterName, Reference argParameter, ParameterBindType argParamNameType);
void RemoveParameter(string argParameterName);
};
}

View File

@@ -0,0 +1,11 @@
namespace Aiwaz.Contracts
{
public interface ISwapChain
{
void Resize(int argWidth, int argHeight);
void Present();
bool Fullscreen { get; set; }
bool VSync { get; set; }
}
}

View File

@@ -0,0 +1,82 @@
using SlimDX.Direct3D10;
namespace Aiwaz.Contracts
{
public struct LockedTextureData
{
public byte[] Data;
public int RowPitch;
};
public class TextureInitialData
{
public TextureInitialData(byte[] Data, int Pitch)
{
this.Data = Data;
this.Pitch = Pitch;
}
public byte[] Data;
public int Pitch;
};
public struct CreateTextureDescriptor
{
public int Width;
public int Height;
public int Elements;
public int MipLevels;
public SlimDX.DXGI.Format Format;
public ResourceUsage AccessType;
public TextureInitialData InitialData;
public static CreateTextureDescriptor AsSingleTexture(int Width, int Height, SlimDX.DXGI.Format Format, int MipLevels)
{
return AsSingleTexture(Width, Height, Format, MipLevels, null, ResourceUsage.Default);
}
public static CreateTextureDescriptor AsSingleTexture(int Width, int Height, SlimDX.DXGI.Format Format, int MipLevels, TextureInitialData InitialData, ResourceUsage AccessType)
{
CreateTextureDescriptor Desc = new CreateTextureDescriptor();
Desc.Width = Width;
Desc.Height = Height;
Desc.Elements = 0;
Desc.Format = Format;
Desc.AccessType = AccessType;
Desc.InitialData = InitialData;
Desc.MipLevels = MipLevels;
return Desc;
}
public static CreateTextureDescriptor AsArrayTexture(int Width, int Height, int Elements, SlimDX.DXGI.Format Format, int MipLevels, TextureInitialData InitialData)
{
CreateTextureDescriptor Desc = new CreateTextureDescriptor();
Desc.Width = Width;
Desc.Height = Height;
Desc.Elements = Elements;
Desc.Format = Format;
Desc.AccessType = ResourceUsage.Default;
Desc.InitialData = InitialData;
Desc.MipLevels = MipLevels;
return Desc;
}
};
public interface ITexture
{
string BindingName { get; set; }
int TextureWidth { get; }
int TextureHeight { get; }
int TextureArraySize { get; }
SlimDX.DXGI.Format TextureFormat { get; }
ShaderResourceView ResourceView { get; }
Texture2D Texture2D { get; }
SlimDX.DataRectangle MapTextureBuffer(MapMode mode);
SlimDX.DataRectangle MapTextureBuffer(MapMode mode, int arrayElement);
void UnmapTextureBuffer();
};
}

View File

@@ -0,0 +1,32 @@
using SlimDX;
namespace Aiwaz.Contracts
{
public enum KeyFrameTarget
{
Position = 0,
Rotation,
Scale
}
public struct KeyFrame
{
KeyFrame(KeyFrameTarget argTarget, Vector3 argValue, float argTime)
{
Target = argTarget;
Value = argValue;
Time = argTime;
}
KeyFrameTarget Target;
Vector3 Value;
float Time;
}
public interface ITransformationAnimation
{
float Duration { get; }
void AddKeyFrame(KeyFrame argKeyFrame);
Matrix GetTransformationAtTime(float argT); // [0.0] - [1.0]
};
}

View File

@@ -0,0 +1,8 @@
namespace Aiwaz.Contracts
{
public interface IUpdatable
{
void Update(bool argForceUpdate);
bool WantsUpdate { get; }
};
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Aiwaz.Contracts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Aiwaz.Contracts")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0413d7de-46a8-4b64-bdee-e4427bf03026")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,31 @@
namespace Aiwaz.Contracts
{
public class Reference
{
public Reference(object inValue)
{
this.RawValue = inValue;
}
public Reference()
{
}
public object RawValue { get; set; }
}
public class ReferenceT<T> : Reference
{
public ReferenceT(T inValue)
{
this.RawValue = inValue;
}
public ReferenceT()
{
}
public T Value { get { return (T)this.RawValue; } set { this.RawValue = value; } }
}
}

View File

@@ -0,0 +1,114 @@
namespace Aiwaz.Contracts
{
public class AiwazResourceAttribute : System.Attribute
{
public string Name { get; protected set;}
public string Description { get; protected set; }
public AiwazResourceAttribute(string name, string description)
{
this.Name = name;
this.Description = description;
}
}
public static class DataFormatByteSize
{
public static uint GetByteSize(this SlimDX.DXGI.Format argFormat)
{
switch (argFormat)
{
case SlimDX.DXGI.Format.Unknown: return 0;
case SlimDX.DXGI.Format.R32G32B32A32_Typeless: return 16;
case SlimDX.DXGI.Format.R32G32B32A32_Float: return 16;
case SlimDX.DXGI.Format.R32G32B32A32_UInt: return 16;
case SlimDX.DXGI.Format.R32G32B32A32_SInt: return 16;
case SlimDX.DXGI.Format.R32G32B32_Typeless: return 12;
case SlimDX.DXGI.Format.R32G32B32_Float: return 12;
case SlimDX.DXGI.Format.R32G32B32_UInt: return 12;
case SlimDX.DXGI.Format.R32G32B32_SInt: return 12;
case SlimDX.DXGI.Format.R16G16B16A16_Typeless: return 8;
case SlimDX.DXGI.Format.R16G16B16A16_Float: return 8;
case SlimDX.DXGI.Format.R16G16B16A16_UNorm: return 8;
case SlimDX.DXGI.Format.R16G16B16A16_UInt: return 8;
case SlimDX.DXGI.Format.R16G16B16A16_SNorm: return 8;
case SlimDX.DXGI.Format.R16G16B16A16_SInt: return 8;
case SlimDX.DXGI.Format.R32G32_Typeless: return 8;
case SlimDX.DXGI.Format.R32G32_Float: return 8;
case SlimDX.DXGI.Format.R32G32_UInt: return 8;
case SlimDX.DXGI.Format.R32G32_SInt: return 8;
case SlimDX.DXGI.Format.R32G8X24_Typeless: return 8;
case SlimDX.DXGI.Format.D32_Float_S8X24_UInt: return 8;
case SlimDX.DXGI.Format.R32_Float_X8X24_Typeless: return 8;
case SlimDX.DXGI.Format.X32_Typeless_G8X24_UInt: return 8;
case SlimDX.DXGI.Format.R10G10B10A2_Typeless: return 4;
case SlimDX.DXGI.Format.R10G10B10A2_UNorm: return 4;
case SlimDX.DXGI.Format.R10G10B10A2_UInt: return 4;
case SlimDX.DXGI.Format.R11G11B10_Float: return 4;
case SlimDX.DXGI.Format.R8G8B8A8_Typeless: return 4;
case SlimDX.DXGI.Format.R8G8B8A8_UNorm: return 4;
case SlimDX.DXGI.Format.R8G8B8A8_UNorm_SRGB: return 4;
case SlimDX.DXGI.Format.R8G8B8A8_UInt: return 4;
case SlimDX.DXGI.Format.R8G8B8A8_SNorm: return 4;
case SlimDX.DXGI.Format.R8G8B8A8_SInt: return 4;
case SlimDX.DXGI.Format.R16G16_Typeless: return 4;
case SlimDX.DXGI.Format.R16G16_Float: return 4;
case SlimDX.DXGI.Format.R16G16_UNorm: return 4;
case SlimDX.DXGI.Format.R16G16_UInt: return 4;
case SlimDX.DXGI.Format.R16G16_SNorm: return 4;
case SlimDX.DXGI.Format.R16G16_SInt: return 4;
case SlimDX.DXGI.Format.R32_Typeless: return 4;
case SlimDX.DXGI.Format.D32_Float: return 4;
case SlimDX.DXGI.Format.R32_Float: return 4;
case SlimDX.DXGI.Format.R32_UInt: return 4;
case SlimDX.DXGI.Format.R32_SInt: return 4;
case SlimDX.DXGI.Format.R24G8_Typeless: return 4;
case SlimDX.DXGI.Format.D24_UNorm_S8_UInt: return 4;
case SlimDX.DXGI.Format.R24_UNorm_X8_Typeless: return 4;
case SlimDX.DXGI.Format.X24_Typeless_G8_UInt: return 4;
case SlimDX.DXGI.Format.R8G8_Typeless: return 2;
case SlimDX.DXGI.Format.R8G8_UNorm: return 2;
case SlimDX.DXGI.Format.R8G8_UInt: return 2;
case SlimDX.DXGI.Format.R8G8_SNorm: return 2;
case SlimDX.DXGI.Format.R8G8_SInt: return 2;
case SlimDX.DXGI.Format.R16_Typeless: return 2;
case SlimDX.DXGI.Format.R16_Float: return 2;
case SlimDX.DXGI.Format.D16_UNorm: return 2;
case SlimDX.DXGI.Format.R16_UNorm: return 2;
case SlimDX.DXGI.Format.R16_UInt: return 2;
case SlimDX.DXGI.Format.R16_SNorm: return 2;
case SlimDX.DXGI.Format.R16_SInt: return 2;
case SlimDX.DXGI.Format.R8_Typeless: return 1;
case SlimDX.DXGI.Format.R8_UNorm: return 1;
case SlimDX.DXGI.Format.R8_UInt: return 1;
case SlimDX.DXGI.Format.R8_SNorm: return 1;
case SlimDX.DXGI.Format.R8_SInt: return 1;
case SlimDX.DXGI.Format.A8_UNorm: return 1;
case SlimDX.DXGI.Format.R1_UNorm: return 1;
case SlimDX.DXGI.Format.R9G9B9E5_SharedExp: return 4;
case SlimDX.DXGI.Format.R8G8_B8G8_UNorm: return 4;
case SlimDX.DXGI.Format.G8R8_G8B8_UNorm: return 4;
case SlimDX.DXGI.Format.BC1_Typeless: return 2;
case SlimDX.DXGI.Format.BC1_UNorm: return 2;
case SlimDX.DXGI.Format.BC1_UNorm_SRGB: return 2;
case SlimDX.DXGI.Format.BC2_Typeless: return 3;
case SlimDX.DXGI.Format.BC2_UNorm: return 3;
case SlimDX.DXGI.Format.BC2_UNorm_SRGB: return 3;
case SlimDX.DXGI.Format.BC3_Typeless: return 4;
case SlimDX.DXGI.Format.BC3_UNorm: return 4;
case SlimDX.DXGI.Format.BC3_UNorm_SRGB: return 4;
case SlimDX.DXGI.Format.BC4_Typeless: return 1;
case SlimDX.DXGI.Format.BC4_UNorm: return 1;
case SlimDX.DXGI.Format.BC4_SNorm: return 1;
case SlimDX.DXGI.Format.BC5_Typeless: return 2;
case SlimDX.DXGI.Format.BC5_UNorm: return 2;
case SlimDX.DXGI.Format.BC5_SNorm: return 2;
case SlimDX.DXGI.Format.B5G6R5_UNorm: return 2;
case SlimDX.DXGI.Format.B5G5R5A1_UNorm: return 2;
case SlimDX.DXGI.Format.B8G8R8A8_UNorm: return 4;
case SlimDX.DXGI.Format.B8G8R8X8_UNorm: return 4;
default: return 0;
}
}
}
}

View File

@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Aiwaz.Core</RootNamespace>
<AssemblyName>Aiwaz.Core</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="SlimDX, Version=2.0.8.42, Culture=neutral, PublicKeyToken=b1b0c32fd1ffe4f9, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\SlimDX\x86\SlimDX.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DeviceEnumerator\DeviceEnumerator.cs" />
<Compile Include="DeviceEnumerator\DisplayAdapter.cs" />
<Compile Include="DeviceEnumerator\DisplayMode.cs" />
<Compile Include="DeviceEnumerator\OutputDevice.cs" />
<Compile Include="Engine\Engine.cs" />
<Compile Include="Exception.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aiwaz.Common\Aiwaz.Common.csproj">
<Project>{0F7D7168-08C1-45AE-AAE3-80506939D7E6}</Project>
<Name>Aiwaz.Common</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Contracts\Aiwaz.Contracts.csproj">
<Project>{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}</Project>
<Name>Aiwaz.Contracts</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
namespace Aiwaz.Core
{
public class DeviceEnumerator : IDisposable
{
private SlimDX.DXGI.Factory Factory;
internal SlimDX.Direct3D10.Device Device;
public bool HasEnumerated
{
get { return EnumeratedAdapters.Count > 0; }
}
public List<DisplayAdapter> EnumeratedAdapters { get; private set;}
public uint DesiredWidth = 0;
public uint DesiredHeight = 0;
public uint DesiredRefreshRate = 0;
public SlimDX.DXGI.Format DesiredFormat = SlimDX.DXGI.Format.Unknown;
public DeviceEnumerator(SlimDX.Direct3D10.Device argDevice)
{
Factory = new SlimDX.DXGI.Factory();
Device = argDevice;
EnumeratedAdapters = new List<DisplayAdapter>();
}
~DeviceEnumerator()
{
this.Dispose();
}
public bool TryEnumerate()
{
for (var i = 0; i < Factory.GetAdapterCount(); ++i)
{
SlimDX.DXGI.Adapter adapter = Factory.GetAdapter(i);
if (adapter.IsInterfaceSupported(typeof(SlimDX.Direct3D10.Device)))
{
DisplayAdapter displayAdapter = new DisplayAdapter(this, adapter);
if (displayAdapter.TryEnumerate())
EnumeratedAdapters.Add(displayAdapter);
else
adapter.Dispose();
}
else
adapter.Dispose();
}
return HasEnumerated;
}
public DisplayAdapter FindBestAdapter(bool argAllowToEnumerate)
{
if (argAllowToEnumerate && !this.TryEnumerate())
return null;
if (!HasEnumerated)
return null;
return EnumeratedAdapters.Last();
}
public OutputDevice FindBestOutput(bool argAllowToEnumerate)
{
if (argAllowToEnumerate && !this.TryEnumerate())
return null;
if (!HasEnumerated)
return null;
return EnumeratedAdapters.Last().FindBestOutput(argAllowToEnumerate);
}
public DisplayMode FindBestDisplayMode(bool argAllowToEnumerate)
{
if (argAllowToEnumerate && !this.TryEnumerate())
return null;
if (!HasEnumerated)
return null;
return EnumeratedAdapters.Last().FindBestDisplayMode(argAllowToEnumerate);
}
public virtual void Verbose()
{
if (!HasEnumerated)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Enumeration was not executed or no results available.");
return;
}
DisplayAdapter displayAdapter = this.FindBestAdapter(false);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Adapter: " + displayAdapter.Name);
Console.WriteLine("Dedicated System Memory: " + Math.Round(displayAdapter.DedicatedSystemMemory / 1024.0 / 1024.0, 0, MidpointRounding.AwayFromZero).ToString() + "MB");
Console.WriteLine("Dedicated Video Memory: " + Math.Round(displayAdapter.DedicatedVideoMemory / 1024.0 / 1024.0, 0, MidpointRounding.AwayFromZero).ToString() + "MB");
Console.WriteLine("Shared System Memory: " + Math.Round(displayAdapter.SharedSystemMemory / 1024.0 / 1024.0, 0, MidpointRounding.AwayFromZero).ToString() + "MB");
Console.WriteLine();
for (int i = 0; i < displayAdapter.OutputDevices.Count; ++i)
{
OutputDevice outputDevice = displayAdapter.OutputDevices[i];
if (i == 0)
Console.Write("Primary Output: ");
else
Console.Write("Secondary Output: ");
Console.WriteLine(outputDevice.Name);
DisplayMode displayMode = outputDevice.FindBestDisplayMode(false);
uint bpp = displayMode.Format.GetByteSize() * 8;
Console.WriteLine("Display: " + displayMode.Width.ToString() + "x" + displayMode.Height.ToString() + "x" + bpp.ToString() + " @" + displayMode.RefreshRate + "Hz");
Console.WriteLine();
}
}
#region IDisposable Members
public void Dispose()
{
if (Factory != null)
Factory.Dispose();
Factory = null;
if (EnumeratedAdapters != null)
foreach (var adapter in EnumeratedAdapters)
adapter.Dispose();
EnumeratedAdapters = null;
}
#endregion
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
namespace Aiwaz.Core
{
public class DisplayAdapter : IDisposable
{
private DeviceEnumerator deviceEnumerator;
public SlimDX.DXGI.Adapter Adapter { get; private set; }
public bool HasEnumerated
{
get { return OutputDevices.Count > 0; }
}
public long DedicatedSystemMemory
{
get { return Adapter.Description.DedicatedSystemMemory; }
}
public long DedicatedVideoMemory
{
get { return Adapter.Description.DedicatedVideoMemory; }
}
public long SharedSystemMemory
{
get { return Adapter.Description.SharedSystemMemory; }
}
public string Name
{
get { return Adapter.Description.Description; }
}
public List<OutputDevice> OutputDevices { get; private set; }
public DisplayAdapter(DeviceEnumerator argDeviceEnumerator, SlimDX.DXGI.Adapter argAdapter)
{
this.deviceEnumerator = argDeviceEnumerator;
this.Adapter = argAdapter;
this.OutputDevices = new List<OutputDevice>();
}
~DisplayAdapter()
{
this.Dispose();
}
public bool TryEnumerate()
{
for (var i = 0; i < Adapter.GetOutputCount(); ++i)
{
var output = Adapter.GetOutput(i);
OutputDevice device = new OutputDevice(deviceEnumerator, output);
if (device.TryEnumerate())
OutputDevices.Add(device);
else
output.Dispose();
}
return HasEnumerated;
}
public OutputDevice FindBestOutput(bool argAllowToEnumerate)
{
if (argAllowToEnumerate && !this.TryEnumerate())
return null;
if (!HasEnumerated)
return null;
return OutputDevices.Last();
}
public DisplayMode FindBestDisplayMode(bool argAllowToEnumerate)
{
if (argAllowToEnumerate && !this.TryEnumerate())
return null;
if (!HasEnumerated)
return null;
return OutputDevices.Last().FindBestDisplayMode(argAllowToEnumerate);
}
#region IDisposable Members
public void Dispose()
{
if (Adapter != null)
Adapter.Dispose();
Adapter = null;
if (OutputDevices != null)
foreach (var output in OutputDevices)
output.Dispose();
OutputDevices = null;
}
#endregion
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
namespace Aiwaz.Core
{
public class DisplayMode
{
public int Width { get; protected set; }
public int Height { get; protected set; }
public int RefreshRate { get; protected set; }
public SlimDX.DXGI.Format Format { get; protected set; }
public DisplayMode(SlimDX.DXGI.ModeDescription description)
{
this.Width = description.Width;
this.Height = description.Height;
this.Format = description.Format;
this.RefreshRate = description.RefreshRate.Numerator == 0 ? 0 : (int)Math.Round(description.RefreshRate.Numerator / (double)description.RefreshRate.Denominator, 0, MidpointRounding.AwayFromZero);
}
}
}

View File

@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
namespace Aiwaz.Core
{
public class OutputDevice : IDisposable
{
private SlimDX.DXGI.OutputDescription outputDesc;
private DeviceEnumerator deviceEnumerator;
public SlimDX.DXGI.Output Output { get; private set; }
public bool HasEnumerated
{
get { return DisplayModes.Count > 0; }
}
public List<DisplayMode> DisplayModes { get; private set; }
public string Name
{
get { return outputDesc.Name; }
}
public OutputDevice(DeviceEnumerator argDeviceEnumerator, SlimDX.DXGI.Output argOutput)
{
this.deviceEnumerator = argDeviceEnumerator;
this.Output = argOutput;
this.DisplayModes = new List<DisplayMode>();
}
~OutputDevice()
{
this.Dispose();
}
public bool TryEnumerate()
{
for ( int formatIndex = (int)deviceEnumerator.DesiredFormat;
formatIndex <= (deviceEnumerator.DesiredFormat == SlimDX.DXGI.Format.Unknown ? (int)SlimDX.DXGI.Format.B8G8R8X8_UNorm : (int)deviceEnumerator.DesiredFormat);
++formatIndex
)
{
var format = (SlimDX.DXGI.Format)formatIndex;
var flags = SlimDX.DXGI.DisplayModeEnumerationFlags.Scaling;
var displayModes = Output.GetDisplayModeList(format, flags);
if (displayModes.Count > 0)
{
foreach (var displayModeRaw in displayModes)
{
var keepDisplayMode = false;
var refreshRate = displayModeRaw.RefreshRate.Numerator == 0 ? 0 : (int)(displayModeRaw.RefreshRate.Numerator / displayModeRaw.RefreshRate.Denominator);
if ((deviceEnumerator.DesiredWidth == 0 || deviceEnumerator.DesiredWidth <= displayModeRaw.Width) &&
(deviceEnumerator.DesiredHeight == 0 || deviceEnumerator.DesiredHeight <= displayModeRaw.Height) &&
(deviceEnumerator.DesiredRefreshRate == 0 || deviceEnumerator.DesiredRefreshRate <= refreshRate) &&
(deviceEnumerator.DesiredFormat == SlimDX.DXGI.Format.Unknown || (int)deviceEnumerator.DesiredFormat == (int)displayModeRaw.Format))
{
if (deviceEnumerator.Device != null)
{
var supported = deviceEnumerator.Device.CheckFormatSupport(format);
if ((supported & SlimDX.Direct3D10.FormatSupport.FormatDisplaySupport) != 0)
keepDisplayMode = true;
}
else
keepDisplayMode = true;
}
if (keepDisplayMode)
DisplayModes.Add(new DisplayMode(displayModeRaw));
}
}
}
return HasEnumerated;
}
public DisplayMode FindBestDisplayMode(bool argAllowToEnumerate)
{
if (argAllowToEnumerate && !this.TryEnumerate())
return null;
if (!HasEnumerated)
return null;
return DisplayModes.Last();
}
#region IDisposable Members
public void Dispose()
{
if (Output != null)
Output.Dispose();
Output = null;
}
#endregion
}
}

View File

@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Common;
using SlimDX;
namespace Aiwaz.Core
{
public static class Engine
{
public static SlimDX.DXGI.Factory Factory { get; private set; }
public static SlimDX.Direct3D10.Device Device { get; private set; }
public static DeviceEnumerator DeviceEnumerator { get; private set; }
public static EngineStates EngineStates { get; private set; }
public static FileSystem FileSystem { get; private set; }
public static bool Initialized = false;
private static List<WeakReference> managedEngineDisposables;
private static Dictionary<string, WeakReference> managedNamedObjects;
public static void Initialize(DisplayAdapter adapter)
{
if (Initialized)
throw new OnlyOneInstanceAllowedException(typeof(Engine).Name);
managedEngineDisposables = new List<WeakReference>();
managedNamedObjects = new Dictionary<string, WeakReference>();
EngineStates = new EngineStates();
DeviceEnumerator = new DeviceEnumerator(null);
DeviceEnumerator.DesiredFormat = SlimDX.DXGI.Format.R8G8B8A8_UNorm;
FileSystem = new FileSystem();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Initializing engine.");
if (adapter == null)
{
if (!DeviceEnumerator.HasEnumerated && !DeviceEnumerator.TryEnumerate())
throw new InitializingFailedException(typeof(Engine).Name, "Failed to enumerate device.");
adapter = DeviceEnumerator.FindBestAdapter(false);
DeviceEnumerator.Verbose();
}
SlimDX.Direct3D10.DeviceCreationFlags deviceFlags = SlimDX.Direct3D10.DeviceCreationFlags.None;
#if DEBUG
// we want debug informations when we run a debug build
deviceFlags |= SlimDX.Direct3D10.DeviceCreationFlags.Debug;
#endif
// lets create the device now
Device = new SlimDX.Direct3D10.Device(adapter.Adapter, SlimDX.Direct3D10.DriverType.Hardware, deviceFlags);
if(Device == null)
throw new InitializingFailedException(typeof(Engine).Name, "Failed to create device.");
Factory = new SlimDX.DXGI.Factory();
if(Factory == null)
throw new InitializingFailedException(typeof(Engine).Name, "Failed to create GI factory.");
Console.WriteLine("Finished initializing engine.\n");
Initialized = true;
}
public static void RegisterEngineDisposable(IDisposable disposable)
{
if (!Initialized)
throw new InvalidOperationException("Engine not initialized!");
RemoveOrphanedObjects();
managedEngineDisposables.Add(new WeakReference(disposable));
}
public static bool UnregisterEngineDisposable(IDisposable disposable)
{
if (!Initialized)
throw new InvalidOperationException("Engine not initialized!");
RemoveOrphanedObjects();
var weak = managedEngineDisposables.FirstOrDefault(item => item.Target == disposable);
if (weak != null)
return managedEngineDisposables.Remove(weak);
return false;
}
public static bool ExistsName(string name)
{
foreach (var o in managedNamedObjects)
{
if (o.Key == name)
return true;
}
return false;
}
public static void RegisterNamedObject(string name, object item)
{
if (!Initialized)
throw new InvalidOperationException("Engine not initialized!");
RemoveOrphanedObjects();
managedNamedObjects.Add(name, new WeakReference(item));
}
public static void UnregisterNamedObject(string name)
{
if (!Initialized)
throw new InvalidOperationException("Engine not initialized!");
RemoveOrphanedObjects();
managedNamedObjects.Remove(name);
}
public static object FindNamedObject(string name)
{
if (!Initialized)
throw new InvalidOperationException("Engine not initialized!");
RemoveOrphanedObjects();
WeakReference result;
if (managedNamedObjects.TryGetValue(name, out result) && result.IsAlive)
return result.Target;
return null;
}
private static void RemoveOrphanedObjects()
{
int count = managedEngineDisposables.Count;
do
{
managedEngineDisposables.RemoveAll(item => item.IsAlive == false);
} while (count > managedEngineDisposables.Count);
}
public static void Uninitialize()
{
if (!Initialized)
throw new InvalidOperationException("Engine not initialized!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Uninitializing engine.");
while (managedEngineDisposables.Count > 0)
{
var weakDisposable = managedEngineDisposables.First();
if (weakDisposable.IsAlive && weakDisposable.Target is IDisposable)
((IDisposable)weakDisposable.Target).Dispose();
managedEngineDisposables.Remove(weakDisposable);
}
if (Device != null)
Device.Dispose();
Device = null;
if (Factory != null)
Factory.Dispose();
Factory = null;
if (DeviceEnumerator != null)
DeviceEnumerator.Dispose();
DeviceEnumerator = null;
if (FileSystem != null)
FileSystem.Dispose();
FileSystem = null;
}
}
}

View File

@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Core
{
public class InitializingFailedException : Exception
{
public InitializingFailedException()
: this(null, null)
{
}
public InitializingFailedException(string objectName)
: this(objectName, null)
{
}
public InitializingFailedException(string objectName, string reason)
{
string text = "";
if (string.IsNullOrEmpty(objectName) && string.IsNullOrEmpty(reason))
text = "Unable to initialize object.";
else if (string.IsNullOrEmpty(reason))
text = string.Format("Unable to initialize object '{0}'.", objectName);
else if (string.IsNullOrEmpty(objectName))
text = string.Format("Unable to initialize object. {0}", reason);
else
text = string.Format("Unable to initialize object '{0}'. {1}", objectName, reason);
if (string.IsNullOrEmpty(text))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
}
}
}
public class UninitializingFailedException : Exception
{
public UninitializingFailedException()
: this(null, null)
{
}
public UninitializingFailedException(string objectName)
: this(objectName, null)
{
}
public UninitializingFailedException(string objectName, string reason)
{
string text = "";
if (string.IsNullOrEmpty(objectName) && string.IsNullOrEmpty(reason))
text = "Unable to uninitialize object.";
else if (string.IsNullOrEmpty(reason))
text = string.Format("Unable to uninitialize object '{0}'.", objectName);
else if (string.IsNullOrEmpty(objectName))
text = string.Format("Unable to uninitialize object. {0}", reason);
else
text = string.Format("Unable to uninitialize object '{0}'. {1}", objectName, reason);
if (string.IsNullOrEmpty(text))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
}
}
}
public class OnlyOneInstanceAllowedException : Exception
{
public OnlyOneInstanceAllowedException()
: this(null, null)
{
}
public OnlyOneInstanceAllowedException(string objectName)
: this(objectName, null)
{
}
public OnlyOneInstanceAllowedException(string objectName, string reason)
{
string text = "";
if (string.IsNullOrEmpty(objectName) && string.IsNullOrEmpty(reason))
text = "Only one instance of this object could exist.";
else if (string.IsNullOrEmpty(reason))
text = string.Format("Only one instance of this object '{0}' could exist.", objectName);
else if (string.IsNullOrEmpty(objectName))
text = string.Format("Only one instance of this object could exist. {1}", reason);
else
text = string.Format("Only one instance of this object '{0}' could exist. {1}", objectName, reason);
if (string.IsNullOrEmpty(text))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
}
}
}
public class ActionFailedException : Exception
{
public ActionFailedException()
: this("Action has failed.")
{
}
public ActionFailedException(string text)
: base(text)
{
if (string.IsNullOrEmpty(text))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
}
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AiwazCore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AiwazCore")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cf679c7b-ebf8-4da3-9f46-97c7dbd88d69")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C3222C73-8869-46A6-862D-4B73DD52BC23}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Aiwaz.Demo</RootNamespace>
<AssemblyName>Aiwaz.Demo</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<StartupObject>
</StartupObject>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="SlimDX, Version=2.0.8.42, Culture=neutral, PublicKeyToken=b1b0c32fd1ffe4f9, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\SlimDX\x86\SlimDX.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aiwaz.Common\Aiwaz.Common.csproj">
<Project>{0F7D7168-08C1-45AE-AAE3-80506939D7E6}</Project>
<Name>Aiwaz.Common</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Contracts\Aiwaz.Contracts.csproj">
<Project>{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}</Project>
<Name>Aiwaz.Contracts</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Core\Aiwaz.Core.csproj">
<Project>{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}</Project>
<Name>Aiwaz.Core</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Resources\Aiwaz.Resources.csproj">
<Project>{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}</Project>
<Name>Aiwaz.Resources</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Aiwaz.Common;
using Aiwaz.Core;
using Aiwaz.Contracts;
using Aiwaz.Resources;
using Aiwaz.Resources.Prefab;
using SlimDX.Windows;
using System.Drawing;
using Aiwaz.Common.Animations;
namespace Aiwaz.Demo
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
var console = new Win32Console();
var renderForm = new RenderForm("Aiwaz.Demo");
Engine.Initialize(null);
var model = new BluModel(new BluModelParams() { FileName = "Data/ChamferBox.blu" } );
model.RootTransformation.LocalScale = new SlimDX.Vector3(0.1f, 0.1f, 0.1f);
model.RootTransformation.LocalPosition = new SlimDX.Vector3(1.0f, 0.0f, 2.0f);
var swapChain = new SwapChain(renderForm.Handle);
swapChain.ClearColor = new SlimDX.Color4(Color.DarkBlue);
swapChain.HasDepthStencilBuffer = true;
swapChain.VSync = false;
var camera = new PerspectiveCamera(new PerspectiveCameraParams() { aspectRatio = (float)renderForm.Size.Width / renderForm.Size.Height } );
var normalMapping = new Shader(new ShaderParams() { FileName = "Data/NormalOutput.fx", TechniqueName = "NormalMapping" } );
var wallTexture = new Texture(new FileTextureParams() { FileName = "Data/Wall.jpg" } );
var wallNormalTexture = new Texture(new FileTextureParams() { FileName = "Data/WallNormal.jpg" });
wallNormalTexture.BindingName = "Normal";
var roomCube = new Cube(new CubeParams() { Width = 10.0f, Height = 10.0f, Depth = 10.0f, IsInverted = true } );
var roomCubeTransformation = new Transformation(new DefaultTransformationBindings());
roomCubeTransformation.LocalPosition = new SlimDX.Vector3(0.0f, 0.0f, 2.0f);
var lightPosition = new ReferenceT<SlimDX.Vector3>(new SlimDX.Vector3(0.0f, 1.0f, 0.0f));
var lightColor = new ReferenceT<SlimDX.Vector4>(new SlimDX.Vector4(2.0f, 2.0f, 1.0f, 1.0f));
var lightParameters = new ShaderParameterSet();
lightParameters.IsPreconditionForFollowingShaders = true;
lightParameters.SetParameter("LightPosition", lightPosition, ParameterBindType.BindBySemantic);
lightParameters.SetParameter("LightColor", lightColor, ParameterBindType.BindBySemantic);
var rootRenderNode = new RenderCommandNode();
rootRenderNode.Children.Add(swapChain);
rootRenderNode.Children.Add(camera);
rootRenderNode.Children.Add(lightParameters);
rootRenderNode.Children.Add(roomCubeTransformation);
rootRenderNode.Children.Add(normalMapping);
rootRenderNode.Children.Add(wallTexture);
rootRenderNode.Children.Add(wallNormalTexture);
rootRenderNode.Children.Add(roomCube.GeometryBuffer);
rootRenderNode.Children.Add(model.RootNode);
var refreshTimer = 0.0f;
MessagePump.Run(renderForm, () =>
{
rootRenderNode.Update(false);
rootRenderNode.ProcessCommands();
swapChain.Present();
float time = (float)HiPerfTimer.ElapsedTime * 10.0f;
lightColor.Value = new SlimDX.Vector4(2.0f, 2.0f, 1.0f, 1.0f) * ((float)Math.Sin(time)+ 2.0f);
roomCubeTransformation.LocalRotationYPR = new SlimDX.Vector3(time, time, time) * 0.01f;
refreshTimer -= (float)HiPerfTimer.LastDeltaTime;
if (refreshTimer < 0.0f)
{
refreshTimer = 1.0f;
renderForm.Text = string.Format("Aiwaz: {0:F2} FPS ({1:F2} ms)", 1.0 / HiPerfTimer.LastDeltaTime, HiPerfTimer.LastDeltaTime * 1000);
}
model.RootTransformation.LocalRotationYPR = new SlimDX.Vector3(time, time, time) * 0.03f;
});
renderForm = null;
swapChain = null;
Engine.Uninitialize();
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Aiwaz.Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Aiwaz.Demo")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("907b7671-5ba3-4251-a4bb-802dbd1ae180")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Aiwaz.Demo.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Aiwaz.Demo.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Aiwaz.Demo.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@@ -0,0 +1,208 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5AD414C8-9564-406C-888E-1C4E89DBA566}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Aiwaz.Editor</RootNamespace>
<AssemblyName>Aiwaz.Editor</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="IronPython, Version=2.6.10920.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\IronPython.dll</HintPath>
</Reference>
<Reference Include="IronPython.Modules, Version=2.6.10920.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\IronPython.Modules.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Dynamic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\Microsoft.Dynamic.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Scripting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\Microsoft.Scripting.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Scripting.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\Microsoft.Scripting.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Scripting.Debugging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\Microsoft.Scripting.Debugging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Scripting.ExtensionAttribute, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\IronPython\Microsoft.Scripting.ExtensionAttribute.dll</HintPath>
</Reference>
<Reference Include="SlimDX, Version=2.0.8.42, Culture=neutral, PublicKeyToken=b1b0c32fd1ffe4f9, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\SlimDX\x86\SlimDX.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="UIAutomationProvider">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="PresentationCore">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="PresentationFramework">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsFormsIntegration">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="Controls\AiwazViewControl.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Controls\PropertyItem.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Controls\PropertyGrid.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Views\MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="Views\MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Controls\PropertyGrid.xaml.cs">
<DependentUpon>PropertyGrid.xaml</DependentUpon>
</Compile>
<Compile Include="Controls\PropertyItem.xaml.cs">
<DependentUpon>PropertyItem.xaml</DependentUpon>
</Compile>
<Compile Include="ViewModels\ResourceViewModel.cs" />
<Compile Include="ViewModels\ViewModelBase.cs" />
<Compile Include="Controls\AiwazViewControl.xaml.cs">
<DependentUpon>AiwazViewControl.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<None Include="Editor.py">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<None Include="Resources\SelectionHighlight.fx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<AppDesigner Include="Properties\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aiwaz.Common\Aiwaz.Common.csproj">
<Project>{0F7D7168-08C1-45AE-AAE3-80506939D7E6}</Project>
<Name>Aiwaz.Common</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Contracts\Aiwaz.Contracts.csproj">
<Project>{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}</Project>
<Name>Aiwaz.Contracts</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Core\Aiwaz.Core.csproj">
<Project>{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}</Project>
<Name>Aiwaz.Core</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Demo\Aiwaz.Demo.csproj">
<Project>{C3222C73-8869-46A6-862D-4B73DD52BC23}</Project>
<Name>Aiwaz.Demo</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Resources\Aiwaz.Resources.csproj">
<Project>{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}</Project>
<Name>Aiwaz.Resources</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Resources\Untitled.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="EmbeddedResources\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,10 @@
<Application x:Class="Aiwaz.Editor.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Views/MainWindow.xaml"
Startup="Application_Startup"
Exit="Application_Exit">
<Application.Resources>
</Application.Resources>
</Application>

View File

@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Aiwaz.Core;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Reflection;
using System.IO;
namespace Aiwaz.Editor
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public ScriptEngine ScriptEngine;
private void Application_Exit(object sender, ExitEventArgs e)
{
Engine.Uninitialize();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
Engine.Initialize(null);
this.ScriptEngine = Python.CreateEngine();
this.ScriptEngine.Runtime.LoadAssembly(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "Aiwaz.Contracts.dll")));
this.ScriptEngine.Runtime.LoadAssembly(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "Aiwaz.Common.dll")));
this.ScriptEngine.Runtime.LoadAssembly(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "Aiwaz.Core.dll")));
this.ScriptEngine.Runtime.LoadAssembly(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "Aiwaz.Resources.dll")));
var globalScope = this.ScriptEngine.Runtime.CreateScope();
globalScope.SetVariable("myVar", "hallo");
var script = this.ScriptEngine.CreateScriptSourceFromFile("Editor.py");
var code = script.Compile();
script.Execute(globalScope); // see output window, fool!
var myVarResult = globalScope.GetVariable("myVar");
}
}
}

View File

@@ -0,0 +1,10 @@
<UserControl x:Class="Aiwaz.Editor.Controls.AiwazViewControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
<Grid>
<WindowsFormsHost>
<wf:UserControl x:Name="RenderTarget" Resize="RenderTarget_Resize"/>
</WindowsFormsHost>
</Grid>
</UserControl>

View File

@@ -0,0 +1,407 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Aiwaz.Resources;
using System.Windows.Threading;
using Aiwaz.Core;
using Aiwaz.Contracts;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using SlimDX;
namespace Aiwaz.Editor.Controls
{
/// <summary>
/// Interaction logic for AiwazViewControl.xaml
/// </summary>
public partial class AiwazViewControl : System.Windows.Controls.UserControl
{
#region Win32
public static Point CorrectGetPosition(Visual relativeTo)
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y));
}
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
#endregion
private DateTime lastPerformCalledTime = DateTime.UtcNow;
private bool rightButtonPressed;
private bool leftButtonPressed;
private bool moveThresholdReached;
private Point lastMousePosition;
private int desiredFPS = 30;
private DispatcherTimer renderTimer;
private RenderCommandNode mainRootNode;
private RenderCommandNode rootNode;
private Shader selectionShader;
private RenderCommandNode selectionMarkerNode;
private PickableResourceInfo selectedResourceInfo;
public delegate void PerformCalledDelegate(object sender, TimeSpan elapsedTime);
public delegate void SelectedResourceChangedDelegate(object sender, PickableResourceInfo newSelectedResourceInfo);
public event PerformCalledDelegate PerformCalled;
public event SelectedResourceChangedDelegate SelectedResourceChanged;
public AiwazViewControl()
{
InitializeComponent();
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
return;
this.SwapChain = new SwapChain(RenderTarget.Handle);
this.SwapChain.HasDepthStencilBuffer = true;
MainRootNode.Children.Add(this.SwapChain);
MainRootNode.Children.Add(RootNode);
renderTimer = new DispatcherTimer();
renderTimer.Tick += new EventHandler(delegate(object s, EventArgs a)
{
this.Perform();
});
renderTimer.Interval = TimeSpan.FromMilliseconds(1000 / 30.0);
renderTimer.Start();
selectionMarkerNode = new RenderCommandNode();
selectionShader = new Shader(new ShaderParams() { FileName = "Resources/SelectionHighlight.fx" });
selectionShader.Priority = 128;
MainRootNode.Children.Add(selectionMarkerNode);
this.RenderTarget.MouseDown += new System.Windows.Forms.MouseEventHandler(RenderTarget_MouseButtonDown);
this.RenderTarget.MouseUp += new System.Windows.Forms.MouseEventHandler(RenderTarget_MouseButtonUp);
}
public ICamera MainCamera
{
get
{
return FindLastAvailableCamera(MainRootNode);
}
}
public PickableResourcesDataSource PickableResources { get; set; }
public RenderCommandNode MainRootNode
{
get
{
if (mainRootNode == null)
{
mainRootNode = new RenderCommandNode();
}
return mainRootNode;
}
set
{
mainRootNode = value;
}
}
public SwapChain SwapChain { get; protected set; }
public RenderCommandNode RootNode
{
get
{
if (rootNode == null)
{
rootNode = new RenderCommandNode();
}
return rootNode;
}
set
{
mainRootNode.Children.Remove(rootNode);
rootNode = value;
mainRootNode.Children.Add(value);
}
}
public TimeSpan RenderInterval
{
get { return renderTimer.Interval; }
set { renderTimer.Interval = value; }
}
public PickableResourceInfo SelectedResourceInfo
{
get
{
return selectedResourceInfo;
}
set
{
if (selectedResourceInfo != null)
{
selectionMarkerNode.Children.Clear();
selectionMarkerNode.MarkDirty();
}
selectedResourceInfo = value;
if (selectedResourceInfo != null)
{
selectionMarkerNode.Children.Add(selectionShader);
if (selectedResourceInfo.Transformation != null)
selectionMarkerNode.Children.Add(selectedResourceInfo.Transformation);
if (selectedResourceInfo.Resource != null)
selectionMarkerNode.Children.Add(selectedResourceInfo.Resource);
}
if (SelectedResourceChanged != null)
SelectedResourceChanged(this, selectedResourceInfo);
}
}
public int DesiredFPS
{
get
{
return desiredFPS;
}
set
{
desiredFPS = value;
if (desiredFPS <= 0)
renderTimer.Interval = TimeSpan.FromMilliseconds(0);
else
renderTimer.Interval = TimeSpan.FromMilliseconds(1000 / (double)desiredFPS);
}
}
private ICamera FindLastAvailableCamera(Resource rootNode)
{
ICamera lastFoundCamera = null;
if (rootNode.Children != null)
foreach (var child in rootNode.Children)
{
if (child is ICamera)
lastFoundCamera = child as ICamera;
if (child is Resource)
lastFoundCamera = this.FindLastAvailableCamera(child as Resource) ?? lastFoundCamera;
}
return lastFoundCamera;
}
protected void Perform()
{
mainRootNode.Update(false);
mainRootNode.ProcessCommands();
this.SwapChain.Present();
var deltaTime = DateTime.UtcNow - lastPerformCalledTime;
this.PerformCalledInternal(deltaTime);
if (PerformCalled != null)
PerformCalled(this, deltaTime);
lastPerformCalledTime = DateTime.UtcNow;
}
private void RenderTarget_Resize(object sender, EventArgs e)
{
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
return;
this.SwapChain.Resize((int)this.Width, (int)this.Height);
}
private void RenderTarget_MouseButtonUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
rightButtonPressed = false;
else if (e.Button == MouseButtons.Left)
leftButtonPressed = false;
lastMousePosition = CorrectGetPosition(this);
if (!moveThresholdReached)
{
if (e.Button == MouseButtons.Right)
{
if (this.ContextMenu != null)
this.ContextMenu.IsOpen = true;
}
else if (e.Button == MouseButtons.Left)
{
if (PickableResources != null)
{
var mainCamera = this.MainCamera;
int width = this.SwapChain.ViewPort.Width;
int height = this.SwapChain.ViewPort.Height;
var viewProj = mainCamera.ViewMatrix * mainCamera.ProjectionMatrix;
Vector3 ZNearPlane = Vector3.Unproject(new Vector3((float)lastMousePosition.X, (float)lastMousePosition.Y, 0), 0, 0, width, height,
this.SwapChain.ViewPort.MinDepth, this.SwapChain.ViewPort.MaxDepth, viewProj);
Vector3 ZFarPlane = Vector3.Unproject(new Vector3((float)lastMousePosition.X, (float)lastMousePosition.Y, 1), 0, 0, width, height,
this.SwapChain.ViewPort.MinDepth, this.SwapChain.ViewPort.MaxDepth, viewProj);
Vector3 direction = ZFarPlane - ZNearPlane;
direction.Normalize();
Ray ray = new Ray(ZNearPlane, direction);
PickableResourceInfo winnerResourceInfo = this.SelectedResourceInfo;
float distance = float.MaxValue;
foreach (var pickable in PickableResources)
{
float newDistance;
if (pickable.PickHull.TryPick(ray, pickable.Transformation.WorldMatrix, out newDistance)
&& newDistance < distance)
{
winnerResourceInfo = pickable;
distance = newDistance;
}
}
if (this.SelectedResourceInfo != null && winnerResourceInfo != null && this.SelectedResourceInfo.Resource == winnerResourceInfo.Resource)
winnerResourceInfo = null;
this.SelectedResourceInfo = winnerResourceInfo;
}
}
}
if (!leftButtonPressed && !rightButtonPressed)
{
renderTimer.Interval = TimeSpan.FromMilliseconds(1000 / (double)desiredFPS);
moveThresholdReached = false;
}
}
private void RenderTarget_MouseButtonDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
rightButtonPressed = true;
else if (e.Button == MouseButtons.Left)
leftButtonPressed = true;
if (leftButtonPressed || rightButtonPressed)
renderTimer.Interval = TimeSpan.FromMilliseconds(0);
lastMousePosition = CorrectGetPosition(this);
}
private void PerformCalledInternal(TimeSpan elapsedTime)
{
var currentMousePosition = CorrectGetPosition(this);
var deltaTime = Math.Max(1.0, elapsedTime.TotalSeconds);
var deltaMouse = currentMousePosition - lastMousePosition;
lastMousePosition = currentMousePosition;
var power = 1.7;
if (rightButtonPressed && !leftButtonPressed)
power = 1.25;
deltaMouse.X = Math.Pow(Math.Abs(deltaMouse.X), power) * Math.Sign(deltaMouse.X) * deltaTime;
deltaMouse.Y = Math.Pow(Math.Abs(deltaMouse.Y), power) * Math.Sign(deltaMouse.Y) * deltaTime;
if (!leftButtonPressed && !rightButtonPressed)
return;
moveThresholdReached = moveThresholdReached || deltaMouse.Length >= 3.0;
if (!moveThresholdReached)
return;
var mainCamera = this.MainCamera as Transformation;
if (rightButtonPressed && leftButtonPressed)
{
mainCamera.LocalPosition += mainCamera.LocalUpDirection * -(float)deltaMouse.Y * 0.005f +
mainCamera.LocalRightDirection * (float)deltaMouse.X * 0.005f;
}
else if (leftButtonPressed)
{
mainCamera.LocalPosition += mainCamera.LocalDirection * -(float)deltaMouse.Y * 0.005f +
mainCamera.LocalRightDirection * (float)deltaMouse.X * 0.005f;
}
else if (rightButtonPressed)
{
var yawPitchRoll = mainCamera.LocalRotationYPR;
yawPitchRoll.X += (float)deltaMouse.X * 0.005f;
yawPitchRoll.Y += (float)deltaMouse.Y * 0.005f;
if (yawPitchRoll.Y > Math.PI / 2)
yawPitchRoll.Y = (float)Math.PI / 2;
else if (yawPitchRoll.Y < -Math.PI / 2)
yawPitchRoll.Y = -(float)Math.PI / 2;
mainCamera.LocalRotationYPR = yawPitchRoll;
}
}
}
public class PickableResourcesDataSource : List<PickableResourceInfo>
{
public static PickableResourcesDataSource CreateFromResource(Resource rootNode)
{
var pickablesDataResource = new PickableResourcesDataSource();
List<KeyValuePair<Transformation, IGeometryBuffer>> pickables = new List<KeyValuePair<Transformation, IGeometryBuffer>>();
FindAllPickables(rootNode, null, pickables);
foreach (var pickable in pickables)
{
pickablesDataResource.Add(new PickableResourceInfo()
{
PickHull = pickable.Value.PickHull,
Transformation = pickable.Key,
Resource = pickable.Value as IResource
});
}
return pickablesDataResource;
}
private static void FindAllPickables(Resource rootNode, Transformation lastTransformation, List<KeyValuePair<Transformation, IGeometryBuffer>> pickables)
{
if (rootNode.Children != null)
foreach (var child in rootNode.Children)
{
if (child is Transformation)
lastTransformation = child as Transformation;
if (child is IGeometryBuffer && lastTransformation != null)
{
var geoBuffer = child as IGeometryBuffer;
if (geoBuffer.IsPickable)
pickables.Add(new KeyValuePair<Transformation, IGeometryBuffer>(lastTransformation, geoBuffer));
}
if (child is Resource)
FindAllPickables(child as Resource, lastTransformation, pickables);
}
}
}
public class PickableResourceInfo
{
public IResource Resource;
public Transformation Transformation;
public IPickHull PickHull;
}
}

View File

@@ -0,0 +1,36 @@
<HeaderedContentControl x:Class="Aiwaz.Editor.Controls.PropertyGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pg="clr-namespace:Aiwaz.Editor.Controls">
<HeaderedContentControl.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Search:" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<TextBox x:Name="searchTextBox" Grid.Column="1"/>
</Grid>
</HeaderedContentControl.Header>
<Border BorderThickness="1" BorderBrush="#FF828790">
<Grid>
<Grid.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="LightGray" Offset="0.0" />
<GradientStop Color="White" Offset="1.0" />
</LinearGradientBrush>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ScrollViewer x:Name="propertyGridScrollBar" Grid.Row="0" CanContentScroll="False" VerticalScrollBarVisibility="Visible">
<ScrollViewer.Content>
<StackPanel x:Name="PropertyPanel"/> <!--PropertyItems go in here-->
</ScrollViewer.Content>
</ScrollViewer>
<TextBlock x:Name="descriptionTextBlock" Grid.Row="1" TextWrapping="Wrap"/>
</Grid>
</Border>
</HeaderedContentControl>

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.ComponentModel;
namespace Aiwaz.Editor.Controls
{
public partial class PropertyGrid : HeaderedContentControl
{
private object selectedObject = null;
public PropertyGrid()
{
InitializeComponent();
searchTextBox.TextChanged += new TextChangedEventHandler(searchTextBox_TextChanged);
}
#region PropertyGrid related stuff
public object SelectedObject{
get { return selectedObject; }
set { selectedObject = value; SelectedObjectHelper(selectedObject,null); }
}
public void SelectedObjectHelper(object value,EventArgs e) {
if (!Application.Current.Dispatcher.CheckAccess())
{
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new EventHandler(SelectedObjectHelper), value, e);
}
else
{
this.PropertyPanel.Children.Clear(); //clear propertypanel
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value))
{
if (!property.IsBrowsable) continue; //could also check for browsableattribute, but this one's shorter
PropertyItem currentProperty = new PropertyItem();
currentProperty.PropertyName = property.Name;
Binding b = new Binding(property.Name);
b.Source = selectedObject;
b.Mode = property.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay;
currentProperty.SetBinding(PropertyItem.PropertyValueProperty, b);
currentProperty.OnActive += new EventHandler<DescriptionEventArgs>(currentProperty_OnActive);
foreach (Attribute attribute in property.Attributes)
{
if (attribute.GetType() == typeof(DescriptionAttribute))
{
currentProperty.PropertyDescription = ((DescriptionAttribute)attribute).Description;
}
if (attribute.GetType() == typeof(CategoryAttribute)) {
currentProperty.PropertyCategory = ((CategoryAttribute)attribute).Category;
}
}
PropertyPanel.Children.Add(currentProperty); //add the propertyitem
}
}
}
#endregion
#region events
void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string filterText = searchTextBox.Text.ToLower(); //we don't want to be case sensitive
foreach (PropertyItem pi in PropertyPanel.Children)
{ //hide PropertyItem if it does not contain filter text
pi.Visibility = (pi.PropertyName.ToLower().Contains(filterText) || filterText.Equals(string.Empty)) ? Visibility.Visible : Visibility.Collapsed;
}
}
void currentProperty_OnActive(object sender, DescriptionEventArgs e)
{
if (!Application.Current.Dispatcher.CheckAccess()){
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new EventHandler<DescriptionEventArgs>(currentProperty_OnActive),sender, e);
}else{
this.descriptionTextBlock.Text = e.Description;
}
}
#endregion
}
}

View File

@@ -0,0 +1,13 @@
<UserControl x:Class="Aiwaz.Editor.Controls.PropertyItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Grid x:Name="PropertyItemGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=PropertyName}" Grid.Column="0"/>
<TextBox Text="{Binding Path=PropertyValue,Mode=TwoWay}" Grid.Column="1" MouseEnter="TextBox_MouseEnter" />
</Grid>
</UserControl>

View File

@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.ComponentModel;
namespace Aiwaz.Editor.Controls
{
/// <summary>
/// Interaction logic for PropertyItem.xaml
/// </summary>
public partial class PropertyItem : UserControl
{
public static readonly DependencyProperty PropertyNameProperty = DependencyProperty.Register("PropertyName", typeof(string), typeof(PropertyItem));
public static readonly DependencyProperty PropertyValueProperty = DependencyProperty.Register("PropertyValue", typeof(object), typeof(PropertyItem));
public static readonly DependencyProperty PropertyDescriptionProperty = DependencyProperty.Register("PropertyDescription", typeof(string), typeof(PropertyItem));
public static readonly DependencyProperty PropertyCategoryProperty = DependencyProperty.Register("PropertyCategory", typeof(string), typeof(PropertyItem));
public EventHandler<DescriptionEventArgs> DescriptionEventHandler;
public event EventHandler<DescriptionEventArgs> OnActive;
public PropertyItem()
{
InitializeComponent();
PropertyItemGrid.DataContext = this;
}
public string PropertyName {
get { return (string)GetValue(PropertyItem.PropertyNameProperty); }
set { SetValue(PropertyItem.PropertyNameProperty, value); }
}
public object PropertyValue
{
get{ return (string)GetValue(PropertyItem.PropertyValueProperty);}
set{ SetValue(PropertyItem.PropertyValueProperty, value); }
}
public string PropertyDescription
{
get { return (string)GetValue(PropertyItem.PropertyDescriptionProperty); }
set { SetValue(PropertyItem.PropertyDescriptionProperty, value);}
}
public string PropertyCategory
{
get { return (string)GetValue(PropertyItem.PropertyCategoryProperty); }
set { SetValue(PropertyItem.PropertyCategoryProperty, value); }
}
#region events
private void TextBox_MouseEnter(object sender, MouseEventArgs e)
{
if (OnActive != null) {
OnActive(this, new DescriptionEventArgs(PropertyDescription));
}
}
#endregion
}
public class DescriptionEventArgs : EventArgs{
public string Description { get; set;}
public DescriptionEventArgs(string descr){
this.Description = descr;
}
}
}

View File

@@ -0,0 +1,3 @@
print myVar
myVar = 100
print myVar

View File

@@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Aiwaz.Editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Aiwaz.Editor")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Aiwaz.Editor.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Aiwaz.Editor.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Aiwaz.Editor.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@@ -0,0 +1,76 @@
matrix WorldMatrix : WorldMatrix;
matrix ViewMatrix : ViewMatrix;
matrix ProjectionMatrix : ProjectionMatrix;
Texture2D Diffuse : Diffuse;
SamplerState samLinear
{
Filter = ANISOTROPIC;
AddressU = Wrap;
AddressV = Wrap;
};
DepthStencilState RenderWithStencilState
{
StencilEnable = false;
DepthEnable = TRUE;
DepthWriteMask = ALL;
DepthFunc = Equal;
};
RasterizerState EnableCulling
{
CullMode = Back;
};
BlendState AlphaBlending
{
AlphaToCoverageEnable = FALSE;
BlendEnable[0] = TRUE;
SrcBlend = SRC_ALPHA;
DestBlend = INV_SRC_ALPHA;
BlendOp = ADD;
SrcBlendAlpha = SRC_ALPHA;
DestBlendAlpha = INV_SRC_ALPHA;
BlendOpAlpha = ADD;
};
struct VS_OUTPUT
{
float4 Pos : SV_POSITION;
float2 Tex : TEXCOORD0;
};
VS_OUTPUT VS(float4 Pos : POSITION, float2 Tex : TEXCOORD)
{
VS_OUTPUT output = (VS_OUTPUT)0;
output.Pos = mul( Pos, WorldMatrix );
output.Pos = mul( output.Pos, ViewMatrix );
output.Pos = mul( output.Pos, ProjectionMatrix );
output.Tex = Tex;
return output;
}
float4 PS( VS_OUTPUT input) : SV_Target
{
return float4(0.0, 1.0, 1.0, 0.25);
}
//--------------------------------------------------------------------------------------
technique10 Render
{
pass P0
{
SetVertexShader( CompileShader( vs_4_0, VS() ) );
SetGeometryShader( NULL );
SetPixelShader( CompileShader( ps_4_0, PS() ) );
SetDepthStencilState( RenderWithStencilState, 0 );
SetBlendState( AlphaBlending, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF );
SetRasterizerState( EnableCulling );
}
}

View File

@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Aiwaz.Contracts;
using System.Collections.Specialized;
using System.Windows.Controls;
using System.Windows.Media;
using System.Reflection;
using System.IO;
using System.Windows.Media.Imaging;
namespace Aiwaz.Editor.ViewModels
{
public class ResourceViewModel : ViewModelBase
{
private bool creating;
public IResource Resource;
public string DisplayName
{
get
{
return Resource.WellKnownName;
}
set
{
Resource.WellKnownName = value;
}
}
public ImageSource DisplayIcon
{
get
{
var stream = File.OpenRead("Resources/Untitled.png");
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.EndInit();
return bitmap;
}
}
private ObservableCollection<ResourceViewModel> nodes;
public ObservableCollection<ResourceViewModel> Nodes
{
get
{
if (nodes == null)
{
nodes = new ObservableCollection<ResourceViewModel>();
nodes.CollectionChanged += new NotifyCollectionChangedEventHandler(nodes_CollectionChanged);
}
return nodes;
}
set
{
if (nodes != value)
{
nodes = value;
OnPropertyChanged("Nodes");
}
}
}
void nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (creating)
return;
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (ResourceViewModel newItem in e.NewItems)
{
Resource.Children.Insert(e.NewStartingIndex, newItem.Resource);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (ResourceViewModel oldItem in e.OldItems)
{
Resource.Children.Remove(oldItem.Resource);
}
}
OnPropertyChanged("Nodes");
}
public ResourceViewModel(IResource resource)
{
this.Resource = resource;
creating = true;
if (resource.Children != null)
foreach (var child in resource.Children)
{
Nodes.Add(new ResourceViewModel(child));
}
creating = false;
OnPropertyChanged("Nodes");
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Aiwaz.Editor.ViewModels
{
public class ViewModelBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}

View File

@@ -0,0 +1,62 @@
<Window x:Class="Aiwaz.Editor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:cus="clr-namespace:Aiwaz.Editor.Controls"
Title="Window1" Height="550" Width="900">
<Window.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="Gray" Offset="0.0" />
<GradientStop Color="LightGray" Offset="1.0" />
</LinearGradientBrush>
</Window.Background>
<Grid Margin="5">
<Grid.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="LightGray" Offset="0.0" />
<GradientStop Color="White" Offset="1.0" />
</LinearGradientBrush>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="10" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="5*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Grid.RowSpan="3">
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
<RowDefinition Height="10" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<TreeView Grid.Row="0" x:Name="trvNodes" ItemsSource="{Binding Nodes}" AllowDrop="True">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding DisplayIcon}"/>
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
<TreeView.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="LightGray" Offset="0.0" />
<GradientStop Color="White" Offset="1.0" />
</LinearGradientBrush>
</TreeView.Background>
</TreeView>
<GridSplitter Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Stretch" Height="10" />
<cus:PropertyGrid x:Name="Properties" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Grid>
<GridSplitter Grid.Row="0" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Center" Width="10" Grid.RowSpan="3"/>
<cus:AiwazViewControl Grid.Row="0" Grid.Column="2" x:Name="aiwazControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</cus:AiwazViewControl>
<GridSplitter Grid.Row="1" Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Stretch" Height="10" />
<Slider Grid.Row="2" Grid.Column="2" />
</Grid>
</Window>

View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using SlimDX;
using SlimDX.Windows;
using Aiwaz.Core;
using Aiwaz.Resources;
using Aiwaz.Editor.ViewModels;
using Aiwaz.Resources.Prefab;
using Aiwaz.Contracts;
using Aiwaz.Editor.Controls;
namespace Aiwaz.Editor
{
public partial class MainWindow : Window
{
public ResourceViewModel ResourceViewModel;
public MainWindow()
{
InitializeComponent();
aiwazControl.SwapChain.ClearColor = new Color4(0.0f, 0.0f, 1.0f);
var model = new BluModel(new BluModelParams() { FileName = "Data/ChamferBox.blu" });
model.RootTransformation.LocalScale = new SlimDX.Vector3(0.1f, 0.1f, 0.1f);
model.RootTransformation.LocalPosition = new SlimDX.Vector3(1.0f, 0.0f, 2.0f);
var camera = new PerspectiveCamera(new PerspectiveCameraParams());
var normalMapping = new Shader(new ShaderParams() { FileName = "Data/NormalOutput.fx", TechniqueName = "NormalMapping" });
var wallTexture = new Texture(new FileTextureParams() { FileName = "Data/Wall.jpg" });
var wallNormalTexture = new Texture(new FileTextureParams() { FileName = "Data/WallNormal.jpg" });
wallNormalTexture.BindingName = "Normal";
var roomCube = new Cube(new CubeParams() { Width = 10.0f, Height = 10.0f, Depth = 10.0f, IsInverted = true });
roomCube.GeometryBuffer.IsPickable = true;
var roomCubeTransformation = new Transformation(new DefaultTransformationBindings());
roomCubeTransformation.LocalPosition = new SlimDX.Vector3(0.0f, 0.0f, 2.0f);
var lightPosition = new ReferenceT<SlimDX.Vector3>(new SlimDX.Vector3(0.0f, 1.0f, 0.0f));
var lightColor = new ReferenceT<SlimDX.Vector4>(new SlimDX.Vector4(2.0f, 2.0f, 1.0f, 1.0f));
var lightParameters = new ShaderParameterSet();
lightParameters.IsPreconditionForFollowingShaders = true;
lightParameters.SetParameter("LightPosition", lightPosition, ParameterBindType.BindBySemantic);
lightParameters.SetParameter("LightColor", lightColor, ParameterBindType.BindBySemantic);
aiwazControl.RootNode.Children.Add(camera);
aiwazControl.RootNode.Children.Add(lightParameters);
aiwazControl.RootNode.Children.Add(roomCubeTransformation);
aiwazControl.RootNode.Children.Add(normalMapping);
aiwazControl.RootNode.Children.Add(wallTexture);
aiwazControl.RootNode.Children.Add(wallNormalTexture);
aiwazControl.RootNode.Children.Add(roomCube);
aiwazControl.RootNode.Children.Add(model);
ResourceViewModel = new ResourceViewModel(aiwazControl.RootNode);
trvNodes.DataContext = ResourceViewModel;
trvNodes.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(trvNodes_SelectedItemChanged);
aiwazControl.PickableResources = PickableResourcesDataSource.CreateFromResource(aiwazControl.RootNode);
aiwazControl.SelectedResourceChanged += new Aiwaz.Editor.Controls.AiwazViewControl.SelectedResourceChangedDelegate(aiwazControl_SelectedResourceChanged);
}
void aiwazControl_SelectedResourceChanged(object sender, Aiwaz.Editor.Controls.PickableResourceInfo newSelectedResourceInfo)
{
Properties.SelectedObject = newSelectedResourceInfo == null ? null : newSelectedResourceInfo.Resource;
}
void trvNodes_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
Properties.SelectedObject = ((ResourceViewModel)(e.NewValue)).Resource;
}
}
}

View File

@@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Aiwaz.Resources</RootNamespace>
<AssemblyName>Aiwaz.Resources</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="SlimDX, Version=2.0.8.42, Culture=neutral, PublicKeyToken=b1b0c32fd1ffe4f9, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Extern\SlimDX\x86\SlimDX.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Attributes\CreationParameters.cs" />
<Compile Include="Attributes\ReadOnly.cs" />
<Compile Include="Attributes\RequiredParameter.cs" />
<Compile Include="BluImporter\BluImporter.cs" />
<Compile Include="Bone.cs" />
<Compile Include="Camera.cs" />
<Compile Include="Commands\CommandBuffer.cs" />
<Compile Include="Commands\CommandUser.cs" />
<Compile Include="CreationParams.cs" />
<Compile Include="GeometryBuffer.cs" />
<Compile Include="PickHull.cs" />
<Compile Include="Prefab\Quad.cs" />
<Compile Include="Prefab\Cube.cs" />
<Compile Include="Prefab\PingPongBuffer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RenderCommandNode.cs" />
<Compile Include="RenderTarget.cs" />
<Compile Include="RenderTargetTexture.cs" />
<Compile Include="Resource.cs" />
<Compile Include="Shader.cs" />
<Compile Include="ShaderParameterSet.cs" />
<Compile Include="SwapChain.cs" />
<Compile Include="Texture.cs" />
<Compile Include="Transformation.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Aiwaz.Common\Aiwaz.Common.csproj">
<Project>{0F7D7168-08C1-45AE-AAE3-80506939D7E6}</Project>
<Name>Aiwaz.Common</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Contracts\Aiwaz.Contracts.csproj">
<Project>{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}</Project>
<Name>Aiwaz.Contracts</Name>
</ProjectReference>
<ProjectReference Include="..\Aiwaz.Core\Aiwaz.Core.csproj">
<Project>{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}</Project>
<Name>Aiwaz.Core</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Resources.Attributes
{
public class CreationParametersAttribute : System.Attribute
{
public string Description { get; protected set; }
public CreationParametersAttribute(string description)
{
this.Description = description;
}
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Resources.Attributes
{
public class ReadOnlyAttribute : System.Attribute
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Resources.Attributes
{
public class RequiredParameterAttribute : System.Attribute
{
}
}

View File

@@ -0,0 +1,373 @@
using System;
using System.IO;
using System.Linq;
using Aiwaz.Common;
using Aiwaz.Contracts;
using Aiwaz.Core;
using System.Collections.Generic;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
using SlimDX;
namespace Aiwaz.Resources
{
public class FileInegrityBroken : Exception
{
public FileInegrityBroken() : base() { }
public FileInegrityBroken(string message) : base(message) { }
}
[CreationParameters("Blu Model from file")]
public class BluModelParams : ICreationParams
{
public string FileName;
public BluModelParams()
{
}
}
[AiwazResource("Blu Model", "A model loaded from a .blu file")]
public class BluModel : Resource
{
private enum BluSectionType
{
Mesh = 0,
Material = 1,
Bone = 2,
Animation = 3,
LastKnownType = 3
};
private class BluImportResult
{
public struct BluImportedGeometryBuffer
{
public IGeometryBuffer GeometryBuffer;
public string MaterialName;
};
public string FileName;
public Dictionary<string, BluImportedGeometryBuffer> GeometryBuffers = new Dictionary<string, BluImportedGeometryBuffer>();
public Dictionary<string, IShaderParameterSet> ShaderParamererSets = new Dictionary<string, IShaderParameterSet>();
public Dictionary<string, IShader> Shaders = new Dictionary<string, IShader>();
//Dictionary<string, BluImportedBone> Bones;
//Dictionary<string, ITransformationAnimation> Animations;
};
public string FileName { get; protected set; }
public RenderCommandNode RootNode { get; protected set; }
public Transformation RootTransformation { get; protected set; }
//IBoneController BoneController;
public BluModel(BluModelParams parameters)
{
creationParams = parameters;
var result = new BluImportResult();
this.FileName = result.FileName = parameters.FileName;
using (var stream = Engine.FileSystem.Open(parameters.FileName))
using (var reader = new BinaryReader(stream))
{
var magic = reader.ReadNullTerminatedString();
if (magic != "BLUF")
throw new FileInegrityBroken();
var fileVersion = reader.ReadInt32();
// sections
while (stream.Position < stream.Length)
{
var objectType = (BluSectionType)reader.ReadInt32();
if (objectType > BluSectionType.LastKnownType)
throw new FileInegrityBroken("Unknown object section detected.");
var objectName = reader.ReadNullTerminatedString();
if (string.IsNullOrEmpty(objectName))
throw new FileInegrityBroken("Object name not set.");
// content
switch (objectType)
{
case BluSectionType.Mesh:
this.ImportMesh(reader, objectName, result);
break;
case BluSectionType.Material:
this.ImportMaterial(reader, objectName, result);
break;
case BluSectionType.Bone:
this.ImportBone(reader, objectName, result);
break;
case BluSectionType.Animation:
this.ImportAnimation(reader, objectName, result);
break;
}
}
}
// build bone hierarchy
//std::map<string8, BluImportedBone>::iterator lk_BonesIter = lr_Result.m_Bones.begin();
//for (; lk_BonesIter != lr_Result.m_Bones.end(); ++lk_BonesIter)
//{
// BluImportedBone lr_Bone = lk_BonesIter->second;
// std::map<string8, BluImportedBone>::iterator lk_Found = lr_Result.m_Bones.find(lr_Bone.m_ParentName);
// if (lk_Found != lr_Result.m_Bones.end())
// lr_Bone.m_Bone->set_Parent(lk_Found->second.m_Bone);
//}
// add bone animations to bones
//std::map<string8, ITransformationAnimation*>::iterator lk_AnimIter = lr_Result.m_Animations.begin();
//for (; lk_AnimIter != lr_Result.m_Animations.end(); ++lk_AnimIter)
//{
// std::map<string8, BluImportedBone>::iterator lk_Found = lr_Result.m_Bones.find(lk_AnimIter->first);
// if (lk_Found != lr_Result.m_Bones.end())
// {
// lk_Found->second.m_Bone->set_TransformationAnimation(lk_AnimIter->second);
// }
//}
// collapse bone map to super parent bones only
//lk_BonesIter = lr_Result.m_Bones.begin();
//for (; lk_BonesIter != lr_Result.m_Bones.end();)
// if (!lk_BonesIter->second.m_ParentName.empty())
// lk_BonesIter = lr_Result.m_Bones.erase(lk_BonesIter);
// else
// {
// // create the boneindexlist structure while we are here
// lk_BonesIter->second.m_Bone->get_BoneIndexList();
// ++lk_BonesIter;
// }
//if (lr_Result.m_Bones.size() > 1)
// throw _T("BLUImporter: Only one bone root allowed!");
// Create a default BoneController
//if (!lr_Result.m_Bones.empty())
//{
// lr_Result.m_BoneController = &m_Engine.get_ResourceFactory().CreateOrFindBoneController();
// lr_Result.m_BoneController->Initialize(*lr_Result.m_Bones.begin()->second.m_Bone);
// float lf_MaxDuration = 0.0f;
// for (lk_AnimIter = lr_Result.m_Animations.begin(); lk_AnimIter != lr_Result.m_Animations.end(); ++lk_AnimIter)
// lf_MaxDuration = lf_MaxDuration < lk_AnimIter->second->get_Duration() ? lk_AnimIter->second->get_Duration() : lf_MaxDuration;
// lr_Result.m_BoneController->RegisterSequence(L"all", 0.0f, lf_MaxDuration, true);
//}
this.RootNode = new RenderCommandNode();
this.RootTransformation = new Transformation(new DefaultTransformationBindings());
//if (!m_Bones.empty())
// m_Bones.begin()->second.m_Bone->GetTransformationAtTime(0.0f, D3DXMATRIX());
//if (m_BoneController != NULL)
//{
// AddToNode(rootNode, m_BoneController);
// m_BoneController->PlaySequence(L"all");
//}
// Create sub nodes
foreach (var geoBufferInfo in result.GeometryBuffers)
{
var meshInfo = geoBufferInfo.Value;
var shader = result.Shaders[meshInfo.MaterialName];
var shaderParameter = result.ShaderParamererSets[meshInfo.MaterialName];
if (shader != null && shaderParameter != null)
{
var subNode = new RenderCommandNode();
subNode.Children.Add((CommandUser)shader);
subNode.Children.Add((CommandUser)this.RootTransformation);
subNode.Children.Add((CommandUser)shaderParameter);
subNode.Children.Add((CommandUser)meshInfo.GeometryBuffer);
this.RootNode.Children.Add(subNode);
}
}
}
private void ImportMesh(BinaryReader reader, string objectName, BluImportResult result)
{
var materialName = reader.ReadNullTerminatedString();
var vertexCount = reader.ReadInt32();
var vertexElementCount = reader.ReadInt32();
var vertexElements = new VertexElement[vertexElementCount];
for (int i = 0; i < vertexElementCount; ++i)
{
int vertexElementOldId = reader.ReadInt32();
switch (vertexElementOldId)
{
case 1: vertexElements[i] = new VertexElement(VertexElement.Format.Position); break;
case 3: vertexElements[i] = new VertexElement(VertexElement.Format.Normal); break;
case 8: vertexElements[i] = new VertexElement(VertexElement.Format.Texture2D); break;
case 11: vertexElements[i] = new VertexElement(VertexElement.Format.Tangent); break;
case 13: vertexElements[i] = new VertexElement(VertexElement.Format.BlendIndices); break;
case 14: vertexElements[i] = new VertexElement(VertexElement.Format.BlendWeight); break;
}
}
var vertexData = reader.ReadBytes(vertexCount * vertexElements.Sum(v => v.Size));
var indexCount = reader.ReadInt32();
var indexRawData = reader.ReadBytes(sizeof(Int32) * indexCount);
int[] indexData = new int[indexCount];
for (int i = 0; i < indexCount; ++i)
indexData[i] = (int)BitConverter.ToInt32(indexRawData, i * sizeof(uint));
string uniqueName = result.FileName + "." + objectName;
var vBuffer = new DataStream(vertexData, true, true);
var iBuffer = new DataStream(indexData, true, true);
var geoBuffer = new GeometryBuffer(
indexCount,
iBuffer,
vertexCount,
vBuffer,
vertexElements,
false);
geoBuffer.IsPickable = true;
//geoBuffer.ConvertToAdjacency();
var mesh = new BluImportResult.BluImportedGeometryBuffer();
mesh.GeometryBuffer = geoBuffer;
mesh.MaterialName = result.FileName + "." + materialName;
result.GeometryBuffers.Add(uniqueName, mesh);
}
private string GetPath(string orignalPath)
{
if (string.IsNullOrEmpty(orignalPath))
return orignalPath;
return Path.Combine(Path.GetDirectoryName(this.FileName), Path.GetFileName(orignalPath));
}
private void ImportMaterial(BinaryReader reader, string objectName, BluImportResult result)
{
string diffuseTexture = this.GetPath(reader.ReadNullTerminatedString());
string specularTexture = this.GetPath(reader.ReadNullTerminatedString());
string normalTexture = this.GetPath(reader.ReadNullTerminatedString());
string glowTexture = this.GetPath(reader.ReadNullTerminatedString());
string reflectionTexture = this.GetPath(reader.ReadNullTerminatedString());
var ambientColor = new SlimDX.Vector4();
ambientColor.X = reader.ReadSingle() / 255.0f;
ambientColor.Y = reader.ReadSingle() / 255.0f;
ambientColor.Z = reader.ReadSingle() / 255.0f;
ambientColor.W = reader.ReadSingle() / 255.0f;
var diffuseColor = new SlimDX.Vector4();
diffuseColor.X = reader.ReadSingle() / 255.0f;
diffuseColor.Y = reader.ReadSingle() / 255.0f;
diffuseColor.Z = reader.ReadSingle() / 255.0f;
diffuseColor.W = reader.ReadSingle() / 255.0f;
var specularColor = new SlimDX.Vector4();
specularColor.X = reader.ReadSingle() / 255.0f;
specularColor.Y = reader.ReadSingle() / 255.0f;
specularColor.Z = reader.ReadSingle() / 255.0f;
specularColor.W = reader.ReadSingle() / 255.0f;
var emissiveColor = new SlimDX.Vector4();
emissiveColor.X = reader.ReadSingle() / 255.0f;
emissiveColor.Y = reader.ReadSingle() / 255.0f;
emissiveColor.Z = reader.ReadSingle() / 255.0f;
emissiveColor.W = reader.ReadSingle() / 255.0f;
var specularlevel = reader.ReadSingle();
var glossiness = reader.ReadSingle();
string uniqueName = result.FileName + "." + objectName;
var material = new ShaderParameterSet();
material.SetParameter("AmbientColor", ambientColor, ParameterBindType.BindBySemantic);
material.SetParameter("DiffuseColor", diffuseColor, ParameterBindType.BindBySemantic);
material.SetParameter("SpecularColor", specularColor * glossiness, ParameterBindType.BindBySemantic);
material.SetParameter("EmissiveColor", emissiveColor, ParameterBindType.BindBySemantic);
material.SetParameter("Shininess", specularlevel, ParameterBindType.BindBySemantic);
var modelShader = new Shader(new ShaderParams() { FileName = "Data/NormalOutput.fx", TechniqueName = "Render" });
result.Shaders.Add(uniqueName, modelShader);
if (!string.IsNullOrEmpty(diffuseTexture))
{
Texture tex = Engine.FindNamedObject(diffuseTexture) as Texture;
if (tex == null)
{
tex = new Texture(new FileTextureParams() { FileName = diffuseTexture });
tex.WellKnownName = diffuseTexture;
}
material.SetParameter("Diffuse", tex, ParameterBindType.BindBySemantic);
}
if (!string.IsNullOrEmpty(specularTexture))
{
Texture tex = Engine.FindNamedObject(specularTexture) as Texture;
if (tex == null)
{
tex = new Texture(new FileTextureParams() { FileName = specularTexture });
tex.WellKnownName = specularTexture;
}
material.SetParameter("Specular", tex, ParameterBindType.BindBySemantic);
}
if (!string.IsNullOrEmpty(normalTexture))
{
Texture tex = Engine.FindNamedObject(normalTexture) as Texture;
if (tex == null)
{
tex = new Texture(new FileTextureParams() { FileName = normalTexture });
tex.WellKnownName = normalTexture;
}
material.SetParameter("Normal", tex, ParameterBindType.BindBySemantic);
}
if (!string.IsNullOrEmpty(glowTexture))
{
Texture tex = Engine.FindNamedObject(glowTexture) as Texture;
if (tex == null)
{
tex = new Texture(new FileTextureParams() { FileName = glowTexture });
tex.WellKnownName = glowTexture;
}
material.SetParameter("Glow", tex, ParameterBindType.BindBySemantic);
}
if (!string.IsNullOrEmpty(reflectionTexture))
{
Texture tex = Engine.FindNamedObject(reflectionTexture) as Texture;
if (tex == null)
{
tex = new Texture(new FileTextureParams() { FileName = reflectionTexture });
tex.WellKnownName = reflectionTexture;
}
material.SetParameter("Reflection", tex, ParameterBindType.BindBySemantic);
}
result.ShaderParamererSets.Add(uniqueName, material);
}
private void ImportBone(BinaryReader reader, string objectName, BluImportResult result)
{
throw new NotImplementedException();
}
private void ImportAnimation(BinaryReader reader, string objectName, BluImportResult result)
{
throw new NotImplementedException();
}
private ICreationParams creationParams;
public override ICreationParams CreationParams
{
get { return creationParams; }
}
private ObservableCollection<IResource> children;
[ReadOnly]
public override ObservableCollection<IResource> Children
{
get
{
if (children == null)
{
children = new ObservableCollection<IResource>();
children.Add(RootNode);
}
return children;
}
}
};
}

View File

@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
namespace Aiwaz.Resources
{
public class Bone : IBone
{
#region IBone Members
private SlimDX.Matrix transformation;
private SlimDX.Matrix invPoseTransformation;
private float lastAnimationTime = float.MinValue;
private IBone parent;
private SlimDX.Matrix[] matrixArray = new SlimDX.Matrix[0];
private ITransformationAnimation transformationAnimation;
private Dictionary<int, IBone> boneIndexList = new Dictionary<int, IBone>();
public Bone(string name, int index, SlimDX.Vector3 poseTranslation, SlimDX.Vector3 poseScale, SlimDX.Quaternion poseRotation)
{
PoseTransformation = SlimDX.Matrix.Transformation(SlimDX.Vector3.Zero, SlimDX.Quaternion.Identity, poseScale, SlimDX.Vector3.Zero, poseRotation, poseTranslation);
invPoseTransformation = this.PoseTransformation;
invPoseTransformation.Invert();
this.Index = index;
this.ChildBones = new List<IBone>();
}
public SlimDX.Matrix GetTransformationAtTime(float time, SlimDX.Matrix rootTransformationMatrix)
{
if (this.TransformationAnimation != null)
{
if (time != lastAnimationTime)
{
if (this.Parent != null)
{
transformation = (this.TransformationAnimation.GetTransformationAtTime(time) * invPoseTransformation) * this.Parent.GetTransformationAtTime(time, rootTransformationMatrix);
transformation = invPoseTransformation * this.TransformationAnimation.GetTransformationAtTime(time);
//m_Transformation = m_Transformation * ( * m_InvPoseTransformation);
}
else
transformation = this.TransformationAnimation.GetTransformationAtTime(time) * invPoseTransformation;
}
}
return transformation;
}
public Dictionary<int, IBone> BoneIndexList
{
get
{
if (parent != null)
return parent.BoneIndexList;
if (boneIndexList.Count == 0)
this.FillBoneIndexList(this);
return boneIndexList;
}
}
public List<IBone> ChildBones { get; protected set; }
public int Index { get; protected set; }
public SlimDX.Matrix[] MatrixArray
{
get
{
if (matrixArray == null)
matrixArray = new SlimDX.Matrix[this.BoneIndexList.Count];
return matrixArray;
}
}
public string Name { get; protected set; }
public SlimDX.Matrix PoseTransformation { get; protected set; }
public IBone Parent
{
get { return parent; }
set
{
if (parent != null)
parent.ChildBones.Remove(this);
parent = value;
if (parent != null)
parent.ChildBones.Add(this);
}
}
public ITransformationAnimation TransformationAnimation
{
get { return transformationAnimation; }
set
{
transformationAnimation = value;
lastAnimationTime = float.MinValue;
transformation = new SlimDX.Matrix();
}
}
internal void FillBoneIndexList(IBone currentBone)
{
boneIndexList[currentBone.Index] = currentBone;
foreach (var childBone in currentBone.ChildBones)
this.FillBoneIndexList(childBone);
}
#endregion
}
}

View File

@@ -0,0 +1,277 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
using Aiwaz.Common.Animations;
using Aiwaz.Resources.Attributes;
namespace Aiwaz.Resources
{
[CreationParameters("Standard orthographic camera")]
public class OrthographicCameraParams
{
public float width;
public float height;
public OrthographicCameraParams()
{
width = 512;
height = 512;
}
}
[AiwazResource("Orthographic Camera", "An orthographic camera for orthogonal views.")]
public class OrthographicCamera : BaseCamera, IOrthographicCamera
{
#region IOrthographicCamera Members
private float width;
private float height;
private OrthographicCamera()
: base()
{
}
public OrthographicCamera(OrthographicCameraParams parameters)
: this()
{
Console.WriteLine(string.Format("Creating OrthographicCamera ({0}x{1})..", parameters.width, parameters.height));
this.Width = parameters.width;
this.Height = parameters.height;
}
public float Width
{
get { return width; }
set
{
width = value;
WantsUpdate = true;
}
}
public float Height
{
get { return height; }
set
{
height = value;
WantsUpdate = true;
}
}
public override void Update(bool forceUpdate)
{
base.Update(forceUpdate);
this.ProjectionMatrix = SlimDX.Matrix.OrthoLH(width, height, this.NearClip, this.FarClip);
this.ViewMatrix = SlimDX.Matrix.LookAtLH(this.WorldPosition, this.WorldPosition + this.WorldDirection, this.WorldUpDirection);
// generate view frustum
var viewProj = this.ViewMatrix * this.ProjectionMatrix;
// Left plane
this.ViewFrustum.Plane[0] = new SlimDX.Plane(viewProj.M14 + viewProj.M11,
viewProj.M24 + viewProj.M21,
viewProj.M34 + viewProj.M31,
viewProj.M44 + viewProj.M41);
// Right plane
this.ViewFrustum.Plane[1] = new SlimDX.Plane(viewProj.M14 - viewProj.M11,
viewProj.M24 - viewProj.M21,
viewProj.M34 - viewProj.M31,
viewProj.M44 - viewProj.M41);
// Top plane
this.ViewFrustum.Plane[2] = new SlimDX.Plane(viewProj.M14 - viewProj.M12,
viewProj.M24 - viewProj.M22,
viewProj.M34 - viewProj.M32,
viewProj.M44 - viewProj.M42);
// Bottom plane
this.ViewFrustum.Plane[3] = new SlimDX.Plane(viewProj.M14 + viewProj.M12,
viewProj.M24 + viewProj.M22,
viewProj.M34 + viewProj.M32,
viewProj.M44 + viewProj.M42);
// Near plane
this.ViewFrustum.Plane[4] = new SlimDX.Plane(viewProj.M13,
viewProj.M23,
viewProj.M33,
viewProj.M43);
// Far plane
this.ViewFrustum.Plane[5] = new SlimDX.Plane(viewProj.M14 - viewProj.M13,
viewProj.M24 - viewProj.M23,
viewProj.M34 - viewProj.M33,
viewProj.M44 - viewProj.M43);
}
#endregion
}
[CreationParameters("Standard orthographic camera")]
public class PerspectiveCameraParams
{
public float fov;
public float aspectRatio;
public PerspectiveCameraParams()
{
fov = 90.0f;
aspectRatio = 1.0f;
}
}
[AiwazResource("Perspective Camera", "An perspective camera for perspective correct views.")]
public class PerspectiveCamera : BaseCamera, IPerspectiveCamera
{
#region IPerspectiveCamera Members
private float fov;
private float aspectRatio;
private PerspectiveCamera()
: base()
{
}
public PerspectiveCamera(PerspectiveCameraParams parameters)
: this()
{
Console.WriteLine(string.Format("Creating PerspectiveCamera (Fov: {0} AspectRatio: {1})..", parameters.fov, parameters.aspectRatio));
this.Fov = parameters.fov;
this.AspectRatio = parameters.aspectRatio;
}
[Animateable]
public float Fov
{
get { return fov; }
set
{
fov = value;
WantsUpdate = true;
}
}
[Animateable]
public float AspectRatio
{
get { return aspectRatio; }
set
{
aspectRatio = value;
WantsUpdate = true;
}
}
public override void Update(bool forceUpdate)
{
base.Update(forceUpdate);
this.ProjectionMatrix = SlimDX.Matrix.PerspectiveFovLH((float)((Math.PI / 180) * fov), this.AspectRatio, this.NearClip, this.FarClip);
this.ViewMatrix = SlimDX.Matrix.LookAtLH(this.WorldPosition, this.WorldPosition + this.WorldDirection, this.WorldUpDirection);
// generate view frustum
var viewProj = this.ViewMatrix * this.ProjectionMatrix;
// Left plane
this.ViewFrustum.Plane[0] = new SlimDX.Plane(
viewProj.M14 + viewProj.M11,
viewProj.M24 + viewProj.M21,
viewProj.M34 + viewProj.M31,
viewProj.M44 + viewProj.M41);
// Right plane
this.ViewFrustum.Plane[1] = new SlimDX.Plane(viewProj.M14 - viewProj.M11,
viewProj.M24 - viewProj.M21,
viewProj.M34 - viewProj.M31,
viewProj.M44 - viewProj.M41);
// Top plane
this.ViewFrustum.Plane[2] = new SlimDX.Plane(viewProj.M14 - viewProj.M12,
viewProj.M24 - viewProj.M22,
viewProj.M34 - viewProj.M32,
viewProj.M44 - viewProj.M42);
// Bottom plane
this.ViewFrustum.Plane[3] = new SlimDX.Plane(viewProj.M14 + viewProj.M12,
viewProj.M24 + viewProj.M22,
viewProj.M34 + viewProj.M32,
viewProj.M44 + viewProj.M42);
// Near plane
this.ViewFrustum.Plane[4] = new SlimDX.Plane(viewProj.M13,
viewProj.M23,
viewProj.M33,
viewProj.M43);
// Far plane
this.ViewFrustum.Plane[5] = new SlimDX.Plane(viewProj.M14 - viewProj.M13,
viewProj.M24 - viewProj.M23,
viewProj.M34 - viewProj.M33,
viewProj.M44 - viewProj.M43);
}
#endregion
}
public abstract class BaseCamera : Transformation, ICamera
{
#region ICamera Members
private float nearClip = 1.0f;
private float farClip = 1000.0f;
Reference projectionMatrix = new Reference(new SlimDX.Matrix());
Reference viewMatrix = new Reference(new SlimDX.Matrix());
public SlimDX.Matrix ProjectionMatrix { get { return (SlimDX.Matrix)projectionMatrix.RawValue; } protected set { projectionMatrix.RawValue = value; } }
public SlimDX.Matrix ViewMatrix { get { return (SlimDX.Matrix)viewMatrix.RawValue; } protected set { viewMatrix.RawValue = value; } }
public BaseCamera()
: base(new CameraTransformationBindings())
{
this.ViewFrustum = new ViewFrustum();
this.IsPreconditionForFollowingShaders = true;
this.RecreateAllShaderParameters();
}
public float FarClip
{
get { return farClip; }
set
{
farClip = value;
WantsUpdate = true;
}
}
public float NearClip
{
get { return nearClip; }
set
{
nearClip = value;
WantsUpdate = true;
}
}
public ViewFrustum ViewFrustum { get; protected set; }
protected override void RecreateAllShaderParameters()
{
this.SetParameter("ViewMatrix", viewMatrix, ParameterBindType.BindBySemantic);
this.SetParameter("ProjectionMatrix", projectionMatrix, ParameterBindType.BindBySemantic);
base.RecreateAllShaderParameters();
}
#endregion
}
}

View File

@@ -0,0 +1,342 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
namespace Aiwaz.Resources
{
public class CommandBuffer
{
private class CommandChainInternal
{
public int Priority = 0;
public List<Command> Chain;
public void UpdatePriority()
{
Priority = -1;
foreach (var command in Chain)
if ((command.Flags & CommandFlags.SubChainStart) != CommandFlags.None)
{
Priority = command.SubPriority;
break;
}
}
public class CommandComparsion : IComparer<Command>
{
public int Compare(Command x, Command y)
{
return x.Priority.CompareTo(y.Priority);
}
}
public class CommandChainComparsion : IComparer<CommandChainInternal>
{
public int Compare(CommandChainInternal x, CommandChainInternal y)
{
if (x.Priority == y.Priority)
return x.Chain.Count.CompareTo(y.Chain.Count);
return x.Priority.CompareTo(y.Priority);
}
}
}
private CommandBuffer optimizedCommandBuffer = null;
private List<CommandChainInternal> gatheredCommandChains = new List<CommandChainInternal>();
public List<Command> BufferedCommands { get; protected set; }
public List<CommandBuffer> ChildCommandBuffers { get; protected set; }
public CommandBuffer ParentBuffer { get; set; }
#region ICommandBuffer Members
public CommandBuffer()
{
BufferedCommands = new List<Command>();
ChildCommandBuffers = new List<CommandBuffer>();
}
public void Clear()
{
BufferedCommands.Clear();
ChildCommandBuffers.Clear();
gatheredCommandChains.Clear();
if (optimizedCommandBuffer != null)
optimizedCommandBuffer.Clear();
}
public void Perform(bool useOptimizedList)
{
if (!useOptimizedList)
{
int subChainStartCommandIndex = -1;
for (int i = 0; i < BufferedCommands.Count;)
{
var command = BufferedCommands[i];
if ((command.Flags & CommandFlags.SubChainStart) != CommandFlags.None)
subChainStartCommandIndex = i;
switch (command.Owner.ExecuteCommand(command.Type, this, i))
{
case CommandExecuteResult.None:
if ((command.Flags & CommandFlags.SubChainEnd) != CommandFlags.None)
subChainStartCommandIndex = -1;
i++;
break;
case CommandExecuteResult.RetrySubChain:
if (subChainStartCommandIndex == -1)
throw new ActionFailedException("Failed to restart sub command chain.");
else
i = subChainStartCommandIndex;
break;
case CommandExecuteResult.RetrySubChainSkipHead:
if (subChainStartCommandIndex == -1)
throw new ActionFailedException("Failed to restart headless sub command chain.");
else
i = subChainStartCommandIndex + 1;
break;
}
}
}
else
{
if (optimizedCommandBuffer != null)
optimizedCommandBuffer.Perform(false);
}
}
public void Optimize()
{
if (optimizedCommandBuffer == null)
optimizedCommandBuffer = new CommandBuffer();
optimizedCommandBuffer.Clear();
List<Command> tempChain = new List<Command>();
this.SearchDrawableCommandChain(this, ref tempChain);
this.FlushGatheredCommandChains();
}
public void AddChildCommandBuffer(CommandBuffer commandBuffer)
{
ChildCommandBuffers.Add(commandBuffer);
commandBuffer.ParentBuffer = this;
}
public void RemoveChildCommandBuffer(CommandBuffer commandBuffer)
{
if (ChildCommandBuffers.Remove(commandBuffer))
commandBuffer.ParentBuffer = null;
}
private void SearchDrawableCommandChain(CommandBuffer incomingBuffer, ref List<Command> currentChain)
{
for (int i = 0; i < incomingBuffer.BufferedCommands.Count;)
{
var currentCommand = incomingBuffer.BufferedCommands[i];
var commandFlags = currentCommand.Flags;
// A command is start AND end of a command chain, this indicates that a serious state change will come,
// so we will need to flush the current command chains.
if ((commandFlags & CommandFlags.FlushChain) != 0)
{
this.FlushGatheredCommandChains();
currentChain.Clear();
}
// Old way commented out due problems with transformations before shaders
// A command was found which does not belong to a build up current chain (due no chain is building herself up..)
// so we drop it, we simply do not care about some run away
/*if (currentChain.empty()
&& (commandFlags & CommandFlags.StartChain) == 0
&& (commandFlags & CommandFlags.EndChain) == 0)
{
++i;
continue;
}*/
// New way is to search the list for a start chain command, then we put this command after the start chain command
if (currentChain.Count == 0
&& (commandFlags & CommandFlags.StartChain) == 0
&& (commandFlags & CommandFlags.EndChain) == 0)
{
var foundPlace = false;
var commands = incomingBuffer.BufferedCommands;
for (int k = i + 1; k < commands.Count; ++k)
if ((commands[k].Flags & CommandFlags.StartChain) != CommandFlags.None)
{
commands.Insert(k + 1, currentCommand);
commands.RemoveAt(i);
foundPlace = true;
break;
}
if (!foundPlace)
++i;
continue;
}
// A new command chain should be initialized, clear our current temp chain and add this command into it.
// All old commands remaining in the chain are already used or where completely useless (SetShader . SetParameter . NextPass).
else if ((commandFlags & CommandFlags.StartChain) != 0 && currentChain.Count > 0)
{
currentChain.Clear();
currentChain.Add(currentCommand);
++i;
}
// We should end our chain, now we need to optimize this chain and add this into the gathered chain list,
// at the next flush command we will put this list into our optimized list, with some more optimizations.
else if ((commandFlags & CommandFlags.EndChain) != 0)
{
// We have a filled chain (at least 1 operation following by this operation)
if (currentChain.Count > 0)
{
var commandChainInternal = new CommandChainInternal();
commandChainInternal.Chain = new List<Command>(currentChain);
commandChainInternal.Chain.Add(currentCommand);
commandChainInternal.Chain.Sort(new CommandChainInternal.CommandComparsion());
//m_OptimizedCommandBuffer.get_BufferedCommands().insert(m_OptimizedCommandBuffer.get_BufferedCommands().end(), chain.begin(), chain.end());
gatheredCommandChains.Add(commandChainInternal);
// Search for the SubChainEnd flagged command , this should be found right after the SubChainStart flagged commands
// both commands will mark the beginning of our chain . delete everything behind this command will ensure
// that we will use a fresh new command chain, only filled with what we need (StartSubChain . EndSubChain)
for (int k = 0; k < currentChain.Count; ++k)
if ((currentChain[k].Flags & CommandFlags.SubChainEnd) != CommandFlags.None)
{
currentChain.RemoveRange(k + 1, currentChain.Count - (k + 1));
break;
}
}
// Our chain was empty, this means a solo command was found, put it into our optimized list and continue,
// there is not much to do here.
else
{
optimizedCommandBuffer.BufferedCommands.Add(currentCommand);
}
++i;
}
// No start and no end of the command chain, just put this command into our chain,
// commands of this type are for example, SetVertexBuffer, SetIndexBuffer, SetTransformation,...
else
{
currentChain.Add(currentCommand);
++i;
}
}
// We may have child buffers, continue our search there.
foreach (var buffer in incomingBuffer.ChildCommandBuffers)
{
var newCurrentChain = new List<Command>(currentChain);
this.SearchDrawableCommandChain(buffer, ref currentChain);
currentChain = newCurrentChain;
}
}
void FlushGatheredCommandChains()
{
var flushedCommands = new List<Command>();
gatheredCommandChains.ForEach(item => item.UpdatePriority());
while (gatheredCommandChains.Count > 0)
{
gatheredCommandChains.Sort(new CommandChainInternal.CommandChainComparsion());
int currentPriority = 0;
List<int> checkables = new List<int>();
for (int i = 0; i < gatheredCommandChains.Count;)
{
if (gatheredCommandChains[i].Chain.Count == 0)
gatheredCommandChains.RemoveAt(i);
else if (checkables.Count == 0 || currentPriority == gatheredCommandChains[i].Priority)
{
currentPriority = gatheredCommandChains[i].Priority;
checkables.Add(i);
++i;
}
else
break;
}
if (checkables.Count == 1)
{
int thisIndex = checkables.First();
flushedCommands.AddRange(gatheredCommandChains[thisIndex].Chain);
gatheredCommandChains.RemoveAt(thisIndex);
if (gatheredCommandChains.Count == 0)
break;
}
List<Command> optimizedCommandChain = new List<Command>();
Command lastCommand = null;
while (checkables.Count > 1)
{
if (checkables.Count > 0 && checkables.First() != 0)
break;
for (int i = 0; i < checkables.Count;)
{
int thisIndex = checkables[i];
var currentCommandChainInternal = gatheredCommandChains[thisIndex];
var thisCommand = currentCommandChainInternal.Chain.First();
if (i == 0 || (thisCommand.CommandInfo.RawValue == lastCommand.CommandInfo.RawValue && thisCommand.Owner == lastCommand.Owner))
{
// we found a similarity (or the first element), put this into our optimized temp list
lastCommand = thisCommand;
if (i == 0 || (thisCommand.Flags & CommandFlags.Unique) != 0)
optimizedCommandChain.Add(thisCommand);
currentCommandChainInternal.Chain.RemoveAt(0);
if (currentCommandChainInternal.Chain.Count == 0)
{
checkables.RemoveAt(i);
break;
}
else
++i;
}
else
{
// do not check this list further, a difference was detected
checkables.RemoveAt(i);
}
}
// resort our gatheredCommandChains so that we could use the remaining content of a list properly, only do that if the checkable list has no direct preceeding elements ({0,2,3} instead {0,1,2})
if (checkables.Count > 0)
for (int i = checkables.First() + 1; i < checkables.Count; ++i)
if (checkables[i] != i)
{
var tmp = gatheredCommandChains[i];
gatheredCommandChains[i] = gatheredCommandChains[checkables[i]];
gatheredCommandChains[checkables[i]] = tmp;
checkables[i] = i;
}
}
flushedCommands.AddRange(optimizedCommandChain);
}
// remove unnecessary SubChainEnd commands
bool openPass = false;
for (int i = flushedCommands.Count - 1; i >= 0; --i)
{
if ((flushedCommands[i].Flags & CommandFlags.SubChainEnd) == CommandFlags.SubChainEnd)
{
if (!openPass)
openPass = true;
else
flushedCommands.RemoveAt(i);
}
else if ((flushedCommands[i].Flags & CommandFlags.SubChainStart) == CommandFlags.SubChainStart)
openPass = false;
}
optimizedCommandBuffer.BufferedCommands.AddRange(flushedCommands);
}
#endregion
}
}

View File

@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using System.Runtime.InteropServices;
using Aiwaz.Core;
namespace Aiwaz.Resources
{
public enum CommandFlags : byte
{
None = 0x00,
SubChainStart = 0x01, // Command will start a new command chain (UseShader for example)
SubChainEnd = 0x02, // Command will end a command chain (Render)
Unique = 0x04, // Similar commands should not be reduced to one Command
StartChain = 0x08, // Command will generate a new command chain
EndChain = 0x10, // Command will end the command chain (RenderGeometry for example)
FlushChain = 0x20, // Command will end the command chain (RenderGeometry for example)
}
public class Command
{
[StructLayout(LayoutKind.Explicit)]
public struct CommandInfoUnion
{
[FieldOffset(0)]
public uint RawValue;
[FieldOffset(0)]
public byte Priority;
[FieldOffset(1)]
public byte SubPriority;
[FieldOffset(2)]
public CommandFlags Flags;
[FieldOffset(3)]
public byte Type;
}
public Command(CommandUser argOwner, CommandFlags argFlags, byte argType)
: this(argOwner, argFlags, argType, 0, 0)
{
}
public Command(CommandUser argOwner, CommandFlags argFlags, byte argType, byte argPriority)
: this(argOwner, argFlags, argType, argPriority, 0)
{
}
public Command(CommandUser argOwner, CommandFlags argFlags, byte argType, byte argPriority, byte argSubPriority)
{
CommandInfo.RawValue = 0;
Owner = argOwner;
Flags = argFlags;
Priority = argPriority;
SubPriority = argSubPriority;
Type = argType;
}
public CommandInfoUnion CommandInfo;
public byte Priority { get { return CommandInfo.Priority; } set { CommandInfo.Priority = value; } }
public byte SubPriority { get { return CommandInfo.SubPriority; } set { CommandInfo.SubPriority = value; } }
public CommandFlags Flags { get { return CommandInfo.Flags; } set { CommandInfo.Flags = value; } }
public byte Type { get { return CommandInfo.Type; } set { CommandInfo.Type = value; } }
public CommandUser Owner;
};
public enum CommandExecuteResult
{
None, // Execution done, proceed to the next Command
RetrySubChain, // Execution should start from a previous "SubChainStart"-flagged Command
RetrySubChainSkipHead // Equal to the above result but skips the as "SubChainStart"-flagged Command
};
public abstract class CommandUser : Resource, IDisposable
{
private List<RenderCommandNode> assignedRenderCommandNodes = new List<RenderCommandNode>();
public List<Command> Commands { get; private set; }
public bool IsPreconditionForNextCommands { get; set; }
public CommandUser()
{
this.Commands = new List<Command>();
Engine.RegisterEngineDisposable(this);
}
~CommandUser()
{
if (!Engine.Initialized)
return;
if (Engine.UnregisterEngineDisposable(this))
this.Dispose();
}
public abstract CommandExecuteResult ExecuteCommand(byte argCommandType, CommandBuffer argCurrentBuffer, int argCurrentPositon);
public void AssignToRenderCommandNode(RenderCommandNode node)
{
assignedRenderCommandNodes.Add(node);
node.MarkDirty();
}
public void UnassignFromRenderCommandNode(RenderCommandNode node)
{
if (assignedRenderCommandNodes.Remove(node))
node.MarkDirty();
}
protected void UnassignFromSceneNodes()
{
for (var i = 0; i < assignedRenderCommandNodes.Count; ++i )
assignedRenderCommandNodes[i].Children.Remove(this);
assignedRenderCommandNodes.Clear();
}
protected void MarkCommandsAsDirty()
{
foreach (var node in assignedRenderCommandNodes)
node.MarkDirty();
}
public new virtual void Dispose()
{
this.WellKnownName = null;
this.UnassignFromSceneNodes();
Engine.UnregisterEngineDisposable(this);
base.Dispose();
}
}
}

View File

@@ -0,0 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aiwaz.Resources
{
}

View File

@@ -0,0 +1,551 @@
using System.Collections.Generic;
using Aiwaz.Core;
using Aiwaz.Contracts;
using System;
using System.Linq;
using SlimDX.Direct3D10;
using SlimDX;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources
{
[AiwazResource("Geometry Buffer", "Renderable buffer with vertex or index data.")]
public class GeometryBuffer : CommandUser, IDisposable, IGeometryBuffer
{
#region Constructor
public GeometryBuffer()
: base()
{
Console.WriteLine("Creating GeometryBuffer..");
PrimitiveTopology = PrimitiveTopology.TriangleList;
Commands.Add(new Command(this, CommandFlags.None, SetIndexBufferCommandType, 1));
Commands.Add(new Command(this, CommandFlags.None, SetVertexBufferCommandType, 0));
Commands.Add(new Command(this, CommandFlags.EndChain | CommandFlags.Unique, DrawGeometryCommandType, 6));
}
public GeometryBuffer(IEnumerable<uint> argIndexData, bool argNeedsDynamicAccess)
: this()
{
this.SetIndexData(argIndexData, argNeedsDynamicAccess);
}
public GeometryBuffer(int argIndexCount, SlimDX.DataStream argIndexData, int argVertexCount, SlimDX.DataStream argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess)
: this()
{
this.SetIndexData(argIndexCount, argIndexData, argNeedsDynamicAccess);
this.SetVertexData(argVertexCount, argVertexData, argVertexElements, argNeedsDynamicAccess);
}
public static GeometryBuffer Create<TVertex>(IEnumerable<TVertex> argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess) where TVertex : struct
{
var geoBuffer = new GeometryBuffer();
geoBuffer.SetVertexData(argVertexData, argVertexElements, argNeedsDynamicAccess);
return geoBuffer;
}
public static GeometryBuffer Create<TVertex>(IEnumerable<uint> argIndexData, IEnumerable<TVertex> argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess) where TVertex : struct
{
var geoBuffer = new GeometryBuffer();
geoBuffer.SetIndexData(argIndexData, argNeedsDynamicAccess);
geoBuffer.SetVertexData(argVertexData, argVertexElements, argNeedsDynamicAccess);
return geoBuffer;
}
#endregion
#region Methods
public void SetVertexData(int argVertexCount, DataStream argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess)
{
Console.WriteLine(string.Format("Vertex data: {0} bytes ({1} elements).", argVertexData.Length, argVertexCount));
var usePickHull = this.IsPickable;
DeleteVertexData();
BufferDescription desc = new BufferDescription((int)argVertexData.Length,
argNeedsDynamicAccess ? ResourceUsage.Dynamic : ResourceUsage.Default,
SlimDX.Direct3D10.BindFlags.VertexBuffer,
argNeedsDynamicAccess ? CpuAccessFlags.Write : 0, ResourceOptionFlags.None);
vertexBuffer = new SlimDX.Direct3D10.Buffer(Engine.Device, argVertexData, desc);
if (vertexBuffer == null)
{
throw new ActionFailedException("GeometryBuffer: Couldn't create vertex buffer!");
}
VertexBufferLength = argVertexCount;
vertexElementSize = (int)argVertexData.Length / argVertexCount;
vertexElements = argVertexElements;
rawVertexData = argVertexData;
if (inputElementDesc == null)
{
if (vertexElements.Length > 0)
{
inputElementDesc = new InputElement[vertexElements.Length];
int i = 0;
foreach (var element in vertexElements)
{
inputElementDesc[i++] = new InputElement(element.SemanticName, element.NameIndex, element.ElementFormat, -1, 0, InputClassification.PerVertexData, 0);
}
}
}
this.IsPickable = usePickHull;
}
public void DeleteVertexData()
{
if (vertexBuffer != null)
Engine.Device.ClearState();
vertexElements = new VertexElement[0];
if (vertexBuffer != null)
vertexBuffer.Dispose();
if (rawVertexData != null)
rawVertexData.Dispose();
vertexBuffer = null;
VertexBufferLength = 0;
vertexElementSize = 0;
rawMappedVertexData = null;
typeMappedVertexData = null;
rawVertexData = null;
inputElementDesc = null;
PickHull = null;
}
public void SetIndexData(int argIndexCount, DataStream argIndexData, bool argNeedsDynamicAccess)
{
Console.WriteLine(string.Format("Index data: {0} bytes ({1} elements).", argIndexData.Length, argIndexCount));
bool usePickHull = this.IsPickable;
DeleteIndexData();
BufferDescription desc = new BufferDescription(
sizeof(uint) * argIndexCount,
ResourceUsage.Default,
SlimDX.Direct3D10.BindFlags.IndexBuffer,
argNeedsDynamicAccess ? CpuAccessFlags.Write : 0, ResourceOptionFlags.None);
indexBuffer = new SlimDX.Direct3D10.Buffer(Engine.Device, argIndexData, desc);
if (indexBuffer == null)
{
throw new ActionFailedException("GeometryBuffer: Couldn't create index buffer!");
}
IndexBufferLength = argIndexCount;
IndexBufferUsableLength = argIndexCount;
IndexBufferOffset = 0;
rawIndexData = argIndexData;
this.IsPickable = usePickHull;
}
public void DeleteIndexData()
{
if (indexBuffer != null)
Engine.Device.ClearState();
if (indexBuffer != null)
indexBuffer.Dispose();
if (rawIndexData != null)
rawIndexData.Dispose();
indexBuffer = null;
rawIndexData = null;
IndexBufferLength = 0;
foreach (var inputLayouts in vertexLayoutsPerShaderAndPass.Values)
foreach (var inputLayout in inputLayouts)
inputLayout.Dispose();
vertexLayoutsPerShaderAndPass.Clear();
PickHull = null;
}
public DataStream MapVertexBufferRaw(MapMode argAccessMode)
{
if (vertexBuffer == null)
throw new NullReferenceException("GeometryBuffer: Access forbidden until resource has been initialized.");
if (rawMappedVertexData != null)
throw new InvalidOperationException("GeometryBuffer: Only one access to the vertex buffer at one time possible.");
try
{
rawMappedVertexData = vertexBuffer.Map(argAccessMode, MapFlags.None);
return rawMappedVertexData;
}
catch (Exception ex)
{
throw new ActionFailedException("GeometryBuffer: Access to the vertex buffer was not successful. " + ex.ToString());
}
}
public void UnmapVertexBuffer()
{
if (vertexBuffer == null)
throw new NullReferenceException("GeometryBuffer: Access forbidden until resource has been initialized.");
if (rawMappedVertexData == null)
throw new InvalidOperationException("GeometryBuffer: No access was done, ending the access to the vertex buffer is not possible.");
if (typeMappedVertexData != null)
{
rawMappedVertexData.Position = 0;
var tmp = (byte[])typeMappedVertexData;
rawMappedVertexData.WriteRange(tmp);
}
vertexBuffer.Unmap();
rawMappedVertexData = null;
typeMappedVertexData = null;
}
public DataStream MapIndexBufferRaw(MapMode argAccessMode)
{
if (indexBuffer == null)
throw new NullReferenceException("GeometryBuffer: Access forbidden until resource has been initialized.");
if (rawMappedIndexData != null)
throw new InvalidOperationException("GeometryBuffer: Only one access to the index buffer at one time possible.");
try
{
rawMappedIndexData = indexBuffer.Map(argAccessMode, MapFlags.None);
return rawMappedIndexData;
}
catch (Exception ex)
{
throw new ActionFailedException("GeometryBuffer: Access to the index buffer was not successful. " + ex.ToString());
}
}
public void UnmapIndexBuffer()
{
if (indexBuffer == null)
throw new NullReferenceException("GeometryBuffer: Access forbidden until resource has been initialized.");
if (rawMappedIndexData == null)
throw new InvalidOperationException("GeometryBuffer: No access was done ending, the access to the index buffer is not possible.");
if (typeMappedIndexData != null)
{
rawMappedIndexData.Position = 0;
rawMappedIndexData.WriteRange(typeMappedIndexData);
}
indexBuffer.Unmap();
rawMappedIndexData = null;
typeMappedIndexData = null;
}
public void ConvertToAdjacency()
{
Console.WriteLine(string.Format("Convert to adjacency."));
switch (PrimitiveTopology)
{
case PrimitiveTopology.LineList:
case PrimitiveTopology.LineStrip:
case PrimitiveTopology.TriangleList:
case PrimitiveTopology.TriangleStrip:
break;
default:
return;
}
InputElement[] inputLayout = new InputElement[2];
inputLayout[0] = new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0);
inputLayout[1] = new InputElement("END", 0, SlimDX.DXGI.Format.R8_UInt, vertexElementSize - 1, 0, InputClassification.PerVertexData, 0);
// create the mesh
int numVertices = VertexBufferLength;
int numIndices = IndexBufferLength;
Mesh mesh = null;
try
{
mesh = new Mesh(Engine.Device, inputLayout, inputLayout[0].SemanticName, numVertices, numIndices / 3, MeshFlags.Has32BitIndices);
}
catch (System.Exception ex)
{
throw new ActionFailedException("GeometryBuffer: Unable to create temp. mesh for adjacency data generation. " + ex.ToString());
}
//set the VB
mesh.SetVertexData(0, rawVertexData);
//set the IB
mesh.SetIndexData(rawIndexData, numIndices);
//generate adjacency
const float epsilon = 0.0f;
mesh.GenerateAdjacencyAndPointRepresentation(epsilon);
//generate adjacency indices
mesh.GenerateGeometryShaderAdjacency();
//get the adjacency data out of the mesh
MeshBuffer indexBufferMesh = null;
DataStream adjIndices = null;
try
{
indexBufferMesh = mesh.GetIndexBuffer();
adjIndices = indexBufferMesh.Map();
}
catch (System.Exception ex)
{
throw new ActionFailedException("GeometryBuffer: Unable to retrive indexdata for adjacency data generation. " + ex.ToString());
}
SetIndexData((int)(adjIndices.Length / sizeof(uint)), adjIndices, false);
//cleanup
indexBufferMesh.Unmap();
indexBufferMesh.Dispose();
mesh.Dispose();
switch (this.PrimitiveTopology)
{
case PrimitiveTopology.LineList:
PrimitiveTopology = PrimitiveTopology.LineListWithAdjacency;
break;
case PrimitiveTopology.LineStrip:
PrimitiveTopology = PrimitiveTopology.LineStripWithAdjacency;
break;
case PrimitiveTopology.TriangleList:
PrimitiveTopology = PrimitiveTopology.TriangleListWithAdjacency;
break;
case PrimitiveTopology.TriangleStrip:
PrimitiveTopology = PrimitiveTopology.TriangleStripWithAdjacency;
break;
}
}
private void Render(IShader argShader)
{
if (vertexElements.Length == 0)
return;
int currentPass = argShader.CurrentPass;
EffectPass currentEffectPass = argShader.Technique.GetPassByIndex(currentPass);
InputLayout vertexLayout = null;
List<InputLayout> ilList;
if (vertexLayoutsPerShaderAndPass.TryGetValue(argShader, out ilList) && ilList.Count > currentPass)
{
vertexLayout = ilList[currentPass];
}
else
{
vertexLayout = new InputLayout(Engine.Device, inputElementDesc, currentEffectPass.Description.Signature);
if (vertexLayout != null)
{
if (ilList == null)
{
ilList = new List<InputLayout>();
ilList.Add(vertexLayout);
vertexLayoutsPerShaderAndPass[argShader] = ilList;
}
else
{
ilList.Add(vertexLayout);
}
}
}
if (vertexLayout != null)
{
currentEffectPass.Apply();
Engine.Device.InputAssembler.SetInputLayout(vertexLayout);
if (indexBuffer == null)
Engine.Device.Draw(VertexBufferLength, 0);
else
Engine.Device.DrawIndexed(IndexBufferUsableLength, IndexBufferOffset, 0);
}
}
#endregion
#region Properties
public int IndexBufferOffset { get; set; }
public int IndexBufferUsableLength { get; set; }
public int IndexBufferLength { get; private set; }
public int VertexBufferLength { get; private set; }
public PrimitiveTopology PrimitiveTopology { get; set; }
public bool IsPickable
{
get
{
return this.PickHull != null;
}
set
{
if (this.IsPickable == value)
return;
this.PickHull = new PickHull(rawVertexData, VertexBufferLength, vertexElements, rawIndexData, IndexBufferLength);
}
}
public IPickHull PickHull { get; protected set; }
#endregion
#region Constants
public static byte SetIndexBufferCommandType = 0;
public static byte SetVertexBufferCommandType = 1;
public static byte DrawGeometryCommandType = 2;
#endregion
#region Private members
SlimDX.Direct3D10.Buffer indexBuffer;
DataStream rawIndexData;
uint[] typeMappedIndexData;
DataStream rawMappedIndexData;
int vertexElementSize;
SlimDX.Direct3D10.Buffer vertexBuffer;
DataStream rawVertexData;
object typeMappedVertexData;
Type typeMappedVertexDataType;
DataStream rawMappedVertexData;
VertexElement[] vertexElements;
InputElement[] inputElementDesc;
Dictionary<IShader, List<InputLayout>> vertexLayoutsPerShaderAndPass = new Dictionary<IShader, List<InputLayout>>();
#endregion
#region CommandUser Members
public override CommandExecuteResult ExecuteCommand(byte argCommandType, CommandBuffer argCurrentBuffer, int argCurrentPositon)
{
if (argCommandType == GeometryBuffer.SetIndexBufferCommandType)
{
if (Engine.EngineStates.LastIndexBufferProvider != this)
{
Engine.Device.InputAssembler.SetIndexBuffer(indexBuffer, SlimDX.DXGI.Format.R32_UInt, IndexBufferOffset);
Engine.EngineStates.LastIndexBufferProvider = this;
}
}
else if (argCommandType == GeometryBuffer.SetVertexBufferCommandType)
{
if (Engine.EngineStates.LastVertexBufferProvider != this)
{
Engine.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, vertexElementSize, 0));
Engine.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology);
Engine.EngineStates.LastVertexBufferProvider = this;
}
}
else if (argCommandType == GeometryBuffer.DrawGeometryCommandType)
{
if (Engine.EngineStates.LastShader == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("GeometryBuffer could not render without a valid shader.");
Console.ForegroundColor = ConsoleColor.White;
}
else if (Engine.EngineStates.LastVertexBufferProvider == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("GeometryBuffer could not render without a valid vertex buffer.");
Console.ForegroundColor = ConsoleColor.White;
}
else
{
Render(Engine.EngineStates.LastShader);
}
}
return CommandExecuteResult.None;
}
#endregion
#region IDisposable Members
void IDisposable.Dispose()
{
if (Engine.EngineStates.LastIndexBufferProvider == this)
Engine.EngineStates.LastIndexBufferProvider = null;
if (Engine.EngineStates.LastVertexBufferProvider == this)
Engine.EngineStates.LastVertexBufferProvider = null;
DeleteVertexData();
DeleteIndexData();
base.Dispose();
}
#endregion
public override ICreationParams CreationParams
{
get { return null; }
}
public override ObservableCollection<IResource> Children
{
get { return null; }
}
#region IGeometryBuffer Members
public void SetIndexData(IEnumerable<uint> argIndexData, bool argNeedsDynamicAccess)
{
this.SetIndexData(argIndexData.Count(), new DataStream(argIndexData.ToArray(), true, true), argNeedsDynamicAccess);
}
public uint[] MapIndexBuffer(MapMode argAccessMode)
{
var rawData = this.MapIndexBufferRaw(argAccessMode);
this.typeMappedIndexData = new uint[this.IndexBufferLength];
rawData.Position = 0;
rawData.ReadRange(this.typeMappedIndexData, 0, this.IndexBufferLength);
rawData.Position = 0;
return this.typeMappedIndexData;
}
#endregion
#region IGeometryBuffer<TVertex> Members
public void SetVertexData<TVertex>(IEnumerable<TVertex> argVertexData, VertexElement[] argVertexElements, bool argNeedsDynamicAccess) where TVertex : struct
{
this.SetVertexData(argVertexData.Count(), new DataStream(argVertexData.ToArray(), true, true), argVertexElements, argNeedsDynamicAccess);
}
public TVertex[] MapVertexBuffer<TVertex>(MapMode argAccessMode) where TVertex : struct
{
var rawData = this.MapVertexBufferRaw(argAccessMode);
typeMappedVertexDataType = typeof(TVertex);
var tmp = new TVertex[this.VertexBufferLength];
typeMappedVertexData = tmp;
rawData.Position = 0;
rawData.ReadRange<TVertex>(tmp, 0, this.VertexBufferLength);
rawData.Position = 0;
return tmp;
}
#endregion
};
}

View File

@@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
namespace Aiwaz.Resources
{
public class PickHull : IPickHull
{
private VertexElement positionElement;
private int strideToPosition;
private DataStream vertexData;
private int vertexCount;
private VertexElement[] vertexElements;
private int vertexElementSize;
private DataStream indexData;
private int indexCount;
private Vector3 boxMaxVector;
private Vector3 boxMinVector;
public PickHull(DataStream vertexData, int vertexCount, VertexElement[] vertexElements, DataStream indexData, int indexCount)
{
this.vertexData = vertexData;
this.vertexCount = vertexCount;
this.vertexElements = vertexElements;
this.indexData = indexData;
this.indexCount = indexCount;
this.vertexElementSize = (int)vertexData.Length / vertexCount;
this.positionElement = vertexElements.First(e => e.WellKnownFormat == VertexElement.Format.Position);
foreach (var element in vertexElements)
{
if (!element.Equals(positionElement))
strideToPosition += element.Size;
else
break;
}
this.Precalculate();
}
public bool TryPick(Ray pickRay, Matrix worldMatrix, out float distance)
{
distance = float.MaxValue;
var boundingSphere = CalcBoundingSphere(worldMatrix);
if (!Ray.Intersects(pickRay, boundingSphere, out distance))
return false;
distance = float.MaxValue;
indexData.Position = 0;
for (var i = 0; i < indexCount / 3; ++i)
{
var triangle = new Vector3[3];
triangle[0] = Vector3.TransformCoordinate(this.GetPositionFromData(indexData.Read<uint>()), worldMatrix);
triangle[1] = Vector3.TransformCoordinate(this.GetPositionFromData(indexData.Read<uint>()), worldMatrix);
triangle[2] = Vector3.TransformCoordinate(this.GetPositionFromData(indexData.Read<uint>()), worldMatrix);
float newDistance;
if (!Ray.Intersects(pickRay, triangle[0], triangle[1], triangle[2], out newDistance)
|| newDistance > distance)
continue;
distance = newDistance;
}
return distance != float.MaxValue;
}
private Vector3 GetPositionFromData(uint index)
{
vertexData.Position = index * vertexElementSize + strideToPosition;
return vertexData.Read<Vector3>();
}
protected void Precalculate()
{
boxMinVector = Vector3.Zero;
boxMaxVector = Vector3.Zero;
for (uint i = 0; i < vertexCount; ++i)
{
boxMinVector = i == 0 ? this.GetPositionFromData(i) : Vector3.Maximize(boxMinVector, this.GetPositionFromData(i));
boxMaxVector = i == 0 ? this.GetPositionFromData(i) : Vector3.Minimize(boxMaxVector, this.GetPositionFromData(i));
}
}
public BoundingSphere CalcBoundingSphere(Matrix worldMatrix)
{
var centerPosition = Vector3.TransformCoordinate(Vector3.Zero, worldMatrix);
var maxVec = Vector3.TransformCoordinate(boxMaxVector, worldMatrix);
return new BoundingSphere(centerPosition, maxVec.Length());
}
public BoundingBox CalcBoundingBox(Matrix worldMatrix)
{
var minVec = Vector3.TransformCoordinate(boxMinVector, worldMatrix);
var maxVec = Vector3.TransformCoordinate(boxMaxVector, worldMatrix);
return new BoundingBox(minVec, maxVec);
}
}
}

View File

@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources.Prefab
{
[CreationParameters("Standard unity-sized non-inverted cube")]
public class CubeParams : ICreationParams
{
public float Width;
public float Height;
public float Depth;
public bool IsInverted;
public CubeParams()
{
Width = 1.0f;
Height = 1.0f;
Depth = 1.0f;
IsInverted = false;
}
}
[AiwazResource("Cube", "A simple non-uniform cube")]
public class Cube : Resource
{
public struct CommonCubeVertex
{
public CommonCubeVertex(SlimDX.Vector3 pos,
SlimDX.Vector3 normal,
SlimDX.Vector3 tangent,
SlimDX.Vector2 tex)
{
this.Pos = pos;
this.Normal = normal;
this.Tangent = tangent;
this.Tex = tex;
}
public SlimDX.Vector3 Pos;
public SlimDX.Vector3 Normal;
public SlimDX.Vector3 Tangent;
public SlimDX.Vector2 Tex;
};
public GeometryBuffer GeometryBuffer { get; protected set; }
public Cube(CubeParams parameters)
{
creationParams = parameters;
float width = parameters.Width * 0.5f;
float height = parameters.Height * 0.5f;
float depth = parameters.Depth * 0.5f;
float normal = parameters.IsInverted ? -1.0f : 1.0f;
float tangent = 1.0f;//isInverted ? -1.0f : 1.0f;
CommonCubeVertex[] vertices = new CommonCubeVertex[]
{
new CommonCubeVertex ( new SlimDX.Vector3( -width, height, -depth ), new SlimDX.Vector3(0.0f, normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, height, -depth ), new SlimDX.Vector3(0.0f, normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, height, depth ), new SlimDX.Vector3(0.0f, normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, height, depth ), new SlimDX.Vector3(0.0f, normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, -height, -depth ), new SlimDX.Vector3(0.0f, -normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, -height, -depth ), new SlimDX.Vector3(0.0f, -normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, -height, depth ), new SlimDX.Vector3(0.0f, -normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, -height, depth ), new SlimDX.Vector3(0.0f, -normal, 0.0f), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, -height, depth ), new SlimDX.Vector3(-normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, tangent, 0.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, -height, -depth ), new SlimDX.Vector3(-normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, tangent, 0.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, height, -depth ), new SlimDX.Vector3(-normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, tangent, 0.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, height, depth ), new SlimDX.Vector3(-normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, tangent, 0.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, -height, depth ), new SlimDX.Vector3(normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, -tangent, 0.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, -height, -depth ), new SlimDX.Vector3(normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, -tangent, 0.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, height, -depth ), new SlimDX.Vector3(normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, -tangent, 0.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, height, depth ), new SlimDX.Vector3(normal, 0.0f, 0.0f), new SlimDX.Vector3(0.0f, -tangent, 0.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, -height, -depth ), new SlimDX.Vector3(0.0f, 0.0f, -normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, -height, -depth ), new SlimDX.Vector3(0.0f, 0.0f, -normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, height, -depth ), new SlimDX.Vector3(0.0f, 0.0f, -normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, height, -depth ), new SlimDX.Vector3(0.0f, 0.0f, -normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, -height, depth ), new SlimDX.Vector3(0.0f, 0.0f, normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, -height, depth ), new SlimDX.Vector3(0.0f, 0.0f, normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( width, height, depth ), new SlimDX.Vector3(0.0f, 0.0f, normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonCubeVertex ( new SlimDX.Vector3( -width, height, depth ), new SlimDX.Vector3(0.0f, 0.0f, normal), new SlimDX.Vector3(-tangent, 0.0f, 0.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
};
var vertexElements = new VertexElement[]
{
new VertexElement(VertexElement.Format.Position),
new VertexElement(VertexElement.Format.Normal),
new VertexElement(VertexElement.Format.Tangent),
new VertexElement(VertexElement.Format.Texture2D)
};
var invertedIndices = new uint[] { 0,1,3, 3,1,2, 5,4,6, 6,4,7, 8,9,11, 11,9,10, 13,12,14, 14,12,15, 16,17,19, 19,17,18, 21,20,22, 22,20,23 };
var normalIndices = new uint[] { 3,1,0, 2,1,3, 6,4,5, 7,4,6, 11,9,8, 10,9,11, 14,12,13, 15,12,14, 19,17,16, 18,17,19, 22,20,21, 23,20,22 };
this.GeometryBuffer = GeometryBuffer.Create<CommonCubeVertex>(
parameters.IsInverted ? invertedIndices : normalIndices,
vertices,
vertexElements,
false);
}
private ICreationParams creationParams;
public override ICreationParams CreationParams
{
get { return creationParams; }
}
private ObservableCollection<IResource> children;
[ReadOnly]
public override ObservableCollection<IResource> Children
{
get
{
if (children == null)
{
children = new ObservableCollection<IResource>();
children.Add(GeometryBuffer);
}
return children;
}
}
}
}

View File

@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources.Prefab
{
public struct PingPongBufferDescription
{
public int LoopCount;
public string ShaderFileName;
public string ShaderTechniqueA;
public string ShaderTechniqueB;
public string PreProcessShaderTechnique;
public int TextureWidth;
public int TextureHeight;
public SlimDX.DXGI.Format TextureFormat;
};
[CreationParameters("Standard ping-pong buffer")]
public class PingPongBufferParams : ICreationParams
{
public PingPongBufferDescription Desc;
public Texture InputTexture;
public PingPongBufferParams()
{
}
}
[AiwazResource("PingPong buffer", "Two buffers that alternate each other")]
public class PingPongBuffer : Resource
{
public Texture InputTexture { get; protected set;}
public Texture OutputTexture { get { return textureB.Texture; } }
public RenderCommandNode RootNode { get; protected set; }
public RenderCommandNode PreProcessNode { get; protected set; }
RenderCommandNode renderTargetNodeA;
RenderCommandNode renderTargetNodeB;
Shader shaderA;
Shader shaderB;
Shader shaderPreProcess;
RenderTargetTexture textureA;
RenderTargetTexture textureB;
GeometryBuffer screenQuad;
ShaderParameterSet shaderParameterA;
ShaderParameterSet shaderParameterB;
ShaderParameterSet shaderParameterPreProcess;
public PingPongBuffer(PingPongBufferParams parameters)
{
creationParams = parameters;
if (string.IsNullOrEmpty(parameters.Desc.ShaderFileName))
throw new ArgumentNullException("ShaderFileName");
shaderA = new Shader(new ShaderParams() { FileName = parameters.Desc.ShaderFileName, TechniqueName = parameters.Desc.ShaderTechniqueA } );
shaderB = new Shader(new ShaderParams() { FileName = parameters.Desc.ShaderFileName, TechniqueName = parameters.Desc.ShaderTechniqueB } );
shaderPreProcess = new Shader(new ShaderParams() { FileName = parameters.Desc.ShaderFileName, TechniqueName = parameters.Desc.PreProcessShaderTechnique });
textureA = new RenderTargetTexture(new RenderTargetTextureParams() { width = parameters.Desc.TextureWidth, height = parameters.Desc.TextureHeight, format = parameters.Desc.TextureFormat } );
textureB = new RenderTargetTexture(new RenderTargetTextureParams() { width = parameters.Desc.TextureWidth, height = parameters.Desc.TextureHeight, format = parameters.Desc.TextureFormat } );
shaderParameterA = new ShaderParameterSet();
shaderParameterA.SetParameter("InputTexture", textureB.Texture, ParameterBindType.BindBySemantic);
shaderParameterB = new ShaderParameterSet();
shaderParameterB.SetParameter("InputTexture", textureA.Texture, ParameterBindType.BindBySemantic);
this.InputTexture = parameters.InputTexture;
shaderParameterPreProcess = new ShaderParameterSet();
shaderParameterPreProcess.SetParameter("InputTexture", this.InputTexture, ParameterBindType.BindBySemantic);
var quad = new Quad(new QuadParams() { Width = 2.0f, Height = 2.0f } );
screenQuad = quad.GeometryBuffer;
renderTargetNodeA = new RenderCommandNode();
renderTargetNodeA.Children.Add(textureA);
renderTargetNodeA.Children.Add(shaderA);
renderTargetNodeA.Children.Add(shaderParameterA);
renderTargetNodeA.Children.Add(screenQuad);
renderTargetNodeB = new RenderCommandNode();
renderTargetNodeB.Children.Add(textureB);
renderTargetNodeB.Children.Add(shaderB);
renderTargetNodeB.Children.Add(shaderParameterB);
renderTargetNodeB.Children.Add(screenQuad);
this.RootNode = new RenderCommandNode();
this.PreProcessNode = new RenderCommandNode();
// preprocessing
this.RootNode.Children.Add(textureB);
this.RootNode.Children.Add(shaderPreProcess);
this.RootNode.Children.Add(shaderParameterPreProcess);
this.RootNode.Children.Add(screenQuad);
this.RootNode.Children.Add(this.PreProcessNode);
// real pingpongs
for (int i = 0; i < parameters.Desc.LoopCount; ++i)
{
this.RootNode.Children.Add(renderTargetNodeA);
this.RootNode.Children.Add(renderTargetNodeB);
}
}
private ICreationParams creationParams;
public override ICreationParams CreationParams
{
get { return creationParams; }
}
private ObservableCollection<IResource> children;
[ReadOnly]
public override ObservableCollection<IResource> Children
{
get
{
if (children == null)
{
children = new ObservableCollection<IResource>();
children.Add(InputTexture);
children.Add(OutputTexture);
children.Add(RootNode);
children.Add(PreProcessNode);
}
return children;
}
}
}
}

View File

@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using SlimDX;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources.Prefab
{
[CreationParameters("Unity-sized one-sided quad")]
public class QuadParams : ICreationParams
{
public float Width;
public float Height;
public bool IsTwoSided;
public QuadParams()
{
Width = 1.0f;
Height = 1.0f;
IsTwoSided = false;
}
}
[AiwazResource("Quad", "A simple 2d non-uniform Quad")]
public class Quad : Resource
{
public struct CommonQuadVertex
{
public CommonQuadVertex(SlimDX.Vector3 pos,
SlimDX.Vector3 normal,
SlimDX.Vector2 tex)
{
this.Pos = pos;
this.Normal = normal;
this.Tex = tex;
}
public SlimDX.Vector3 Pos;
public SlimDX.Vector3 Normal;
public SlimDX.Vector2 Tex;
};
public GeometryBuffer GeometryBuffer { get; protected set; }
public Quad(QuadParams parameters)
{
this.creationParams = parameters;
float width = parameters.Width * 0.5f;
float height = parameters.Height * 0.5f;
CommonQuadVertex[] quadOneSidedVertices = new CommonQuadVertex[]
{
new CommonQuadVertex( new SlimDX.Vector3( -width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
};
CommonQuadVertex[] quadTwoSidedVertices = new CommonQuadVertex[]
{
new CommonQuadVertex( new SlimDX.Vector3( -width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, -1.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, 1.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, 1.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, 1.0f), new SlimDX.Vector2( 1.0f, 1.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( -width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, 1.0f), new SlimDX.Vector2( 1.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, 1.0f), new SlimDX.Vector2( 0.0f, 0.0f ) ),
new CommonQuadVertex( new SlimDX.Vector3( width, -height, 0.0f ), new SlimDX.Vector3(0.0f, 0.0f, 1.0f), new SlimDX.Vector2( 0.0f, 1.0f ) ),
};
var vertexElements = new VertexElement[]
{
new VertexElement(VertexElement.Format.Position),
new VertexElement(VertexElement.Format.Normal),
new VertexElement(VertexElement.Format.Texture2D)
};
var oneSidedIndices = new uint[] { 0,1,2, 3,4,5 };
var twoSidedIndices = new uint[] { 0, 1, 2, 3, 4, 5, 11, 10, 9, 8, 7, 6 };
this.GeometryBuffer = GeometryBuffer.Create<CommonQuadVertex>(
parameters.IsTwoSided ? twoSidedIndices : oneSidedIndices,
parameters.IsTwoSided ? quadTwoSidedVertices : quadOneSidedVertices,
vertexElements,
false);
}
private ICreationParams creationParams;
public override ICreationParams CreationParams
{
get { return creationParams; }
}
private ObservableCollection<IResource> children;
[ReadOnly]
public override ObservableCollection<IResource> Children
{
get
{
if (children == null)
{
children = new ObservableCollection<IResource>();
children.Add(GeometryBuffer);
}
return children;
}
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AiwazResources")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AiwazResources")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db9f92df-997d-4870-b687-8cc93789465e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace Aiwaz.Resources
{
[AiwazResource("RenderCommand Node", "Node to update and perform other nodes.")]
public class RenderCommandNode : CommandUser, IUpdatable
{
#region IRenderCommandNode Members
private ObservableCollection<IResource> children;
public CommandBuffer CommandBuffer { get; protected set; }
public bool IsDirty { get; protected set;}
public RenderCommandNode ParentRenderCommandNode { get; set; }
public RenderCommandNode()
{
Console.WriteLine(string.Format("Creating RenderCommandNode.."));
children = new ObservableCollection<IResource>();
children.CollectionChanged += new NotifyCollectionChangedEventHandler(children_CollectionChanged);
CommandBuffer = new CommandBuffer();
}
void children_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
List<CommandUser> commandUsers = new List<CommandUser>();
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (IResource resource in e.NewItems)
GetCommandUsers(resource, ref commandUsers);
foreach (CommandUser user in commandUsers)
{
user.AssignToRenderCommandNode(this);
var node = user as RenderCommandNode;
if (node != null)
node.ParentRenderCommandNode = this;
}
this.MarkDirty();
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (IResource resource in e.OldItems)
GetCommandUsers(resource, ref commandUsers);
foreach (CommandUser user in commandUsers)
{
var node = user as RenderCommandNode;
if (node != null)
node.ParentRenderCommandNode = null;
user.UnassignFromRenderCommandNode(this);
}
this.MarkDirty();
}
}
public void MarkDirty()
{
IsDirty = true;
if (ParentRenderCommandNode != null)
ParentRenderCommandNode.MarkDirty();
}
public void ProcessCommands()
{
if (IsDirty)
{
this.GenerateDeviceCommands();
CommandBuffer.Optimize();
}
CommandBuffer.Perform(true);
}
public void GenerateDeviceCommands()
{
if (!IsDirty)
return;
IsDirty = false;
CommandBuffer.Clear();
List<CommandUser> commandUsers = new List<CommandUser>();
foreach (var child in children)
GetCommandUsers(child, ref commandUsers);
foreach (CommandUser user in commandUsers)
{
// Add the commands all commands
CommandBuffer.BufferedCommands.AddRange(user.Commands);
// Walk further if we found another RenderCommandNode
var node = user as RenderCommandNode;
if (node != null)
{
node.GenerateDeviceCommands();
// Merge the buffers
CommandBuffer.AddChildCommandBuffer(node.CommandBuffer);
}
}
}
private void GetCommandUsers(IResource resource, ref List<CommandUser> commandUsers)
{
if (resource as CommandUser != null)
commandUsers.Add(resource as CommandUser);
else foreach (var child in resource.Children)
GetCommandUsers(child, ref commandUsers);
}
#endregion
public override CommandExecuteResult ExecuteCommand(byte argCommandType, CommandBuffer argCurrentBuffer, int argCurrentPositon)
{
return CommandExecuteResult.None;
}
#region IUpdatable Members
public void Update(bool forceUpdate)
{
List<CommandUser> commandUsers = new List<CommandUser>();
foreach (var child in children)
GetCommandUsers(child, ref commandUsers);
// Walk through all updatables and update them.
foreach (var user in commandUsers)
{
var updatable = user as IUpdatable;
if (updatable != null && (updatable.WantsUpdate || forceUpdate))
updatable.Update(forceUpdate);
}
}
public bool WantsUpdate
{
get { return true; }
}
#endregion
#region IDisposable Members
public override void Dispose()
{
if (ParentRenderCommandNode != null)
ParentRenderCommandNode.Children.Remove(this);
while (Children.Count > 0)
Children.RemoveAt(0);
base.Dispose();
}
#endregion
public override ICreationParams CreationParams
{
get { return null; }
}
public override ObservableCollection<IResource> Children
{
get { return children; }
}
}
}

View File

@@ -0,0 +1,296 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
namespace Aiwaz.Resources
{
public abstract class RenderTarget : CommandUser, IRenderTargetBase, IDisposable
{
public RenderTarget()
: base()
{
Commands.Add(new Command(this, CommandFlags.EndChain | CommandFlags.FlushChain, setRenderTargetCommandType, 0, 0));
this.ClearDepth = 1.0f;
}
~RenderTarget()
{
if (Engine.Initialized)
this.Dispose();
}
#region IRenderTargetBase Members
internal static SlimDX.Direct3D10.ShaderResourceView[] emptyShaderResView = new SlimDX.Direct3D10.ShaderResourceView[128];
private SlimDX.Direct3D10.RenderTargetView[] renderTargetViews;
private List<IRenderTargetBase> additionalRenderTargets = new List<IRenderTargetBase>();
private SlimDX.Direct3D10.Viewport[] viewports;
protected int multiSampleCount = 1;
protected int multiSampleQuality = 0;
private BindFlags lastBindFlags = BindFlags.Default;
public float ClearDepth { get; set; }
public byte ClearStencil { get; set; }
public SlimDX.Color4 ClearColor { get; set; }
private ViewPort viewPort;
public ViewPort ViewPort
{
get { return viewPort; }
set
{
viewPort = value;
this.KillViewPortAndRenderTargetData();
this.BuildViewPortAndRenderTargetData();
}
}
public abstract int RenderTargetWidth { get; }
public abstract int RenderTargetHeight { get; }
public abstract SlimDX.DXGI.Format RenderTargetFormat { get; }
private bool hasDepthStencilBuffer;
public bool HasDepthStencilBuffer
{
get { return hasDepthStencilBuffer; }
set
{
hasDepthStencilBuffer = value;
Engine.Device.ClearState();
if (DX10DepthStencilView != null)
DX10DepthStencilView.Dispose();
DX10DepthStencilView = null;
if (DX10DepthStencilTexture != null)
DX10DepthStencilTexture.Dispose();
DX10DepthStencilTexture = null;
if (!hasDepthStencilBuffer)
return; // no further effort needed here
var depthTextureDesc = new SlimDX.Direct3D10.Texture2DDescription()
{
Width = this.RenderTargetWidth,
Height = this.RenderTargetHeight,
MipLevels = 1,
ArraySize = 1,
Format = SlimDX.DXGI.Format.D24_UNorm_S8_UInt,
SampleDescription = new SlimDX.DXGI.SampleDescription(multiSampleCount == 0 ? 1 : multiSampleCount, multiSampleQuality),
Usage = SlimDX.Direct3D10.ResourceUsage.Default,
BindFlags = SlimDX.Direct3D10.BindFlags.DepthStencil,
CpuAccessFlags = SlimDX.Direct3D10.CpuAccessFlags.None,
OptionFlags = SlimDX.Direct3D10.ResourceOptionFlags.None
};
DX10DepthStencilTexture = new SlimDX.Direct3D10.Texture2D(Engine.Device, depthTextureDesc);
if (DX10DepthStencilTexture == null)
throw new Aiwaz.Core.ActionFailedException("RenderTarget: Unable to create depth stencil texture.");
var depthStencilViewDesc = new SlimDX.Direct3D10.DepthStencilViewDescription()
{
Format = depthTextureDesc.Format,
Dimension = multiSampleCount >= 1 ? SlimDX.Direct3D10.DepthStencilViewDimension.Texture2DMultisampled : SlimDX.Direct3D10.DepthStencilViewDimension.Texture2D,
MipSlice = 0
};
DX10DepthStencilView = new SlimDX.Direct3D10.DepthStencilView(Engine.Device, DX10DepthStencilTexture, depthStencilViewDesc);
if (DX10DepthStencilView == null)
throw new Aiwaz.Core.ActionFailedException("RenderTarget: Unable to create depth stencil view.");
}
}
public SlimDX.Direct3D10.RenderTargetView DX10RenderTargetView { get; protected set; }
public SlimDX.Direct3D10.DepthStencilView DX10DepthStencilView { get; protected set; }
public SlimDX.Direct3D10.Texture2D DX10DepthStencilTexture { get; protected set; }
public void AddAdditionalRenderTarget(IRenderTargetBase target)
{
this.RemoveAdditionalRenderTarget(target);
//if (AdditionalRenderTargets.Count + 1 == D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT)
// throw new Aiwaz.Core.ActionFailedException("RenderTarget: Unable to add an additional rendering target, list is full.");
additionalRenderTargets.Add(target);
this.KillViewPortAndRenderTargetData();
this.BuildViewPortAndRenderTargetData();
}
public void RemoveAdditionalRenderTarget(IRenderTargetBase target)
{
if (additionalRenderTargets.Remove(target))
{
this.KillViewPortAndRenderTargetData();
this.BuildViewPortAndRenderTargetData();
}
}
public void Bind(BindFlags bindFlags)
{
if ((bindFlags & ~ BindFlags.ClearAll) != (lastBindFlags & ~ BindFlags.ClearAll))
{
lastBindFlags = bindFlags;
this.KillViewPortAndRenderTargetData();
this.BuildViewPortAndRenderTargetData();
}
else
lastBindFlags = bindFlags;
this.Clear(bindFlags);
Engine.Device.PixelShader.SetShaderResources(emptyShaderResView, 0, 128);
Engine.Device.OutputMerger.SetTargets(DX10DepthStencilView, renderTargetViews);
Engine.Device.Rasterizer.SetViewports(viewports);
Engine.EngineStates.LastRenderTarget = this;
}
public void UnbindAllRenderTargets()
{
if (Engine.EngineStates.LastRenderTarget == this)
{
Engine.Device.OutputMerger.SetTargets(new SlimDX.Direct3D10.RenderTargetView[0]);
Engine.Device.Rasterizer.SetViewports(new SlimDX.Direct3D10.Viewport[0]);
Engine.EngineStates.LastRenderTarget = null;
}
}
protected void BuildViewPortAndRenderTargetData()
{
// Rebuild render targets
if (renderTargetViews == null && viewports == null)
{
if ((lastBindFlags & BindFlags.BindAllTextures) == BindFlags.BindAllTextures)
{
renderTargetViews = new SlimDX.Direct3D10.RenderTargetView[additionalRenderTargets.Count + 1];
viewports = new SlimDX.Direct3D10.Viewport[additionalRenderTargets.Count + 1];
renderTargetViews[0] = this.DX10RenderTargetView;
viewports[0] = this.ViewPort;
for (int i = 0; i < additionalRenderTargets.Count; ++i)
{
renderTargetViews[i + 1] = additionalRenderTargets[i].DX10RenderTargetView;
viewports[i + 1] = additionalRenderTargets[i].ViewPort;
}
}
else if ((lastBindFlags & BindFlags.BindAllTextures) != BindFlags.None)
{
var activeRenderTargetCount = 0;
if ((lastBindFlags & BindFlags.BindBaseTexture) != BindFlags.None) ++activeRenderTargetCount;
if ((lastBindFlags & BindFlags.BindAdditionalTexture0) != BindFlags.None) ++activeRenderTargetCount;
if ((lastBindFlags & BindFlags.BindAdditionalTexture1) != BindFlags.None) ++activeRenderTargetCount;
if ((lastBindFlags & BindFlags.BindAdditionalTexture2) != BindFlags.None) ++activeRenderTargetCount;
if ((lastBindFlags & BindFlags.BindAdditionalTexture3) != BindFlags.None) ++activeRenderTargetCount;
renderTargetViews = new SlimDX.Direct3D10.RenderTargetView[activeRenderTargetCount];
viewports = new SlimDX.Direct3D10.Viewport[activeRenderTargetCount];
int bufferIndex = 0;
if ((lastBindFlags & BindFlags.BindBaseTexture) != BindFlags.None)
{
renderTargetViews[bufferIndex] = this.DX10RenderTargetView;
viewports[bufferIndex++] = this.ViewPort;
}
if ((lastBindFlags & BindFlags.BindAdditionalTexture0) != BindFlags.None)
{
renderTargetViews[bufferIndex] = additionalRenderTargets[0].DX10RenderTargetView;
viewports[bufferIndex++] = additionalRenderTargets[0].ViewPort;
}
if ((lastBindFlags & BindFlags.BindAdditionalTexture1) != BindFlags.None)
{
renderTargetViews[bufferIndex] = additionalRenderTargets[1].DX10RenderTargetView;
viewports[bufferIndex++] = additionalRenderTargets[1].ViewPort;
}
if ((lastBindFlags & BindFlags.BindAdditionalTexture2) != BindFlags.None)
{
renderTargetViews[bufferIndex] = additionalRenderTargets[2].DX10RenderTargetView;
viewports[bufferIndex++] = additionalRenderTargets[2].ViewPort;
}
if ((lastBindFlags & BindFlags.BindAdditionalTexture3) != BindFlags.None)
{
renderTargetViews[bufferIndex] = additionalRenderTargets[3].DX10RenderTargetView;
viewports[bufferIndex++] = additionalRenderTargets[3].ViewPort;
}
}
else
throw new ActionFailedException("No render target bindable.");
}
}
protected void KillViewPortAndRenderTargetData()
{
renderTargetViews = null;
viewports = null;
if (Engine.EngineStates.LastRenderTarget == this)
Engine.EngineStates.LastRenderTarget = null;
}
#endregion
#region IDisposable Members
protected void DisposeInternal()
{
this.KillViewPortAndRenderTargetData();
this.UnbindAllRenderTargets();
if (DX10RenderTargetView != null)
DX10RenderTargetView.Dispose();
DX10RenderTargetView = null;
if (DX10DepthStencilView != null)
DX10DepthStencilView.Dispose();
DX10DepthStencilView = null;
if (DX10DepthStencilTexture != null)
DX10DepthStencilTexture.Dispose();
DX10DepthStencilTexture = null;
}
public override void Dispose()
{
this.DisposeInternal();
base.Dispose();
}
#endregion
#region CommandUser
const byte setRenderTargetCommandType = 0;
public override CommandExecuteResult ExecuteCommand(byte commandType, CommandBuffer currentBuffer, int currentPositon)
{
if (commandType == setRenderTargetCommandType)
{
if (Engine.EngineStates.LastRenderTarget != this)
{
this.UnbindAllRenderTargets();
this.Bind(BindFlags.Default);
}
else
this.Clear(BindFlags.Default);
}
return CommandExecuteResult.None;
}
protected void Clear(BindFlags bindFlags)
{
if ((bindFlags & BindFlags.ClearColor) != BindFlags.None)
Engine.Device.ClearRenderTargetView(DX10RenderTargetView, ClearColor);
if ((bindFlags & BindFlags.ClearDepthStencil) != BindFlags.None && DX10DepthStencilView != null)
Engine.Device.ClearDepthStencilView(DX10DepthStencilView, SlimDX.Direct3D10.DepthStencilClearFlags.Depth | SlimDX.Direct3D10.DepthStencilClearFlags.Stencil, ClearDepth, ClearStencil);
}
#endregion
}
}

View File

@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources
{
[CreationParameters("Create an empty RenderTarget texture")]
public class RenderTargetTextureParams : ICreationParams
{
public int width;
public int height;
public SlimDX.DXGI.Format format;
public int multiSampleCount;
public int multiSampleQuality;
public RenderTargetTextureParams()
{
width = 512;
height = 512;
format = SlimDX.DXGI.Format.Unknown;
multiSampleCount = 0;
multiSampleQuality = 0;
}
}
[AiwazResource("RenderTarget texture", "An output target for render operations which could be used as texture input.")]
public class RenderTargetTexture : RenderTarget
{
public RenderTargetTexture(RenderTargetTextureParams parameters)
: base()
{
creationParams = parameters;
Console.WriteLine(string.Format("Creating RenderTargetTexture ({0}x{1} {2})..", parameters.width, parameters.height, parameters.format.ToString()));
this.BuildRenderTargetTexture(parameters.width, parameters.height, parameters.format, parameters.multiSampleCount, parameters.multiSampleQuality);
}
protected void BuildRenderTargetTexture(int width, int height, SlimDX.DXGI.Format format, int multiSampleCount, int multiSampleQuality)
{
if (this.Texture != null &&
width == this.RenderTargetWidth &&
height == this.RenderTargetHeight &&
format == this.RenderTargetFormat &&
this.multiSampleCount == multiSampleCount &&
this.multiSampleQuality == multiSampleQuality)
{
return;
}
this.DisposeInternal();
// get missing information
if (multiSampleCount == 0)
multiSampleCount = 1;
if (width == 0)
width = 1;
if (height == 0)
height = 1;
if (format == SlimDX.DXGI.Format.Unknown)
format = SlimDX.DXGI.Format.R8G8B8A8_UNorm;
this.multiSampleCount = multiSampleCount;
this.multiSampleQuality = multiSampleQuality;
if (this.Texture == null)
this.Texture = new Texture(new EmptyTextureParams()
{
Width = width,
Height = height,
Elements = 1,
MipLevels = 0,
Format = format,
AccessType = SlimDX.Direct3D10.ResourceUsage.Staging,
RenderTarget = true,
MultiSampleCount = multiSampleCount,
MultiSampleQuality = multiSampleQuality
});
else if (this.Texture is Texture)
((Texture)this.Texture).CreateRenderTargetTexture(width, height, format, multiSampleCount, multiSampleQuality);
this.DX10RenderTargetView = new SlimDX.Direct3D10.RenderTargetView(Engine.Device, this.Texture.Texture2D);
this.ViewPort = new ViewPort()
{
Width = width,
Height = height
};
}
public override int RenderTargetWidth
{
get { return Texture.TextureWidth; }
}
public override int RenderTargetHeight
{
get { return Texture.TextureHeight; }
}
public override SlimDX.DXGI.Format RenderTargetFormat
{
get { return Texture.TextureFormat; }
}
#region IRenderTargetTexture Members
public void Resize(int width, int height)
{
if (this.RenderTargetWidth == width || this.RenderTargetHeight == height)
return;
var usedDepthStencilBuffer = this.HasDepthStencilBuffer;
this.BuildRenderTargetTexture(width, height, RenderTargetFormat, multiSampleCount, multiSampleQuality);
this.HasDepthStencilBuffer = usedDepthStencilBuffer;
}
public Texture Texture { get; protected set; }
#endregion
private ICreationParams creationParams;
public override ICreationParams CreationParams
{
get { return creationParams; }
}
private ObservableCollection<IResource> children;
[ReadOnly]
public override ObservableCollection<IResource> Children
{
get
{
if (children == null)
{
children = new ObservableCollection<IResource>();
children.Add(Texture);
}
return children;
}
}
}
}

View File

@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Aiwaz.Resources
{
public abstract class Resource : IResource, INotifyPropertyChanged, IDisposable
{
#region IResource Members
public abstract ICreationParams CreationParams
{
get;
}
protected string wellKnownName;
public string WellKnownName
{
get
{
if (wellKnownName == null)
{
string resourceName = null;
foreach (var attribute in this.GetType().GetCustomAttributes(true))
{
if (attribute.GetType().Equals(typeof(AiwazResourceAttribute)))
{
resourceName = ((AiwazResourceAttribute)attribute).Name;
}
}
if (resourceName == null)
resourceName = "Unknown resource";
int count = 1;
do
{
wellKnownName = string.Format("{0} {1}", resourceName, count++);
} while (Engine.ExistsName(wellKnownName));
Engine.RegisterNamedObject(wellKnownName, this);
}
return wellKnownName;
}
set
{
string newName = value;
if (Engine.ExistsName(newName))
{
int count = 1;
do
{
newName = string.Format("{0} {1}", value, count++);
} while (Engine.ExistsName(newName));
}
if (!string.IsNullOrEmpty(wellKnownName))
Engine.UnregisterNamedObject(wellKnownName);
wellKnownName = newName;
if (!string.IsNullOrEmpty(wellKnownName))
Engine.RegisterNamedObject(wellKnownName, this);
}
}
public IResource Parent
{
get;
set;
}
public abstract ObservableCollection<IResource> Children
{
get;
}
#endregion
#region INotifyPropertyChanged Members
protected void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region IDisposable Members
private bool _disposed = false;
protected bool Disposed
{
get { return _disposed; }
}
protected virtual void Dispose(bool disposing)
{
if (!Disposed)
{
_disposed = true;
}
}
public virtual void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Resource() { Dispose(false); }
#endregion
}
}

View File

@@ -0,0 +1,209 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Common;
using Aiwaz.Core;
using Aiwaz.Resources.Attributes;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources
{
public class TechniqueNotFoundException : Exception { }
public class UnableToLoadShaderException : Exception
{
public UnableToLoadShaderException(string errors)
: base(errors)
{
}
}
[CreationParameters("Load a shader from file")]
public class ShaderParams : ICreationParams
{
[RequiredParameter]
public string FileName;
public string TechniqueName;
public ShaderParams()
{
FileName = null;
TechniqueName = null;
}
}
[AiwazResource("Shader", "A complex shader to perform individual shading operations when rendering geometry buffers.")]
public class Shader : CommandUser, IShader
{
#region IShader Members
const byte applyFirstPassCommandType = 0;
const byte nextPassCommandType = 1;
private InternalShader internalShader;
private string techniqueName;
private byte priority = 0;
public Shader(ShaderParams parameters)
{
creationParams = parameters;
Console.WriteLine(string.Format("Creating Shader ({0} Technique: {1})..", parameters.FileName, parameters.TechniqueName));
internalShader = Engine.FindNamedObject(parameters.FileName) as InternalShader;
if (internalShader == null)
internalShader = new InternalShader(parameters.FileName);
Commands.Add(new Command(this, CommandFlags.StartChain | CommandFlags.SubChainStart, applyFirstPassCommandType, 2, this.Priority));
Commands.Add(new Command(this, CommandFlags.SubChainEnd, nextPassCommandType, byte.MaxValue, this.Priority));
this.TechniqueName = parameters.TechniqueName;
}
public string TechniqueName
{
get { return techniqueName; }
set
{
techniqueName = value;
if (string.IsNullOrEmpty(techniqueName))
{
this.Technique = internalShader.Effect.GetTechniqueByIndex(0);
if (this.Technique != null)
techniqueName = this.Technique.Description.Name;
}
else
this.Technique = internalShader.Effect.GetTechniqueByName(TechniqueName);
if (this.Technique == null)
throw new TechniqueNotFoundException();
CurrentPass = 0;
}
}
public SlimDX.Direct3D10.EffectTechnique Technique { get; protected set; }
public SlimDX.Direct3D10.Effect Effect { get { return internalShader.Effect; } }
public byte Priority
{
get
{
return priority;
}
set
{
priority = value;
foreach (var command in Commands)
if (command.Type == applyFirstPassCommandType)
command.SubPriority = priority;
}
}
public int CurrentPass { get; protected set; }
#endregion
public override CommandExecuteResult ExecuteCommand(byte commandType, CommandBuffer currentBuffer, int currentPositon)
{
if (commandType == applyFirstPassCommandType)
{
CurrentPass = 0;
Engine.EngineStates.LastShader = this;
}
else if (commandType == nextPassCommandType)
{
if (CurrentPass >= this.Technique.Description.PassCount)
CurrentPass = this.Technique.Description.PassCount;
else
CurrentPass++;
if (CurrentPass >= this.Technique.Description.PassCount)
return CommandExecuteResult.None;
return CommandExecuteResult.RetrySubChainSkipHead;
}
return CommandExecuteResult.None;
}
#region IDisposable Members
public override void Dispose()
{
Engine.EngineStates.LastShader = null;
base.Dispose();
}
#endregion
private ICreationParams creationParams;
public override ICreationParams CreationParams
{
get { return creationParams; }
}
public override ObservableCollection<IResource> Children
{
get { return null; }
}
}
internal class InternalShader : IDisposable
{
#region IInternalShader Members
private string fileName;
public InternalShader(string fileName)
{
this.fileName = fileName;
Engine.RegisterNamedObject(fileName, this);
Engine.RegisterEngineDisposable(this);
using (var stream = Engine.FileSystem.Open(fileName))
{
string errors;
Effect = SlimDX.Direct3D10.Effect.FromStream(Engine.Device, stream, "fx_4_0",
#if DEBUG
SlimDX.Direct3D10.ShaderFlags.EnableStrictness | SlimDX.Direct3D10.ShaderFlags.Debug,
#else
SlimDX.Direct3D10.ShaderFlags.EnableStrictness,
#endif
SlimDX.Direct3D10.EffectFlags.None, null, null, out errors);
if (!string.IsNullOrEmpty(errors))
throw new UnableToLoadShaderException(errors);
}
}
~InternalShader()
{
if (!Engine.Initialized)
return;
Engine.UnregisterNamedObject(fileName);
if (Engine.UnregisterEngineDisposable(this))
this.Dispose();
}
public SlimDX.Direct3D10.Effect Effect { get; protected set; }
#endregion
#region IDisposable Members
public void Dispose()
{
if (this.Effect != null)
this.Effect.Dispose();
this.Effect = null;
Engine.UnregisterNamedObject(fileName);
Engine.UnregisterEngineDisposable(this);
}
#endregion
}
}

View File

@@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
using Aiwaz.Common;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources
{
public class ShaderNotSetException : Exception {}
public class UnsupportedShaderParameterTypeException : Exception {}
[AiwazResource("Shader parameter set", "A set of parameters for one or more shaders.")]
public class ShaderParameterSet : CommandUser, IShaderParameterSet
{
#region IShaderParameterSet Members
const byte setShaderParameterCollectionCommandType = 0;
const byte setFollowingShaderParameterCollectionCommandType = 1;
private bool isPreconditionForFollowingShaders;
private byte basePriority;
protected BaseShaderParameterSet baseShaderParameterSet = new BaseShaderParameterSet();
public ShaderParameterSet()
: this(4)
{
}
protected ShaderParameterSet(byte basePriority)
{
this.basePriority = basePriority;
this.IsPreconditionForFollowingShaders = false;
}
public bool IsPreconditionForFollowingShaders
{
get
{
return isPreconditionForFollowingShaders;
}
set
{
if (Commands.Count > 0 && value == isPreconditionForFollowingShaders)
return;
isPreconditionForFollowingShaders = value;
Commands.Clear();
if (isPreconditionForFollowingShaders)
Commands.Add(new Command(this, CommandFlags.EndChain | CommandFlags.FlushChain, setFollowingShaderParameterCollectionCommandType, 0, 0));
else
Commands.Add(new Command(this, CommandFlags.None, setShaderParameterCollectionCommandType, basePriority, 0));
this.MarkCommandsAsDirty();
}
}
public void SetParameter(string parameterName, IShaderParameter parameter)
{
baseShaderParameterSet.SetShaderParameter(parameterName, parameter);
}
public void SetParameter(string parameterName, ITexture argParameter, ParameterBindType argParamNameType)
{
this.SetParameter(parameterName, new Reference(argParameter), argParamNameType);
}
public void SetParameter(string parameterName, float argParameter, ParameterBindType argParamNameType)
{
this.SetParameter(parameterName, new Reference(argParameter), argParamNameType);
}
public void SetParameter(string parameterName, SlimDX.Vector3 argParameter, ParameterBindType argParamNameType)
{
this.SetParameter(parameterName, new Reference(argParameter), argParamNameType);
}
public void SetParameter(string parameterName, SlimDX.Vector4 argParameter, ParameterBindType argParamNameType)
{
this.SetParameter(parameterName, new Reference(argParameter), argParamNameType);
}
public void SetParameter(string parameterName, SlimDX.Matrix argParameter, ParameterBindType argParamNameType)
{
this.SetParameter(parameterName, new Reference(argParameter), argParamNameType);
}
public void SetParameter(string parameterName, bool argParameter, ParameterBindType argParamNameType)
{
this.SetParameter(parameterName, new Reference(argParameter), argParamNameType);
}
public void SetParameter(string parameterName, Reference argParameter, ParameterBindType argParamNameType)
{
baseShaderParameterSet.SetShaderParameter(parameterName, new ShaderParameter(argParamNameType, argParameter));
}
public void RemoveParameter(string name)
{
baseShaderParameterSet.RemoveShaderParameter(name);
}
#endregion
public override CommandExecuteResult ExecuteCommand(byte commandType, CommandBuffer currentBuffer, int currentPositon)
{
if (commandType == setShaderParameterCollectionCommandType)
{
if (Engine.EngineStates.LastShader == null)
throw new ShaderNotSetException();
baseShaderParameterSet.UseParametersOnShader(Engine.EngineStates.LastShader);
}
else if (commandType == setFollowingShaderParameterCollectionCommandType)
{
var shaders = currentBuffer.BufferedCommands.Where(c => c.Owner is IShader && c.Type == 0).Select(c => c.Owner as IShader);
foreach (var shader in shaders)
baseShaderParameterSet.UseParametersOnShader(shader);
}
return CommandExecuteResult.None;
}
#region IDisposable Members
public override void Dispose()
{
base.Dispose();
}
#endregion
public override ICreationParams CreationParams
{
get { return null; }
}
public override ObservableCollection<IResource> Children
{
get { return null; }
}
}
public class BaseShaderParameterSet
{
Dictionary<string, IShaderParameter> parameterMap = new Dictionary<string, IShaderParameter>();
Dictionary<WeakReference, List<Pair<IShaderParameter, SlimDX.Direct3D10.EffectVariable>>> shaderToParameterMap = new Dictionary<WeakReference, List<Pair<IShaderParameter, SlimDX.Direct3D10.EffectVariable>>>();
public void UseParametersOnShader(IShader shader)
{
if (parameterMap.Count == 0)
return;
List<Pair<IShaderParameter, SlimDX.Direct3D10.EffectVariable>> shaderParams = null;
var searchedShaderPair = shaderToParameterMap.FirstOrDefault(a => a.Key.IsAlive && a.Key.Target == shader);
if (searchedShaderPair.Key != null)
shaderParams = searchedShaderPair.Value;
if (shaderParams == null)
{
shaderParams = new List<Pair<IShaderParameter, SlimDX.Direct3D10.EffectVariable>>();
// (re)create shader entries
foreach (var parameter in parameterMap)
if (parameter.Value != null)
{
SlimDX.Direct3D10.EffectVariable effectvar = null;
if (parameter.Value.ParameterNameType == ParameterBindType.BindByVariable)
effectvar = shader.Effect.GetVariableByName(parameter.Key);
else if (parameter.Value.ParameterNameType == ParameterBindType.BindBySemantic)
effectvar = shader.Effect.GetVariableBySemantic(parameter.Key);
if (effectvar != null && effectvar.IsValid)
shaderParams.Add(new Pair<IShaderParameter, SlimDX.Direct3D10.EffectVariable>(parameter.Value, effectvar));
}
if (shaderParams.Count == 0)
return;
shaderToParameterMap[new WeakReference(shader)] = shaderParams;
}
foreach (var parameter in shaderParams)
parameter.First.ApplyValue(parameter.Second);
}
public void SetShaderParameter(string name, IShaderParameter parameter)
{
this.RemoveShaderParameter(name);
parameterMap[name] = parameter;
}
public void RemoveShaderParameter(string name)
{
shaderToParameterMap.Clear();
parameterMap.Remove(name);
}
public void RemoveAllShaderParameters()
{
parameterMap.Clear();
shaderToParameterMap.Clear();
}
}
public class ShaderParameter : IShaderParameter
{
private enum ObjectType
{
Int,
IntArray,
Float,
FloatArray,
Bool,
BoolArray,
Vector2,
Vector3,
Vector4,
Vector4Array,
Matrix,
MatrixArray,
Texture
}
private Reference valueObject;
private ObjectType type;
public ShaderParameter(ParameterBindType parameterNameType, Reference valueObject)
{
this.ParameterNameType = parameterNameType;
this.valueObject = valueObject;
if (valueObject.RawValue is bool)
this.type = ObjectType.Bool;
else if (valueObject.RawValue is bool[])
this.type = ObjectType.BoolArray;
else if (valueObject.RawValue is int)
this.type = ObjectType.Int;
else if (valueObject.RawValue is int[])
this.type = ObjectType.IntArray;
else if (valueObject.RawValue is float)
this.type = ObjectType.Float;
else if (valueObject.RawValue is float[])
this.type = ObjectType.FloatArray;
else if (valueObject.RawValue is SlimDX.Matrix)
this.type = ObjectType.Matrix;
else if (valueObject.RawValue is SlimDX.Matrix[])
this.type = ObjectType.MatrixArray;
else if (valueObject.RawValue is SlimDX.Vector2)
this.type = ObjectType.Vector2;
else if (valueObject.RawValue is SlimDX.Vector3)
this.type = ObjectType.Vector3;
else if (valueObject.RawValue is SlimDX.Vector4)
this.type = ObjectType.Vector4;
else if (valueObject.RawValue is SlimDX.Vector4[])
this.type = ObjectType.Vector4Array;
else if (valueObject.RawValue is ITexture)
this.type = ObjectType.Texture;
else
throw new UnsupportedShaderParameterTypeException();
}
#region IShaderParameter Members
public ParameterBindType ParameterNameType { get; protected set; }
public void ApplyValue(SlimDX.Direct3D10.EffectVariable variable)
{
switch (this.type)
{
case ObjectType.Bool:
variable.AsScalar().Set((bool)valueObject.RawValue);
break;
case ObjectType.BoolArray:
variable.AsScalar().Set((bool[])valueObject.RawValue);
break;
case ObjectType.Int:
variable.AsScalar().Set((int)valueObject.RawValue);
break;
case ObjectType.IntArray:
variable.AsScalar().Set((int[])valueObject.RawValue);
break;
case ObjectType.Float:
variable.AsScalar().Set((float)valueObject.RawValue);
break;
case ObjectType.FloatArray:
variable.AsScalar().Set((float[])valueObject.RawValue);
break;
case ObjectType.Vector2:
variable.AsVector().Set((SlimDX.Vector2)valueObject.RawValue);
break;
case ObjectType.Vector3:
variable.AsVector().Set((SlimDX.Vector3)valueObject.RawValue);
break;
case ObjectType.Vector4:
variable.AsVector().Set((SlimDX.Vector4)valueObject.RawValue);
break;
case ObjectType.Vector4Array:
variable.AsVector().Set((SlimDX.Vector4[])valueObject.RawValue);
break;
case ObjectType.Matrix:
variable.AsMatrix().SetMatrix((SlimDX.Matrix)valueObject.RawValue);
break;
case ObjectType.MatrixArray:
variable.AsMatrix().SetMatrix((SlimDX.Matrix[])valueObject.RawValue);
break;
case ObjectType.Texture:
variable.AsResource().SetResource(((ITexture)valueObject.RawValue).ResourceView);
break;
}
}
#endregion
}
}

View File

@@ -0,0 +1,234 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using System.Runtime.InteropServices;
using Aiwaz.Core;
using System.Collections.ObjectModel;
namespace Aiwaz.Resources
{
[AiwazResource("SwapChain", "An output target for render operations, the output could be displayed directly into a window.")]
public class SwapChain : RenderTarget, ISwapChain
{
[DllImport("user32.dll")]
static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[Serializable, StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT(int left_, int top_, int right_, int bottom_)
{
Left = left_;
Top = top_;
Right = right_;
Bottom = bottom_;
}
public int Height { get { return Bottom - Top; } }
public int Width { get { return Right - Left; } }
}
private SlimDX.DXGI.SwapChainDescription swapChainDescription;
private SlimDX.DXGI.SwapChain swapChain;
public SwapChain(IntPtr windowHandle)
: this(windowHandle, 0, 0, 0, SlimDX.DXGI.Format.Unknown, 0, 0)
{
}
public SwapChain(IntPtr windowHandle, int width, int height, int refreshRate, SlimDX.DXGI.Format format)
: this (windowHandle, width, height, refreshRate, format, 0, 0)
{
}
public SwapChain(IntPtr windowHandle, int width, int height, int refreshRate, SlimDX.DXGI.Format format, int multiSampleCount, int multiSampleQuality)
: base()
{
VSync = true;
// get missing information
if (multiSampleCount <= 0)
multiSampleCount = 1;
if (width == 0 || height == 0)
{
RECT windowRect = new RECT();
GetClientRect(windowHandle, out windowRect);
if (width == 0)
width = windowRect.Right - windowRect.Left;
if (height == 0)
height = windowRect.Bottom - windowRect.Top;
}
if (refreshRate == 0)
refreshRate = 60; // 60Hz
if (format == SlimDX.DXGI.Format.Unknown)
format = SlimDX.DXGI.Format.R8G8B8A8_UNorm; // RGBA(X) 8Bit per channel -> 32Bit
swapChainDescription = new SlimDX.DXGI.SwapChainDescription()
{
BufferCount = 1,
Usage = SlimDX.DXGI.Usage.RenderTargetOutput,
OutputHandle = windowHandle,
IsWindowed = true,
ModeDescription = new SlimDX.DXGI.ModeDescription()
{
Width = width,
Height = height,
Format = (SlimDX.DXGI.Format)format,
RefreshRate = new SlimDX.Rational(refreshRate, 1)
},
SampleDescription = new SlimDX.DXGI.SampleDescription()
{
Count = multiSampleCount,
Quality = multiSampleQuality
}
};
this.multiSampleCount = multiSampleCount;
this.multiSampleQuality = multiSampleQuality;
Console.WriteLine(string.Format("Creating SwapChain ({0}x{1}x{2} {3})..", width, height, refreshRate, format.ToString()));
swapChain = new SlimDX.DXGI.SwapChain(Engine.Factory, Engine.Device, swapChainDescription);
if (swapChain == null)
throw new InitializingFailedException(this.GetType().Name, "Unable to create internal swap chain.");
this.RetriveData();
this.ViewPort = new ViewPort()
{
Width = width,
Height = height
};
}
public override int RenderTargetWidth
{
get { return swapChainDescription.ModeDescription.Width; }
}
public override int RenderTargetHeight
{
get { return swapChainDescription.ModeDescription.Height; }
}
public override SlimDX.DXGI.Format RenderTargetFormat
{
get { return swapChainDescription.ModeDescription.Format; }
}
#region ISwapChain Members
public void Resize(int width, int height)
{
if (width <= 0 || height <= 0)
{
RECT windowRect = new RECT();
GetClientRect(swapChainDescription.OutputHandle, out windowRect);
if (width <= 0)
width = windowRect.Right - windowRect.Left;
if (height <= 0)
height = windowRect.Bottom - windowRect.Top;
}
if (swapChainDescription.ModeDescription.Width == width &&
swapChainDescription.ModeDescription.Height == height)
return;
var depthStencilBuffer = this.HasDepthStencilBuffer;
Engine.Device.ClearState();
this.HasDepthStencilBuffer = false;
if (this.DX10RenderTargetView != null)
this.DX10RenderTargetView.Dispose();
this.DX10RenderTargetView = null;
swapChain.ResizeBuffers(swapChainDescription.BufferCount, width, height, swapChainDescription.ModeDescription.Format, SlimDX.DXGI.SwapChainFlags.AllowModeSwitch);
var desc = swapChainDescription.ModeDescription;
desc.Width = width;
desc.Height = height;
swapChainDescription.ModeDescription = desc;
this.RetriveData();
this.HasDepthStencilBuffer = depthStencilBuffer;
this.ViewPort = new ViewPort()
{
Width = width,
Height = height
};
}
public void Present()
{
swapChain.Present(VSync ? 1 : 0, SlimDX.DXGI.PresentFlags.None);
}
public bool Fullscreen
{
get { return !swapChainDescription.IsWindowed; }
set
{
if (swapChainDescription.IsWindowed == !value)
return;
swapChainDescription.IsWindowed = !value;
var hasDepthStencilBuffer = this.HasDepthStencilBuffer;
Engine.Device.ClearState();
this.HasDepthStencilBuffer = false;
if (this.DX10RenderTargetView != null)
this.DX10RenderTargetView.Dispose();
this.DX10RenderTargetView = null;
swapChain.SetFullScreenState(value, Engine.DeviceEnumerator.FindBestOutput(false).Output);
this.RetriveData();
this.HasDepthStencilBuffer = hasDepthStencilBuffer;
}
}
public bool VSync { get; set; }
private void RetriveData()
{
using (var backbufferTexture = SlimDX.Direct3D10.Texture2D.FromSwapChain<SlimDX.Direct3D10.Texture2D>(swapChain, 0))
{
DX10RenderTargetView = new SlimDX.Direct3D10.RenderTargetView(Engine.Device, backbufferTexture);
}
}
#endregion
#region IDisposable Members
public override void Dispose()
{
if (swapChain != null)
swapChain.Dispose();
swapChain = null;
base.Dispose();
}
#endregion
public override ICreationParams CreationParams
{
get { return null; }
}
public override ObservableCollection<IResource> Children
{
get { return null; }
}
}
}

View File

@@ -0,0 +1,267 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Core;
using SlimDX.Direct3D10;
using Aiwaz.Resources.Attributes;
namespace Aiwaz.Resources
{
[CreationParameters("Create an empty texture")]
public class EmptyTextureParams : ICreationParams
{
public int Width;
public int Height;
public int Elements;
public int MipLevels;
public SlimDX.DXGI.Format Format;
public ResourceUsage AccessType;
public TextureInitialData InitialData;
public bool RenderTarget;
public int MultiSampleCount;
public int MultiSampleQuality;
public EmptyTextureParams()
{
Width = 512;
Height = 512;
Elements = 1;
MipLevels = 1;
Format = SlimDX.DXGI.Format.Unknown;
AccessType = ResourceUsage.Default;
InitialData = null;
RenderTarget = false;
MultiSampleCount = 0;
MultiSampleQuality = 0;
}
}
[CreationParameters("Load a texture from file")]
public class FileTextureParams : ICreationParams
{
[RequiredParameter]
public string FileName;
public SlimDX.Direct3D10.ResourceUsage AccessType;
public FileTextureParams()
{
AccessType = ResourceUsage.Default;
}
}
[AiwazResource("Texture", "A placeholder of multidimensional data")]
public class Texture : ShaderParameterSet, ITexture
{
#region ITexture Members
private string bindingName = "Diffuse";
private SlimDX.Direct3D10.Resource resource;
private int lockedSubResource = 0;
private bool isLocked = false;
private Texture()
: base(3)
{
}
public Texture(FileTextureParams descriptor)
: this()
{
Console.WriteLine(string.Format("Creating Texture ({0})..", descriptor.FileName));
this.LoadFromFile(descriptor.FileName, descriptor.AccessType);
this.WellKnownName = descriptor.FileName;
}
public Texture(EmptyTextureParams descriptor)
: this()
{
this.CreateTexture(descriptor.Width, descriptor.Height, descriptor.MipLevels, descriptor.Elements, descriptor.Format, descriptor.InitialData, descriptor.AccessType, descriptor.RenderTarget, descriptor.MultiSampleCount, descriptor.MultiSampleQuality);
}
public string BindingName
{
get { return bindingName; }
set
{
if (!string.IsNullOrEmpty(bindingName))
this.RemoveParameter(bindingName);
bindingName = value;;
if (!string.IsNullOrEmpty(bindingName))
this.SetParameter(bindingName, this, ParameterBindType.BindBySemantic);
}
}
public int TextureWidth { get; protected set; }
public int TextureHeight { get; protected set; }
public int TextureArraySize { get; protected set; }
public SlimDX.DXGI.Format TextureFormat { get; protected set; }
public SlimDX.Direct3D10.ShaderResourceView ResourceView { get; protected set; }
public SlimDX.Direct3D10.Texture2D Texture2D { get; protected set; }
public SlimDX.DataRectangle MapTextureBuffer(SlimDX.Direct3D10.MapMode mode)
{
return this.MapTextureBuffer(mode, 0);
}
public SlimDX.DataRectangle MapTextureBuffer(SlimDX.Direct3D10.MapMode mode, int arrayElement)
{
if (isLocked)
throw new ActionFailedException("Texture is already locked.");
isLocked = true;
lockedSubResource = arrayElement;
return this.Texture2D.Map(arrayElement, mode, SlimDX.Direct3D10.MapFlags.None);
}
public void UnmapTextureBuffer()
{
if (!isLocked)
return;
isLocked = false;
this.Texture2D.Unmap(lockedSubResource);
}
private void LoadFromFile(string fileName, SlimDX.Direct3D10.ResourceUsage accessType)
{
var loadInfo = SlimDX.Direct3D10.ImageLoadInformation.FromDefaults();
if (accessType == SlimDX.Direct3D10.ResourceUsage.Staging)
{
loadInfo.BindFlags = 0;
loadInfo.Usage = SlimDX.Direct3D10.ResourceUsage.Staging;
loadInfo.CpuAccessFlags = SlimDX.Direct3D10.CpuAccessFlags.Write | SlimDX.Direct3D10.CpuAccessFlags.Read;
}
else if (accessType == SlimDX.Direct3D10.ResourceUsage.Dynamic)
{
loadInfo.Usage = SlimDX.Direct3D10.ResourceUsage.Dynamic;
loadInfo.CpuAccessFlags = SlimDX.Direct3D10.CpuAccessFlags.Write;
}
using (var stream = Engine.FileSystem.Open(fileName))
{
this.Texture2D = SlimDX.Direct3D10.Texture2D.FromStream(Engine.Device, stream, (int)stream.Length, loadInfo);
resource = this.Texture2D;
}
if (accessType != SlimDX.Direct3D10.ResourceUsage.Staging)
{
var texViewDesc = new SlimDX.Direct3D10.ShaderResourceViewDescription();
texViewDesc.Format = this.Texture2D.Description.Format;
texViewDesc.Dimension = SlimDX.Direct3D10.ShaderResourceViewDimension.Texture2D;
texViewDesc.MostDetailedMip = 0;
texViewDesc.MipLevels = this.Texture2D.Description.MipLevels;
this.ResourceView = new SlimDX.Direct3D10.ShaderResourceView(Engine.Device, this.Texture2D, texViewDesc);
}
this.TextureWidth = this.Texture2D.Description.Width;
this.TextureHeight = this.Texture2D.Description.Height;
this.TextureFormat = this.Texture2D.Description.Format;
this.TextureArraySize = 0;
this.BindingName = this.BindingName;
}
internal void CreateRenderTargetTexture(int width, int height, SlimDX.DXGI.Format format, int multiSampleCount, int multiSampleQuality)
{
this.CreateTexture(width, height, 1, 0, format, null, SlimDX.Direct3D10.ResourceUsage.Staging, true, multiSampleCount, multiSampleQuality);
}
private void DisposeInternal()
{
if (this.ResourceView != null)
this.ResourceView.Dispose();
this.ResourceView = null;
if (this.resource != null)
this.resource.Dispose();
this.resource = null;
this.Texture2D = null;
}
private void CreateTexture(int width, int height, int mipLevels, int elements, SlimDX.DXGI.Format format, TextureInitialData initialData, SlimDX.Direct3D10.ResourceUsage accessType, bool renderTarget, int multiSampleCount, int multiSampleQuality)
{
Console.WriteLine(string.Format("Creating Texture ({0}x{1} {2})..", width, height, format.ToString()));
this.DisposeInternal();
// calculate the needed amount of mipmap levels
int mipMapLevels = 1;
for (int tmp = Math.Min(height, width); tmp > 1; tmp /= 2, ++mipMapLevels);
mipMapLevels = Math.Max(1, Math.Min(mipMapLevels, mipLevels == 0 ? mipMapLevels : mipLevels));
// create the resource
var texDesc = new SlimDX.Direct3D10.Texture2DDescription();
texDesc.Width = width;
texDesc.Height = height;
texDesc.MipLevels = mipMapLevels;
texDesc.ArraySize = Math.Max(1, elements);
texDesc.Format = format;
texDesc.SampleDescription = new SlimDX.DXGI.SampleDescription(multiSampleCount, multiSampleQuality);
if (accessType == SlimDX.Direct3D10.ResourceUsage.Dynamic)
{
texDesc.Usage = SlimDX.Direct3D10.ResourceUsage.Dynamic;
texDesc.CpuAccessFlags = SlimDX.Direct3D10.CpuAccessFlags.Write;
}
if (accessType == SlimDX.Direct3D10.ResourceUsage.Staging)
texDesc.BindFlags = ((mipMapLevels > 1 || renderTarget) ? SlimDX.Direct3D10.BindFlags.RenderTarget : SlimDX.Direct3D10.BindFlags.None) | SlimDX.Direct3D10.BindFlags.ShaderResource;
if (mipMapLevels > 1)
texDesc.OptionFlags = SlimDX.Direct3D10.ResourceOptionFlags.GenerateMipMaps;
resource = this.Texture2D = new SlimDX.Direct3D10.Texture2D(Engine.Device, texDesc);
// create the resource view when possible
if (accessType != SlimDX.Direct3D10.ResourceUsage.Staging)
{
var texViewDesc = new SlimDX.Direct3D10.ShaderResourceViewDescription();
texViewDesc.Format = texDesc.Format;
texViewDesc.ElementWidth = elements;
if (elements > 0)
texViewDesc.Dimension = multiSampleCount == 1 ? SlimDX.Direct3D10.ShaderResourceViewDimension.Texture2DArray : SlimDX.Direct3D10.ShaderResourceViewDimension.Texture2DMultisampledArray;
else
texViewDesc.Dimension = multiSampleCount == 1 ? SlimDX.Direct3D10.ShaderResourceViewDimension.Texture2D : SlimDX.Direct3D10.ShaderResourceViewDimension.Texture2DMultisampled;
texViewDesc.MostDetailedMip = 0;
texViewDesc.MipLevels = texDesc.MipLevels;
texViewDesc.ArraySize = elements;
this.ResourceView = new SlimDX.Direct3D10.ShaderResourceView(Engine.Device, resource, texViewDesc);
}
// finalize
this.TextureWidth = width;
this.TextureHeight = height;
this.TextureFormat = format;
this.TextureArraySize = 1;
this.BindingName = this.BindingName;
}
#region IDisposable Members
public override void Dispose()
{
this.DisposeInternal();
base.Dispose();
}
#endregion
#endregion
}
}

View File

@@ -0,0 +1,306 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aiwaz.Contracts;
using Aiwaz.Resources.Attributes;
namespace Aiwaz.Resources
{
public class TransformationBindings : ICreationParams
{
public string WorldMatrixSemanticName;
public string LocalMatrixSemanticName;
public string WorldPositionSemanticName;
public string LocalPositionSemanticName;
public string WorldDirectionSemanticName;
public string LocalDirectionSemanticName;
public string WorldUpDirectionSemanticName;
public string LocalUpDirectionSemanticName;
public string WorldRightDirectionSemanticName;
public string LocalRightDirectionSemanticName;
}
[CreationParameters("Default transformation")]
public class DefaultTransformationBindings : TransformationBindings
{
public DefaultTransformationBindings()
{
WorldMatrixSemanticName = "WorldMatrix";
LocalMatrixSemanticName = "LocalMatrix";
WorldPositionSemanticName = "WorldPosition";
LocalPositionSemanticName = "LocalPosition";
WorldDirectionSemanticName = "WorldDirection";
LocalDirectionSemanticName = "LocalDirection";
WorldUpDirectionSemanticName = "WorldUpDirection";
LocalUpDirectionSemanticName = "LocalUpDirection";
WorldRightDirectionSemanticName = "WorldUpDirection";
LocalRightDirectionSemanticName = "LocalUpDirection";
}
}
[CreationParameters("Camera transformation")]
public class CameraTransformationBindings : TransformationBindings
{
public CameraTransformationBindings()
{
WorldPositionSemanticName = "CamPos";
WorldDirectionSemanticName = "CamDir";
}
}
[AiwazResource("Transformation", "Common transformations for a shader and geometry buffers like position, scale and rotation.")]
public class Transformation : ShaderParameterSet, IUpdatable
{
#region ITransformation Members
Reference worldMatrixRef = new Reference(new SlimDX.Matrix());
Reference worldPositionRef = new Reference(new SlimDX.Vector3());
Reference worldDirectionRef = new Reference(new SlimDX.Vector3());
Reference worldUpDirectionRef = new Reference(new SlimDX.Vector3());
Reference worldRightDirectionRef = new Reference(new SlimDX.Vector3());
Reference localMatrixRef = new Reference(new SlimDX.Matrix());
Reference localPositionRef = new Reference(new SlimDX.Vector3());
Reference localDirectionRef = new Reference(new SlimDX.Vector3());
Reference localUpDirectionRef = new Reference(new SlimDX.Vector3());
Reference localRightDirectionRef = new Reference(new SlimDX.Vector3());
private TransformationBindings transformationBindings;
private SlimDX.Vector3 lastKnownYawPitchRoll;
private SlimDX.Quaternion localRotation;
private SlimDX.Vector3 localScale;
private Transformation transformationParent;
private List<Transformation> transformations = new List<Transformation>();
private Transformation()
: base(5)
{
}
private Transformation(TransformationBindings transformationBindings)
: this()
{
this.WorldScale = this.LocalScale = new SlimDX.Vector3(1.0f, 1.0f, 1.0f);
this.LocalDirection = this.WorldDirection = new SlimDX.Vector3(0.0f, 0.0f, 1.0f);
this.LocalUpDirection = this.WorldUpDirection = new SlimDX.Vector3(0.0f, 1.0f, 0.0f);
this.LocalRightDirection = this.WorldRightDirection = new SlimDX.Vector3(1.0f, 0.0f, 0.0f);
this.TransformationBindings = transformationBindings;
}
public Transformation(DefaultTransformationBindings transformationBindings)
: this((TransformationBindings)transformationBindings)
{
}
public Transformation(CameraTransformationBindings transformationBindings)
: this((TransformationBindings)transformationBindings)
{
}
public TransformationBindings TransformationBindings
{
get { return transformationBindings; }
set
{
transformationBindings = value;
baseShaderParameterSet.RemoveAllShaderParameters();
this.RecreateAllShaderParameters();
}
}
public SlimDX.Vector3 LocalPosition
{
get { return (SlimDX.Vector3)localPositionRef.RawValue; }
set
{
localPositionRef.RawValue = value;
WantsUpdate = true;
}
}
public SlimDX.Vector3 WorldPosition { get { return (SlimDX.Vector3)worldPositionRef.RawValue; } protected set { worldPositionRef.RawValue = value; } }
public SlimDX.Vector3 LocalRotationYPR
{
get
{
return lastKnownYawPitchRoll;
}
set
{
lastKnownYawPitchRoll = value;
LocalRotation = SlimDX.Quaternion.RotationYawPitchRoll(value.X, value.Y, value.Z);
WantsUpdate = true;
}
}
public SlimDX.Quaternion LocalRotation
{
get { return localRotation; }
set
{
localRotation = value;
WantsUpdate = true;
}
}
public SlimDX.Quaternion WorldRotation { get; protected set; }
public SlimDX.Vector3 LocalDirection { get { return (SlimDX.Vector3)localDirectionRef.RawValue; } protected set { localDirectionRef.RawValue = value; } }
public SlimDX.Vector3 WorldDirection { get { return (SlimDX.Vector3)worldDirectionRef.RawValue; } protected set { worldDirectionRef.RawValue = value; } }
public SlimDX.Vector3 LocalUpDirection { get { return (SlimDX.Vector3)localUpDirectionRef.RawValue; } protected set { localUpDirectionRef.RawValue = value; } }
public SlimDX.Vector3 WorldUpDirection { get { return (SlimDX.Vector3)worldUpDirectionRef.RawValue; } protected set { worldUpDirectionRef.RawValue = value; } }
public SlimDX.Vector3 LocalRightDirection { get { return (SlimDX.Vector3)localRightDirectionRef.RawValue; } protected set { localRightDirectionRef.RawValue = value; } }
public SlimDX.Vector3 WorldRightDirection { get { return (SlimDX.Vector3)worldRightDirectionRef.RawValue; } protected set { worldRightDirectionRef.RawValue = value; } }
public SlimDX.Vector3 LocalScale
{
get { return localScale; }
set
{
localScale = value;
WantsUpdate = true;
}
}
public SlimDX.Vector3 WorldScale { get; protected set; }
public SlimDX.Matrix WorldMatrix { get { return (SlimDX.Matrix)worldMatrixRef.RawValue; } protected set { worldMatrixRef.RawValue = value; } }
public SlimDX.Matrix LocalMatrix { get { return (SlimDX.Matrix)localMatrixRef.RawValue; } protected set { localMatrixRef.RawValue = value; } }
public Transformation TransformationParent
{
get { return transformationParent; }
set
{
var oldTransformationParent = transformationParent;
transformationParent = value;
WantsUpdate = true;
if (oldTransformationParent != null)
oldTransformationParent.RemoveTransformation(this);
}
}
public IEnumerable<Transformation> Transformations { get { return transformations; } }
public void AddTransformation(Transformation transformation)
{
if (!transformations.Contains(transformation))
{
transformation.TransformationParent = this;
transformations.Add(transformation);
WantsUpdate = true;
}
}
public void RemoveTransformation(Transformation transformation)
{
if (transformations.Remove(transformation))
transformation.TransformationParent = null;
}
protected virtual void RecreateAllShaderParameters()
{
if (transformationBindings == null)
return;
if (!string.IsNullOrEmpty(transformationBindings.WorldMatrixSemanticName))
this.SetParameter(transformationBindings.WorldMatrixSemanticName, worldMatrixRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.LocalMatrixSemanticName))
this.SetParameter(transformationBindings.LocalMatrixSemanticName, localMatrixRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.WorldPositionSemanticName))
this.SetParameter(transformationBindings.WorldPositionSemanticName, worldPositionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.LocalPositionSemanticName))
this.SetParameter(transformationBindings.LocalPositionSemanticName, localPositionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.WorldDirectionSemanticName))
this.SetParameter(transformationBindings.WorldDirectionSemanticName, worldDirectionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.LocalDirectionSemanticName))
this.SetParameter(transformationBindings.LocalDirectionSemanticName, localDirectionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.WorldUpDirectionSemanticName))
this.SetParameter(transformationBindings.WorldUpDirectionSemanticName, worldUpDirectionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.LocalUpDirectionSemanticName))
this.SetParameter(transformationBindings.LocalUpDirectionSemanticName, localUpDirectionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.WorldRightDirectionSemanticName))
this.SetParameter(transformationBindings.WorldRightDirectionSemanticName, worldRightDirectionRef, ParameterBindType.BindBySemantic);
if (!string.IsNullOrEmpty(transformationBindings.LocalRightDirectionSemanticName))
this.SetParameter(transformationBindings.LocalRightDirectionSemanticName, localRightDirectionRef, ParameterBindType.BindBySemantic);
}
#endregion
#region IUpdatable Members
public virtual void Update(bool forceUpdate)
{
if (!WantsUpdate && !forceUpdate)
return;
WantsUpdate = false;
var localMatrix = SlimDX.Matrix.Transformation(SlimDX.Vector3.Zero, SlimDX.Quaternion.Identity, localScale, SlimDX.Vector3.Zero, localRotation, this.LocalPosition);
var direction = new SlimDX.Vector3(0.0f, 0.0f, 1.0f);
var upDirection = new SlimDX.Vector3(0.0f, 1.0f, 0.0f);
var rightDirection = new SlimDX.Vector3(1.0f, 0.0f, 0.0f);
{
var rotMat = SlimDX.Matrix.RotationQuaternion(localRotation);
LocalDirection = SlimDX.Vector3.TransformNormal(direction, rotMat);
LocalUpDirection = SlimDX.Vector3.TransformNormal(upDirection, rotMat);
LocalRightDirection = SlimDX.Vector3.TransformNormal(rightDirection, rotMat);
}
WorldMatrix = localMatrix;
// stack parent matrix
if (transformationParent != null)
WorldMatrix = localMatrix * transformationParent.WorldMatrix;
// extract world related data
SlimDX.Vector3 tmpScale;
SlimDX.Vector3 tmpPos;
SlimDX.Quaternion tmpRot;
WorldMatrix.Decompose(out tmpScale, out tmpRot, out tmpPos);
WorldPosition = tmpPos;
WorldRotation = tmpRot;
WorldScale = tmpScale;
{
var rotMat = SlimDX.Matrix.RotationQuaternion(WorldRotation);
WorldDirection = SlimDX.Vector3.TransformNormal(direction, rotMat);
WorldUpDirection = SlimDX.Vector3.TransformNormal(upDirection, rotMat);
WorldRightDirection = SlimDX.Vector3.TransformNormal(rightDirection, rotMat);
}
// update following transformations
foreach (var transformation in transformations)
if (transformation is IUpdatable)
{
var updatable = transformation as IUpdatable;
if (updatable != null && (updatable.WantsUpdate || forceUpdate))
updatable.Update(forceUpdate);
}
}
public bool WantsUpdate { get; protected set; }
#endregion
}
}

250
aiwaz/Backup/Aiwaz.sln Normal file
View File

@@ -0,0 +1,250 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Aiwaz", "Aiwaz\Aiwaz.vcproj", "{19BD7EE4-4F92-4695-A59F-8A96618FD709}"
ProjectSection(ProjectDependencies) = postProject
{9B82203B-9845-482A-A0DA-C94127BE5D79} = {9B82203B-9845-482A-A0DA-C94127BE5D79}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlib", "zlib\zlib.vcproj", "{9B82203B-9845-482A-A0DA-C94127BE5D79}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Demo", "Demo\Demo.vcproj", "{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}"
ProjectSection(ProjectDependencies) = postProject
{19BD7EE4-4F92-4695-A59F-8A96618FD709} = {19BD7EE4-4F92-4695-A59F-8A96618FD709}
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{186AE1D2-7748-4CEB-AE3C-322B57434AF7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Cpp Oldschool", "Cpp Oldschool", "{95F04974-B74B-40F5-8AFF-CF1B4664E958}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Aiwaz", "Aiwaz", "{8274F2BD-7576-4C21-9A77-86791F6D5919}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aiwaz.Contracts", "Aiwaz.Contracts\Aiwaz.Contracts.csproj", "{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aiwaz.Demo", "Aiwaz.Demo\Aiwaz.Demo.csproj", "{C3222C73-8869-46A6-862D-4B73DD52BC23}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aiwaz.Common", "Aiwaz.Common\Aiwaz.Common.csproj", "{0F7D7168-08C1-45AE-AAE3-80506939D7E6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aiwaz.Core", "Aiwaz.Core\Aiwaz.Core.csproj", "{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aiwaz.Resources", "Aiwaz.Resources\Aiwaz.Resources.csproj", "{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{E085478B-ED44-4AB1-BA12-693DFFAB0127}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AiwazAnimator", "AiwazAnimator\AiwazAnimator.csproj", "{436DDDBB-9427-4B6D-A840-9A4889DF20D3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aiwaz.Editor", "Aiwaz.Editor\Aiwaz.Editor.csproj", "{5AD414C8-9564-406C-888E-1C4E89DBA566}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|Win32 = Debug|Win32
Debug|x86 = Debug|x86
Part1|Any CPU = Part1|Any CPU
Part1|Mixed Platforms = Part1|Mixed Platforms
Part1|Win32 = Part1|Win32
Part1|x86 = Part1|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|Win32 = Release|Win32
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Debug|Any CPU.ActiveCfg = Debug|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Debug|Mixed Platforms.Build.0 = Debug|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Debug|Win32.ActiveCfg = Debug|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Debug|Win32.Build.0 = Debug|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Debug|x86.ActiveCfg = Debug|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Part1|Any CPU.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Part1|Mixed Platforms.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Part1|Win32.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Part1|x86.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Release|Any CPU.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Release|Mixed Platforms.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Release|Mixed Platforms.Build.0 = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Release|Win32.ActiveCfg = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Release|Win32.Build.0 = Release|Win32
{19BD7EE4-4F92-4695-A59F-8A96618FD709}.Release|x86.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Debug|Any CPU.ActiveCfg = Debug|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Debug|Mixed Platforms.Build.0 = Debug|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Debug|Win32.ActiveCfg = Debug|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Debug|Win32.Build.0 = Debug|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Debug|x86.ActiveCfg = Debug|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Part1|Any CPU.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Part1|Mixed Platforms.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Part1|Win32.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Part1|x86.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Release|Any CPU.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Release|Mixed Platforms.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Release|Mixed Platforms.Build.0 = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Release|Win32.ActiveCfg = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Release|Win32.Build.0 = Release|Win32
{9B82203B-9845-482A-A0DA-C94127BE5D79}.Release|x86.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Debug|Any CPU.ActiveCfg = Debug|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Debug|Mixed Platforms.Build.0 = Debug|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Debug|Win32.ActiveCfg = Debug|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Debug|Win32.Build.0 = Debug|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Debug|x86.ActiveCfg = Debug|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Part1|Any CPU.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Part1|Mixed Platforms.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Part1|Win32.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Part1|x86.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Release|Any CPU.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Release|Mixed Platforms.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Release|Mixed Platforms.Build.0 = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Release|Win32.ActiveCfg = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Release|Win32.Build.0 = Release|Win32
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4}.Release|x86.ActiveCfg = Release|Win32
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|Win32.ActiveCfg = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|Win32.Build.0 = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Debug|x86.ActiveCfg = Debug|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Part1|Any CPU.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Part1|Any CPU.Build.0 = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Part1|Mixed Platforms.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Part1|Mixed Platforms.Build.0 = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Part1|Win32.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Part1|x86.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Release|Any CPU.Build.0 = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Release|Win32.ActiveCfg = Release|Any CPU
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A}.Release|x86.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|Win32.ActiveCfg = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|Win32.Build.0 = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Debug|x86.ActiveCfg = Debug|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Part1|Any CPU.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Part1|Any CPU.Build.0 = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Part1|Mixed Platforms.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Part1|Mixed Platforms.Build.0 = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Part1|Win32.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Part1|x86.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Release|Any CPU.Build.0 = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Release|Win32.ActiveCfg = Release|Any CPU
{C3222C73-8869-46A6-862D-4B73DD52BC23}.Release|x86.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|Win32.ActiveCfg = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|Win32.Build.0 = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Debug|x86.ActiveCfg = Debug|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Part1|Any CPU.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Part1|Any CPU.Build.0 = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Part1|Mixed Platforms.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Part1|Mixed Platforms.Build.0 = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Part1|Win32.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Part1|x86.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Release|Any CPU.Build.0 = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Release|Win32.ActiveCfg = Release|Any CPU
{0F7D7168-08C1-45AE-AAE3-80506939D7E6}.Release|x86.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|Win32.ActiveCfg = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|Win32.Build.0 = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Debug|x86.ActiveCfg = Debug|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Part1|Any CPU.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Part1|Any CPU.Build.0 = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Part1|Mixed Platforms.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Part1|Mixed Platforms.Build.0 = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Part1|Win32.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Part1|x86.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Release|Any CPU.Build.0 = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Release|Win32.ActiveCfg = Release|Any CPU
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508}.Release|x86.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|Win32.ActiveCfg = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|Win32.Build.0 = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Debug|x86.ActiveCfg = Debug|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Part1|Any CPU.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Part1|Any CPU.Build.0 = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Part1|Mixed Platforms.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Part1|Mixed Platforms.Build.0 = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Part1|Win32.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Part1|x86.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Release|Any CPU.Build.0 = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Release|Win32.ActiveCfg = Release|Any CPU
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7}.Release|x86.ActiveCfg = Release|Any CPU
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Debug|Any CPU.ActiveCfg = Debug|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Debug|Mixed Platforms.Build.0 = Debug|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Debug|Win32.ActiveCfg = Debug|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Debug|x86.ActiveCfg = Debug|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Debug|x86.Build.0 = Debug|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Part1|Any CPU.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Part1|Mixed Platforms.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Part1|Mixed Platforms.Build.0 = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Part1|Win32.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Part1|x86.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Part1|x86.Build.0 = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Release|Any CPU.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Release|Mixed Platforms.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Release|Mixed Platforms.Build.0 = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Release|Win32.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Release|x86.ActiveCfg = Release|x86
{436DDDBB-9427-4B6D-A840-9A4889DF20D3}.Release|x86.Build.0 = Release|x86
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|Win32.ActiveCfg = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|Win32.Build.0 = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Debug|x86.ActiveCfg = Debug|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Part1|Any CPU.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Part1|Any CPU.Build.0 = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Part1|Mixed Platforms.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Part1|Mixed Platforms.Build.0 = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Part1|Win32.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Part1|x86.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Release|Any CPU.Build.0 = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Release|Win32.ActiveCfg = Release|Any CPU
{5AD414C8-9564-406C-888E-1C4E89DBA566}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{186AE1D2-7748-4CEB-AE3C-322B57434AF7} = {95F04974-B74B-40F5-8AFF-CF1B4664E958}
{7AD8CE26-922D-42C9-BCA1-F3635D545EC4} = {95F04974-B74B-40F5-8AFF-CF1B4664E958}
{9B82203B-9845-482A-A0DA-C94127BE5D79} = {186AE1D2-7748-4CEB-AE3C-322B57434AF7}
{19BD7EE4-4F92-4695-A59F-8A96618FD709} = {186AE1D2-7748-4CEB-AE3C-322B57434AF7}
{DE4D6FE6-D1FB-41A1-8ABA-19635B8FFD7A} = {8274F2BD-7576-4C21-9A77-86791F6D5919}
{0F7D7168-08C1-45AE-AAE3-80506939D7E6} = {8274F2BD-7576-4C21-9A77-86791F6D5919}
{B7AB4BB3-6FFC-453E-928D-852A6FF8C508} = {8274F2BD-7576-4C21-9A77-86791F6D5919}
{EA73561A-0B57-4FDC-8AF3-52E959BA67E7} = {8274F2BD-7576-4C21-9A77-86791F6D5919}
{436DDDBB-9427-4B6D-A840-9A4889DF20D3} = {E085478B-ED44-4AB1-BA12-693DFFAB0127}
{5AD414C8-9564-406C-888E-1C4E89DBA566} = {E085478B-ED44-4AB1-BA12-693DFFAB0127}
EndGlobalSection
EndGlobal

BIN
aiwaz/Backup/Aiwaz.v11.suo Normal file

Binary file not shown.