Daily update on 20250618-051714 by Nitload Youmu. Additional Message : Brief support to collection operation in EXPRESS. A collection type added in core lib and compilestack.

Signed-off-by: Nitload <YoumuLiu_NSI@whv0t.onmicrosoft.com>
This commit is contained in:
Nitload
2025-06-18 05:17:14 +08:00
parent 74c01effe4
commit c624a8ca38
300 changed files with 12227 additions and 4303 deletions
@@ -56,15 +56,16 @@ namespace StgSharp.Commom.Collections
if( _reverse.TryGetValue( key, out TFirst value ) ) {
return value;
}
throw new ArgumentException(
$"Cannot find key {key!.ToString()} in dictionary." );
throw new ArgumentException( $"Cannot find key {key!.ToString()} in dictionary." );
}
set
{
if( _reverse.TryGetValue( key, out TFirst origin ) ) {
if( _reverse.TryGetValue( key, out TFirst origin ) )
{
_reverse[ key ] = value;
_forward.Remove( origin );
} else {
} else
{
_reverse.Add( key, value );
}
_forward.Add( value, key );
@@ -78,15 +79,16 @@ namespace StgSharp.Commom.Collections
if( _forward.TryGetValue( key, out TSecond value ) ) {
return value;
}
throw new ArgumentException(
$"Cannot find key {key!.ToString()} in dictionary." );
throw new ArgumentException( $"Cannot find key {key!.ToString()} in dictionary." );
}
set
{
if( _forward.TryGetValue( key, out TSecond origin ) ) {
if( _forward.TryGetValue( key, out TSecond origin ) )
{
_forward[ key ] = value;
_reverse.Remove( origin );
} else {
} else
{
_forward.Add( key, value );
}
_reverse.Add( value, key );
@@ -109,8 +111,7 @@ namespace StgSharp.Commom.Collections
public void Add( KeyValuePair<TFirst, TSecond> item )
{
if( _forward.ContainsKey( item.Key ) || _reverse.ContainsKey(
item.Value ) ) {
if( _forward.ContainsKey( item.Key ) || _reverse.ContainsKey( item.Value ) ) {
throw new ArgumentException( "Duplicate key or value." );
}
_forward.Add( item.Key, item.Value );
@@ -134,8 +135,9 @@ namespace StgSharp.Commom.Collections
public bool Contains( KeyValuePair<TFirst, TSecond> item )
{
return _forward.Contains( item ) && _reverse.TryGetValue(
item.Value, out TFirst var ) && var!.Equals( item.Key );
return _forward.Contains( item ) &&
_reverse.TryGetValue( item.Value, out TFirst var ) &&
var!.Equals( item.Key );
}
public bool Contains( TSecond key )
@@ -148,9 +150,7 @@ namespace StgSharp.Commom.Collections
return _forward.ContainsKey( key );
}
public void CopyTo(
KeyValuePair<TFirst, TSecond>[] array,
int arrayIndex )
public void CopyTo( KeyValuePair<TFirst, TSecond>[] array, int arrayIndex )
{
if( array == null ) {
throw new ArgumentNullException( nameof( array ) );
@@ -159,8 +159,7 @@ namespace StgSharp.Commom.Collections
throw new ArgumentOutOfRangeException( nameof( arrayIndex ) );
}
if( array.Length - arrayIndex < _forward.Count ) {
throw new ArgumentException(
"The array is too small to copy the elements." );
throw new ArgumentException( "The array is too small to copy the elements." );
}
foreach( KeyValuePair<TFirst, TSecond> pair in _forward ) {
@@ -39,13 +39,17 @@ namespace StgSharp.Commom.Collections
{
public static class CapacityFixedListBuilder
{
internal static CapacityFixedList<T> Create<T>(ReadOnlySpan<T> values)
internal static CapacityFixedList<T> Create<T>( ReadOnlySpan<T> values )
{
return new CapacityFixedList<T>(values);
return new CapacityFixedList<T>( values );
}
}
[CollectionBuilder(typeof(CapacityFixedListBuilder),nameof(CapacityFixedListBuilder.Create))]
[CollectionBuilder(
typeof( CapacityFixedListBuilder ),
nameof( CapacityFixedListBuilder.Create ) )]
public class CapacityFixedList<T> : IList<T>
{
@@ -57,7 +61,7 @@ namespace StgSharp.Commom.Collections
_values = new T[size];
}
public CapacityFixedList(ReadOnlySpan<T> values)
public CapacityFixedList( ReadOnlySpan<T> values )
{
_values = values.ToArray();
}
@@ -65,13 +69,14 @@ namespace StgSharp.Commom.Collections
public T this[ int index ]
{
get => index < _index ?
_values[ index ] : throw new ArgumentOutOfRangeException(
nameof( index ) );
_values[ index ] : throw new ArgumentOutOfRangeException( nameof( index ) );
set
{
if( index < _index ) {
if( index < _index )
{
_values[ index ] = value;
} else {
} else
{
throw new ArgumentOutOfRangeException( nameof( index ) );
}
}
@@ -83,7 +88,8 @@ namespace StgSharp.Commom.Collections
public void Add( T item )
{
if( _index < capacity - 1 ) {
if( _index < capacity - 1 )
{
_index++;
this[ _index ] = item;
}
@@ -97,7 +103,8 @@ namespace StgSharp.Commom.Collections
public bool Contains( T item )
{
for( int i = 0; i <= _index; i++ ) {
for( int i = 0; i <= _index; i++ )
{
if( item.Equals( _values[ i ] ) ) {
return true;
}
@@ -120,7 +127,8 @@ namespace StgSharp.Commom.Collections
public int IndexOf( T item )
{
T v;
for( int i = 0; i <= _index; i++ ) {
for( int i = 0; i <= _index; i++ )
{
if( ( v = _values[ i ] ) != null && v.Equals( item ) ) {
return i;
}
@@ -131,8 +139,10 @@ namespace StgSharp.Commom.Collections
public bool Remove( T item )
{
T v;
for( int i = 0; i <= _index; i++ ) {
if( ( v = _values[ i ] ) != null && v.Equals( item ) ) {
for( int i = 0; i <= _index; i++ )
{
if( ( v = _values[ i ] ) != null && v.Equals( item ) )
{
_values[ i ] = _values[ _index ];
_index--;
return true;
@@ -143,8 +153,10 @@ namespace StgSharp.Commom.Collections
public void RemoveAll( Predicate<T> predicate )
{
for( int i = _index; i > 0; i-- ) {
if( predicate( _values[ i ] ) ) {
for( int i = _index; i > 0; i-- )
{
if( predicate( _values[ i ] ) )
{
_values[ i ] = _values[ _index ];
_index--;
}
@@ -153,7 +165,8 @@ namespace StgSharp.Commom.Collections
public void RemoveAt( int index )
{
if( index <= _index ) {
if( index <= _index )
{
_values[ index ] = _values[ _index ];
_index--;
}
@@ -38,51 +38,39 @@ namespace StgSharp.Commom.Collections
public interface IBidirectionalDictionary<TFirst, TSecond> : IDictionary<TFirst, TSecond>
{
public TFirst this[ TSecond key ]
{
get;
set;
}
public TFirst this[ TSecond key ] { get; set; }
public ICollection<TFirst> FirstIndex
{
get;
}
public ICollection<TFirst> FirstIndex { get; }
public ICollection<TSecond> SecondIndex
{
get;
}
public ICollection<TSecond> SecondIndex { get; }
public IReadOnlyDictionary<TFirst, TSecond> Forward
{
get;
}
public IReadOnlyDictionary<TFirst, TSecond> Forward { get; }
public IReadOnlyDictionary<TSecond, TFirst> Reverse
{
get;
}
public IReadOnlyDictionary<TSecond, TFirst> Reverse { get; }
/// <summary>
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains
/// the specified key.
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />
/// contains the specified key.
/// </summary>
/// <param _name="key"> The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />. </param>
/// <param _label="key">
/// The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />.
/// </param>
/// <returns>
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an element
/// with the specified key; otherwise, false.
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an
/// element with the specified key; otherwise, false.
/// </returns>
public bool Contains( TSecond key );
/// <summary>
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains
/// the specified key.
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />
/// contains the specified key.
/// </summary>
/// <param _name="key"> The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />. </param>
/// <param _label="key">
/// The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />.
/// </param>
/// <returns>
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an element
/// with the specified key; otherwise, false.
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an
/// element with the specified key; otherwise, false.
/// </returns>
public bool Contains( TFirst key );
@@ -93,8 +81,7 @@ namespace StgSharp.Commom.Collections
ICollection<TSecond> IDictionary<TFirst, TSecond>.Values => SecondIndex;
bool IDictionary<TFirst, TSecond>.ContainsKey( TFirst key ) => Contains(
key );
bool IDictionary<TFirst, TSecond>.ContainsKey( TFirst key ) => Contains( key );
#pragma warning restore CA1033
}
}
@@ -36,11 +36,7 @@ namespace StgSharp.Collections
public interface IHashMultiplexer<T> : IEqualityComparer<T>
{
int RemainedMultiplexCount
{
get;
set;
}
int RemainedMultiplexCount { get; set; }
void CacheHash( T obj, int count );
+19 -9
View File
@@ -40,10 +40,12 @@ using System.Xml.Serialization;
namespace StgSharp.Collections
{
/// <summary>
/// Part of a collection. This contains a direct reference to _origin collection, so all change
/// to _origin collection will be reflected in this object.
/// Part of a collection. This contains a direct reference to _origin collection, so all
/// change to _origin collection will be reflected in this object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T">
///
/// </typeparam>
public struct ListSegment<T> : ICollection<T>
{
@@ -56,8 +58,7 @@ namespace StgSharp.Collections
ArgumentNullException.ThrowIfNull( collection );
ArgumentOutOfRangeException.ThrowIfLessThan( begin, 0 );
ArgumentOutOfRangeException.ThrowIfLessThan( length, 0 );
ArgumentOutOfRangeException.ThrowIfLessThan(
begin + length, collection.Count );
ArgumentOutOfRangeException.ThrowIfLessThan( begin + length, collection.Count );
_collection = collection;
_begin = begin;
_length = length;
@@ -68,12 +69,22 @@ namespace StgSharp.Collections
get
{
ArgumentOutOfRangeException.ThrowIfLessThan( indexValue, 0 );
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(
indexValue, _length );
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual( indexValue, _length );
return _collection[ indexValue + _begin ];
}
}
public T this[ Index i ]
{
get
{
int offset = i.IsFromEnd ? _length - i.Value : i.Value;
ArgumentOutOfRangeException.ThrowIfLessThan( offset, 0 );
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual( offset, _length );
return _collection[ offset + _begin ];
}
}
public bool IsReadOnly => true;
public int Count => _length;
@@ -87,8 +98,7 @@ namespace StgSharp.Collections
public void CopyTo( T[] array, int arrayIndex )
{
ArgumentNullException.ThrowIfNull( array );
Span<T> span = CollectionsMarshal.AsSpan<T>( _collection )
.Slice( _begin, _length );
Span<T> span = CollectionsMarshal.AsSpan<T>( _collection ).Slice( _begin, _length );
Span<T> target = new Span<T>( array, arrayIndex, _length );
span.CopyTo( target );
}
@@ -40,17 +40,17 @@ namespace StgSharp.Collections
{
public partial class PartialDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> _source;
private readonly HashSet<TKey> _keys;
private readonly PartialDictionaryValues _values;
public PartialDictionary(
Dictionary<TKey, TValue> source,
TKey[] index )
public PartialDictionary( Dictionary<TKey, TValue> source, TKey[] index )
{
_source = source;
_keys = new HashSet<TKey>( index );
foreach( TKey item in _keys ) {
foreach( TKey item in _keys )
{
if( !_source.ContainsKey( item ) ) {
_source.Add( item, default! );
}
@@ -58,13 +58,12 @@ namespace StgSharp.Collections
_values = new PartialDictionaryValues( this );
}
public PartialDictionary(
Dictionary<TKey, TValue> source,
HashSet<TKey> keys )
public PartialDictionary( Dictionary<TKey, TValue> source, HashSet<TKey> keys )
{
_source = source;
_keys = keys;
foreach( TKey item in _keys ) {
foreach( TKey item in _keys )
{
if( !_source.ContainsKey( item ) ) {
_source.Add( item, default! );
}
@@ -73,20 +72,19 @@ namespace StgSharp.Collections
}
public PartialDictionary(
Dictionary<TKey, TValue> source,
TKey[] index, IHashMultiplexer<TKey> multiplexer
)
Dictionary<TKey, TValue> source,
TKey[] index,
IHashMultiplexer<TKey> multiplexer )
{
_source = source;
_keys = new HashSet<TKey>(index);
foreach (TKey item in _keys)
_keys = new HashSet<TKey>( index );
foreach( TKey item in _keys )
{
if (!_source.ContainsKey(item))
{
_source.Add(item, default!);
if( !_source.ContainsKey( item ) ) {
_source.Add( item, default! );
}
}
_values = new PartialDictionaryValues(this);
_values = new PartialDictionaryValues( this );
}
public TValue this[ TKey key ]
@@ -131,14 +129,14 @@ namespace StgSharp.Collections
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
foreach( TKey item in _keys ) {
yield return new KeyValuePair<TKey, TValue>(
item, _source[ item ] );
yield return new KeyValuePair<TKey, TValue>( item, _source[ item ] );
}
}
public bool TryGetValue( TKey key, out TValue value )
{
if( _keys.Contains( key ) ) {
if( _keys.Contains( key ) )
{
value = _source[ key ];
return true;
}
@@ -146,8 +144,7 @@ namespace StgSharp.Collections
return false;
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(
KeyValuePair<TKey, TValue> item )
void ICollection<KeyValuePair<TKey, TValue>>.Add( KeyValuePair<TKey, TValue> item )
{
return;
}
@@ -157,8 +154,7 @@ namespace StgSharp.Collections
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(
KeyValuePair<TKey, TValue> item )
bool ICollection<KeyValuePair<TKey, TValue>>.Remove( KeyValuePair<TKey, TValue> item )
{
throw new NotSupportedException();
}
@@ -43,8 +43,7 @@ namespace StgSharp.Collections
private readonly PartialDictionary<TKey, TValue> _values;
public PartialDictionaryValues(
PartialDictionary<TKey, TValue> value )
public PartialDictionaryValues( PartialDictionary<TKey, TValue> value )
{
_values = value;
}
@@ -55,7 +54,8 @@ namespace StgSharp.Collections
public bool Contains( TValue item )
{
foreach( KeyValuePair<TKey, TValue> kvp in _values ) {
foreach( KeyValuePair<TKey, TValue> kvp in _values )
{
if( kvp.Value != null && kvp.Value.Equals( item ) ) {
return true;
}
@@ -65,7 +65,8 @@ namespace StgSharp.Collections
public void CopyTo( TValue[] array, int arrayIndex )
{
foreach( KeyValuePair<TKey, TValue> kvp in _values ) {
foreach( KeyValuePair<TKey, TValue> kvp in _values )
{
array[ arrayIndex ] = kvp.Value;
arrayIndex++;
}
@@ -0,0 +1,185 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RandomAccessibleStack.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Collections
{
public class RandomAccessibleStack<T> : IEnumerable<T>
{
private const int DefaultCapacity = 4;
private T[] _array;
private int _size;
private int _version;
/// <summary>
/// Initializes a new instance of the RandomAccessStack class that is empty and has the
/// default initial capacity.
/// </summary>
public RandomAccessibleStack()
{
_array = new T[DefaultCapacity];
}
/// <summary>
/// Initializes a new instance of the RandomAccessStack class that is empty and has the
/// specified initial capacity.
/// </summary>
public RandomAccessibleStack( int capacity )
{
if( capacity < 0 ) {
throw new ArgumentOutOfRangeException(
nameof( capacity ), "Capacity must be non-negative." );
}
_array = new T[capacity];
}
/// <summary>
/// Gets or sets the element at the specified index in the stack (0 = bottom, Count-1 =
/// top).
/// </summary>
public T this[ int index ]
{
get
{
if( index < 0 || index >= _size ) {
throw new ArgumentOutOfRangeException( nameof( index ) );
}
return _array[ index ];
}
/*
set
{
if( index < 0 || index >= _size ) {
throw new ArgumentOutOfRangeException( nameof( index ) );
}
_array[ index ] = value;
_version++;
}
/**/
}
/// <summary>
/// Gets the number of elements contained in the stack.
/// </summary>
public int Count => _size;
/// <summary>
/// Removes all objects from the stack.
/// </summary>
public void Clear()
{
Array.Clear( _array, 0, _size );
_size = 0;
_version++;
}
/// <summary>
/// Returns an enumerator that iterates through the stack from top to bottom. Throws if
/// the stack is modified during iteration.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
int expectedVersion = _version;
for( int i = _size - 1; i >= 0; i-- )
{
if( expectedVersion != _version ) {
throw new InvalidOperationException(
"Collection was modified during enumeration." );
}
yield return _array[ i ];
}
}
/// <summary>
/// Returns the object at the top of the stack without removing it.
/// </summary>
public T Peek()
{
if( _size == 0 ) {
throw new InvalidOperationException( "Stack is empty." );
}
return _array[ _size - 1 ];
}
/// <summary>
/// Removes and returns the object at the top of the stack.
/// </summary>
public T Pop()
{
if( _size == 0 ) {
throw new InvalidOperationException( "Stack is empty." );
}
T item = _array[ --_size ];
_array[ _size ] = default!;
_version++;
return item;
}
/// <summary>
/// Adds an item to the top of the stack.
/// </summary>
public void Push( T item )
{
if( _size == _array.Length ) {
EnsureCapacity( _size + 1 );
}
_array[ _size++ ] = item;
_version++;
}
private void EnsureCapacity( int min )
{
int newCapacity = _array.Length == 0 ? DefaultCapacity : _array.Length * 2;
if( newCapacity < min ) {
newCapacity = min;
}
Array.Resize( ref _array, newCapacity );
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="KeyMultiplexer.cs"
// file="StringHashMultiplexer.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -38,7 +38,7 @@ using System.Threading;
namespace StgSharp.Collections
{
public sealed class StringHashMultiplexer : IHashMultiplexer<string>
public sealed class StringHashMultiplexer : IHashMultiplexer<string>
{
private int _initCount, _remainedCount, _hashCache, _hashLast;
@@ -74,15 +74,15 @@ namespace StgSharp.Collections
{
int hash;
fixed( char* cPtr = obj.AsSpan() ) {
hash = InternalIO.Intrinsic
.city_hash_simplify( cPtr, obj.Length );
hash = InternalIO.Intrinsic.city_hash_simplify( cPtr, obj.Length );
}
return hash;
}
public int GetHashCode( string obj )
{
if( _remainedCount > 0 && ReferenceEquals( _source, obj ) ) {
if( _remainedCount > 0 && ReferenceEquals( _source, obj ) )
{
_remainedCount--;
return _hashCache;
}
@@ -139,8 +139,7 @@ namespace StgSharp.Collections
{
int hash;
fixed( char* cPtr = obj.AsSpan() ) {
hash = InternalIO.Intrinsic
.city_hash_simplify( cPtr, obj.Length );
hash = InternalIO.Intrinsic.city_hash_simplify( cPtr, obj.Length );
}
return hash;
}
@@ -152,7 +151,8 @@ namespace StgSharp.Collections
private void Dispose( bool disposing )
{
if( !disposedValue ) {
if( !disposedValue )
{
if( disposing ) {
_multiplexers.Dispose();
}
@@ -51,17 +51,9 @@ namespace StgSharp.Controls
get => throw new NotImplementedException();
}
public Rectangle BoundingBox
{
get;
set;
}
public Rectangle BoundingBox { get; set; }
public Vec2 Position
{
get;
set;
}
public Vec2 Position { get; set; }
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
@@ -63,22 +63,14 @@ namespace StgSharp.Controls
get => throw new NotSupportedException();
}
public Rectangle BoundingBox
{
get;
set;
}
public Rectangle BoundingBox { get; set; }
public TriggerButton CurrentButton
{
get => current;
}
public Vec2 Position
{
get;
set;
}
public Vec2 Position { get; set; }
protected List<TriggerButton> AllButton
{
@@ -52,16 +52,15 @@ namespace StgSharp.Controls
private PlainGeometryMesh _tittleMesh;
public CharacterLineIndexImage(
int length,
char defaultChar,
PlainGeometryMesh tittleMesh,
IEnumerable<(char, PlainGeometryMesh)> indexEnumeration )
int length,
char defaultChar,
PlainGeometryMesh tittleMesh,
IEnumerable<(char, PlainGeometryMesh)> indexEnumeration )
{
this.length = length;
displayIndex = new char[length];
_tittleMesh = tittleMesh;
texIndex = indexEnumeration.ToDictionary(
item => item.Item1, item => item.Item2 );
texIndex = indexEnumeration.ToDictionary( item => item.Item1, item => item.Item2 );
}
public bool IsEntity
@@ -93,8 +92,8 @@ namespace StgSharp.Controls
}
string result = ( message.Length >= length ) ?
message.Substring( message.Length - displayIndex.Length ) : message.PadLeft(
length, defaultChar );
message.Substring( message.Length - displayIndex.Length ) : message.PadLeft(
length, defaultChar );
displayIndex = result.ToCharArray();
}
@@ -42,27 +42,13 @@ namespace StgSharp.Controls
public interface ControllingItem : IEnumerable<PlainGeometryMesh>
{
public abstract bool IsEntity
{
get;
}
public abstract bool IsEntity { get; }
public abstract ReadOnlySpan<Vec4> TextureBox
{
get;
}
public abstract ReadOnlySpan<Vec4> TextureBox { get; }
public abstract Rectangle BoundingBox
{
get;
set;
}
public abstract Rectangle BoundingBox { get; set; }
public abstract Vec2 Position
{
get;
set;
}
public abstract Vec2 Position { get; set; }
IEnumerator IEnumerable.GetEnumerator()
{
@@ -57,17 +57,9 @@ namespace StgSharp.Controls
get => renderMesh.TextureCoord;
}
public Rectangle BoundingBox
{
get;
set;
}
public Rectangle BoundingBox { get; set; }
public Vec2 Position
{
get;
set;
}
public Vec2 Position { get; set; }
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
@@ -63,17 +63,9 @@ namespace StgSharp.Controls
get => marker.TextureCoord;
}
public Rectangle BoundingBox
{
get;
set;
}
public Rectangle BoundingBox { get; set; }
public Vec2 Position
{
get;
set;
}
public Vec2 Position { get; set; }
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
@@ -41,9 +41,9 @@ using System.Text;
namespace StgSharp.Controls
{
public delegate void RenderButtonTextureCallback(
ButtonStatus status,
float beginTime,
in TextureProvider texture );
ButtonStatus status,
float beginTime,
in TextureProvider texture );
public enum ButtonStatus
{
@@ -106,9 +106,11 @@ namespace StgSharp.Controls
{
add
{
if( _renderButton == null ) {
if( _renderButton == null )
{
_renderButton = value;
} else {
} else
{
_renderButton += value;
}
}
@@ -120,17 +122,9 @@ namespace StgSharp.Controls
}
}
public bool IsHighLighted
{
get;
internal set;
}
public bool IsHighLighted { get; internal set; }
public bool IsDisabled
{
get;
internal set;
}
public bool IsDisabled { get; internal set; }
public bool IsEntity => true;
@@ -139,41 +133,17 @@ namespace StgSharp.Controls
get => MemoryMarshal.Cast<Vec2, Vec4>( _texture.TextureCoordinate );
}
public Rectangle BoundingBox
{
get;
set;
}
public Rectangle BoundingBox { get; set; }
public TriggerButton Left
{
get;
internal set;
}
public TriggerButton Left { get; internal set; }
public TriggerButton Right
{
get;
internal set;
}
public TriggerButton Right { get; internal set; }
public TriggerButton Up
{
get;
internal set;
}
public TriggerButton Up { get; internal set; }
public TriggerButton Down
{
get;
internal set;
}
public TriggerButton Down { get; internal set; }
public Vec2 Position
{
get;
set;
}
public Vec2 Position { get; set; }
internal TextureProvider Texture
{
@@ -181,11 +151,7 @@ namespace StgSharp.Controls
set => _texture = value;
}
protected ButtonStatus CurrentStatus
{
get;
set;
}
protected ButtonStatus CurrentStatus { get; set; }
public void DeHighlight()
{
@@ -209,9 +175,11 @@ namespace StgSharp.Controls
public void Enable()
{
if( CurrentStatus == ButtonStatus.Disable ) {
if( CurrentStatus == ButtonStatus.Disable )
{
CurrentStatus = ButtonStatus.DisableToEnable;
} else {
} else
{
return;
}
if( enableCallback != null ) {
@@ -227,9 +195,11 @@ namespace StgSharp.Controls
public void Highlight()
{
if( CurrentStatus == ButtonStatus.Enable ) {
if( CurrentStatus == ButtonStatus.Enable )
{
CurrentStatus |= ButtonStatus.EnableToHighlight;
} else {
} else
{
return;
}
if( confirmCallback != null ) {
+3 -3
View File
@@ -215,9 +215,9 @@ namespace StgSharp
}
#pragma warning restore CA1707
#pragma warning restore CA1712
#pragma warning restore CA7008
#pragma warning restore CA1707
#pragma warning restore CA1712
#pragma warning restore CA7008
internal enum InputEquipment
{
@@ -37,15 +37,9 @@ namespace StgSharp.Controlling.UsrActivity
public interface IClickTrigger
{
public int TargetKeyOrButtonID
{
get;
}
public int TargetKeyOrButtonID { get; }
public KeyStatus TriggeredStatus
{
get;
}
public KeyStatus TriggeredStatus { get; }
}
}
@@ -70,16 +70,12 @@ namespace StgSharp.Controlling.UsrActivity
return $"Key {_stick} triggered when {_status}";
}
public static bool operator !=(
JoystickTrigger left,
JoystickTrigger right )
public static bool operator !=( JoystickTrigger left, JoystickTrigger right )
{
return !( left == right );
}
public static bool operator ==(
JoystickTrigger left,
JoystickTrigger right )
public static bool operator ==( JoystickTrigger left, JoystickTrigger right )
{
return ( left._status == right._status ) && ( left._stick == right._stick );
}
@@ -73,7 +73,8 @@ namespace StgSharp.Controlling.UsrActivity
public static bool operator ==( KeyTrigger left, KeyTrigger right )
{
return ( left._triggerStat == right._triggerStat ) && ( left._targetKey == right._targetKey );
return ( left._triggerStat == right._triggerStat ) &&
( left._targetKey == right._targetKey );
}
bool IEquatable<KeyTrigger>.Equals( KeyTrigger other )
@@ -49,42 +49,31 @@ namespace StgSharp.Controlling.UsrActivity
private static KeyTrigger keyboardtemp;
private static MouseTrigger mousetemp;
public static JoystickTrigger BuildJoystickClickTrigger(
int keyCode,
KeyStatus status )
public static JoystickTrigger BuildJoystickClickTrigger( int keyCode, KeyStatus status )
{
if( keyCode > MouseMin && keyCode < MouseMax ) {
return new JoystickTrigger( ( Joystick )keyCode, status );
}
throw new InvalidOperationException(
"Known key code or key is not on joystick." );
throw new InvalidOperationException( "Known key code or key is not on joystick." );
}
public static KeyTrigger BuildKeyboardClickTrigger(
int keyCode,
KeyStatus status )
public static KeyTrigger BuildKeyboardClickTrigger( int keyCode, KeyStatus status )
{
if( keyCode > KeyboardMin && keyCode < KeyboardMax ) {
return new KeyTrigger( ( KeyboardKey )keyCode, status );
}
throw new InvalidOperationException(
"Known key code or kay is not on keyboard." );
throw new InvalidOperationException( "Known key code or kay is not on keyboard." );
}
public static MouseTrigger BuildMouseClickTrigger(
int keyCode,
KeyStatus status )
public static MouseTrigger BuildMouseClickTrigger( int keyCode, KeyStatus status )
{
if( keyCode >= MouseMin && keyCode <= MouseMax ) {
return new MouseTrigger( ( Mouse )keyCode, status );
}
throw new InvalidOperationException(
"Known key code or key is not on mouse." );
throw new InvalidOperationException( "Known key code or key is not on mouse." );
}
public static IClickTrigger BuildTrigger(
int keyCode,
KeyStatus status )
public static IClickTrigger BuildTrigger( int keyCode, KeyStatus status )
{
if( keyCode > KeyboardMin && keyCode < KeyboardMax ) {
return new KeyTrigger( ( KeyboardKey )keyCode, status );
+1 -1
View File
@@ -38,7 +38,7 @@ using System.Threading.Tasks;
namespace StgSharp
{
public static unsafe partial class StgSharp
public static unsafe partial class World
{
private static byte leastUnusedArea;
+3 -3
View File
@@ -39,9 +39,9 @@ using System.Threading.Tasks;
namespace StgSharp.Internal
{
/// <summary>
/// An independent storage area, used as the only folder type in root folder. Contains several
/// <see cref="SSD" /> files reference as virtual disc. Data is actually stored in <see
/// cref="SSD" />s in certain RAID mode.
/// An independent storage area, used as the only folder type in root folder. Contains several
/// <see cref="SSD" /> files reference as virtual disc. Data is actually stored in <see
/// cref="SSD" />s in certain RAID mode.
/// </summary>
public partial class Area { }
}
+2 -1
View File
@@ -66,7 +66,8 @@ namespace StgSharp.Internal
public unsafe byte[] GetBytes()
{
byte[] ret = new byte[16];
fixed( M128* vptr = &data ) {
fixed( M128* vptr = &data )
{
byte* bptr = ( byte* )vptr;
for( int i = 0; i < 15; i++ ) {
ret[ i ] = *bptr;
+24 -19
View File
@@ -44,12 +44,11 @@ using System.Threading.Tasks;
namespace StgSharp.Internal
{
[StructLayout( LayoutKind.Explicit, Size = StgSharp.ssdSegmentLength * 16 )]
[StructLayout( LayoutKind.Explicit, Size = World.ssdSegmentLength * 16 )]
public unsafe struct SSDSegment : IComparable<int>, IComparable<SSDSegment>
{
[FieldOffset( 16 )] public fixed byte Data[
16 * ( StgSharp.ssdSegmentLength - 1 ) ];
[FieldOffset( 16 )] public fixed byte Data[ 16 * ( World.ssdSegmentLength - 1 ) ];
[FieldOffset( 12 )] public int DataHash;
[FieldOffset( 8 )] public int PreviousHash;
[FieldOffset( 0 * 16 )] public SSDSegmentHead Head;
@@ -63,7 +62,7 @@ namespace StgSharp.Internal
{
get
{
if( index > ( 16 * ( StgSharp.ssdSegmentLength - 1 ) ) - 1 ) {
if( index > ( 16 * ( World.ssdSegmentLength - 1 ) ) - 1 ) {
throw new IndexOutOfRangeException();
}
return Data[ index ];
@@ -71,7 +70,7 @@ namespace StgSharp.Internal
set
{
if( index > ( 16 * ( StgSharp.ssdSegmentLength - 1 ) ) - 1 ) {
if( index > ( 16 * ( World.ssdSegmentLength - 1 ) ) - 1 ) {
throw new IndexOutOfRangeException();
}
Data[ index ] = value;
@@ -98,15 +97,15 @@ namespace StgSharp.Internal
public static SSDSegment FromStream( byte[] stream )
{
if( stream.Length != 16 * StgSharp.ssdSegmentLength ) {
if( stream.Length != 16 * World.ssdSegmentLength ) {
throw new ArgumentException();
}
SSDSegment ret = new SSDSegment();
fixed( byte* bptr = stream ) {
fixed( byte* bptr = stream )
{
ret.Head.data = *( M128* )bptr;
for( int i = 1; i < StgSharp.ssdSegmentLength; i++ ) {
ret.WriteData<M128>(
i - 1, *( M128* )( bptr + ( 16 * i ) ) );
for( int i = 1; i < World.ssdSegmentLength; i++ ) {
ret.WriteData<M128>( i - 1, *( M128* )( bptr + ( 16 * i ) ) );
}
}
return ret;
@@ -114,9 +113,11 @@ namespace StgSharp.Internal
public byte[] GetBytes()
{
byte[] ret = new byte[16 * StgSharp.ssdSegmentLength];
fixed( M128* mptr = &Head.data ) {
fixed( byte* aptr = ret ) {
byte[] ret = new byte[16 * World.ssdSegmentLength];
fixed( M128* mptr = &Head.data )
{
fixed( byte* aptr = ret )
{
Vector4* vsptr = ( Vector4* )mptr;
Vector4* vtptr = ( Vector4* )aptr;
for( int i = 0; i < 18; i++ ) {
@@ -131,9 +132,10 @@ namespace StgSharp.Internal
public int GetDataHash()
{
Vector4 v = Vector4.One;
fixed( M128* mptr = &Head.data ) {
fixed( M128* mptr = &Head.data )
{
Vector4* vptr = ( Vector4* )mptr;
for( int i = 0; i < StgSharp.ssdSegmentLength - 1; i += 1 ) {
for( int i = 0; i < World.ssdSegmentLength - 1; i += 1 ) {
v += ( *vptr ) * 31;
}
}
@@ -145,9 +147,10 @@ namespace StgSharp.Internal
public override int GetHashCode()
{
int ret = 17;
fixed( M128* mptr = &Head.data ) {
fixed( M128* mptr = &Head.data )
{
Vector4* vptr = ( Vector4* )mptr;
for( int i = 0; i < StgSharp.ssdSegmentLength; i++ ) {
for( int i = 0; i < World.ssdSegmentLength; i++ ) {
ret = ( ret + ( *vptr ).GetHashCode() ) * 31;
}
}
@@ -156,7 +159,8 @@ namespace StgSharp.Internal
public unsafe T ReadData<T>( int index ) where T: struct
{
fixed( byte* bptr = Data ) {
fixed( byte* bptr = Data )
{
T* tptr = ( T* )bptr;
return *( tptr + index );
}
@@ -164,7 +168,8 @@ namespace StgSharp.Internal
public unsafe void WriteData<T>( int index, T value ) where T: struct
{
fixed( byte* bptr = Data ) {
fixed( byte* bptr = Data )
{
T* tptr = ( T* )bptr;
*( tptr + index ) = value;
}
+1 -2
View File
@@ -58,8 +58,7 @@ namespace StgSharp.Internal
public static SSD FromFile( string fileRoute )
{
return new SSD(
new FileStream( fileRoute, FileMode.Open, FileAccess.Read ) )
return new SSD( new FileStream( fileRoute, FileMode.Open, FileAccess.Read ) )
{
};
}
+2 -10
View File
@@ -60,17 +60,9 @@ namespace StgSharp.Internal.FileIO
streamSource.Read( data.AsSpan() );
}
public SSDrawHead Head
{
get;
set;
}
public SSDrawHead Head { get; set; }
public string Name
{
get;
set;
}
public string Name { get; set; }
}
+1 -1
View File
@@ -35,7 +35,7 @@ using System.Text;
namespace StgSharp.Internal
{
/// <summary>
/// A class contains a sets of methods to serialize several types
/// A class contains a sets of methods to serialize several types
/// </summary>
public static partial class Serializer { }
}
@@ -39,10 +39,7 @@ namespace StgSharp.Internal
public interface ISSDSerializable
{
public SerializableTypeCode SSDTypeCode
{
get;
}
public SerializableTypeCode SSDTypeCode { get; }
public byte[] GetBytes();
@@ -68,8 +65,7 @@ namespace StgSharp.Internal
public static partial class Serializer
{
public static T Deserialize<T>( byte[] stream )
where T: ISSDSerializable
public static T Deserialize<T>( byte[] stream ) where T: ISSDSerializable
{
T serializableObject = Activator.CreateInstance<T>();
serializableObject.FromBytes( stream );
@@ -78,7 +74,8 @@ namespace StgSharp.Internal
public static string GetNameTail( SerializableTypeCode typeCode )
{
switch( typeCode ) {
switch( typeCode )
{
case SerializableTypeCode.IndexTable:
return "_idt";
case SerializableTypeCode.PixelImage:
+9 -16
View File
@@ -41,13 +41,9 @@ namespace StgSharp.Data
public interface IValueBox
{
ref object ValueReference
{
get;
}
ref object ValueReference { get; }
static virtual IValueBox<T> AsGeneric<T>( IValueBox box )
where T: struct
static virtual IValueBox<T> AsGeneric<T>( IValueBox box ) where T: struct
{
if( box is not IValueBox<T> genericBox ) {
return null;
@@ -65,19 +61,17 @@ namespace StgSharp.Data
public interface IValueBox<T> where T: struct
{
T Value
{
get;
set;
}
T Value { get; set; }
}
/// <summary>
/// A class attempt to reduce cost of boxing, though still a bit slower than direct access to
/// _origin value type instance.
/// A class attempt to reduce cost of boxing, though still a bit slower than direct access to
/// _origin value type instance.
/// </summary>
/// <typeparam name="T"> Type of instance to be boxed. </typeparam>
/// <typeparam name="T">
/// Type of instance to be boxed.
/// </typeparam>
public class ValueBox<T> : IValueBox, IValueBox<T> where T: struct
{
@@ -88,8 +82,7 @@ namespace StgSharp.Data
_value = value;
}
public ref object ValueReference => ref Unsafe.As<T, object>(
ref _value );
public ref object ValueReference => ref Unsafe.As<T, object>( ref _value );
public T Value
{
+3 -16
View File
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
namespace StgSharp.Entities
{
public class Enemy : IEntity
@@ -39,23 +38,11 @@ namespace StgSharp.Entities
internal Launcher<EntityPartical> _dieBulletLauncher;
public bool _selectalbe;
public Launcher<EntityPartical> AwardLauncher
{
get;
set;
}
public Launcher<EntityPartical> AwardLauncher { get; set; }
public Launcher<EntityPartical> CommonBulletLauncher
{
get;
set;
}
public Launcher<EntityPartical> CommonBulletLauncher { get; set; }
public Launcher<EntityPartical> DieBulletLauncher
{
get;
set;
}
public Launcher<EntityPartical> DieBulletLauncher { get; set; }
public override void OnRenderFrame()
{
+10 -25
View File
@@ -42,29 +42,21 @@ namespace StgSharp
protected uint _bornTick;
internal Func<int, Vec3> _movHandler;
internal LinkedList<PlainGeometry> _collisionBox;
internal PlainGeometryCollisionSensor<PlainGeometry, PlainGeometry> _collisionSensor;
internal Point _basePoint;
internal Point _pos;
internal Point _position;
internal PlainGeometryCollisionSensor<PlainGeometry, PlainGeometry> _collisionSensor;
internal string _texture;
/// <summary>
/// X position of an enenmy entity
/// X position of an enenmy entity
/// </summary>
public float X
{
get;
set;
}
public float X { get; set; }
/// <summary>
/// Y position of an enemy entity
/// Y position of an enemy entity
/// </summary>
public float Y
{
get;
set;
}
public float Y { get; set; }
public LinkedList<PlainGeometry> CollisionBox
{
@@ -73,7 +65,7 @@ namespace StgSharp
}
/// <summary>
/// A sensor used for checking out if a bullet hit a player or something else
/// A sensor used for checking out if a bullet hit a player or something else
/// </summary>
public PlainGeometryCollisionSensor<PlainGeometry, PlainGeometry> CollisionSensor
{
@@ -81,20 +73,13 @@ namespace StgSharp
set => _collisionSensor = value;
}
public string TextureGL
{
get;
set;
}
public string TextureGL { get; set; }
/// <summary>
/// A 2D vector presenting the position of an enemy entity, position can also be visited by
/// X, Y
/// A 2D vector presenting the position of an enemy entity, position can also be visited
/// by X, Y
/// </summary>
public Vec2 Location
{
get;
}
public Vec2 Location { get; }
public abstract void OnRenderFrame();
+45 -51
View File
@@ -46,59 +46,45 @@ namespace StgSharp
private static Process? _dialogueProcess;
private static AnonymousPipeServerStream _dialogueClientPipe,_dialogueServerPipe;
private static ConcurrentBag<string> msgCache = new ConcurrentBag<string>(
);
private static ConcurrentBag<string> msgCache = new ConcurrentBag<string>();
private static int _readAndWriteThreadId;
private static ProcessStartInfo _dialogueProcessInfo;
private static StreamReader _dr;
private static StreamWriter _dw;
public static bool NeedShowWhenStartup
public static bool NeedShowWhenStartup { get; set; }
public static void PostError( Exception ex )
{
get;
set;
CreateDialogueProcessIfNotExist();
_dw.WriteLine( $"posterror {ex.Message}" );
_dialogueProcess!.Exited -= DialogueProcessExitCallback;
}
public static void SetReadAndWriteThread(Thread thread)
public static void SetReadAndWriteThread( Thread thread )
{
_readAndWriteThreadId = thread.ManagedThreadId;
}
private static void AssertThread()
{
if (_readAndWriteThreadId != Environment.CurrentManagedThreadId)
{
throw new InvalidOperationException("Communication with dialogue can only call from certain thread.");
}
}
internal static void CreateDialogueProcessIfNotExist()
{
if( _dialogueProcess != null ) {
return;
}
if (!File.Exists(_dialogueProcessInfo.FileName))
{
}
if( !File.Exists( _dialogueProcessInfo.FileName ) ) { }
_dialogueProcess = Process.Start( _dialogueProcessInfo );
_dr = new StreamReader(_dialogueClientPipe);
_dw = new StreamWriter(_dialogueServerPipe);
_dr = new StreamReader( _dialogueClientPipe );
_dw = new StreamWriter( _dialogueServerPipe );
_dialogueProcess!.Exited += DialogueProcessExitCallback;
_dialogueProcess!.Exited += DialogueProcessExitCallback;
_dialogueServerPipe.DisposeLocalCopyOfClientHandle();
_dialogueClientPipe.DisposeLocalCopyOfClientHandle();
}
private static void DialogueProcessExitCallback(object? sender, EventArgs e)
{
_dialogueProcess = null;
_dr.Close();
_dw.Close();
}
internal static void LoadDialogue()
{
_dialogueServerPipe = new AnonymousPipeServerStream(
@@ -106,21 +92,25 @@ namespace StgSharp
_dialogueClientPipe = new AnonymousPipeServerStream(
PipeDirection.In, HandleInheritability.Inheritable );
string route = Assembly.GetAssembly( typeof( StgSharp ) ).Location;
string route = Assembly.GetAssembly( typeof( World ) ).Location;
string path = Path.GetDirectoryName( route );
string exeName;
if( RuntimeInformation.IsOSPlatform( OSPlatform.Windows ) ) {
if( RuntimeInformation.IsOSPlatform( OSPlatform.Windows ) )
{
exeName = ".exe";
} else if( RuntimeInformation.IsOSPlatform( OSPlatform.Linux ) || RuntimeInformation.IsOSPlatform(
OSPlatform.OSX ) ) {
} else if( RuntimeInformation.IsOSPlatform( OSPlatform.Linux ) ||
RuntimeInformation.IsOSPlatform( OSPlatform.OSX ) )
{
exeName = string.Empty;
} else {
} else
{
throw new PlatformNotSupportedException( "Unknown OS platform" );
}
string consoleRoute = Path.Combine(path, @"StgSharpTerminalDialogue", $@"StgSharpTerminalDialogue{exeName}");
string consoleRoute = Path.Combine(
path, @"StgSharpTerminalDialogue", $@"StgSharpTerminalDialogue{exeName}" );
_dialogueProcessInfo = new ProcessStartInfo
{
@@ -129,26 +119,13 @@ namespace StgSharp
UseShellExecute = true,
RedirectStandardOutput = false,
};
}
internal static void PostMessage(
string instruction,
params string[] operands)
internal static void PostMessage( string instruction, params string[] operands )
{
CreateDialogueProcessIfNotExist();
_dw.WriteLine($"{instruction} {operands}");
}
public static void PostError(Exception ex)
{
CreateDialogueProcessIfNotExist();
_dw.WriteLine($"posterror {ex.Message}");
_dialogueProcess!.Exited -= DialogueProcessExitCallback;
_dw.WriteLine( $"{instruction} {operands}" );
}
internal static void UnloadDialogue()
@@ -169,10 +146,12 @@ namespace StgSharp
}
string temp = string .Empty;
do {
do
{
temp = _dr.ReadLine();
temp = temp ?? string.Empty;
if( !temp!.StartsWith( target ) ) {
if( !temp!.StartsWith( target ) )
{
break;
}
} while (true);
@@ -181,5 +160,20 @@ namespace StgSharp
return index != -1 ? temp.Substring( index + 1 ) : string.Empty;
}
private static void AssertThread()
{
if( _readAndWriteThreadId != Environment.CurrentManagedThreadId ) {
throw new InvalidOperationException(
"Communication with dialogue can only call from certain thread." );
}
}
private static void DialogueProcessExitCallback( object? sender, EventArgs e )
{
_dialogueProcess = null;
_dr.Close();
_dw.Close();
}
}
}
+3 -3
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GlobalSetting.cs"
// Project: StgSharp
// Project: World
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -39,7 +39,7 @@ using System.Threading.Tasks;
namespace StgSharp
{
public static unsafe partial class StgSharp
public static unsafe partial class World
{
internal const int ssdSegmentLength = 16;
@@ -74,7 +74,7 @@ namespace StgSharp
/// <summary>
/// CustomizeInit an instance of OpenGL program, This method should be called before any
/// other StgSharp api.
/// other World api.
/// </summary>
public static void InitGL( int majorVersion, int minorVersion )
{
+4 -4
View File
@@ -39,7 +39,7 @@ using System.Threading.Tasks;
namespace StgSharp
{
public static partial class StgSharp
public static partial class World
{
private static unsafe IntPtr[] monitorsArray;
@@ -48,12 +48,12 @@ namespace StgSharp
{
get
{
if( monitorsArray == null ) {
if( monitorsArray == null )
{
int count = 0;
IntPtr* arrayhandle = InternalIO.glfwGetMonitors( &count );
monitorsArray = new IntPtr[count];
Marshal.Copy(
( IntPtr )arrayhandle, monitorsArray, 0, count );
Marshal.Copy( ( IntPtr )arrayhandle, monitorsArray, 0, count );
Marshal.FreeHGlobal( ( IntPtr )arrayhandle );
}
return monitorsArray;
+30 -27
View File
@@ -28,11 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// using StgSharp.Envitronment;
// using StgSharp.Envitronment.Win32;
// using StgSharp.Graphics;
// using StgSharp.Math;
using StgSharp.Internal;
using StgSharp.Internal.Intrinsic;
@@ -71,12 +66,12 @@ namespace StgSharp
}
public static partial class StgSharp
public static partial class World
{
/// <summary>
/// Version of current StgSharp platform. Main version represent in hundred's digit, and sub
/// version represent in ten's digit.
/// Version of current World platform. Main version represent in hundred's digit, and sub
/// version represent in ten's digit.
/// </summary>
public const long version = 430;
@@ -92,8 +87,7 @@ namespace StgSharp
InternalIO.glfwInit();
InternalIO.InternalAppendLog( "\n\n\n" );
InternalIO.InternalWriteLog(
$"Program {Assembly.GetEntryAssembly()!.FullName} Started.",
LogType.Info );
$"Program {Assembly.GetEntryAssembly()!.FullName} Started.", LogType.Info );
_mainThreadID = Environment.CurrentManagedThreadId;
@@ -122,8 +116,7 @@ namespace StgSharp
public static void LogWarning( Exception notVerySeriesException )
{
InternalIO.InternalWriteLog(
notVerySeriesException.Message, LogType.Warning );
InternalIO.InternalWriteLog( notVerySeriesException.Message, LogType.Warning );
}
public static void Mark( bool needConsole )
@@ -142,12 +135,12 @@ namespace StgSharp
}
public static void Track(
object target,
string message,
bool isConsole,
[CallerFilePath] string filePath = "",
[CallerMemberName] string callerName = "",
[CallerLineNumber] int lineNumber = 0 )
object target,
string message,
bool isConsole,
[CallerFilePath] string filePath = "",
[CallerMemberName] string callerName = "",
[CallerLineNumber] int lineNumber = 0 )
{
Type t = target.GetType();
string log = $"Tracked object: {nameof(target)}\t\tType:{t.Name}\n";
@@ -159,18 +152,24 @@ namespace StgSharp
}
log += $"Tracking at:\n{filePath}\t{callerName}\tline {lineNumber}\n";
log += $"Additional information:\n{message}\n";
if( isConsole ) {
if( isConsole )
{
Console.WriteLine( log );
} else {
} else
{
InternalIO.InternalWriteLog( log, LogType.Info );
}
}
/// <summary>
/// Write a log message to log file, and mark the _level of this message.
/// Write a log message to log file, and mark the _level of this message.
/// </summary>
/// <param _name="message"> A string contains information of how current evironment runs. </param>
/// <param _name="logType"> The severity of current message. </param>
/// <param _label="message">
/// A string contains information of how current evironment runs.
/// </param>
/// <param _label="logType">
/// The severity of current message.
/// </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void WriteLog( string message, LogType logType )
{
@@ -183,10 +182,12 @@ namespace StgSharp
throw new InvalidCastException(
"Failed to convert api, the function pointer is zero." );
}
try {
try
{
return Marshal.GetDelegateForFunctionPointer<TDele>( funcPtr );
}
catch( Exception ) {
catch( Exception )
{
throw;
}
}
@@ -197,10 +198,12 @@ namespace StgSharp
throw new InvalidCastException(
"Failed to convert api, the function pointer is zero." );
}
try {
try
{
return Marshal.GetDelegateForFunctionPointer( funcPtr, T );
}
catch( Exception ) {
catch( Exception )
{
throw;
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ using System.Threading.Tasks;
namespace StgSharp
{
public static partial class StgSharp
public static partial class World
{
private static ConcurrentDictionary<int, KeyStatus> keyListener
@@ -41,22 +41,16 @@ namespace StgSharp.Geometries
{
private static PlainCoordinate statndardPlainCoordination = new PlainCoordinate(
null, new Point( 0, 0, 0 ), new Vec3( 1, 0, 0 ),
new Vec3( 0, 1, 0 ) );
null, new Point( 0, 0, 0 ), new Vec3( 1, 0, 0 ), new Vec3( 0, 1, 0 ) );
public PlainCoordinate(
CoordinationBase local,
Point origin,
Vec3 xAxis,
Vec3 yAxis )
public PlainCoordinate( CoordinationBase local, Point origin, Vec3 xAxis, Vec3 yAxis )
: base( local )
{
CoordMat = Matrix44.Unit;
CoordMat.colum0 = new Vec4( xAxis, 0 );
CoordMat.colum1 = new Vec4( yAxis, 0 );
CoordMat.colum2 = new Vec4(
Linear.Normalize( Vec3.Cross( xAxis, yAxis ) ), 0 );
CoordMat.colum2 = new Vec4( Linear.Normalize( Vec3.Cross( xAxis, yAxis ) ), 0 );
LocalOrigin = origin;
}
@@ -40,11 +40,11 @@ namespace StgSharp.Geometries
{
public SpaceCoordinate(
CoordinationBase localCoordination,
Point origin,
Vec3 xAxis,
Vec3 yAxis,
Vec3 zAxis )
CoordinationBase localCoordination,
Point origin,
Vec3 xAxis,
Vec3 yAxis,
Vec3 zAxis )
: base( localCoordination ) { }
}
+4 -10
View File
@@ -36,31 +36,25 @@ namespace StgSharp.Geometries
public unsafe class ToUpperDimensionException : Exception
{
protected ToUpperDimensionException(
SerializationInfo info,
StreamingContext context )
protected ToUpperDimensionException( SerializationInfo info, StreamingContext context )
: base( info, context ) { }
public ToUpperDimensionException() { }
public ToUpperDimensionException( string message ) : base( message ) { }
public ToUpperDimensionException(
string message,
Exception innerException )
public ToUpperDimensionException( string message, Exception innerException )
: base( message, innerException ) { }
}
/// <summary>
/// 当几何体调用了过多的CalcVec方法时,产生UnusedVertexException异常
/// 当几何体调用了过多的CalcVec方法时,产生UnusedVertexException异常
/// </summary>
public class UnusedVertexException : Exception
{
protected UnusedVertexException(
SerializationInfo info,
StreamingContext context )
protected UnusedVertexException( SerializationInfo info, StreamingContext context )
: base( info, context ) { }
public UnusedVertexException() { }
@@ -40,9 +40,7 @@ using System.Text;
namespace StgSharp.Geometries
{
[UnmanagedFunctionPointer( CallingConvention.Cdecl )]
public delegate Vec3 GeometryMotionDelegate(
TimeSpanProvider timeSource,
out float rotation );
public delegate Vec3 GeometryMotionDelegate( TimeSpanProvider timeSource, out float rotation );
public class GeometryMotion
{
@@ -54,20 +52,23 @@ namespace StgSharp.Geometries
private TimeSpanProvider time;
public unsafe GeometryMotion(
bool isIncreament,
TimeSpanProvider timeSource,
GeometryMotionDelegate motionDelegate )
bool isIncreament,
TimeSpanProvider timeSource,
GeometryMotionDelegate motionDelegate )
{
isIncrementMode = isIncreament;
time = timeSource;
if( motionDelegate == null ) {
if( motionDelegate == null )
{
handle = ( IntPtr )( delegate*<TimeSpanProvider, out float, Vec3> )&defaultMotion;
movement = defaultMotion;
} else if( motionDelegate.Method.IsStatic ) {
} else if( motionDelegate.Method.IsStatic )
{
sourceIsStatic = true;
handle = Marshal.GetFunctionPointerForDelegate( motionDelegate );
movement = motionDelegate;
} else {
} else
{
movement = motionDelegate;
}
@@ -88,25 +89,27 @@ namespace StgSharp.Geometries
{
float rot;
Vec3 vec;
if( sourceIsStatic ) {
if( sourceIsStatic )
{
vec = ( ( delegate* unmanaged[Cdecl]<TimeSpanProvider, out float, Vec3> )handle )(
time, out rot );
} else {
} else
{
vec = movement( time, out rot );
}
if( isIncrementMode ) {
if( isIncrementMode )
{
coord += vec;
rotation += rot;
} else {
} else
{
coord = vec;
rotation = rot;
}
}
private static Vec3 defaultMotion(
TimeSpanProvider provider,
out float rotation )
private static Vec3 defaultMotion( TimeSpanProvider provider, out float rotation )
{
rotation = 0;
return Vec3.Zero;
+6 -21
View File
@@ -42,33 +42,18 @@ namespace StgSharp.Geometries
public interface IGeometry
{
public Point this[ int index ]
{
get;
set;
}
public Point this[ int index ] { get; set; }
#pragma warning disable CA1819
public Vec4[] VertexStream
#pragma warning restore CA1819
{
get;
}
#pragma warning restore CA1819
{ get; }
public CoordinationBase Coordination
{
get;
}
public CoordinationBase Coordination { get; }
public int VertexCount
{
get;
}
public int VertexCount { get; }
public ReadOnlySpan<int> VertexIndices
{
get;
}
public ReadOnlySpan<int> VertexIndices { get; }
}
}
+17 -41
View File
@@ -43,53 +43,29 @@ namespace StgSharp.Geometries
public interface IInstancing
{
public float Rotation
{
get { return GlobalBuffer.CoordAndRotationList[ BufferId ].W; }
set
{
Vec4 temp = GlobalBuffer.CoordAndRotationList[ BufferId ];
temp.W = value;
GlobalBuffer.CoordAndRotationList[ BufferId ] = temp;
}
}
public float Rotation { get { return GlobalBuffer.CoordAndRotationList[ BufferId ].W; } set
{
Vec4 temp = GlobalBuffer.CoordAndRotationList[
BufferId ];
temp.W = value;
GlobalBuffer.CoordAndRotationList[
BufferId ] = temp;
} }
public float Scale
{
get { return GlobalBuffer.ScalingList[ BufferId ]; }
set { GlobalBuffer.ScalingList[ BufferId ] = value; }
}
public float Scale { get { return GlobalBuffer.ScalingList[ BufferId ]; } set { GlobalBuffer.ScalingList[
BufferId ] = value; } }
public GeometryMotion Motion
{
get;
set;
}
public GeometryMotion Motion { get; set; }
public IInstancingBuffer GlobalBuffer
{
get;
internal set;
}
public IInstancingBuffer GlobalBuffer { get; internal set; }
public int BufferId
{
get;
internal set;
}
public int BufferId { get; internal set; }
public Vec3 CenterPositionGlobal
{
get;
internal set;
}
public Vec3 CenterPositionGlobal { get; internal set; }
public Vec3 Coord
{
get { return GlobalBuffer.CoordAndRotationList[ BufferId ].XYZ; }
set { GlobalBuffer.CoordAndRotationList[ BufferId ] = new Vec4(
value.reg ); }
}
public Vec3 Coord { get { return GlobalBuffer.CoordAndRotationList[ BufferId ].XYZ; } set { GlobalBuffer.CoordAndRotationList[
BufferId ] = new Vec4(
value.reg ); } }
public void Move()
{
@@ -39,35 +39,17 @@ namespace StgSharp.Geometries
public interface IInstancingBuffer
{
public Span<Vec4> CoordAndRotationSpan
{
get;
}
public Span<Vec4> CoordAndRotationSpan { get; }
public Span<float> ScalingSpan
{
get;
}
public Span<float> ScalingSpan { get; }
internal IGeometry TypicalShape
{
get;
}
internal IGeometry TypicalShape { get; }
internal List<IInstancing> InstanceList
{
get;
}
internal List<IInstancing> InstanceList { get; }
internal List<Vec4> CoordAndRotationList
{
get;
}
internal List<Vec4> CoordAndRotationList { get; }
internal List<float> ScalingList
{
get;
}
internal List<float> ScalingList { get; }
}
}
@@ -47,14 +47,11 @@ namespace StgSharp.Geometries
internal Matrix32 axis;
/// <summary>
/// The _origin of this coordinate.
/// The _origin of this coordinate.
/// </summary>
public Vec3 origin;
public PartialPlainCoordinate(
Vec3 origin,
Vec3 horiziontial,
Vec3 vertical )
public PartialPlainCoordinate( Vec3 origin, Vec3 horiziontial, Vec3 vertical )
{
this.origin = origin;
axis = new Matrix32();
@@ -66,12 +63,12 @@ namespace StgSharp.Geometries
}
/// <summary>
/// The horizontial axis of the coordinate. Point to the right direction.
/// The horizontial axis of the coordinate. Point to the right direction.
/// </summary>
public Vec3 axis_H => axis.colum0;
/// <summary>
/// The vertical axis of the coordinate. Point to the top direction.
/// The vertical axis of the coordinate. Point to the top direction.
/// </summary>
public Vec3 axis_V => axis.colum1;
@@ -41,11 +41,7 @@ namespace StgSharp.Geometries
public interface IPlainEntity
{
public Vec2 CenterPosition
{
get;
set;
}
public Vec2 CenterPosition { get; set; }
public bool CollideWith( IPlainEntity entity );
@@ -53,29 +53,13 @@ namespace StgSharp.Geometries
( ( IInstancingBuffer )buffer ).InstanceList.Add( this );
}
public GeometryMotion Motion
{
get;
set;
}
public GeometryMotion Motion { get; set; }
public IInstancingBuffer GlobalBuffer
{
get;
set;
}
public IInstancingBuffer GlobalBuffer { get; set; }
public int BufferId
{
get;
set;
}
public int BufferId { get; set; }
Vec3 IInstancing.CenterPositionGlobal
{
get;
set;
}
Vec3 IInstancing.CenterPositionGlobal { get; set; }
bool IPlainEntity.CollideWith( IPlainEntity entity )
{
@@ -37,7 +37,7 @@ using System.ComponentModel;
namespace StgSharp.Geometries
{
/// <summary>
/// Plain geometry only contains straight sides.
/// Plain geometry only contains straight sides.
/// </summary>
public abstract class PlainGeometry : IGeometry
{
@@ -58,10 +58,7 @@ namespace StgSharp.Geometries
public int VertexCount => this.vertexMat.Length;
public abstract ReadOnlySpan<int> VertexIndices
{
get;
}
public abstract ReadOnlySpan<int> VertexIndices { get; }
#pragma warning disable CA1819
public Vec4[] VertexStream => vertexMat;
@@ -85,12 +85,12 @@ namespace StgSharp.Geometries
{
get
{
if( coordArray.Length != coordList.Capacity ) {
if( coordArray.Length != coordList.Capacity )
{
FieldInfo fieldInfo = typeof( List<Vec4> ).
GetField(
"_items",
BindingFlags.NonPublic | BindingFlags.Instance );
if( fieldInfo == null ) {
GetField( "_items", BindingFlags.NonPublic | BindingFlags.Instance );
if( fieldInfo == null )
{
#pragma warning disable CA1065
#pragma warning disable CA2201
throw new NullReferenceException();
@@ -107,12 +107,12 @@ namespace StgSharp.Geometries
{
get
{
if( scaleArray.Length != coordList.Capacity ) {
if( scaleArray.Length != coordList.Capacity )
{
FieldInfo fieldInfo = typeof( List<float> ).
GetField(
"_items",
BindingFlags.NonPublic | BindingFlags.Instance );
if( fieldInfo == null ) {
GetField( "_items", BindingFlags.NonPublic | BindingFlags.Instance );
if( fieldInfo == null )
{
#pragma warning disable CA1065
#pragma warning disable CA2201
throw new NullReferenceException();
@@ -167,8 +167,7 @@ namespace StgSharp.Geometries
temp.BufferId = instance.BufferId;
coordList[ instance.BufferId ] = coordList[ coordList.Count - 1 ];
scalingList[ instance.BufferId ] = scalingList[
scalingList.Count - 1 ];
scalingList[ instance.BufferId ] = scalingList[ scalingList.Count - 1 ];
instanceList.RemoveAt( instanceList.Count - 1 );
coordList.RemoveAt( coordList.Count - 1 );
@@ -185,7 +184,8 @@ namespace StgSharp.Geometries
protected virtual void Dispose( bool disposing )
{
if( !disposedValue ) {
if( !disposedValue )
{
if( disposing ) {
mutex.Dispose();
}
@@ -204,8 +204,7 @@ namespace StgSharp.Geometries
}
}
IGeometry IInstancingBuffer.TypicalShape => throw new NotImplementedException(
);
IGeometry IInstancingBuffer.TypicalShape => throw new NotImplementedException();
#region field of mem opt
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
@@ -44,18 +43,19 @@ namespace StgSharp.Geometries
internal Point center;
public Parallelogram(
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
if( this[ 0 ].Coord + this[ 2 ].Coord != this[ 1 ].Coord + this[ 3 ].Coord ) {
if( this[ 0 ].Coord + this[ 2 ].Coord != this[ 1 ].Coord + this[ 3 ].Coord )
{
InternalIO.InternalWriteLog(
"Init of geometry item failed, because four vertices cannot form a rectangle.",
LogType.Warning );
@@ -64,19 +64,20 @@ namespace StgSharp.Geometries
}
public Parallelogram(
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( coordination, v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
if( this[ 0 ].Coord + this[ 2 ].Coord != this[ 1 ].Coord + this[ 3 ].Coord ) {
if( this[ 0 ].Coord + this[ 2 ].Coord != this[ 1 ].Coord + this[ 3 ].Coord )
{
InternalIO.InternalWriteLog(
"Init of geometry item failed, because four vertices cannot form a rectangle.",
LogType.Warning );
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
@@ -56,11 +55,7 @@ namespace StgSharp.Geometries
vertexMat = rawCoord;
}
public Polygon4(
Point topLeft,
Point topRight,
Point bottomRight,
Point bottomLeft )
public Polygon4( Point topLeft, Point topRight, Point bottomRight, Point bottomLeft )
: base( PlainCoordinate.StandardPlainCoordination )
{
this[ 0 ] = topLeft;
@@ -70,12 +65,12 @@ namespace StgSharp.Geometries
}
public Polygon4(
CoordinationBase coordinate,
PlainCoordinate coordination,
Point topLeft,
Point topRight,
Point bottomRight,
Point bottomLeft )
CoordinationBase coordinate,
PlainCoordinate coordination,
Point topLeft,
Point topRight,
Point bottomRight,
Point bottomLeft )
: base( coordinate )
{
this[ 0 ] = topLeft;
@@ -85,14 +80,14 @@ namespace StgSharp.Geometries
}
public Polygon4(
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new Vec4[4];
@@ -104,15 +99,15 @@ namespace StgSharp.Geometries
}
public Polygon4(
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( coordination )
{
vertexMat = new Vec4[4];
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
@@ -48,16 +47,16 @@ namespace StgSharp.Geometries
}
public Polygon5(
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y,
float v4x,
float v4y )
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y,
float v4x,
float v4y )
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new Vec4[5];
@@ -69,17 +68,17 @@ namespace StgSharp.Geometries
}
public Polygon5(
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y,
float v4x,
float v4y )
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y,
float v4x,
float v4y )
: base( coordination )
{
vertexMat = new Vec4[5];
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
@@ -48,14 +47,14 @@ namespace StgSharp.Geometries
}
public Polygon6(
PlainCoordinate coordination,
Vec2 vert0,
Vec2 vert1,
Vec2 vert2,
Vec2 vert3,
Vec2 vert4,
Vec2 vert5,
Vec2 vert6 )
PlainCoordinate coordination,
Vec2 vert0,
Vec2 vert1,
Vec2 vert2,
Vec2 vert3,
Vec2 vert4,
Vec2 vert5,
Vec2 vert6 )
: base( coordination )
{
vertexMat = new Vec4[6];
@@ -39,14 +39,14 @@ namespace StgSharp.Geometries
{
public Rectangle(
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
@@ -59,15 +59,15 @@ namespace StgSharp.Geometries
}
public Rectangle(
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( coordination, v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
@@ -80,10 +80,14 @@ namespace StgSharp.Geometries
}
/// <summary>
/// Calculate movement to center
/// Calculate movement to center
/// </summary>
/// <param _name="tick"> CurrentBlueprint time tick </param>
/// <returns></returns>
/// <param _label="tick">
/// CurrentPipeline time tick
/// </param>
/// <returns>
///
/// </returns>
public virtual Vec3 MovCenter( uint tick )
{
return default( Vec3 );
@@ -35,20 +35,20 @@ using System.Numerics;
namespace StgSharp.Geometries
{
/// <summary>
/// A square
/// A square
/// </summary>
public class Square : Rectangle
{
public Square(
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
if( true ) { }
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Math;
@@ -57,10 +56,10 @@ namespace StgSharp.Geometries
}
public Triangle(
PlainCoordinate coordination,
Point vertex01,
Point vertex02,
Point vertex03 )
PlainCoordinate coordination,
Point vertex01,
Point vertex02,
Point vertex03 )
: base( coordination )
{
this[ 0 ] = vertex01;
@@ -68,13 +67,7 @@ namespace StgSharp.Geometries
this[ 2 ] = vertex03;
}
public Triangle(
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y )
public Triangle( float v0x, float v0y, float v1x, float v1y, float v2x, float v2y )
: base( PlainCoordinate.StandardPlainCoordination )
{
this[ 0 ] = new Point( v0x, v0y, 0 );
@@ -83,13 +76,13 @@ namespace StgSharp.Geometries
}
public Triangle(
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y )
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y )
: base( coordination )
{
this[ 0 ] = new Point( v0x, v0y, 0 );
+1 -1
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Point.cs"
// Project: StgSharp
// Project: World
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -0,0 +1,145 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TriangulatedSurface.cs"
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.HighPerformance;
using StgSharp.Math;
using StgSharp.Math.HighPrecision;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Text;
namespace StgSharp.Geometries
{
public class TriangulatedSurface
{
private HashSet<(int begin,int end)> _sides;
private List<List<int>> _sideIndices;
private List<int> _triangleIndices;
private List<Vec3> _vertices;
public TriangulatedSurface()
{
_triangleIndices = new List<int>();
_vertices = new List<Vec3>();
_sides = new HashSet<(int,int)>();
_sideIndices = new List<List<int>>();
}
/**/
public IEnumerable<List<int>> SideIndicesEnumeratble
{
get => _sideIndices ;
}
/*
public Triangle GetTriangle( int index )
{
Vec3HP v1,v2,v3;
int t = index * 3;
v1 = _vertices[ t + 0 ];
v2 = _vertices[ t + 1 ];
v3 = _vertices[ t + 2 ];
return new Triangle( v1, v2, v3 );
}
/**/
public Span<Vec3> VertexSpan
{
get => CollectionsMarshal.AsSpan( _vertices );
}
public Span<int> TriangleIndicesSpan
{
get => CollectionsMarshal.AsSpan( _triangleIndices );
}
/**/
public void AddIndicesByOrder( int v1, int v2, int v3 )
{
_triangleIndices.Add( v1 );
_triangleIndices.Add( v2 );
_triangleIndices.Add( v3 );
if( !( _sides.Remove( (v1,v2) ) || _sides.Remove( (v2, v1) ) ) ) {
_sides.Add( (v1, v2) );
}
if( !( _sides.Remove( (v2, v3) ) || _sides.Remove( (v3, v2) ) ) ) {
_sides.Add( (v2, v3) );
}
if( !( _sides.Remove( (v3, v1) ) || _sides.Remove( (v1, v3) ) ) ) {
_sides.Add( (v3, v1) );
}
}
public void AddVertexByOrder( Vec3 vertex )
{
_vertices.Add( vertex );
}
public int TriangleCount()
{
return _triangleIndices.Count / 3;
}
public void TrimExcess()
{
_triangleIndices.TrimExcess();
_vertices.TrimExcess();
Dictionary<int, int> side_dictionary = _sides.ToDictionary( x => x.begin, x => x.end );
int begin = side_dictionary.First().Key;
List<int> sideLoop = new List<int>( begin );
_sideIndices.Add( sideLoop );
while( side_dictionary.Count > 0 )
{
if( side_dictionary.Remove( begin, out begin ) )
{
sideLoop.Add( begin );
} else
{
begin = side_dictionary.First().Key;
sideLoop = new List<int>( begin );
_sideIndices.Add( sideLoop );
}
}
_sideIndices.TrimExcess();
}
public int VertexCount()
{
return _vertices.Count;
}
}
}
+91 -11
View File
@@ -1,4 +1,34 @@
// This file is used by Code Analysis to maintain SuppressMessage
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Global.cs"
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
@@ -9,13 +39,63 @@ global using StgSharp.Internal.OpenGL;
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Design", "CA1008:枚举应具有零值", Justification = "<挂起>", Scope = "type", Target = "~T:StgSharp.Graphics.OpenGL.ShaderStatus")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "member", Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``2(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1}")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "member", Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``3(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1,``2}")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "member", Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``4(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1,``2,``3}")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "type", Target = "~T:StgSharp.Graphics.OpenGL.Uniform`4")]
[assembly: SuppressMessage("Design", "CA1043:将整型或字符串参数用于索引器", Justification = "<挂起>", Scope = "member", Target = "~P:StgSharp.MVVM.View.ViewBase.IViewResponder`1.Item(StgSharp.Controlling.UsrActivity.ITrigger)")]
[assembly: SuppressMessage("Design", "CA1043:将整型或字符串参数用于索引器", Justification = "<挂起>", Scope = "member", Target = "~P:StgSharp.MVVM.View.ViewBase.ViewResponder`1.Item(StgSharp.Controlling.UsrActivity.ITrigger)")]
[assembly: SuppressMessage("Performance", "CA1864:首选 \"IDictionary.TryAdd(TKey, TValue)\" 方法", Justification = "<挂起>", Scope = "member", Target = "~P:StgSharp.MVVM.View.ViewBase.ViewRender`1.Item(System.String)")]
[assembly: SuppressMessage("Design", "CA1033:接口方法应可由子类型调用", Justification = "<挂起>", Scope = "member", Target = "~P:StgSharp.Collections.IBidirectionalDictionary`2.System#Collections#Generic#IDictionary<TFirst,TSecond>#Keys")]
[assembly: SuppressMessage("Design", "CA1033:接口方法应可由子类型调用", Justification = "<挂起>", Scope = "member", Target = "~P:StgSharp.Collections.IBidirectionalDictionary`2.System#Collections#Generic#IDictionary<TFirst,TSecond>#Values")]
[assembly: SuppressMessage(
"Design",
"CA1008:枚举应具有零值",
Justification = "<挂起>",
Scope = "type",
Target = "~T:StgSharp.Graphics.OpenGL.ShaderStatus" )]
[assembly: SuppressMessage(
"Naming",
"CA1715:标识符应具有正确的前缀",
Justification = "<挂起>",
Scope = "member",
Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``2(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1}" )]
[assembly: SuppressMessage(
"Naming",
"CA1715:标识符应具有正确的前缀",
Justification = "<挂起>",
Scope = "member",
Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``3(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1,``2}" )]
[assembly: SuppressMessage(
"Naming",
"CA1715:标识符应具有正确的前缀",
Justification = "<挂起>",
Scope = "member",
Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``4(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1,``2,``3}" )]
[assembly: SuppressMessage(
"Naming",
"CA1715:标识符应具有正确的前缀",
Justification = "<挂起>",
Scope = "type",
Target = "~T:StgSharp.Graphics.OpenGL.Uniform`4" )]
[assembly: SuppressMessage(
"Design",
"CA1043:将整型或字符串参数用于索引器",
Justification = "<挂起>",
Scope = "member",
Target = "~P:StgSharp.MVVM.ViewBase.IViewResponder`1.Item(StgSharp.Controlling.UsrActivity.ITrigger)" )]
[assembly: SuppressMessage(
"Design",
"CA1043:将整型或字符串参数用于索引器",
Justification = "<挂起>",
Scope = "member",
Target = "~P:StgSharp.MVVM.ViewBase.ViewResponder`1.Item(StgSharp.Controlling.UsrActivity.ITrigger)" )]
[assembly: SuppressMessage(
"Performance",
"CA1864:首选 \"IDictionary.TryAdd(TKey, TValue)\" 方法",
Justification = "<挂起>",
Scope = "member",
Target = "~P:StgSharp.MVVM.ViewBase.ViewRender`1.Item(System.String)" )]
[assembly: SuppressMessage(
"Design",
"CA1033:接口方法应可由子类型调用",
Justification = "<挂起>",
Scope = "member",
Target = "~P:StgSharp.Collections.IBidirectionalDictionary`2.System#Collections#Generic#IDictionary<TFirst,TSecond>#Keys" )]
[assembly: SuppressMessage(
"Design",
"CA1033:接口方法应可由子类型调用",
Justification = "<挂起>",
Scope = "member",
Target = "~P:StgSharp.Collections.IBidirectionalDictionary`2.System#Collections#Generic#IDictionary<TFirst,TSecond>#Values" )]
@@ -38,11 +38,7 @@ namespace StgSharp.Graphics
public static class ImageHelper
{
public static void Resize(
Image i,
int width,
int height,
ImageMovement move )
public static void Resize( Image i, int width, int height, ImageMovement move )
{
if( i == null ) {
throw new ArgumentNullException( nameof( i ) );
@@ -58,7 +54,8 @@ namespace StgSharp.Graphics
i.Height = height;
i.Width = width;
i.PixelUpdateCount++;
switch( move ) {
switch( move )
{
case ImageMovement.Discard:
break;
case ImageMovement.Top:
@@ -39,7 +39,7 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics
{
/// <summary>
/// Interface of all kinds OpenGL Buffer objects
/// Interface of all kinds OpenGL Buffer objects
/// </summary>
public abstract class BufferObjectBase : IDisposable
{
@@ -48,16 +48,22 @@ namespace StgSharp.Graphics
protected RenderStream binding;
/// <summary>
/// Get the only handle to one of the Object instance
/// Get the only handle to one of the Object instance
/// </summary>
/// <param _name="index"></param>
/// <returns></returns>
/// <param _label="index">
///
/// </param>
/// <returns>
///
/// </returns>
public GlHandle this[ int index ] => _bufferHandle[ index ];
/// <summary>
/// Bind a Buffer instance to OpenGL
/// Bind a Buffer instance to OpenGL
/// </summary>
/// <param _name="index"> Index of handle of the object in this instance to be bind </param>
/// <param _label="index">
/// Index of handle of the object in this instance to be bind
/// </param>
public abstract void Bind( int index );
public void Dispose()
+18 -26
View File
@@ -28,8 +28,8 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Internal;
using StgSharp.Graphics.OpenGL;
using StgSharp.Internal;
using StgSharp.Math;
using System;
@@ -73,7 +73,8 @@ namespace StgSharp.Graphics
{
get
{
if( ( _data.Length == 0 ) || ( _data == null ) ) {
if( ( _data.Length == 0 ) || ( _data == null ) )
{
GetBytes();
return _data!;
}
@@ -84,7 +85,7 @@ namespace StgSharp.Graphics
public ImageChannel Channel => _rawInfo.Channel;
/// <summary>
/// Hash code of time pixels updated last time.
/// Hash code of time pixels updated last time.
/// </summary>
public int PixelUpdateCount
{
@@ -106,8 +107,7 @@ namespace StgSharp.Graphics
internal set => _rawInfo.Width = value;
}
public int PixelSize => ImageInfo.GetPixelSize(
_rawInfo.pixelLayout, _rawInfo.Channel );
public int PixelSize => ImageInfo.GetPixelSize( _rawInfo.pixelLayout, _rawInfo.Channel );
public PixelChannelLayout PixelLayout
{
@@ -134,9 +134,9 @@ namespace StgSharp.Graphics
}
public static Image FromMemory(
(int width, int height) size,
ImageChannel channel,
byte[] stream )
(int width, int height) size,
ImageChannel channel,
byte[] stream )
{
ImageInfo _info = new ImageInfo
{
@@ -152,10 +152,10 @@ namespace StgSharp.Graphics
}
public static Image FromMemory(
(int width, int height) size,
ImageChannel channel,
PixelChannelLayout layout,
byte[] stream )
(int width, int height) size,
ImageChannel channel,
PixelChannelLayout layout,
byte[] stream )
{
ImageInfo _info = new ImageInfo
{
@@ -172,11 +172,10 @@ namespace StgSharp.Graphics
public unsafe byte[] GetBytes()
{
if( _data.Length == 0 ) {
int size = Width * Height * ImageInfo.GetPixelSize(
PixelLayout, Channel );
_data = new Span<byte>( ( byte* )_rawInfo.StreamPtr,
size ).ToArray();
if( _data.Length == 0 )
{
int size = Width * Height * ImageInfo.GetPixelSize( PixelLayout, Channel );
_data = new Span<byte>( ( byte* )_rawInfo.StreamPtr, size ).ToArray();
fixed( ImageInfo* pptr = &_rawInfo ) {
InternalIO.InternalUnloadImage( pptr );
}
@@ -187,10 +186,7 @@ namespace StgSharp.Graphics
public Image ProvideImage() => this;
internal static Image FromMemory(
ImageInfo info,
byte[] data,
int operationCount )
internal static Image FromMemory( ImageInfo info, byte[] data, int operationCount )
{
return new Image
{
@@ -206,13 +202,9 @@ namespace StgSharp.Graphics
}
}
}
namespace StgSharp.Graphics.OpenGL
{
public static partial class GlHelper
{
}
public static partial class GlHelper { }
}
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Commom.Collections;
using System;
using System.Collections.Generic;
@@ -42,11 +41,11 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// A collection of a sets of OpenGL textures. The collection can automatically select one of
/// the texture with minimum costs to upgrade pixels to Buffer. Usually <see
/// cref="AutoTextureGL" /> is used for <see cref="IImageProvider" /> loading, but not for
/// target of <see cref="OpenGLFunction.FrameBufferTexture2d(FrameBufferTarget, uint,
/// Texture2DTarget, GlHandle, int)" />.
/// A collection of a sets of OpenGL textures. The collection can automatically select one of
/// the texture with minimum costs to upgrade pixels to Buffer. Usually <see
/// cref="AutoTextureGL" /> is used for <see cref="IImageProvider" /> loading, but not for
/// target of <see cref="OpenGLFunction.FrameBufferTexture2d(FrameBufferTarget, uint,
/// Texture2DTarget, GlHandle, int)" />.
/// </summary>
public sealed class AutoTextureGL
{
@@ -54,8 +53,7 @@ namespace StgSharp.Graphics.OpenGL
private TextureProperty[] propertyCache;
private BidirectionalDictionary<Image, int> imageIndexMap = new BidirectionalDictionary<Image, int>(
);
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>(
);
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>();
private int _size, _currentIndex;
private LinkedList<int> usedTextureIndex;
@@ -69,8 +67,7 @@ namespace StgSharp.Graphics.OpenGL
texturePackage = texture;
_size = texture.Count;
imageIndexMap = new BidirectionalDictionary<Image, int>();
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range( 0, _size ) );
unusedTextureUnitIndex = new Queue<int>( Enumerable.Range( 0, _size ) );
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
@@ -80,8 +77,7 @@ namespace StgSharp.Graphics.OpenGL
this._size = textureObjectSize;
imageIndexMap = new BidirectionalDictionary<Image, int>();
texturePackage = new TextureGL( textureObjectSize, binding );
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range( 0, _size ) );
unusedTextureUnitIndex = new Queue<int>( Enumerable.Range( 0, _size ) );
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
@@ -105,29 +101,34 @@ namespace StgSharp.Graphics.OpenGL
SelectTextureAndBind( i, property );
}
public void SelectTextureAndBind(
[NotNull]Image i,
TextureProperty property )
public void SelectTextureAndBind( [NotNull]Image i, TextureProperty property )
{
//usable texture with image match
if( imageIndexMap.TryGetValue( i, out int index ) ) {
if( imageIndexMap.TryGetValue( i, out int index ) )
{
//prop setting match
if( propertyCache[ index ] == property ) {
if( propertyCache[ index ] == property )
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D( index ); //GL.Assert(true);
if( i.PixelUpdateCount != imageUpdateIndex[ i ] ) {
if( i.PixelUpdateCount != imageUpdateIndex[ i ] )
{
texturePackage.LoadTexture( index, i ); //GL.Assert(true);
}
} else {
} else
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D( index ); //GL.Assert(true);
texturePackage.Set2dProperty( index, property ); //GL.Assert(true);
if( i.PixelUpdateCount != imageUpdateIndex[ i ] ) {
if( i.PixelUpdateCount != imageUpdateIndex[ i ] )
{
texturePackage.LoadTexture( index, i ); //GL.Assert(true);
}
}
} else {
if( unusedTextureUnitIndex.TryDequeue( out int newIndex ) ) {
} else
{
if( unusedTextureUnitIndex.TryDequeue( out int newIndex ) )
{
//has extra unused texture object
imageIndexMap.Add( i, index );
texturePackage.Bind2D( index );
@@ -136,7 +137,8 @@ namespace StgSharp.Graphics.OpenGL
usedTextureIndex.AddLast( newIndex );
propertyCache[ newIndex ] = property;
imageUpdateIndex[ i ] = i.PixelUpdateCount;
} else {
} else
{
//recycle from current
int reusedIndex = usedTextureIndex.First!.Value;
usedTextureIndex.RemoveFirst();
@@ -151,8 +153,7 @@ namespace StgSharp.Graphics.OpenGL
public static AutoTextureGL ToAuto( [NotNull]TextureGL texture )
{
if( texture.IndexOfCurrentTexture != -1 ) {
throw new InvalidOperationException(
"Texture to be converted has been editted." );
throw new InvalidOperationException( "Texture to be converted has been editted." );
}
return new AutoTextureGL( texture );
}
+9 -17
View File
@@ -43,9 +43,9 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// A collection of handle to Element Buffer Object in OpenglFunc. Each <see langword="uint" />
/// value indexed from instance of this class this is the only handle to one Element Buffer
/// Object.
/// A collection of handle to Element Buffer Object in OpenglFunc. Each <see langword="uint"
/// /> value indexed from instance of this class this is the only handle to one Element Buffer
/// Object.
/// </summary>
public sealed unsafe class ElementBuffer : GlBufferObjectBase
{
@@ -58,29 +58,21 @@ namespace StgSharp.Graphics.OpenGL
public override sealed void Bind( int index )
{
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.BindBuffer( BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
}
public void SetValue<T>( int index, T[] bufferArray, BufferUsage usage )
where T: struct, INumber<T>
{
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData<T>(
BufferType.ElementArrayBuffer, bufferArray, usage );
GL.BindBuffer( BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData<T>( BufferType.ElementArrayBuffer, bufferArray, usage );
}
public void SetValue<T>(
int index,
ReadOnlySpan<T> bufferSpan,
BufferUsage usage )
public void SetValue<T>( int index, ReadOnlySpan<T> bufferSpan, BufferUsage usage )
where T: struct, INumber<T>
{
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData<T>( BufferType.ElementArrayBuffer, bufferSpan,
usage );
GL.BindBuffer( BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData<T>( BufferType.ElementArrayBuffer, bufferSpan, usage );
}
protected override sealed void Dispose( bool disposing )
+15 -9
View File
@@ -63,10 +63,13 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Bind the frame Buffer object with _name frame Buffer to the frame Buffer target specified
/// by target. <see langword="FrameBufferTarget.All" /> will be set as default target.
/// Bind the frame Buffer object with _label frame Buffer to the frame Buffer target
/// specified by target. <see langword="FrameBufferTarget.All" /> will be set as default
/// target.
/// </summary>
/// <param _name="index"> Index of object to be binded in handle set </param>
/// <param _label="index">
/// Index of object to be binded in handle set
/// </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override unsafe void Bind( int index )
{
@@ -74,11 +77,15 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Bind the frame Buffer object with _name frame Buffer to the frame Buffer target specified
/// by target. Target of this frame Buffer should be set manually.
/// Bind the frame Buffer object with _label frame Buffer to the frame Buffer target
/// specified by target. Target of this frame Buffer should be set manually.
/// </summary>
/// <param _name="target"> The frame Buffer target of the binding operation. </param>
/// <param _name="index"> Index of object to be binded in handle set </param>
/// <param _label="target">
/// The frame Buffer target of the binding operation.
/// </param>
/// <param _label="index">
/// Index of object to be binded in handle set
/// </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Bind( FrameBufferTarget target, int index )
{
@@ -88,8 +95,7 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void BindNull()
{
OpenGLFunction.CurrentGL
.BindFrameBuffer( FrameBufferTarget.All, GlHandle.Zero );
OpenGLFunction.CurrentGL.BindFrameBuffer( FrameBufferTarget.All, GlHandle.Zero );
}
protected override void Dispose( bool disposing )
@@ -51,19 +51,17 @@ namespace StgSharp.Graphics.OpenGL
GL.BindRenderBuffer( this[ index ] );
}
public void Store(
RenderBufferInternalFormat format,
(int width, int height) size )
public void Store( RenderBufferInternalFormat format, (int width, int height) size )
{
if( ( size.width > binding.Width ) || ( size.height > binding.Height ) ) {
StgSharp.LogWarning(
"FrameBuffer is larger than current canvas binding" );
World.LogWarning( "FrameBuffer is larger than current canvas binding" );
}
}
protected override void Dispose( bool disposing )
{
foreach( GlHandle item in _bufferHandle ) {
foreach( GlHandle item in _bufferHandle )
{
Console.WriteLine( "removing a render buffer" );
GL.DeleteRenderBuffer( item );
}
@@ -84,16 +84,20 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Load an <see cref="Image" /> to certain texture.
/// Load an <see cref="Image" /> to certain texture.
/// </summary>
/// <param _name="index"> </param>
/// <param _name="i"> </param>
/// <param _label="index">
///
/// </param>
/// <param _label="i">
///
/// </param>
public unsafe void LoadTexture( int index, Image i )
{
byte[] handle = i.PixelBuffer;
_gl.TextureImage2d(
Texture2DTarget.Texture2D, 0, i.Channel, ( uint )i.Width,
( uint )i.Height, i.Channel, i.PixelLayout, pixels: handle );
Texture2DTarget.Texture2D, 0, i.Channel, ( uint )i.Width, ( uint )i.Height,
i.Channel, i.PixelLayout, pixels: handle );
_gl.GenerateMipmap( Texture2DTarget.Texture2D );
}
@@ -101,50 +105,45 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dFilterProperty(
int index,
TextureFilter onMinify,
TextureFilter onMagnify )
int index,
TextureFilter onMinify,
TextureFilter onMagnify )
{
#if DEBUG
if( index != currentEditingTextureIndex ) {
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter(
glConst.TEXTURE_2D, glConst.TEXTURE_MIN_FILTER,
( int )onMinify );
_gl.TextureParameter(
glConst.TEXTURE_2D, glConst.TEXTURE_MAG_FILTER,
( int )onMagnify );
_gl.TextureParameter( glConst.TEXTURE_2D, glConst.TEXTURE_MIN_FILTER, ( int )onMinify );
_gl.TextureParameter( glConst.TEXTURE_2D, glConst.TEXTURE_MAG_FILTER,
( int )onMagnify );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dWrapProperty(
int index,
TextureWrap onHorizontial,
TextureWrap onVertical )
int index,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
#if DEBUG
if( index != currentEditingTextureIndex ) {
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter(
glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_S,
( int )onHorizontial );
_gl.TextureParameter(
glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_T, ( int )onVertical );
_gl.TextureParameter( glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_S,
( int )onHorizontial );
_gl.TextureParameter( glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_T, ( int )onVertical );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dProperty( int index, TextureProperty property )
{
Set2dFilterProperty(
index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty(
index, property.WrapOnHorizontial, property.WrapOnVertical );
Set2dFilterProperty( index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty( index, property.WrapOnHorizontial, property.WrapOnVertical );
}
#endregion texture setting
@@ -162,10 +161,10 @@ namespace StgSharp.Graphics.OpenGL
[FieldOffset( 12 )] private TextureWrap vert;
public TextureProperty(
TextureFilter onMagnify,
TextureFilter onMinify,
TextureWrap onHorizontial,
TextureWrap onVertical )
TextureFilter onMagnify,
TextureFilter onMinify,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
FilterOnMagnify = onMagnify;
FilterOnMinify = onMinify;
@@ -205,8 +204,7 @@ namespace StgSharp.Graphics.OpenGL
public override int GetHashCode()
{
return HashCode.Combine(
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial,
WrapOnVertical );
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical );
}
public override string ToString()
@@ -214,30 +212,25 @@ namespace StgSharp.Graphics.OpenGL
return $"FilterOnMagnify:{FilterOnMagnify}, " + $"FilterOnMagnify:{FilterOnMagnify}, " + $"WrapOnHorizontial:{WrapOnHorizontial}, " + $"WrapOnVertical:{WrapOnVertical}";
}
public static bool operator !=(
TextureProperty left,
TextureProperty right )
public static bool operator !=( TextureProperty left, TextureProperty right )
{
return left.mask != right.mask;
}
public static bool operator ==(
TextureProperty left,
TextureProperty right )
public static bool operator ==( TextureProperty left, TextureProperty right )
{
return left.mask == right.mask;
}
public static implicit operator TextureProperty(
(
(
TextureFilter onMagnify, TextureFilter onMinify,
TextureWrap onHorizontial, TextureWrap onVertical
) propertyValueTuple )
{
return new TextureProperty(
propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
propertyValueTuple.onHorizontial,
propertyValueTuple.onVertical );
propertyValueTuple.onHorizontial, propertyValueTuple.onVertical );
}
}
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="VAO.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
@@ -59,15 +58,15 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetVertexAttribute(
uint index,
int vertexLength,
TypeCode dataType,
bool isNomalized,
uint stride,
int pointer )
uint attributeIndex,
int vertexLength,
TypeCode dataType,
bool isNomalized,
uint stride,
int pointer )
{
GL.SetVertexAttribute(
index, vertexLength, dataType, isNomalized, stride, pointer );
attributeIndex, vertexLength, dataType, isNomalized, stride, pointer );
}
protected override sealed void Dispose( bool disposing )
+72 -48
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="VBO.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -65,16 +65,21 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set _data to current vertex Buffer object
/// Set _data to current vertex Buffer object
/// </summary>
/// <typeparam _name="TItem"> Type of bufferData </typeparam>
/// <param _name="index"> Index to find certain VBO in this instance </param>
/// <param _name="bufferData"> Data to write in </param>
/// <param _name="usage"> How OpenGL use these _data, defined by <see cref="BufferUsage" /></param>
public void WriteMatrixData<T>(
int index,
T bufferData,
BufferUsage usage )
/// <typeparam _label="TItem">
/// Type of bufferData
/// </typeparam>
/// <param _label="index">
/// Index to find certain VBO in this instance
/// </param>
/// <param _label="bufferData">
/// Data to write in
/// </param>
/// <param _label="usage">
/// How OpenGL use these _data, defined by <see cref="BufferUsage" />
/// </param>
public void WriteMatrixData<T>( int index, T bufferData, BufferUsage usage )
where T: struct, IMatrix<T>
{
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
@@ -82,16 +87,21 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set _data to current vertex Buffer object
/// Set _data to current vertex Buffer object
/// </summary>
/// <typeparam _name="TItem"> Type of bufferData </typeparam>
/// <param _name="index"> Index to find certain VBO in this instance </param>
/// <param _name="bufferArray"> Data to write in </param>
/// <param _name="usage"> How OpenGL use these _data, defined by <see cref="BufferUsage" /></param>
public void WriteScalerData<T>(
int index,
T[] bufferArray,
BufferUsage usage )
/// <typeparam _label="TItem">
/// Type of bufferData
/// </typeparam>
/// <param _label="index">
/// Index to find certain VBO in this instance
/// </param>
/// <param _label="bufferArray">
/// Data to write in
/// </param>
/// <param _label="usage">
/// How OpenGL use these _data, defined by <see cref="BufferUsage" />
/// </param>
public void WriteScalerData<T>( int index, T[] bufferArray, BufferUsage usage )
where T: struct, INumber<T>
{
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
@@ -99,16 +109,21 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set _data to current vertex Buffer object
/// Set _data to current vertex Buffer object
/// </summary>
/// <typeparam _name="TItem"> Type of bufferData </typeparam>
/// <param _name="index"> Index to find certain VBO in this instance </param>
/// <param _name="scalerSpan"> A <see cref="Span{T}" /> of _data to write in </param>
/// <param _name="usage"> How OpenGL use these _data, defined by <see cref="BufferUsage" /></param>
public void WriteScalerData<T>(
int index,
ReadOnlySpan<T> scalerSpan,
BufferUsage usage )
/// <typeparam _label="TItem">
/// Type of bufferData
/// </typeparam>
/// <param _label="index">
/// Index to find certain VBO in this instance
/// </param>
/// <param _label="scalerSpan">
/// A <see cref="Span{T}" /> of _data to write in
/// </param>
/// <param _label="usage">
/// How OpenGL use these _data, defined by <see cref="BufferUsage" />
/// </param>
public void WriteScalerData<T>( int index, ReadOnlySpan<T> scalerSpan, BufferUsage usage )
where T: struct,INumber<T>
{
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
@@ -116,16 +131,21 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set _data to current vertex Buffer object
/// Set data to current vertex Buffer object
/// </summary>
/// <typeparam _name="TItem"> Type of bufferData </typeparam>
/// <param _name="index"> Index to find certain VBO in this instance </param>
/// <param _name="vectorSpan"> A <see cref="Span{T}" /> of _data to write in </param>
/// <param _name="usage"> How OpenGL use these _data, defined by <see cref="BufferUsage" /></param>
public void WriteVectorData<T>(
int index,
ReadOnlySpan<T> vectorSpan,
BufferUsage usage )
/// <typeparam _label="TItem">
/// Type of bufferData
/// </typeparam>
/// <param _label="index">
/// Index to find certain VBO in this instance
/// </param>
/// <param _label="vectorSpan">
/// A <see cref="Span{T}" /> of data to write in
/// </param>
/// <param _label="usage">
/// How OpenGL use these data, defined by <see cref="BufferUsage" />
/// </param>
public void WriteVectorData<T>( int index, ReadOnlySpan<T> vectorSpan, BufferUsage usage )
where T: struct, IVector<T>
{
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
@@ -133,21 +153,25 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set _data to current vertex Buffer object
/// Set _data to current vertex Buffer object
/// </summary>
/// <typeparam _name="TItem"> Type of bufferData </typeparam>
/// <param _name="index"> Index to find certain VBO in this instance </param>
/// <param _name="vectorArray"> A array of _data to write in </param>
/// <param _name="usage"> How OpenGL use these _data, defined by <see cref="BufferUsage" /></param>
public void WriteVectorData<T>(
int index,
T[] vectorArray,
BufferUsage usage )
/// <typeparam _label="TItem">
/// Type of bufferData
/// </typeparam>
/// <param _label="index">
/// Index to find certain VBO in this instance
/// </param>
/// <param _label="vectorArray">
/// A array of _data to write in
/// </param>
/// <param _label="usage">
/// How OpenGL use these _data, defined by <see cref="BufferUsage" />
/// </param>
public void WriteVectorData<T>( int index, T[] vectorArray, BufferUsage usage )
where T: struct, IVector<T>
{
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferVectorData( BufferType.ArrayBuffer, vectorArray,
usage );
GL.SetBufferVectorData( BufferType.ArrayBuffer, vectorArray, usage );
}
protected override sealed void Dispose( bool disposing )
@@ -49,14 +49,14 @@ namespace StgSharp.Graphics.ShaderEdit
/// <summary>
///
/// </summary>
public void GainAllUniforms(
ShaderProgram source,
params string[] uniformName );
public void GainAllUniforms( ShaderProgram source, params string[] uniformName );
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <returns>
///
/// </returns>
public ShaderStruct GetConvertedGLtype();
/// <summary>
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Shader.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -33,6 +33,7 @@ using StgSharp.Internal;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -83,14 +84,14 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
/// <param _name="target">
/// <param _label="target">
/// Shader program to attach
/// </param>
/// <param _name="index">
/// <param _label="index">
/// Index of shader code in current shader code set.
/// </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void AttachTo( int index, ShaderProgram target )
public void AttachTo( int index, [NotNull]ShaderProgram target )
{
GL.AttachShader( target.handle, handle[ index ] );
}
@@ -187,7 +188,7 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param _name="name">
/// <param _label="name">
/// ContextName of the Uniform in shader code
/// </param>
/// <returns>
@@ -202,7 +203,7 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param _name="name">
/// <param _label="name">
/// ContextName of the Uniform in shader code
/// </param>
/// <returns>
@@ -216,7 +217,7 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param _name="name">
/// <param _label="name">
/// ContextName of the Uniform in shader code
/// </param>
/// <returns>
@@ -232,7 +233,7 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param _name="name">
/// <param _label="name">
/// ContextName of the Uniform in shader code
/// </param>
/// <returns>
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Uniform.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -35,6 +35,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
@@ -65,7 +66,10 @@ namespace StgSharp.Graphics.OpenGL
internal static Uniform<T> FromHandle( GlHandle handle )
{
return new Uniform<T> { id = handle };
return new Uniform<T>
{
id = handle
};
}
}
@@ -82,14 +86,15 @@ namespace StgSharp.Graphics.OpenGL
internal static Uniform<T, U> FromHandle( GlHandle handle )
{
return new Uniform<T, U> { id = handle };
return new Uniform<T, U>
{
id = handle
};
}
}
public sealed class Uniform<T, U, V> : Uniform where T: struct
where U: struct
where V: struct
public sealed class Uniform<T, U, V> : Uniform where T: struct where U: struct where V: struct
{
internal Uniform() { }
@@ -101,13 +106,15 @@ namespace StgSharp.Graphics.OpenGL
internal static Uniform<T, U, V> FromHandle( GlHandle handle )
{
return new Uniform<T, U, V> { id = handle };
return new Uniform<T, U, V>
{
id = handle
};
}
}
public sealed class Uniform<T, U, V, W> : Uniform where T: struct
where U: struct
public sealed class Uniform<T, U, V, W> : Uniform where T: struct where U: struct
where V: struct
where W: struct
{
@@ -121,7 +128,10 @@ namespace StgSharp.Graphics.OpenGL
internal static Uniform<T, U, V, W> FromHandle( GlHandle handle )
{
return new Uniform<T, U, V, W> { id = handle };
return new Uniform<T, U, V, W>
{
id = handle
};
}
}
@@ -133,14 +143,13 @@ namespace StgSharp.Graphics.OpenGL
public void SetUniformValue( [NotNull] Uniform<Matrix44> uniform, Matrix44 mat )
{
Matrix44 temp = mat;
Context.glUniformMatrix4fv(
uniform.id.SignedValue, 1, false, ( float* )&temp );
Context.glUniformMatrix4fv( uniform.id.SignedValue, 1, false, ( float* )&temp );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue(
[NotNull]Uniform<float, float, float, float> uniform,
Vec4 vec )
[NotNull]Uniform<float, float, float, float> uniform,
Vec4 vec )
{
Vec4 temp = vec;
Context.glUniform1fv( uniform.id.SignedValue, 4, &temp.reg );
@@ -166,31 +175,28 @@ namespace StgSharp.Graphics.OpenGL
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue(
[NotNull] Uniform<float, float> uniform,
float v0,
float v1 )
public void SetUniformValue( [NotNull] Uniform<float, float> uniform, float v0, float v1 )
{
Context.glUniform2f( uniform.id.SignedValue, v0, v1 );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue(
[NotNull] Uniform<float, float, float> uniform,
float v0,
float v1,
float v2 )
[NotNull] Uniform<float, float, float> uniform,
float v0,
float v1,
float v2 )
{
Context.glUniform3f( uniform.id.SignedValue, v0, v1, v2 );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue(
[NotNull] Uniform<float, float, float, float> uniform,
float v0,
float v1,
float v2,
float v3 )
[NotNull] Uniform<float, float, float, float> uniform,
float v0,
float v1,
float v2,
float v3 )
{
Context.glUniform4f( uniform.id.SignedValue, v0, v1, v2, v3 );
}
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -38,7 +38,7 @@ using System.Threading.Tasks;
namespace StgSharp.Internal
{
/// <summary>
/// OpenGL numeric type. An IEEE-754 floating-point value, clamped to the range [0,1].
/// OpenGL numeric type. An IEEE-754 floating-point value, clamped to the range [0,1].
/// </summary>
[StructLayout( LayoutKind.Sequential )]
public struct GLclampf
@@ -64,8 +64,8 @@ namespace StgSharp.Internal
}
/// <summary>
/// OpenGL numeric type. An IEEE-754 double precision floating-point value, clamped to the range
/// [0,1].
/// OpenGL numeric type. An IEEE-754 double precision floating-point value, clamped to the
/// range [0,1].
/// </summary>
[StructLayout( LayoutKind.Sequential )]
public struct GLclampd
+2 -1
View File
@@ -4851,7 +4851,8 @@ namespace StgSharp.Graphics.OpenGL
public static uint Color( int i )
{
#if DEBUG
if( ( i > OpenGLFunction.CurrentGL.AttachmentColorRange ) || ( i < 0 ) ) {
if( ( i > OpenGLFunction.CurrentGL.AttachmentColorRange ) || ( i < 0 ) )
{
throw new ArgumentOutOfRangeException();
}
#endif
+26 -31
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glContext.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.HighPerformance;
using StgSharp.Internal;
using StgSharp.Internal.Intrinsic;
@@ -57,16 +56,12 @@ namespace StgSharp.Graphics.OpenGL
}
}
public static bool operator !=(
OpenglContext left,
OpenglContext right )
public static bool operator !=( OpenglContext left, OpenglContext right )
{
return !( left == right );
}
public static bool operator ==(
OpenglContext left,
OpenglContext right )
public static bool operator ==( OpenglContext left, OpenglContext right )
{
return left.Equals( right );
}
@@ -95,7 +90,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint*, ulong*, uint, uint, uint, uint, IntPtr, IntPtr, UIntPtr, uint, uint*, ulong*, uint> glAsyncCopyBufferSubDataNVX;
internal unsafe delegate*<uint, uint*, ulong*, uint, uint, uint, uint, int, int, int, int, uint, uint, int, int, int, int, uint, uint, uint, uint, uint*, ulong*, uint> glAsyncCopyImageSubDataNVX;
internal unsafe delegate*<uint, void> glAsyncMarkerSGIX;
internal unsafe delegate*<GLhandleARB, GLhandleARB, void> glAttachObjectARB;
internal unsafe delegate*<glHandleARB, glHandleARB, void> glAttachObjectARB;
internal unsafe delegate*<uint, uint, void> glAttachShader;
internal unsafe delegate*<uint, uint, void> glBeginConditionalRender;
internal unsafe delegate*<uint, uint, void> glBeginConditionalRenderNV;
@@ -113,7 +108,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<void> glBeginVertexShaderEXT;
internal unsafe delegate*<uint, void> glBeginVideoCaptureNV;
internal unsafe delegate*<uint, uint, byte*, void> glBindAttribLocation;
internal unsafe delegate*<GLhandleARB, uint, byte*, void> glBindAttribLocationARB;
internal unsafe delegate*<glHandleARB, uint, byte*, void> glBindAttribLocationARB;
internal unsafe delegate*<uint, uint, void> glBindBuffer;
internal unsafe delegate*<uint, uint, void> glBindBufferARB;
internal unsafe delegate*<uint, uint, uint, void> glBindBufferBase;
@@ -301,7 +296,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, void> glCommandListSegmentsNV;
internal unsafe delegate*<uint, void> glCompileCommandListNV;
internal unsafe delegate*<uint, void> glCompileShader;
internal unsafe delegate*<GLhandleARB, void> glCompileShaderARB;
internal unsafe delegate*<glHandleARB, void> glCompileShaderARB;
internal unsafe delegate*<uint, uint, byte*, int*, void> glCompileShaderIncludeARB;
internal unsafe delegate*<uint, uint, int, uint, uint, int, uint, void*, void> glCompressedMultiTexImage1DEXT;
internal unsafe delegate*<uint, uint, int, uint, uint, uint, int, uint, void*, void> glCompressedMultiTexImage2DEXT;
@@ -384,7 +379,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint*, void> glCreateMemoryObjectsEXT;
internal unsafe delegate*<uint, uint*, void> glCreatePerfQueryINTEL;
internal unsafe delegate*<uint> glCreateProgram;
internal unsafe delegate*<GLhandleARB> glCreateProgramObjectARB;
internal unsafe delegate*<glHandleARB> glCreateProgramObjectARB;
internal unsafe delegate*<uint, uint*, void> glCreateProgramPipelines;
internal unsafe delegate*<uint> glCreateProgressFenceNVX;
internal unsafe delegate*<uint, uint, uint*, void> glCreateQueries;
@@ -392,7 +387,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint*, void> glCreateSamplers;
internal unsafe delegate*<uint, uint*, void> glCreateSemaphoresNV;
internal unsafe delegate*<uint, uint> glCreateShader;
internal unsafe delegate*<uint, GLhandleARB> glCreateShaderObjectARB;
internal unsafe delegate*<uint, glHandleARB> glCreateShaderObjectARB;
internal unsafe delegate*<uint, byte*, uint> glCreateShaderProgramEXT;
internal unsafe delegate*<uint, uint, byte*, uint> glCreateShaderProgramv;
internal unsafe delegate*<uint, uint*, void> glCreateStatesNV;
@@ -428,7 +423,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint*, void> glDeleteMemoryObjectsEXT;
internal unsafe delegate*<int, byte*, void> glDeleteNamedStringARB;
internal unsafe delegate*<uint, uint, uint*, void> glDeleteNamesAMD;
internal unsafe delegate*<GLhandleARB, void> glDeleteObjectARB;
internal unsafe delegate*<glHandleARB, void> glDeleteObjectARB;
internal unsafe delegate*<uint, uint*, void> glDeleteOcclusionQueriesNV;
internal unsafe delegate*<uint, uint, void> glDeletePathsNV;
internal unsafe delegate*<uint, uint*, void> glDeletePerfMonitorsAMD;
@@ -467,7 +462,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<float, float, void> glDepthRangef;
internal unsafe delegate*<GLclampf, GLclampf, void> glDepthRangefOES;
internal unsafe delegate*<GLfixed, GLfixed, void> glDepthRangexOES;
internal unsafe delegate*<GLhandleARB, GLhandleARB, void> glDetachObjectARB;
internal unsafe delegate*<glHandleARB, glHandleARB, void> glDetachObjectARB;
internal unsafe delegate*<uint, uint, void> glDetachShader;
internal unsafe delegate*<uint, uint, float*, void> glDetailTexFuncSGIS;
internal unsafe delegate*<uint, void> glDisable;
@@ -682,12 +677,12 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, void> glGenerateTextureMipmapEXT;
internal unsafe delegate*<uint, uint, uint, int*, void> glGetActiveAtomicCounterBufferiv;
internal unsafe delegate*<uint, uint, uint, uint*, int*, uint*, byte*, void> glGetActiveAttrib;
internal unsafe delegate*<GLhandleARB, uint, uint, uint*, int*, uint*, byte*, void> glGetActiveAttribARB;
internal unsafe delegate*<glHandleARB, uint, uint, uint*, int*, uint*, byte*, void> glGetActiveAttribARB;
internal unsafe delegate*<uint, uint, uint, uint, uint*, byte*, void> glGetActiveSubroutineName;
internal unsafe delegate*<uint, uint, uint, uint, uint*, byte*, void> glGetActiveSubroutineUniformName;
internal unsafe delegate*<uint, uint, uint, uint, int*, void> glGetActiveSubroutineUniformiv;
internal unsafe delegate*<uint, uint, uint, uint*, int*, uint*, byte*, void> glGetActiveUniform;
internal unsafe delegate*<GLhandleARB, uint, uint, uint*, int*, uint*, byte*, void> glGetActiveUniformARB;
internal unsafe delegate*<glHandleARB, uint, uint, uint*, int*, uint*, byte*, void> glGetActiveUniformARB;
internal unsafe delegate*<uint, uint, uint, uint*, byte*, void> glGetActiveUniformBlockName;
internal unsafe delegate*<uint, uint, uint, int*, void> glGetActiveUniformBlockiv;
internal unsafe delegate*<uint, uint, uint, uint*, byte*, void> glGetActiveUniformName;
@@ -695,10 +690,10 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, uint, uint*, uint*, uint*, byte*, void> glGetActiveVaryingNV;
internal unsafe delegate*<uint, uint, float*, void> glGetArrayObjectfvATI;
internal unsafe delegate*<uint, uint, int*, void> glGetArrayObjectivATI;
internal unsafe delegate*<GLhandleARB, uint, uint*, GLhandleARB*, void> glGetAttachedObjectsARB;
internal unsafe delegate*<glHandleARB, uint, uint*, glHandleARB*, void> glGetAttachedObjectsARB;
internal unsafe delegate*<uint, uint, uint*, uint*, void> glGetAttachedShaders;
internal unsafe delegate*<uint, byte*, int> glGetAttribLocation;
internal unsafe delegate*<GLhandleARB, byte*, int> glGetAttribLocationARB;
internal unsafe delegate*<glHandleARB, byte*, int> glGetAttribLocationARB;
internal unsafe delegate*<uint, uint, bool*, void> glGetBooleanIndexedvEXT;
internal unsafe delegate*<uint, uint, bool*, void> glGetBooleani_v;
internal unsafe delegate*<uint, bool*, void> glGetBooleanv;
@@ -769,7 +764,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, int*, void> glGetFramebufferParameterivMESA;
internal unsafe delegate*<uint> glGetGraphicsResetStatus;
internal unsafe delegate*<uint> glGetGraphicsResetStatusARB;
internal unsafe delegate*<uint, GLhandleARB> glGetHandleARB;
internal unsafe delegate*<uint, glHandleARB> glGetHandleARB;
internal unsafe delegate*<uint, bool, uint, uint, void*, void> glGetHistogramEXT;
internal unsafe delegate*<uint, uint, float*, void> glGetHistogramParameterfvEXT;
internal unsafe delegate*<uint, uint, int*, void> glGetHistogramParameterivEXT;
@@ -778,7 +773,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, int, bool, int, uint, ulong> glGetImageHandleNV;
internal unsafe delegate*<uint, uint, float*, void> glGetImageTransformParameterfvHP;
internal unsafe delegate*<uint, uint, int*, void> glGetImageTransformParameterivHP;
internal unsafe delegate*<GLhandleARB, uint, uint*, byte*, void> glGetInfoLogARB;
internal unsafe delegate*<glHandleARB, uint, uint*, byte*, void> glGetInfoLogARB;
internal unsafe delegate*<int> glGetInstrumentsSGIX;
internal unsafe delegate*<uint, uint, long*, void> glGetInteger64i_v;
internal unsafe delegate*<uint, long*, void> glGetInteger64v;
@@ -853,9 +848,9 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, int*, void> glGetObjectBufferivATI;
internal unsafe delegate*<uint, uint, uint, uint*, byte*, void> glGetObjectLabel;
internal unsafe delegate*<uint, uint, uint, uint*, byte*, void> glGetObjectLabelEXT;
internal unsafe delegate*<GLhandleARB, uint, float*, void> glGetObjectParameterfvARB;
internal unsafe delegate*<glHandleARB, uint, float*, void> glGetObjectParameterfvARB;
internal unsafe delegate*<uint, uint, uint, int*, void> glGetObjectParameterivAPPLE;
internal unsafe delegate*<GLhandleARB, uint, int*, void> glGetObjectParameterivARB;
internal unsafe delegate*<glHandleARB, uint, int*, void> glGetObjectParameterivARB;
internal unsafe delegate*<void*, uint, uint*, byte*, void> glGetObjectPtrLabel;
internal unsafe delegate*<uint, uint, int*, void> glGetOcclusionQueryivNV;
internal unsafe delegate*<uint, uint, uint*, void> glGetOcclusionQueryuivNV;
@@ -944,7 +939,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, uint*, byte*, void> glGetShaderInfoLog;
internal unsafe delegate*<uint, uint, int*, int*, void> glGetShaderPrecisionFormat;
internal unsafe delegate*<uint, uint, uint*, byte*, void> glGetShaderSource;
internal unsafe delegate*<GLhandleARB, uint, uint*, byte*, void> glGetShaderSourceARB;
internal unsafe delegate*<glHandleARB, uint, uint*, byte*, void> glGetShaderSourceARB;
internal unsafe delegate*<uint, uint, int*, void> glGetShaderiv;
internal unsafe delegate*<uint, uint, uint*, void> glGetShadingRateImagePaletteNV;
internal unsafe delegate*<uint, uint, uint, int*, void> glGetShadingRateSampleLocationivNV;
@@ -1002,16 +997,16 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, int, int> glGetUniformBufferSizeEXT;
internal unsafe delegate*<uint, uint, byte*, char**, uint*, void> glGetUniformIndices;
internal unsafe delegate*<uint, byte*, int> glGetUniformLocation;
internal unsafe delegate*<GLhandleARB, byte*, int> glGetUniformLocationARB;
internal unsafe delegate*<glHandleARB, byte*, int> glGetUniformLocationARB;
internal unsafe delegate*<uint, int, IntPtr> glGetUniformOffsetEXT;
internal unsafe delegate*<uint, int, uint*, void> glGetUniformSubroutineuiv;
internal unsafe delegate*<uint, int, double*, void> glGetUniformdv;
internal unsafe delegate*<uint, int, float*, void> glGetUniformfv;
internal unsafe delegate*<GLhandleARB, int, float*, void> glGetUniformfvARB;
internal unsafe delegate*<glHandleARB, int, float*, void> glGetUniformfvARB;
internal unsafe delegate*<uint, int, long*, void> glGetUniformi64vARB;
internal unsafe delegate*<uint, int, long*, void> glGetUniformi64vNV;
internal unsafe delegate*<uint, int, int*, void> glGetUniformiv;
internal unsafe delegate*<GLhandleARB, int, int*, void> glGetUniformivARB;
internal unsafe delegate*<glHandleARB, int, int*, void> glGetUniformivARB;
internal unsafe delegate*<uint, int, ulong*, void> glGetUniformui64vARB;
internal unsafe delegate*<uint, int, ulong*, void> glGetUniformui64vNV;
internal unsafe delegate*<uint, int, uint*, void> glGetUniformuiv;
@@ -1178,7 +1173,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<float, void> glLineWidth;
internal unsafe delegate*<GLfixed, void> glLineWidthxOES;
internal unsafe delegate*<uint, void> glLinkProgram;
internal unsafe delegate*<GLhandleARB, void> glLinkProgramARB;
internal unsafe delegate*<glHandleARB, void> glLinkProgramARB;
internal unsafe delegate*<uint, uint, void**, uint*, uint*, uint*, uint, void> glListDrawCommandsStatesClientNV;
internal unsafe delegate*<uint, uint, float, void> glListParameterfSGIX;
internal unsafe delegate*<uint, uint, float*, void> glListParameterfvSGIX;
@@ -1844,7 +1839,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, uint, uint, void> glShaderOp2EXT;
internal unsafe delegate*<uint, uint, uint, uint, uint, void> glShaderOp3EXT;
internal unsafe delegate* unmanaged[Stdcall]<uint, uint, byte**, void*, void> glShaderSource;
internal unsafe delegate*<GLhandleARB, uint, byte**, int*, void> glShaderSourceARB;
internal unsafe delegate*<glHandleARB, uint, byte**, int*, void> glShaderSourceARB;
internal unsafe delegate*<uint, uint, uint, void> glShaderStorageBlockBinding;
internal unsafe delegate*<bool, void> glShadingRateImageBarrierNV;
internal unsafe delegate*<uint, uint, uint, uint*, void> glShadingRateImagePaletteNV;
@@ -2196,7 +2191,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint, uint, void*, uint, void> glUpdateObjectBufferATI;
internal unsafe delegate*<uint, void> glUploadGpuMaskNVX;
internal unsafe delegate*<uint, void> glUseProgram;
internal unsafe delegate*<GLhandleARB, void> glUseProgramObjectARB;
internal unsafe delegate*<glHandleARB, void> glUseProgramObjectARB;
internal unsafe delegate*<uint, uint, uint, void> glUseProgramStages;
internal unsafe delegate*<uint, uint, void> glUseShaderProgramEXT;
internal unsafe delegate*<void> glVDPAUFiniNV;
@@ -2211,7 +2206,7 @@ namespace StgSharp.Graphics.OpenGL
internal unsafe delegate*<uint, uint*, void> glVDPAUUnmapSurfacesNV;
internal unsafe delegate*<uint, void> glVDPAUUnregisterSurfaceNV;
internal unsafe delegate*<uint, void> glValidateProgram;
internal unsafe delegate*<GLhandleARB, void> glValidateProgramARB;
internal unsafe delegate*<glHandleARB, void> glValidateProgramARB;
internal unsafe delegate*<uint, void> glValidateProgramPipeline;
internal unsafe delegate*<uint, uint, uint, uint, uint, void> glVariantArrayObjectATI;
internal unsafe delegate*<uint, uint, uint, void*, void> glVariantPointerEXT;
+24 -8
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glEnum.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -28,13 +28,13 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System.Runtime.CompilerServices;
namespace StgSharp.Graphics.OpenGL
{
public enum PixelChannelLayout
{
UByte = glConst.UNSIGNED_BYTE,
Byte = glConst.BYTE,
UShort = glConst.UNSIGNED_SHORT,
@@ -54,6 +54,16 @@ namespace StgSharp.Graphics.OpenGL
UInt8888Rev = glConst.UNSIGNED_INT_8_8_8_8_REV,
UInt1010102 = glConst.UNSIGNED_INT_10_10_10_2,
UInt2101010Rev = glConst.UNSIGNED_INT_2_10_10_10_REV
}
public enum FaceMode
{
Point = glConst.POINT,
Line = glConst.LINE,
Fill = glConst.FILL
}
public enum FrameBufferStatus
@@ -125,12 +135,18 @@ namespace StgSharp.Graphics.OpenGL
public enum glOperation : uint
{
StencilTest = glConst.STENCIL_TEST,
DepthTest = glConst.DEPTH_TEST,
PolygonOffsetFill = glConst.POLYGON_OFFSET_FILL,
PolygonOffsetLine = glConst.POLYGON_OFFSET_LINE,
PolygonOffsetPoint = glConst.POLYGON_OFFSET_POINT,
}
#pragma warning disable CA1008
#pragma warning disable CA1008
public enum ShaderType : int
#pragma warning restore CA1008
#pragma warning restore CA1008
{
Fragment = glConst.FRAGMENT_SHADER,
@@ -140,9 +156,9 @@ namespace StgSharp.Graphics.OpenGL
}
#pragma warning disable CA1008
#pragma warning disable CA1008
public enum BufferType : int
#pragma warning restore CA1008
#pragma warning restore CA1008
{
ArrayBuffer = glConst.ARRAY_BUFFER,
@@ -162,9 +178,9 @@ namespace StgSharp.Graphics.OpenGL
}
#pragma warning disable CA1008
#pragma warning disable CA1008
public enum BufferUsage : int
#pragma warning restore CA1008
#pragma warning restore CA1008
{
StreamDraw = 0x88E0,
+6 -13
View File
@@ -60,19 +60,13 @@ namespace StgSharp.Graphics.OpenGL
internal GlArrayFormatException( string message ) : base( message ) { }
internal GlArrayFormatException(
SerializationInfo info,
StreamingContext context )
internal GlArrayFormatException( SerializationInfo info, StreamingContext context )
: base( info, context ) { }
internal GlArrayFormatException(
string message,
Exception innerException )
internal GlArrayFormatException( string message, Exception innerException )
: base( message, innerException ) { }
public GlArrayFormatException(
PixelChannelLayout layout,
string arrayname )
public GlArrayFormatException( PixelChannelLayout layout, string arrayname )
: base( $"{arrayname} cannot be used as layout of {layout}" ) { }
}
@@ -80,13 +74,12 @@ namespace StgSharp.Graphics.OpenGL
public static partial class GlHelper
{
public static bool CheckArrayFormat(
this Array array,
PixelChannelLayout layout )
public static bool CheckArrayFormat( this Array array, PixelChannelLayout layout )
{
return layout switch
{
PixelChannelLayout.Byte or PixelChannelLayout.UByte332 or PixelChannelLayout.UByte233Rev => ( array is byte[] ) || ( array is sbyte[] ),
PixelChannelLayout.Byte or PixelChannelLayout.UByte332 or PixelChannelLayout.UByte233Rev => ( array is byte[] ) ||
( array is sbyte[] ),
PixelChannelLayout.Short => array is short[],
PixelChannelLayout.UShort => array is ushort[],
PixelChannelLayout.Int => array is int[],
@@ -55,7 +55,8 @@ namespace StgSharp.Graphics.OpenGL
internal void ReturnAvailableUnit( IEnumerable<TextureUnit> source )
{
int v = glConst.TEXTURE0 + TextureUnitCount;
foreach( TextureUnit unit in source ) {
foreach( TextureUnit unit in source )
{
if( ( int )unit > v ) {
throw new InvalidOperationException(
"Source contains texture unit beyond context support." );
@@ -63,15 +64,16 @@ namespace StgSharp.Graphics.OpenGL
}
}
internal int TryGetAvailableTextureUnit(
int count,
out IEnumerable<TextureUnit> result )
internal int TryGetAvailableTextureUnit( int count, out IEnumerable<TextureUnit> result )
{
result = new Queue<TextureUnit>();
for( int i = 0; i < count; i++ ) {
if( UnusedTextureImageUint.TryDequeue( out TextureUnit unit ) ) {
for( int i = 0; i < count; i++ )
{
if( UnusedTextureImageUint.TryDequeue( out TextureUnit unit ) )
{
( result as Queue<TextureUnit> )!.Enqueue( unit );
} else {
} else
{
return i;
}
}
@@ -80,8 +82,7 @@ namespace StgSharp.Graphics.OpenGL
private ConcurrentQueue<TextureUnit> InitializeUnusedTextureImageUint()
{
ConcurrentQueue<TextureUnit> result = new ConcurrentQueue<TextureUnit>(
);
ConcurrentQueue<TextureUnit> result = new ConcurrentQueue<TextureUnit>();
for( int index = 0; index < TextureUnitCount; index++ ) {
result.Enqueue( ( TextureUnit )( glConst.TEXTURE0 + index ) );
}
+42 -16
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glFunction.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -128,10 +128,10 @@ namespace StgSharp.Graphics.OpenGL
/// Bind a frame Buffer to a frame Buffer target Same function as <see
/// href="https://docs._gl/gl3/glBindFramebuffer"> glBindFramebuffer </see>.
/// </summary>
/// <param _name="target">
/// <param _label="target">
/// The frame Buffer target of the binding operation.
/// </param>
/// <param _name="handle">
/// <param _label="handle">
/// The handle of the frame Buffer object to bind.
/// </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
@@ -283,7 +283,7 @@ namespace StgSharp.Graphics.OpenGL
/// only deifference is that this mehtod can only delete one renderbuffer at the same
/// time.
/// </summary>
/// <param _name="bufferHandle">
/// <param _label="bufferHandle">
/// Handle to Buffer to delete.
/// </param>
public unsafe void DeleteRenderBuffer( GlHandle bufferHandle )
@@ -303,6 +303,23 @@ namespace StgSharp.Graphics.OpenGL
}
}
public void DepthMaskAccess( bool isWrite )
{
Context.glDepthMask( isWrite );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Disable( glOperation operation )
{
Context.glDisable( ( uint )operation );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void DrawArrays( GeometryType mode, int first, uint count )
{
Context.glDrawArrays( ( uint )mode, first, count );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void DrawElements( GeometryType mode, uint count, TypeCode type, IntPtr ptr )
{
@@ -340,7 +357,6 @@ namespace StgSharp.Graphics.OpenGL
case TypeCode.Byte:
a = glConst.UNSIGNED_BYTE;
break;
default:
InternalIO.InternalWriteLog(
$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}",
@@ -525,6 +541,18 @@ namespace StgSharp.Graphics.OpenGL
}
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void PolygonMode( FaceMode mode )
{
Context.glPolygonMode( glConst.FRONT_AND_BACK, ( uint )mode );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void PolygonOffset( float factor, float unit )
{
Context.glPolygonOffset( factor, unit );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void ReadPixels(
(int X, int Y) beginPosition,
@@ -595,16 +623,16 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void SetBufferData<T>(
BufferType bufferType,
ReadOnlySpan<T> bufferArray,
ReadOnlySpan<T> bufferSpan,
BufferUsage usage )
where T: struct,INumber<T>
{
int size = bufferArray.Length * Marshal.SizeOf( typeof( T ) );
if( bufferArray == null ) {
int size = bufferSpan.Length * Marshal.SizeOf( typeof( T ) );
if( bufferSpan == null ) {
return;
}
#pragma warning disable CS8500
fixed( void* bufferPtr = bufferArray )
fixed( void* bufferPtr = bufferSpan )
#pragma warning restore CS8500
{
Context.glBufferData(
@@ -625,7 +653,7 @@ namespace StgSharp.Graphics.OpenGL
}
#pragma warning disable CS8500
fixed( void* bufferPtr = &bufferArray.GetPinnableReference() )
fixed( void* bufferPtr = bufferArray )
#pragma warning restore CS8500
{
Context.glBufferData(
@@ -636,16 +664,13 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void SetBufferVectorData<T>(
BufferType bufferType,
ReadOnlySpan<T> bufferArray,
ReadOnlySpan<T> bufferSpan,
BufferUsage usage )
where T: struct, IVector<T>
{
int size = bufferArray.Length * Marshal.SizeOf( typeof( T ) );
if( bufferArray == null ) {
return;
}
int size = bufferSpan.Length * Marshal.SizeOf( typeof( T ) );
#pragma warning disable CS8500
fixed( void* bufferPtr = &bufferArray.GetPinnableReference() )
fixed( void* bufferPtr = bufferSpan )
#pragma warning restore CS8500
{
Context.glBufferData(
@@ -783,6 +808,7 @@ namespace StgSharp.Graphics.OpenGL
Context.glViewport( x, y, width, height );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void WaitAccomplishment()
{
Context.glFinish();
+9 -9
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glHalfNV.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -35,7 +35,7 @@ using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Internal.OpenGL
namespace StgSharp.Graphics.OpenGL
{
[StructLayout( LayoutKind.Explicit, Size = 16 )]
public struct glHalfNV
@@ -48,9 +48,14 @@ namespace StgSharp.Internal.OpenGL
binary = bin;
}
public static glHalfNV FromInt16(short x)
public static glHalfNV FromInt16( short x )
{
return new glHalfNV(x);
return new glHalfNV( x );
}
public static short ToInt16( glHalfNV half )
{
return half.binary;
}
public static explicit operator glHalfNV( short x )
@@ -58,11 +63,6 @@ namespace StgSharp.Internal.OpenGL
return new glHalfNV( x );
}
public static short ToInt16(glHalfNV half)
{
return half.binary;
}
public static explicit operator short( glHalfNV x )
{
return x.binary;
+15 -6
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glHandle.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -46,24 +46,33 @@ namespace StgSharp.Graphics.OpenGL
public struct GlHandle
{
[FieldOffset( 0 )] public int SignedValue;
[FieldOffset( 0 )] public uint Value;
[FieldOffset( 0 )] internal int SignedValue;
[FieldOffset( 0 )] internal uint Value;
public static GlHandle Zero
{
get => new GlHandle { Value = 0 };
get => new GlHandle
{
Value = 0
};
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static GlHandle Alloc( uint value )
{
return new GlHandle { Value = value };
return new GlHandle
{
Value = value
};
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static GlHandle SignedAlloc( int value )
{
return new GlHandle { SignedValue = value };
return new GlHandle
{
SignedValue = value
};
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderSourceGenrator.cs"
// file="glRenderObjectGenrator.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -48,10 +48,14 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Create a set of <see cref="ElementBuffer" />.
/// Create a set of <see cref="ElementBuffer" />.
/// </summary>
/// <param _name="count"> Amount of EBO to be created. </param>
/// <returns></returns>
/// <param _label="count">
/// Amount of EBO to be created.
/// </param>
/// <returns>
///
/// </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected ElementBuffer CreateElementBuffer( int count )
{
@@ -71,10 +75,14 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Create a sets of <see cref="TextureGL" />
/// Create a sets of <see cref="TextureGL" />
/// </summary>
/// <param _name="count"> Amount of textures to be created. </param>
/// <returns></returns>
/// <param _label="count">
/// Amount of textures to be created.
/// </param>
/// <returns>
///
/// </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected TextureGL CreateTexture( int count )
{
@@ -82,10 +90,14 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Create a set of <see cref="VertexArray" />.
/// Create a set of <see cref="VertexArray" />.
/// </summary>
/// <param _name="count"> Amount of VAO to be created. </param>
/// <returns></returns>
/// <param _label="count">
/// Amount of VAO to be created.
/// </param>
/// <returns>
///
/// </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected VertexArray CreateVertexArray( int count )
{
@@ -93,10 +105,14 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Create a set of <see cref="VertexBuffer" />.
/// Create a set of <see cref="VertexBuffer" />.
/// </summary>
/// <param _name="count"> Amount of Object to be created. </param>
/// <returns></returns>
/// <param _label="count">
/// Amount of Object to be created.
/// </param>
/// <returns>
///
/// </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected VertexBuffer CreateVertexBuffer( int count )
{
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderStream.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -58,29 +58,28 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Initialize an opengl context and load all opengl functions.
/// Initialize an opengl context and load all opengl functions.
/// </summary>
public unsafe void InitializeContext()
{
if( ContextHandle == default ) {
ContextHandle = Marshal.AllocHGlobal(
Marshal.SizeOf( typeof( OpenglContext ) ) );
if( ContextHandle == default )
{
ContextHandle = Marshal.AllocHGlobal( Marshal.SizeOf( typeof( OpenglContext ) ) );
OpenglContext* contextID = ( OpenglContext* )ContextHandle;
contextID->glGetString = ( delegate*<uint, IntPtr> )IntPtr.Zero;
}
if( GL == null ) {
_context = OpenGLFunction.BuildGlFunctionPackage(
ContextHandle );
_context = OpenGLFunction.BuildGlFunctionPackage( ContextHandle );
}
}
/// <summary>
/// Initialize an OpenGl viewPortDisplay if current form has not been binded to any
/// viewPortDisplay. and set the viewPortDisplay binded to current form as current OpenGL
/// viewPortDisplay.
/// Initialize an OpenGl viewPortDisplay if current form has not been binded to any
/// viewPortDisplay. and set the viewPortDisplay binded to current form as current OpenGL
/// viewPortDisplay.
/// </summary>
/// <exception cref="Exception">
/// Something goes wrong and StgSharp fails in creating a new OpenGL viewPortDisplay.
/// Something goes wrong and World fails in creating a new OpenGL viewPortDisplay.
/// </exception>
public unsafe void MakeAsCurrentContext()
{
@@ -91,8 +90,7 @@ namespace StgSharp.Graphics.OpenGL
/// <inheritdoc />
public override void RenderEnd()
{
if( !renderToThread.TryGetValue( this,
out Thread t ) || t != Thread.CurrentThread ) {
if( !renderToThread.TryGetValue( this, out Thread t ) || t != Thread.CurrentThread ) {
throw new InvalidOperationException(
$"Current render has had been binded to thread {t!.ManagedThreadId}" );
}
@@ -106,8 +104,8 @@ namespace StgSharp.Graphics.OpenGL
public override void RenderStart()
{
Thread current = Thread.CurrentThread;
if( !renderToThread.TryGetValue( this,
out Thread t ) || t == ThreadHelper.EmptyThread ) {
if( !renderToThread.TryGetValue( this, out Thread t ) || t == ThreadHelper.EmptyThread )
{
renderToThread[ this ] = current;
MakeAsCurrentContext();
return;
@@ -120,10 +118,10 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override void SetSizeLimit(
int minWidth,
int minHeight,
int maxWidth,
int maxHeight )
int minWidth,
int minHeight,
int maxWidth,
int maxHeight )
{
InternalIO.glfwSetWindowSizeLimits(
this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight );
@@ -144,8 +142,8 @@ namespace StgSharp.Graphics.OpenGL
}
protected override sealed Uniform<Matrix44> NativeCameraUniform(
ShaderProgram source,
string name )
ShaderProgram source,
string name )
{
NativeCamera.GainAllUniforms( source, name );
return NativeCamera.convertedUniform;
@@ -153,18 +151,18 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed void NativeCameraViewRange(
Radius fieldOfRange,
Vec2 offset,
(float frontDepth, float backDepth) viewDepth )
Radius fieldOfRange,
Vec2 offset,
(float frontDepth, float backDepth) viewDepth )
{
NativeCamera.SetViewRange(
fieldOfRange, this.Size, offset, viewDepth );
NativeCamera.SetViewRange( fieldOfRange, this.Size, offset, viewDepth );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed void NativeCameraViewTarget(
Vec3 position,
Vec3 direction,
Vec3 up )
Vec3 position,
Vec3 direction,
Vec3 up )
{
NativeCamera.SetViewDirection( position, direction, up );
}
+12 -82
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glType.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -37,24 +36,26 @@ using System.Text;
namespace StgSharp.Internal.OpenGL
{
public delegate IntPtr GLfuncLoader( string name );
internal delegate void GLVULKANPROCNV();
public unsafe struct GLhandleARB
public unsafe struct glHandleARB
{
private dynamic value;
public unsafe GLhandleARB( dynamic value )
public unsafe glHandleARB( dynamic value )
{
if( !RuntimeInformation.IsOSPlatform( OSPlatform.OSX ) ) {
if( value.GetType().Name != "Uint32" ) {
if( !RuntimeInformation.IsOSPlatform( OSPlatform.OSX ) )
{
if( value.GetType().Name != "Uint32" )
{
goto errorlog;
}
this.value = value;
} else {
if( value.GetType().Name != "IntPtr" ) {
} else
{
if( value.GetType().Name != "IntPtr" )
{
goto errorlog;
}
this.value = value;
@@ -68,81 +69,10 @@ namespace StgSharp.Internal.OpenGL
}
}
public static implicit operator uint( GLhandleARB value )
public static implicit operator uint( glHandleARB value )
{
return ( uint )value;
}
}
#region GLFW_dele
internal unsafe delegate void GLFWwindowsizefun(
glfwWindow* window,
int width,
int height );
internal unsafe delegate void GLFWwindowrefreshfun( glfwWindow* window );
internal unsafe delegate void GLFWwindowposfun(
glfwWindow* window,
int xpos,
int ypos );
internal unsafe delegate void GLFWwindowmaximizefun(
glfwWindow* window,
int maximized );
internal unsafe delegate void GLFWwindowiconifyfun(
glfwWindow* window,
int iconified );
internal unsafe delegate void GLFWwindowfocusfun(
glfwWindow* window,
int focused );
internal unsafe delegate void GLFWwindowcontentscalefun(
glfwWindow* window,
float xscale,
float yscale );
internal unsafe delegate void GLFWwindowclosefun( glfwWindow* window );
internal unsafe delegate void GLFWvkproc();
internal unsafe delegate void GLFWscrollfun(
glfwWindow* window,
double xoffset,
double yoffset );
internal unsafe delegate void GLFWmousebuttonfun(
glfwWindow* window,
int button,
int action,
int mods );
internal unsafe delegate void GLFWmonitorfun(
glfwMonitor* monitor,
int monitorevent );
internal unsafe delegate void GLFWkeyfun(
glfwWindow* window,
int key,
int scancode,
int action,
int mods );
internal unsafe delegate void GLFWjoystickfun( int jid, int keyevent );
public unsafe delegate void GLFWglproc();
internal unsafe delegate void GLFWerrorfun(
int error_code,
sbyte* description );
internal unsafe delegate void GLFWdropfun(
glfwWindow* window,
int path_count,
sbyte*[] paths );
internal unsafe delegate void GLFWcursorposfun(
glfwWindow* window,
double xpos,
double ypos );
internal unsafe delegate void GLFWcursorenterfun(
glfwWindow* window,
int entered );
internal unsafe delegate void GLFWcharmodsfun(
glfwWindow* window,
uint codepoint,
int mods );
internal unsafe delegate void GLFWcharfun(
glfwWindow* window,
uint codepoint );
#endregion
}
+5 -24
View File
@@ -38,34 +38,15 @@ namespace StgSharp.Graphics
public interface IPixel
{
public float Red
{
get;
set;
}
public float Red { get; set; }
public float Green
{
get;
set;
}
public float Green { get; set; }
public float Blue
{
get;
set;
}
public float Blue { get; set; }
public float Alpha
{
get;
set;
}
public float Alpha { get; set; }
internal int Size
{
get;
}
internal int Size { get; }
}
@@ -46,9 +46,7 @@ namespace StgSharp.Graphics
private PlainGeometry _shape;
private TextureProvider _texture;
public PlainGeometryMesh(
[NotNull] PlainGeometry shape,
[NotNull] TextureProvider texture )
public PlainGeometryMesh( [NotNull] PlainGeometry shape, [NotNull] TextureProvider texture )
{
if( shape.VertexCount > texture.TextureCoordinate.Length ) {
throw new ArgumentException(
@@ -61,10 +59,7 @@ namespace StgSharp.Graphics
//private Image _texture;
public PlainGeometryMesh(
PlainGeometry shape,
Image texture,
Vec2[] texCoord )
public PlainGeometryMesh( PlainGeometry shape, Image texture, Vec2[] texCoord )
{
ArgumentNullException.ThrowIfNull( shape );
ArgumentNullException.ThrowIfNull( texCoord );
+48 -48
View File
@@ -1,7 +1,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RenderStream.cs"
// Project: StgSharp
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
@@ -32,7 +32,6 @@ using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using StgSharp.MVVM;
using StgSharp.MVVM.View;
using StgSharp.Timing;
using System;
@@ -50,8 +49,9 @@ namespace StgSharp.Graphics
public abstract class RenderStream
{
private protected ViewPort primeArgs;
private Camera nativeCamera;
private protected ViewPort primeArgs;
internal TimeSpanProvider _timeProvider;
public (int width, int height) Size
@@ -59,10 +59,7 @@ namespace StgSharp.Graphics
get => (Width, Height);
}
public abstract bool IsContextSharable
{
get;
}
public abstract bool IsContextSharable { get; }
public int Height
{
@@ -93,7 +90,7 @@ namespace StgSharp.Graphics
internal IntPtr CanvasHandle
{
get => primeArgs.ViewPortID;
get => primeArgs.ViewPortHandle;
}
internal IntPtr ContextHandle
@@ -129,28 +126,33 @@ namespace StgSharp.Graphics
}
/// <summary>
/// Set the size limit of current form
/// Set the size limit of current form
/// </summary>
/// <param _name="minWidth"> Minimum width of current form </param>
/// <param _name="minHeight"> Minimum height of current form </param>
/// <param _name="maxWidth"> Maximum width of current form </param>
/// <param _name="maxHeight"> Maximum height of current form </param>
/// <param _label="minWidth">
/// Minimum width of current form
/// </param>
/// <param _label="minHeight">
/// Minimum height of current form
/// </param>
/// <param _label="maxWidth">
/// Maximum width of current form
/// </param>
/// <param _label="maxHeight">
/// Maximum height of current form
/// </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public abstract void SetSizeLimit(
int minWidth,
int minHeight,
int maxWidth,
int maxHeight );
int minWidth,
int minHeight,
int maxWidth,
int maxHeight );
public static TTarget ShareContextFrom<TSource, TTarget>(
[NotNull]TSource source )
public static TTarget ShareContextFrom<TSource, TTarget>( [NotNull]TSource source )
where TSource: RenderStream
where TTarget: RenderStream, new()
{
TTarget target = new TTarget();
target.Initialize(
source.BindedViewPortContext,
source._timeProvider );
target.Initialize( source.BindedViewPortContext, source._timeProvider );
return target;
}
@@ -170,38 +172,37 @@ namespace StgSharp.Graphics
#region native camera operation
protected abstract void NativeCameraViewRange(
Radius fieldOfRange,
Vec2 offset,
(float frontDepth, float backDepth) viewDepth );
Radius fieldOfRange,
Vec2 offset,
(float frontDepth, float backDepth) viewDepth );
protected abstract void NativeCameraViewTarget(
Vec3 position,
Vec3 direction,
Vec3 up );
protected abstract void NativeCameraViewTarget( Vec3 position, Vec3 direction, Vec3 up );
/// <summary>
/// Get <see cref="Uniform{T}" />(TView is <see cref="Matrix44" />) uniform from a shader.
/// This uniform will be used as projection matrix of this camera. Additionally, for multi-
/// shader rendering, each shader requires a uniform, so do not ignore return value of this
/// method.
/// Get <see cref="Uniform{T}" />(TView is <see cref="Matrix44" />) uniform from a shader.
/// This uniform will be used as projection matrix of this camera. Additionally, for
/// multi- shader rendering, each shader requires a uniform, so do not ignore return
/// value of this method.
/// </summary>
/// <param _name="source"> Shader using this camera </param>
/// <param _name="name"> ContextName of projection camera named in shader </param>
/// <param _label="source">
/// Shader using this camera
/// </param>
/// <param _label="name">
/// ContextName of projection camera named in shader
/// </param>
/// <returns>
/// <see cref="Uniform{T}" />(TView is <see cref="Matrix44" />) representing projection
/// matrix in shader program.
/// <see cref="Uniform{T}" />(TView is <see cref="Matrix44" />) representing projection
/// matrix in shader program.
/// </returns>
protected abstract Uniform<Matrix44> NativeCameraUniform(
ShaderProgram source,
string name );
ShaderProgram source,
string name );
#endregion
#region internal operation
public void Initialize(
ViewPort v,
TimeSpanProvider timeProvider )
public void Initialize( ViewPort v, TimeSpanProvider timeProvider )
{
if( v == null ) {
throw new ArgumentNullException( nameof( v ) );
@@ -227,13 +228,14 @@ namespace StgSharp.Graphics
protected abstract void CustomizeInit();
/// <summary>
/// Marking the start of current render operations, and set this renser context as current.
/// Marking the start of current render operations, and set this renser context as
/// current.
/// </summary>
public abstract void RenderStart();
/// <summary>
/// Marking the end of current render operations, and release the binding of this renser
/// context to current, making it available for another thread as current.
/// Marking the end of current render operations, and release the binding of this renser
/// context to current, making it available for another thread as current.
/// </summary>
public abstract void RenderEnd();
@@ -241,9 +243,7 @@ namespace StgSharp.Graphics
#region public resource generator
protected abstract Shader CreateShaderSegment(
ShaderType type,
int count );
protected abstract Shader CreateShaderSegment( ShaderType type, int count );
protected abstract ShaderProgram CreateShaderProgram();
@@ -48,11 +48,9 @@ namespace StgSharp.Graphics.ShaderEdit
private List<string> codeList;
private List<ShaderFunction> usedShaderFunctions;
public Uniform<T> DefineUniform<T>( string name, int index )
where T: struct
public Uniform<T> DefineUniform<T>( string name, int index ) where T: struct
{
ShaderParameter p = new ShaderParameter(
name, ShaderParameter.TypeMarshal<T>() );
ShaderParameter p = new ShaderParameter( name, ShaderParameter.TypeMarshal<T>() );
uniformDefine.Add( index, p );
//return new Uniform<TView>();
@@ -72,23 +70,26 @@ namespace StgSharp.Graphics.ShaderEdit
public int ParameterCount => inputList.Count;
public void EmitCall(
ShaderFunction function,
ShaderParameter outPut,
params ShaderParameter[] inputParams )
ShaderFunction function,
ShaderParameter outPut,
params ShaderParameter[] inputParams )
{
if( inputParams.Length != function.ParameterCount ) {
if( inputParams.Length != function.ParameterCount )
{
// Param list length not equal
throw new ArgumentException(
"Provided parameters does not match function's parameter list." );
}
if( !ShaderParameter.IsSameType( outPut, function.outPut ) ) {
if( !ShaderParameter.IsSameType( outPut, function.outPut ) )
{
// Type of returning value not equal
throw new ArgumentException(
"Provided parameters does not match function's parameter list." );
}
for( int i = 0; i < inputParams.Length; i++ ) {
if( !ShaderParameter.IsSameType(
function.inputList[ i ], inputParams[ i ] ) ) {
for( int i = 0; i < inputParams.Length; i++ )
{
if( !ShaderParameter.IsSameType( function.inputList[ i ], inputParams[ i ] ) )
{
// Input type not match
throw new InvalidCastException(
"Provided parameters does not match function's parameter list." );
@@ -124,20 +125,21 @@ namespace StgSharp.Graphics.ShaderEdit
isReadOnly = false;
}
public static bool IsSameType(
ShaderParameter param1,
ShaderParameter param2 )
public static bool IsSameType( ShaderParameter param1, ShaderParameter param2 )
{
if( param1.type != InternalShaderType.Struct ) {
if( param1.type != InternalShaderType.Struct )
{
return param1.type == param2.type;
} else {
} else
{
throw new Exception( "Struct is currently not supported." );
}
}
public static InternalShaderType TypeMarshal<T>() where T: struct
{
switch( Type.GetTypeCode( typeof( T ) ) ) {
switch( Type.GetTypeCode( typeof( T ) ) )
{
case TypeCode.Single:
return InternalShaderType.Float;
case TypeCode.Double:
@@ -149,7 +151,8 @@ namespace StgSharp.Graphics.ShaderEdit
default:
break;
}
switch( typeof( T ).Name ) {
switch( typeof( T ).Name )
{
case "vec4d":
return InternalShaderType.Vector4;
case "Matrix2x2":
@@ -171,8 +174,7 @@ namespace StgSharp.Graphics.ShaderEdit
case "Matrix4x4":
return InternalShaderType.Matrix4x4;
default:
throw new ArgumentException(
"Not supported shader data type." );
throw new ArgumentException( "Not supported shader data type." );
}
}
@@ -53,8 +53,7 @@ namespace StgSharp.Graphics.ShaderEdit
internal ShaderStruct() { }
public ShaderStruct(
params (GlHandle, ShaderStructMember)[] uniformPairs )
public ShaderStruct( params (GlHandle, ShaderStructMember)[] uniformPairs )
{
uniformPair = new Dictionary<GlHandle, ShaderStructMember>();
if( uniformPairs.Length == 0 ) {
@@ -69,10 +68,12 @@ namespace StgSharp.Graphics.ShaderEdit
public unsafe void SetAllUniforms()
{
OpenglContext* gl = ( OpenglContext* )OpenGL.OpenGLFunction.CurrentGL.ContextHandle;
foreach( KeyValuePair<GlHandle, ShaderStructMember> uniform in uniformPair ) {
foreach( KeyValuePair<GlHandle, ShaderStructMember> uniform in uniformPair )
{
int id = uniform.Key.SignedValue;
ShaderStructMember s = uniform.Value;
switch( s.type ) {
switch( s.type )
{
case InternalShaderType.Struct:
throw new ArgumentException(
"Incorrect type \"Struct\" defined in this self define type" );
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.PipeLine;
using System;
+4 -2
View File
@@ -75,9 +75,11 @@ namespace StgSharp.Graphics
if( i == _tex ) {
return;
}
if( i.Size == _tex.Size ) {
if( i.Size == _tex.Size )
{
_tex = i;
} else {
} else
{
throw new ArgumentException(
$"Size of {nameof(i)} does not equals to current image." );
}
+40 -43
View File
@@ -42,65 +42,62 @@ using System.Text;
// using Windows.Win32;
#endif
namespace StgSharp.Graphics
{
/// <summary>
/// Function handler to load an opengl function by searching its _label.
/// </summary>
/// <param _label="name">
/// the _label of the Opengl function
/// </param>
/// <returns>
/// An Intptr value representing the pointer to the function
/// </returns>
public delegate IntPtr glLoader( string name );
#region StgSharpDele
public unsafe delegate void FrameBufferSizeHandler(
IntPtr window,
int width,
int height);
public unsafe delegate void FrameBufferSizeHandler( IntPtr window, int width, int height );
public unsafe delegate void FramePositionHandler(
IntPtr window,
float width,
float height);
public unsafe delegate void FramePositionHandler( IntPtr window, float width, float height );
#endregion
/// <summary>
/// Function handler to load an opengl function by searching its _name.
/// </summary>
/// <param _name="name"> the _name of the Opengl function </param>
/// <returns> An Intptr value representing the pointer to the function </returns>
public delegate IntPtr glLoader(string name);
#region glDEBUG
internal unsafe delegate void GLDEBUGPROC(
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam);
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam );
internal unsafe delegate void GLDEBUGPROCARB(
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam);
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam );
internal unsafe delegate void GLDEBUGPROCKHR(
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam);
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam );
internal unsafe delegate void GLDEBUGPROCAMD(
uint id,
int category,
int severity,
int length,
sbyte* message,
void* userParam);
uint id,
int category,
int severity,
int length,
sbyte* message,
void* userParam );
#endregion
#endregion
}
@@ -42,8 +42,7 @@ namespace StgSharp.Threading
public class FrameworkSyncContext : SynchronizationContext
{
private static readonly FrameworkSyncContext _mainThreadContext = new FrameworkSyncContext(
);
private static readonly FrameworkSyncContext _mainThreadContext = new FrameworkSyncContext();
private readonly BlockingCollection<SendOrPostCallback> _syncContexts = new BlockingCollection<SendOrPostCallback>(
);
@@ -67,9 +66,11 @@ namespace StgSharp.Threading
public override void Send( SendOrPostCallback d, object state )
{
if( Thread.CurrentThread == _mainThread ) {
if( Thread.CurrentThread == _mainThread )
{
d( state );
} else {
} else
{
Post( d, state );
}
}
+1 -2
View File
@@ -52,8 +52,7 @@ namespace StgSharp.HighPerformance
{
ReadOnlySpan<char> nameSpan = _name.AsSpan();
fixed( char* cptr = nameSpan ) {
return InternalIO.Intrinsic
.city_hash_simplify( cptr, _name.Length );
return InternalIO.Intrinsic.city_hash_simplify( cptr, _name.Length );
}
}
+4 -2
View File
@@ -81,7 +81,8 @@ namespace StgSharp.HighPerformance
public T Read<T>( int index ) where T: struct, INumber<T>
{
fixed( byte* p = Buffer ) {
fixed( byte* p = Buffer )
{
#pragma warning disable CS8500
return *( ( T* )p + index );
#pragma warning restore CS8500
@@ -105,7 +106,8 @@ namespace StgSharp.HighPerformance
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Write<T>( int index, T value ) where T: struct, INumber<T>
{
fixed( byte* p = Buffer ) {
fixed( byte* p = Buffer )
{
#pragma warning disable CS8500
*( ( T* )p + index ) = value;
#pragma warning restore CS8500
-1
View File
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -46,20 +46,13 @@ namespace StgSharp.HighPerformance
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static unsafe int CityHashSimplify(
char* span,
int begin,
int length )
public static unsafe int CityHashSimplify( char* span, int begin, int length )
{
return InternalIO.Intrinsic
.city_hash_simplify( span + begin, length );
return InternalIO.Intrinsic.city_hash_simplify( span + begin, length );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static unsafe int IndexOfCharPair(
char* source,
int pairValue,
int length )
public static unsafe int IndexOfCharPair( char* source, int pairValue, int length )
{
return InternalIO.Intrinsic.index_pair( source, pairValue, length );
}
+11 -14
View File
@@ -46,10 +46,10 @@ namespace StgSharp.Internal
[UnmanagedCallConv( CallConvs = [typeof( CallConvCdecl )] )]
#pragma warning disable CA5392
internal static partial int glCheckShaderStatus(
ref OpenglContext context,
uint shaderHandle,
int key,
ref IntPtr logPtr );
ref OpenglContext context,
uint shaderHandle,
int key,
ref IntPtr logPtr );
#pragma warning restore CA5392
@@ -57,9 +57,7 @@ namespace StgSharp.Internal
[LibraryImport( SSC_libName, EntryPoint = "initGL" )]
[UnmanagedCallConv( CallConvs = [typeof( CallConvCdecl )] )]
internal static partial void InternalInitGL(
int majorVersion,
int minorVersion );
internal static partial void InternalInitGL( int majorVersion, int minorVersion );
[LibraryImport(
SSC_libName,
@@ -71,8 +69,8 @@ namespace StgSharp.Internal
[LibraryImport( SSC_libName, EntryPoint = "linkShaderProgram" )]
[UnmanagedCallConv( CallConvs = [typeof( CallConvCdecl )] )]
internal static unsafe partial uint InternalLinkShaderProgram(
OpenglContext* context,
uint shaderProgram );
OpenglContext* context,
uint shaderProgram );
[LibraryImport( SSC_libName, EntryPoint = "readLog" )]
[UnmanagedCallConv( CallConvs = [typeof( CallConvCdecl )] )]
@@ -84,14 +82,13 @@ namespace StgSharp.Internal
StringMarshalling = StringMarshalling.Utf8 )]
[UnmanagedCallConv( CallConvs = [typeof( CallConvCdecl )] )]
internal static unsafe partial void InternalLoadImage(
string fileName,
ImageInfo* output,
ImageLoader loader );
string fileName,
ImageInfo* output,
ImageLoader loader );
[LibraryImport( SSC_libName, EntryPoint = "unloadImageData" )]
[UnmanagedCallConv( CallConvs = [typeof( CallConvCdecl )] )]
internal static unsafe partial void InternalUnloadImage(
ImageInfo* output );
internal static unsafe partial void InternalUnloadImage( ImageInfo* output );
#endregion ssgc api define
}
+19 -20
View File
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
@@ -60,8 +59,7 @@ namespace StgSharp.Internal
internal static IntPtr SSClibPtr = IntPtr.Zero;
internal static SemaphoreSlim logSyncSemaphore = new SemaphoreSlim(
1, 1 );
internal static SemaphoreSlim logSyncSemaphore = new SemaphoreSlim( 1, 1 );
static InternalIO()
{
@@ -76,7 +74,8 @@ namespace StgSharp.Internal
internal static void InternalAppendLog( string log )
{
if( !File.Exists( SS_errorLog ) ) {
if( !File.Exists( SS_errorLog ) )
{
FileStream stream = File.Create( SS_errorLog );
stream.Close();
}
@@ -87,10 +86,10 @@ namespace StgSharp.Internal
}
[Obsolete( "Not completed", true )]
internal static IntPtr InternalLoadProc<T>( IntPtr lib, string name )
where T: Delegate
internal static IntPtr InternalLoadProc<T>( IntPtr lib, string name ) where T: Delegate
{
try {
try
{
IntPtr procPtr =
#if WINDOWS
IntPtr.Zero;
@@ -102,7 +101,8 @@ namespace StgSharp.Internal
#endif
return procPtr;
}
catch( Exception ) {
catch( Exception )
{
throw;
}
}
@@ -110,34 +110,33 @@ namespace StgSharp.Internal
internal static void InternalWriteLog( string logLine, LogType logType )
{
logSyncSemaphore.Wait();
if( !File.Exists( SS_errorLog ) ) {
if( !File.Exists( SS_errorLog ) )
{
FileStream stream = File.Create( SS_errorLog );
stream.Close();
}
using( StreamWriter logStream = File.AppendText( SS_errorLog ) ) {
logStream.WriteLine(
$"{logType}\t{DateTime.Now.ToString("o")}" );
using( StreamWriter logStream = File.AppendText( SS_errorLog ) )
{
logStream.WriteLine( $"{logType}\t{DateTime.Now.ToString("o")}" );
logStream.WriteLine( logLine );
}
logSyncSemaphore.Release();
}
internal static void InternalWriteLog(
string beforeTime,
string logLine,
LogType logType )
internal static void InternalWriteLog( string beforeTime, string logLine, LogType logType )
{
logSyncSemaphore.Wait();
if( !File.Exists( SS_errorLog ) ) {
if( !File.Exists( SS_errorLog ) )
{
FileStream stream = File.Create( SS_errorLog );
stream.Close();
}
using( StreamWriter logStream = File.AppendText( SS_errorLog ) ) {
using( StreamWriter logStream = File.AppendText( SS_errorLog ) )
{
logStream.WriteLine( beforeTime );
logStream.WriteLine(
$"{logType}\t@\t{DateTime.Now.ToString("o")}" );
logStream.WriteLine( $"{logType}\t@\t{DateTime.Now.ToString("o")}" );
logStream.WriteLine( logLine );
}
logSyncSemaphore.Release( 1 );

Some files were not shown because too many files have changed in this diff Show More