Moving some files around

This commit is contained in:
Marc Hernandez 2019-12-08 00:16:21 -08:00
parent afd97b1522
commit 6e2e40dee3
14 changed files with 4180 additions and 4176 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,172 +1,172 @@
using System;
using System.IO;
using System.Xml;
using System.Reflection;
namespace lib
{
public class DescAttribute : Attribute
{
public string Desc { get; private set; }
public DescAttribute( string desc )
{
Desc = desc;
}
}
[Serializable]
public class ConfigCfg : Config
{
public readonly bool writeOutTemplateFiles = true;
}
[Serializable]
public class Config
{
/*
static public Config Load( string filename )
{
return null;
}
*/
static ConfigCfg s_cfg = new ConfigCfg();
static public void startup( string filename )
{
res.Mgr.register<Config>( load );
res.Mgr.registerSub( typeof( Config ) );
s_cfg = Config.load<ConfigCfg>( filename );
}
#region SaveLoad
/*
static public res.Ref<Config> res_load( string filename )
{
return new res.Ref<Config>( filename, load( filename ) );
}
*/
static public T res_load<T>( string filename ) where T : Config
{
return load<T>( filename );
}
/*
static public ResRefConfig res_load( string filename, Type t )
{
return new ResRefConfig( filename, load( filename, t ) );
}
*/
static public Config load( string filename )
{
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
XmlFormatter2 formatter = new XmlFormatter2();
Config cfg = (Config)formatter.Deserialize( fs );
return cfg;
}
static public T load<T>( string filename ) where T : Config
{
return (T)load( filename, typeof( T ) );
}
static public Config load( string filename, Type t )
{
Config cfg = null;
try
{
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
XmlFormatter2 formatter = new XmlFormatter2();
cfg = (Config)( t != null ? formatter.DeserializeKnownType( fs, t ) : formatter.Deserialize( fs ) );
cfg.SetFilename( filename );
}
catch( FileNotFoundException )
{
Type[] types = new Type[ 0 ];
object[] parms = new object[ 0 ];
//types[ 0 ] = typeof( string );
//parms[ 0 ] = filename;
ConstructorInfo cons = t.GetConstructor( types );
try
{
cfg = (Config)cons.Invoke( parms );
}
catch( Exception e )
{
Log.error( $"Exception while creating config {t.ToString()}, Msg {e.Message}" );
}
//cfg.SetFilename( filename );
if( s_cfg.writeOutTemplateFiles )
{
var templateFile = $"templates/{filename}";
var dirName = Path.GetDirectoryName( templateFile );
lib.Util.checkAndAddDirectory( dirName );
lib.Log.info( $"Writing out template config of type {t.Name} in {templateFile}" );
Config.save( cfg, templateFile );
}
}
return cfg;
}
static public void save( Config cfg )
{
Config.save( cfg, cfg.m_filename );
}
static public void save( Config cfg, String filename )
{
FileStream fs = new FileStream( filename, FileMode.Create, FileAccess.Write );
XmlFormatter2 formatter = new XmlFormatter2();
formatter.Serialize( fs, cfg );
fs.Close();
}
#endregion
private string m_filename = "";
public Config()
{
}
public Config( string filename )
{
m_filename = filename;
}
public String Filename { get { return m_filename; } }
protected void SetFilename( String filename ) { m_filename = filename; }
}
}
using System;
using System.IO;
using System.Xml;
using System.Reflection;
namespace lib
{
public class DescAttribute : Attribute
{
public string Desc { get; private set; }
public DescAttribute( string desc )
{
Desc = desc;
}
}
[Serializable]
public class ConfigCfg : Config
{
public readonly bool writeOutTemplateFiles = true;
}
[Serializable]
public class Config
{
/*
static public Config Load( string filename )
{
return null;
}
*/
static ConfigCfg s_cfg = new ConfigCfg();
static public void startup( string filename )
{
res.Mgr.register<Config>( load );
res.Mgr.registerSub( typeof( Config ) );
s_cfg = Config.load<ConfigCfg>( filename );
}
#region SaveLoad
/*
static public res.Ref<Config> res_load( string filename )
{
return new res.Ref<Config>( filename, load( filename ) );
}
*/
static public T res_load<T>( string filename ) where T : Config
{
return load<T>( filename );
}
/*
static public ResRefConfig res_load( string filename, Type t )
{
return new ResRefConfig( filename, load( filename, t ) );
}
*/
static public Config load( string filename )
{
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
XmlFormatter2 formatter = new XmlFormatter2();
Config cfg = (Config)formatter.Deserialize( fs );
return cfg;
}
static public T load<T>( string filename ) where T : Config
{
return (T)load( filename, typeof( T ) );
}
static public Config load( string filename, Type t )
{
Config cfg = null;
try
{
FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read );
XmlFormatter2 formatter = new XmlFormatter2();
cfg = (Config)( t != null ? formatter.DeserializeKnownType( fs, t ) : formatter.Deserialize( fs ) );
cfg.SetFilename( filename );
}
catch( FileNotFoundException )
{
Type[] types = new Type[ 0 ];
object[] parms = new object[ 0 ];
//types[ 0 ] = typeof( string );
//parms[ 0 ] = filename;
ConstructorInfo cons = t.GetConstructor( types );
try
{
cfg = (Config)cons.Invoke( parms );
}
catch( Exception e )
{
Log.error( $"Exception while creating config {t.ToString()}, Msg {e.Message}" );
}
//cfg.SetFilename( filename );
if( s_cfg.writeOutTemplateFiles )
{
var templateFile = $"templates/{filename}";
var dirName = Path.GetDirectoryName( templateFile );
lib.Util.checkAndAddDirectory( dirName );
lib.Log.info( $"Writing out template config of type {t.Name} in {templateFile}" );
Config.save( cfg, templateFile );
}
}
return cfg;
}
static public void save( Config cfg )
{
Config.save( cfg, cfg.m_filename );
}
static public void save( Config cfg, String filename )
{
FileStream fs = new FileStream( filename, FileMode.Create, FileAccess.Write );
XmlFormatter2 formatter = new XmlFormatter2();
formatter.Serialize( fs, cfg );
fs.Close();
}
#endregion
private string m_filename = "";
public Config()
{
}
public Config( string filename )
{
m_filename = filename;
}
public String Filename { get { return m_filename; } }
protected void SetFilename( String filename ) { m_filename = filename; }
}
}

View File

@ -1,15 +1,15 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
// A spot for immutable helpers
public static class imm
{
}
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
// A spot for immutable helpers
public static class imm
{
}

View File

@ -1,52 +1,52 @@
using System;
namespace lib
{
[Serializable]
public struct Pos
{
public float x { get; private set; }
public float y { get; private set; }
public float z { get; private set; }
public Pos( float _x, float _y, float _z ) : this()
{
x = _x;
y = _y;
z = _z;
}
// overload operator +
public static Pos operator +( Pos a, Pos b )
{
return new Pos( a.x + b.x, a.y + b.y, a.z + b.z );
}
public static Pos operator -( Pos a, Pos b )
{
return new Pos( a.x - b.x, a.y - b.y, a.z - b.z );
}
public static Pos operator /( Pos a, float val )
{
return new Pos( a.x / val, a.y / val, a.z / val );
}
public static Pos operator *( Pos a, float val )
{
return new Pos( a.x * val, a.y * val, a.z * val );
}
public float distSqr( Pos other )
{
float dx = x - other.x;
float dy = y - other.y;
float dz = z - other.z;
return dx * dx + dy * dy + dz * dz;
}
{
[Serializable]
public struct Pos
{
public float x { get; private set; }
public float y { get; private set; }
public float z { get; private set; }
public Pos( float _x, float _y, float _z ) : this()
{
x = _x;
y = _y;
z = _z;
}
// overload operator +
public static Pos operator +( Pos a, Pos b )
{
return new Pos( a.x + b.x, a.y + b.y, a.z + b.z );
}
public static Pos operator -( Pos a, Pos b )
{
return new Pos( a.x - b.x, a.y - b.y, a.z - b.z );
}
public static Pos operator /( Pos a, float val )
{
return new Pos( a.x / val, a.y / val, a.z / val );
}
public static Pos operator *( Pos a, float val )
{
return new Pos( a.x * val, a.y * val, a.z * val );
}
public float distSqr( Pos other )
{
float dx = x - other.x;
float dy = y - other.y;
float dz = z - other.z;
return dx * dx + dy * dy + dz * dz;
}
}
}

View File

@ -1,110 +1,110 @@
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net.Sockets;
using System.IO;
//using Util;
namespace lib
{
public interface IProcess
{
void process( object obj );
}
public class Conn
{
public Socket Sock { get { return m_socket; } }
public Stream Stream { get { return m_streamNet; } }
public Conn( Socket sock, IProcess proc )
{
m_socket = sock;
sock.NoDelay = true;
m_streamNet = new NetworkStream( m_socket );
m_proc = proc;
}
public object recieveObject()
{
return recieveObject( Stream );
}
public object recieveObject( Stream stream )
{
object obj = null;
var formatter = new XmlFormatter2();
try
{
obj = formatter.Deserialize( stream );
}
catch( System.Xml.XmlException ex )
{
lib.Log.error( $"Outer Exception {ex.Message}" );
}
return obj;
}
public void send( object obj )
{
var formatter = new XmlFormatter2();
try
{
var ms = new MemoryStream( 1024 );
formatter.Serialize( ms, obj );
//var str = System.Text.Encoding.Default.GetString( mm_buffer, 0, (int)ms.Position );
//lib.Log.info( $"Sent data {str} of length {ms.Position}" );
//lib.Log.info( $"Sent {obj}" );
byte[] byteSize = BitConverter.GetBytes( (uint)ms.Position );
m_streamNet.Write( byteSize, 0, 4 );
m_streamNet.Write( ms.GetBuffer(), 0, (int)ms.Position );
m_streamNet.Flush();
}
catch( Exception e )
{
lib.Log.warn( $"Exception sending obj {obj} of {e}" );
throw;
}
}
public virtual void recieve( object obj )
{
if( m_proc != null )
m_proc.process( obj );
}
Socket m_socket;
NetworkStream m_streamNet;
IProcess m_proc;
//private BufferedStream m_streamBufIn;
//private BufferedStream m_streamBufOut;
}
}
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net.Sockets;
using System.IO;
//using Util;
namespace lib
{
public interface IProcess
{
void process( object obj );
}
public class Conn
{
public Socket Sock { get { return m_socket; } }
public Stream Stream { get { return m_streamNet; } }
public Conn( Socket sock, IProcess proc )
{
m_socket = sock;
sock.NoDelay = true;
m_streamNet = new NetworkStream( m_socket );
m_proc = proc;
}
public object recieveObject()
{
return recieveObject( Stream );
}
public object recieveObject( Stream stream )
{
object obj = null;
var formatter = new XmlFormatter2();
try
{
obj = formatter.Deserialize( stream );
}
catch( System.Xml.XmlException ex )
{
lib.Log.error( $"Outer Exception {ex.Message}" );
}
return obj;
}
public void send( object obj )
{
var formatter = new XmlFormatter2();
try
{
var ms = new MemoryStream( 1024 );
formatter.Serialize( ms, obj );
//var str = System.Text.Encoding.Default.GetString( mm_buffer, 0, (int)ms.Position );
//lib.Log.info( $"Sent data {str} of length {ms.Position}" );
//lib.Log.info( $"Sent {obj}" );
byte[] byteSize = BitConverter.GetBytes( (uint)ms.Position );
m_streamNet.Write( byteSize, 0, 4 );
m_streamNet.Write( ms.GetBuffer(), 0, (int)ms.Position );
m_streamNet.Flush();
}
catch( Exception e )
{
lib.Log.warn( $"Exception sending obj {obj} of {e}" );
throw;
}
}
public virtual void recieve( object obj )
{
if( m_proc != null )
m_proc.process( obj );
}
Socket m_socket;
NetworkStream m_streamNet;
IProcess m_proc;
//private BufferedStream m_streamBufIn;
//private BufferedStream m_streamBufOut;
}
}

View File

@ -17,8 +17,8 @@ namespace lib.Net
{
m_username = name;
m_password = pass;
}
}
public readonly String m_username;
public readonly String m_password;
}
@ -29,23 +29,23 @@ namespace lib.Net
public LoginResp( bool resp )
{
m_resp = resp;
}
}
public readonly bool m_resp;
}
}
#region Admin Messages
//Subclasses of this need to be on an admin client.
//Subclasses of this need to be on an admin client.
[Serializable]
public class Admin
{
{
};
[Serializable]
public class CreateEntity : Admin
{
{
}
@ -53,17 +53,17 @@ namespace lib.Net
public class MoveEntity : Admin
{
}
}
#endregion
[Serializable]
public class EntityBase
{
public EntityBase( int id )
{
m_id = id;
}
}
public readonly int m_id;
};
@ -77,8 +77,8 @@ namespace lib.Net
m_x = x;
m_y = y;
m_z = z;
}
}
public readonly float m_x;
public readonly float m_y;
public readonly float m_z;
@ -90,14 +90,14 @@ namespace lib.Net
public EntityDesc( int id ) :
base( id )
{
}
//Should an entity have a mesh? Be made up of multiple meshes?
public readonly String m_mesh;
}
}
//Should an entity have a mesh? Be made up of multiple meshes?
public readonly String m_mesh;
}
}

View File

@ -1,220 +1,220 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
static public class scr
{
public class PredEnumerator
{
public static PredEnumerator<T> Create<T>( IEnumerator<T> en, Predicate<T> pred )
{
return new PredEnumerator<T>( en, pred );
}
public static PredEnumerator<T> Create<T>( IEnumerable<T> en, Predicate<T> pred )
{
return new PredEnumerator<T>( en.GetEnumerator(), pred );
}
}
public class PredEnumerator<T> : PredEnumerator, IEnumerator<T>
{
public T Current => m_en.Current;
object IEnumerator.Current => m_en.Current;
public PredEnumerator( IEnumerator<T> en, Predicate<T> pred )
{
m_en = en;
m_pred = pred;
}
public bool MoveNext()
{
var success = m_en.MoveNext();
if( !success )
return false;
while( !m_pred( m_en.Current ) && ( success = m_en.MoveNext() ) )
{
}
return success;
}
public void Reset()
{
m_en.Reset();
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose( bool disposing )
{
if( !disposedValue )
{
if( disposing )
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~MyEnumerator()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose( true );
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
IEnumerator<T> m_en;
Predicate<T> m_pred;
}
public class PredEnumerable<T> : IEnumerable<T>
{
public PredEnumerable( PredEnumerator<T> en )
{
m_en = en;
}
public IEnumerator<T> GetEnumerator()
{
return m_en;
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_en;
}
PredEnumerator<T> m_en;
}
public static void GetAllFields( Type t, List<FieldInfo> list )
{
var fieldArr = t.GetFields(
BindingFlags.DeclaredOnly |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance);
var en = PredEnumerator.Create<FieldInfo>( fieldArr.AsEnumerable<FieldInfo>(), fa => fa.GetCustomAttribute( typeof( NonSerializedAttribute ) ) == null );
list.AddRange( new PredEnumerable<FieldInfo>( en ) );
if( t.BaseType != null && t.BaseType != typeof( object ) )
{
GetAllFields( t.BaseType, list );
}
}
public static ImmutableList<FieldInfo> GetAllFields( Type t )
{
if( s_fieldCache.TryGetValue( t, out var info ) )
return info;
var list = new List<FieldInfo>();
GetAllFields( t, list );
var immList = list.ToImmutableList();
s_fieldCache = s_fieldCache.Add( t, immList );
return immList;
}
public static void GetAllProperties( Type t, List<PropertyInfo> list )
{
var propArr = t.GetProperties(
BindingFlags.DeclaredOnly |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance
);
var en = PredEnumerator.Create<PropertyInfo>( propArr.AsEnumerable<PropertyInfo>(),
fa => fa.GetCustomAttribute( typeof( NonSerializedAttribute ) ) == null && !list.Exists( f => f.Name == fa.Name ) );
list.AddRange( new PredEnumerable<PropertyInfo>( en ) );
if( t.BaseType != null && t.BaseType != typeof( object ) )
{
GetAllProperties( t.BaseType, list );
}
}
public static ImmutableList<PropertyInfo> GetAllProperties( Type t )
{
if( s_propCache.TryGetValue( t, out var info ) )
return info;
var list = new List<PropertyInfo>();
GetAllProperties( t, list );
var immList = list.ToImmutableList();
s_propCache = s_propCache.Add( t, immList );
return immList;
}
static ImmutableDictionary<Type, ImmutableList<FieldInfo>> s_fieldCache = ImmutableDictionary<Type, ImmutableList<FieldInfo>>.Empty;
static ImmutableDictionary<Type, ImmutableList<PropertyInfo>> s_propCache = ImmutableDictionary<Type, ImmutableList<PropertyInfo>>.Empty;
//SLOW
static public string TypeToIdentifier( string typename )
{
return typename.Replace( '<', '_' ).Replace( '>', '_' ).Replace( ',', '_' ).Replace( ' ', '_' ).Replace( '.', '_' ).Replace( '+', '_' ).Replace( '[', '_' ).Replace( ']', '_' ).Replace( '$', '_' ).Replace( ':', '_' );
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
static public class scr
{
public class PredEnumerator
{
public static PredEnumerator<T> Create<T>( IEnumerator<T> en, Predicate<T> pred )
{
return new PredEnumerator<T>( en, pred );
}
public static PredEnumerator<T> Create<T>( IEnumerable<T> en, Predicate<T> pred )
{
return new PredEnumerator<T>( en.GetEnumerator(), pred );
}
}
public class PredEnumerator<T> : PredEnumerator, IEnumerator<T>
{
public T Current => m_en.Current;
object IEnumerator.Current => m_en.Current;
public PredEnumerator( IEnumerator<T> en, Predicate<T> pred )
{
m_en = en;
m_pred = pred;
}
public bool MoveNext()
{
var success = m_en.MoveNext();
if( !success )
return false;
while( !m_pred( m_en.Current ) && ( success = m_en.MoveNext() ) )
{
}
return success;
}
public void Reset()
{
m_en.Reset();
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose( bool disposing )
{
if( !disposedValue )
{
if( disposing )
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~MyEnumerator()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose( true );
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
IEnumerator<T> m_en;
Predicate<T> m_pred;
}
public class PredEnumerable<T> : IEnumerable<T>
{
public PredEnumerable( PredEnumerator<T> en )
{
m_en = en;
}
public IEnumerator<T> GetEnumerator()
{
return m_en;
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_en;
}
PredEnumerator<T> m_en;
}
public static void GetAllFields( Type t, List<FieldInfo> list )
{
var fieldArr = t.GetFields(
BindingFlags.DeclaredOnly |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance);
var en = PredEnumerator.Create<FieldInfo>( fieldArr.AsEnumerable<FieldInfo>(), fa => fa.GetCustomAttribute( typeof( NonSerializedAttribute ) ) == null );
list.AddRange( new PredEnumerable<FieldInfo>( en ) );
if( t.BaseType != null && t.BaseType != typeof( object ) )
{
GetAllFields( t.BaseType, list );
}
}
public static ImmutableList<FieldInfo> GetAllFields( Type t )
{
if( s_fieldCache.TryGetValue( t, out var info ) )
return info;
var list = new List<FieldInfo>();
GetAllFields( t, list );
var immList = list.ToImmutableList();
s_fieldCache = s_fieldCache.Add( t, immList );
return immList;
}
public static void GetAllProperties( Type t, List<PropertyInfo> list )
{
var propArr = t.GetProperties(
BindingFlags.DeclaredOnly |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance
);
var en = PredEnumerator.Create<PropertyInfo>( propArr.AsEnumerable<PropertyInfo>(),
fa => fa.GetCustomAttribute( typeof( NonSerializedAttribute ) ) == null && !list.Exists( f => f.Name == fa.Name ) );
list.AddRange( new PredEnumerable<PropertyInfo>( en ) );
if( t.BaseType != null && t.BaseType != typeof( object ) )
{
GetAllProperties( t.BaseType, list );
}
}
public static ImmutableList<PropertyInfo> GetAllProperties( Type t )
{
if( s_propCache.TryGetValue( t, out var info ) )
return info;
var list = new List<PropertyInfo>();
GetAllProperties( t, list );
var immList = list.ToImmutableList();
s_propCache = s_propCache.Add( t, immList );
return immList;
}
static ImmutableDictionary<Type, ImmutableList<FieldInfo>> s_fieldCache = ImmutableDictionary<Type, ImmutableList<FieldInfo>>.Empty;
static ImmutableDictionary<Type, ImmutableList<PropertyInfo>> s_propCache = ImmutableDictionary<Type, ImmutableList<PropertyInfo>>.Empty;
//SLOW
static public string TypeToIdentifier( string typename )
{
return typename.Replace( '<', '_' ).Replace( '>', '_' ).Replace( ',', '_' ).Replace( ' ', '_' ).Replace( '.', '_' ).Replace( '+', '_' ).Replace( '[', '_' ).Replace( ']', '_' ).Replace( '$', '_' ).Replace( ':', '_' );
}
}

View File

@ -9,157 +9,157 @@ using System.IO;
using System.Security.Permissions;
namespace lib
{
[Serializable]
public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
{
{
[Serializable]
public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
{
#region Constants
private const string DictionaryNodeName = "Dictionary";
private const string ItemNodeName = "Item";
private const string KeyNodeName = "Key";
private const string ValueNodeName = "Value";
private const string DictionaryNodeName = "Dictionary";
private const string ItemNodeName = "Item";
private const string KeyNodeName = "Key";
private const string ValueNodeName = "Value";
#endregion
#region Constructors
public SerializableDictionary()
{
}
public SerializableDictionary( IDictionary<TKey, TVal> dictionary )
: base( dictionary )
{
}
public SerializableDictionary( IEqualityComparer<TKey> comparer )
: base( comparer )
{
}
public SerializableDictionary( int capacity )
: base( capacity )
{
}
public SerializableDictionary( IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer )
: base( dictionary, comparer )
{
}
public SerializableDictionary( int capacity, IEqualityComparer<TKey> comparer )
: base( capacity, comparer )
{
}
public SerializableDictionary()
{
}
public SerializableDictionary( IDictionary<TKey, TVal> dictionary )
: base( dictionary )
{
}
public SerializableDictionary( IEqualityComparer<TKey> comparer )
: base( comparer )
{
}
public SerializableDictionary( int capacity )
: base( capacity )
{
}
public SerializableDictionary( IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer )
: base( dictionary, comparer )
{
}
public SerializableDictionary( int capacity, IEqualityComparer<TKey> comparer )
: base( capacity, comparer )
{
}
#endregion
#region ISerializable Members
protected SerializableDictionary( SerializationInfo info, StreamingContext context )
{
int itemCount = info.GetInt32("ItemCount");
for( int i = 0; i < itemCount; i++ )
{
KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair<TKey, TVal>));
this.Add( kvp.Key, kvp.Value );
}
}
[SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context )
{
info.AddValue( "ItemCount", this.Count );
int itemIdx = 0;
foreach( KeyValuePair<TKey, TVal> kvp in this )
{
info.AddValue( String.Format( $"Item{itemIdx}" ), kvp, typeof( KeyValuePair<TKey, TVal> ) );
itemIdx++;
}
}
protected SerializableDictionary( SerializationInfo info, StreamingContext context )
{
int itemCount = info.GetInt32("ItemCount");
for( int i = 0; i < itemCount; i++ )
{
KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format( $"Item{i}" ), typeof(KeyValuePair<TKey, TVal>));
this.Add( kvp.Key, kvp.Value );
}
}
[SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter )]
void ISerializable.GetObjectData( SerializationInfo info, StreamingContext context )
{
info.AddValue( "ItemCount", this.Count );
int itemIdx = 0;
foreach( KeyValuePair<TKey, TVal> kvp in this )
{
info.AddValue( String.Format( $"Item{itemIdx}" ), kvp, typeof( KeyValuePair<TKey, TVal> ) );
itemIdx++;
}
}
#endregion
#region IXmlSerializable Members
void IXmlSerializable.WriteXml( System.Xml.XmlWriter writer )
{
//writer.WriteStartElement(DictionaryNodeName);
foreach( KeyValuePair<TKey, TVal> kvp in this )
{
writer.WriteStartElement( ItemNodeName );
writer.WriteStartElement( KeyNodeName );
KeySerializer.Serialize( writer, kvp.Key );
writer.WriteEndElement();
writer.WriteStartElement( ValueNodeName );
ValueSerializer.Serialize( writer, kvp.Value );
writer.WriteEndElement();
writer.WriteEndElement();
}
//writer.WriteEndElement();
}
void IXmlSerializable.ReadXml( System.Xml.XmlReader reader )
{
if( reader.IsEmptyElement )
{
return;
}
// Move past container
if( !reader.Read() )
{
throw new XmlException( "Error in Deserialization of Dictionary" );
}
//reader.ReadStartElement(DictionaryNodeName);
while( reader.NodeType != XmlNodeType.EndElement )
{
reader.ReadStartElement( ItemNodeName );
reader.ReadStartElement( KeyNodeName );
TKey key = (TKey)KeySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement( ValueNodeName );
TVal value = (TVal)ValueSerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadEndElement();
this.Add( key, value );
reader.MoveToContent();
}
//reader.ReadEndElement();
reader.ReadEndElement(); // Read End Element to close Read of containing node
}
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.WriteXml( System.Xml.XmlWriter writer )
{
//writer.WriteStartElement(DictionaryNodeName);
foreach( KeyValuePair<TKey, TVal> kvp in this )
{
writer.WriteStartElement( ItemNodeName );
writer.WriteStartElement( KeyNodeName );
KeySerializer.Serialize( writer, kvp.Key );
writer.WriteEndElement();
writer.WriteStartElement( ValueNodeName );
ValueSerializer.Serialize( writer, kvp.Value );
writer.WriteEndElement();
writer.WriteEndElement();
}
//writer.WriteEndElement();
}
void IXmlSerializable.ReadXml( System.Xml.XmlReader reader )
{
if( reader.IsEmptyElement )
{
return;
}
// Move past container
if( !reader.Read() )
{
throw new XmlException( "Error in Deserialization of Dictionary" );
}
//reader.ReadStartElement(DictionaryNodeName);
while( reader.NodeType != XmlNodeType.EndElement )
{
reader.ReadStartElement( ItemNodeName );
reader.ReadStartElement( KeyNodeName );
TKey key = (TKey)KeySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement( ValueNodeName );
TVal value = (TVal)ValueSerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadEndElement();
this.Add( key, value );
reader.MoveToContent();
}
//reader.ReadEndElement();
reader.ReadEndElement(); // Read End Element to close Read of containing node
}
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
#endregion
#region Private Properties
protected XmlSerializer ValueSerializer
{
get
{
if( valueSerializer == null )
{
valueSerializer = new XmlSerializer( typeof( TVal ) );
}
return valueSerializer;
}
}
private XmlSerializer KeySerializer
{
get
{
if( keySerializer == null )
{
keySerializer = new XmlSerializer( typeof( TKey ) );
}
return keySerializer;
}
}
protected XmlSerializer ValueSerializer
{
get
{
if( valueSerializer == null )
{
valueSerializer = new XmlSerializer( typeof( TVal ) );
}
return valueSerializer;
}
}
private XmlSerializer KeySerializer
{
get
{
if( keySerializer == null )
{
keySerializer = new XmlSerializer( typeof( TKey ) );
}
return keySerializer;
}
}
#endregion
#region Private Members
private XmlSerializer keySerializer = null;
private XmlSerializer valueSerializer = null;
private XmlSerializer keySerializer = null;
private XmlSerializer valueSerializer = null;
#endregion
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,52 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lib
{
public class Clock
{
public Clock( long timeOffset )
{
m_timer = new Timer();
m_lastTime = m_timer.Current;
m_totalMillis = timeOffset;
m_totalSeconds = (double)m_totalMillis / 1000.0;
}
public void tick()
{
long current = m_timer.Current;
m_dtMillis = (int)( current - m_lastTime );
m_dtSeconds = (double)m_dtMillis / 1000.0;
m_totalMillis += m_dtMillis;
m_totalSeconds = (double)m_totalMillis / 1000.0;
m_lastTime = current;
}
public int dtMs { get { return m_dtMillis; } }
public double dtSec { get { return m_dtSeconds; } }
public long ms { get { return m_totalMillis; } }
public double sec { get { return m_totalSeconds; } }
Timer m_timer;
long m_lastTime = 0;
int m_dtMillis = 0;
double m_dtSeconds = 0;
long m_totalMillis = 0;
double m_totalSeconds = 0;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lib
{
public class Clock
{
public Clock( long timeOffset )
{
m_timer = new Timer();
m_lastTime = m_timer.Current;
m_totalMillis = timeOffset;
m_totalSeconds = (double)m_totalMillis / 1000.0;
}
public void tick()
{
long current = m_timer.Current;
m_dtMillis = (int)( current - m_lastTime );
m_dtSeconds = (double)m_dtMillis / 1000.0;
m_totalMillis += m_dtMillis;
m_totalSeconds = (double)m_totalMillis / 1000.0;
m_lastTime = current;
}
public int dtMs { get { return m_dtMillis; } }
public double dtSec { get { return m_dtSeconds; } }
public long ms { get { return m_totalMillis; } }
public double sec { get { return m_totalSeconds; } }
Timer m_timer;
long m_lastTime = 0;
int m_dtMillis = 0;
double m_dtSeconds = 0;
long m_totalMillis = 0;
double m_totalSeconds = 0;
}
}

View File

@ -1,377 +1,377 @@
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace lib
{
public class MicroStopwatch : System.Diagnostics.Stopwatch
{
readonly double _microSecPerTick
= 1000000D / System.Diagnostics.Stopwatch.Frequency;
public MicroStopwatch()
{
if( !System.Diagnostics.Stopwatch.IsHighResolution )
{
throw new Exception( "On this system the high-resolution " +
"performance counter is not available" );
}
}
public long ElapsedMicroseconds
{
get
{
return (long)( ElapsedTicks * _microSecPerTick );
}
}
}
/// <summary>
/// MicroTimer class
/// </summary>
public class MicroTimer
{
public delegate void MicroTimerElapsedEventHandler(
object sender,
MicroTimerEventArgs timerEventArgs );
public event MicroTimerElapsedEventHandler MicroTimerElapsed;
System.Threading.Thread _threadTimer = null;
long _ignoreEventIfLateBy = long.MaxValue;
long _timerIntervalInMicroSec = 0;
bool _stopTimer = true;
public MicroTimer()
{
}
public MicroTimer( long timerIntervalInMicroseconds )
{
Interval = timerIntervalInMicroseconds;
}
public long Interval
{
get
{
return System.Threading.Interlocked.Read(
ref _timerIntervalInMicroSec );
}
set
{
System.Threading.Interlocked.Exchange(
ref _timerIntervalInMicroSec, value );
}
}
public long IgnoreEventIfLateBy
{
get
{
return System.Threading.Interlocked.Read(
ref _ignoreEventIfLateBy );
}
set
{
System.Threading.Interlocked.Exchange(
ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value );
}
}
public bool Enabled
{
set
{
if( value )
{
Start();
}
else
{
Stop();
}
}
get
{
return ( _threadTimer != null && _threadTimer.IsAlive );
}
}
public void Start()
{
if( Enabled || Interval <= 0 )
{
return;
}
_stopTimer = false;
System.Threading.ThreadStart threadStart = delegate()
{
NotificationTimer(ref _timerIntervalInMicroSec,
ref _ignoreEventIfLateBy,
ref _stopTimer);
};
_threadTimer = new System.Threading.Thread( threadStart );
_threadTimer.Priority = System.Threading.ThreadPriority.Highest;
_threadTimer.Start();
}
public void Stop()
{
_stopTimer = true;
if( _threadTimer != null && _threadTimer.ManagedThreadId ==
System.Threading.Thread.CurrentThread.ManagedThreadId )
{
return;
}
while( Enabled )
{
System.Threading.Thread.SpinWait( 10 );
}
}
void NotificationTimer( ref long timerIntervalInMicroSec,
ref long ignoreEventIfLateBy,
ref bool stopTimer )
{
int timerCount = 0;
long nextNotification = 0;
MicroStopwatch microStopwatch = new MicroStopwatch();
microStopwatch.Start();
while( !stopTimer )
{
long callbackFunctionExecutionTime =
microStopwatch.ElapsedMicroseconds - nextNotification;
long timerIntervalInMicroSecCurrent =
System.Threading.Interlocked.Read(ref timerIntervalInMicroSec);
long ignoreEventIfLateByCurrent =
System.Threading.Interlocked.Read(ref ignoreEventIfLateBy);
nextNotification += timerIntervalInMicroSecCurrent;
timerCount++;
long elapsedMicroseconds = 0;
while( ( elapsedMicroseconds = microStopwatch.ElapsedMicroseconds )
< nextNotification )
{
System.Threading.Thread.SpinWait( 10 );
}
long timerLateBy = elapsedMicroseconds - nextNotification;
if( timerLateBy >= ignoreEventIfLateByCurrent )
{
continue;
}
MicroTimerEventArgs microTimerEventArgs =
new MicroTimerEventArgs(timerCount,
elapsedMicroseconds,
timerLateBy,
callbackFunctionExecutionTime);
MicroTimerElapsed( this, microTimerEventArgs );
}
microStopwatch.Stop();
}
}
/// <summary>
/// MicroTimer Event Argument class
/// </summary>
public class MicroTimerEventArgs : EventArgs
{
// Simple counter, number times timed event (callback function) executed
public int TimerCount { get; private set; }
// Time when timed event was called since timer started
public long ElapsedMicroseconds { get; private set; }
// How late the timer was compared to when it should have been called
public long TimerLateBy { get; private set; }
// Time it took to execute previous call to callback function (OnTimedEvent)
public long CallbackFunctionExecutionTime { get; private set; }
public MicroTimerEventArgs( int timerCount,
long elapsedMicroseconds,
long timerLateBy,
long callbackFunctionExecutionTime )
{
TimerCount = timerCount;
ElapsedMicroseconds = elapsedMicroseconds;
TimerLateBy = timerLateBy;
CallbackFunctionExecutionTime = callbackFunctionExecutionTime;
}
}
public class Timer
{
MicroStopwatch m_watch;
private long startTime;
private long stopTime;
private long freq;
private long freq_millis;
public Timer()
{
m_watch = new MicroStopwatch();
//startTime = m_watch.ElapsedMicroseconds;
//stopTime = m_watch.ElapsedMicroseconds;
freq = 1000 * 1000;
freq_millis = freq / 1000;
Start();
}
// Start the timer
public Timer Start()
{
m_watch.Start();
startTime = m_watch.ElapsedMicroseconds;
stopTime = m_watch.ElapsedMicroseconds;
return this;
}
// Stop the timer
public Timer Stop()
{
m_watch.Stop();
stopTime = m_watch.ElapsedMicroseconds;
return this;
}
public double Seconds
{
get
{
long current = m_watch.ElapsedMicroseconds;
return (double)( current - startTime ) / freq;
}
}
public long Current
{
get
{
long current = m_watch.ElapsedMicroseconds;
return ( current - startTime ) / freq_millis;
}
}
public double Duration
{
get
{
return (double)( stopTime - startTime ) / (double)freq;
}
}
public long DurationMS
{
get { return ( stopTime - startTime ) / freq_millis; }
}
}
public class TimerWin
{
[DllImport( "Kernel32.dll" )]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount );
[DllImport( "Kernel32.dll" )]
private static extern bool QueryPerformanceFrequency(
out long lpFrequency );
private long startTime;
private long stopTime;
private long freq;
private long freq_millis;
// Constructor
public TimerWin()
{
startTime = 0;
stopTime = 0;
if( QueryPerformanceFrequency( out freq ) == false )
{
// high-performance counter not supported
throw new Win32Exception();
}
freq_millis = freq / 1000;
}
// Start the timer
public void Start()
{
// lets do the waiting threads there work
//Thread.Sleep(0);
QueryPerformanceCounter( out startTime );
}
// Stop the timer
public void Stop()
{
QueryPerformanceCounter( out stopTime );
}
public double Seconds
{
get
{
long current;
QueryPerformanceCounter( out current );
return (double)( current - startTime ) / freq;
}
}
public long Current
{
get
{
long current;
QueryPerformanceCounter( out current );
return ( current - startTime ) / freq_millis;
}
}
public double Duration
{
get
{
return (double)( stopTime - startTime ) / (double)freq;
}
}
public long DurationMS
{
get { return ( stopTime - startTime ) / freq_millis; }
}
}
}
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace lib
{
public class MicroStopwatch : System.Diagnostics.Stopwatch
{
readonly double _microSecPerTick
= 1000000D / System.Diagnostics.Stopwatch.Frequency;
public MicroStopwatch()
{
if( !System.Diagnostics.Stopwatch.IsHighResolution )
{
throw new Exception( "On this system the high-resolution " +
"performance counter is not available" );
}
}
public long ElapsedMicroseconds
{
get
{
return (long)( ElapsedTicks * _microSecPerTick );
}
}
}
/// <summary>
/// MicroTimer class
/// </summary>
public class MicroTimer
{
public delegate void MicroTimerElapsedEventHandler(
object sender,
MicroTimerEventArgs timerEventArgs );
public event MicroTimerElapsedEventHandler MicroTimerElapsed;
System.Threading.Thread _threadTimer = null;
long _ignoreEventIfLateBy = long.MaxValue;
long _timerIntervalInMicroSec = 0;
bool _stopTimer = true;
public MicroTimer()
{
}
public MicroTimer( long timerIntervalInMicroseconds )
{
Interval = timerIntervalInMicroseconds;
}
public long Interval
{
get
{
return System.Threading.Interlocked.Read(
ref _timerIntervalInMicroSec );
}
set
{
System.Threading.Interlocked.Exchange(
ref _timerIntervalInMicroSec, value );
}
}
public long IgnoreEventIfLateBy
{
get
{
return System.Threading.Interlocked.Read(
ref _ignoreEventIfLateBy );
}
set
{
System.Threading.Interlocked.Exchange(
ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value );
}
}
public bool Enabled
{
set
{
if( value )
{
Start();
}
else
{
Stop();
}
}
get
{
return ( _threadTimer != null && _threadTimer.IsAlive );
}
}
public void Start()
{
if( Enabled || Interval <= 0 )
{
return;
}
_stopTimer = false;
System.Threading.ThreadStart threadStart = delegate()
{
NotificationTimer(ref _timerIntervalInMicroSec,
ref _ignoreEventIfLateBy,
ref _stopTimer);
};
_threadTimer = new System.Threading.Thread( threadStart );
_threadTimer.Priority = System.Threading.ThreadPriority.Highest;
_threadTimer.Start();
}
public void Stop()
{
_stopTimer = true;
if( _threadTimer != null && _threadTimer.ManagedThreadId ==
System.Threading.Thread.CurrentThread.ManagedThreadId )
{
return;
}
while( Enabled )
{
System.Threading.Thread.SpinWait( 10 );
}
}
void NotificationTimer( ref long timerIntervalInMicroSec,
ref long ignoreEventIfLateBy,
ref bool stopTimer )
{
int timerCount = 0;
long nextNotification = 0;
MicroStopwatch microStopwatch = new MicroStopwatch();
microStopwatch.Start();
while( !stopTimer )
{
long callbackFunctionExecutionTime =
microStopwatch.ElapsedMicroseconds - nextNotification;
long timerIntervalInMicroSecCurrent =
System.Threading.Interlocked.Read(ref timerIntervalInMicroSec);
long ignoreEventIfLateByCurrent =
System.Threading.Interlocked.Read(ref ignoreEventIfLateBy);
nextNotification += timerIntervalInMicroSecCurrent;
timerCount++;
long elapsedMicroseconds = 0;
while( ( elapsedMicroseconds = microStopwatch.ElapsedMicroseconds )
< nextNotification )
{
System.Threading.Thread.SpinWait( 10 );
}
long timerLateBy = elapsedMicroseconds - nextNotification;
if( timerLateBy >= ignoreEventIfLateByCurrent )
{
continue;
}
MicroTimerEventArgs microTimerEventArgs =
new MicroTimerEventArgs(timerCount,
elapsedMicroseconds,
timerLateBy,
callbackFunctionExecutionTime);
MicroTimerElapsed( this, microTimerEventArgs );
}
microStopwatch.Stop();
}
}
/// <summary>
/// MicroTimer Event Argument class
/// </summary>
public class MicroTimerEventArgs : EventArgs
{
// Simple counter, number times timed event (callback function) executed
public int TimerCount { get; private set; }
// Time when timed event was called since timer started
public long ElapsedMicroseconds { get; private set; }
// How late the timer was compared to when it should have been called
public long TimerLateBy { get; private set; }
// Time it took to execute previous call to callback function (OnTimedEvent)
public long CallbackFunctionExecutionTime { get; private set; }
public MicroTimerEventArgs( int timerCount,
long elapsedMicroseconds,
long timerLateBy,
long callbackFunctionExecutionTime )
{
TimerCount = timerCount;
ElapsedMicroseconds = elapsedMicroseconds;
TimerLateBy = timerLateBy;
CallbackFunctionExecutionTime = callbackFunctionExecutionTime;
}
}
public class Timer
{
MicroStopwatch m_watch;
private long startTime;
private long stopTime;
private long freq;
private long freq_millis;
public Timer()
{
m_watch = new MicroStopwatch();
//startTime = m_watch.ElapsedMicroseconds;
//stopTime = m_watch.ElapsedMicroseconds;
freq = 1000 * 1000;
freq_millis = freq / 1000;
Start();
}
// Start the timer
public Timer Start()
{
m_watch.Start();
startTime = m_watch.ElapsedMicroseconds;
stopTime = m_watch.ElapsedMicroseconds;
return this;
}
// Stop the timer
public Timer Stop()
{
m_watch.Stop();
stopTime = m_watch.ElapsedMicroseconds;
return this;
}
public double Seconds
{
get
{
long current = m_watch.ElapsedMicroseconds;
return (double)( current - startTime ) / freq;
}
}
public long Current
{
get
{
long current = m_watch.ElapsedMicroseconds;
return ( current - startTime ) / freq_millis;
}
}
public double Duration
{
get
{
return (double)( stopTime - startTime ) / (double)freq;
}
}
public long DurationMS
{
get { return ( stopTime - startTime ) / freq_millis; }
}
}
public class TimerWin
{
[DllImport( "Kernel32.dll" )]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount );
[DllImport( "Kernel32.dll" )]
private static extern bool QueryPerformanceFrequency(
out long lpFrequency );
private long startTime;
private long stopTime;
private long freq;
private long freq_millis;
// Constructor
public TimerWin()
{
startTime = 0;
stopTime = 0;
if( QueryPerformanceFrequency( out freq ) == false )
{
// high-performance counter not supported
throw new Win32Exception();
}
freq_millis = freq / 1000;
}
// Start the timer
public void Start()
{
// lets do the waiting threads there work
//Thread.Sleep(0);
QueryPerformanceCounter( out startTime );
}
// Stop the timer
public void Stop()
{
QueryPerformanceCounter( out stopTime );
}
public double Seconds
{
get
{
long current;
QueryPerformanceCounter( out current );
return (double)( current - startTime ) / freq;
}
}
public long Current
{
get
{
long current;
QueryPerformanceCounter( out current );
return ( current - startTime ) / freq_millis;
}
}
public double Duration
{
get
{
return (double)( stopTime - startTime ) / (double)freq;
}
}
public long DurationMS
{
get { return ( stopTime - startTime ) / freq_millis; }
}
}
}